PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
more progress, roadmap, wip
Brandon Thomas108fdc108ca7
diff --git a/CLAUDE.md b/CLAUDE.mdindex e0fd683e8..59e773985 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3,7 +3,7 @@PrintCraft is a clean-room, open-source, Rust-native PDF application targeting Adobe Acrobat Pro parity. It runs natively on macOS, Windows and Linux, and on the web via WASM. It is the sibling of `../photocraft` (a Photoshop-class editor) and follows the same conventions.## Start every session here-1. Read `plan/STATUS.md`: the current milestone, the next unchecked task and any blockers.+1. Read `plan/STATUS.md`: the current milestone, the next unchecked task and any blockers. `ROADMAP.md` holds the milestone estimates and progress; update its table and log at the end of every session.2. Read that task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the README of the crate you're touching.3. Follow the **autonomous operation protocol** in `plan/execution-plan.md` §7 (orient → plan → implement + test → verify → record → commit). Don't stop to ask unless §7 lists the decision as the user's.diff --git a/Cargo.lock b/Cargo.lockindex 497421e43..be12b15bf 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8,6 +8,8 @@ version = "0.24.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320"dependencies = [+ "enumn",+ "serde","uuid",]@@ -141,6 +143,7 @@ dependencies = ["cfg-if","getrandom 0.3.4","once_cell",+ "serde","version_check","zerocopy",]@@ -439,15 +442,30 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec 0.8.0",+]+[[package]]name = "bit-set"version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"dependencies = [- "bit-vec",+ "bit-vec 0.9.1",]+[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"+[[package]]name = "bit-vec"version = "0.9.1"@@ -465,6 +483,9 @@ name = "bitflags"version = "2.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"+dependencies = [+ "serde_core",+][[package]]name = "block-buffer"@@ -675,7 +696,7 @@ checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"dependencies = ["cfg-if","cpufeatures",- "rand_core",+ "rand_core 0.10.1",][[package]]@@ -951,6 +972,7 @@ checksum = "0656a7530b9e2841ee7a5f983965bdd9840c32f4012f759cfd44b912cced6b34"dependencies = ["bytemuck","emath",+ "serde",][[package]]@@ -966,6 +988,7 @@ dependencies = ["egui-wgpu","egui-winit","egui_glow",+ "glow","glutin","glutin-winit","image",@@ -979,6 +1002,8 @@ dependencies = ["pollster 1.0.1","profiling","raw-window-handle",+ "ron",+ "serde","static_assertions","wasm-bindgen","web-sys",@@ -1003,6 +1028,8 @@ dependencies = ["log","nohash-hasher","profiling",+ "ron",+ "serde","smallvec","unicode-segmentation","web-sys",@@ -1044,6 +1071,7 @@ dependencies = ["objc2-ui-kit 0.3.2","profiling","raw-window-handle",+ "serde","smithay-clipboard","web-time","winit",@@ -1078,6 +1106,24 @@ dependencies = ["winit",]+[[package]]+name = "egui_kittest"+version = "0.36.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5eb3f3effb2726fee23449293e67acbf6cc6ce35525b1722bd5743bb348114d5"+dependencies = [+ "eframe",+ "egui",+ "egui-wgpu",+ "image",+ "kittest",+ "log",+ "pollster 1.0.1",+ "serde",+ "toml",+ "wgpu",+]+[[package]]name = "either"version = "1.18.0"@@ -1091,6 +1137,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "52c8d4141cf0f60fb2f7aefaf352d3ffa5171ef0ab09731c64391801e95e48f1"dependencies = ["bytemuck",+ "serde",][[package]]@@ -1154,6 +1201,17 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "enumn"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "epaint"version = "0.36.2"@@ -1172,6 +1230,7 @@ dependencies = ["parking_lot","profiling","self_cell",+ "serde","skrifa 0.44.0","smallvec","unicode-general-category",@@ -1286,6 +1345,12 @@ version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"+[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"+[[package]]name = "foldhash"version = "0.2.0"@@ -1308,6 +1373,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b8eb065f3251655b3c90e22e5e363f310fc5332fb3402e37bbc94752283248f6"dependencies = ["bytemuck",+ "serde",][[package]]@@ -1421,9 +1487,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"dependencies = ["cfg-if",+ "js-sys","libc","r-efi 6.0.0",- "rand_core",+ "rand_core 0.10.1",+ "wasm-bindgen",][[package]]@@ -1618,8 +1686,6 @@ dependencies = [[[package]]name = "hayro"version = "0.7.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c4caa128ab87fd48ffb7490617cf93f77f606820dffbc9fd9ef6ab0ed077f56d"dependencies = ["bytemuck","hayro-interpret",@@ -1648,8 +1714,6 @@ dependencies = [[[package]]name = "hayro-interpret"version = "0.7.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f2613d0406898995042d0794c4245b2f2fba1246490c8ac593769bba6551129d"dependencies = ["bitflags 2.13.2","hayro-cmap",@@ -1901,6 +1965,16 @@ version = "3.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"+[[package]]+name = "kittest"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90ceaa75eb0036a32b6b9833962eb18137449e9817e2e586006471925b727fd5"+dependencies = [+ "accesskit",+ "accesskit_consumer 0.35.0",+]+[[package]]name = "kurbo"version = "0.11.3"@@ -2017,7 +2091,7 @@ dependencies = ["log","md-5","nom",- "rand",+ "rand 0.10.3","rangemap","rayon","sha2",@@ -2103,7 +2177,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"dependencies = ["arrayvec",- "bit-set",+ "bit-set 0.10.0","bitflags 2.13.2","cfg-if","cfg_aliases",@@ -2789,6 +2863,15 @@ dependencies = ["portable-atomic",]+[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]+[[package]]name = "presser"version = "0.3.1"@@ -2804,23 +2887,66 @@ dependencies = ["printcraft-ui-egui",]+[[package]]+name = "printcraft-cli"+version = "0.1.0"+dependencies = [+ "printcraft-engine",+ "printcraft-render",+ "serde_json",+]++[[package]]+name = "printcraft-cos"+version = "0.1.0"+dependencies = [+ "hayro-syntax",+ "printcraft-filters",+ "proptest",+ "thiserror 2.0.21",+]+[[package]]name = "printcraft-engine"version = "0.1.0"dependencies = [+ "printcraft-cos",+ "printcraft-organize","printcraft-render",+ "thiserror 2.0.21",+]++[[package]]+name = "printcraft-filters"+version = "0.1.0"+dependencies = [+ "flate2",+ "proptest",+ "thiserror 2.0.21",+ "weezl 0.2.1",][[package]]name = "printcraft-geom"version = "0.1.0"+[[package]]+name = "printcraft-organize"+version = "0.1.0"+dependencies = [+ "hayro-syntax",+ "printcraft-cos",+ "thiserror 2.0.21",+]+[[package]]name = "printcraft-render"version = "0.1.0"dependencies = [+ "getrandom 0.4.3","hayro","hayro-syntax",+ "kurbo 0.13.1","log","lopdf","thiserror 2.0.21",@@ -2833,10 +2959,30 @@ dependencies = ["eframe","egui","egui_extras",+ "egui_kittest",+ "image",+ "js-sys",+ "log","printcraft-engine","printcraft-render","rfd","serde",+ "serde_json",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "printcraft-web"+version = "0.1.0"+dependencies = [+ "eframe",+ "egui",+ "js-sys",+ "printcraft-ui-egui",+ "wasm-bindgen-futures",+ "web-sys",][[package]]@@ -2863,12 +3009,37 @@ version = "1.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"+[[package]]+name = "proptest"+version = "1.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"+dependencies = [+ "bit-set 0.8.0",+ "bit-vec 0.8.0",+ "bitflags 2.13.2",+ "num-traits",+ "rand 0.9.5",+ "rand_chacha",+ "rand_xorshift",+ "regex-syntax",+ "rusty-fork",+ "tempfile",+ "unarray",+]+[[package]]name = "pxfm"version = "0.1.30"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"+[[package]]+name = "quick-error"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"+[[package]]name = "quick-error"version = "2.0.1"@@ -2905,6 +3076,16 @@ version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"+[[package]]+name = "rand"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"+dependencies = [+ "rand_chacha",+ "rand_core 0.9.5",+]+[[package]]name = "rand"version = "0.10.3"@@ -2913,7 +3094,26 @@ checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"dependencies = ["chacha20","getrandom 0.4.3",- "rand_core",+ "rand_core 0.10.1",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",][[package]]@@ -2922,6 +3122,15 @@ version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"+[[package]]+name = "rand_xorshift"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"+dependencies = [+ "rand_core 0.9.5",+]+[[package]]name = "range-alloc"version = "0.1.5"@@ -3020,6 +3229,12 @@ dependencies = ["bitflags 2.13.2",]+[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"+[[package]]name = "renderdoc-sys"version = "1.1.0"@@ -3076,6 +3291,20 @@ dependencies = ["bytemuck",]+[[package]]+name = "ron"+version = "0.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "81116b9531d61eabc41aeb228e4b6b2435bcca3233b98cf3b3077d4e6e9debb3"+dependencies = [+ "bitflags 2.13.2",+ "once_cell",+ "serde",+ "serde_derive",+ "typeid",+ "unicode-ident",+]+[[package]]name = "roxmltree"version = "0.20.0"@@ -3135,6 +3364,18 @@ version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"+[[package]]+name = "rusty-fork"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"+dependencies = [+ "fnv",+ "quick-error 1.2.3",+ "tempfile",+ "wait-timeout",+]+[[package]]name = "same-file"version = "1.0.6"@@ -3198,6 +3439,19 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "serde_json"+version = "1.0.151"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]+[[package]]name = "serde_repr"version = "0.1.21"@@ -3209,6 +3463,15 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "serde_spanned"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"+dependencies = [+ "serde_core",+]+[[package]]name = "sha2"version = "0.11.0"@@ -3313,6 +3576,9 @@ name = "smallvec"version = "1.16.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"+dependencies = [+ "serde",+][[package]]name = "smithay-client-toolkit"@@ -3541,7 +3807,7 @@ dependencies = ["fax","flate2","half",- "quick-error",+ "quick-error 2.0.1","weezl 0.1.12","zune-jpeg",]@@ -3587,6 +3853,19 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "toml"+version = "1.1.6+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"+dependencies = [+ "serde_core",+ "serde_spanned",+ "toml_datetime",+ "toml_parser",+ "winnow",+]+[[package]]name = "toml_datetime"version = "1.1.1+spec-1.1.0"@@ -3658,6 +3937,12 @@ dependencies = ["rustc-hash 2.1.3",]+[[package]]+name = "typeid"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"+[[package]]name = "typenum"version = "1.20.1"@@ -3675,6 +3960,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "unarray"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"+[[package]]name = "unicode-bidi"version = "0.3.18"@@ -3833,6 +4124,15 @@ version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"+[[package]]+name = "wait-timeout"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"+dependencies = [+ "libc",+]+[[package]]name = "walkdir"version = "2.5.0"@@ -4112,8 +4412,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"dependencies = ["arrayvec",- "bit-set",- "bit-vec",+ "bit-set 0.10.0",+ "bit-vec 0.9.1","bitflags 2.13.2","bytemuck","cfg_aliases",@@ -4185,7 +4485,7 @@ dependencies = ["android_system_properties","arrayvec","ash",- "bit-set",+ "bit-set 0.10.0","bitflags 2.13.2","block2 0.6.2","bytemuck",@@ -4684,6 +4984,7 @@ dependencies = ["anyhow","lopdf","png 0.18.1",+ "serde_json",][[package]]@@ -4862,6 +5163,12 @@ version = "0.6.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"+[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"+[[package]]name = "zune-core"version = "0.5.3"diff --git a/Cargo.toml b/Cargo.tomlindex 9d150313c..6129bd2fa 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,7 +1,8 @@[workspace]resolver = "3"members = ["crates/*", "apps/*", "xtask"]-default-members = ["crates/*", "apps/printcraft", "xtask"]+exclude = ["vendor"]+default-members = ["crates/*", "apps/printcraft", "apps/printcraft-cli", "xtask"][workspace.package]version = "0.1.0"@@ -13,6 +14,9 @@ repository = "https://github.com/storytold/printcraft"[workspace.dependencies]# internalprintcraft-geom = { path = "crates/geom" }+printcraft-filters = { path = "crates/filters" }+printcraft-cos = { path = "crates/cos" }+printcraft-organize = { path = "crates/organize" }printcraft-render = { path = "crates/render" }printcraft-engine = { path = "crates/engine" }printcraft-ui-egui = { path = "crates/ui-egui" }@@ -21,13 +25,18 @@ printcraft-ui-egui = { path = "crates/ui-egui" }hayro = "0.7.1"hayro-syntax = "0.7.2"lopdf = "0.45"+flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] }+weezl = "0.2"# foundationthiserror = "2"serde = { version = "1", features = ["derive", "rc"] }serde_json = "1"log = "0.4"-kurbo = "0.12"+kurbo = "0.13"++# testing+proptest = "1"# uiegui = "0.36"@@ -52,3 +61,8 @@ opt-level = 1[profile.release]lto = "thin"codegen-units = 1++# Vendored, patched third-party crates (see vendor/README.md). Each patch is meant to go upstream.+[patch.crates-io]+hayro-interpret = { path = "vendor/hayro-interpret" }+hayro = { path = "vendor/hayro" }diff --git a/NOTICE b/NOTICEindex 1a98ff85f..3c736d0ff 100644--- a/NOTICE+++ b/NOTICE@@ -13,3 +13,7 @@ This product bundles or depends on third-party material under the following liceAsset licences are not visible to cargo-deny; keep this file current whenever assets or asset-bundlingdependencies change (plan/adr/0002, 0006).++Vendored (vendor/, patched; see vendor/README.md):+- hayro 0.7.1 — Apache-2.0 OR MIT, Copyright the hayro authors (licence files kept in vendor/hayro).+- hayro-interpret 0.7.0 — Apache-2.0 OR MIT, Copyright the hayro authors (LICENSE-APACHE, LICENSE-MIT kept in vendor/hayro-interpret).diff --git a/README.md b/README.mdindex b13535fc7..4c8bbbd93 100644--- a/README.md+++ b/README.md@@ -3,14 +3,78 @@ PrintCraftFrom the artcraft team-A clean-room, open-source PDF application written in Rust, aiming at Adobe Acrobat Pro parity. It runs natively on macOS, Windows and Linux, and in the browser via WebAssembly. It is a sibling project of PhotoCraft.+A clean-room, open-source PDF application written in Rust, aiming at Adobe Acrobat Pro parity. It runs natively on macOS, Windows and Linux, and in the browser via WebAssembly.-**Status:** early. The viewer slice works; the core PDF object layer (M1) is next. The plan lives in `plan/` (local) and the rules for contributors and agents are in `CLAUDE.md`.+<p align="center">+ <img src="docs/images/printcraft-viewer.png" alt="PrintCraft showing the typography showcase PDF, with the All tools panel on the left and threaded comments on the right" width="100%">+</p>++- **Engine first.** Parsing, rendering and editing live in library crates. The egui interface is one swappable crate on top.+- **Faithful to the file.** The PDF object graph is the document model. Unknown data is preserved. Saves are incremental: the original bytes are kept and your edits are appended.+- **Tested against the real world.** The pdf.js test corpus (983 files) is opened, rendered and round-tripped on every change, and qpdf and poppler are used as independent checks.++<p align="center">+ <img src="docs/images/printcraft-organize.png" alt="The Organize pages view: a grid of page thumbnails with rotate, delete, insert and move actions" width="100%">+</p>++## Status++**Early.** Work so far:+- **Viewer:** rendering, text find, select and copy, bookmarks, comments, layers, attachments and form-field highlighting, on desktop and the web.+- **Editing:**+ - Page organizing: rotate, delete, insert and reorder pages.+ - Document properties.+ - Undo and redo.+ - Save and Save As.+ - A prompt to save unsaved changes before closing.++See [ROADMAP.md](ROADMAP.md) for the milestones, progress and estimates to full parity.```shcargo run -p printcraft -- some.pdf # desktop appcargo xtask demo-pdf # build dist/demo/printcraft-showcase.pdf (needs Chrome)-cargo run -p printcraft -- dist/demo/printcraft-showcase.pdf --panel bookmarks+cargo run -p printcraft -- dist/demo/printcraft-showcase.pdf --panel comments+cargo run -p printcraft-cli -- edit in.pdf --rotate 1:90 --delete 3 --title "Report" --out out.pdf```-Licence: MIT OR Apache-2.0 (proposed). Third-party material is listed in `NOTICE`.+The rules for contributors and agents are in [CLAUDE.md](CLAUDE.md).++## The Craft family++Open-source, clean-room, pure-Rust creative applications. Each is native on macOS, Windows and Linux, runs on the web, and can be driven by agents.++<table>+ <tr>+ <td width="20%" align="center" valign="top">+ <a href="https://github.com/storytold/photocraft"><b>PhotoCraft</b></a><br>+ <sub>Image editing</sub>+ </td>+ <td width="20%" align="center" valign="top">+ <a href="https://github.com/storytold/drawcraft"><b>DrawCraft</b></a><br>+ <sub>Vector illustration</sub>+ </td>+ <td width="20%" align="center" valign="top">+ <a href="https://github.com/storytold/filmcraft"><b>FilmCraft</b></a><br>+ <sub>Video editing</sub>+ </td>+ <td width="20%" align="center" valign="top">+ <a href="https://github.com/storytold/lightcraft"><b>LightCraft</b></a><br>+ <sub>Photo library & raw</sub>+ </td>+ <td width="20%" align="center" valign="top">+ <a href="https://github.com/storytold/printcraft"><b>PrintCraft</b></a><br>+ <sub>PDF documents</sub>+ </td>+ </tr>+ <tr>+ <td valign="top"><sub>Layered raster editor with byte-exact PSD/PSB round trips and 13 formats at 8/16/32-bit. A Photoshop-class workflow.</sub></td>+ <td valign="top"><sub>Vector illustration with the Illustrator-style tools, panels, menus and shortcuts people already know.</sub></td>+ <td valign="top"><sub>Non-linear video editor with frame-exact timing and its own codecs. Aims at Premiere Pro parity.</sub></td>+ <td valign="top"><sub>Photo library and non-destructive raw developer: its own raw decoders, a wide-gamut float pipeline and a local-first catalog.</sub></td>+ <td valign="top"><sub>View, organize, annotate, fill, sign and edit PDFs. Aims at Acrobat Pro parity. <i>You are here.</i></sub></td>+ </tr>+</table>++## Licence++MIT OR Apache-2.0 (proposed). Third-party material is listed in [NOTICE](NOTICE).diff --git a/ROADMAP.md b/ROADMAP.mdnew file mode 100644index 000000000..9293b08f1--- /dev/null+++ b/ROADMAP.md@@ -0,0 +1,80 @@+# PrintCraft roadmap++The milestones, current progress and time estimates to Acrobat Pro feature parity. Keep this up to date:+- **Every session:** update the progress column and add a line to the log.+- **Every milestone:** re-estimate.++Detailed task lists and acceptance tests are in `plan/execution-plan.md` (local-only). This file is the public summary.++**What "parity" means here:** the offline feature set of Acrobat Pro, milestones M0–M14. It excludes Adobe's cloud services (Document Cloud storage, Adobe Sign, the Adobe AI Assistant). Those have no clean-room equivalent; PrintCraft's alternatives are local-first, plus opt-in providers (M13).++## Estimate summary++The unit is **wall-clock hours of agent work**: Claude Opus-class models coding continuously, with a person reviewing at milestone boundaries. Time spent waiting for that review is not included.++| Scenario | Hours to parity (M0–M14) | Continuous calendar time |+|---|---|---|+| One agent, 24/7 | **2,000–4,000 h** | ≈ 3–6 months |+| 3–5 agents in parallel on separate crates after M4 | **800–1,500 h** | ≈ 5–9 weeks |+| Realistic, with human review, integration and pauses | — | ≈ 4–9 months (see `plan/execution-plan.md` §9) |++**How these numbers are built:**+- **Size:** about 450–700k lines of Rust at parity, including tests. The repo has about 15k today.+- **Rate:** so far, about 1.0–1.5k lines of *kept, tested* code per agent-hour. That includes debugging against the oracles (qpdf, poppler, pdf.js corpus).+- **Why the total is 3–6× the raw typing time:** the hard work is not the line count. Most of the time goes into fidelity work: text editing and reflow, font embedding, redaction that really removes content, signature validation, PDF/A and PDF/UA, XFA, OCR and web performance. Each of these needs repeated oracle checks and visual comparison.+- **Parallelism is limited early:** M0–M4 are mostly sequential, because the core crates must settle first. Extra agents pay off from M5 onwards.+- **The long tail:** the last 5–10% (odd real-world files, pixel-level polish) costs about as much as the first 50%.++## Milestones++Hours are for a single agent (low–high). "Done" is the estimated fraction of that milestone's *acceptance criteria* that are met. It is not a count of lines of code.++| M | Milestone | Est. hours | Done | Remaining (h) | Notes |+|---|---|---|---|---|---|+| M0 | Skeleton: workspace, xtask gates, CI | 15–30 | 70% | 5–10 | Missing: GitHub workflow, `deny.toml`, remaining crate stubs, parity TOML |+| M1 | COS: filters, crypt, parser, xref, writer | 120–200 | 40% | 70–120 | Filters done. cos parses every xref form, repairs damaged files, and writes incremental and full saves. Open, edit and save pass on 946 of 951 corpus files. Missing: crypt (R2–R6), object-stream and xref-stream output for full saves, fuzzing, ≥ 250 tests |+| M2 | Model, render, text | 200–350 | 15% | 170–300 | hayro bootstrap renderer (vendored patches). Text extraction reaches word-F1 0.98 against pdftotext. Missing: model crate, fonts, DisplayList, renderer independent of hayro |+| M3 | Viewer app (native + web) | 80–150 | 65% | 30–55 | Acrobat-style shell, find, select, panels, tiles, web build. Missing: UI control channel, 60 fps test on a 500-page document, snapshot tests of every panel |+| M4 | Engine, history, save, organize | 100–180 | 30% | 70–125 | Done: page rotate, delete, move and insert blank; info edits; undo/redo (⌘Z/⇧⌘Z, Edit menu); save and save-as (incremental, atomic write, web download); a dot on tabs with unsaved changes; save prompt on close and quit; organize-grid multi-select; CLI `edit`. Missing: command registry, autosave and recovery, combine/split, bookmark and label editing, drag-to-reorder |+| M5 | Comments (all annotation types, XFDF) | 120–200 | 0% | 120–200 | Read-only comments panel exists |+| M6 | Forms + JavaScript | 160–320 | 0% | 160–320 | Fields are displayed, not filled |+| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 0% | 250–500 | Longest pole |+| M8 | Security + redaction | 100–180 | 0% | 100–180 | |+| M9 | Signatures (PAdES, validation) | 160–280 | 0% | 160–280 | |+| M10 | OCR, create, export, print | 200–350 | 0% | 200–350 | |+| M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 0% | 200–350 | |+| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 0% | 200–380 | |+| M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 0% | 60–120 | |+| M14 | 1.0 polish: performance, localization, installers | 120–250 | 0% | 120–250 | |+| | **Total** | **2,085–3,840** | **≈ 5%** | **≈ 1,915–3,540** | |++**Overall progress: about 5% of the effort.** The viewer and the core are far ahead of the editing features, because the viewer was built first so progress could be seen.++## Critical path++M0 → M1 → M2 → M3 → M4 must happen in order. After M4, M5–M12 can run in parallel across crates. The long poles are M7 (content editing), M9 (signatures) and M12 (XFA).++## Risks most likely to push estimates up++- Fidelity of text editing: fonts, subsets, reflow.+- XFA dynamic layout.+- Real-world signature chains and revocation checks.+- The rendering long tail: Type3 fonts, broken fonts, shadings.+- Correctness of PDF/A and PDF/UA conversion.+- CPU rendering performance on the web.++## Log++Newest first. One line per session: the date, what moved, and the new overall percentage.++- **2026-09-30 (session 3):**+ - New crates: `filters` (every non-image filter, 57 tests) and `cos` (object parser, xref reader, repair, incremental and full writer).+ - New `organize` crate: page operations and info edits.+ - Engine: editing with undo/redo and save. CLI: `edit`.+ - UI: organize toolbar with multi-select, ⌘Z/⇧⌘Z/⌘S/⇧⌘S, Edit menu, editable Description properties, a dot on tabs with unsaved changes, and a save prompt on close and quit. 13 new kittest tests.+ - Corpus: open, edit and save round-trip on 946 of 951 files. 182 of 182 sampled saved outputs pass `qpdf --check`.+ - Overall ≈ 5%.+- **2026-09-30 (session 2):**+ - Robustness sweep (963 of 983 files open, 0 crashes), text layer, find and select, tiles, web build, polish.+ - Overall ≈ 3–4%.+- **2026-09-30 (session 1):** planning complete; viewer vertical slice.diff --git a/apps/printcraft-cli/Cargo.toml b/apps/printcraft-cli/Cargo.tomlnew file mode 100644index 000000000..919db0e4b--- /dev/null+++ b/apps/printcraft-cli/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "printcraft-cli"+description = "PrintCraft command-line tool: inspect, render and robustness-check PDFs"+version.workspace = true+edition.workspace = true+license.workspace = true++[[bin]]+name = "printcraft-cli"+path = "src/main.rs"++[lints]+workspace = true++[dependencies]+printcraft-render = { workspace = true }+serde_json = { workspace = true }+printcraft-engine = { workspace = true }diff --git a/apps/printcraft-cli/src/main.rs b/apps/printcraft-cli/src/main.rsnew file mode 100644index 000000000..7cfca0b3a--- /dev/null+++ b/apps/printcraft-cli/src/main.rs@@ -0,0 +1,288 @@+//! printcraft-cli — headless PrintCraft.+//!+//! ```text+//! printcraft-cli info <file.pdf> [--password PW] document summary as JSON+//! printcraft-cli render <file.pdf> --page N [--dpi 96] --out x.pam+//! printcraft-cli text <file.pdf> [--page N] extracted text (pages separated by form feeds)+//! printcraft-cli edit <in.pdf> --out out.pdf [--rotate 1,3:90] [--delete 2,4] [--move 5:1]+//! [--insert-blank 1] [--title T] [--author A] [--full]+//! printcraft-cli check <files or dirs…> [--timeout 20] [--dpi 36] [--json out.json]+//! ```+//!+//! `check` is the robustness harness: every file is opened, inspected and fully rendered in a+//! *separate child process* with a wall-clock timeout, so hangs, panics and aborts in any+//! dependency are observed and reported instead of taking the harness down.++use std::io::Write;+use std::path::{Path, PathBuf};+use std::process::{Command, ExitCode, Stdio};+use std::sync::Arc;+use std::time::{Duration, Instant};++use printcraft_render::{PageRenderer, RenderConfig, RenderRequest, RequestKind, inspect};++fn main() -> ExitCode {+ let args: Vec<String> = std::env::args().skip(1).collect();+ let result = match args.first().map(String::as_str) {+ Some("info") => info(&args[1..]),+ Some("render") => render(&args[1..]),+ Some("text") => text(&args[1..]),+ Some("edit") => edit(&args[1..]),+ Some("check") => check(&args[1..]),+ Some("check-one") => check_one(&args[1..]),+ Some("--version") => {+ println!("printcraft-cli {}", env!("CARGO_PKG_VERSION"));+ Ok(())+ }+ _ => Err("usage: printcraft-cli <info|render|text|edit|check> … (see source header for options)".into()),+ };+ match result {+ Ok(()) => ExitCode::SUCCESS,+ Err(e) => {+ eprintln!("printcraft-cli: {e}");+ ExitCode::FAILURE+ }+ }+}++fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {+ args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)+}++fn positional(args: &[String]) -> Vec<&str> {+ let mut out = Vec::new();+ let mut skip = false;+ for a in args {+ if skip {+ skip = false;+ continue;+ }+ if a.starts_with("--") {+ skip = true;+ continue;+ }+ out.push(a.as_str());+ }+ out+}++fn read(path: &str) -> Result<Arc<Vec<u8>>, String> {+ std::fs::read(path).map(Arc::new).map_err(|e| format!("{path}: {e}"))+}++fn info(args: &[String]) -> Result<(), String> {+ let path = *positional(args).first().ok_or("info: missing file")?;+ let info = inspect(read(path)?, flag(args, "--password")).map_err(|e| e.to_string())?;+ let json = serde_json::json!({+ "file": path,+ "pdf_version": info.pdf_version,+ "file_size": info.file_size,+ "pages": info.pages.len(),+ "first_page_pt": info.pages.first().map(|p| [p.width, p.height]),+ "title": info.title, "author": info.author, "producer": info.producer, "creator": info.creator,+ "encrypted": info.encrypted, "tagged": info.tagged, "javascript": info.has_javascript,+ "bookmarks": info.outline.len(), "annotations": info.annotations.len(), "fields": info.fields.len(),+ "links": info.links.len(), "layers": info.layers.len(), "attachments": info.attachments.len(),+ "page_labels": info.pages.iter().take(8).map(|p| p.label.clone()).collect::<Vec<_>>(),+ "warnings": info.warnings,+ });+ println!("{}", serde_json::to_string_pretty(&json).unwrap_or_default());+ Ok(())+}++fn text(args: &[String]) -> Result<(), String> {+ let path = *positional(args).first().ok_or("text: missing file")?;+ let mut r = PageRenderer::new(read(path)?, RenderConfig { password: flag(args, "--password").map(Arc::from), ..Default::default() });+ let pages: Vec<usize> = match flag(args, "--page") {+ Some(p) => vec![p.parse::<usize>().map_err(|_| "bad --page")?.saturating_sub(1)],+ None => (0..r.page_count()).collect(),+ };+ for (n, p) in pages.iter().enumerate() {+ let out = r.render(RenderRequest { page: *p, kind: RequestKind::Text, tile: None, scale: 1.0, tag: 0 });+ if let Some(e) = out.error {+ eprintln!("page {}: {e}", p + 1);+ continue;+ }+ if n > 0 {+ println!("\u{c}");+ }+ println!("{}", out.text.map(|t| t.plain_text()).unwrap_or_default());+ }+ Ok(())+}++/// 1-based page list ("1,3,5") → 0-based indices.+fn page_list(s: &str) -> Result<Vec<usize>, String> {+ s.split(',').map(|p| p.trim().parse::<usize>().ok().filter(|n| *n > 0).map(|n| n - 1).ok_or(format!("bad page number {p:?}"))).collect()+}++/// Apply page and metadata edits through the engine and save (incrementally unless `--full`).+fn edit(args: &[String]) -> Result<(), String> {+ use printcraft_engine::{Edit, Session};+ let path = *positional(args).first().ok_or("edit: missing file")?;+ let out = flag(args, "--out").ok_or("edit: missing --out")?;+ let mut session = Session::new();+ let id = session.open(path, Some(path.to_string()), read(path)?, flag(args, "--password")).map_err(|e| e.to_string())?;+ let mut edits = Vec::new();+ let mut i = 0;+ while i < args.len() {+ let value = args.get(i + 1).map(String::as_str).unwrap_or("");+ match args[i].as_str() {+ "--rotate" => {+ let (pages, deg) = value.split_once(':').ok_or("--rotate PAGES:DEGREES")?;+ edits.push(Edit::RotatePages { pages: page_list(pages)?, degrees: deg.parse().map_err(|_| "bad degrees")? });+ }+ "--delete" => edits.push(Edit::DeletePages { pages: page_list(value)? }),+ "--move" => {+ let (pages, to) = value.split_once(':').ok_or("--move PAGES:TO")?;+ let to: usize = to.parse().map_err(|_| "bad target")?;+ edits.push(Edit::MovePages { pages: page_list(pages)?, to: to.saturating_sub(1) });+ }+ "--insert-blank" => {+ let at: usize = value.parse().map_err(|_| "bad position")?;+ edits.push(Edit::InsertBlankPage { at: at.saturating_sub(1), width: 612.0, height: 792.0 });+ }+ "--title" => edits.push(Edit::SetInfo { key: "Title".into(), value: value.into() }),+ "--author" => edits.push(Edit::SetInfo { key: "Author".into(), value: value.into() }),+ _ => {}+ }+ i += 1;+ }+ for e in edits {+ session.apply(id, e).map_err(|e| e.to_string())?;+ }+ let bytes = if args.iter().any(|a| a == "--full") { session.save_full_bytes(id) } else { session.save_bytes(id) }.map_err(|e| e.to_string())?;+ std::fs::write(out, bytes.as_slice()).map_err(|e| format!("{out}: {e}"))+}++fn render(args: &[String]) -> Result<(), String> {+ let path = *positional(args).first().ok_or("render: missing file")?;+ let page: usize = flag(args, "--page").unwrap_or("1").parse().map_err(|_| "bad --page")?;+ let dpi: f32 = flag(args, "--dpi").unwrap_or("96").parse().map_err(|_| "bad --dpi")?;+ let out = flag(args, "--out").ok_or("render: missing --out (.pam)")?;+ let mut r = PageRenderer::new(read(path)?, RenderConfig { password: flag(args, "--password").map(Arc::from), ..Default::default() });+ let p = r.render(RenderRequest { page: page.saturating_sub(1), kind: RequestKind::Pixels, tile: None, scale: dpi / 72.0, tag: 0 });+ if let Some(e) = p.error {+ return Err(e);+ }+ // PAM (netpbm RGB_ALPHA) keeps this tool dependency-free; convert with any image tool.+ let mut f = std::fs::File::create(out).map_err(|e| e.to_string())?;+ write!(f, "P7\nWIDTH {}\nHEIGHT {}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", p.width, p.height).map_err(|e| e.to_string())?;+ f.write_all(&p.rgba).map_err(|e| e.to_string())?;+ eprintln!("rendered page {page} at {dpi} dpi: {}×{} px in {} ms", p.width, p.height, p.millis);+ Ok(())+}++/// Child-process body for `check`: prints one JSON line.+fn check_one(args: &[String]) -> Result<(), String> {+ let path = *positional(args).first().ok_or("check-one: missing file")?;+ let dpi: f32 = flag(args, "--dpi").unwrap_or("36").parse().map_err(|_| "bad --dpi")?;+ let start = Instant::now();+ let bytes = read(path)?;+ let (status, pages, failed, detail, warnings) = match inspect(bytes.clone(), None) {+ Err(e) => (format!("open-error:{}", short(&e.to_string())), 0, 0, e.to_string(), 0),+ Ok(info) => {+ let mut r = PageRenderer::new(bytes, RenderConfig::default());+ let mut failed = Vec::new();+ for i in 0..info.pages.len().min(500) {+ let p = r.render(RenderRequest { page: i, kind: RequestKind::Pixels, tile: None, scale: dpi / 72.0, tag: 0 });+ if let Some(e) = r.render(RenderRequest { page: i, kind: RequestKind::Text, tile: None, scale: 1.0, tag: 0 }).error {+ failed.push(format!("p{} text: {e}", i + 1));+ }+ if let Some(e) = p.error {+ failed.push(format!("p{}: {e}", i + 1));+ }+ }+ let status = if failed.is_empty() { "ok".to_string() } else { "page-errors".to_string() };+ (status, info.pages.len(), failed.len(), failed.join(" | "), info.warnings.len())+ }+ };+ let line = serde_json::json!({ "file": path, "status": status, "pages": pages, "failed_pages": failed, "warnings": warnings,+ "ms": start.elapsed().as_millis() as u64, "detail": detail.chars().take(400).collect::<String>() });+ println!("{line}");+ Ok(())+}++fn short(s: &str) -> String {+ s.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).take(4).collect::<Vec<_>>().join("-").to_lowercase()+}++fn collect(paths: &[&str]) -> Vec<PathBuf> {+ let mut out = Vec::new();+ let mut stack: Vec<PathBuf> = paths.iter().map(PathBuf::from).collect();+ while let Some(p) = stack.pop() {+ if p.is_dir() {+ if let Ok(rd) = std::fs::read_dir(&p) {+ stack.extend(rd.flatten().map(|e| e.path()));+ }+ } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {+ out.push(p);+ }+ }+ out.sort();+ out+}++fn check(args: &[String]) -> Result<(), String> {+ let files = collect(&positional(args));+ if files.is_empty() {+ return Err("check: no PDF files found".into());+ }+ let timeout = Duration::from_secs(flag(args, "--timeout").unwrap_or("20").parse().map_err(|_| "bad --timeout")?);+ let dpi = flag(args, "--dpi").unwrap_or("36").to_string();+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;+ let mut results = Vec::new();+ let mut counts: std::collections::BTreeMap<String, usize> = Default::default();+ for (n, f) in files.iter().enumerate() {+ let r = run_child(&exe, f, &dpi, timeout);+ let status = r["status"].as_str().unwrap_or("?").to_string();+ *counts.entry(status.split(':').next().unwrap_or("?").to_string()).or_default() += 1;+ if status != "ok" {+ eprintln!(+ "[{}/{}] {status:<28} {} {}",+ n + 1,+ files.len(),+ f.display(),+ r["detail"].as_str().unwrap_or("").chars().take(160).collect::<String>()+ );+ }+ results.push(r);+ }+ eprintln!("\nchecked {} files: {:?}", files.len(), counts);+ if let Some(out) = flag(args, "--json") {+ std::fs::write(out, serde_json::to_string_pretty(&results).unwrap_or_default()).map_err(|e| e.to_string())?;+ }+ Ok(())+}++fn run_child(exe: &Path, file: &Path, dpi: &str, timeout: Duration) -> serde_json::Value {+ let file_s = file.to_string_lossy().to_string();+ let child = Command::new(exe).args(["check-one", &file_s, "--dpi", dpi]).stdout(Stdio::piped()).stderr(Stdio::null()).spawn();+ let mut child = match child {+ Ok(c) => c,+ Err(e) => return serde_json::json!({ "file": file_s, "status": "harness-error", "detail": e.to_string() }),+ };+ let start = Instant::now();+ loop {+ match child.try_wait() {+ Ok(Some(status)) => {+ let mut out = String::new();+ if let Some(mut so) = child.stdout.take() {+ use std::io::Read;+ let _ = so.read_to_string(&mut out);+ }+ return match serde_json::from_str::<serde_json::Value>(out.trim()) {+ Ok(v) => v,+ Err(_) => serde_json::json!({ "file": file_s, "status": "crash", "detail": format!("child exited with {status}") }),+ };+ }+ Ok(None) if start.elapsed() > timeout => {+ let _ = child.kill();+ let _ = child.wait();+ return serde_json::json!({ "file": file_s, "status": "timeout", "detail": format!("exceeded {}s", timeout.as_secs()) });+ }+ Ok(None) => std::thread::sleep(Duration::from_millis(20)),+ Err(e) => return serde_json::json!({ "file": file_s, "status": "harness-error", "detail": e.to_string() }),+ }+ }+}diff --git a/apps/printcraft-web/Cargo.toml b/apps/printcraft-web/Cargo.tomlnew file mode 100644index 000000000..dc7ad99cf--- /dev/null+++ b/apps/printcraft-web/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "printcraft-web"+description = "PrintCraft in the browser (wasm32; build with `trunk build --release` in this directory)"+version.workspace = true+edition.workspace = true+license.workspace = true+publish = false++[lints]+workspace = true++[dependencies]+printcraft-ui-egui = { workspace = true }+eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] }+egui = { workspace = true }++[target.'cfg(target_arch = "wasm32")'.dependencies]+wasm-bindgen-futures = "0.4"+web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "HtmlElement", "Location", "Url", "UrlSearchParams", "Response"] }+js-sys = "0.3"diff --git a/apps/printcraft-web/index.html b/apps/printcraft-web/index.htmlnew file mode 100644index 000000000..5980e3676--- /dev/null+++ b/apps/printcraft-web/index.html@@ -0,0 +1,17 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>PrintCraft</title>+ <link data-trunk rel="rust" data-wasm-opt="z" />+ <style>+ html, body { margin: 0; height: 100%; overflow: hidden; background: #f1f1f3; }+ canvas { width: 100%; height: 100%; display: block; outline: none; }+ @media (prefers-color-scheme: dark) { html, body { background: #19191c; } }+ </style>+ </head>+ <body>+ <canvas id="printcraft"></canvas>+ </body>+</html>diff --git a/apps/printcraft-web/src/main.rs b/apps/printcraft-web/src/main.rsnew file mode 100644index 000000000..151683704--- /dev/null+++ b/apps/printcraft-web/src/main.rs@@ -0,0 +1,77 @@+//! PrintCraft in the browser. Build: `cd apps/printcraft-web && trunk build --release`+//! (trunk generates the JS loader; no handwritten JS — plan/execution-plan.md §1).++#[cfg(target_arch = "wasm32")]+fn main() {+ use eframe::wasm_bindgen::JsCast;+ use printcraft_ui_egui::PrintCraftApp;++ let options = eframe::WebOptions { renderer: eframe::Renderer::Glow, ..Default::default() };+ wasm_bindgen_futures::spawn_local(async move {+ let Some(canvas) = web_sys::window()+ .and_then(|w| w.document())+ .and_then(|d| d.get_element_by_id("printcraft"))+ .and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok())+ else {+ return;+ };+ let started = eframe::WebRunner::new()+ .start(+ canvas,+ options,+ Box::new(|cc| {+ let mut app = PrintCraftApp::new();+ if let Some(json) = cc.storage.and_then(|s| s.get_string("printcraft")) {+ app.restore(&json);+ }+ // `?file=<url>` opens a PDF from a URL (same-origin or CORS-enabled).+ if let Some(url) = query_param("file") {+ let inbox = app.inbox.clone();+ let ctx = cc.egui_ctx.clone();+ wasm_bindgen_futures::spawn_local(async move {+ match fetch_bytes(&url).await {+ Ok(bytes) => {+ let name =+ url.rsplit('/').next().unwrap_or("document.pdf").split('?').next().unwrap_or("document.pdf").to_string();+ if let Ok(mut q) = inbox.lock() {+ q.push((name, bytes));+ }+ ctx.request_repaint();+ }+ Err(e) => eframe::web_sys::console::error_1(&format!("PrintCraft: could not fetch {url}: {e}").into()),+ }+ });+ }+ Ok(Box::new(app))+ }),+ )+ .await;+ if let Err(e) = started {+ eframe::web_sys::console::error_1(&e);+ }+ });+}++#[cfg(target_arch = "wasm32")]+fn query_param(key: &str) -> Option<String> {+ let search = web_sys::window()?.location().search().ok()?;+ web_sys::UrlSearchParams::new_with_str(&search).ok()?.get(key)+}++#[cfg(target_arch = "wasm32")]+async fn fetch_bytes(url: &str) -> Result<Vec<u8>, String> {+ use eframe::wasm_bindgen::JsCast;+ let window = web_sys::window().ok_or("no window")?;+ let resp = wasm_bindgen_futures::JsFuture::from(window.fetch_with_str(url)).await.map_err(|e| format!("{e:?}"))?;+ let resp: web_sys::Response = resp.dyn_into().map_err(|_| "not a response")?;+ if !resp.ok() {+ return Err(format!("HTTP {}", resp.status()));+ }+ let buf = wasm_bindgen_futures::JsFuture::from(resp.array_buffer().map_err(|e| format!("{e:?}"))?).await.map_err(|e| format!("{e:?}"))?;+ Ok(js_sys::Uint8Array::new(&buf).to_vec())+}++#[cfg(not(target_arch = "wasm32"))]+fn main() {+ eprintln!("printcraft-web targets wasm32: run `trunk serve` or `trunk build --release` in apps/printcraft-web");+}diff --git a/apps/printcraft/Cargo.toml b/apps/printcraft/Cargo.tomlindex c959ad468..4e126586d 100644--- a/apps/printcraft/Cargo.toml+++ b/apps/printcraft/Cargo.toml@@ -10,5 +10,5 @@ workspace = true[dependencies]printcraft-ui-egui = { workspace = true }-eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11"] }+eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] }egui = { workspace = true }diff --git a/apps/printcraft/src/main.rs b/apps/printcraft/src/main.rsindex a868b9aa2..819a5e079 100644--- a/apps/printcraft/src/main.rs+++ b/apps/printcraft/src/main.rs@@ -39,8 +39,11 @@ fn main() -> eframe::Result {eframe::run_native("PrintCraft",native,- Box::new(move |_cc| {+ Box::new(move |cc| {let mut app = PrintCraftApp::new();+ if let Some(json) = cc.storage.and_then(|s| s.get_string("printcraft")) {+ app.restore(&json);+ }app.integrated_titlebar = integrated;for f in files {app.open_path(&f);diff --git a/assets/demo/README.md b/assets/demo/README.mdnew file mode 100644index 000000000..f68a9480e--- /dev/null+++ b/assets/demo/README.md@@ -0,0 +1,78 @@+# PrintCraft showcase PDF++`showcase.html` is the source of a 13-page, US Letter test document for+viewing and rendering. The PDF is built on your machine and is not committed:++```sh+cargo xtask demo-pdf # writes dist/demo/printcraft-showcase.pdf+cargo xtask demo-pdf --chrome /path/to/chrome --out /tmp/showcase.pdf+```++You need Google Chrome, Chromium or Edge. The tool looks for it in the usual+install locations and on `PATH`, or uses `--chrome` or the `PRINTCRAFT_CHROME`+environment variable if you set one.++## How it is built++1. **Raster.** The xtask renders a Mandelbrot image (Seahorse Valley) and+ encodes it as a PNG. It then inlines the PNG into the HTML as a `data:` URI+ and points `{{ASSETS}}` at this repository's `assets/` directory (for the+ Inter and JetBrains Mono fonts).+2. **Chrome.** Headless Chrome prints the page to PDF with+ `--headless=new --no-pdf-header-footer --generate-pdf-document-outline --print-to-pdf`.+ Skia produces 12 tagged pages with embedded font subsets. Variable+ system-ui weights come out as Type 3 fonts and emoji as Type 3 bitmap+ glyphs. The pages also get shadings, blend modes, soft masks, tiling+ patterns, links, named destinations and bookmarks built from the headings.+3. **Post-processing with `lopdf`** (`xtask/src/demo_pdf/`) adds what a+ browser cannot emit:+ - **Annotations.** The HTML contains marker links to+ `https://mark.printcraft.invalid/<kind>/<id>`. Chrome turns each one into+ a Link annotation whose `/Rect` follows the layout. The xtask replaces+ each marker with a real annotation: Highlight, Underline, StrikeOut,+ Squiggly, Caret, Text with Popup and a threaded reply and review state,+ FreeText with `/DA` and `/RC`, Line with arrow, Square, Circle, Polygon,+ PolyLine, Ink, a custom "APPROVED" Stamp and a FileAttachment. Every+ annotation has its own `/AP` appearance stream, plus `/T`, `/M`, `/NM`+ and `/Contents`.+ - **An appended AcroForm page**, drawn directly with the standard 14 fonts:+ - text fields, including date and amount fields with+ `AFDate_*`/`AFNumber_*` format actions, and a multiline field+ - checkboxes, a radio group, a combo box and a multi-select list box+ - a push button whose JavaScript action calls `app.alert`+ - an unsigned signature field++ Every widget has `/AP` appearance streams, so `NeedAppearances` is false.+ - **Layers.** "Draft watermark" (on) puts a diagonal DRAFT on the review+ page. "Print-only notes" is off on screen and on when printed, with+ `/AS` usage events.+ - **Page labels.** The pages are labelled Cover, i, ii, then 1 to 10.+ - **Bookmarks.** Chrome's heading outline is kept, with its titles tidied,+ and an entry is added for the form page.+ - **Metadata and attachments.** The Info dictionary and an XMP metadata+ stream carry the same values. `/ViewerPreferences /DisplayDocTitle` and+ `/PageMode /UseOutlines` are set. `showcase-data.csv` is attached in+ `/EmbeddedFiles` and `/AF`, and `review-notes.txt` is attached through+ the file-attachment annotation.++Chrome embeds subsets of **macOS system fonts** (Hoefler Text, Didot, Avenir+Next, Geeza Pro, Kohinoor Devanagari, Hiragino, Apple Color Emoji and others),+so the output depends on the host and we must not redistribute it. This is why+`dist/` is gitignored. On Linux or Windows the CSS falls back to other fonts+and the layout will differ. The xtask refuses to continue if Chrome's page+count is not 12, because the post-processing uses fixed page indices.++## Editing the showcase++- Each `<section class="page">` is exactly one Letter page with+ `overflow: hidden`. Keep every section's content inside its page.+- The page order is fixed in `xtask/src/demo_pdf/postprocess.rs`+ (`PAGE_CONTENTS`, `PAGE_SETTING_TEXT`, `PAGE_REVIEW`).+- Marker links use `white-space: nowrap`, so each one produces a single+ rectangle.+- All prose is original. The chart values in `showcase-data.csv` are+ illustrative only.++To check the result, look at the output of `pdfinfo`, `pdffonts` and+`qpdf --check`, and render the pages with+`pdftoppm -r 60 -png dist/demo/printcraft-showcase.pdf /tmp/showcase`.diff --git a/assets/demo/showcase.html b/assets/demo/showcase.htmlindex e5b10786e..6e57fb9d0 100644--- a/assets/demo/showcase.html+++ b/assets/demo/showcase.html@@ -64,7 +64,7 @@ body {.page:last-child { break-after: auto; }a { color: var(--blue); text-decoration: none; }-a.mk { color: inherit; }+a.mk { color: inherit; white-space: nowrap; }/* running header and folio */.runhead {@@ -163,6 +163,11 @@ small, .small { font-size: 8pt; }.tracking div { font: 500 11pt var(--sans); text-transform: uppercase; color: var(--ink-2); padding: 3pt 0; border-bottom: 0.5pt dotted var(--rule); display: flex; justify-content: space-between; }.tracking span.v { font: 400 7pt var(--mono); color: var(--ink-3); letter-spacing: 0; text-transform: none; }+.families { display: grid; grid-template-columns: repeat(6, 1fr); gap: 8pt; margin-top: 6pt; }+.families div { border-top: 1.5pt solid var(--ink); padding-top: 4pt; font: 400 7pt/1.3 var(--sans); color: var(--ink-3); }+.families span { display: block; font-size: 30pt; line-height: 1.25; color: var(--ink); }+.families b { display: block; font: 600 7.5pt var(--sans); color: var(--ink); }+/* ---------- body text ---------- */.cols {column-count: 2; column-gap: 0.32in; column-rule: 0.5pt solid var(--rule);@@ -189,7 +194,7 @@ sup.fn { font: 600 6.5pt var(--sans); color: var(--accent); vertical-align: supeposition: absolute; left: 0.85in; right: 0.85in; bottom: 0.85in;border-top: 0.5pt solid var(--ink-3); padding-top: 6pt; width: 2.2in;}-.footnotes-body { position: absolute; left: 0.85in; right: 0.85in; bottom: 0.82in; font: 7.5pt/1.45 var(--serif); color: var(--ink-2); columns: 2; column-gap: 0.32in; }+.footnotes-body { position: absolute; left: 0.85in; right: 0.85in; bottom: 0.82in; border-top: 0.5pt solid var(--ink-3); padding-top: 6pt; font: 7.5pt/1.45 var(--serif); color: var(--ink-2); columns: 2; column-gap: 0.32in; }.footnotes-body p { margin: 0 0 3pt; }.footnotes-body b { font: 600 6.5pt var(--sans); color: var(--accent); }@@ -209,14 +214,13 @@ sup.fn { font: 600 6.5pt var(--sans); color: var(--accent); vertical-align: supe/* ---------- expressive ---------- */.fx-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14pt 22pt; }-.fx { border: 0.5pt solid var(--rule); border-radius: 6pt; padding: 12pt 14pt 10pt; background: #fffdf8; position: relative; overflow: hidden; height: 1.35in; }+.fx { border: 0.5pt solid var(--rule); border-radius: 6pt; padding: 12pt 14pt 10pt; background: #fffdf8; position: relative; overflow: hidden; height: 1.5in; }.fx .caption { position: absolute; bottom: 8pt; left: 14pt; right: 14pt; }-.shadow { font: 800 40pt var(--ui); color: #fffdf8; letter-spacing: -0.02em; text-shadow: 3pt 3pt 0 rgba(228,87,46,0.55), 6pt 6pt 0 rgba(42,111,219,0.35), 0 0 1pt rgba(22,33,59,0.9); }-.gradtext { display: inline-block; padding-right: 4pt; font: 800 42pt/1 var(--ui); letter-spacing: -0.03em; background: linear-gradient(120deg, #2a6fdb, #1a9e8f 40%, #e9a100 70%, #e4572e); -webkit-background-clip: text; background-clip: text; color: transparent; }-.rot { position: absolute; top: 18pt; right: 18pt; transform: rotate(-12deg); font: 700 13pt var(--sans); color: #fff; background: var(--accent); padding: 3pt 10pt; letter-spacing: 0.2em; }-.skew { display: inline-block; transform: skewX(-18deg); font: 700 28pt var(--sans); background: var(--ink); color: var(--paper); padding: 2pt 14pt; }+.shadow { font: 800 40pt "Avenir Next", var(--sans); color: #fffdf8; letter-spacing: -0.02em; text-shadow: 3pt 3pt 0 rgba(228,87,46,0.55), 6pt 6pt 0 rgba(42,111,219,0.35), 0 0 1pt rgba(22,33,59,0.9); }+.rot { position: absolute; top: 12pt; right: 14pt; transform: rotate(-12deg); font: 700 13pt var(--sans); color: #fff; background: var(--accent); padding: 3pt 10pt; letter-spacing: 0.2em; }+.skew { display: inline-block; transform: skewX(-18deg); font: 700 24pt var(--sans); background: var(--ink); color: var(--paper); padding: 2pt 14pt; }.vert-stack { font: 600 9pt var(--sans); letter-spacing: 0.3em; writing-mode: vertical-rl; transform: rotate(180deg); position: absolute; left: 12pt; top: 12pt; color: var(--teal); text-transform: uppercase; }-.outline-text { font: 800 38pt var(--ui); color: transparent; -webkit-text-stroke: 1pt var(--ink); letter-spacing: 0.02em; }+.outline-text { font: 700 34pt/1.1 "Avenir Next", var(--sans); color: transparent; -webkit-text-stroke: 1pt var(--ink); letter-spacing: 0.02em; }.tracked { font: 400 9pt var(--sans); letter-spacing: 0.6em; text-transform: uppercase; color: var(--ink-2); }/* ---------- scripts ---------- */@@ -224,7 +228,7 @@ sup.fn { font: 600 6.5pt var(--sans); color: var(--accent); vertical-align: supe.sc { border-top: 1.5pt solid var(--ink); padding: 6pt 0 0; }.sc .nm { font: 600 6.8pt var(--sans); letter-spacing: 0.2em; text-transform: uppercase; color: var(--ink-3); display: flex; justify-content: space-between; }.sc .nm i { font-style: normal; color: var(--accent); letter-spacing: 0.05em; }-.sc .tx { font-size: 14pt; line-height: 1.35; margin-top: 3pt; }+.sc .tx { font-size: 13.5pt; white-space: nowrap; line-height: 1.35; margin-top: 3pt; }.sc .en { font: italic 8pt var(--serif); color: var(--ink-3); margin-top: 2pt; }.jp-block {writing-mode: vertical-rl; font: 15pt/1.7 "Hiragino Mincho ProN", serif; height: 2.7in;@@ -378,6 +382,15 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;<div style="letter-spacing:0.12em">Measure twice, set once <span class="v">+120</span></div><div style="letter-spacing:0.3em">Measure twice <span class="v">+300</span></div></div>+ <h3>The families in this specimen</h3>+ <div class="families">+ <div><span style="font-family:Didot">Ag</span><b>Didot</b>Display</div>+ <div><span style="font-family:'Hoefler Text'">Ag</span><b>Hoefler Text</b>Body text</div>+ <div><span style="font-family:'Avenir Next';font-weight:500">Ag</span><b>Avenir Next</b>Labels</div>+ <div><span style="font-family:'PC Mono'">Ag</span><b>JetBrains Mono</b>Code</div>+ <div><span style="font-family:'Snell Roundhand'">Ag</span><b>Snell Roundhand</b>Script</div>+ <div><span style="font-family:'STIX Two Math'">∑x</span><b>STIX Two Math</b>Mathematics</div>+ </div><div class="folio"><span>Foreword</span><b>ii</b></div></section>@@ -388,16 +401,15 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;<h2 class="sec" id="h-setting">Setting <em>Text</em></h2><p class="dek">Two justified columns with automatic hyphenation, old-style figures, a drop cap and a pull quote — the everyday machinery of a well-made page.</p><div class="cols">- <p class="first">Long before there were screens, a page of type was a negotiation between the width of a column and the length of the words that had to fill it. The compositor adjusted spaces, divided a word at a sensible syllable, and occasionally rewrote a line so the paragraph would lie flat. Justified text asks for exactly that care, and <a class="mk" href="https://mark.printcraft.invalid/highlight/body">a renderer must honour the spacing it was given</a>.<sup class="fn">1</sup></p>+ <p class="first">Long before there were screens, a page of type was a negotiation between the width of a column and the length of the words that had to fill it. The compositor adjusted spaces, divided a word at a sensible syllable, and occasionally rewrote a line so the paragraph would lie flat. Justified text asks for exactly that care, and a renderer must <a class="mk" href="https://mark.printcraft.invalid/highlight/body">honour the spacing</a> it was given.<sup class="fn">1</sup></p><p>A PDF does not reflow. Every glyph has already been placed by the program that wrote the file, and the reader’s job is to reproduce those positions faithfully at any zoom. That sounds simple until one remembers that a single line may mix three fonts, a ligature standing in for two letters, and a hyphen that exists only because the line happened to break there in 1994 or 2026.</p><p>Old-style figures, like the ones in this paragraph’s 1,280 characters and 36 lines, rise and fall with the lowercase so that numbers do not shout. Ligatures such as <i>fi</i>, <i>fl</i> and <i>ffi</i> in words like <i>officially</i>, <i>affluent</i> and <i>afflicted</i> join letters that would otherwise collide.<sup class="fn">2</sup></p>- <div class="pull">“The best typography is the kind you only notice when it is missing.”<cite>A working maxim of the trade</cite></div>+ <div class="pull">“Good typography is noticed only when it is missing.”<cite>A working maxim of the trade</cite></div><p>Hyphenation is where browsers and word processors differ most. Chrome consults the system’s hyphenation dictionaries when a paragraph declares its language and asks for automatic hyphens, which is why the words in these columns occasionally divide across lines. The result is a more even texture, with fewer rivers of white running down the column.</p><p>Columns introduce their own questions: where to break, whether a heading may sit at the foot of one, and how a quotation spanning both should interrupt the flow. Here the pull quote spans the full measure and the text resumes beneath it, balanced between the two columns.</p><p>Small text matters too. Notes, captions and legal lines are often set at seven or eight points, where hinting, stem darkening and subpixel positioning decide whether a reader squints. The footnotes below are set at seven and a half points in the same face as the body.<sup class="fn">3</sup></p><p>Finally, notice the drop cap that opens this chapter. It is an ordinary letter, floated and enlarged, with the first line set in small capitals. A renderer need do nothing special for it, which is precisely the point: most typographic richness in a PDF is just careful placement of ordinary glyphs.</p></div>- <div class="footnotes"></div><div class="footnotes-body"><p><b>1</b> Word spacing in PDF is usually baked into glyph positions rather than expressed with the word-spacing operator, so readers rarely need to stretch anything themselves.</p><p><b>2</b> In a PDF a ligature is a single glyph; text extraction relies on the font’s ToUnicode map to recover the letters it represents.</p>@@ -453,8 +465,8 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;<p class="dek">Effects that become transparency groups, soft masks, clipping paths and transformed text objects once they reach PDF.</p><div class="fx-grid"><div class="fx"><div class="shadow">Layered</div><div class="caption"><b>text-shadow</b> · two translucent offset copies composited under the glyphs</div></div>- <div class="fx"><div class="gradtext">Spectrum</div><div class="caption"><b>background-clip: text</b> · a linear shading clipped to glyph outlines</div></div>- <div class="fx"><div style="margin-top:22pt"><span class="skew">Skewed</span></div><div class="rot">Rotated</div><div class="caption"><b>transform</b> · skewX(−18°) on a filled box and rotate(−12°) on a label</div></div>+ <div class="fx"><svg viewBox="0 0 250 60" style="width:2.6in;height:auto;display:block" aria-label="Spectrum"><defs><linearGradient id="specg" x1="0" y1="0" x2="1" y2="0.4"><stop offset="0" stop-color="#2a6fdb"/><stop offset="0.4" stop-color="#1a9e8f"/><stop offset="0.7" stop-color="#e9a100"/><stop offset="1" stop-color="#e4572e"/></linearGradient></defs><text x="0" y="48" font-family="Avenir Next, sans-serif" font-weight="800" font-size="50" letter-spacing="-1" fill="url(#specg)">Spectrum</text></svg><div class="caption"><b>Gradient-filled text</b> · an axial shading clipped to glyph outlines (text render mode 7)</div></div>+ <div class="fx"><div style="margin-top:26pt;margin-left:6pt"><span class="skew">Skewed</span></div><div class="rot">Rotated</div><div class="caption"><b>transform</b> · skewX(−18°) on a filled box and rotate(−12°) on a label</div></div><div class="fx"><div class="outline-text">Outline</div><div class="tracked" style="margin-top:4pt">Tracked to 600</div><div class="caption"><b>-webkit-text-stroke</b> · glyphs stroked, not filled (render mode 1)</div></div></div>@@ -488,23 +500,23 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;<div class="kicker">Chapter four</div><h2 class="sec" id="h-scripts">Scripts of the <em>World</em></h2><p class="dek">A short greeting — roughly, “every letter deserves a good home” — in writing systems that need bidirectional layout, contextual shaping, reordering and vertical setting.</p>- <div style="display:grid;grid-template-columns:1fr 1.25in;gap:18pt">+ <div style="display:grid;grid-template-columns:1fr 1in;gap:16pt"><div class="scripts">- <div class="sc" lang="ar" dir="rtl"><div class="nm" dir="ltr">Arabic <i>RTL · joining</i></div><div class="tx" style="font-family:'Geeza Pro'">لكل حرف بيت جميل</div><div class="en" dir="ltr">Geeza Pro</div></div>+ <div class="sc" lang="ar" dir="rtl"><div class="nm" dir="ltr">Arabic <i>RTL · joining</i></div><div class="tx" style="font-family:'Geeza Pro'">لكل حرف بيت</div><div class="en" dir="ltr">Geeza Pro</div></div><div class="sc" lang="he" dir="rtl"><div class="nm" dir="ltr">Hebrew <i>RTL</i></div><div class="tx" style="font-family:'SF Hebrew','Arial Hebrew',sans-serif">לכל אות יש בית טוב</div><div class="en" dir="ltr">SF Hebrew</div></div>- <div class="sc" lang="hi"><div class="nm">Devanagari <i>conjuncts</i></div><div class="tx" style="font-family:'Kohinoor Devanagari'">हर अक्षर का सुंदर घर</div><div class="en">Kohinoor Devanagari</div></div>- <div class="sc" lang="th"><div class="nm">Thai <i>no spaces</i></div><div class="tx" style="font-family:Thonburi,sans-serif">ทุกตัวอักษรมีบ้านที่ดี</div><div class="en">Thonburi</div></div>+ <div class="sc" lang="hi"><div class="nm">Devanagari <i>conjuncts</i></div><div class="tx" style="font-family:'Kohinoor Devanagari'">हर अक्षर का घर</div><div class="en">Kohinoor Devanagari</div></div>+ <div class="sc" lang="th"><div class="nm">Thai <i>no spaces</i></div><div class="tx" style="font-family:Thonburi,sans-serif">ทุกอักษรมีบ้าน</div><div class="en">Thonburi</div></div><div class="sc" lang="el"><div class="nm">Greek <i>polytonic</i></div><div class="tx" style="font-family:'Hoefler Text',serif">Κάθε γράμμα ἔχει σπίτι</div><div class="en">Hoefler Text</div></div>- <div class="sc" lang="ru"><div class="nm">Cyrillic</div><div class="tx" style="font-family:Baskerville,serif">У каждой буквы есть дом</div><div class="en">Baskerville</div></div>- <div class="sc" lang="zh-Hans"><div class="nm">Chinese <i>simplified</i></div><div class="tx" style="font-family:'PingFang SC','Hiragino Sans GB',sans-serif">每个字都有一个好家</div><div class="en">PingFang SC</div></div>- <div class="sc" lang="ko"><div class="nm">Korean <i>Hangul</i></div><div class="tx" style="font-family:'Apple SD Gothic Neo',sans-serif">모든 글자에게 좋은 집을</div><div class="en">Apple SD Gothic Neo</div></div>- <div class="sc"><div class="nm">IPA <i>phonetics</i></div><div class="tx" style="font-family:'Charis SIL','Hoefler Text','Times New Roman',serif">/ˈtaɪpˌsɛtɪŋ ɪz ˈkræft/</div><div class="en">International Phonetic Alphabet</div></div>- <div class="sc" lang="hy"><div class="nm">Armenian</div><div class="tx" style="font-family:'SF Armenian',sans-serif">Ամեն տառ ունի տուն</div><div class="en">SF Armenian</div></div>- <div class="sc" lang="ka"><div class="nm">Georgian</div><div class="tx" style="font-family:'SF Georgian',sans-serif">ყველა ასოს აქვს სახლი</div><div class="en">SF Georgian</div></div>- <div class="sc" lang="ta"><div class="nm">Tamil</div><div class="tx" style="font-family:'Tamil Sangam MN',sans-serif">ஒவ்வொரு எழுத்துக்கும் வீடு</div><div class="en">Tamil Sangam MN</div></div>+ <div class="sc" lang="ru"><div class="nm">Cyrillic</div><div class="tx" style="font-family:Baskerville,serif">Каждой букве — дом</div><div class="en">Baskerville</div></div>+ <div class="sc" lang="zh-Hans"><div class="nm">Chinese <i>simplified</i></div><div class="tx" style="font-family:'PingFang SC','Hiragino Sans GB',sans-serif">每个字都有家</div><div class="en">PingFang SC</div></div>+ <div class="sc" lang="ko"><div class="nm">Korean <i>Hangul</i></div><div class="tx" style="font-family:'Apple SD Gothic Neo',sans-serif">모든 글자에 집을</div><div class="en">Apple SD Gothic Neo</div></div>+ <div class="sc"><div class="nm">IPA <i>phonetics</i></div><div class="tx" style="font-family:'Charis SIL','Hoefler Text','Times New Roman',serif">/taɪp ɪz ˈkræft/</div><div class="en">International Phonetic Alphabet</div></div>+ <div class="sc" lang="hy"><div class="nm">Armenian</div><div class="tx" style="font-family:'SF Armenian',sans-serif">Ամեն տառին՝ տուն</div><div class="en">SF Armenian</div></div>+ <div class="sc" lang="ka"><div class="nm">Georgian</div><div class="tx" style="font-family:'SF Georgian',sans-serif">ყველა ასოს — სახლი</div><div class="en">SF Georgian</div></div>+ <div class="sc" lang="ta"><div class="nm">Tamil</div><div class="tx" style="font-family:'Tamil Sangam MN',sans-serif">எழுத்துக்கு வீடு</div><div class="en">Tamil Sangam MN</div></div></div><div>- <div class="sc" lang="ja" style="border-top:none;padding:0"><div class="nm">Japanese <i>vertical</i></div>+ <div class="sc" lang="ja" style="border-top:none;padding:0"><div class="nm">Japanese</div><div class="jp-wrap" style="margin-top:6pt"><div class="jp-block">すべての文字に、<br>よい家を。<br>縦書きで読む。</div></div><div class="en" style="margin-top:6pt">Hiragino Mincho ProN, writing-mode: vertical-rl</div></div>@@ -706,13 +718,13 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;<div class="kicker">Chapter eight</div><h2 class="sec" id="h-code">Code & <em>Images</em></h2><p class="dek">A monospaced listing with syntax colouring, and the raster that it describes.</p>-<pre class="code"><span class="ln">1</span><span class="c">// Escape-time rendering of the Mandelbrot set into an RGB buffer.</span>+<pre class="code"><span class="ln">1</span><span class="c">// Escape-time rendering of Seahorse Valley into an RGB buffer.</span><span class="ln">2</span><span class="k">fn</span> <span class="f">mandelbrot</span>(width: <span class="ty">u32</span>, height: <span class="ty">u32</span>) -> <span class="ty">Vec</span><<span class="ty">u8</span>> {<span class="ln">3</span> <span class="k">let mut</span> rgb = <span class="ty">Vec</span>::<span class="f">with_capacity</span>((width * height * <span class="m">3</span>) <span class="k">as</span> <span class="ty">usize</span>);<span class="ln">4</span> <span class="k">for</span> py <span class="k">in</span> <span class="m">0</span>..height {<span class="ln">5</span> <span class="k">for</span> px <span class="k">in</span> <span class="m">0</span>..width {-<span class="ln">6</span> <span class="k">let</span> c = (<span class="m">-2.2</span> + <span class="m">3.0</span> * px <span class="k">as</span> <span class="ty">f64</span> / width <span class="k">as</span> <span class="ty">f64</span>,-<span class="ln">7</span> <span class="m">-1.5</span> + <span class="m">3.0</span> * py <span class="k">as</span> <span class="ty">f64</span> / height <span class="k">as</span> <span class="ty">f64</span>);+<span class="ln">6</span> <span class="k">let</span> c = (<span class="n">CX</span> + <span class="n">SPAN</span> * (px <span class="k">as</span> <span class="ty">f64</span> / width <span class="k">as</span> <span class="ty">f64</span> - <span class="m">0.5</span>),+<span class="ln">7</span> <span class="n">CY</span> - <span class="n">SPAN</span> * (py <span class="k">as</span> <span class="ty">f64</span> / height <span class="k">as</span> <span class="ty">f64</span> - <span class="m">0.5</span>));<span class="ln">8</span> <span class="k">let</span> (<span class="k">mut</span> z, <span class="k">mut</span> n) = ((<span class="m">0.0</span>, <span class="m">0.0</span>), <span class="m">0</span>);<span class="ln">9</span> <span class="k">while</span> n < <span class="n">MAX_ITER</span> && z.<span class="m">0</span> * z.<span class="m">0</span> + z.<span class="m">1</span> * z.<span class="m">1</span> <= <span class="m">4.0</span> {<span class="ln">10</span> z = (z.<span class="m">0</span> * z.<span class="m">0</span> - z.<span class="m">1</span> * z.<span class="m">1</span> + c.<span class="m">0</span>, <span class="m">2.0</span> * z.<span class="m">0</span> * z.<span class="m">1</span> + c.<span class="m">1</span>);diff --git a/crates/cos/Cargo.toml b/crates/cos/Cargo.tomlnew file mode 100644index 000000000..a5623b211--- /dev/null+++ b/crates/cos/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "printcraft-cos"+description = "PDF object layer: lazy tolerant parsing, copy-on-write edits, incremental and full saving"+version.workspace = true+edition.workspace = true+license.workspace = true++[lints]+workspace = true++[dependencies]+printcraft-filters = { workspace = true }+thiserror = { workspace = true }++[dev-dependencies]+proptest = { workspace = true }+hayro-syntax = { workspace = true }diff --git a/crates/cos/examples/cosinfo.rs b/crates/cos/examples/cosinfo.rsnew file mode 100644index 000000000..a35242b57--- /dev/null+++ b/crates/cos/examples/cosinfo.rs@@ -0,0 +1,17 @@+//! Print how a file was opened: revisions, repair notes, trailer. `cargo run -p printcraft-cos --example cosinfo f.pdf`+fn main() {+ let path = std::env::args().nth(1).expect("usage: cosinfo <file.pdf>");+ let bytes = std::sync::Arc::new(std::fs::read(&path).expect("readable"));+ match printcraft_cos::Document::open(bytes) {+ Ok(doc) => {+ println!("version {} revisions {:?}", doc.version(), doc.revisions());+ for r in doc.repair_log() {+ println!("repair: {r}");+ }+ let mut t = Vec::new();+ printcraft_cos::serialize(&printcraft_cos::Object::Dict(doc.trailer().clone()), &mut t);+ println!("trailer {}", String::from_utf8_lossy(&t));+ }+ Err(e) => println!("error: {e}"),+ }+}diff --git a/crates/cos/src/document.rs b/crates/cos/src/document.rsnew file mode 100644index 000000000..39271981e--- /dev/null+++ b/crates/cos/src/document.rs@@ -0,0 +1,708 @@+//! Document: cross-reference data, lazy object loading, and a copy-on-write overlay of edits.+//!+//! `Document` is cheap to clone (the original bytes, xref index and parse caches are shared), so+//! a clone is a snapshot: undo/redo and background jobs hold clones while the UI edits another.+//! Edits never touch the original bytes; the writer appends them (incremental save) or rewrites+//! the file (full save).++use std::collections::{BTreeMap, HashMap, HashSet};+use std::sync::{Arc, Mutex};++use crate::CosError;+use crate::object::{Dict, ObjRef, Object};+use crate::parser::{Lexer, is_whitespace, parse_indirect};++thread_local! {+ static LOAD_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };+}++/// Nesting counter for object loads on this thread (see `Document::try_get`).+struct LoadGuard;++impl LoadGuard {+ const MAX: u32 = 32;++ fn enter() -> Option<Self> {+ LOAD_DEPTH.with(|d| {+ if d.get() >= Self::MAX {+ return None;+ }+ d.set(d.get() + 1);+ Some(LoadGuard)+ })+ }+}++impl Drop for LoadGuard {+ fn drop(&mut self) {+ LOAD_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum XrefEntry {+ Free { next_generation: u16 },+ InFile { offset: u64, generation: u16 },+ InStream { stream: u32, index: u32 },+}++/// One cross-reference section of the file (one per save; the first is the original).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Revision {+ /// Offset of the xref section (`startxref` value).+ pub xref_offset: u64,+ /// `true` if the section is a cross-reference stream.+ pub is_stream: bool,+}++#[derive(Clone, Debug)]+struct ObjStm {+ /// (object number, byte offset within `data`).+ index: Vec<(u32, usize)>,+ data: Arc<Vec<u8>>,+}++/// Where an overlay slot came from.+#[derive(Clone, Debug, PartialEq)]+enum Slot {+ Set(u16, Arc<Object>),+ Freed(u16),+}++#[derive(Clone)]+pub struct Document {+ data: Arc<Vec<u8>>,+ entries: Arc<BTreeMap<u32, XrefEntry>>,+ trailer: Dict,+ revisions: Arc<Vec<Revision>>,+ repair_log: Arc<Vec<String>>,+ cache: Arc<Mutex<HashMap<u32, Arc<Object>>>>,+ objstms: Arc<Mutex<HashMap<u32, Arc<ObjStm>>>>,+ overlay: BTreeMap<u32, Slot>,+ next_num: u32,+ /// Position of the `%PDF-` header (some files have junk before it).+ header_offset: usize,+ version: String,+}++impl std::fmt::Debug for Document {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Document").field("bytes", &self.data.len()).field("objects", &self.entries.len()).field("edits", &self.overlay.len()).finish()+ }+}++impl Document {+ /// Parse a document. Damaged cross-reference data is reconstructed; see `repair_log`.+ pub fn open(data: Arc<Vec<u8>>) -> Result<Self, CosError> {+ // Viewers accept files whose header is missing or damaged as long as the body looks+ // like PDF; so do we (a note goes to the repair log).+ let header = find(&data, b"%PDF-", 0, 1024);+ let headerless = header.is_none();+ if headerless && find(&data, b" obj", 0, 4096).is_none() {+ return Err(CosError::NotPdf);+ }+ let header_offset = header.unwrap_or(0);+ let version = match header {+ Some(h) => String::from_utf8_lossy(&data[(h + 5).min(data.len())..(h + 8).min(data.len())]).trim().to_string(),+ None => "1.4".to_string(),+ };+ let mut doc = Document {+ data,+ entries: Arc::new(BTreeMap::new()),+ trailer: Dict::new(),+ revisions: Arc::new(Vec::new()),+ repair_log: Arc::new(Vec::new()),+ cache: Arc::default(),+ objstms: Arc::default(),+ overlay: BTreeMap::new(),+ next_num: 1,+ header_offset,+ version,+ };+ let mut log = Vec::new();+ if headerless {+ log.push("the %PDF- header is missing; reading the file as PDF 1.4".into());+ }+ let parsed = doc.read_xref_chain(&mut log);+ let ok = match parsed {+ Ok((entries, trailer, revisions)) => {+ doc.entries = Arc::new(entries);+ doc.trailer = trailer;+ doc.revisions = Arc::new(revisions);+ doc.root_is_catalog()+ }+ Err(e) => {+ log.push(format!("cross-reference data unreadable ({e}); rebuilding from object headers"));+ false+ }+ };+ if !ok {+ if !doc.entries.is_empty() {+ log.push("cross-reference data does not lead to a valid catalog; rebuilding from object headers".into());+ }+ doc.reconstruct(&mut log)?;+ }+ doc.repair_log = Arc::new(log);+ if doc.trailer.contains(b"Encrypt") {+ return Err(CosError::Encrypted);+ }+ let max = doc.entries.keys().next_back().copied().unwrap_or(0);+ let size = doc.trailer.int(b"Size").unwrap_or(0).max(0) as u32;+ doc.next_num = max.max(size.saturating_sub(1)) + 1;+ Ok(doc)+ }++ pub fn bytes(&self) -> &Arc<Vec<u8>> {+ &self.data+ }++ pub fn version(&self) -> &str {+ &self.version+ }++ pub fn trailer(&self) -> &Dict {+ &self.trailer+ }++ pub fn trailer_mut(&mut self) -> &mut Dict {+ &mut self.trailer+ }++ pub fn revisions(&self) -> &[Revision] {+ &self.revisions+ }++ pub fn repair_log(&self) -> &[String] {+ &self.repair_log+ }++ /// `true` when there are unsaved edits.+ pub fn is_modified(&self) -> bool {+ !self.overlay.is_empty()+ }++ /// Object numbers changed since the document was opened (or last saved).+ pub fn modified_objects(&self) -> Vec<u32> {+ self.overlay.keys().copied().collect()+ }++ pub fn root(&self) -> Option<ObjRef> {+ self.trailer.reference(b"Root")+ }++ // ── object access ───────────────────────────────────────────────────────────────────────++ /// Fetch an object by reference. Missing objects are `Null` (ISO 32000-2 §7.3.10).+ pub fn get(&self, r: ObjRef) -> Arc<Object> {+ self.try_get(r.num).unwrap_or_else(|_| Arc::new(Object::Null))+ }++ /// Follow a reference if `o` is one; otherwise return `o` itself.+ pub fn resolve(&self, o: &Object) -> Arc<Object> {+ match o {+ Object::Ref(r) => self.get(*r),+ other => Arc::new(other.clone()),+ }+ }++ /// Resolve and return a dictionary (a stream's dictionary counts).+ pub fn dict(&self, o: &Object) -> Option<Dict> {+ self.resolve(o).as_dict().cloned()+ }++ pub fn try_get(&self, num: u32) -> Result<Arc<Object>, CosError> {+ match self.overlay.get(&num) {+ Some(Slot::Set(_, o)) => return Ok(o.clone()),+ Some(Slot::Freed(_)) => return Ok(Arc::new(Object::Null)),+ None => {}+ }+ if let Some(o) = self.cache.lock().map_err(|_| CosError::Poisoned)?.get(&num) {+ return Ok(o.clone());+ }+ // Loading can re-enter (indirect stream `/Length`, object streams); damaged files make+ // cycles such as `6 0 obj << /Length 6 0 R >>`. Bound the nesting on every path.+ let _guard =+ LoadGuard::enter().ok_or_else(|| CosError::Syntax { offset: 0, detail: format!("reference cycle while loading object {num}") })?;+ let obj = self.load(num, 0)?;+ let obj = Arc::new(obj);+ self.cache.lock().map_err(|_| CosError::Poisoned)?.insert(num, obj.clone());+ Ok(obj)+ }++ fn load(&self, num: u32, depth: u32) -> Result<Object, CosError> {+ if depth > 16 {+ return Err(CosError::Syntax { offset: 0, detail: "reference cycle while loading".into() });+ }+ match self.entries.get(&num) {+ None | Some(XrefEntry::Free { .. }) => Ok(Object::Null),+ Some(XrefEntry::InFile { offset, .. }) => {+ let resolve = |r: ObjRef| self.try_get(r.num).ok().and_then(|o| o.as_int());+ let off = *offset as usize;+ match parse_indirect(&self.data, off, &resolve) {+ Ok((id, o)) if id.num == num => Ok(o),+ // Offsets relative to a shifted header, or simply wrong: try both fixes.+ _ => match parse_indirect(&self.data, off + self.header_offset, &resolve) {+ Ok((id, o)) if id.num == num => Ok(o),+ _ => self.scan_for(num).ok_or(CosError::MissingObject(num)),+ },+ }+ }+ Some(XrefEntry::InStream { stream, index }) => {+ let stm = self.objstm(*stream)?;+ let (n, off) = stm+ .index+ .get(*index as usize)+ .copied()+ .or_else(|| stm.index.iter().find(|(n, _)| *n == num).copied())+ .ok_or(CosError::MissingObject(num))?;+ let off =+ if n == num { off } else { stm.index.iter().find(|(n, _)| *n == num).map(|(_, o)| *o).ok_or(CosError::MissingObject(num))? };+ Lexer::new(&stm.data, off).object()+ }+ }+ }++ fn objstm(&self, num: u32) -> Result<Arc<ObjStm>, CosError> {+ if let Some(s) = self.objstms.lock().map_err(|_| CosError::Poisoned)?.get(&num) {+ return Ok(s.clone());+ }+ let Object::Stream(s) = &*self.try_get(num)? else { return Err(CosError::MissingObject(num)) };+ let n = s.dict.int(b"N").unwrap_or(0).clamp(0, 1_000_000) as usize;+ let first = s.dict.int(b"First").unwrap_or(0).max(0) as usize;+ let data = s.decoded()?;+ let mut lx = Lexer::new(&data, 0);+ let mut index = Vec::with_capacity(n);+ for _ in 0..n {+ let (Some(Object::Int(onum)), Some(Object::Int(off))) = (lx.object().ok(), lx.object().ok()) else { break };+ index.push((onum.max(0) as u32, first + off.max(0) as usize));+ }+ let stm = Arc::new(ObjStm { index, data: Arc::new(data) });+ self.objstms.lock().map_err(|_| CosError::Poisoned)?.insert(num, stm.clone());+ Ok(stm)+ }++ /// Last-resort lookup: scan the file for `num G obj`.+ fn scan_for(&self, num: u32) -> Option<Object> {+ let needle = format!("{num} ");+ let data = &self.data;+ let mut found = None;+ let mut i = 0;+ while let Some(p) = find(data, needle.as_bytes(), i, data.len()) {+ i = p + 1;+ if p > 0 && !is_whitespace(data[p - 1]) {+ continue;+ }+ if let Ok((id, o)) = parse_indirect(data, p, &|_| None)+ && id.num == num+ {+ found = Some(o); // keep the last (newest) definition+ }+ }+ found+ }++ // ── editing ─────────────────────────────────────────────────────────────────────────────++ /// Replace an object (keeping its generation).+ pub fn set(&mut self, r: ObjRef, obj: impl Into<Object>) {+ self.overlay.insert(r.num, Slot::Set(r.generation, Arc::new(obj.into())));+ if r.num >= self.next_num {+ self.next_num = r.num + 1;+ }+ }++ /// Add a new indirect object and return its reference.+ pub fn add(&mut self, obj: impl Into<Object>) -> ObjRef {+ let r = ObjRef::new(self.next_num, 0);+ self.next_num += 1;+ self.overlay.insert(r.num, Slot::Set(0, Arc::new(obj.into())));+ r+ }++ /// Delete an object (its number becomes free with the next generation).+ pub fn free(&mut self, r: ObjRef) {+ self.overlay.insert(r.num, Slot::Freed(r.generation.saturating_add(1)));+ }++ /// Edit a dictionary (or stream dictionary) object in place.+ pub fn update_dict(&mut self, r: ObjRef, f: impl FnOnce(&mut Dict)) -> Result<(), CosError> {+ let mut obj = (*self.get(r)).clone();+ let d = obj.as_dict_mut().ok_or(CosError::NotADictionary(r))?;+ f(d);+ self.set(r, obj);+ Ok(())+ }++ /// Current generation of an object number.+ pub fn generation(&self, num: u32) -> u16 {+ match self.overlay.get(&num) {+ Some(Slot::Set(g, _)) => *g,+ Some(Slot::Freed(g)) => *g,+ None => match self.entries.get(&num) {+ Some(XrefEntry::InFile { generation, .. }) => *generation,+ Some(XrefEntry::Free { next_generation }) => *next_generation,+ _ => 0,+ },+ }+ }++ pub(crate) fn overlay_entries(&self) -> impl Iterator<Item = (u32, u16, Option<Arc<Object>>)> + '_ {+ self.overlay.iter().map(|(n, s)| match s {+ Slot::Set(g, o) => (*n, *g, Some(o.clone())),+ Slot::Freed(g) => (*n, *g, None),+ })+ }++ pub(crate) fn next_num(&self) -> u32 {+ self.next_num+ }++ /// All object numbers known (file and overlay), excluding freed ones.+ pub fn object_numbers(&self) -> Vec<u32> {+ let mut set: HashSet<u32> = self.entries.iter().filter(|(_, e)| !matches!(e, XrefEntry::Free { .. })).map(|(n, _)| *n).collect();+ for (n, s) in &self.overlay {+ match s {+ Slot::Set(..) => set.insert(*n),+ Slot::Freed(_) => set.remove(n),+ };+ }+ let mut v: Vec<u32> = set.into_iter().collect();+ v.sort_unstable();+ v+ }++ /// Rebase this document on bytes written by the writer (after a save): edits become part of+ /// the file and the overlay is cleared, so the next incremental save appends only new edits.+ pub fn reopen_after_save(&self, bytes: Arc<Vec<u8>>) -> Result<Self, CosError> {+ Document::open(bytes)+ }++ // ── cross-reference parsing ─────────────────────────────────────────────────────────────++ fn root_is_catalog(&self) -> bool {+ let Some(r) = self.root() else { return false };+ matches!(self.try_get(r.num).as_deref(), Ok(Object::Dict(d)) if d.name(b"Type") == Some(b"Catalog") || d.contains(b"Pages"))+ }++ #[allow(clippy::type_complexity)]+ fn read_xref_chain(&self, log: &mut Vec<String>) -> Result<(BTreeMap<u32, XrefEntry>, Dict, Vec<Revision>), CosError> {+ let data = &self.data;+ let tail_start = data.len().saturating_sub(4096);+ let sx = rfind(data, b"startxref", tail_start).ok_or(CosError::Syntax { offset: data.len(), detail: "no startxref".into() })?;+ let mut lx = Lexer::new(data, sx + 9);+ let first = match lx.object() {+ Ok(Object::Int(n)) if n >= 0 => n as u64,+ _ => return Err(CosError::Syntax { offset: sx, detail: "bad startxref value".into() }),+ };+ let mut entries = BTreeMap::new();+ let mut trailer: Option<Dict> = None;+ let mut revisions = Vec::new();+ let mut visited = HashSet::new();+ let mut next = Some(first);+ while let Some(off) = next.take() {+ if !visited.insert(off) || visited.len() > 10_000 {+ log.push(format!("cross-reference chain loops at offset {off}; stopped"));+ break;+ }+ let (sect_trailer, is_stream) = match self.read_section(off as usize, &mut entries) {+ Ok(v) => v,+ Err(e) if self.header_offset > 0 => {+ log.push(format!("xref at {off} unreadable ({e}); retrying relative to the header"));+ self.read_section(off as usize + self.header_offset, &mut entries)?+ }+ Err(e) => {+ if revisions.is_empty() {+ return Err(e);+ }+ log.push(format!("older cross-reference section at {off} is unreadable: {e}"));+ break;+ }+ };+ revisions.push(Revision { xref_offset: off, is_stream });+ // Hybrid files: the /XRefStm entries supplement the table (§7.5.8.4).+ if let Some(x) = sect_trailer.int(b"XRefStm").filter(|x| *x >= 0)+ && let Err(e) = self.read_section(x as usize, &mut entries)+ {+ log.push(format!("hybrid /XRefStm at {x} unreadable: {e}"));+ }+ next = sect_trailer.int(b"Prev").filter(|p| *p >= 0).map(|p| p as u64);+ if trailer.is_none() {+ trailer = Some(sect_trailer);+ }+ }+ revisions.reverse();+ let mut trailer = trailer.ok_or(CosError::Syntax { offset: 0, detail: "no trailer".into() })?;+ for k in [&b"Prev"[..], b"XRefStm", b"Type", b"W", b"Index", b"Filter", b"DecodeParms", b"Length"] {+ trailer.remove(k);+ }+ Ok((entries, trailer, revisions))+ }++ /// Read one section at `off`, adding entries not already known (newer sections win).+ fn read_section(&self, off: usize, entries: &mut BTreeMap<u32, XrefEntry>) -> Result<(Dict, bool), CosError> {+ let data = &self.data;+ let mut lx = Lexer::new(data, off);+ if lx.eat_keyword(b"xref") {+ loop {+ lx.skip_ws();+ if lx.eat_keyword(b"trailer") {+ let t = lx.object()?;+ let d = t.as_dict().cloned().ok_or(CosError::Syntax { offset: lx.pos, detail: "trailer is not a dictionary".into() })?;+ return Ok((d, false));+ }+ let (Ok(Object::Int(start)), Ok(Object::Int(count))) = (lx.object(), lx.object()) else {+ return Err(CosError::Syntax { offset: lx.pos, detail: "bad xref subsection header".into() });+ };+ if start < 0 || !(0..=10_000_000).contains(&count) {+ return Err(CosError::Syntax { offset: lx.pos, detail: "implausible xref subsection".into() });+ }+ for i in 0..count {+ lx.skip_ws();+ let o = lx.token();+ lx.skip_ws();+ let g = lx.token();+ lx.skip_ws();+ let kind = lx.token();+ let num = (start + i) as u32;+ let offset = std::str::from_utf8(o).ok().and_then(|s| s.parse::<u64>().ok());+ let generation = std::str::from_utf8(g).ok().and_then(|s| s.parse::<u32>().ok()).unwrap_or(0).min(u16::MAX as u32) as u16;+ let entry = match (kind, offset) {+ (b"n", Some(offset)) => XrefEntry::InFile { offset, generation },+ (b"f", _) => XrefEntry::Free { next_generation: generation },+ _ => return Err(CosError::Syntax { offset: lx.pos, detail: "bad xref entry".into() }),+ };+ // Offset 0 "in use" entries are a known producer bug: ignore them.+ if matches!(entry, XrefEntry::InFile { offset: 0, .. }) {+ continue;+ }+ entries.entry(num).or_insert(entry);+ }+ }+ }+ // Cross-reference stream.+ let (_, obj) = parse_indirect(data, off, &|_| None)?;+ let Object::Stream(s) = obj else { return Err(CosError::Syntax { offset: off, detail: "expected xref table or stream".into() }) };+ if s.dict.name(b"Type") != Some(b"XRef") {+ return Err(CosError::Syntax { offset: off, detail: "stream at startxref is not /Type /XRef".into() });+ }+ let w: Vec<usize> = s+ .dict+ .get(b"W")+ .and_then(Object::as_array)+ .map(|a| a.iter().map(|x| x.as_int().unwrap_or(0).clamp(0, 8) as usize).collect())+ .unwrap_or_default();+ if w.len() < 3 {+ return Err(CosError::Syntax { offset: off, detail: "xref stream /W invalid".into() });+ }+ let size = s.dict.int(b"Size").unwrap_or(0).max(0);+ let index: Vec<i64> = match s.dict.get(b"Index").and_then(Object::as_array) {+ Some(a) => a.iter().filter_map(Object::as_int).collect(),+ None => vec![0, size],+ };+ let raw = s.decoded()?;+ let row = w[0] + w[1] + w[2];+ if row == 0 {+ return Err(CosError::Syntax { offset: off, detail: "xref stream row width 0".into() });+ }+ let field = |r: &[u8], from: usize, len: usize, default: u64| -> u64 {+ if len == 0 {+ return default;+ }+ r[from..from + len].iter().fold(0u64, |acc, b| acc << 8 | *b as u64)+ };+ let mut rows = raw.chunks_exact(row);+ for pair in index.chunks(2) {+ let [start, count] = pair else { break };+ for i in 0..(*count).max(0) {+ let Some(r) = rows.next() else { break };+ let t = field(r, 0, w[0], 1);+ let a = field(r, w[0], w[1], 0);+ let b = field(r, w[0] + w[1], w[2], 0);+ let num = (*start + i).max(0) as u32;+ let entry = match t {+ 0 => XrefEntry::Free { next_generation: b.min(u16::MAX as u64) as u16 },+ 1 => XrefEntry::InFile { offset: a, generation: b.min(u16::MAX as u64) as u16 },+ 2 => XrefEntry::InStream { stream: a.min(u32::MAX as u64) as u32, index: b.min(u32::MAX as u64) as u32 },+ _ => continue, // reserved types are treated as null references (§7.5.8.3)+ };+ if matches!(entry, XrefEntry::InFile { offset: 0, .. }) {+ continue;+ }+ entries.entry(num).or_insert(entry);+ }+ }+ Ok((s.dict.clone(), true))+ }++ /// Rebuild the cross-reference index by scanning for `N G obj` headers (§7.5.4 recovery).+ fn reconstruct(&mut self, log: &mut Vec<String>) -> Result<(), CosError> {+ let data = self.data.clone();+ let mut entries: BTreeMap<u32, XrefEntry> = BTreeMap::new();+ let mut i = 0;+ let mut objstms = Vec::new();+ while i < data.len() {+ // Object headers start at a line start (or after whitespace).+ let at_start = i == 0 || is_whitespace(data[i - 1]) || data[i - 1] == b'>';+ if at_start && data[i].is_ascii_digit() {+ let mut lx = Lexer::new(&data, i);+ let n = lx.token();+ lx.skip_ws();+ let g = lx.token();+ if !n.is_empty() && !g.is_empty() && n.iter().all(u8::is_ascii_digit) && g.iter().all(u8::is_ascii_digit) && lx.eat_keyword(b"obj") {+ let num = std::str::from_utf8(n).ok().and_then(|s| s.parse::<u32>().ok());+ let generation = std::str::from_utf8(g).ok().and_then(|s| s.parse::<u16>().ok()).unwrap_or(0);+ if let Some(num) = num {+ entries.insert(num, XrefEntry::InFile { offset: i as u64, generation });+ objstms.push(num);+ }+ i = lx.pos;+ continue;+ }+ }+ i += 1;+ }+ if entries.is_empty() {+ return Err(CosError::Syntax { offset: 0, detail: "no objects found".into() });+ }+ self.entries = Arc::new(entries.clone());+ self.cache.lock().map_err(|_| CosError::Poisoned)?.clear();+ // Objects inside object streams.+ for num in objstms {+ if let Ok(o) = self.try_get(num)+ && let Object::Stream(s) = &*o+ && s.dict.name(b"Type") == Some(b"ObjStm")+ && let Ok(stm) = self.objstm(num)+ {+ for (idx, (inner, _)) in stm.index.iter().enumerate() {+ entries.entry(*inner).or_insert(XrefEntry::InStream { stream: num, index: idx as u32 });+ }+ }+ }+ self.entries = Arc::new(entries);+ self.cache.lock().map_err(|_| CosError::Poisoned)?.clear();+ // Trailer: the last `trailer` dictionary with a usable /Root, else the catalog itself.+ let mut trailer = None;+ let mut from = 0;+ while let Some(p) = find(&data, b"trailer", from, data.len()) {+ from = p + 7;+ let mut lx = Lexer::new(&data, from);+ if let Ok(Object::Dict(d)) = lx.object()+ && d.reference(b"Root").is_some_and(|r| matches!(self.try_get(r.num).as_deref(), Ok(Object::Dict(_))))+ {+ trailer = Some(d);+ }+ }+ let trailer = match trailer {+ Some(t) => t,+ None => {+ let catalog = self+ .entries+ .keys()+ .copied()+ .find(|n| matches!(self.try_get(*n).as_deref(), Ok(Object::Dict(d)) if d.name(b"Type") == Some(b"Catalog")));+ let Some(c) = catalog else { return Err(CosError::Syntax { offset: 0, detail: "no document catalog found".into() }) };+ let mut t = Dict::new();+ t.set(b"Root".to_vec(), Object::Ref(ObjRef::new(c, self.generation(c))));+ t+ }+ };+ let mut trailer = trailer;+ for k in [&b"Prev"[..], b"XRefStm"] {+ trailer.remove(k);+ }+ self.trailer = trailer;+ self.revisions = Arc::new(Vec::new());+ log.push(format!("rebuilt cross-reference index from {} object headers", self.entries.len()));+ Ok(())+ }+}++pub(crate) fn find(hay: &[u8], needle: &[u8], from: usize, to: usize) -> Option<usize> {+ let to = to.min(hay.len());+ if from >= to || needle.is_empty() || to - from < needle.len() {+ return None;+ }+ hay[from..to].windows(needle.len()).position(|w| w == needle).map(|p| p + from)+}++fn rfind(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {+ if hay.len() < needle.len() {+ return None;+ }+ (from..=hay.len() - needle.len()).rev().find(|&i| &hay[i..i + needle.len()] == needle)+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Build a classic-xref file from object bodies (object i+1 = bodies[i]).+ pub(crate) fn build(bodies: &[&str], trailer: &str) -> Vec<u8> {+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, b) in bodies.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{b}\nendobj\n", i + 1).as_bytes());+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes());+ for o in offsets {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n<< /Size {} {trailer} >>\nstartxref\n{xref}\n%%EOF\n", bodies.len() + 1).as_bytes());+ out+ }++ #[test]+ fn self_referential_length_does_not_overflow() {+ let bytes = build(+ &["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "<< /Length 3 0 R >>\nstream\nabc\nendstream"],+ "/Root 1 0 R",+ );+ let doc = Document::open(Arc::new(bytes)).unwrap();+ // Either recovered via the endstream search or reported — but never a stack overflow.+ let o = doc.get(ObjRef::new(3, 0));+ if let Object::Stream(s) = o.as_ref() {+ assert_eq!(s.raw.as_slice(), b"abc");+ }+ }++ #[test]+ fn mutually_referential_lengths_do_not_overflow() {+ let bytes = build(+ &[+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [] /Count 0 >>",+ "<< /Length 4 0 R >>\nstream\nabc\nendstream",+ "<< /Length 3 0 R >>\nstream\nxyz\nendstream",+ ],+ "/Root 1 0 R",+ );+ let doc = Document::open(Arc::new(bytes)).unwrap();+ let _ = doc.get(ObjRef::new(3, 0));+ let _ = doc.get(ObjRef::new(4, 0));+ }++ #[test]+ fn reads_classic_revision_and_edits_are_copy_on_write() {+ let bytes = build(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"], "/Root 1 0 R");+ let doc = Document::open(Arc::new(bytes)).unwrap();+ assert_eq!(doc.revisions().len(), 1);+ assert!(doc.repair_log().is_empty());+ let mut edited = doc.clone();+ edited.update_dict(ObjRef::new(1, 0), |d| d.set(b"Lang".to_vec(), Object::String(crate::PdfString::literal("en")))).unwrap();+ assert!(edited.is_modified() && !doc.is_modified(), "clone is an independent snapshot");+ assert!(doc.get(ObjRef::new(1, 0)).as_dict().unwrap().get(b"Lang").is_none());+ }++ #[test]+ fn damaged_xref_is_reconstructed() {+ let mut bytes = build(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"], "/Root 1 0 R");+ let n = bytes.len();+ bytes[n - 12..n - 6].copy_from_slice(b"999999"); // point startxref into nowhere+ let doc = Document::open(Arc::new(bytes)).unwrap();+ assert!(doc.revisions().is_empty());+ assert!(!doc.repair_log().is_empty());+ assert_eq!(doc.root(), Some(ObjRef::new(1, 0)));+ }+}diff --git a/crates/cos/src/lib.rs b/crates/cos/src/lib.rsnew file mode 100644index 000000000..63152d887--- /dev/null+++ b/crates/cos/src/lib.rs@@ -0,0 +1,38 @@+//! printcraft-cos — the PDF object layer (L1, standalone with `printcraft-filters`).+//!+//! Parses the COS object graph lazily and tolerantly, keeps edits in a copy-on-write overlay+//! (cheap snapshots for undo), and writes documents back either incrementally (original bytes+//! untouched) or as a full, garbage-collected rewrite. The PDF object graph *is* PrintCraft's+//! document model (plan/architecture.md §5, ADR-0010).+//!+//! Status (M1 in progress): parsing of all xref forms, object streams, repair by scanning,+//! incremental and full writing. Not yet: encryption (M1.6), object-stream / xref-stream output+//! for full saves, linearization (M11).++mod document;+mod object;+mod parser;+mod writer;++pub use document::{Document, Revision, XrefEntry};+pub use object::{Dict, MAX_DECODED, Name, ObjRef, Object, PdfString, Stream};+pub use parser::{Lexer, parse_indirect};+pub use writer::{SaveOptions, pdf_date, serialize, write_full, write_incremental};++#[derive(Debug, thiserror::Error, Clone, PartialEq)]+pub enum CosError {+ #[error("not a PDF file (no %PDF- header)")]+ NotPdf,+ #[error("syntax error at byte {offset}: {detail}")]+ Syntax { offset: usize, detail: String },+ #[error("object {0} is missing")]+ MissingObject(u32),+ #[error("object {0} is not a dictionary")]+ NotADictionary(ObjRef),+ #[error("stream data could not be decoded: {0}")]+ Filter(String),+ #[error("the document is encrypted; editing encrypted documents arrives with M1.6")]+ Encrypted,+ #[error("internal lock poisoned")]+ Poisoned,+}diff --git a/crates/cos/src/object.rs b/crates/cos/src/object.rsnew file mode 100644index 000000000..01ad7824e--- /dev/null+++ b/crates/cos/src/object.rs@@ -0,0 +1,386 @@+//! The PDF object model (ISO 32000-2 §7.3).+//!+//! Dictionaries keep their key order so rewritten objects stay recognisable in diffs and+//! byte-stable when re-serialized. Streams keep their *encoded* bytes; decoding is on demand.++use std::sync::Arc;++use printcraft_filters::{Filter, Params};++use crate::CosError;++/// An indirect reference: object number and generation.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct ObjRef {+ pub num: u32,+ pub generation: u16,+}++impl ObjRef {+ pub const fn new(num: u32, generation: u16) -> Self {+ Self { num, generation }+ }+}++impl std::fmt::Display for ObjRef {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{} {} R", self.num, self.generation)+ }+}++/// A string object. `hex` records how it was written, so it is re-emitted the same way.+#[derive(Clone, Debug, PartialEq)]+pub struct PdfString {+ pub bytes: Vec<u8>,+ pub hex: bool,+}++impl PdfString {+ pub fn literal(bytes: impl Into<Vec<u8>>) -> Self {+ Self { bytes: bytes.into(), hex: false }+ }++ /// A text string (ISO 32000-2 §7.9.2.2): PDFDocEncoding when possible, else UTF-16BE with BOM.+ pub fn text(s: &str) -> Self {+ if s.chars().all(|c| (' '..='~').contains(&c) || c == '\n' || c == '\r' || c == '\t') {+ return Self::literal(s.as_bytes().to_vec());+ }+ let mut bytes = vec![0xFE, 0xFF];+ for u in s.encode_utf16() {+ bytes.extend_from_slice(&u.to_be_bytes());+ }+ Self { bytes, hex: false }+ }++ /// Decode a text string: UTF-16BE (BOM), UTF-8 (BOM, PDF 2.0) or PDFDocEncoding.+ pub fn to_text(&self) -> String {+ let b = &self.bytes;+ if b.len() >= 2 && b[0] == 0xFE && b[1] == 0xFF {+ let units: Vec<u16> = b[2..].chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();+ return String::from_utf16_lossy(&units);+ }+ if b.len() >= 3 && b[..3] == [0xEF, 0xBB, 0xBF] {+ return String::from_utf8_lossy(&b[3..]).into_owned();+ }+ b.iter().map(|&c| pdfdoc_char(c)).collect()+ }+}++/// PDFDocEncoding → Unicode (ISO 32000-2 Annex D). Bytes 0x18–0x1F and 0x80–0xA0 differ from Latin-1.+fn pdfdoc_char(c: u8) -> char {+ const HIGH: [char; 33] = [+ '•', '†', '‡', '…', '—', '–', 'ƒ', '⁄', '‹', '›', '−', '‰', '„', '“', '”', '‘', '’', '‚', '™', 'fi', 'fl', 'Ł', 'Œ', 'Š', 'Ÿ', 'Ž', 'ı', 'ł',+ 'œ', 'š', 'ž', '\u{FFFD}', '€',+ ];+ const LOW: [char; 8] = ['˘', 'ˇ', 'ˆ', '˙', '˝', '˛', '˚', '˜'];+ match c {+ 0x18..=0x1F => LOW[(c - 0x18) as usize],+ 0x80..=0xA0 => HIGH[(c - 0x80) as usize],+ _ => c as char,+ }+}++/// A name object (without the leading `/`, with `#xx` escapes already decoded).+pub type Name = Vec<u8>;++/// An ordered dictionary.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Dict {+ entries: Vec<(Name, Object)>,+}++impl Dict {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn get(&self, key: &[u8]) -> Option<&Object> {+ self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v)+ }++ pub fn get_mut(&mut self, key: &[u8]) -> Option<&mut Object> {+ self.entries.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v)+ }++ /// Insert or replace, keeping the position of an existing key.+ pub fn set(&mut self, key: impl Into<Name>, value: impl Into<Object>) {+ let key = key.into();+ let value = value.into();+ match self.entries.iter_mut().find(|(k, _)| *k == key) {+ Some((_, v)) => *v = value,+ None => self.entries.push((key, value)),+ }+ }++ pub fn remove(&mut self, key: &[u8]) -> Option<Object> {+ let i = self.entries.iter().position(|(k, _)| k == key)?;+ Some(self.entries.remove(i).1)+ }++ pub fn contains(&self, key: &[u8]) -> bool {+ self.get(key).is_some()+ }++ pub fn iter(&self) -> impl Iterator<Item = (&Name, &Object)> {+ self.entries.iter().map(|(k, v)| (k, v))+ }++ pub fn len(&self) -> usize {+ self.entries.len()+ }++ pub fn is_empty(&self) -> bool {+ self.entries.is_empty()+ }++ pub fn name(&self, key: &[u8]) -> Option<&[u8]> {+ self.get(key).and_then(Object::as_name)+ }++ pub fn int(&self, key: &[u8]) -> Option<i64> {+ self.get(key).and_then(Object::as_int)+ }++ pub fn reference(&self, key: &[u8]) -> Option<ObjRef> {+ self.get(key).and_then(Object::as_ref)+ }+}++impl FromIterator<(Name, Object)> for Dict {+ fn from_iter<T: IntoIterator<Item = (Name, Object)>>(iter: T) -> Self {+ let mut d = Dict::new();+ for (k, v) in iter {+ d.set(k, v);+ }+ d+ }+}++/// A stream: dictionary plus its data *as stored* (still filtered).+#[derive(Clone, Debug, PartialEq)]+pub struct Stream {+ pub dict: Dict,+ pub raw: Arc<Vec<u8>>,+}++/// Upper bound for a single decoded stream (decompression-bomb defence).+pub const MAX_DECODED: usize = 1 << 30;++impl Stream {+ /// A new stream from already-encoded bytes (`/Length` is set at write time).+ pub fn from_raw(dict: Dict, raw: Vec<u8>) -> Self {+ Self { dict, raw: Arc::new(raw) }+ }++ /// A new stream holding `data` compressed with Flate.+ pub fn flate(mut dict: Dict, data: &[u8]) -> Self {+ dict.set(b"Filter".to_vec(), Object::Name(b"FlateDecode".to_vec()));+ dict.remove(b"DecodeParms");+ Self { dict, raw: Arc::new(printcraft_filters::encode_flate(data)) }+ }++ /// The filter chain declared in the dictionary.+ pub fn filters(&self) -> Vec<(Filter, Params)> {+ let names: Vec<&[u8]> = match self.dict.get(b"Filter") {+ Some(Object::Name(n)) => vec![n],+ Some(Object::Array(a)) => a.iter().filter_map(Object::as_name).collect(),+ _ => Vec::new(),+ };+ let parms: Vec<Option<&Dict>> = match self.dict.get(b"DecodeParms") {+ Some(Object::Dict(d)) => vec![Some(d)],+ Some(Object::Array(a)) => a.iter().map(Object::as_dict).collect(),+ _ => Vec::new(),+ };+ names+ .into_iter()+ .enumerate()+ .map(|(i, n)| {+ let p = parms.get(i).copied().flatten();+ let get = |k: &[u8], d: i64| p.and_then(|p| p.int(k)).unwrap_or(d);+ let params = Params {+ predictor: get(b"Predictor", 1),+ colors: get(b"Colors", 1),+ bits_per_component: get(b"BitsPerComponent", 8),+ columns: get(b"Columns", 1),+ early_change: get(b"EarlyChange", 1),+ };+ (Filter::from_name(n), params)+ })+ .collect()+ }++ /// Decoded data, tolerating truncated or corrupt encodings the way viewers do (the data+ /// decoded before the damage is returned). Streams with image codecs fail with+ /// `CosError::Filter` (keep them encoded). Use `decoded_strict` to detect damage.+ pub fn decoded(&self) -> Result<Vec<u8>, CosError> {+ let chain = self.filters();+ if chain.is_empty() {+ return Ok(self.raw.as_ref().clone());+ }+ printcraft_filters::decode_tolerant(&chain, &self.raw, MAX_DECODED).map(|(v, _)| v).map_err(|e| CosError::Filter(e.to_string()))+ }++ /// Decoded data; any corruption is an error.+ pub fn decoded_strict(&self) -> Result<Vec<u8>, CosError> {+ let chain = self.filters();+ if chain.is_empty() {+ return Ok(self.raw.as_ref().clone());+ }+ printcraft_filters::decode(&chain, &self.raw, MAX_DECODED).map_err(|e| CosError::Filter(e.to_string()))+ }+}++#[derive(Clone, Debug, PartialEq)]+pub enum Object {+ Null,+ Bool(bool),+ Int(i64),+ Real(f64),+ String(PdfString),+ Name(Name),+ Array(Vec<Object>),+ Dict(Dict),+ Stream(Stream),+ Ref(ObjRef),+}++impl Object {+ pub fn name(n: &str) -> Self {+ Object::Name(n.as_bytes().to_vec())+ }++ pub fn as_int(&self) -> Option<i64> {+ match self {+ Object::Int(i) => Some(*i),+ Object::Real(r) if r.fract() == 0.0 && r.is_finite() => Some(*r as i64),+ _ => None,+ }+ }++ pub fn as_f64(&self) -> Option<f64> {+ match self {+ Object::Int(i) => Some(*i as f64),+ Object::Real(r) => Some(*r),+ _ => None,+ }+ }++ pub fn as_name(&self) -> Option<&[u8]> {+ match self {+ Object::Name(n) => Some(n),+ _ => None,+ }+ }++ pub fn as_ref(&self) -> Option<ObjRef> {+ match self {+ Object::Ref(r) => Some(*r),+ _ => None,+ }+ }++ pub fn as_dict(&self) -> Option<&Dict> {+ match self {+ Object::Dict(d) => Some(d),+ Object::Stream(s) => Some(&s.dict),+ _ => None,+ }+ }++ pub fn as_dict_mut(&mut self) -> Option<&mut Dict> {+ match self {+ Object::Dict(d) => Some(d),+ Object::Stream(s) => Some(&mut s.dict),+ _ => None,+ }+ }++ pub fn as_array(&self) -> Option<&Vec<Object>> {+ match self {+ Object::Array(a) => Some(a),+ _ => None,+ }+ }++ pub fn as_string(&self) -> Option<&PdfString> {+ match self {+ Object::String(s) => Some(s),+ _ => None,+ }+ }+}++impl From<i64> for Object {+ fn from(v: i64) -> Self {+ Object::Int(v)+ }+}+impl From<i32> for Object {+ fn from(v: i32) -> Self {+ Object::Int(v as i64)+ }+}+impl From<f64> for Object {+ fn from(v: f64) -> Self {+ Object::Real(v)+ }+}+impl From<bool> for Object {+ fn from(v: bool) -> Self {+ Object::Bool(v)+ }+}+impl From<ObjRef> for Object {+ fn from(v: ObjRef) -> Self {+ Object::Ref(v)+ }+}+impl From<Dict> for Object {+ fn from(v: Dict) -> Self {+ Object::Dict(v)+ }+}+impl From<Vec<Object>> for Object {+ fn from(v: Vec<Object>) -> Self {+ Object::Array(v)+ }+}+impl From<PdfString> for Object {+ fn from(v: PdfString) -> Self {+ Object::String(v)+ }+}+impl From<Stream> for Object {+ fn from(v: Stream) -> Self {+ Object::Stream(v)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn text_strings_round_trip() {+ for s in ["Plain ASCII", "Café — naïve", "日本語", "emoji 📄"] {+ assert_eq!(PdfString::text(s).to_text(), s);+ }+ assert!(!PdfString::text("abc").bytes.starts_with(&[0xFE, 0xFF]));+ }++ #[test]+ fn pdfdoc_encoding_high_range() {+ assert_eq!(PdfString::literal(vec![0x84, 0x92, 0xA0, b'A']).to_text(), "—™€A");+ }++ #[test]+ fn dict_preserves_order_and_replaces_in_place() {+ let mut d = Dict::new();+ d.set(b"B".to_vec(), 1);+ d.set(b"A".to_vec(), 2);+ d.set(b"B".to_vec(), 3);+ let keys: Vec<_> = d.iter().map(|(k, _)| k.clone()).collect();+ assert_eq!(keys, vec![b"B".to_vec(), b"A".to_vec()]);+ assert_eq!(d.int(b"B"), Some(3));+ }+}diff --git a/crates/cos/src/parser.rs b/crates/cos/src/parser.rsnew file mode 100644index 000000000..807471312--- /dev/null+++ b/crates/cos/src/parser.rs@@ -0,0 +1,514 @@+//! Lexer and object parser (ISO 32000-2 §7.2–7.3), tolerant of common real-world damage.+//!+//! The parser works on a byte slice and a position; it never allocates for skipped data and+//! never panics on malformed input (every index is bounds-checked). Depth is limited to defend+//! against pathological nesting.++use crate::CosError;+use crate::object::{Dict, ObjRef, Object, PdfString, Stream};++const MAX_DEPTH: usize = 128;++pub(crate) fn is_whitespace(b: u8) -> bool {+ matches!(b, b'\0' | b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')+}++pub(crate) fn is_delimiter(b: u8) -> bool {+ matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%')+}++fn is_regular(b: u8) -> bool {+ !is_whitespace(b) && !is_delimiter(b)+}++/// A cursor over PDF bytes.+pub struct Lexer<'a> {+ pub data: &'a [u8],+ pub pos: usize,+}++impl<'a> Lexer<'a> {+ pub fn new(data: &'a [u8], pos: usize) -> Self {+ Self { data, pos: pos.min(data.len()) }+ }++ fn peek(&self) -> Option<u8> {+ self.data.get(self.pos).copied()+ }++ /// Skip whitespace and comments.+ pub fn skip_ws(&mut self) {+ while let Some(b) = self.peek() {+ if is_whitespace(b) {+ self.pos += 1;+ } else if b == b'%' {+ while let Some(c) = self.peek() {+ if c == b'\n' || c == b'\r' {+ break;+ }+ self.pos += 1;+ }+ } else {+ break;+ }+ }+ }++ /// Read a run of regular characters (a keyword or number).+ pub fn token(&mut self) -> &'a [u8] {+ let start = self.pos.min(self.data.len());+ while self.peek().is_some_and(is_regular) {+ self.pos += 1;+ }+ &self.data[start..self.pos]+ }++ /// `true` (and consumes it) if the next token is exactly `kw`.+ pub fn eat_keyword(&mut self, kw: &[u8]) -> bool {+ self.skip_ws();+ let end = self.pos + kw.len();+ if self.data.get(self.pos..end) == Some(kw) && self.data.get(end).is_none_or(|b| !is_regular(*b)) {+ self.pos = end;+ true+ } else {+ false+ }+ }++ fn err(&self, what: &str) -> CosError {+ CosError::Syntax { offset: self.pos, detail: what.to_string() }+ }++ /// Parse one direct object. References `N G R` are recognised.+ pub fn object(&mut self) -> Result<Object, CosError> {+ self.object_depth(0)+ }++ fn object_depth(&mut self, depth: usize) -> Result<Object, CosError> {+ if depth > MAX_DEPTH {+ return Err(self.err("nesting too deep"));+ }+ self.skip_ws();+ let Some(b) = self.peek() else { return Err(self.err("unexpected end of data")) };+ match b {+ b'/' => {+ self.pos += 1;+ Ok(Object::Name(self.name_body()))+ }+ b'(' => {+ self.pos += 1;+ Ok(Object::String(PdfString { bytes: self.literal_string()?, hex: false }))+ }+ b'<' if self.data.get(self.pos + 1) == Some(&b'<') => {+ self.pos += 2;+ Ok(Object::Dict(self.dict_body(depth)?))+ }+ b'<' => {+ self.pos += 1;+ Ok(Object::String(PdfString { bytes: self.hex_string()?, hex: true }))+ }+ b'[' => {+ self.pos += 1;+ let mut items = Vec::new();+ loop {+ self.skip_ws();+ match self.peek() {+ None => return Err(self.err("unterminated array")),+ Some(b']') => {+ self.pos += 1;+ break;+ }+ _ => {+ let before = self.pos;+ match self.object_depth(depth + 1) {+ Ok(o) => items.push(o),+ // Tolerate junk inside arrays by skipping one byte.+ Err(_) if self.pos == before => self.pos += 1,+ Err(e) => return Err(e),+ }+ }+ }+ }+ Ok(Object::Array(items))+ }+ b'+' | b'-' | b'.' | b'0'..=b'9' => self.number_or_ref(),+ _ => {+ let start = self.pos;+ let tok = self.token();+ match tok {+ b"true" => Ok(Object::Bool(true)),+ b"false" => Ok(Object::Bool(false)),+ b"null" => Ok(Object::Null),+ b"" => {+ self.pos = start + 1;+ Err(CosError::Syntax { offset: start, detail: format!("unexpected byte 0x{b:02x}") })+ }+ other => Err(CosError::Syntax { offset: start, detail: format!("unexpected keyword {:?}", String::from_utf8_lossy(other)) }),+ }+ }+ }+ }++ fn name_body(&mut self) -> Vec<u8> {+ let mut out = Vec::new();+ while let Some(b) = self.peek() {+ if !is_regular(b) {+ break;+ }+ self.pos += 1;+ if b == b'#'+ && let (Some(h), Some(l)) = (self.data.get(self.pos).and_then(|c| hexval(*c)), self.data.get(self.pos + 1).and_then(|c| hexval(*c)))+ {+ out.push(h << 4 | l);+ self.pos += 2;+ continue;+ }+ out.push(b);+ }+ out+ }++ fn literal_string(&mut self) -> Result<Vec<u8>, CosError> {+ let mut out = Vec::new();+ let mut depth = 1usize;+ while let Some(b) = self.peek() {+ self.pos += 1;+ match b {+ b'(' => {+ depth += 1;+ out.push(b);+ }+ b')' => {+ depth -= 1;+ if depth == 0 {+ return Ok(out);+ }+ out.push(b);+ }+ b'\\' => {+ let Some(e) = self.peek() else { break };+ self.pos += 1;+ match e {+ b'n' => out.push(b'\n'),+ b'r' => out.push(b'\r'),+ b't' => out.push(b'\t'),+ b'b' => out.push(8),+ b'f' => out.push(12),+ b'(' | b')' | b'\\' => out.push(e),+ b'\r' => {+ if self.peek() == Some(b'\n') {+ self.pos += 1;+ }+ }+ b'\n' => {}+ b'0'..=b'7' => {+ let mut v = (e - b'0') as u32;+ for _ in 0..2 {+ match self.peek() {+ Some(d @ b'0'..=b'7') => {+ v = v * 8 + (d - b'0') as u32;+ self.pos += 1;+ }+ _ => break,+ }+ }+ out.push((v & 0xFF) as u8);+ }+ other => out.push(other),+ }+ }+ // End-of-line markers inside strings are normalised to \n (§7.3.4.2).+ b'\r' => {+ if self.peek() == Some(b'\n') {+ self.pos += 1;+ }+ out.push(b'\n');+ }+ other => out.push(other),+ }+ }+ Err(self.err("unterminated string"))+ }++ fn hex_string(&mut self) -> Result<Vec<u8>, CosError> {+ let mut out = Vec::new();+ let mut hi: Option<u8> = None;+ while let Some(b) = self.peek() {+ self.pos += 1;+ if b == b'>' {+ if let Some(h) = hi {+ out.push(h << 4);+ }+ return Ok(out);+ }+ if is_whitespace(b) {+ continue;+ }+ let Some(v) = hexval(b) else { return Err(self.err("invalid hex digit")) };+ match hi.take() {+ None => hi = Some(v),+ Some(h) => out.push(h << 4 | v),+ }+ }+ Err(self.err("unterminated hex string"))+ }++ fn dict_body(&mut self, depth: usize) -> Result<Dict, CosError> {+ let mut d = Dict::new();+ loop {+ self.skip_ws();+ match self.peek() {+ None => return Err(self.err("unterminated dictionary")),+ Some(b'>') if self.data.get(self.pos + 1) == Some(&b'>') => {+ self.pos += 2;+ return Ok(d);+ }+ Some(b'/') => {+ self.pos += 1;+ let key = self.name_body();+ self.skip_ws();+ // A key directly followed by `>>` has no value: treat as null. (A following+ // `/` is a name *value*, so it cannot signal a missing value.)+ if self.peek() == Some(b'>') && self.data.get(self.pos + 1) == Some(&b'>') {+ d.set(key, Object::Null);+ continue;+ }+ let value = self.object_depth(depth + 1)?;+ d.set(key, value);+ }+ Some(_) => {+ // Tolerate garbage between entries (seen in damaged files): skip a token.+ let before = self.pos;+ let _ = self.object_depth(depth + 1);+ if self.pos == before {+ self.pos += 1;+ }+ }+ }+ }+ }++ fn number_or_ref(&mut self) -> Result<Object, CosError> {+ let start = self.pos;+ let first = self.number()?;+ // Look ahead for "G R" to form a reference.+ if let Object::Int(n) = first+ && n >= 0+ {+ let save = self.pos;+ self.skip_ws();+ if self.peek().is_some_and(|b| b.is_ascii_digit()) {+ let gstart = self.pos;+ let g = self.token();+ if g.iter().all(u8::is_ascii_digit) && self.eat_keyword(b"R") {+ let generation = std::str::from_utf8(g).ok().and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);+ if n <= u32::MAX as i64 {+ return Ok(Object::Ref(ObjRef::new(n as u32, generation.min(u16::MAX as u32) as u16)));+ }+ }+ let _ = gstart;+ }+ self.pos = save;+ }+ let _ = start;+ Ok(first)+ }++ fn number(&mut self) -> Result<Object, CosError> {+ let start = self.pos;+ let tok = self.token();+ let s = std::str::from_utf8(tok).map_err(|_| self.err("bad number"))?;+ if s.contains('.') {+ // Tolerate forms like "--5", "5-" or "1.2.3" by parsing the longest valid prefix.+ let cleaned: String = s.trim_start_matches('+').replacen("--", "-", 1);+ let mut end = cleaned.len();+ while end > 0 {+ if let Ok(v) = cleaned[..end].parse::<f64>() {+ return Ok(Object::Real(v));+ }+ end -= 1;+ }+ return Ok(Object::Real(0.0));+ }+ match s.trim_start_matches('+').parse::<i64>() {+ Ok(v) => Ok(Object::Int(v)),+ Err(_) => {+ // Out-of-range integers are treated as reals (§7.3.3 allows implementation limits).+ s.parse::<f64>().map(Object::Real).map_err(|_| CosError::Syntax { offset: start, detail: format!("bad number {s:?}") })+ }+ }+ }+}++fn hexval(b: u8) -> Option<u8> {+ match b {+ b'0'..=b'9' => Some(b - b'0'),+ b'a'..=b'f' => Some(b - b'a' + 10),+ b'A'..=b'F' => Some(b - b'A' + 10),+ _ => None,+ }+}++/// Parse an indirect object at `offset`: `N G obj <object> [stream…endstream] endobj`.+/// `resolve_length` resolves an indirect `/Length`. Returns the object and its (num, gen).+pub fn parse_indirect(data: &[u8], offset: usize, resolve_length: &dyn Fn(ObjRef) -> Option<i64>) -> Result<(ObjRef, Object), CosError> {+ let mut lx = Lexer::new(data, offset);+ lx.skip_ws();+ let num_tok = lx.token();+ lx.skip_ws();+ let gen_tok = lx.token();+ let parse_u = |t: &[u8]| std::str::from_utf8(t).ok().and_then(|s| s.parse::<u64>().ok());+ let (Some(num), Some(generation)) = (parse_u(num_tok), parse_u(gen_tok)) else {+ return Err(CosError::Syntax { offset, detail: "expected object header".into() });+ };+ if !lx.eat_keyword(b"obj") {+ return Err(CosError::Syntax { offset: lx.pos, detail: "expected 'obj'".into() });+ }+ let id = ObjRef::new(num.min(u32::MAX as u64) as u32, generation.min(u16::MAX as u64) as u16);+ let obj = match lx.object() {+ Ok(o) => o,+ // "N G obj endobj" (empty) is treated as null.+ Err(_) if lx.eat_keyword(b"endobj") => return Ok((id, Object::Null)),+ Err(e) => return Err(e),+ };+ lx.skip_ws();+ if let Object::Dict(dict) = &obj+ && lx.eat_keyword(b"stream")+ {+ // The keyword is followed by CRLF or LF (a lone CR is tolerated).+ match (data.get(lx.pos), data.get(lx.pos + 1)) {+ (Some(b'\r'), Some(b'\n')) => lx.pos += 2,+ (Some(b'\n'), _) | (Some(b'\r'), _) => lx.pos += 1,+ _ => {}+ }+ let start = lx.pos;+ let declared = match dict.get(b"Length") {+ Some(Object::Int(n)) => Some(*n),+ Some(Object::Ref(r)) => resolve_length(*r),+ _ => None,+ };+ let valid = |len: i64| -> bool {+ if len < 0 {+ return false;+ }+ let end = start.saturating_add(len as usize);+ if end > data.len() {+ return false;+ }+ let mut after = Lexer::new(data, end);+ after.eat_keyword(b"endstream")+ };+ let len = match declared {+ Some(l) if valid(l) => l as usize,+ // Wrong or missing /Length: search for "endstream" (§7.3.8.1 recovery).+ _ => find_endstream(data, start).ok_or_else(|| CosError::Syntax { offset: start, detail: "stream without endstream".into() })? - start,+ };+ let raw = data[start..start + len].to_vec();+ let mut dict = dict.clone();+ dict.set(b"Length".to_vec(), Object::Int(raw.len() as i64));+ return Ok((id, Object::Stream(Stream::from_raw(dict, raw))));+ }+ Ok((id, obj))+}++/// Offset where stream data ends (before the EOL preceding "endstream").+fn find_endstream(data: &[u8], from: usize) -> Option<usize> {+ let hay = data.get(from..)?;+ let at = hay.windows(9).position(|w| w == b"endstream")? + from;+ let mut end = at;+ if end > from && data[end - 1] == b'\n' {+ end -= 1;+ }+ if end > from && data[end - 1] == b'\r' {+ end -= 1;+ }+ Some(end)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn obj(s: &str) -> Object {+ Lexer::new(s.as_bytes(), 0).object().unwrap_or_else(|e| panic!("{s}: {e}"))+ }++ #[test]+ fn scalars() {+ assert_eq!(obj("true"), Object::Bool(true));+ assert_eq!(obj("null"), Object::Null);+ assert_eq!(obj(" -17 "), Object::Int(-17));+ assert_eq!(obj("+42"), Object::Int(42));+ assert_eq!(obj("-.5"), Object::Real(-0.5));+ assert_eq!(obj("4."), Object::Real(4.0));+ assert_eq!(obj("99999999999999999999"), Object::Real(1e20));+ assert_eq!(obj("12 0 R"), Object::Ref(ObjRef::new(12, 0)));+ assert_eq!(obj("12 0 obj").as_int(), Some(12), "12 followed by 0 obj is not a reference");+ }++ #[test]+ fn names_decode_hex_escapes() {+ assert_eq!(obj("/A#20B"), Object::Name(b"A B".to_vec()));+ assert_eq!(obj("/Adobe#"), Object::Name(b"Adobe#".to_vec()));+ assert_eq!(obj("/"), Object::Name(Vec::new()));+ }++ #[test]+ fn literal_strings() {+ let s = |x: &str| obj(x).as_string().expect("string").bytes.clone();+ assert_eq!(s("(a (nested) b)"), b"a (nested) b");+ assert_eq!(s(r"(\n\t\\\(\))"), b"\n\t\\()");+ assert_eq!(s(r"(\101\1011)"), b"AA1");+ assert_eq!(s("(line\\\ncontinued)"), b"linecontinued");+ assert_eq!(s("(cr\r\nlf)"), b"cr\nlf");+ }++ #[test]+ fn hex_strings() {+ let s = obj("<48 65 6C6c6f7>");+ assert_eq!(s.as_string().unwrap().bytes, b"Hellop");+ assert!(s.as_string().unwrap().hex);+ }++ #[test]+ fn arrays_and_dicts() {+ let o = obj("<< /Type /Page /Kids [1 0 R 2 0 R] /Box [0 0 612.5 792] /Nested << /A true >> /Empty >>");+ let d = o.as_dict().unwrap();+ assert_eq!(d.name(b"Type"), Some(&b"Page"[..]));+ assert_eq!(d.get(b"Kids").unwrap().as_array().unwrap().len(), 2);+ assert_eq!(d.get(b"Box").unwrap().as_array().unwrap()[2], Object::Real(612.5));+ assert_eq!(d.get(b"Empty"), Some(&Object::Null));+ }++ #[test]+ fn comments_are_whitespace() {+ assert_eq!(obj("% hello\n [1 % two\n 3]"), Object::Array(vec![Object::Int(1), Object::Int(3)]));+ }++ #[test]+ fn indirect_stream_with_wrong_length_recovers() {+ let data = b"7 0 obj\n<< /Length 999 >>\nstream\nHELLO\nendstream\nendobj\n";+ let (id, o) = parse_indirect(data, 0, &|_| None).unwrap();+ assert_eq!(id, ObjRef::new(7, 0));+ let Object::Stream(s) = o else { panic!("stream expected") };+ assert_eq!(s.raw.as_slice(), b"HELLO");+ assert_eq!(s.dict.int(b"Length"), Some(5));+ }++ #[test]+ fn indirect_length_is_resolved() {+ let data = b"7 0 obj\n<< /Length 8 0 R >>\nstream\r\nAB\r\nendstream\nendobj\n";+ let (_, o) = parse_indirect(data, 0, &|r| (r.num == 8).then_some(2)).unwrap();+ let Object::Stream(s) = o else { panic!() };+ assert_eq!(s.raw.as_slice(), b"AB");+ }++ #[test]+ fn garbage_never_panics() {+ for input in ["<<", "[", "(", "<", "<< /A", "[1 2", ")", "]", ">>", "<<>>>", "1 0", "\0\0", "/A#", "<zz>", "((("] {+ let _ = Lexer::new(input.as_bytes(), 0).object();+ }+ let deep = "[".repeat(10_000);+ assert!(Lexer::new(deep.as_bytes(), 0).object().is_err());+ }+}diff --git a/crates/cos/src/writer.rs b/crates/cos/src/writer.rsnew file mode 100644index 000000000..aa2710597--- /dev/null+++ b/crates/cos/src/writer.rs@@ -0,0 +1,386 @@+//! Serialization and saving (ISO 32000-2 §7.5).+//!+//! * `write_incremental` appends the edited objects, a cross-reference section in the same style+//! as the file's last one (table or stream) and a trailer with `/Prev`. The original bytes are+//! never modified, which keeps digital signatures over earlier revisions valid.+//! * `write_full` writes only objects reachable from the trailer, renumbered densely, with a+//! classic cross-reference table — the "Save As" / garbage-collecting path.++use std::collections::{BTreeMap, HashMap, VecDeque};+use std::io::Write;++use crate::CosError;+use crate::document::Document;+use crate::object::{Dict, ObjRef, Object, PdfString, Stream};++/// Serialize one object. Deterministic: same object → same bytes.+pub fn serialize(o: &Object, out: &mut Vec<u8>) {+ match o {+ Object::Null => out.extend_from_slice(b"null"),+ Object::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),+ Object::Int(i) => {+ let _ = write!(out, "{i}");+ }+ Object::Real(r) => write_real(*r, out),+ Object::String(s) => write_string(s, out),+ Object::Name(n) => write_name(n, out),+ Object::Array(a) => {+ out.push(b'[');+ for (i, x) in a.iter().enumerate() {+ if i > 0 {+ out.push(b' ');+ }+ serialize(x, out);+ }+ out.push(b']');+ }+ Object::Dict(d) => write_dict(d, out),+ Object::Stream(s) => write_stream(s, out),+ Object::Ref(r) => {+ let _ = write!(out, "{} {} R", r.num, r.generation);+ }+ }+}++fn write_real(r: f64, out: &mut Vec<u8>) {+ if !r.is_finite() {+ out.push(b'0');+ return;+ }+ if r.fract() == 0.0 && r.abs() < 1e15 {+ let _ = write!(out, "{}", r as i64);+ return;+ }+ // Plain decimal notation (no exponents, §7.3.3), trimmed.+ let s = format!("{r:.6}");+ let s = s.trim_end_matches('0').trim_end_matches('.');+ out.extend_from_slice(if s == "-0" { b"0" } else { s.as_bytes() });+}++fn write_name(n: &[u8], out: &mut Vec<u8>) {+ out.push(b'/');+ for &b in n {+ let regular = (b'!'..=b'~').contains(&b) && !matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%' | b'#');+ if regular {+ out.push(b);+ } else {+ let _ = write!(out, "#{b:02X}");+ }+ }+}++fn write_string(s: &PdfString, out: &mut Vec<u8>) {+ let binary = s.bytes.iter().filter(|b| !(b' '..=b'~').contains(*b) && !matches!(b, b'\n' | b'\r' | b'\t')).count();+ if s.hex || binary * 4 > s.bytes.len().max(1) {+ out.push(b'<');+ for b in &s.bytes {+ let _ = write!(out, "{b:02X}");+ }+ out.push(b'>');+ return;+ }+ out.push(b'(');+ for &b in &s.bytes {+ match b {+ b'(' | b')' | b'\\' => {+ out.push(b'\\');+ out.push(b);+ }+ b'\n' => out.extend_from_slice(b"\\n"),+ b'\r' => out.extend_from_slice(b"\\r"),+ b'\t' => out.extend_from_slice(b"\\t"),+ 0x08 => out.extend_from_slice(b"\\b"),+ 0x0C => out.extend_from_slice(b"\\f"),+ b' '..=b'~' => out.push(b),+ _ => {+ let _ = write!(out, "\\{b:03o}");+ }+ }+ }+ out.push(b')');+}++fn write_dict(d: &Dict, out: &mut Vec<u8>) {+ out.extend_from_slice(b"<<");+ for (k, v) in d.iter() {+ write_name(k, out);+ out.push(b' ');+ serialize(v, out);+ }+ out.extend_from_slice(b">>");+}++fn write_stream(s: &Stream, out: &mut Vec<u8>) {+ let mut d = s.dict.clone();+ d.set(b"Length".to_vec(), Object::Int(s.raw.len() as i64));+ write_dict(&d, out);+ out.extend_from_slice(b"\nstream\n");+ out.extend_from_slice(&s.raw);+ out.extend_from_slice(b"\nendstream");+}++fn write_indirect(num: u32, generation: u16, o: &Object, out: &mut Vec<u8>) {+ let _ = writeln!(out, "{num} {generation} obj");+ serialize(o, out);+ out.extend_from_slice(b"\nendobj\n");+}++/// Options for saving.+#[derive(Clone, Debug)]+pub struct SaveOptions {+ /// Replace or add `/Info /ModDate` with this PDF date string (e.g. from `pdf_date`).+ pub mod_date: Option<String>,+ /// Seed for a new file identifier when the document has none (deterministic in tests).+ pub id_seed: u64,+}++impl Default for SaveOptions {+ fn default() -> Self {+ Self { mod_date: None, id_seed: 0x5052_494E_5443_5241 }+ }+}++/// Append the document's edits to its original bytes (incremental update, §7.5.6).+///+/// A document that had to be reconstructed (no usable cross-reference chain) cannot be updated+/// incrementally — other readers would follow the broken chain — so it is rewritten in full,+/// which also repairs the file (what users expect after "the file was damaged and repaired").+pub fn write_incremental(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosError> {+ if doc.revisions().is_empty() {+ return write_full(doc, opts);+ }+ let mut doc = doc.clone();+ stamp_mod_date(&mut doc, opts);+ let original = doc.bytes().clone();+ let mut out = Vec::with_capacity(original.len() + 4096);+ out.extend_from_slice(&original);+ if !matches!(out.last(), Some(b'\n' | b'\r')) {+ out.push(b'\n');+ }+ let mut offsets: BTreeMap<u32, (u64, u16, bool)> = BTreeMap::new(); // num → (offset, gen, in use)+ for (num, generation, obj) in doc.overlay_entries().collect::<Vec<_>>() {+ match obj {+ Some(o) => {+ offsets.insert(num, (out.len() as u64, generation, true));+ write_indirect(num, generation, &o, &mut out);+ }+ None => {+ offsets.insert(num, (0, generation, false));+ }+ }+ }+ let prev = doc.revisions().last().map(|r| r.xref_offset);+ let as_stream = doc.revisions().last().is_some_and(|r| r.is_stream);+ let mut trailer = doc.trailer().clone();+ ensure_id(&mut trailer, opts, &original);+ if let Some(p) = prev {+ trailer.set(b"Prev".to_vec(), Object::Int(p as i64));+ }+ let size = doc.next_num().max(trailer.int(b"Size").unwrap_or(0) as u32);+ if as_stream {+ write_xref_stream(&mut out, &mut trailer, &offsets, size, &[])?;+ } else {+ trailer.set(b"Size".to_vec(), Object::Int(size as i64));+ let xref_at = out.len();+ write_xref_table(&mut out, &offsets, prev.is_none());+ out.extend_from_slice(b"trailer\n");+ write_dict(&trailer, &mut out);+ let _ = write!(out, "\nstartxref\n{xref_at}\n%%EOF\n");+ }+ Ok(out)+}++/// Write only reachable objects, renumbered from 1, with a classic cross-reference table.+pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosError> {+ let mut doc = doc.clone();+ stamp_mod_date(&mut doc, opts);+ let trailer_in = doc.trailer().clone();+ // Breadth-first walk from the trailer, assigning new numbers in visit order.+ let mut map: HashMap<ObjRef, u32> = HashMap::new();+ let mut order: Vec<ObjRef> = Vec::new();+ let mut queue: VecDeque<ObjRef> = VecDeque::new();+ let visit_refs = |o: &Object, queue: &mut VecDeque<ObjRef>| collect_refs(o, &mut |r| queue.push_back(r));+ for key in [&b"Root"[..], b"Info"] {+ if let Some(r) = trailer_in.reference(key) {+ queue.push_back(r);+ }+ }+ while let Some(r) = queue.pop_front() {+ if map.contains_key(&r) {+ continue;+ }+ let o = doc.get(r);+ if matches!(*o, Object::Null) {+ continue; // dangling reference: written as null by renumbering below+ }+ map.insert(r, (order.len() + 1) as u32);+ order.push(r);+ visit_refs(&o, &mut queue);+ }+ let mut out = Vec::new();+ let _ = writeln!(out, "%PDF-{}\n%\u{e2}\u{e3}\u{cf}\u{d3}", doc.version().chars().take(3).collect::<String>());+ // The binary comment must be raw high bytes, not UTF-8.+ out.truncate(out.len() - "\u{e2}\u{e3}\u{cf}\u{d3}\n".len());+ out.extend_from_slice(&[0xE2, 0xE3, 0xCF, 0xD3, b'\n']);+ let mut offsets: BTreeMap<u32, (u64, u16, bool)> = BTreeMap::new();+ for (i, r) in order.iter().enumerate() {+ let num = (i + 1) as u32;+ let o = renumber(&doc.get(*r), &map);+ offsets.insert(num, (out.len() as u64, 0, true));+ write_indirect(num, 0, &o, &mut out);+ }+ let mut trailer = Dict::new();+ trailer.set(b"Size".to_vec(), Object::Int(order.len() as i64 + 1));+ for key in [&b"Root"[..], b"Info"] {+ if let Some(r) = trailer_in.reference(key).and_then(|r| map.get(&r)) {+ trailer.set(key.to_vec(), Object::Ref(ObjRef::new(*r, 0)));+ }+ }+ if let Some(id) = trailer_in.get(b"ID") {+ trailer.set(b"ID".to_vec(), id.clone());+ }+ ensure_id(&mut trailer, opts, doc.bytes());+ let xref_at = out.len();+ write_xref_table(&mut out, &offsets, true);+ out.extend_from_slice(b"trailer\n");+ write_dict(&trailer, &mut out);+ let _ = write!(out, "\nstartxref\n{xref_at}\n%%EOF\n");+ Ok(out)+}++fn collect_refs(o: &Object, f: &mut impl FnMut(ObjRef)) {+ match o {+ Object::Ref(r) => f(*r),+ Object::Array(a) => a.iter().for_each(|x| collect_refs(x, f)),+ Object::Dict(d) => d.iter().for_each(|(_, v)| collect_refs(v, f)),+ Object::Stream(s) => s.dict.iter().for_each(|(_, v)| collect_refs(v, f)),+ _ => {}+ }+}++fn renumber(o: &Object, map: &HashMap<ObjRef, u32>) -> Object {+ match o {+ Object::Ref(r) => map.get(r).map(|n| Object::Ref(ObjRef::new(*n, 0))).unwrap_or(Object::Null),+ Object::Array(a) => Object::Array(a.iter().map(|x| renumber(x, map)).collect()),+ Object::Dict(d) => Object::Dict(d.iter().map(|(k, v)| (k.clone(), renumber(v, map))).collect()),+ Object::Stream(s) => Object::Stream(Stream { dict: s.dict.iter().map(|(k, v)| (k.clone(), renumber(v, map))).collect(), raw: s.raw.clone() }),+ other => other.clone(),+ }+}++/// Classic xref table with one subsection per run of consecutive numbers (§7.5.4).+fn write_xref_table(out: &mut Vec<u8>, offsets: &BTreeMap<u32, (u64, u16, bool)>, include_zero: bool) {+ out.extend_from_slice(b"xref\n");+ let mut all: Vec<(u32, (u64, u16, bool))> = offsets.iter().map(|(k, v)| (*k, *v)).collect();+ if include_zero {+ all.insert(0, (0, (0, 65535, false)));+ }+ let mut i = 0;+ while i < all.len() {+ let start = all[i].0;+ let mut j = i;+ while j + 1 < all.len() && all[j + 1].0 == all[j].0 + 1 {+ j += 1;+ }+ let _ = writeln!(out, "{} {}", start, j - i + 1);+ for (_, (off, generation, used)) in &all[i..=j] {+ let _ = writeln!(out, "{:010} {:05} {} ", off, generation, if *used { 'n' } else { 'f' });+ }+ i = j + 1;+ }+}++/// A cross-reference stream section (for files whose last section is a stream, §7.5.8).+fn write_xref_stream(+ out: &mut Vec<u8>,+ trailer: &mut Dict,+ offsets: &BTreeMap<u32, (u64, u16, bool)>,+ size: u32,+ _extra: &[u32],+) -> Result<(), CosError> {+ let xref_num = size;+ let xref_at = out.len() as u64;+ let mut rows: BTreeMap<u32, (u8, u64, u16)> =+ offsets.iter().map(|(n, (o, g, used))| (*n, if *used { (1, *o, *g) } else { (0, 0, *g) })).collect();+ rows.insert(xref_num, (1, xref_at, 0));+ let mut data = Vec::new();+ let mut index = Vec::new();+ let nums: Vec<u32> = rows.keys().copied().collect();+ let mut i = 0;+ while i < nums.len() {+ let mut j = i;+ while j + 1 < nums.len() && nums[j + 1] == nums[j] + 1 {+ j += 1;+ }+ index.push(Object::Int(nums[i] as i64));+ index.push(Object::Int((j - i + 1) as i64));+ i = j + 1;+ }+ for (t, a, b) in rows.values() {+ data.push(*t);+ data.extend_from_slice(&(*a as u32).to_be_bytes());+ data.extend_from_slice(&b.to_be_bytes());+ }+ let mut d = trailer.clone();+ d.set(b"Type".to_vec(), Object::name("XRef"));+ d.set(b"Size".to_vec(), Object::Int(xref_num as i64 + 1));+ d.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Int(4), Object::Int(2)]));+ d.set(b"Index".to_vec(), Object::Array(index));+ let stream = Stream::flate(d, &data);+ write_indirect(xref_num, 0, &Object::Stream(stream), out);+ let _ = write!(out, "startxref\n{xref_at}\n%%EOF\n");+ trailer.set(b"Size".to_vec(), Object::Int(xref_num as i64 + 1));+ Ok(())+}++fn stamp_mod_date(doc: &mut Document, opts: &SaveOptions) {+ let Some(date) = &opts.mod_date else { return };+ let date = Object::String(PdfString::literal(date.as_bytes().to_vec()));+ match doc.trailer().get(b"Info").cloned() {+ Some(Object::Ref(r)) => {+ let _ = doc.update_dict(r, |d| d.set(b"ModDate".to_vec(), date.clone()));+ }+ _ => {+ let mut info = Dict::new();+ info.set(b"ModDate".to_vec(), date);+ let r = doc.add(info);+ doc.trailer_mut().set(b"Info".to_vec(), Object::Ref(r));+ }+ }+}++/// Keep an existing `/ID`, or create one (two equal 16-byte strings, §14.4).+fn ensure_id(trailer: &mut Dict, opts: &SaveOptions, content: &[u8]) {+ if matches!(trailer.get(b"ID"), Some(Object::Array(a)) if a.len() == 2) {+ return;+ }+ // FNV-1a over a sample of the content and the seed: stable, dependency-free.+ let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ opts.id_seed;+ for b in content.iter().step_by((content.len() / 4096).max(1)).chain(content.iter().rev().take(64)) {+ h ^= *b as u64;+ h = h.wrapping_mul(0x0100_0000_01b3);+ }+ let mut id = Vec::with_capacity(16);+ id.extend_from_slice(&h.to_be_bytes());+ id.extend_from_slice(&h.rotate_left(29).wrapping_mul(0x9E37_79B9_7F4A_7C15).to_be_bytes());+ let s = Object::String(PdfString { bytes: id, hex: true });+ trailer.set(b"ID".to_vec(), Object::Array(vec![s.clone(), s]));+}++/// A PDF date string for "now" given seconds since the Unix epoch (UTC).+pub fn pdf_date(unix_secs: i64) -> String {+ let days = unix_secs.div_euclid(86_400);+ let secs = unix_secs.rem_euclid(86_400);+ // Civil-from-days (Howard Hinnant's algorithm).+ let z = days + 719_468;+ let era = z.div_euclid(146_097);+ let doe = z - era * 146_097;+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;+ let y = yoe + era * 400;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let d = doy - (153 * mp + 2) / 5 + 1;+ let m = if mp < 10 { mp + 3 } else { mp - 9 };+ let y = if m <= 2 { y + 1 } else { y };+ format!("D:{y:04}{m:02}{d:02}{:02}{:02}{:02}Z", secs / 3600, secs / 60 % 60, secs % 60)+}diff --git a/crates/cos/tests/corpus.rs b/crates/cos/tests/corpus.rsnew file mode 100644index 000000000..c2cbf1bcb--- /dev/null+++ b/crates/cos/tests/corpus.rs@@ -0,0 +1,101 @@+//! Corpus parity: every file hayro-syntax can open must also open with our reader, agree on the+//! page count, and survive an incremental save that touches the catalog (the appended revision+//! must be readable by both readers and leave the original bytes untouched).+//!+//! Runs over `corpus/pdfjs/test/pdfs` when present (`cargo xtask corpus` fetches it); otherwise+//! it is a no-op so CI without the corpus stays green. Run with `--ignored --nocapture`.++use std::sync::Arc;++use printcraft_cos::{Document, Object, SaveOptions, write_full, write_incremental};++/// Leaf pages reachable from the catalog (cycle-safe), like viewers count them.+fn page_count(doc: &Document) -> Option<usize> {+ let root = doc.get(doc.root()?);+ let mut stack = vec![root.as_dict()?.get(b"Pages")?.clone()];+ let (mut seen, mut n) = (std::collections::HashSet::new(), 0);+ while let Some(o) = stack.pop() {+ if let Object::Ref(r) = o+ && !seen.insert(r)+ {+ continue;+ }+ let node = doc.resolve(&o);+ let Some(d) = node.as_dict() else { continue };+ match d.get(b"Kids").map(|k| doc.resolve(k)) {+ Some(k) if d.name(b"Type") != Some(b"Page") => stack.extend(k.as_array().cloned().unwrap_or_default().into_iter().rev()),+ _ => n += 1,+ }+ }+ Some(n)+}++#[test]+#[ignore = "needs corpus/; run with --ignored"]+fn corpus_parity() {+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/pdfjs/test/pdfs");+ let Ok(entries) = std::fs::read_dir(&dir) else {+ eprintln!("corpus not present at {}", dir.display());+ return;+ };+ let mut files: Vec<_> = entries.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "pdf")).collect();+ files.sort();+ let (mut checked, mut encrypted, mut failures) = (0, 0, Vec::new());+ for path in &files {+ let bytes = Arc::new(std::fs::read(path).unwrap());+ let Ok(reference) = std::panic::catch_unwind(|| hayro_syntax::Pdf::new(bytes.clone())) else { continue };+ let Ok(reference) = reference else { continue }; // hayro can't open it either: not a parity case+ let name = path.file_name().unwrap().to_string_lossy().into_owned();+ if std::env::var("COS_ONLY").is_ok_and(|o| o != name) {+ continue;+ }+ if std::env::var_os("COS_TRACE").is_some() {+ eprintln!("{name}");+ }+ let expected = reference.pages().len();+ let result = std::panic::catch_unwind(|| -> Result<(), String> {+ let mut doc = match Document::open(bytes.clone()) {+ Ok(d) => d,+ Err(printcraft_cos::CosError::Encrypted) => return Err("encrypted".into()),+ Err(e) => return Err(format!("open: {e}")),+ };+ // hayro may repair a broken /Count; compare against the leaf walk count loosely.+ if page_count(&doc) != Some(expected) && expected > 0 {+ return Err(format!("page count {:?} vs hayro {expected}", page_count(&doc)));+ }+ let root = doc.root().ok_or("no root")?;+ doc.update_dict(root, |d| d.set(b"PrintCraftTest".to_vec(), Object::Bool(true))).map_err(|e| e.to_string())?;+ let saved = write_incremental(&doc, &SaveOptions::default()).map_err(|e| format!("save: {e}"))?;+ // Reconstructed files are rewritten in full; everything else must keep its bytes.+ if !doc.revisions().is_empty() && saved.get(..bytes.len()) != Some(&bytes[..]) {+ return Err("prefix modified".into());+ }+ let again = Document::open(Arc::new(saved.clone())).map_err(|e| format!("reopen: {e}"))?;+ let flag = again.get(again.root().ok_or("no root after save")?).as_dict().and_then(|d| d.get(b"PrintCraftTest").cloned());+ if flag != Some(Object::Bool(true)) {+ return Err("edit lost after reopen".into());+ }+ let hay = hayro_syntax::Pdf::new(Arc::new(saved)).map_err(|e| format!("hayro reopen: {e:?}"))?;+ if hay.pages().len() != expected {+ return Err(format!("hayro sees {} pages after save, expected {expected}", hay.pages().len()));+ }+ let full = write_full(&doc, &SaveOptions::default()).map_err(|e| format!("full: {e}"))?;+ let hay = hayro_syntax::Pdf::new(Arc::new(full)).map_err(|e| format!("hayro full: {e:?}"))?;+ if hay.pages().len() != expected {+ return Err(format!("hayro sees {} pages after full save, expected {expected}", hay.pages().len()));+ }+ Ok(())+ });+ match result {+ Ok(Ok(())) => checked += 1,+ Ok(Err(e)) if e == "encrypted" => encrypted += 1,+ Ok(Err(e)) => failures.push(format!("{name}: {e}")),+ Err(_) => failures.push(format!("{name}: PANIC")),+ }+ }+ eprintln!("cos corpus parity: {checked} ok, {encrypted} encrypted (skipped), {} failures", failures.len());+ for f in &failures {+ eprintln!(" {f}");+ }+ assert!(failures.iter().all(|f| !f.ends_with("PANIC")), "no panics");+}diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.tomlindex ebeff37d6..fe70e6980 100644--- a/crates/engine/Cargo.toml+++ b/crates/engine/Cargo.toml@@ -10,3 +10,6 @@ workspace = true[dependencies]printcraft-render = { workspace = true }+printcraft-cos = { workspace = true }+printcraft-organize = { workspace = true }+thiserror = { workspace = true }diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 2db3584fb..eaeef388e 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -1,32 +1,174 @@//! printcraft-engine — the façade every frontend talks to (architecture §4).//!-//! This first slice holds open documents and the tool catalogue. The command registry, history-//! and jobs arrive in M4; the types here are shaped so that the UI never touches rendering or-//! parsing crates directly.+//! Holds open documents, their edit history and the tool catalogue. Frontends never touch the+//! parsing, rendering or editing crates directly.+//!+//! **Editing model.** Each document keeps a `printcraft_cos::Document` (the object graph with a+//! copy-on-write overlay of edits). An edit runs on a clone, and on success the previous state is+//! pushed onto the undo stack (clones share all unchanged data, so this is cheap). After every+//! edit the *working file* is produced by an incremental write — original bytes plus one+//! appended revision — and the view is refreshed from it, so what you see is exactly what Save+//! will write. Saving rebases onto the written bytes, so the next save appends only new edits.pub mod catalog;use std::sync::Arc;-use printcraft_render::{DocInfo, OpenError, RenderPool, inspect};+use printcraft_cos::{SaveOptions, write_full, write_incremental};+use printcraft_render::{DocInfo, OpenError, RenderConfig, RenderPool, inspect};/// Stable identifier of an open document within a session.#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]pub struct DocId(pub u64);+/// Undo/redo depth. Snapshots share unchanged data, so this is memory-cheap.+const MAX_UNDO: usize = 100;++/// Editing state of a document (absent when the document cannot be edited yet, e.g. encrypted).+#[derive(Clone)]+struct Editor {+ cos: printcraft_cos::Document,+ undo: Vec<(String, printcraft_cos::Document)>,+ redo: Vec<(String, printcraft_cos::Document)>,+}+pub struct Document {pub id: DocId,pub name: String,pub path: Option<String>,+ /// The working file: what Save writes and what is displayed.pub bytes: Arc<Vec<u8>>,pub info: DocInfo,pub renderer: RenderPool,+ /// The password the document was opened with (needed to read attachments, etc.).+ pub password: Option<String>,+ /// `true` when there are edits that have not been saved.+ pub dirty: bool,+ /// Why the document cannot be edited (e.g. encryption), if so.+ pub read_only_reason: Option<String>,+ editor: Option<Editor>,+ config: RenderConfig,+}++impl Document {+ pub fn can_undo(&self) -> Option<&str> {+ self.editor.as_ref().and_then(|e| e.undo.last()).map(|(l, _)| l.as_str())+ }++ pub fn can_redo(&self) -> Option<&str> {+ self.editor.as_ref().and_then(|e| e.redo.last()).map(|(l, _)| l.as_str())+ }++ pub fn editable(&self) -> bool {+ self.editor.is_some()+ }++ /// Current value of a document-information entry (Title, Author, …).+ pub fn info_value(&self, key: &str) -> Option<String> {+ self.editor.as_ref().and_then(|e| printcraft_organize::info(&e.cos, key))+ }++ /// Notes about damage repaired while opening (Document Properties ▸ Advanced, notices).+ pub fn repair_log(&self) -> Vec<String> {+ self.editor.as_ref().map(|e| e.cos.repair_log().to_vec()).unwrap_or_default()+ }+}++fn render_threads() -> usize {+ std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(2, 8) - 1+}++/// Edits that can be applied to a document. Page indices are 0-based.+#[derive(Clone, Debug, PartialEq)]+pub enum Edit {+ RotatePages {+ pages: Vec<usize>,+ degrees: i64,+ },+ DeletePages {+ pages: Vec<usize>,+ },+ MovePages {+ pages: Vec<usize>,+ to: usize,+ },+ InsertBlankPage {+ at: usize,+ width: f64,+ height: f64,+ },+ SetInfo {+ key: String,+ value: String,+ },+ /// Several edits applied as one undoable step (all or nothing).+ Batch {+ label: String,+ edits: Vec<Edit>,+ },+}++impl Edit {+ /// Label for the Edit menu and history ("Undo Rotate pages").+ pub fn label(&self) -> String {+ match self {+ Edit::RotatePages { pages, .. } => plural("Rotate page", pages.len()),+ Edit::DeletePages { pages } => plural("Delete page", pages.len()),+ Edit::MovePages { pages, .. } => plural("Move page", pages.len()),+ Edit::InsertBlankPage { .. } => "Insert blank page".into(),+ Edit::SetInfo { key, .. } => format!("Change {key}"),+ Edit::Batch { label, .. } => label.clone(),+ }+ }+}++/// Perform an edit on a working copy (the caller discards it on error).+fn run_edit(doc: &mut printcraft_cos::Document, edit: &Edit) -> Result<(), EditError> {+ match edit {+ Edit::RotatePages { pages, degrees } => printcraft_organize::rotate_pages(doc, pages, *degrees)?,+ Edit::DeletePages { pages } => printcraft_organize::delete_pages(doc, pages)?,+ Edit::MovePages { pages, to } => printcraft_organize::move_pages(doc, pages, *to)?,+ Edit::InsertBlankPage { at, width, height } => {+ printcraft_organize::insert_blank_page(doc, *at, *width, *height)?;+ }+ Edit::SetInfo { key, value } => printcraft_organize::set_info(doc, key, value)?,+ Edit::Batch { edits, .. } => {+ for e in edits {+ run_edit(doc, e)?;+ }+ }+ }+ Ok(())+}++fn plural(s: &str, n: usize) -> String {+ if n == 1 { s.to_string() } else { format!("{s}s") }+}++#[derive(Debug, thiserror::Error, PartialEq)]+pub enum EditError {+ #[error("no such document")]+ NoDocument,+ #[error("this document can't be edited: {0}")]+ ReadOnly(String),+ #[error("{0}")]+ Organize(#[from] printcraft_organize::OrganizeError),+ #[error("the edited document could not be written: {0}")]+ Write(String),+ #[error("the edited document could not be reopened: {0}")]+ Reopen(String),+ #[error("nothing to undo")]+ NothingToUndo,+ #[error("nothing to redo")]+ NothingToRedo,}#[derive(Default)]pub struct Session {docs: Vec<Document>,next_id: u64,+ /// Seconds since the Unix epoch, injected so saves are deterministic in tests.+ clock: Option<fn() -> i64>,}impl Session {@@ -34,18 +176,177 @@ impl Session {Self::default()}+ /// Use a fixed clock (tests) instead of the system time.+ pub fn with_clock(mut self, clock: fn() -> i64) -> Self {+ self.clock = Some(clock);+ self+ }++ fn now(&self) -> Option<i64> {+ if let Some(c) = self.clock {+ return Some(c());+ }+ #[cfg(not(target_arch = "wasm32"))]+ return std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs() as i64);+ #[cfg(target_arch = "wasm32")]+ return None;+ }+/// Open a document from bytes. Rendering starts lazily when pages are requested.- pub fn open(&mut self, name: impl Into<String>, path: Option<String>, bytes: Vec<u8>) -> Result<DocId, OpenError> {- let bytes = Arc::new(bytes);- let info = inspect(bytes.clone())?;- let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(2, 8) - 1;- let renderer = RenderPool::new(bytes.clone(), threads);+ ///+ /// `password` is tried as either the user or owner password when the file is encrypted.+ pub fn open(&mut self, name: impl Into<String>, path: Option<String>, bytes: Arc<Vec<u8>>, password: Option<&str>) -> Result<DocId, OpenError> {+ let info = inspect(bytes.clone(), password)?;+ let config = RenderConfig { password: password.map(Arc::from), ..Default::default() };+ let renderer = RenderPool::new(bytes.clone(), render_threads(), config.clone());+ let (editor, read_only_reason) = match std::panic::catch_unwind(|| printcraft_cos::Document::open(bytes.clone())) {+ Ok(Ok(cos)) => (Some(Editor { cos, undo: Vec::new(), redo: Vec::new() }), None),+ Ok(Err(e)) => (None, Some(e.to_string())),+ Err(_) => (None, Some("the document structure could not be read for editing".into())),+ };self.next_id += 1;let id = DocId(self.next_id);- self.docs.push(Document { id, name: name.into(), path, bytes, info, renderer });+ self.docs.push(Document {+ id,+ name: name.into(),+ path,+ bytes,+ info,+ renderer,+ password: password.map(str::to_owned),+ dirty: false,+ read_only_reason,+ editor,+ config,+ });Ok(id)}+ fn doc_mut(&mut self, id: DocId) -> Result<&mut Document, EditError> {+ self.docs.iter_mut().find(|d| d.id == id).ok_or(EditError::NoDocument)+ }++ /// Apply an edit. On success the previous state is undoable and the view data is refreshed.+ pub fn apply(&mut self, id: DocId, edit: Edit) -> Result<(), EditError> {+ let doc = self.doc_mut(id)?;+ let reason = doc.read_only_reason.clone().unwrap_or_default();+ let editor = doc.editor.as_mut().ok_or(EditError::ReadOnly(reason))?;+ let mut next = editor.cos.clone();+ run_edit(&mut next, &edit)?;+ let previous = std::mem::replace(&mut editor.cos, next);+ editor.undo.push((edit.label(), previous));+ if editor.undo.len() > MAX_UNDO {+ editor.undo.remove(0);+ }+ editor.redo.clear();+ if let Err(e) = Self::refresh(doc) {+ // Roll back: the edit produced something we cannot display.+ if let Some(ed) = doc.editor.as_mut()+ && let Some((_, prev)) = ed.undo.pop()+ {+ ed.cos = prev;+ }+ let _ = Self::refresh(doc);+ return Err(e);+ }+ doc.dirty = true;+ Ok(())+ }++ pub fn undo(&mut self, id: DocId) -> Result<String, EditError> {+ let doc = self.doc_mut(id)?;+ let editor = doc.editor.as_mut().ok_or(EditError::NothingToUndo)?;+ let (label, prev) = editor.undo.pop().ok_or(EditError::NothingToUndo)?;+ let current = std::mem::replace(&mut editor.cos, prev);+ editor.redo.push((label.clone(), current));+ Self::refresh(doc)?;+ doc.dirty = true;+ Ok(label)+ }++ pub fn redo(&mut self, id: DocId) -> Result<String, EditError> {+ let doc = self.doc_mut(id)?;+ let editor = doc.editor.as_mut().ok_or(EditError::NothingToRedo)?;+ let (label, next) = editor.redo.pop().ok_or(EditError::NothingToRedo)?;+ let current = std::mem::replace(&mut editor.cos, next);+ editor.undo.push((label.clone(), current));+ Self::refresh(doc)?;+ doc.dirty = true;+ Ok(label)+ }++ /// Rebuild working bytes, inspection and renderer from the current edit state.+ fn refresh(doc: &mut Document) -> Result<(), EditError> {+ let Some(editor) = doc.editor.as_ref() else { return Ok(()) };+ let bytes = if editor.cos.is_modified() {+ Arc::new(write_incremental(&editor.cos, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))?)+ } else {+ editor.cos.bytes().clone()+ };+ let info = inspect(bytes.clone(), doc.password.as_deref()).map_err(|e| EditError::Reopen(e.to_string()))?;+ // Keep the user's layer choices where the layers still exist.+ let mut info = info;+ for l in &mut info.layers {+ if let Some(old) = doc.info.layers.iter().find(|o| o.id == l.id) {+ l.visible = old.visible;+ }+ }+ doc.info = info;+ doc.bytes = bytes.clone();+ doc.renderer = RenderPool::new(bytes, render_threads(), doc.config.clone());+ Ok(())+ }++ /// The bytes to write for Save: an incremental update of the file as opened/last saved,+ /// with `/ModDate` stamped. Call `mark_saved` after writing them successfully.+ pub fn save_bytes(&self, id: DocId) -> Result<Arc<Vec<u8>>, EditError> {+ let doc = self.get(id).ok_or(EditError::NoDocument)?;+ let Some(editor) = doc.editor.as_ref() else { return Ok(doc.bytes.clone()) };+ if !editor.cos.is_modified() {+ return Ok(editor.cos.bytes().clone());+ }+ let opts = SaveOptions { mod_date: self.now().map(printcraft_cos::pdf_date), ..SaveOptions::default() };+ write_incremental(&editor.cos, &opts).map(Arc::new).map_err(|e| EditError::Write(e.to_string()))+ }++ /// A compact, garbage-collected rewrite (Save As ▸ "Optimized" / Reduce File Size groundwork).+ pub fn save_full_bytes(&self, id: DocId) -> Result<Arc<Vec<u8>>, EditError> {+ let doc = self.get(id).ok_or(EditError::NoDocument)?;+ let editor = doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?;+ let opts = SaveOptions { mod_date: self.now().map(printcraft_cos::pdf_date), ..SaveOptions::default() };+ write_full(&editor.cos, &opts).map(Arc::new).map_err(|e| EditError::Write(e.to_string()))+ }++ /// Record a successful save of `bytes` (to `path`, if any): rebase editing on the saved file+ /// so the next save appends only newer edits. Undo history is kept.+ pub fn mark_saved(&mut self, id: DocId, bytes: Arc<Vec<u8>>, path: Option<String>) -> Result<(), EditError> {+ let doc = self.doc_mut(id)?;+ if let Some(editor) = doc.editor.as_mut() {+ editor.cos = printcraft_cos::Document::open(bytes.clone()).map_err(|e| EditError::Reopen(e.to_string()))?;+ }+ if let Some(p) = path {+ doc.name = std::path::Path::new(&p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.clone());+ doc.path = Some(p);+ }+ doc.dirty = false;+ Self::refresh(doc)+ }++ /// Show or hide a layer (optional content group) for viewing. Returns `true` if it changed;+ /// callers must drop cached rasters and text for the document.+ pub fn set_layer_visible(&mut self, id: DocId, layer: usize, visible: bool) -> bool {+ let Some(doc) = self.docs.iter_mut().find(|d| d.id == id) else { return false };+ let Some(l) = doc.info.layers.get_mut(layer) else { return false };+ if l.visible == visible {+ return false;+ }+ l.visible = visible;+ let overrides: Vec<(i32, i32, bool)> = doc.info.layers.iter().map(|l| (l.id.0 as i32, l.id.1 as i32, l.visible)).collect();+ doc.config.layers = Arc::new(overrides);+ doc.renderer = RenderPool::new(doc.bytes.clone(), render_threads(), doc.config.clone());+ true+ }+pub fn close(&mut self, id: DocId) {self.docs.retain(|d| d.id != id);}@@ -58,3 +359,6 @@ impl Session {&self.docs}}++#[cfg(test)]+mod tests;diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsnew file mode 100644index 000000000..fd7540387--- /dev/null+++ b/crates/engine/src/tests.rs@@ -0,0 +1,191 @@+use std::sync::Arc;++use super::*;++/// A minimal `n`-page document; page `i` shows "Page i+1".+pub(crate) fn fixture(n: usize) -> Vec<u8> {+ let mut objs: Vec<Vec<u8>> = vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()];+ let kids: Vec<String> = (0..n).map(|i| format!("{} 0 R", 4 + 2 * i)).collect();+ objs.push(format!("<< /Type /Pages /Kids [{}] /Count {n} /MediaBox [0 0 200 300] >>", kids.join(" ")).into_bytes());+ objs.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec());+ for i in 0..n {+ objs.push(format!("<< /Type /Page /Parent 2 0 R /Contents {} 0 R /Resources << /Font << /F1 3 0 R >> >> >>", 5 + 2 * i).into_bytes());+ let body = format!("BT /F1 24 Tf 20 150 Td (Page {}) Tj ET", i + 1);+ objs.push(format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()).into_bytes());+ }+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());+ out.extend_from_slice(o);+ out.extend_from_slice(b"\nendobj\n");+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ out+}++fn session_with(n: usize) -> (Session, DocId) {+ let mut s = Session::new().with_clock(|| 1_700_000_000);+ let id = s.open("fixture.pdf", None, Arc::new(fixture(n)), None).expect("opens");+ (s, id)+}++fn page_texts(s: &Session, id: DocId) -> Vec<String> {+ let doc = s.get(id).unwrap();+ let mut r = printcraft_render::PageRenderer::new(doc.bytes.clone(), Default::default());+ (0..doc.info.pages.len())+ .map(|p| {+ let r = r.render(RenderRequestFor::text(p));+ r.text.map(|t| t.plain_text().trim().to_string()).unwrap_or_default()+ })+ .collect()+}++/// Shorthand for building text-extraction requests.+struct RenderRequestFor;+impl RenderRequestFor {+ fn text(page: usize) -> printcraft_render::RenderRequest {+ printcraft_render::RenderRequest { page, kind: printcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() }+ }+}++#[test]+fn edits_update_view_data_and_mark_dirty() {+ let (mut s, id) = session_with(3);+ assert!(s.get(id).unwrap().editable());+ assert!(!s.get(id).unwrap().dirty);+ s.apply(id, Edit::DeletePages { pages: vec![1] }).unwrap();+ let doc = s.get(id).unwrap();+ assert!(doc.dirty);+ assert_eq!(doc.info.pages.len(), 2, "inspection refreshed");+ assert_eq!(doc.can_undo(), Some("Delete page"));+ assert_eq!(page_texts(&s, id), ["Page 1", "Page 3"], "renderer refreshed");+}++#[test]+fn undo_and_redo_restore_exact_states() {+ let (mut s, id) = session_with(3);+ let original = s.get(id).unwrap().bytes.clone();+ s.apply(id, Edit::MovePages { pages: vec![2], to: 0 }).unwrap();+ s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();+ assert_eq!(s.get(id).unwrap().info.pages[0].rotation, 90);+ assert_eq!(s.undo(id).unwrap(), "Rotate page");+ assert_eq!(s.get(id).unwrap().info.pages[0].rotation, 0);+ assert_eq!(s.undo(id).unwrap(), "Move page");+ assert_eq!(s.get(id).unwrap().bytes, original, "undoing everything returns the original bytes");+ assert_eq!(s.undo(id), Err(EditError::NothingToUndo));+ assert_eq!(s.redo(id).unwrap(), "Move page");+ assert_eq!(page_texts(&s, id), ["Page 3", "Page 1", "Page 2"]);+ // A new edit clears the redo stack.+ s.apply(id, Edit::InsertBlankPage { at: 0, width: 612.0, height: 792.0 }).unwrap();+ assert_eq!(s.redo(id), Err(EditError::NothingToRedo));+ assert_eq!(s.get(id).unwrap().info.pages.len(), 4);+}++#[test]+fn failed_edit_changes_nothing() {+ let (mut s, id) = session_with(2);+ let before = s.get(id).unwrap().bytes.clone();+ let err = s.apply(id, Edit::DeletePages { pages: vec![0, 1] }).unwrap_err();+ assert_eq!(err, EditError::Organize(printcraft_organize::OrganizeError::WouldRemoveAllPages));+ let doc = s.get(id).unwrap();+ assert!(!doc.dirty);+ assert_eq!(doc.can_undo(), None);+ assert_eq!(doc.bytes, before);+}++#[test]+fn save_is_incremental_stamps_mod_date_and_rebases() {+ let (mut s, id) = session_with(2);+ let original = s.get(id).unwrap().bytes.clone();+ s.apply(id, Edit::SetInfo { key: "Title".into(), value: "Quarterly report".into() }).unwrap();+ let saved = s.save_bytes(id).unwrap();+ assert_eq!(&saved[..original.len()], &original[..], "incremental save keeps the original bytes");+ let text = String::from_utf8_lossy(&saved[original.len()..]);+ assert!(text.contains("/ModDate (D:20231114221320Z)"), "mod date stamped: {text}");+ s.mark_saved(id, saved.clone(), Some("/tmp/out/report.pdf".into())).unwrap();+ let doc = s.get(id).unwrap();+ assert!(!doc.dirty);+ assert_eq!(doc.name, "report.pdf");+ assert_eq!(doc.info_value("Title").as_deref(), Some("Quarterly report"));+ assert_eq!(doc.info.title.as_deref(), Some("Quarterly report"));+ // Saving again without edits writes the same bytes; a later edit appends just one revision.+ assert_eq!(s.save_bytes(id).unwrap(), saved);+ s.apply(id, Edit::RotatePages { pages: vec![1], degrees: -90 }).unwrap();+ let second = s.save_bytes(id).unwrap();+ assert_eq!(&second[..saved.len()], &saved[..]);+ let reopened = printcraft_cos::Document::open(second).unwrap();+ assert_eq!(reopened.revisions().len(), 3);+}++#[test]+fn undo_still_works_after_save() {+ let (mut s, id) = session_with(2);+ s.apply(id, Edit::DeletePages { pages: vec![0] }).unwrap();+ let saved = s.save_bytes(id).unwrap();+ s.mark_saved(id, saved, None).unwrap();+ s.undo(id).unwrap();+ let doc = s.get(id).unwrap();+ assert!(doc.dirty, "undoing past a save makes the document dirty again");+ assert_eq!(doc.info.pages.len(), 2);+}++#[test]+fn full_save_is_readable_and_smaller_after_deletes() {+ let (mut s, id) = session_with(5);+ s.apply(id, Edit::DeletePages { pages: vec![0, 1, 2] }).unwrap();+ let full = s.save_full_bytes(id).unwrap();+ assert!(full.len() < s.save_bytes(id).unwrap().len());+ let mut s2 = Session::new();+ let id2 = s2.open("full.pdf", None, full, None).unwrap();+ assert_eq!(page_texts(&s2, id2), ["Page 4", "Page 5"]);+}++#[test]+fn layer_choices_survive_edits() {+ // No layers in the fixture: just make sure refresh keeps working with an empty list and+ // that unknown layers are rejected.+ let (mut s, id) = session_with(1);+ assert!(!s.set_layer_visible(id, 0, false));+ s.apply(id, Edit::InsertBlankPage { at: 1, width: 100.0, height: 100.0 }).unwrap();+ assert_eq!(s.get(id).unwrap().info.pages.len(), 2);+}++#[test]+fn edits_to_unknown_documents_are_rejected() {+ let (mut s, _) = session_with(1);+ assert_eq!(s.apply(DocId(999), Edit::DeletePages { pages: vec![0] }), Err(EditError::NoDocument));+ assert_eq!(s.undo(DocId(999)), Err(EditError::NoDocument));+ assert!(s.save_bytes(DocId(999)).is_err());+}++#[test]+fn batch_is_one_undo_step_and_all_or_nothing() {+ let (mut s, id) = session_with(3);+ let batch = Edit::Batch {+ label: "Change properties".into(),+ edits: vec![Edit::SetInfo { key: "Title".into(), value: "T".into() }, Edit::SetInfo { key: "Author".into(), value: "A".into() }],+ };+ s.apply(id, batch).unwrap();+ assert_eq!(s.get(id).unwrap().info_value("Author").as_deref(), Some("A"));+ assert_eq!(s.undo(id).unwrap(), "Change properties");+ assert_eq!(s.get(id).unwrap().info_value("Title"), None);+ assert_eq!(s.get(id).unwrap().can_undo(), None, "one step");+ // A failing member rolls back the whole batch.+ let bad = Edit::Batch { label: "x".into(), edits: vec![Edit::RotatePages { pages: vec![0], degrees: 90 }, Edit::DeletePages { pages: vec![9] }] };+ assert!(s.apply(id, bad).is_err());+ assert_eq!(s.get(id).unwrap().info.pages[0].rotation, 0);+}++#[test]+fn insert_blank_between_pages_keeps_both_neighbours() {+ let (mut s, id) = session_with(2);+ s.apply(id, Edit::InsertBlankPage { at: 1, width: 200.0, height: 300.0 }).unwrap();+ assert_eq!(page_texts(&s, id), ["Page 1", "", "Page 2"]);+}diff --git a/crates/filters/Cargo.toml b/crates/filters/Cargo.tomlnew file mode 100644index 000000000..f8ea7c198--- /dev/null+++ b/crates/filters/Cargo.toml@@ -0,0 +1,19 @@+[package]+name = "printcraft-filters"+description = "PDF stream filters (ISO 32000-2 §7.4): Flate, LZW, predictors, ASCII85, ASCIIHex, RunLength"+version.workspace = true+edition.workspace = true+license.workspace = true+rust-version.workspace = true+repository.workspace = true++[lints]+workspace = true++[dependencies]+flate2.workspace = true+thiserror.workspace = true++[dev-dependencies]+proptest.workspace = true+weezl.workspace = truediff --git a/crates/filters/README.md b/crates/filters/README.mdnew file mode 100644index 000000000..a35749d41--- /dev/null+++ b/crates/filters/README.md@@ -0,0 +1,50 @@+# printcraft-filters++PDF stream filters: the decoders and encoders behind `/Filter` and `/DecodeParms`.++- **Layer:** L0, standalone. No dependency on any other PrintCraft crate. `cos` depends on it (architecture §3 rule 3).+- **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `miniz_oxide` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters).+- `#![forbid(unsafe_code)]`. Builds for `wasm32-unknown-unknown`.++## API++```rust+pub enum Filter { Flate, Lzw, AsciiHex, Ascii85, RunLength, Dct, Jpx, Jbig2, CcittFax, Crypt, Unknown(String) }+Filter::from_name(b"FlateDecode" | b"Fl" | ...) -> Filter // full names and inline-image abbreviations+Filter::name(&self) -> &str; Filter::is_image_codec(&self) -> bool++pub struct Params { predictor, colors, bits_per_component, columns, early_change } // i64s; Default = 1, 1, 8, 1, 1+pub enum FilterError { Corrupt { filter, detail }, LimitExceeded(usize), Unsupported(String) }++decode(chain, data, max_output) -> Result<Vec<u8>, FilterError>+decode_tolerant(chain, data, max_output) -> Result<(Vec<u8>, bool /*partial*/), FilterError>+encode(filter, params, data) -> Result<Vec<u8>, FilterError>+encode_flate(data) -> Vec<u8> // zlib, level 6+```++- `chain` is applied first to last, as in a `/Filter` array.+- Image codecs (DCT, JPX, JBIG2, CCITT), `Crypt` and unknown filters anywhere in a chain give `Unsupported`: callers keep such data encoded. Decryption belongs to `crypt`.+- `max_output` bounds every intermediate buffer (including the pre-predictor buffer) and gives `LimitExceeded(max_output)`.+- `decode_tolerant` turns `Corrupt` into "what was decoded so far" plus `partial = true`, then runs the rest of the chain on it (predictors are applied to partial output too). `LimitExceeded` and `Unsupported` are still errors.++## Behaviour++| Filter | Decode | Encode |+|---|---|---|+| FlateDecode | zlib header checked, then inflated raw: a missing or wrong Adler-32 is tolerated; no valid header → raw deflate; trailing bytes ignored; preset dictionary → Corrupt; truncated → Corrupt (partial in tolerant mode) | zlib level 6 |+| LZWDecode | 9–12-bit MSB-first codes, clear (256), EOD (257), `EarlyChange` 0/1; missing EOD/initial clear tolerated; a full table stops growing | greedy, leading clear, clear-table when the table fills, EOD |+| Predictors (Flate/LZW) | 2 = TIFF (1/2/4/8/16 bpc), 10–15 = PNG with per-row tags 0–4; partial final rows decoded; bad params or tags → Corrupt | 2, 10 None, 11 Sub, 12 Up, 13 Average, 14 Paeth, 15 per-row optimum (min sum of signed residuals) |+| ASCIIHexDecode | white space ignored, odd digit padded with 0, `>` EOD (optional), other characters → Corrupt | upper case, newline every 64 digits, `>` |+| ASCII85Decode | `<~` prefix, `z`, white space, `~>` (or bare `~`, or none) EOD, final partial group; `z` inside a group, a 1-char final group, overflow or bad characters → Corrupt | `z` for zero groups, newline every 75 characters, `~>` |+| RunLengthDecode | 0–127 literal, 129–255 repeat, 128 EOD (optional); truncated run → Corrupt | runs of ≥2 repeat, literals up to 128, 128 |++## Tests++- Unit tests per filter with hand-computed vectors (the ISO 32000-2 LZW example, RFC 1951 stored blocks, PNG/TIFF rows).+- LZW is cross-checked against `weezl` (dev-dependency) in both directions for both early-change settings.+- `tests/proptests.rs`: encode→decode round trips for every encodable filter × predictor × colors × bpc × columns, two-filter chains, output-limit checks, and fuzz-style no-panic tests (random bytes, random/nonsense params, bit-flipped valid streams).+- `fuzz/`: a detached cargo-fuzz crate (`cargo +nightly fuzz run decode`, run from `crates/filters/`).++## Status++M1.1/M1.2 for the general-purpose filters are done. Not yet here: the image codecs (DCT via zune-jpeg, JPX via hayro-jpeg2000, JBIG2, CCITT G3/G4 decode and G4 encode, DCT encode) and Flate encode levels other than 6.diff --git a/crates/filters/fuzz/.gitignore b/crates/filters/fuzz/.gitignorenew file mode 100644index 000000000..ab0eaa1a4--- /dev/null+++ b/crates/filters/fuzz/.gitignore@@ -0,0 +1,5 @@+target/+corpus/+artifacts/+coverage/+Cargo.lockdiff --git a/crates/filters/fuzz/Cargo.toml b/crates/filters/fuzz/Cargo.tomlnew file mode 100644index 000000000..efa0774d7--- /dev/null+++ b/crates/filters/fuzz/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "printcraft-filters-fuzz"+version = "0.0.0"+publish = false+edition = "2024"+license = "MIT OR Apache-2.0"++[package.metadata]+cargo-fuzz = true++# Detached from the PrintCraft workspace: run with `cargo +nightly fuzz run decode`+# from crates/filters/.+[workspace]++[dependencies]+libfuzzer-sys = "0.4"+printcraft-filters = { path = ".." }++[[bin]]+name = "decode"+path = "fuzz_targets/decode.rs"+test = false+doc = false+bench = falsediff --git a/crates/filters/fuzz/fuzz_targets/decode.rs b/crates/filters/fuzz/fuzz_targets/decode.rsnew file mode 100644index 000000000..c9923ed73--- /dev/null+++ b/crates/filters/fuzz/fuzz_targets/decode.rs@@ -0,0 +1,32 @@+//! Feeds arbitrary bytes to every decoder, with parameters taken from the first bytes.+#![no_main]++use libfuzzer_sys::fuzz_target;+use printcraft_filters::{Filter, Params, decode, decode_tolerant};++const FILTERS: [Filter; 5] = [Filter::Flate, Filter::Lzw, Filter::AsciiHex, Filter::Ascii85, Filter::RunLength];+const PREDICTORS: [i64; 8] = [1, 2, 10, 11, 12, 13, 14, 15];+const BPC: [i64; 5] = [1, 2, 4, 8, 16];++fuzz_target!(|data: &[u8]| {+ let Some((head, body)) = data.split_first_chunk::<4>() else { return };+ // Up to two chained filters; the second only when head[0] says so.+ let params = Params {+ predictor: PREDICTORS[usize::from(head[1] & 7)],+ colors: i64::from(head[1] >> 3 & 3) + 1,+ bits_per_component: BPC[usize::from(head[2]) % BPC.len()],+ columns: i64::from(head[3]) + 1,+ early_change: i64::from(head[2] >> 7),+ };+ let mut chain = vec![(FILTERS[usize::from(head[0] & 7) % FILTERS.len()].clone(), params.clone())];+ if head[0] & 0x80 != 0 {+ chain.insert(0, (FILTERS[usize::from(head[0] >> 3 & 7) % FILTERS.len()].clone(), Params::default()));+ }+ let max = 1 << 22;+ if let Ok(out) = decode(&chain, body, max) {+ assert!(out.len() <= max);+ }+ if let Ok((out, _)) = decode_tolerant(&chain, body, max) {+ assert!(out.len() <= max);+ }+});diff --git a/crates/filters/src/ascii85.rs b/crates/filters/src/ascii85.rsnew file mode 100644index 000000000..ff3b39219--- /dev/null+++ b/crates/filters/src/ascii85.rs@@ -0,0 +1,156 @@+//! ASCII85Decode (ISO 32000-2 §7.4.3): groups of five characters `!`..`u` encode four+//! bytes base-85, `z` stands for four zero bytes, `~>` is EOD, white space is ignored and+//! a final partial group of n characters (2–5) yields n − 1 bytes. A leading `<~` and a+//! missing EOD are tolerated.++use crate::{Failure, Step, is_pdf_whitespace};++const NAME: &str = "ASCII85Decode";++fn push(out: &mut Vec<u8>, bytes: &[u8], max: usize) -> Result<(), Failure> {+ if out.len() + bytes.len() > max {+ return Err(Failure::limit(max));+ }+ out.extend_from_slice(bytes);+ Ok(())+}++pub(crate) fn decode(data: &[u8], max: usize) -> Step {+ let start = data.iter().position(|&b| !is_pdf_whitespace(b)).unwrap_or(data.len());+ let body = data[start..].strip_prefix(b"<~").unwrap_or(&data[start..]);+ let mut out = Vec::with_capacity((body.len() / 5 * 4 + 4).min(max));+ let mut acc: u64 = 0;+ let mut n = 0usize;+ for (i, &b) in body.iter().enumerate() {+ match b {+ b'!'..=b'u' => {+ acc = acc * 85 + u64::from(b - b'!');+ n += 1;+ if n == 5 {+ let Ok(v) = u32::try_from(acc) else {+ return Err(Failure::corrupt(NAME, format!("group ending at {i} exceeds 2^32"), out));+ };+ push(&mut out, &v.to_be_bytes(), max)?;+ acc = 0;+ n = 0;+ }+ }+ b'z' if n == 0 => push(&mut out, &[0; 4], max)?,+ b'z' => return Err(Failure::corrupt(NAME, format!("'z' inside a group at {i}"), out)),+ // `~` starts the EOD marker; tolerate it without the following `>`.+ b'~' => break,+ b if is_pdf_whitespace(b) => {}+ b => return Err(Failure::corrupt(NAME, format!("invalid character 0x{b:02x} at {i}"), out)),+ }+ }+ match n {+ 0 => {}+ 1 => return Err(Failure::corrupt(NAME, "final group has a single character", out)),+ _ => {+ // Pad with `u` (84) to a full group and keep n − 1 bytes.+ for _ in n..5 {+ acc = acc * 85 + 84;+ }+ let Ok(v) = u32::try_from(acc) else {+ return Err(Failure::corrupt(NAME, "final group exceeds 2^32", out));+ };+ push(&mut out, &v.to_be_bytes()[..n - 1], max)?;+ }+ }+ Ok(out)+}++/// Encodes with `z` for zero groups, a newline every 75 characters, and a `~>` EOD.+pub(crate) fn encode(data: &[u8]) -> Vec<u8> {+ let mut out = Vec::with_capacity(data.len() * 5 / 4 + data.len() / 60 + 8);+ let mut col = 0;+ let mut put = |out: &mut Vec<u8>, s: &[u8]| {+ for &c in s {+ if col == 75 {+ out.push(b'\n');+ col = 0;+ }+ out.push(c);+ col += 1;+ }+ };+ for chunk in data.chunks(4) {+ let mut word = [0u8; 4];+ word[..chunk.len()].copy_from_slice(chunk);+ let mut v = u32::from_be_bytes(word);+ if v == 0 && chunk.len() == 4 {+ put(&mut out, b"z");+ continue;+ }+ let mut digits = [0u8; 5];+ for d in digits.iter_mut().rev() {+ *d = (v % 85) as u8 + b'!';+ v /= 85;+ }+ put(&mut out, &digits[..chunk.len() + 1]);+ }+ out.extend_from_slice(b"~>");+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::FilterError;++ fn dec(d: &[u8]) -> Result<Vec<u8>, FilterError> {+ decode(d, 1000).map_err(|f| f.error)+ }++ #[test]+ fn vectors() {+ // "Man " = 0x4D616E20 = 24·85⁴ + 73·85³ + 80·85² + 78·85 + 61 -> "9jqo^".+ assert_eq!(dec(b"9jqo^~>").unwrap(), b"Man ");+ assert_eq!(encode(b"Man "), b"9jqo^~>");+ // "M" padded to 0x4D000000 -> "9`" (24, 63); decoding pads with 'u'.+ assert_eq!(encode(b"M"), b"9`~>");+ assert_eq!(dec(b"9`~>").unwrap(), b"M");+ assert_eq!(dec(b"z~>").unwrap(), [0; 4]);+ assert_eq!(encode(&[0; 4]), b"z~>");+ // A partial zero group is not `z`.+ assert_eq!(encode(&[0; 3]), b"!!!!~>");+ assert_eq!(dec(b"!!!!~>").unwrap(), [0; 3]);+ assert_eq!(dec(b"s8W-!~>").unwrap(), [0xff; 4]);+ }++ #[test]+ fn syntax_tolerance() {+ assert_eq!(dec(b"<~9jqo^~>").unwrap(), b"Man ");+ assert_eq!(dec(b" \n<~9j\r\nq o\t^z~>").unwrap(), b"Man \0\0\0\0");+ assert_eq!(dec(b"9jqo^").unwrap(), b"Man "); // missing EOD+ assert_eq!(dec(b"9jqo^~").unwrap(), b"Man "); // bare ~+ assert_eq!(dec(b"9jqo^~>garbage{").unwrap(), b"Man ");+ assert_eq!(dec(b"~>").unwrap(), b"");+ assert_eq!(dec(b"").unwrap(), b"");+ }++ #[test]+ fn corrupt() {+ assert!(matches!(dec(b"9jz~>"), Err(FilterError::Corrupt { .. })));+ assert!(matches!(dec(b"9jqo^9~>"), Err(FilterError::Corrupt { .. })));+ assert!(matches!(dec(b"uuuuu~>"), Err(FilterError::Corrupt { .. }))); // > 2^32 - 1+ assert!(matches!(dec(b"9jqo^v~>"), Err(FilterError::Corrupt { .. })));+ let f = decode(b"9jqo^{", 100).err().unwrap();+ assert_eq!(f.partial, b"Man ");+ }++ #[test]+ fn limit() {+ assert!(matches!(decode(b"zz", 7).map_err(|f| f.error), Err(FilterError::LimitExceeded(7))));+ assert!(matches!(decode(b"z9`", 4).map_err(|f| f.error), Err(FilterError::LimitExceeded(4))));+ assert_eq!(decode(b"zz", 8).ok().unwrap().len(), 8);+ }++ #[test]+ fn line_wrapping() {+ let data: Vec<u8> = (0..=255u8).collect();+ let e = encode(&data);+ assert!(e.split(|&b| b == b'\n').all(|l| l.len() <= 77));+ assert_eq!(dec(&e).unwrap_or_default().len(), 256);+ }+}diff --git a/crates/filters/src/asciihex.rs b/crates/filters/src/asciihex.rsnew file mode 100644index 000000000..5ba0574e8--- /dev/null+++ b/crates/filters/src/asciihex.rs@@ -0,0 +1,106 @@+//! ASCIIHexDecode (ISO 32000-2 §7.4.2): pairs of hex digits, white space ignored,+//! `>` is EOD, an odd final digit is padded with 0. A missing EOD is tolerated.++use crate::{Failure, Step, is_pdf_whitespace};++const NAME: &str = "ASCIIHexDecode";++fn nibble(b: u8) -> Option<u8> {+ match b {+ b'0'..=b'9' => Some(b - b'0'),+ b'a'..=b'f' => Some(b - b'a' + 10),+ b'A'..=b'F' => Some(b - b'A' + 10),+ _ => None,+ }+}++pub(crate) fn decode(data: &[u8], max: usize) -> Step {+ let mut out = Vec::with_capacity((data.len() / 2).min(max));+ let mut hi: Option<u8> = None;+ for (i, &b) in data.iter().enumerate() {+ if is_pdf_whitespace(b) {+ continue;+ }+ if b == b'>' {+ break;+ }+ let Some(n) = nibble(b) else {+ return Err(Failure::corrupt(NAME, format!("invalid character 0x{b:02x} at offset {i}"), out));+ };+ match hi.take() {+ None => hi = Some(n),+ Some(h) => {+ if out.len() == max {+ return Err(Failure::limit(max));+ }+ out.push(h << 4 | n);+ }+ }+ }+ if let Some(h) = hi {+ if out.len() == max {+ return Err(Failure::limit(max));+ }+ out.push(h << 4);+ }+ Ok(out)+}++/// Upper-case hex, a newline every 64 digits, terminated by `>`.+pub(crate) fn encode(data: &[u8]) -> Vec<u8> {+ const HEX: &[u8; 16] = b"0123456789ABCDEF";+ let mut out = Vec::with_capacity(data.len() * 2 + data.len() / 32 + 1);+ for (i, &b) in data.iter().enumerate() {+ if i > 0 && i % 32 == 0 {+ out.push(b'\n');+ }+ out.push(HEX[usize::from(b >> 4)]);+ out.push(HEX[usize::from(b & 15)]);+ }+ out.push(b'>');+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::FilterError;++ fn dec(d: &[u8]) -> Result<Vec<u8>, FilterError> {+ decode(d, 1000).map_err(|f| f.error)+ }++ #[test]+ fn vectors() {+ assert_eq!(dec(b"48656c6C6F>").unwrap(), b"Hello");+ assert_eq!(dec(b" 4 8\n6\r5\t6\x0c c\x006c 6f >").unwrap(), b"Hello");+ assert_eq!(dec(b"901FA>").unwrap(), [0x90, 0x1f, 0xa0]);+ assert_eq!(dec(b"901FA").unwrap(), [0x90, 0x1f, 0xa0]); // missing EOD+ assert_eq!(dec(b"41>zz garbage after EOD").unwrap(), b"A");+ assert_eq!(dec(b">").unwrap(), b"");+ assert_eq!(dec(b"").unwrap(), b"");+ }++ #[test]+ fn invalid_char() {+ let f = decode(b"4142G43>", 1000).err().unwrap();+ assert!(matches!(f.error, FilterError::Corrupt { .. }));+ assert_eq!(f.partial, b"AB");+ }++ #[test]+ fn limit() {+ assert!(matches!(decode(b"414243", 2).map_err(|f| f.error), Err(FilterError::LimitExceeded(2))));+ assert!(matches!(decode(b"41424", 2).map_err(|f| f.error), Err(FilterError::LimitExceeded(2))));+ assert_eq!(decode(b"4142", 2).ok().unwrap(), b"AB");+ }++ #[test]+ fn encoding() {+ assert_eq!(encode(b"Hello"), b"48656C6C6F>");+ assert_eq!(encode(b""), b">");+ let long = encode(&[0xab; 40]);+ assert_eq!(long[64], b'\n');+ assert_eq!(dec(&long).unwrap(), [0xab; 40]);+ }+}diff --git a/crates/filters/src/flate.rs b/crates/filters/src/flate.rsnew file mode 100644index 000000000..7bb8f53fc--- /dev/null+++ b/crates/filters/src/flate.rs@@ -0,0 +1,166 @@+//! FlateDecode (ISO 32000-2 §7.4.4): zlib (RFC 1950) wrapping deflate (RFC 1951).+//!+//! Real-world quirks handled:+//! - the Adler-32 trailer is not required (some producers omit or corrupt it), because the+//! deflate stream is inflated raw after the 2-byte zlib header;+//! - streams without a valid zlib header are inflated as raw deflate;+//! - data after the end of the deflate stream is ignored.++use std::io::Write;++use flate2::{Compression, Decompress, FlushDecompress, Status};++use crate::{Failure, Step};++const NAME: &str = "FlateDecode";++/// Checks the RFC 1950 header: CM = 8, CINFO ≤ 7 and the FCHECK multiple-of-31 rule.+fn zlib_header(data: &[u8]) -> Option<(u8, u8)> {+ let (&cmf, &flg) = (data.first()?, data.get(1)?);+ let ok = cmf & 0x0f == 8 && cmf >> 4 <= 7 && (u16::from(cmf) << 8 | u16::from(flg)) % 31 == 0;+ ok.then_some((cmf, flg))+}++pub(crate) fn decode(data: &[u8], max: usize) -> Step {+ match zlib_header(data) {+ Some((_, flg)) if flg & 0x20 != 0 => Err(Failure::corrupt(NAME, "zlib preset dictionary is not allowed in PDF", Vec::new())),+ Some(_) => match inflate_raw(&data[2..], max) {+ // A header that only looked valid: retry the whole input as raw deflate.+ Err(f) if f.partial.is_empty() && matches!(f.error, crate::FilterError::Corrupt { .. }) => inflate_raw(data, max).map_err(|_| f),+ r => r,+ },+ None => inflate_raw(data, max),+ }+}++fn inflate_raw(input: &[u8], max: usize) -> Step {+ let mut d = Decompress::new(false);+ let mut out: Vec<u8> = Vec::new();+ // One byte beyond the limit lets us tell "exactly max" from "more than max".+ let cap = max.saturating_add(1);+ loop {+ if out.len() == out.capacity() {+ if out.len() >= cap {+ return Err(Failure::limit(max));+ }+ let grow = out.capacity().max(input.len().saturating_mul(2)).max(4096).min(cap - out.len());+ out.reserve_exact(grow);+ }+ let consumed = d.total_in() as usize;+ let produced = out.len();+ let res = d.decompress_vec(&input[consumed.min(input.len())..], &mut out, FlushDecompress::None);+ if out.len() > max {+ return Err(Failure::limit(max));+ }+ match res {+ Err(e) => return Err(Failure::corrupt(NAME, e.to_string(), out)),+ Ok(Status::StreamEnd) => return Ok(out),+ Ok(Status::Ok | Status::BufError) => {+ let progressed = d.total_in() as usize != consumed || out.len() != produced;+ let room_left = out.len() < out.capacity();+ if room_left && (d.total_in() as usize >= input.len() || !progressed) {+ return Err(Failure::corrupt(NAME, "unexpected end of deflate data", out));+ }+ }+ }+ }+}++/// zlib at level 6.+pub(crate) fn encode(data: &[u8]) -> Vec<u8> {+ let mut e = flate2::write::ZlibEncoder::new(Vec::with_capacity(data.len() / 2 + 64), Compression::new(6));+ // Writing into a Vec cannot fail.+ e.write_all(data).expect("in-memory write");+ e.finish().expect("in-memory write")+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::FilterError;++ fn dec(d: &[u8]) -> Result<Vec<u8>, FilterError> {+ decode(d, 1 << 24).map_err(|f| f.error)+ }++ #[test]+ fn known_zlib_vector() {+ // zlib("a"): header 78 9C, fixed-Huffman block, Adler-32 0x00620062.+ assert_eq!(dec(&[0x78, 0x9c, 0x4b, 0x04, 0x00, 0x00, 0x62, 0x00, 0x62]).unwrap(), b"a");+ }++ #[test]+ fn hand_built_stored_block() {+ // RFC 1951 §3.2.4 stored block: BFINAL=1 BTYPE=00, LEN=5, NLEN=!5, "hello",+ // then Adler-32("hello") = 0x062C0215.+ let v = [0x78, 0x01, 0x01, 0x05, 0x00, 0xfa, 0xff, b'h', b'e', b'l', b'l', b'o', 0x06, 0x2c, 0x02, 0x15];+ assert_eq!(dec(&v).unwrap(), b"hello");+ // Missing Adler-32 is tolerated.+ assert_eq!(dec(&v[..12]).unwrap(), b"hello");+ // Wrong Adler-32 is tolerated (as in other readers).+ let mut bad = v;+ bad[15] ^= 0xff;+ assert_eq!(dec(&bad).unwrap(), b"hello");+ // Trailing garbage after the stream is ignored.+ let mut trailing = v.to_vec();+ trailing.extend_from_slice(b"\r\nendstream");+ assert_eq!(dec(&trailing).unwrap(), b"hello");+ }++ #[test]+ fn raw_deflate_fallback() {+ let data = b"raw deflate without any zlib header, repeated repeated repeated".repeat(4);+ let mut e = flate2::write::DeflateEncoder::new(Vec::new(), Compression::new(6));+ e.write_all(&data).unwrap();+ let raw = e.finish().unwrap();+ assert!(zlib_header(&raw).is_none());+ assert_eq!(dec(&raw).unwrap(), data);+ }++ #[test]+ fn round_trip_and_missing_checksum() {+ let data: Vec<u8> = (0..50_000u32).map(|i| (i * i % 251) as u8).collect();+ let z = encode(&data);+ assert_eq!(&z[..2], &[0x78, 0x9c]);+ assert_eq!(dec(&z).unwrap(), data);+ assert_eq!(dec(&z[..z.len() - 4]).unwrap(), data);+ assert_eq!(dec(&z[..z.len() - 2]).unwrap(), data);+ }++ #[test]+ fn empty_input() {+ assert_eq!(dec(&encode(b"")).unwrap(), b"");+ assert!(matches!(dec(b""), Err(FilterError::Corrupt { .. })));+ }++ #[test]+ fn corrupt_and_truncated() {+ let data: Vec<u8> = (0..10_000u32).map(|i| (i % 13) as u8).collect();+ let z = encode(&data);+ match decode(&z[..z.len() / 2], 1 << 24) {+ Err(f) => {+ assert!(matches!(f.error, FilterError::Corrupt { .. }));+ assert_eq!(&data[..f.partial.len()], &f.partial[..]);+ }+ Ok(_) => panic!("truncated stream decoded"),+ }+ // BTYPE = 11 is reserved (RFC 1951 §3.2.3).+ assert!(matches!(dec(&[0x78, 0x9c, 0x07, 0, 0, 0]), Err(FilterError::Corrupt { .. })));+ // Preset dictionary.+ assert!(matches!(dec(&[0x78, 0x20, 0, 0, 0, 0]), Err(FilterError::Corrupt { .. })));+ }++ #[test]+ fn bomb_is_bounded() {+ let z = encode(&vec![0u8; 16 << 20]);+ assert!(z.len() < 32 * 1024);+ assert!(matches!(dec_limit(&z, 1 << 20), Err(FilterError::LimitExceeded(n)) if n == 1 << 20));+ assert_eq!(dec_limit(&z, 16 << 20).unwrap().len(), 16 << 20);+ assert!(matches!(dec_limit(&z, (16 << 20) - 1), Err(FilterError::LimitExceeded(_))));+ assert!(matches!(dec_limit(&z, 0), Err(FilterError::LimitExceeded(0))));+ }++ fn dec_limit(d: &[u8], max: usize) -> Result<Vec<u8>, FilterError> {+ decode(d, max).map_err(|f| f.error)+ }+}diff --git a/crates/filters/src/lib.rs b/crates/filters/src/lib.rsnew file mode 100644index 000000000..ce91500ee--- /dev/null+++ b/crates/filters/src/lib.rs@@ -0,0 +1,325 @@+//! PDF stream filters (ISO 32000-2 §7.4).+//!+//! Layer L0, standalone: this crate depends on no other PrintCraft crate.+//!+//! Decoding covers the general-purpose filters (`FlateDecode`, `LZWDecode` with+//! TIFF/PNG predictors, `ASCIIHexDecode`, `ASCII85Decode`, `RunLengthDecode`).+//! Image codecs (`DCTDecode`, `JPXDecode`, `JBIG2Decode`, `CCITTFaxDecode`),+//! `Crypt` and unknown filters are reported as [`FilterError::Unsupported`] so+//! callers keep such data encoded.+//!+//! Every decoder is bounded by a caller-supplied `max_output` (decompression-bomb+//! defence) and never panics on malformed input.+#![forbid(unsafe_code)]++mod ascii85;+mod asciihex;+mod flate;+mod lzw;+mod predictor;+mod runlength;++use std::borrow::Cow;++/// A PDF stream filter, identified by its `/Filter` name.+#[derive(Clone, Debug, PartialEq, Eq, Hash)]+pub enum Filter {+ Flate,+ Lzw,+ AsciiHex,+ Ascii85,+ RunLength,+ Dct,+ Jpx,+ Jbig2,+ CcittFax,+ Crypt,+ /// Any other name (kept verbatim, lossily converted to UTF-8).+ Unknown(String),+}++impl Filter {+ /// Parses a filter name. Accepts the full names (ISO 32000-2 Table 6) and the+ /// inline-image abbreviations (Table 92): `Fl`, `LZW`, `AHx`, `A85`, `RL`, `DCT`, `CCF`.+ /// A leading `/` is ignored.+ pub fn from_name(name: &[u8]) -> Filter {+ let n = name.strip_prefix(b"/").unwrap_or(name);+ match n {+ b"FlateDecode" | b"Fl" => Filter::Flate,+ b"LZWDecode" | b"LZW" => Filter::Lzw,+ b"ASCIIHexDecode" | b"AHx" => Filter::AsciiHex,+ b"ASCII85Decode" | b"A85" => Filter::Ascii85,+ b"RunLengthDecode" | b"RL" => Filter::RunLength,+ b"DCTDecode" | b"DCT" => Filter::Dct,+ b"JPXDecode" => Filter::Jpx,+ b"JBIG2Decode" => Filter::Jbig2,+ b"CCITTFaxDecode" | b"CCF" => Filter::CcittFax,+ b"Crypt" => Filter::Crypt,+ other => Filter::Unknown(String::from_utf8_lossy(other).into_owned()),+ }+ }++ /// The full PDF name (without the leading `/`).+ pub fn name(&self) -> &str {+ match self {+ Filter::Flate => "FlateDecode",+ Filter::Lzw => "LZWDecode",+ Filter::AsciiHex => "ASCIIHexDecode",+ Filter::Ascii85 => "ASCII85Decode",+ Filter::RunLength => "RunLengthDecode",+ Filter::Dct => "DCTDecode",+ Filter::Jpx => "JPXDecode",+ Filter::Jbig2 => "JBIG2Decode",+ Filter::CcittFax => "CCITTFaxDecode",+ Filter::Crypt => "Crypt",+ Filter::Unknown(s) => s,+ }+ }++ /// True for the image codecs (DCT, JPX, JBIG2, CCITT fax).+ pub fn is_image_codec(&self) -> bool {+ matches!(self, Filter::Dct | Filter::Jpx | Filter::Jbig2 | Filter::CcittFax)+ }++ fn is_decodable(&self) -> bool {+ matches!(self, Filter::Flate | Filter::Lzw | Filter::AsciiHex | Filter::Ascii85 | Filter::RunLength)+ }+}++/// `/DecodeParms` values relevant to the general-purpose filters (ISO 32000-2 Tables 8–9).+#[derive(Clone, Debug, PartialEq)]+pub struct Params {+ /// 1 = none, 2 = TIFF predictor 2, 10–15 = PNG predictors.+ pub predictor: i64,+ pub colors: i64,+ pub bits_per_component: i64,+ pub columns: i64,+ /// LZW only: 1 (default) switches code width one code early, 0 does not.+ pub early_change: i64,+}++impl Default for Params {+ fn default() -> Self {+ Params { predictor: 1, colors: 1, bits_per_component: 8, columns: 1, early_change: 1 }+ }+}++/// Errors from decoding or encoding.+#[derive(Debug, thiserror::Error)]+pub enum FilterError {+ #[error("{filter}: corrupt data: {detail}")]+ Corrupt { filter: &'static str, detail: String },+ #[error("decoded output exceeds the limit of {0} bytes")]+ LimitExceeded(usize),+ #[error("unsupported filter: {0}")]+ Unsupported(String),+}++/// A decoder failure carrying whatever was decoded before the error.+pub(crate) struct Failure {+ pub(crate) error: FilterError,+ pub(crate) partial: Vec<u8>,+}++impl Failure {+ pub(crate) fn corrupt(filter: &'static str, detail: impl Into<String>, partial: Vec<u8>) -> Self {+ Failure { error: FilterError::Corrupt { filter, detail: detail.into() }, partial }+ }++ pub(crate) fn limit(max: usize) -> Self {+ Failure { error: FilterError::LimitExceeded(max), partial: Vec::new() }+ }+}++pub(crate) type Step = Result<Vec<u8>, Failure>;++/// Decodes `data` through `chain` (first element applied first).+///+/// Image codecs, `Crypt` and unknown filters anywhere in the chain give+/// [`FilterError::Unsupported`] (callers keep such data encoded). `max_output` bounds+/// every intermediate buffer.+pub fn decode(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<Vec<u8>, FilterError> {+ run(chain, data, max_output, true).map(|(v, _)| v)+}++/// Like [`decode`], but on corrupt data returns what was decoded before the error and+/// reports `partial = true` (the behaviour viewers expect). The remaining filters of the+/// chain still run on the partial data. Limit and unsupported errors are still errors.+pub fn decode_tolerant(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, bool), FilterError> {+ run(chain, data, max_output, false)+}++fn run(chain: &[(Filter, Params)], data: &[u8], max: usize, strict: bool) -> Result<(Vec<u8>, bool), FilterError> {+ if let Some((f, _)) = chain.iter().find(|(f, _)| !f.is_decodable()) {+ return Err(FilterError::Unsupported(f.name().to_owned()));+ }+ let mut cur: Cow<[u8]> = Cow::Borrowed(data);+ let mut partial = false;+ for (filter, params) in chain {+ cur = Cow::Owned(match decode_one(filter, params, &cur, max) {+ Ok(v) => v,+ Err(Failure { error: FilterError::Corrupt { .. }, partial: out }) if !strict => {+ partial = true;+ out+ }+ Err(f) => return Err(f.error),+ });+ }+ Ok((cur.into_owned(), partial))+}++fn decode_one(filter: &Filter, params: &Params, data: &[u8], max: usize) -> Step {+ match filter {+ Filter::Flate => with_predictor(flate::decode(data, max), params, "FlateDecode"),+ Filter::Lzw => with_predictor(lzw::decode(data, params.early_change != 0, max), params, "LZWDecode"),+ Filter::AsciiHex => asciihex::decode(data, max),+ Filter::Ascii85 => ascii85::decode(data, max),+ Filter::RunLength => runlength::decode(data, max),+ other => Err(Failure { error: FilterError::Unsupported(other.name().to_owned()), partial: Vec::new() }),+ }+}++/// Applies the predictor to a decoder's result, including to partial output on failure.+fn with_predictor(step: Step, params: &Params, name: &'static str) -> Step {+ match step {+ Ok(v) => predictor::decode(params, v, name),+ Err(Failure { error, partial }) => {+ let partial = match predictor::decode(params, partial, name) {+ Ok(v) => v,+ Err(f) => f.partial,+ };+ Err(Failure { error, partial })+ }+ }+}++/// Encodes `data` with `filter`. Supported: Flate (zlib, level 6), LZW, ASCIIHex,+/// ASCII85, RunLength. For Flate and LZW, `params.predictor >= 2` applies the+/// predictor first (TIFF 2, PNG 10–15; 15 chooses the per-row optimum).+pub fn encode(filter: &Filter, params: &Params, data: &[u8]) -> Result<Vec<u8>, FilterError> {+ match filter {+ Filter::Flate => Ok(flate::encode(&predictor::encode(params, data)?)),+ Filter::Lzw => Ok(lzw::encode(&predictor::encode(params, data)?, params.early_change != 0)),+ Filter::AsciiHex => Ok(asciihex::encode(data)),+ Filter::Ascii85 => Ok(ascii85::encode(data)),+ Filter::RunLength => Ok(runlength::encode(data)),+ other => Err(FilterError::Unsupported(format!("encoding with {}", other.name()))),+ }+}++/// zlib (RFC 1950) at compression level 6.+pub fn encode_flate(data: &[u8]) -> Vec<u8> {+ flate::encode(data)+}++/// PDF white-space characters (ISO 32000-2 Table 1).+pub(crate) fn is_pdf_whitespace(b: u8) -> bool {+ matches!(b, 0 | 9 | 10 | 12 | 13 | 32)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn names_and_abbreviations() {+ for (full, abbr, f) in [+ (&b"FlateDecode"[..], &b"Fl"[..], Filter::Flate),+ (b"LZWDecode", b"LZW", Filter::Lzw),+ (b"ASCIIHexDecode", b"AHx", Filter::AsciiHex),+ (b"ASCII85Decode", b"A85", Filter::Ascii85),+ (b"RunLengthDecode", b"RL", Filter::RunLength),+ (b"DCTDecode", b"DCT", Filter::Dct),+ (b"CCITTFaxDecode", b"CCF", Filter::CcittFax),+ ] {+ assert_eq!(Filter::from_name(full), f);+ assert_eq!(Filter::from_name(abbr), f);+ assert_eq!(f.name().as_bytes(), full);+ }+ assert_eq!(Filter::from_name(b"/JPXDecode"), Filter::Jpx);+ assert_eq!(Filter::from_name(b"JBIG2Decode"), Filter::Jbig2);+ assert_eq!(Filter::from_name(b"Crypt"), Filter::Crypt);+ assert_eq!(Filter::from_name(b"Foo"), Filter::Unknown("Foo".into()));+ assert_eq!(Filter::Unknown("Foo".into()).name(), "Foo");+ assert!(Filter::Dct.is_image_codec() && Filter::CcittFax.is_image_codec());+ assert!(!Filter::Flate.is_image_codec() && !Filter::Crypt.is_image_codec());+ }++ #[test]+ fn default_params() {+ let p = Params::default();+ assert_eq!((p.predictor, p.colors, p.bits_per_component, p.columns, p.early_change), (1, 1, 8, 1, 1));+ }++ #[test]+ fn unsupported_filters() {+ for f in [Filter::Dct, Filter::Jpx, Filter::Jbig2, Filter::CcittFax, Filter::Crypt, Filter::Unknown("X".into())] {+ let chain = [(Filter::AsciiHex, Params::default()), (f.clone(), Params::default())];+ assert!(matches!(decode(&chain, b"00>", 100), Err(FilterError::Unsupported(_))));+ assert!(matches!(decode_tolerant(&chain, b"00>", 100), Err(FilterError::Unsupported(_))));+ assert!(matches!(encode(&f, &Params::default(), b"x"), Err(FilterError::Unsupported(_))));+ }+ }++ #[test]+ fn empty_chain_is_identity() {+ assert_eq!(decode(&[], b"abc", 1).unwrap(), b"abc");+ }++ #[test]+ fn chain_ascii85_flate() {+ let data = b"Hello, chained filters! Hello, chained filters!".repeat(10);+ let z = encode_flate(&data);+ let a = encode(&Filter::Ascii85, &Params::default(), &z).unwrap();+ let chain = [(Filter::Ascii85, Params::default()), (Filter::Flate, Params::default())];+ assert_eq!(decode(&chain, &a, 1 << 20).unwrap(), data);+ }++ #[test]+ fn chain_three_filters_with_predictor() {+ let p = Params { predictor: 12, colors: 3, columns: 5, ..Params::default() };+ let data: Vec<u8> = (0..300u32).map(|i| (i * 7 % 251) as u8).collect();+ let lzw = encode(&Filter::Lzw, &p, &data).unwrap();+ let rl = encode(&Filter::RunLength, &Params::default(), &lzw).unwrap();+ let hex = encode(&Filter::AsciiHex, &Params::default(), &rl).unwrap();+ let chain = [(Filter::AsciiHex, Params::default()), (Filter::RunLength, Params::default()), (Filter::Lzw, p)];+ assert_eq!(decode(&chain, &hex, 1 << 20).unwrap(), data);+ }++ #[test]+ fn limit_applies_to_intermediate_buffers() {+ let hex = encode(&Filter::AsciiHex, &Params::default(), &[7u8; 100]).unwrap();+ let chain = [(Filter::AsciiHex, Params::default())];+ assert!(matches!(decode(&chain, &hex, 99), Err(FilterError::LimitExceeded(99))));+ assert_eq!(decode(&chain, &hex, 100).unwrap().len(), 100);+ }++ #[test]+ fn tolerant_flate_returns_partial() {+ let data: Vec<u8> = (0..20_000u32).map(|i| (i % 97) as u8 ^ (i / 300) as u8).collect();+ let mut z = encode_flate(&data);+ let cut = z.len() / 2;+ z.truncate(cut);+ let chain = [(Filter::Flate, Params::default())];+ assert!(matches!(decode(&chain, &z, 1 << 20), Err(FilterError::Corrupt { .. })));+ let (out, partial) = decode_tolerant(&chain, &z, 1 << 20).unwrap();+ assert!(partial);+ assert!(!out.is_empty() && out.len() < data.len());+ assert_eq!(&data[..out.len()], &out[..]);+ // Complete data is not partial.+ let (out, partial) = decode_tolerant(&chain, &encode_flate(&data), 1 << 20).unwrap();+ assert!(!partial);+ assert_eq!(out, data);+ }++ #[test]+ fn tolerant_partial_flows_through_predictor() {+ let p = Params { predictor: 12, columns: 4, ..Params::default() };+ let data: Vec<u8> = (0..4000u32).map(|i| (i * 31 % 256) as u8).collect();+ let mut z = encode(&Filter::Flate, &p, &data).unwrap();+ z.truncate(z.len() - 20);+ let (out, partial) = decode_tolerant(&[(Filter::Flate, p)], &z, 1 << 20).unwrap();+ assert!(partial);+ assert_eq!(&data[..out.len()], &out[..]);+ }+}diff --git a/crates/filters/src/lzw.rs b/crates/filters/src/lzw.rsnew file mode 100644index 000000000..9653ac2fb--- /dev/null+++ b/crates/filters/src/lzw.rs@@ -0,0 +1,314 @@+//! LZWDecode (ISO 32000-2 §7.4.4.2): variable-width codes of 9–12 bits, MSB first,+//! 256 = clear-table, 257 = EOD, first free code 258. With `EarlyChange` 1 (the+//! default) the code width grows one code early.+//!+//! Tolerated: data ending without EOD, a missing initial clear-table code, a table that+//! fills up without a clear-table code (entries are then no longer added).++use std::collections::HashMap;++use crate::{Failure, Step};++const NAME: &str = "LZWDecode";+const CLEAR: u16 = 256;+const EOD: u16 = 257;+const FIRST: usize = 258;+const TABLE: usize = 4096;+/// The encoder emits clear-table when its next free code reaches this value.+const ENCODER_RESET_AT: usize = TABLE;++/// The code width a decoder uses when its next free code is `next`.+fn width(next: usize, early: bool) -> u32 {+ match next + usize::from(early) {+ 0..512 => 9,+ 512..1024 => 10,+ 1024..2048 => 11,+ _ => 12,+ }+}++struct BitReader<'a> {+ data: &'a [u8],+ pos: usize,+ acc: u32,+ bits: u32,+}++impl BitReader<'_> {+ fn read(&mut self, n: u32) -> Option<u16> {+ while self.bits < n {+ let &b = self.data.get(self.pos)?;+ self.pos += 1;+ self.acc = (self.acc << 8) | u32::from(b);+ self.bits += 8;+ }+ self.bits -= n;+ let v = (self.acc >> self.bits) & ((1 << n) - 1);+ self.acc &= (1 << self.bits) - 1;+ Some(v as u16)+ }+}++pub(crate) fn decode(data: &[u8], early: bool, max: usize) -> Step {+ // Table entry = (prefix code, last byte, first byte, length).+ let mut prefix = vec![0u16; TABLE];+ let mut last = vec![0u8; TABLE];+ let mut first = vec![0u8; TABLE];+ let mut len = vec![0u16; TABLE];+ for i in 0..256 {+ last[i] = i as u8;+ first[i] = i as u8;+ len[i] = 1;+ }+ let mut next = FIRST;+ let mut w = 9;+ let mut prev: Option<usize> = None;+ let mut r = BitReader { data, pos: 0, acc: 0, bits: 0 };+ let mut out = Vec::with_capacity(data.len().saturating_mul(2).min(max));++ while let Some(code) = r.read(w) {+ match code {+ CLEAR => {+ next = FIRST;+ w = 9;+ prev = None;+ continue;+ }+ EOD => break,+ _ => {}+ }+ let code = usize::from(code);+ if let Some(p) = prev {+ let head = if code < next {+ first[code]+ } else if code == next && next < TABLE {+ first[p]+ } else {+ return Err(Failure::corrupt(NAME, format!("code {code} not in table (next {next})"), out));+ };+ if next < TABLE {+ prefix[next] = p as u16;+ last[next] = head;+ first[next] = first[p];+ len[next] = len[p] + 1;+ next += 1;+ }+ } else if code >= 256 {+ return Err(Failure::corrupt(NAME, format!("code {code} before any table entry"), out));+ }+ // Emit the string for `code`, walking the prefix chain backwards.+ let n = usize::from(len[code]);+ if out.len() + n > max {+ return Err(Failure::limit(max));+ }+ let start = out.len();+ out.resize(start + n, 0);+ let mut c = code;+ for slot in out[start..].iter_mut().rev() {+ *slot = last[c];+ c = usize::from(prefix[c]);+ }+ prev = Some(code);+ w = width(next, early);+ }+ Ok(out)+}++struct BitWriter {+ out: Vec<u8>,+ acc: u32,+ bits: u32,+}++impl BitWriter {+ fn write(&mut self, code: u16, n: u32) {+ self.acc = (self.acc << n) | u32::from(code);+ self.bits += n;+ while self.bits >= 8 {+ self.bits -= 8;+ self.out.push((self.acc >> self.bits) as u8);+ }+ self.acc &= (1 << self.bits) - 1;+ }++ fn finish(mut self) -> Vec<u8> {+ if self.bits > 0 {+ self.out.push((self.acc << (8 - self.bits)) as u8);+ }+ self.out+ }+}++/// Greedy LZW with a leading clear-table code and a trailing EOD.+pub(crate) fn encode(data: &[u8], early: bool) -> Vec<u8> {+ let mut wr = BitWriter { out: Vec::with_capacity(data.len() / 2 + 8), acc: 0, bits: 0 };+ let mut dict: HashMap<(u16, u8), u16> = HashMap::new();+ // `next` is the encoder's next free code; `dnext` mirrors the decoder's, which lags+ // one entry behind (the decoder adds an entry only once it sees the following code).+ let mut next = FIRST;+ let mut dnext = FIRST;+ let mut codes_since_clear = 0usize;+ wr.write(CLEAR, 9);+ let emit = |wr: &mut BitWriter, code: u16, dnext: &mut usize, since: &mut usize| {+ wr.write(code, width(*dnext, early));+ if *since > 0 && *dnext < TABLE {+ *dnext += 1;+ }+ *since += 1;+ };+ let Some((&b0, rest)) = data.split_first() else {+ wr.write(EOD, 9);+ return wr.finish();+ };+ let mut cur = u16::from(b0);+ for &b in rest {+ if let Some(&c) = dict.get(&(cur, b)) {+ cur = c;+ continue;+ }+ emit(&mut wr, cur, &mut dnext, &mut codes_since_clear);+ dict.insert((cur, b), next as u16);+ next += 1;+ if next == ENCODER_RESET_AT {+ wr.write(CLEAR, width(dnext, early));+ dict.clear();+ next = FIRST;+ dnext = FIRST;+ codes_since_clear = 0;+ }+ cur = u16::from(b);+ }+ emit(&mut wr, cur, &mut dnext, &mut codes_since_clear);+ wr.write(EOD, width(dnext, early));+ wr.finish()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::FilterError;++ fn dec(d: &[u8], early: bool) -> Result<Vec<u8>, FilterError> {+ decode(d, early, 1 << 26).map_err(|f| f.error)+ }++ /// ISO 32000-2 §7.4.4.2 example: codes 256 45 258 258 65 259 66 257.+ const SPEC_IN: [u8; 10] = [45, 45, 45, 45, 45, 65, 45, 45, 45, 66];+ const SPEC_OUT: [u8; 9] = [0x80, 0x0B, 0x60, 0x50, 0x22, 0x0C, 0x0C, 0x85, 0x01];++ #[test]+ fn spec_example() {+ assert_eq!(dec(&SPEC_OUT, true).unwrap(), SPEC_IN);+ assert_eq!(encode(&SPEC_IN, true), SPEC_OUT);+ // Below 511 codes the early-change setting makes no difference.+ assert_eq!(dec(&SPEC_OUT, false).unwrap(), SPEC_IN);+ }++ #[test]+ fn missing_eod_and_clear() {+ // Drop the EOD (last 9 bits span the final 2 bytes; keep bits for 66 only).+ let mut w = BitWriter { out: vec![], acc: 0, bits: 0 };+ for c in [45u16, 258, 258, 65, 259, 66] {+ w.write(c, 9);+ }+ assert_eq!(dec(&w.finish(), true).unwrap(), SPEC_IN);+ }++ #[test]+ fn invalid_codes() {+ let mut w = BitWriter { out: vec![], acc: 0, bits: 0 };+ for c in [256u16, 65, 300] {+ w.write(c, 9);+ }+ let f = decode(&w.finish(), true, 1000).err().unwrap();+ assert!(matches!(f.error, FilterError::Corrupt { .. }));+ assert_eq!(f.partial, b"A");+ let mut w = BitWriter { out: vec![], acc: 0, bits: 0 };+ w.write(258, 9);+ assert!(matches!(dec(&w.finish(), true), Err(FilterError::Corrupt { .. })));+ }++ #[test]+ fn widths() {+ assert_eq!((width(510, true), width(511, true), width(511, false), width(512, false)), (9, 10, 9, 10));+ assert_eq!((width(1022, true), width(1023, true), width(2047, true), width(4095, false)), (10, 11, 12, 12));+ }++ fn noisy(n: usize, seed: u32) -> Vec<u8> {+ let mut s = seed;+ (0..n)+ .map(|_| {+ s = s.wrapping_mul(1_103_515_245).wrapping_add(12_345);+ ((s >> 16) % 7) as u8 * 31+ })+ .collect()+ }++ #[test]+ fn all_widths_and_clears_round_trip() {+ for early in [false, true] {+ for data in [noisy(200_000, 1), (0..=255u8).cycle().take(70_000).collect(), vec![9u8; 100_000]] {+ let e = encode(&data, early);+ assert_eq!(dec(&e, early).unwrap(), data);+ }+ }+ }++ #[test]+ fn cross_check_with_weezl() {+ use weezl::BitOrder::Msb;+ for data in [noisy(150_000, 7), SPEC_IN.to_vec(), vec![]] {+ // early change 1 is the TIFF size switch; 0 is the plain variant.+ let tiff = weezl::encode::Encoder::with_tiff_size_switch(Msb, 8).encode(&data).unwrap();+ assert_eq!(dec(&tiff, true).unwrap(), data);+ let plain = weezl::encode::Encoder::new(Msb, 8).encode(&data).unwrap();+ assert_eq!(dec(&plain, false).unwrap(), data);+ let ours = encode(&data, true);+ assert_eq!(weezl::decode::Decoder::with_tiff_size_switch(Msb, 8).decode(&ours).unwrap(), data);+ let ours = encode(&data, false);+ assert_eq!(weezl::decode::Decoder::new(Msb, 8).decode(&ours).unwrap(), data);+ }+ }++ #[test]+ fn full_table_without_clear() {+ // Hand-roll a stream that fills the table and keeps going at 12 bits.+ let data = noisy(40_000, 3);+ let mut w = BitWriter { out: vec![], acc: 0, bits: 0 };+ let mut dict: HashMap<Vec<u8>, u16> = (0..=255u8).map(|b| (vec![b], u16::from(b))).collect();+ let (mut next, mut dnext, mut since) = (FIRST, FIRST, 0usize);+ let mut cur: Vec<u8> = vec![];+ let mut put = |w: &mut BitWriter, code: u16, dnext: &mut usize| {+ w.write(code, width(*dnext, true));+ if since > 0 && *dnext < TABLE {+ *dnext += 1;+ }+ since += 1;+ };+ w.write(CLEAR, 9);+ for &b in &data {+ let mut ext = cur.clone();+ ext.push(b);+ if dict.contains_key(&ext) {+ cur = ext;+ continue;+ }+ put(&mut w, dict[&cur], &mut dnext);+ if next < TABLE {+ dict.insert(ext, next as u16);+ next += 1;+ }+ cur = vec![b];+ }+ put(&mut w, dict[&cur], &mut dnext);+ w.write(EOD, width(dnext, true));+ assert_eq!(dec(&w.finish(), true).unwrap(), data);+ }++ #[test]+ fn limit() {+ let e = encode(&vec![0u8; 100_000], true);+ assert!(matches!(decode(&e, true, 50_000).map_err(|f| f.error), Err(FilterError::LimitExceeded(50_000))));+ assert_eq!(decode(&e, true, 100_000).ok().unwrap().len(), 100_000);+ }+}diff --git a/crates/filters/src/predictor.rs b/crates/filters/src/predictor.rsnew file mode 100644index 000000000..f9348941b--- /dev/null+++ b/crates/filters/src/predictor.rs@@ -0,0 +1,332 @@+//! Predictor functions for FlateDecode and LZWDecode (ISO 32000-2 §7.4.4.4).+//!+//! - Predictor 2: TIFF 6.0 horizontal differencing (Section 14), per component, for+//! 1, 2, 4, 8 and 16 bits per component.+//! - Predictors 10–15: PNG filters (RFC 2083 §6): each row carries its own filter-type+//! byte (0 None, 1 Sub, 2 Up, 3 Average, 4 Paeth), whatever the predictor value is.+//!+//! A final partial row is decoded as far as its data goes.++use crate::{Failure, FilterError, Params, Step};++struct Layout {+ bpc: usize,+ colors: usize,+ /// Bytes per complete pixel, at least 1 (the PNG `bpp`).+ bpp: usize,+ /// Bytes per row (without the PNG tag byte).+ row: usize,+ /// Samples per row (colors × columns).+ samples: usize,+}++fn layout(p: &Params) -> Result<Layout, String> {+ let bpc = match p.bits_per_component {+ b @ (1 | 2 | 4 | 8 | 16) => b as usize,+ b => return Err(format!("invalid BitsPerComponent {b}")),+ };+ if !(1..=255).contains(&p.colors) {+ return Err(format!("invalid Colors {}", p.colors));+ }+ if p.columns < 1 {+ return Err(format!("invalid Columns {}", p.columns));+ }+ let colors = p.colors as usize;+ let samples = usize::try_from(p.columns).ok().and_then(|c| c.checked_mul(colors)).ok_or_else(|| format!("Columns {} too large", p.columns))?;+ let bits = samples.checked_mul(bpc).ok_or_else(|| format!("Columns {} too large", p.columns))?;+ Ok(Layout { bpc, colors, bpp: (colors * bpc).div_ceil(8), row: bits.div_ceil(8), samples })+}++/// Undoes the predictor named by `p.predictor` (1 = identity).+pub(crate) fn decode(p: &Params, data: Vec<u8>, name: &'static str) -> Step {+ match p.predictor {+ 1 => Ok(data),+ 2 | 10..=15 => {+ let l = layout(p).map_err(|e| Failure::corrupt(name, e, Vec::new()))?;+ if p.predictor == 2 { Ok(tiff_decode(&l, data)) } else { png_decode(&l, &data, name) }+ }+ other => Err(Failure::corrupt(name, format!("invalid Predictor {other}"), Vec::new())),+ }+}++/// Applies the predictor named by `p.predictor` (1 = identity; 15 = per-row optimum).+pub(crate) fn encode(p: &Params, data: &[u8]) -> Result<Vec<u8>, FilterError> {+ match p.predictor {+ 1 => Ok(data.to_vec()),+ 2 | 10..=15 => {+ let l = layout(p).map_err(FilterError::Unsupported)?;+ Ok(if p.predictor == 2 { tiff_encode(&l, data) } else { png_encode(&l, data, p.predictor) })+ }+ other => Err(FilterError::Unsupported(format!("Predictor {other}"))),+ }+}++// ---- TIFF predictor 2 ----++fn get(row: &[u8], i: usize, bpc: usize) -> u16 {+ match bpc {+ 16 => u16::from_be_bytes([row[2 * i], row[2 * i + 1]]),+ 8 => u16::from(row[i]),+ _ => {+ let bit = i * bpc;+ let shift = 8 - bpc - bit % 8;+ u16::from(row[bit / 8] >> shift) & ((1 << bpc) - 1)+ }+ }+}++fn set(row: &mut [u8], i: usize, bpc: usize, v: u16) {+ match bpc {+ 16 => row[2 * i..2 * i + 2].copy_from_slice(&v.to_be_bytes()),+ 8 => row[i] = v as u8,+ _ => {+ let bit = i * bpc;+ let shift = 8 - bpc - bit % 8;+ let mask = (((1u16 << bpc) - 1) << shift) as u8;+ row[bit / 8] = (row[bit / 8] & !mask) | (((v << shift) as u8) & mask);+ }+ }+}++/// Complete samples available in a (possibly partial) row.+fn samples_in(l: &Layout, row_len: usize) -> usize {+ (row_len * 8 / l.bpc).min(l.samples)+}++fn tiff_decode(l: &Layout, mut data: Vec<u8>) -> Vec<u8> {+ let mask = if l.bpc == 16 { u16::MAX } else { (1u16 << l.bpc) - 1 };+ for row in data.chunks_mut(l.row) {+ for i in l.colors..samples_in(l, row.len()) {+ let v = get(row, i, l.bpc).wrapping_add(get(row, i - l.colors, l.bpc)) & mask;+ set(row, i, l.bpc, v);+ }+ }+ data+}++fn tiff_encode(l: &Layout, data: &[u8]) -> Vec<u8> {+ let mask = if l.bpc == 16 { u16::MAX } else { (1u16 << l.bpc) - 1 };+ let mut out = data.to_vec();+ for row in out.chunks_mut(l.row) {+ // Descending, so the left neighbour still holds its original value.+ for i in (l.colors..samples_in(l, row.len())).rev() {+ let v = get(row, i, l.bpc).wrapping_sub(get(row, i - l.colors, l.bpc)) & mask;+ set(row, i, l.bpc, v);+ }+ }+ out+}++// ---- PNG predictors ----++fn paeth(a: u8, b: u8, c: u8) -> u8 {+ let p = i16::from(a) + i16::from(b) - i16::from(c);+ let (pa, pb, pc) = ((p - i16::from(a)).abs(), (p - i16::from(b)).abs(), (p - i16::from(c)).abs());+ if pa <= pb && pa <= pc {+ a+ } else if pb <= pc {+ b+ } else {+ c+ }+}++/// The PNG predictor value for byte `i` given the reconstructed current row `cur`+/// (bytes before `i`) and the prior row `up`.+fn predict(tag: u8, cur: &[u8], up: &[u8], i: usize, bpp: usize) -> u8 {+ let a = if i >= bpp { cur[i - bpp] } else { 0 };+ let b = up[i];+ let c = if i >= bpp { up[i - bpp] } else { 0 };+ match tag {+ 1 => a,+ 2 => b,+ 3 => ((u16::from(a) + u16::from(b)) / 2) as u8,+ 4 => paeth(a, b, c),+ _ => 0,+ }+}++fn png_decode(l: &Layout, data: &[u8], name: &'static str) -> Step {+ let mut out = Vec::with_capacity(data.len());+ // The prior row: never longer than the input, even for absurd Columns values.+ let mut up = vec![0u8; l.row.min(data.len())];+ for chunk in data.chunks(l.row.saturating_add(1)) {+ let (tag, src) = (chunk[0], &chunk[1..]);+ if tag > 4 {+ return Err(Failure::corrupt(name, format!("invalid PNG filter type {tag}"), out));+ }+ let start = out.len();+ for (i, &x) in src.iter().enumerate() {+ let pred = predict(tag, &out[start..], &up, i, l.bpp);+ out.push(x.wrapping_add(pred));+ }+ up[..src.len()].copy_from_slice(&out[start..]);+ }+ Ok(out)+}++fn png_filter(tag: u8, cur: &[u8], up: &[u8], bpp: usize, dst: &mut Vec<u8>) {+ dst.clear();+ dst.push(tag);+ dst.extend(cur.iter().enumerate().map(|(i, &x)| x.wrapping_sub(predict(tag, cur, up, i, bpp))));+}++/// Sum of residuals as signed bytes: the usual heuristic for choosing a PNG filter.+fn cost(filtered: &[u8]) -> u64 {+ filtered[1..].iter().map(|&b| u64::from((b as i8).unsigned_abs())).sum()+}++fn png_encode(l: &Layout, data: &[u8], predictor: i64) -> Vec<u8> {+ let rows = data.len().div_ceil(l.row.max(1));+ let mut out = Vec::with_capacity(data.len() + rows);+ let zeros = vec![0u8; l.row.min(data.len())];+ let (mut best, mut trial) = (Vec::new(), Vec::new());+ let mut up: &[u8] = &zeros;+ for cur in data.chunks(l.row) {+ let up_row = &up[..cur.len()];+ if predictor == 15 {+ png_filter(0, cur, up_row, l.bpp, &mut best);+ let mut best_cost = cost(&best);+ for tag in 1..=4 {+ png_filter(tag, cur, up_row, l.bpp, &mut trial);+ let c = cost(&trial);+ if c < best_cost {+ best_cost = c;+ std::mem::swap(&mut best, &mut trial);+ }+ }+ } else {+ png_filter((predictor - 10) as u8, cur, up_row, l.bpp, &mut best);+ }+ out.extend_from_slice(&best);+ up = cur;+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn p(predictor: i64, colors: i64, bpc: i64, columns: i64) -> Params {+ Params { predictor, colors, bits_per_component: bpc, columns, early_change: 1 }+ }++ fn dec(params: &Params, data: &[u8]) -> Result<Vec<u8>, FilterError> {+ decode(params, data.to_vec(), "FlateDecode").map_err(|f| f.error)+ }++ #[test]+ fn png_hand_vectors() {+ // 3 columns, 1 color, 8 bpc. Rows: None, Sub, Up, Average, Paeth.+ let enc = [+ 0, 10, 20, 30, // None -> 10 20 30+ 1, 5, 1, 1, // Sub -> 5 6 7+ 2, 1, 1, 1, // Up -> 6 7 8+ 3, 10, 10, 10, // Avg -> 10+3=13, 10+(13+7)/2=20, 10+(20+8)/2=24+ 4, 1, 1,+ 1, // Paeth: a=0,b=13,c=0 -> p=13 -> b: 14; a=14,b=20,c=13: p=21 -> pa=7,pb=1,pc=8 -> b: 21;+ // a=21,b=24,c=20: p=25 -> pa=4,pb=1,pc=5 -> b: 25+ ];+ let out = dec(&p(15, 1, 8, 3), &enc).unwrap();+ assert_eq!(out, [10, 20, 30, 5, 6, 7, 6, 7, 8, 13, 20, 24, 14, 21, 25]);+ }++ #[test]+ fn paeth_tie_breaks() {+ // RFC 2083 order: a, then b, then c.+ assert_eq!(paeth(1, 1, 1), 1);+ assert_eq!(paeth(10, 20, 15), 15); // p=15: pa=5 pb=5 pc=0 -> c+ assert_eq!(paeth(20, 10, 10), 20); // p=20: pa=0 -> a+ assert_eq!(paeth(5, 9, 7), 7); // p=7: pa=2 pb=2 pc=0 -> c+ }++ #[test]+ fn png_multibyte_pixels() {+ // colors=3 bpc=16 -> bpp=6; 1 column; Sub on the first pixel uses a=0 throughout.+ let enc = [1, 1, 2, 3, 4, 5, 6, 2, 1, 1, 1, 1, 1, 1];+ let out = dec(&p(11, 3, 16, 1), &enc).unwrap();+ assert_eq!(out, [1, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 7]);+ // colors=3 bpc=8, 2 columns: Sub looks 3 bytes back.+ let enc = [1, 1, 2, 3, 1, 1, 1];+ assert_eq!(dec(&p(11, 3, 8, 2), &enc).unwrap(), [1, 2, 3, 2, 3, 4]);+ }++ #[test]+ fn png_partial_final_row() {+ let enc = [0, 1, 2, 3, 4, 2, 1, 1];+ assert_eq!(dec(&p(12, 1, 8, 4), &enc).unwrap(), [1, 2, 3, 4, 2, 3]);+ // A lone tag byte at the end yields nothing.+ assert_eq!(dec(&p(12, 1, 8, 4), &[0, 1, 2, 3, 4, 2]).unwrap(), [1, 2, 3, 4]);+ }++ #[test]+ fn png_invalid_tag() {+ let r = decode(&p(10, 1, 8, 2), vec![0, 1, 2, 5, 1, 1], "FlateDecode");+ let f = r.err().unwrap();+ assert!(matches!(f.error, FilterError::Corrupt { .. }));+ assert_eq!(f.partial, [1, 2]);+ }++ #[test]+ fn tiff_8bit() {+ // 2 colors, 3 columns: differences per component.+ let enc = [10, 20, 1, 2, 3, 4, /* row 2 */ 5, 5, 250, 10, 1, 1];+ assert_eq!(dec(&p(2, 2, 8, 3), &enc).unwrap(), [10, 20, 11, 22, 14, 26, 5, 5, 255, 15, 0, 16]);+ }++ #[test]+ fn tiff_16bit() {+ let enc = [0x01, 0x00, 0xff, 0xff, 0x00, 0x02];+ assert_eq!(dec(&p(2, 1, 16, 3), &enc).unwrap(), [0x01, 0x00, 0x00, 0xff, 0x01, 0x01]);+ }++ #[test]+ fn tiff_sub_byte() {+ // 1 bpc, 1 color, 10 columns: bits 1 0 0 1 1 0 0 0 | 1 1 (pad 000000)+ // Cumulative XOR: 1 1 1 0 1 1 1 1 | 0 1+ let enc = [0b1001_1000, 0b1100_0000];+ assert_eq!(dec(&p(2, 1, 1, 10), &enc).unwrap(), [0b1110_1111, 0b0100_0000]);+ // 4 bpc, 1 color, 3 columns: samples 5, 15, 3 -> 5, 4, 7 (mod 16).+ assert_eq!(dec(&p(2, 1, 4, 3), &[0x5f, 0x30]).unwrap(), [0x54, 0x70]);+ // 2 bpc, 2 colors, 2 columns: samples 1 2 3 3 -> 1 2 0 1.+ assert_eq!(dec(&p(2, 2, 2, 2), &[0b0110_1111]).unwrap(), [0b0110_0001]);+ // Padding bits are left alone.+ assert_eq!(dec(&p(2, 1, 4, 1), &[0x5f]).unwrap(), [0x5f]);+ }++ #[test]+ fn tiff_partial_rows() {+ // 16-bit with an odd trailing byte: the lone byte is left as is.+ assert_eq!(dec(&p(2, 1, 16, 4), &[0, 1, 0, 1, 9]).unwrap(), [0, 1, 0, 2, 9]);+ assert_eq!(dec(&p(2, 1, 8, 4), &[1, 1, 1, 1, 2, 2]).unwrap(), [1, 2, 3, 4, 2, 4]);+ }++ #[test]+ fn invalid_params() {+ for bad in [p(2, 1, 3, 1), p(12, 0, 8, 1), p(12, 1, 8, 0), p(3, 1, 8, 1), p(12, 1, 8, i64::MAX), p(2, 300, 8, 1)] {+ assert!(matches!(dec(&bad, &[0, 1, 2]), Err(FilterError::Corrupt { .. })), "{bad:?}");+ assert!(encode(&bad, &[1, 2]).is_err());+ }+ // Huge but representable Columns does not allocate a huge row.+ assert_eq!(dec(&p(12, 1, 8, 1 << 40), &[2, 7, 8]).unwrap(), [7, 8]);+ }++ #[test]+ fn encode_choices() {+ let data = [1u8, 2, 3, 4, 5, 6];+ let up = encode(&p(12, 1, 8, 3), &data).unwrap();+ assert_eq!(up, [2, 1, 2, 3, 2, 3, 3, 3]);+ let paeth = encode(&p(14, 1, 8, 3), &data).unwrap();+ assert_eq!(paeth[0], 4);+ assert_eq!(paeth[4], 4);+ // Per-row optimum picks Sub for a ramp.+ let ramp: Vec<u8> = (0..64).collect();+ let opt = encode(&p(15, 1, 8, 64), &ramp).unwrap();+ assert_eq!(opt[0], 1);+ for pred in [10, 11, 12, 13, 14, 15] {+ let e = encode(&p(pred, 1, 8, 3), &data).unwrap();+ assert_eq!(dec(&p(pred, 1, 8, 3), &e).unwrap(), data);+ }+ }+}diff --git a/crates/filters/src/runlength.rs b/crates/filters/src/runlength.rsnew file mode 100644index 000000000..e77b619f9--- /dev/null+++ b/crates/filters/src/runlength.rs@@ -0,0 +1,117 @@+//! RunLengthDecode (ISO 32000-2 §7.4.5): a length byte L of 0–127 copies the next+//! L + 1 bytes, 129–255 repeats the next byte 257 − L times, 128 is EOD.+//! A missing EOD is tolerated; a truncated run is corrupt.++use crate::{Failure, Step};++const NAME: &str = "RunLengthDecode";++pub(crate) fn decode(data: &[u8], max: usize) -> Step {+ let mut out = Vec::with_capacity(data.len().saturating_mul(2).min(max));+ let mut i = 0;+ while let Some(&l) = data.get(i) {+ i += 1;+ match l {+ 128 => break,+ 0..=127 => {+ let n = usize::from(l) + 1;+ let avail = n.min(data.len() - i);+ if out.len() + avail > max {+ return Err(Failure::limit(max));+ }+ out.extend_from_slice(&data[i..i + avail]);+ i += avail;+ if avail < n {+ return Err(Failure::corrupt(NAME, "truncated literal run", out));+ }+ }+ _ => {+ let Some(&b) = data.get(i) else {+ return Err(Failure::corrupt(NAME, "truncated repeat run", out));+ };+ i += 1;+ let n = 257 - usize::from(l);+ if out.len() + n > max {+ return Err(Failure::limit(max));+ }+ out.resize(out.len() + n, b);+ }+ }+ }+ Ok(out)+}++pub(crate) fn encode(data: &[u8]) -> Vec<u8> {+ let mut out = Vec::with_capacity(data.len() + data.len() / 128 + 2);+ let n = data.len();+ let mut i = 0;+ while i < n {+ let mut run = 1;+ while i + run < n && run < 128 && data[i + run] == data[i] {+ run += 1;+ }+ if run >= 2 {+ out.push((257 - run) as u8);+ out.push(data[i]);+ i += run;+ continue;+ }+ // Literal: extend until a repeat begins or 128 bytes.+ let start = i;+ let mut j = i + 1;+ while j < n && j - start < 128 && !(j + 1 < n && data[j] == data[j + 1]) {+ j += 1;+ }+ out.push((j - start - 1) as u8);+ out.extend_from_slice(&data[start..j]);+ i = j;+ }+ out.push(128);+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::FilterError;++ fn dec(d: &[u8]) -> Result<Vec<u8>, FilterError> {+ decode(d, 10_000).map_err(|f| f.error)+ }++ #[test]+ fn vectors() {+ assert_eq!(dec(&[2, b'a', b'b', b'c', 254, b'x', 128]).unwrap(), b"abcxxx");+ assert_eq!(dec(&[129, 7, 128]).unwrap(), [7; 128]);+ assert!(dec(&[127]).is_err());+ assert_eq!(dec(&[0, b'q']).unwrap(), b"q"); // missing EOD+ assert_eq!(dec(&[128, 0, b'q']).unwrap(), b""); // data after EOD ignored+ assert_eq!(dec(&[]).unwrap(), b"");+ }++ #[test]+ fn truncated() {+ let f = decode(&[4, b'a', b'b'], 100).err().unwrap();+ assert!(matches!(f.error, FilterError::Corrupt { .. }));+ assert_eq!(f.partial, b"ab");+ assert!(matches!(dec(&[0, b'a', 200]), Err(FilterError::Corrupt { .. })));+ }++ #[test]+ fn limit() {+ assert!(matches!(decode(&[129, 0, 129, 0], 200).map_err(|f| f.error), Err(FilterError::LimitExceeded(200))));+ assert!(matches!(decode(&[3, 1, 2, 3, 4], 3).map_err(|f| f.error), Err(FilterError::LimitExceeded(3))));+ assert_eq!(decode(&[129, 0, 129, 0], 256).ok().unwrap().len(), 256);+ }++ #[test]+ fn encoding() {+ assert_eq!(encode(b"abcxxx"), [2, b'a', b'b', b'c', 254, b'x', 128]);+ assert_eq!(encode(b""), [128]);+ assert_eq!(encode(&[5; 300]), [129, 5, 129, 5, 213, 5, 128]);+ let lit: Vec<u8> = (0..200u8).collect();+ let e = encode(&lit);+ assert_eq!((e[0], e[129]), (127, 71));+ assert_eq!(dec(&e).unwrap(), lit);+ }+}diff --git a/crates/filters/tests/proptests.proptest-regressions b/crates/filters/tests/proptests.proptest-regressionsnew file mode 100644index 000000000..0b9bbac5c--- /dev/null+++ b/crates/filters/tests/proptests.proptest-regressions@@ -0,0 +1,7 @@+# Seeds for failure cases proptest has generated in the past. It is+# automatically read and these particular cases re-run before any+# novel cases are generated.+#+# It is recommended to check this file in to source control so that+# everyone who runs the test benefits from these saved cases.+cc 690714485bf1c84d6f7788b0205b5d62942b9774699a364161224381ebb08f22 # shrinks to filter = Flate, params = Params { predictor: 10, colors: 1, bits_per_component: 1, columns: 1, early_change: 0 }, data = [74, 4, 40, 11, 72, 5, 123, 154, 191, 76, 212, 154, 73, 3, 113, 92, 51, 190, 160, 141, 12, 106, 83, 206, 91, 214, 202, 23, 39, 151, 117, 114, 220, 76, 204, 235, 186, 176, 80, 229, 63, 79, 67, 63, 177, 94, 142, 223, 140, 248, 1, 203, 157, 88, 175, 77, 69, 155, 159, 152, 47, 216, 81, 234, 169, 144, 235, 202, 75, 191, 233, 128, 225, 162, 96, 126, 245, 57, 135, 167, 184, 53, 138, 215, 153, 248, 165, 18, 81, 128, 44, 139, 223, 76, 191, 58, 137, 48, 93, 14, 80, 58, 30, 63, 40, 235, 68, 159, 137, 113, 123, 24, 150, 84, 78, 190, 207, 36, 189, 220, 192, 161, 121, 179, 1, 242, 152, 205, 64, 67, 50, 245, 94, 185, 81, 132, 27, 25, 122, 7, 223, 178, 147, 70, 27, 130, 226, 217, 54, 87, 112, 14, 196, 133, 193, 27, 147, 30, 38, 182, 108, 72, 75, 107, 113, 244, 65, 9, 62, 11, 66, 234, 146, 180, 56, 85, 170, 255, 38, 37, 159, 48, 3, 159, 125, 230, 34, 110, 7, 58, 92, 66, 14, 29, 50, 98, 56, 228, 118, 243, 32, 99, 158, 252, 246, 249, 185, 106, 11, 127, 218, 104, 216, 204, 23, 59, 85, 34, 123, 28, 253, 14, 147, 201, 205, 176, 60, 39, 249, 143, 205, 190, 183, 83, 27, 213, 23, 225, 172, 43, 225, 31, 62, 205, 53, 88, 202, 200, 75, 152, 252, 105, 20, 95, 20, 0, 229, 170, 23, 222, 252, 208, 41, 206, 133, 167, 41, 89, 208, 136, 98, 203, 93, 112, 18, 75, 54, 217, 191, 163, 165, 88, 137, 203, 7, 66, 218, 184, 251, 48, 25, 144, 29, 183, 119, 101, 192, 234, 116, 81, 211, 255, 22, 16, 20, 36, 190, 253, 73, 246, 9, 141, 99, 90, 178, 252, 93, 112, 233, 213, 42, 127, 227, 208, 125, 129, 41, 99, 111, 228, 123, 106, 131, 39, 204, 158, 18, 6, 221, 168, 135, 60, 107, 156, 254, 93, 255, 163, 34, 142, 110, 16, 207, 84, 243, 180, 145, 42, 240, 252, 64, 53, 225, 211, 231, 255, 215, 221, 181, 69, 8, 59, 134, 254, 98, 16, 157, 100, 115, 145, 190, 115, 49, 153, 255, 242, 159, 248, 37, 192, 48, 133, 42, 158, 35, 111, 7, 101, 1, 12, 131, 117, 149, 23, 224, 80, 101, 146, 235, 24, 214, 166, 254, 39, 121, 65, 109, 7, 115, 4, 126, 238, 207, 122, 72, 78, 170, 80, 239, 13, 233, 101, 110, 101, 121, 219, 159, 194, 78, 33, 198, 239, 149, 64, 6, 105, 138, 106, 34, 82, 253, 66, 74, 219, 101, 247, 133, 23, 140, 254, 221, 164, 77, 66, 28, 202, 253, 230, 152, 200, 164, 143, 126, 92, 231, 72, 120, 249, 230, 119, 24, 109, 185, 137, 26, 206, 91, 90, 76, 140, 134, 137, 67, 83, 52, 105, 135, 184, 180, 231, 213, 190, 252, 144, 129, 85, 96, 4, 62, 70, 197, 73, 164, 61, 209, 150, 227, 138, 92, 25, 117, 84, 161, 81, 247, 94, 53, 207, 93, 59, 223, 222, 87, 255, 216, 219, 143, 36, 255, 131, 117, 9, 30, 144, 196, 209, 139, 253, 187, 193, 126, 243, 21, 66, 19, 226, 95, 166, 245, 11, 63, 220, 30, 55, 255, 172, 108, 87, 187, 2, 3, 242, 243, 175, 134, 88, 128, 97, 68, 102, 241, 94, 109, 219, 219, 6, 38, 155, 249, 194, 33, 175, 48, 141, 41, 82, 186, 85, 232, 157, 160, 145, 233, 103, 190, 239, 106, 247, 241, 11, 216, 90, 56, 154, 18, 119, 33, 181, 109, 145, 80, 158, 51, 129, 150, 147, 255, 14, 135, 86, 62, 250, 84, 8, 235, 237, 246, 227, 137, 112, 175, 239, 226, 182, 92, 188, 236, 254, 87, 49, 18, 208, 139, 48, 200, 151, 201, 196, 182, 182], max = 1319diff --git a/crates/filters/tests/proptests.rs b/crates/filters/tests/proptests.rsnew file mode 100644index 000000000..a4300e68a--- /dev/null+++ b/crates/filters/tests/proptests.rs@@ -0,0 +1,150 @@+//! Round-trip property tests (encode → decode) for every encodable filter and predictor,+//! and fuzz-style tests feeding arbitrary bytes and parameters to every decoder.++use printcraft_filters::{Filter, FilterError, Params, decode, decode_tolerant, encode};+use proptest::prelude::*;++const MAX: usize = 1 << 24;++fn encodable() -> impl Strategy<Value = Filter> {+ prop_oneof![Just(Filter::Flate), Just(Filter::Lzw), Just(Filter::AsciiHex), Just(Filter::Ascii85), Just(Filter::RunLength),]+}++fn any_filter() -> impl Strategy<Value = Filter> {+ prop_oneof![+ encodable(),+ Just(Filter::Dct),+ Just(Filter::Jpx),+ Just(Filter::Jbig2),+ Just(Filter::CcittFax),+ Just(Filter::Crypt),+ Just(Filter::Unknown("Foo".into())),+ ]+}++fn valid_params() -> impl Strategy<Value = Params> {+ (prop::sample::select(vec![1i64, 2, 10, 11, 12, 13, 14, 15]), 1i64..=5, prop::sample::select(vec![1i64, 2, 4, 8, 16]), 1i64..=40, 0i64..=1)+ .prop_map(|(predictor, colors, bits_per_component, columns, early_change)| Params {+ predictor,+ colors,+ bits_per_component,+ columns,+ early_change,+ })+}++/// Anything, including nonsense values.+fn wild_params() -> impl Strategy<Value = Params> {+ let wild = prop_oneof![Just(i64::MIN), Just(i64::MAX), Just(-1i64), Just(0i64), 0i64..=40, any::<i64>()];+ (+ prop_oneof![valid_params().prop_map(|p| p.predictor), wild.clone()],+ prop_oneof![1i64..=5, wild.clone()],+ prop_oneof![Just(8i64), Just(16), Just(1), wild.clone()],+ prop_oneof![1i64..=40, wild.clone()],+ wild,+ )+ .prop_map(|(predictor, colors, bits_per_component, columns, early_change)| Params {+ predictor,+ colors,+ bits_per_component,+ columns,+ early_change,+ })+}++/// Low-entropy data (so LZW/Flate/RunLength exercise their repeat paths) mixed with noise.+fn data() -> impl Strategy<Value = Vec<u8>> {+ prop_oneof![prop::collection::vec(any::<u8>(), 0..2000), prop::collection::vec(prop::sample::select(vec![0u8, 1, 7, 255]), 0..6000),]+}++proptest! {+ #[test]+ fn round_trip(filter in encodable(), params in valid_params(), data in data()) {+ let enc = encode(&filter, ¶ms, &data).unwrap();+ let chain = [(filter, params)];+ prop_assert_eq!(&decode(&chain, &enc, MAX).unwrap(), &data);+ let (out, partial) = decode_tolerant(&chain, &enc, MAX).unwrap();+ prop_assert!(!partial);+ prop_assert_eq!(&out, &data);+ }++ #[test]+ fn round_trip_chain(a in encodable(), b in encodable(), params in valid_params(), data in data()) {+ let inner = encode(&b, ¶ms, &data).unwrap();+ let outer = encode(&a, &Params::default(), &inner).unwrap();+ let chain = [(a, Params::default()), (b, params)];+ prop_assert_eq!(decode(&chain, &outer, MAX).unwrap(), data);+ }++ #[test]+ fn lzw_long_round_trip(early in 0i64..=1, data in prop::collection::vec(0u8..4, 20_000..60_000)) {+ let p = Params { early_change: early, ..Params::default() };+ let enc = encode(&Filter::Lzw, &p, &data).unwrap();+ prop_assert_eq!(decode(&[(Filter::Lzw, p)], &enc, MAX).unwrap(), data);+ }++ #[test]+ fn output_limit_is_respected(filter in encodable(), params in valid_params(), data in data(), max in 0usize..3000) {+ let enc = encode(&filter, ¶ms, &data).unwrap();+ // PNG predictors add a tag byte per row to the intermediate (pre-predictor) buffer.+ let png = matches!(filter, Filter::Flate | Filter::Lzw) && params.predictor >= 10;+ let row = (params.colors * params.bits_per_component * params.columns + 7) as usize / 8;+ let intermediate = if png { data.len() + data.len().div_ceil(row) } else { data.len() };+ match decode(&[(filter, params)], &enc, max) {+ Ok(out) => prop_assert!(out.len() <= max && out == data),+ Err(FilterError::LimitExceeded(m)) => prop_assert!(m == max && intermediate > max),+ Err(e) => prop_assert!(false, "unexpected {e}"),+ }+ }++ #[test]+ fn decoders_never_panic(+ chain in prop::collection::vec((any_filter(), wild_params()), 0..4),+ data in prop::collection::vec(any::<u8>(), 0..3000),+ max in prop_oneof![Just(0usize), 1usize..100_000],+ ) {+ if let Ok(out) = decode(&chain, &data, max) {+ prop_assert!(out.len() <= max || chain.is_empty());+ }+ if let Ok((out, _)) = decode_tolerant(&chain, &data, max) {+ prop_assert!(out.len() <= max || chain.is_empty());+ }+ }++ #[test]+ fn single_decoders_never_panic(filter in encodable(), params in wild_params(), data in prop::collection::vec(any::<u8>(), 0..3000)) {+ let chain = [(filter, params)];+ let _ = decode(&chain, &data, 1 << 20);+ let _ = decode_tolerant(&chain, &data, 1 << 20);+ }++ #[test]+ fn encoders_never_panic(filter in any_filter(), params in wild_params(), data in prop::collection::vec(any::<u8>(), 0..2000)) {+ if let Ok(enc) = encode(&filter, ¶ms, &data) {+ prop_assert_eq!(decode(&[(filter, params)], &enc, MAX).unwrap(), data);+ }+ }++ #[test]+ fn mutated_streams_never_panic(filter in encodable(), params in valid_params(), data in data(), flips in prop::collection::vec((any::<prop::sample::Index>(), any::<u8>()), 1..8)) {+ let mut enc = encode(&filter, ¶ms, &data).unwrap();+ for (i, x) in flips {+ if !enc.is_empty() {+ let k = i.index(enc.len());+ enc[k] ^= x;+ }+ }+ let chain = [(filter, params)];+ let _ = decode(&chain, &enc, 1 << 20);+ let _ = decode_tolerant(&chain, &enc, 1 << 20);+ }+}++#[test]+fn flate_bomb_in_chain() {+ let bomb = printcraft_filters::encode_flate(&vec![0u8; 32 << 20]);+ let a85 = encode(&Filter::Ascii85, &Params::default(), &bomb).unwrap();+ let chain = [(Filter::Ascii85, Params::default()), (Filter::Flate, Params::default())];+ assert!(matches!(decode(&chain, &a85, 1 << 20), Err(FilterError::LimitExceeded(_))));+ assert!(matches!(decode_tolerant(&chain, &a85, 1 << 20), Err(FilterError::LimitExceeded(_))));+}diff --git a/crates/organize/Cargo.toml b/crates/organize/Cargo.tomlnew file mode 100644index 000000000..46fb417e9--- /dev/null+++ b/crates/organize/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "printcraft-organize"+description = "Page and document-structure edits: rotate, delete, move, insert pages; document info"+version.workspace = true+edition.workspace = true+license.workspace = true++[lints]+workspace = true++[dependencies]+printcraft-cos = { workspace = true }+thiserror = { workspace = true }++[dev-dependencies]+hayro-syntax = { workspace = true }diff --git a/crates/organize/src/lib.rs b/crates/organize/src/lib.rsnew file mode 100644index 000000000..e59a8af81--- /dev/null+++ b/crates/organize/src/lib.rs@@ -0,0 +1,214 @@+//! printcraft-organize — page and document-structure edits (L4).+//!+//! Every operation mutates a `printcraft_cos::Document` (copy-on-write), so callers snapshot the+//! document before an edit for undo. Operations never drop data they do not understand.+//!+//! Page-tree strategy: before restructuring, inheritable page attributes (`Resources`,+//! `MediaBox`, `CropBox`, `Rotate` — ISO 32000-2 §7.7.3.4) are copied onto each page, then the+//! tree is rebuilt as a single flat `/Pages` node. Intermediate nodes become unreachable (a full+//! save drops them; an incremental save leaves them untouched). Flat trees are valid for any+//! page count and are what most producers write for small documents.++use printcraft_cos::{Dict, Document, ObjRef, Object, PdfString};++#[derive(Debug, thiserror::Error, PartialEq)]+pub enum OrganizeError {+ #[error("the document has no page tree")]+ NoPageTree,+ #[error("page {0} does not exist")]+ NoSuchPage(usize),+ #[error("a document must keep at least one page")]+ WouldRemoveAllPages,+ #[error("{0}")]+ Cos(#[from] printcraft_cos::CosError),+}++const INHERITABLE: [&[u8]; 4] = [b"Resources", b"MediaBox", b"CropBox", b"Rotate"];++/// A leaf page in document order.+#[derive(Clone, Debug, PartialEq)]+pub struct PageRef {+ pub obj: ObjRef,+}++fn pages_root(doc: &Document) -> Result<ObjRef, OrganizeError> {+ let root = doc.root().ok_or(OrganizeError::NoPageTree)?;+ let catalog = doc.get(root);+ catalog.as_dict().and_then(|d| d.reference(b"Pages")).ok_or(OrganizeError::NoPageTree)+}++/// All leaf pages in order, with their effective inherited attributes.+fn walk(doc: &Document) -> Result<Vec<(ObjRef, Dict)>, OrganizeError> {+ let root = pages_root(doc)?;+ let mut out = Vec::new();+ let mut seen = std::collections::HashSet::new();+ // (node, inherited attributes from ancestors)+ let mut stack: Vec<(ObjRef, Dict)> = vec![(root, Dict::new())];+ while let Some((node, inherited)) = stack.pop() {+ if !seen.insert(node) || seen.len() > 1_000_000 {+ continue; // cycles in broken trees+ }+ let obj = doc.get(node);+ let Some(d) = obj.as_dict() else { continue };+ let mut attrs = inherited.clone();+ for k in INHERITABLE {+ if let Some(v) = d.get(k) {+ attrs.set(k.to_vec(), v.clone());+ }+ }+ let is_pages = d.name(b"Type") == Some(b"Pages") || (d.contains(b"Kids") && d.name(b"Type") != Some(b"Page"));+ if is_pages {+ let kids = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default();+ for k in kids.iter().rev() {+ if let Some(r) = k.as_ref() {+ stack.push((r, attrs.clone()));+ }+ }+ } else {+ out.push((node, attrs));+ }+ }+ Ok(out)+}++/// Leaf pages in document order.+pub fn pages(doc: &Document) -> Result<Vec<PageRef>, OrganizeError> {+ Ok(walk(doc)?.into_iter().map(|(obj, _)| PageRef { obj }).collect())+}++pub fn page_count(doc: &Document) -> Result<usize, OrganizeError> {+ Ok(walk(doc)?.len())+}++/// Rebuild the page tree as one flat node with `order` as its kids (attributes pushed down).+fn rebuild(doc: &mut Document, order: &[(ObjRef, Dict)]) -> Result<(), OrganizeError> {+ let root = pages_root(doc)?;+ for (page, inherited) in order {+ doc.update_dict(*page, |d| {+ for k in INHERITABLE {+ if !d.contains(k)+ && let Some(v) = inherited.get(k)+ {+ d.set(k.to_vec(), v.clone());+ }+ }+ d.set(b"Parent".to_vec(), Object::Ref(root));+ })?;+ }+ doc.update_dict(root, |d| {+ d.set(b"Type".to_vec(), Object::name("Pages"));+ d.set(b"Kids".to_vec(), Object::Array(order.iter().map(|(r, _)| Object::Ref(*r)).collect()));+ d.set(b"Count".to_vec(), Object::Int(order.len() as i64));+ // Attributes now live on the pages; leaving them here would be harmless but misleading.+ for k in INHERITABLE {+ d.remove(k);+ }+ d.remove(b"Parent");+ })?;+ Ok(())+}++fn check(indices: &[usize], n: usize) -> Result<(), OrganizeError> {+ match indices.iter().find(|i| **i >= n) {+ Some(i) => Err(OrganizeError::NoSuchPage(*i)),+ None => Ok(()),+ }+}++/// Rotate pages by a multiple of 90° (positive = clockwise), adjusting `/Rotate` (§7.7.3.3).+pub fn rotate_pages(doc: &mut Document, indices: &[usize], degrees: i64) -> Result<(), OrganizeError> {+ let all = walk(doc)?;+ check(indices, all.len())?;+ let delta = (degrees / 90) * 90;+ for &i in indices {+ let (page, inherited) = &all[i];+ let current = doc.get(*page).as_dict().and_then(|d| d.int(b"Rotate")).or_else(|| inherited.int(b"Rotate")).unwrap_or(0);+ let new = (current + delta).rem_euclid(360);+ doc.update_dict(*page, |d| d.set(b"Rotate".to_vec(), Object::Int(new)))?;+ }+ Ok(())+}++/// Delete pages. Refuses to delete every page.+pub fn delete_pages(doc: &mut Document, indices: &[usize]) -> Result<(), OrganizeError> {+ let all = walk(doc)?;+ check(indices, all.len())?;+ let keep: Vec<(ObjRef, Dict)> = all.iter().enumerate().filter(|(i, _)| !indices.contains(i)).map(|(_, p)| p.clone()).collect();+ if keep.is_empty() {+ return Err(OrganizeError::WouldRemoveAllPages);+ }+ rebuild(doc, &keep)+}++/// Move the pages at `indices` (kept in their relative order) so they start at position `to`+/// in the resulting document.+pub fn move_pages(doc: &mut Document, indices: &[usize], to: usize) -> Result<(), OrganizeError> {+ let all = walk(doc)?;+ check(indices, all.len())?;+ let mut sorted = indices.to_vec();+ sorted.sort_unstable();+ sorted.dedup();+ let moving: Vec<(ObjRef, Dict)> = sorted.iter().map(|i| all[*i].clone()).collect();+ let mut rest: Vec<(ObjRef, Dict)> = all.iter().enumerate().filter(|(i, _)| !sorted.contains(i)).map(|(_, p)| p.clone()).collect();+ let at = to.min(rest.len());+ rest.splice(at..at, moving);+ rebuild(doc, &rest)+}++/// Insert a blank page of `width × height` points at position `at` (0 = before the first page).+pub fn insert_blank_page(doc: &mut Document, at: usize, width: f64, height: f64) -> Result<ObjRef, OrganizeError> {+ let mut all = walk(doc)?;+ let root = pages_root(doc)?;+ let mut page = Dict::new();+ page.set(b"Type".to_vec(), Object::name("Page"));+ page.set(b"Parent".to_vec(), Object::Ref(root));+ page.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), Object::Real(width), Object::Real(height)]));+ page.set(b"Resources".to_vec(), Object::Dict(Dict::new()));+ let r = doc.add(page);+ let at = at.min(all.len());+ all.insert(at, (r, Dict::new()));+ rebuild(doc, &all)?;+ Ok(r)+}++/// Document information keys editable in Document Properties ▸ Description.+pub const INFO_KEYS: [&str; 4] = ["Title", "Author", "Subject", "Keywords"];++/// Read a document-information entry as text.+pub fn info(doc: &Document, key: &str) -> Option<String> {+ let info = doc.trailer().get(b"Info").map(|o| doc.resolve(o))?;+ info.as_dict()?.get(key.as_bytes()).and_then(|v| doc.resolve(v).as_string().map(|s| s.to_text()))+}++/// Set (or clear, with an empty value) a document-information entry.+///+/// Note: documents with XMP metadata also carry these values in the XMP packet; synchronising+/// XMP arrives with the `model` crate (M2) — viewers that prefer XMP may still show old values.+pub fn set_info(doc: &mut Document, key: &str, value: &str) -> Result<(), OrganizeError> {+ let value = value.trim();+ let entry = (!value.is_empty()).then(|| Object::String(PdfString::text(value)));+ match doc.trailer().get(b"Info").cloned() {+ Some(Object::Ref(r)) if doc.get(r).as_dict().is_some() => {+ doc.update_dict(r, |d| match entry {+ Some(v) => d.set(key.as_bytes().to_vec(), v),+ None => {+ d.remove(key.as_bytes());+ }+ })?;+ }+ _ => {+ let Some(v) = entry else { return Ok(()) };+ let mut d = match doc.trailer().get(b"Info") {+ Some(Object::Dict(d)) => d.clone(),+ _ => Dict::new(),+ };+ d.set(key.as_bytes().to_vec(), v);+ let r = doc.add(d);+ doc.trailer_mut().set(b"Info".to_vec(), Object::Ref(r));+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests;diff --git a/crates/organize/src/tests.rs b/crates/organize/src/tests.rsnew file mode 100644index 000000000..07a7bfea5--- /dev/null+++ b/crates/organize/src/tests.rs@@ -0,0 +1,187 @@+use std::sync::Arc;++use printcraft_cos::{Document, Object, SaveOptions, write_full, write_incremental};++use super::*;++/// A 3-page document with a nested page tree. MediaBox and Rotate are inherited from the root,+/// Resources from an intermediate node; each page's content says which page it is.+fn fixture() -> Vec<u8> {+ let objs: Vec<Vec<u8>> = vec![+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), // 1+ b"<< /Type /Pages /Kids [3 0 R 6 0 R] /Count 3 /MediaBox [0 0 300 400] /Rotate 90 >>".to_vec(), // 2+ b"<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R] /Count 2 /Resources << /Font << /F1 10 0 R >> >> >>".to_vec(), // 3+ b"<< /Type /Page /Parent 3 0 R /Contents 7 0 R >>".to_vec(), // 4+ b"<< /Type /Page /Parent 3 0 R /Contents 8 0 R >>".to_vec(), // 5+ b"<< /Type /Page /Parent 2 0 R /Contents 9 0 R /Resources << /Font << /F1 10 0 R >> >> /MediaBox [0 0 500 500] >>".to_vec(), // 6+ stream(b"BT /F1 12 Tf 20 20 Td (Page 1) Tj ET"), // 7+ stream(b"BT /F1 12 Tf 20 20 Td (Page 2) Tj ET"), // 8+ stream(b"BT /F1 12 Tf 20 20 Td (Page 3) Tj ET"), // 9+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), // 10+ b"<< /Title (Original) /Producer (fixture) >>".to_vec(), // 11+ ];+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());+ out.extend_from_slice(o);+ out.extend_from_slice(b"\nendobj\n");+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R /Info 11 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ out+}++fn stream(body: &[u8]) -> Vec<u8> {+ let mut v = format!("<< /Length {} >>\nstream\n", body.len()).into_bytes();+ v.extend_from_slice(body);+ v.extend_from_slice(b"\nendstream");+ v+}++fn open(bytes: Vec<u8>) -> Document {+ Document::open(Arc::new(bytes)).expect("opens")+}++/// The text label of each page, via its content stream, in order.+fn labels(doc: &Document) -> Vec<String> {+ pages(doc)+ .unwrap()+ .iter()+ .map(|p| {+ let page = doc.get(p.obj);+ let c = page.as_dict().and_then(|d| d.get(b"Contents").cloned());+ match c.map(|c| doc.resolve(&c)).as_deref() {+ Some(Object::Stream(s)) => {+ let data = s.decoded().unwrap();+ let t = String::from_utf8_lossy(&data);+ t.split('(').nth(1).and_then(|x| x.split(')').next()).unwrap_or("").to_string()+ }+ _ => "blank".into(),+ }+ })+ .collect()+}++/// Save incrementally, verify the prefix is untouched, and reopen — both with our reader and with+/// an independent parser (hayro-syntax) that must agree on the page count.+fn save_and_reopen(doc: &Document) -> Document {+ let original = doc.bytes().clone();+ let bytes = write_incremental(doc, &SaveOptions::default()).expect("saves");+ assert_eq!(&bytes[..original.len()], &original[..], "incremental save must not modify existing bytes");+ let reopened = open(bytes.clone());+ let independent = hayro_syntax::Pdf::new(bytes).expect("hayro opens our output");+ assert_eq!(independent.pages().len(), page_count(&reopened).unwrap(), "readers agree on page count");+ reopened+}++#[test]+fn walks_nested_tree_in_order() {+ let doc = open(fixture());+ assert_eq!(labels(&doc), ["Page 1", "Page 2", "Page 3"]);+}++#[test]+fn rotate_uses_inherited_rotation_and_round_trips() {+ let mut doc = open(fixture());+ rotate_pages(&mut doc, &[0, 2], 90).unwrap();+ rotate_pages(&mut doc, &[2], -270).unwrap(); // page 3: inherited 90 + 90 - 270 = -90 ≡ 270+ let doc = save_and_reopen(&doc);+ let rot = |i: usize| {+ let p = pages(&doc).unwrap()[i].obj;+ doc.get(p).as_dict().and_then(|d| d.int(b"Rotate"))+ };+ assert_eq!(rot(0), Some(180), "inherited 90 + 90");+ assert_eq!(rot(1), None, "untouched page keeps inheriting");+ assert_eq!(rot(2), Some(270), "normalised into 0..360");+}++#[test]+fn delete_keeps_inherited_attributes_on_survivors() {+ let mut doc = open(fixture());+ delete_pages(&mut doc, &[0]).unwrap();+ let doc = save_and_reopen(&doc);+ assert_eq!(labels(&doc), ["Page 2", "Page 3"]);+ // Page 2 inherited Resources (from the intermediate node) and MediaBox/Rotate (from the root);+ // the tree was flattened, so they must now be on the page itself.+ let p = doc.get(pages(&doc).unwrap()[0].obj);+ let d = p.as_dict().unwrap();+ assert!(d.contains(b"Resources") && d.contains(b"MediaBox"));+ assert_eq!(d.int(b"Rotate"), Some(90));+ let root = doc.get(doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap());+ assert_eq!(root.as_dict().unwrap().int(b"Count"), Some(2));+}++#[test]+fn cannot_delete_every_page_or_missing_pages() {+ let mut doc = open(fixture());+ assert_eq!(delete_pages(&mut doc, &[0, 1, 2]), Err(OrganizeError::WouldRemoveAllPages));+ assert_eq!(delete_pages(&mut doc, &[7]), Err(OrganizeError::NoSuchPage(7)));+ assert_eq!(rotate_pages(&mut doc, &[3], 90), Err(OrganizeError::NoSuchPage(3)));+ assert!(!doc.is_modified(), "failed operations leave the document untouched");+}++#[test]+fn move_pages_reorders() {+ let mut doc = open(fixture());+ move_pages(&mut doc, &[2], 0).unwrap();+ assert_eq!(labels(&doc), ["Page 3", "Page 1", "Page 2"]);+ move_pages(&mut doc, &[0, 1], 3).unwrap();+ assert_eq!(labels(&doc), ["Page 2", "Page 3", "Page 1"]);+ let doc = save_and_reopen(&doc);+ assert_eq!(labels(&doc), ["Page 2", "Page 3", "Page 1"]);+}++#[test]+fn inserts_blank_page() {+ let mut doc = open(fixture());+ insert_blank_page(&mut doc, 1, 612.0, 792.0).unwrap();+ let doc = save_and_reopen(&doc);+ assert_eq!(labels(&doc), ["Page 1", "blank", "Page 2", "Page 3"]);+ let hay = hayro_syntax::Pdf::new(doc.bytes().clone()).unwrap();+ let (w, h) = hay.pages().get(1).unwrap().render_dimensions();+ assert_eq!((w, h), (612.0, 792.0));+}++#[test]+fn document_info_edits_round_trip_with_unicode() {+ let mut doc = open(fixture());+ set_info(&mut doc, "Title", "Résumé — 履歴書").unwrap();+ set_info(&mut doc, "Author", "PrintCraft").unwrap();+ set_info(&mut doc, "Producer", "").unwrap(); // clearing removes the key+ let doc = save_and_reopen(&doc);+ assert_eq!(info(&doc, "Title").as_deref(), Some("Résumé — 履歴書"));+ assert_eq!(info(&doc, "Author").as_deref(), Some("PrintCraft"));+ assert_eq!(info(&doc, "Producer"), None);+}++#[test]+fn successive_incremental_saves_stack_revisions() {+ let mut doc = open(fixture());+ rotate_pages(&mut doc, &[0], 90).unwrap();+ let doc = save_and_reopen(&doc);+ assert_eq!(doc.revisions().len(), 2);+ let mut doc = doc;+ delete_pages(&mut doc, &[1]).unwrap();+ let doc = save_and_reopen(&doc);+ assert_eq!(doc.revisions().len(), 3);+ assert_eq!(labels(&doc), ["Page 1", "Page 3"]);+}++#[test]+fn full_save_drops_unreachable_objects() {+ let mut doc = open(fixture());+ delete_pages(&mut doc, &[0, 1]).unwrap();+ let bytes = write_full(&doc, &SaveOptions::default()).unwrap();+ let full = open(bytes.clone());+ assert_eq!(labels(&full), ["Page 3"]);+ // Deleted pages, their content streams and the orphaned intermediate node are gone.+ assert!(full.object_numbers().len() < doc.object_numbers().len());+ assert_eq!(info(&full, "Title").as_deref(), Some("Original"));+ assert_eq!(hayro_syntax::Pdf::new(bytes).unwrap().pages().len(), 1);+}diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.tomlindex afadd24af..5e646481e 100644--- a/crates/render/Cargo.toml+++ b/crates/render/Cargo.toml@@ -12,5 +12,10 @@ workspace = truehayro = { workspace = true }hayro-syntax = { workspace = true }lopdf = { workspace = true }+kurbo = { workspace = true }thiserror = { workspace = true }log = { workspace = true }++# lopdf (bootstrap) draws random bytes for encryption; on the web they come from the browser.+[target.'cfg(target_arch = "wasm32")'.dependencies]+getrandom = { version = "0.4", features = ["wasm_js"] }diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rsindex 9a6eb01ca..e247091b7 100644--- a/crates/render/src/inspect.rs+++ b/crates/render/src/inspect.rs@@ -7,8 +7,12 @@use std::collections::{BTreeMap, HashMap, HashSet};use std::sync::Arc;+use std::panic::{AssertUnwindSafe, catch_unwind};++use hayro::hayro_syntax::DecryptionError;+use hayro::hayro_syntax::LoadPdfError;use hayro::hayro_syntax::Pdf;-use lopdf::{Dictionary, Document, Object, ObjectId};+use lopdf::{Dictionary, Document, LoadOptions, Object, ObjectId};use crate::OpenError;@@ -31,6 +35,7 @@ pub struct DocInfo {pub fields: Vec<Field>,pub links: Vec<Link>,pub layers: Vec<Layer>,+ pub fonts: Vec<FontInfo>,pub attachments: Vec<Attachment>,pub warnings: Vec<String>,}@@ -112,6 +117,8 @@ pub struct Field {#[derive(Clone, Debug)]pub struct Layer {+ /// Object number and generation of the optional content group.+ pub id: (u32, u16),pub name: String,pub visible: bool,}@@ -121,30 +128,92 @@ pub struct Attachment {pub name: String,pub description: Option<String>,pub size: Option<usize>,+ pub source: AttachmentSource,+}++/// Where an attachment lives (so its bytes can be fetched on demand).+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum AttachmentSource {+ /// Document-level: `/Names /EmbeddedFiles` entry with this key.+ Document { key: String },+ /// A FileAttachment annotation: page index and position in the page's `/Annots`.+ Annotation { page: usize, index: usize },+}++/// A font used by the document (Document Properties ▸ Fonts).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct FontInfo {+ /// BaseFont without the subset tag.+ pub name: String,+ /// Type1, TrueType, Type0, Type3, MMType1, CIDFontType0/2 …+ pub kind: String,+ pub embedded: bool,+ pub subset: bool,+ pub encoding: Option<String>,}-/// Inspect a document. Fails only if the renderer itself cannot open the file.-pub fn inspect(bytes: Arc<Vec<u8>>) -> Result<DocInfo, OpenError> {- let pdf = Pdf::new(bytes.clone()).map_err(|e| match format!("{e:?}") {- s if s.to_lowercase().contains("encrypt") || s.to_lowercase().contains("password") => OpenError::NeedsPassword,- s => OpenError::Invalid(s),- })?;+/// Inspect a document. Fails only if the renderer itself cannot open the file (or needs a+/// password). Never panics: parser crashes are caught and reported.+pub fn inspect(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Result<DocInfo, OpenError> {+ let pdf = catch_unwind(AssertUnwindSafe(|| Pdf::new_with_password(bytes.clone(), password.unwrap_or(""))))+ .map_err(|p| OpenError::Invalid(format!("the parser crashed: {}", crate::raster::panic_message(&p))))?+ .map_err(|e| match e {+ LoadPdfError::Decryption(DecryptionError::PasswordProtected) => {+ if password.is_some() {+ OpenError::WrongPassword+ } else {+ OpenError::NeedsPassword+ }+ }+ LoadPdfError::Decryption(other) => OpenError::Unsupported(format!("encryption not supported: {other:?}")),+ LoadPdfError::Invalid => OpenError::Invalid("no readable page tree or cross-reference data was found".into()),+ })?;let mut info = DocInfo { file_size: bytes.len(), pdf_version: format!("{:?}", pdf.version()), ..Default::default() };- for (i, page) in pdf.pages().iter().enumerate() {- let (w, h) = page.render_dimensions();- let c = page.intersected_crop_box();- let rotation = match page.rotation() {- hayro::hayro_syntax::page::Rotation::None => 0,- hayro::hayro_syntax::page::Rotation::Horizontal => 90,- hayro::hayro_syntax::page::Rotation::Flipped => 180,- hayro::hayro_syntax::page::Rotation::FlippedHorizontal => 270,- };- let crop = [c.x0 as f32, c.y0 as f32, c.x1 as f32, c.y1 as f32];- info.pages.push(PageInfo { width: w, height: h, label: (i + 1).to_string(), crop, rotation });+ let pages = catch_unwind(AssertUnwindSafe(|| {+ let mut out = Vec::new();+ for (i, page) in pdf.pages().iter().enumerate() {+ let (w, h) = page.render_dimensions();+ let c = page.intersected_crop_box();+ let rotation = match page.rotation() {+ hayro::hayro_syntax::page::Rotation::None => 0,+ hayro::hayro_syntax::page::Rotation::Horizontal => 90,+ hayro::hayro_syntax::page::Rotation::Flipped => 180,+ hayro::hayro_syntax::page::Rotation::FlippedHorizontal => 270,+ };+ let crop = [c.x0 as f32, c.y0 as f32, c.x1 as f32, c.y1 as f32];+ // Degenerate boxes still get a usable placeholder size so layout never divides by zero.+ let (w, h) = if w.is_finite() && h.is_finite() && w >= 1.0 && h >= 1.0 { (w, h) } else { (612.0, 792.0) };+ out.push(PageInfo { width: w, height: h, label: (i + 1).to_string(), crop, rotation });+ }+ out+ }));+ match pages {+ Ok(p) => info.pages = p,+ Err(p) => return Err(OpenError::Invalid(format!("the page tree could not be read: {}", crate::raster::panic_message(&p)))),+ }+ let options = LoadOptions { password: password.map(str::to_owned), ..LoadOptions::default() };+ let structure = catch_unwind(AssertUnwindSafe(|| match Document::load_mem_with_options(&bytes, options) {+ Ok(doc) => {+ let mut tmp = DocInfo::default();+ std::mem::swap(&mut tmp.pages, &mut info.pages);+ Inspector::new(&doc).fill(&mut tmp);+ Ok(tmp)+ }+ Err(e) => Err(e.to_string()),+ }));+ match structure {+ Ok(Ok(mut filled)) => {+ filled.file_size = info.file_size;+ filled.pdf_version = std::mem::take(&mut info.pdf_version);+ info = filled;+ }+ Ok(Err(e)) => info.warnings.push(format!("Some document structure (bookmarks, comments, fields) could not be read: {e}")),+ Err(p) => {+ info.warnings.push(format!("Document structure inspection crashed and was skipped: {}", crate::raster::panic_message(&p)));+ }}- match Document::load_mem(&bytes) {- Ok(doc) => Inspector::new(&doc).fill(&mut info),- Err(e) => info.warnings.push(format!("structure inspection unavailable: {e}")),+ if info.pages.is_empty() {+ return Err(OpenError::Invalid("the document has no pages".into()));}Ok(info)}@@ -194,11 +263,12 @@ impl<'a> Inspector<'a> {}info.has_javascript |= info.fields.iter().any(|f| f.has_actions);self.layers(catalog, &mut info.layers);+ self.fonts(&mut info.fonts);if let Some(names) = catalog.get(b"Names").ok().and_then(|o| self.dict(o)) {if let Some(ef) = names.get(b"EmbeddedFiles").ok().and_then(|o| self.dict(o)) {let mut seen = HashSet::new();for (name, spec) in self.name_tree(ef, &mut seen, 0) {- info.attachments.push(self.attachment(name, spec));+ info.attachments.push(self.attachment(name.clone(), spec, AttachmentSource::Document { key: name }));}}info.has_javascript |= names.get(b"JavaScript").is_ok();@@ -379,9 +449,15 @@ impl<'a> Inspector<'a> {for (&id, &page) in &self.page_index {let Ok(page_dict) = self.doc.get_dictionary(id) else { continue };let Ok(Object::Array(annots)) = page_dict.get(b"Annots").map(|o| self.resolve(o)) else { continue };- for a in annots {+ for (index, a) in annots.iter().enumerate() {let Some(d) = self.dict(a) else { continue };let Some(subtype) = self.name(d, b"Subtype") else { continue };+ if subtype == "FileAttachment"+ && let Ok(fs) = d.get(b"FS")+ {+ let name = self.text(d, b"Contents").unwrap_or_else(|| "attachment".into());+ info.attachments.push(self.attachment(name, fs, AttachmentSource::Annotation { page, index }));+ }if subtype == "Link" {if let Some(link) = self.link(page, d) {if matches!(&link.target, LinkTarget::Other(s) if s == "JavaScript") {@@ -541,11 +617,55 @@ impl<'a> Inspector<'a> {Some(id) if on.contains(&id) => true,_ => !base_off,};- out.push(Layer { name: self.text(d, b"Name").unwrap_or_else(|| "Layer".into()), visible });+ let Some(id) = id else { continue };+ out.push(Layer { id, name: self.text(d, b"Name").unwrap_or_else(|| "Layer".into()), visible });+ }+ }++ fn fonts(&self, out: &mut Vec<FontInfo>) {+ let mut seen = HashSet::new();+ let mut pages: Vec<_> = self.page_index.iter().collect();+ pages.sort_by_key(|(_, i)| **i);+ for (&pid, _) in pages {+ let Ok(fonts) = self.doc.get_page_fonts(pid) else { continue };+ for (_, f) in fonts {+ let base = f+ .get(b"BaseFont")+ .ok()+ .and_then(|o| o.as_name().ok())+ .map(|n| String::from_utf8_lossy(n).into_owned())+ .unwrap_or_else(|| "(unnamed)".into());+ let kind = self.name(f, b"Subtype").unwrap_or_default();+ let encoding = match f.get(b"Encoding").map(|o| self.resolve(o)) {+ Ok(Object::Name(n)) => Some(String::from_utf8_lossy(n).into_owned()),+ Ok(Object::Dictionary(_)) => Some("Custom".into()),+ Ok(Object::Stream(_)) => Some("Embedded CMap".into()),+ _ => None,+ };+ // Embedded: FontFile/2/3 in the descriptor (for Type0, in the descendant font).+ let descriptor_of = |d: &Dictionary| d.get(b"FontDescriptor").ok().and_then(|o| self.dict(o)).cloned();+ let desc = descriptor_of(f).or_else(|| {+ f.get(b"DescendantFonts")+ .ok()+ .and_then(|o| self.resolve(o).as_array().ok())+ .and_then(|a| a.first())+ .and_then(|o| self.dict(o))+ .and_then(descriptor_of)+ });+ let embedded =+ kind == "Type3" || desc.is_some_and(|d| d.get(b"FontFile").is_ok() || d.get(b"FontFile2").is_ok() || d.get(b"FontFile3").is_ok());+ let subset = base.len() > 7 && base.as_bytes()[6] == b'+' && base[..6].bytes().all(|b| b.is_ascii_uppercase());+ let name = if subset { base[7..].to_string() } else { base };+ let info = FontInfo { name, kind, embedded, subset, encoding };+ if seen.insert((info.name.clone(), info.kind.clone(), info.embedded)) {+ out.push(info);+ }+ }}+ out.sort_by(|a, b| a.name.cmp(&b.name));}- fn attachment(&self, name: String, spec: &Object) -> Attachment {+ fn attachment(&self, name: String, spec: &Object, source: AttachmentSource) -> Attachment {let d = self.dict(spec);let size =d.and_then(|d| d.get(b"EF").ok()).and_then(|o| self.dict(o)).and_then(|ef| ef.get(b"F").ok().or_else(|| ef.get(b"UF").ok())).and_then(@@ -563,7 +683,7 @@ impl<'a> Inspector<'a> {},);let display = d.and_then(|d| self.text(d, b"UF").or_else(|| self.text(d, b"F"))).unwrap_or(name);- Attachment { name: display, description: d.and_then(|d| self.text(d, b"Desc")), size }+ Attachment { name: display, description: d.and_then(|d| self.text(d, b"Desc")), size, source }}}@@ -620,6 +740,39 @@ fn pretty_date(s: &str) -> String {}}+/// Fetch an attachment's bytes (decoded). Capped at 1 GiB to defuse decompression bombs.+pub fn attachment_data(bytes: &[u8], password: Option<&str>, att: &Attachment) -> Result<Vec<u8>, String> {+ let run = || -> Result<Vec<u8>, String> {+ let options = LoadOptions { password: password.map(str::to_owned), ..LoadOptions::default() };+ let doc = Document::load_mem_with_options(bytes, options).map_err(|e| e.to_string())?;+ let insp = Inspector::new(&doc);+ let spec: &Object = match &att.source {+ AttachmentSource::Document { key } => {+ let names = doc.catalog().ok().and_then(|c| c.get(b"Names").ok()).and_then(|o| insp.dict(o)).ok_or("no /Names")?;+ let ef = names.get(b"EmbeddedFiles").ok().and_then(|o| insp.dict(o)).ok_or("no /EmbeddedFiles")?;+ let mut seen = HashSet::new();+ insp.name_tree(ef, &mut seen, 0).into_iter().find(|(k, _)| k == key).map(|(_, v)| v).ok_or("attachment not found")?+ }+ AttachmentSource::Annotation { page, index } => {+ let (&pid, _) = insp.page_index.iter().find(|(_, i)| **i == *page).ok_or("page not found")?;+ let annots = doc.get_dictionary(pid).map_err(|e| e.to_string())?.get(b"Annots").map_err(|e| e.to_string())?;+ let a = insp.resolve(annots).as_array().map_err(|e| e.to_string())?.get(*index).ok_or("annotation not found")?;+ insp.dict(a).and_then(|d| d.get(b"FS").ok()).ok_or("annotation has no file")?+ }+ };+ let fs = insp.dict(spec).ok_or("bad file specification")?;+ let ef = fs.get(b"EF").ok().and_then(|o| insp.dict(o)).ok_or("the file is not embedded (external reference)")?;+ let stream = ef.get(b"UF").ok().or_else(|| ef.get(b"F").ok()).map(|o| insp.resolve(o)).ok_or("no embedded stream")?;+ let stream = stream.as_stream().map_err(|e| e.to_string())?;+ if stream.dict.get(b"Filter").is_ok() {+ stream.decompressed_content_with_limit(1 << 30).map_err(|e| e.to_string())+ } else {+ Ok(stream.content.clone())+ }+ };+ catch_unwind(AssertUnwindSafe(run)).unwrap_or_else(|p| Err(format!("reading the attachment crashed: {}", crate::raster::panic_message(&p))))+}+#[cfg(test)]mod tests {use super::*;@@ -633,6 +786,37 @@ mod tests {assert_eq!(alpha(53), "aaa");}+ const ATTACHMENTS: &[u8] = b"%PDF-1.7+1 0 obj << /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(notes.txt) 6 0 R] >> >> >> endobj+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [4 0 R] /Resources << /Font << /F1 9 0 R >> >> >> endobj+4 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [10 10 30 30] /Contents (data.csv) /FS 8 0 R >> endobj+5 0 obj << /Type /EmbeddedFile /Length 11 >> stream+hello notes+endstream endobj+6 0 obj << /Type /Filespec /F (notes.txt) /UF (notes.txt) /EF << /F 5 0 R >> /Desc (Doc-level) >> endobj+7 0 obj << /Type /EmbeddedFile /Length 5 >> stream+a,b,c+endstream endobj+8 0 obj << /Type /Filespec /F (data.csv) /EF << /F 7 0 R >> >> endobj+9 0 obj << /Type /Font /Subtype /Type1 /BaseFont /ABCDEF+Helvetica >> endobj+trailer << /Root 1 0 R >>+%%EOF";++ #[test]+ fn attachments_of_both_kinds_are_listed_and_extracted() {+ let bytes = Arc::new(ATTACHMENTS.to_vec());+ let info = inspect(bytes.clone(), None).expect("opens");+ let names: Vec<_> = info.attachments.iter().map(|a| a.name.as_str()).collect();+ assert!(names.contains(&"notes.txt") && names.contains(&"data.csv"), "{names:?}");+ for a in &info.attachments {+ let data = attachment_data(&bytes, None, a).expect("extracts");+ let expected: &[u8] = if a.name == "notes.txt" { b"hello notes" } else { b"a,b,c" };+ assert_eq!(data, expected, "{}", a.name);+ }+ assert_eq!(info.fonts, vec![FontInfo { name: "Helvetica".into(), kind: "Type1".into(), embedded: false, subset: true, encoding: None }]);+ }+#[test]fn dates_are_prettified() {assert_eq!(pretty_date("D:20260930104512-04'00'"), "2026-09-30 10:45");diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex 283d41ba1..cc36b39e1 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -8,15 +8,24 @@mod inspect;mod raster;+pub mod text;-pub use inspect::{Annotation, Attachment, DocInfo, Field, FieldKind, Layer, Link, LinkTarget, OutlineItem, PageInfo, inspect};-pub use raster::{RenderPool, RenderRequest, RenderedPage};+pub use inspect::{+ Annotation, Attachment, AttachmentSource, DocInfo, Field, FieldKind, FontInfo, Layer, Link, LinkTarget, OutlineItem, PageInfo, attachment_data,+ inspect,+};+pub use raster::{MAX_PIXELS, MAX_SIDE, PageRenderer, RenderConfig, RenderPool, RenderRequest, RenderedPage, RequestKind, Tile, effective_scale};+pub use text::{PageText, TextGlyph};/// Errors surfaced to the user when a document cannot be opened.#[derive(Debug, thiserror::Error)]pub enum OpenError {#[error("the file is not a readable PDF: {0}")]Invalid(String),- #[error("the document is encrypted and needs a password")]+ #[error("the document is protected by a password")]NeedsPassword,+ #[error("the password is incorrect")]+ WrongPassword,+ #[error("{0}")]+ Unsupported(String),}diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rsindex 2672e5918..ef885236c 100644--- a/crates/render/src/raster.rs+++ b/crates/render/src/raster.rs@@ -1,9 +1,14 @@//! Background page rasterization.//!//! A `RenderPool` owns N worker threads. Each worker parses the shared bytes once (hayro's parser-//! is lazy, so this is cheap) and keeps its own render cache. Requests carry a generation number;-//! the UI drops results for stale generations (e.g. after a zoom change).+//! is lazy, so this is cheap) and keeps its own render cache. Requests carry a caller tag that is+//! echoed back; the UI drops results for stale tags (e.g. after a zoom change).+//!+//! **Robustness:** every page render runs under `catch_unwind`. A panic inside the renderer on a+//! malformed page yields a `RenderedPage` with `error` set, and the worker rebuilds its parser and+//! cache before continuing, so one bad page can never take down the app or poison later pages.+use std::panic::{AssertUnwindSafe, catch_unwind};use std::sync::mpsc::{Receiver, Sender, channel};use std::sync::{Arc, Mutex};use std::thread::JoinHandle;@@ -13,24 +18,193 @@ use hayro::hayro_syntax::Pdf;use hayro::vello_cpu::color::palette::css::WHITE;use hayro::{RenderCache, RenderSettings, render};+/// Monotonic-ish timer that is safe on wasm32 (where `std::time::Instant` panics).+#[derive(Clone, Copy)]+struct Stopwatch(#[cfg(not(target_arch = "wasm32"))] std::time::Instant);++impl Stopwatch {+ fn start() -> Self {+ #[cfg(not(target_arch = "wasm32"))]+ return Self(std::time::Instant::now());+ #[cfg(target_arch = "wasm32")]+ return Self();+ }+ fn millis(self) -> u32 {+ #[cfg(not(target_arch = "wasm32"))]+ return self.0.elapsed().as_millis() as u32;+ #[cfg(target_arch = "wasm32")]+ return 0;+ }+}++/// Per-document rendering configuration.+#[derive(Clone, Debug, Default)]+pub struct RenderConfig {+ /// User or owner password for encrypted documents.+ pub password: Option<Arc<str>>,+ /// Layer (optional content group) visibility overrides: (object number, generation, visible).+ pub layers: Arc<Vec<(i32, i32, bool)>>,+}++impl RenderConfig {+ fn settings(&self) -> InterpreterSettings {+ InterpreterSettings { ocg_overrides: self.layers.clone(), ..InterpreterSettings::default() }+ }+}+/// Hard cap on a rendered side, to bound memory at extreme zoom levels (tiling arrives in M3.3).-const MAX_SIDE: f32 = 8192.0;+pub const MAX_SIDE: f32 = 8192.0;+/// Hard cap on rendered pixels per page (~64 MP ≈ 256 MB RGBA).+pub const MAX_PIXELS: f32 = 64.0e6;++/// What a request asks for.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum RequestKind {+ /// A raster of the page.+ #[default]+ Pixels,+ /// The page's text layer (glyphs with Unicode and boxes); `scale` is ignored.+ Text,+}-#[derive(Clone, Copy, Debug, PartialEq)]+/// A region of a scaled page, in device pixels (for tiled rendering of large pages).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct Tile {+ pub x: u32,+ pub y: u32,+ pub w: u32,+ pub h: u32,+}++#[derive(Clone, Copy, Debug, PartialEq, Default)]pub struct RenderRequest {pub page: usize,+ pub kind: RequestKind,+ /// Render only this region (device pixels at `scale`). `None` renders the whole page.+ pub tile: Option<Tile>,/// Device pixels per PDF point.pub scale: f32,/// Caller-defined tag, echoed back (used for zoom generations / thumbnail vs page).pub tag: u64,}+#[derive(Debug)]pub struct RenderedPage {pub request: RenderRequest,pub width: u32,pub height: u32,- /// Premultiplied RGBA8, row-major.+ /// Premultiplied RGBA8, row-major. Empty when `error` is set.pub rgba: Vec<u8>,+ /// Why the page could not be rendered (renderer panic, empty page box, …).+ pub error: Option<String>,+ /// For `RequestKind::Text`.+ pub text: Option<Arc<crate::text::PageText>>,+ pub millis: u32,+}++/// Clamp a requested scale so the output respects `MAX_SIDE` and `MAX_PIXELS`.+pub fn effective_scale(width_pt: f32, height_pt: f32, scale: f32) -> f32 {+ let (w, h) = (width_pt.max(1.0), height_pt.max(1.0));+ let by_side = MAX_SIDE / w.max(h);+ let by_area = (MAX_PIXELS / (w * h)).sqrt();+ scale.min(by_side).min(by_area).max(0.01)+}++/// Render one page with a caller-owned parser and cache. Panics inside the renderer are caught+/// and reported as `Err((message, panicked))`.+type Output = (u32, u32, Vec<u8>, Option<Arc<crate::text::PageText>>);++fn render_page<'a>(pdf: &'a Pdf, cache: &RenderCache<'a>, settings: &InterpreterSettings, req: RenderRequest) -> Result<Output, (String, bool)> {+ if req.kind == RequestKind::Text {+ return match catch_unwind(AssertUnwindSafe(|| crate::text::extract_page(pdf, req.page, settings))) {+ Ok(Some(t)) => Ok((0, 0, Vec::new(), Some(Arc::new(t)))),+ Ok(None) => Err((format!("page {} does not exist", req.page + 1), false)),+ Err(panic) => Err((format!("text extraction crashed on page {}: {}", req.page + 1, panic_message(&panic)), true)),+ };+ }+ let result = catch_unwind(AssertUnwindSafe(|| {+ let pages = pdf.pages();+ let page = pages.get(req.page).ok_or_else(|| format!("page {} does not exist", req.page + 1))?;+ let (w, h) = page.render_dimensions();+ if !(w.is_finite() && h.is_finite()) || w < 0.5 || h < 0.5 {+ return Err(format!("page {} has an empty or invalid page box ({w}×{h} pt)", req.page + 1));+ }+ let rs = match req.tile {+ // Tiles are bounded by construction, so the page itself may be arbitrarily large.+ Some(t) => {+ let scale = req.scale.clamp(0.01, 400.0);+ let (tw, th) = (t.w.clamp(1, 4096), t.h.clamp(1, 4096));+ RenderSettings {+ x_scale: scale,+ y_scale: scale,+ width: Some(tw as u16),+ height: Some(th as u16),+ x_offset: t.x as f32,+ y_offset: t.y as f32,+ bg_color: WHITE,+ }+ }+ None => {+ let scale = effective_scale(w, h, req.scale);+ RenderSettings { x_scale: scale, y_scale: scale, bg_color: WHITE, ..Default::default() }+ }+ };+ let pixmap = render(page, cache, settings, &rs);+ Ok((pixmap.width() as u32, pixmap.height() as u32, pixmap.data_as_u8_slice().to_vec(), None))+ }));+ match result {+ Ok(Ok(v)) => Ok(v),+ Ok(Err(e)) => Err((e, false)),+ Err(panic) => Err((format!("renderer crashed on page {}: {}", req.page + 1, panic_message(&panic)), true)),+ }+}++fn finish(req: RenderRequest, start: Stopwatch, r: Result<Output, (String, bool)>) -> RenderedPage {+ let millis = start.millis();+ match r {+ Ok((width, height, rgba, text)) => RenderedPage { request: req, width, height, rgba, error: None, text, millis },+ Err((e, _)) => RenderedPage { request: req, width: 0, height: 0, rgba: Vec::new(), error: Some(e), text: None, millis },+ }+}++/// A single-threaded renderer over one parsed document (used by the CLI and tests).+pub struct PageRenderer {+ bytes: Arc<Vec<u8>>,+ config: RenderConfig,+ pdf: Option<Pdf>,+ settings: InterpreterSettings,+}++impl PageRenderer {+ pub fn new(bytes: Arc<Vec<u8>>, config: RenderConfig) -> Self {+ let pdf = parse(&bytes, config.password.as_deref());+ let settings = config.settings();+ Self { bytes, config, pdf, settings }+ }++ pub fn page_count(&self) -> usize {+ self.pdf.as_ref().map(|p| p.pages().len()).unwrap_or(0)+ }++ /// Render one page. Never panics.+ pub fn render(&mut self, req: RenderRequest) -> RenderedPage {+ let start = Stopwatch::start();+ let Some(pdf) = self.pdf.as_ref() else { return finish(req, start, Err(("the document could not be parsed".into(), false))) };+ let cache = RenderCache::new();+ let r = render_page(pdf, &cache, &self.settings, req);+ if matches!(r, Err((_, true))) {+ self.pdf = parse(&self.bytes, self.config.password.as_deref());+ }+ finish(req, start, r)+ }+}++fn parse(bytes: &Arc<Vec<u8>>, password: Option<&str>) -> Option<Pdf> {+ catch_unwind(AssertUnwindSafe(|| Pdf::new_with_password(bytes.clone(), password.unwrap_or("")).ok())).ok().flatten()+}++pub(crate) fn panic_message(p: &Box<dyn std::any::Any + Send>) -> String {+ p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "unknown panic".into())}type Queue = Arc<Mutex<Vec<RenderRequest>>>;@@ -40,34 +214,53 @@ pub struct RenderPool {wake: Vec<Sender<()>>,results: Receiver<RenderedPage>,_workers: Vec<JoinHandle<()>>,+ /// Used when threads are unavailable (wasm32 without atomics, or spawn failure): requests are+ /// rendered on the calling thread inside `try_recv`, one per call.+ inline: Option<std::cell::RefCell<PageRenderer>>,}impl RenderPool {- pub fn new(bytes: Arc<Vec<u8>>, threads: usize) -> Self {+ pub fn new(bytes: Arc<Vec<u8>>, threads: usize, config: RenderConfig) -> Self {let queue: Queue = Arc::new(Mutex::new(Vec::new()));let (res_tx, results) = channel();let mut wake = Vec::new();let mut workers = Vec::new();- for i in 0..threads.max(1) {+ let threads = if cfg!(target_arch = "wasm32") { 0 } else { threads.max(1) };+ for i in 0..threads {let (wtx, wrx) = channel::<()>();wake.push(wtx);let queue = queue.clone();let res_tx = res_tx.clone();let bytes = bytes.clone();- let handle = std::thread::Builder::new()- .name(format!("printcraft-render-{i}"))- .spawn(move || worker(bytes, queue, wrx, res_tx))- .expect("spawn render worker");- workers.push(handle);+ let config = config.clone();+ let spawned = std::thread::Builder::new().name(format!("printcraft-render-{i}")).spawn(move || worker(bytes, config, queue, wrx, res_tx));+ match spawned {+ Ok(h) => workers.push(h),+ Err(e) => log::error!("could not spawn render worker {i}: {e}"),+ }}- Self { queue, wake, results, _workers: workers }+ let inline = workers.is_empty().then(|| std::cell::RefCell::new(PageRenderer::new(bytes, config)));+ Self { queue, wake, results, _workers: workers, inline }+ }++ /// A pool without worker threads: renders inside `try_recv` (the web path; also used in tests).+ pub fn new_inline(bytes: Arc<Vec<u8>>, config: RenderConfig) -> Self {+ let (_tx, results) = channel();+ let inline = Some(std::cell::RefCell::new(PageRenderer::new(bytes, config)));+ Self { queue: Arc::new(Mutex::new(Vec::new())), wake: Vec::new(), results, _workers: Vec::new(), inline }+ }++ /// `true` when rendering happens on the caller's thread (no worker threads available).+ pub fn is_inline(&self) -> bool {+ self.inline.is_some()}/// Replace the pending queue (most urgent first). In-flight renders are not interrupted.pub fn set_queue(&self, mut requests: Vec<RenderRequest>) {requests.reverse(); // workers pop from the end- if let Ok(mut q) = self.queue.lock() {- *q = requests;+ match self.queue.lock() {+ Ok(mut q) => *q = requests,+ Err(poisoned) => *poisoned.into_inner() = requests,}for w in &self.wake {let _ = w.send(());@@ -75,32 +268,46 @@ impl RenderPool {}pub fn try_recv(&self) -> Option<RenderedPage> {+ if let Some(r) = &self.inline {+ let next = match self.queue.lock() {+ Ok(mut q) => q.pop(),+ Err(poisoned) => poisoned.into_inner().pop(),+ };+ return next.map(|req| r.borrow_mut().render(req));+ }self.results.try_recv().ok()}}-fn worker(bytes: Arc<Vec<u8>>, queue: Queue, wake: Receiver<()>, out: Sender<RenderedPage>) {- let Ok(pdf) = Pdf::new(bytes) else { return };- let settings = InterpreterSettings::default();- let cache = RenderCache::new();- let pages = pdf.pages();+fn worker(bytes: Arc<Vec<u8>>, config: RenderConfig, queue: Queue, wake: Receiver<()>, out: Sender<RenderedPage>) {+ let settings = config.settings();+ // Outer loop: (re)build parser + cache; rebuilt after a renderer panic.loop {- let next = queue.lock().ok().and_then(|mut q| q.pop());- let Some(req) = next else {- if wake.recv().is_err() {- return; // pool dropped+ let pdf = parse(&bytes, config.password.as_deref());+ let cache = RenderCache::new();+ loop {+ let next = match queue.lock() {+ Ok(mut q) => q.pop(),+ Err(poisoned) => poisoned.into_inner().pop(),+ };+ let Some(req) = next else {+ if wake.recv().is_err() {+ return; // pool dropped+ }+ continue;+ };+ let start = Stopwatch::start();+ let r = match &pdf {+ Some(pdf) => render_page(pdf, &cache, &settings, req),+ None => Err(("the document could not be parsed".into(), false)),+ };+ let panicked = matches!(r, Err((_, true)));+ if out.send(finish(req, start, r)).is_err() {+ return;+ }+ if panicked {+ break;}- continue;- };- let Some(page) = pages.get(req.page) else { continue };- let (w, h) = page.render_dimensions();- let scale = req.scale.min(MAX_SIDE / w.max(h).max(1.0));- let rs = RenderSettings { x_scale: scale, y_scale: scale, bg_color: WHITE, ..Default::default() };- let pixmap = render(page, &cache, &settings, &rs);- let (width, height) = (pixmap.width() as u32, pixmap.height() as u32);- let rgba = pixmap.data_as_u8_slice().to_vec();- if out.send(RenderedPage { request: req, width, height, rgba }).is_err() {- return;}}}@@ -121,18 +328,165 @@ trailer << /Root 1 0 R >>#[test]fn renders_a_blue_rectangle() {- let pool = RenderPool::new(Arc::new(ONE_PAGE.to_vec()), 1);- pool.set_queue(vec![RenderRequest { page: 0, scale: 1.0, tag: 7 }]);+ let pool = RenderPool::new(Arc::new(ONE_PAGE.to_vec()), 1, RenderConfig::default());+ pool.set_queue(vec![RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 7 }]);let page = loop {if let Some(p) = pool.try_recv() {break p;}std::thread::sleep(std::time::Duration::from_millis(5));};+ assert!(page.error.is_none(), "{:?}", page.error);assert_eq!((page.width, page.height, page.request.tag), (100, 50, 7));// Pixel (20, 30) in y-down device space is inside the rect drawn at y 10..30 (y-up).let px = |x: u32, y: u32| &page.rgba[((y * page.width + x) * 4) as usize..][..4];assert_eq!(px(20, 30), &[0, 0, 255, 255]);assert_eq!(px(80, 5), &[255, 255, 255, 255]);}++ #[test]+ fn missing_page_and_garbage_input_fail_gracefully() {+ let mut r = PageRenderer::new(Arc::new(ONE_PAGE.to_vec()), RenderConfig::default());+ assert!(r.render(RenderRequest { page: 9, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 }).error.is_some());+ let mut g = PageRenderer::new(Arc::new(b"not a pdf at all".to_vec()), RenderConfig::default());+ assert_eq!(g.page_count(), 0);+ assert!(g.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 }).error.is_some());+ }++ #[test]+ fn scale_is_clamped_for_huge_pages() {+ // A 200-inch-square page at 4x would be 57,600 px per side.+ let s = effective_scale(14_400.0, 14_400.0, 4.0);+ assert!(14_400.0 * s <= MAX_SIDE + 0.5);+ assert!((14_400.0 * s).powi(2) <= MAX_PIXELS * 1.01);+ }++ /// A checkbox whose `/AP /N` is a state dictionary must draw the `/AS` state; a NoView+ /// annotation must not draw at all. (Regression test for the vendored hayro patch.)+ #[test]+ fn widget_appearance_states() {+ let pdf = b"%PDF-1.7+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Annots [4 0 R 7 0 R] >> endobj+4 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (cb) /V /Yes /AS /Yes /Rect [10 10 30 30]+ /AP << /N << /Yes 5 0 R /Off 6 0 R >> >> >> endobj+5 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 24 >> stream+1 0 0 rg 0 0 20 20 re f+endstream endobj+6 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 24 >> stream+0 0 1 rg 0 0 20 20 re f+endstream endobj+7 0 obj << /Type /Annot /Subtype /Square /F 32 /Rect [60 60 90 90] /AP << /N 8 0 R >> >> endobj+8 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 30 30] /Length 24 >> stream+0 1 0 rg 0 0 30 30 re f+endstream endobj+trailer << /Root 1 0 R >>+%%EOF";+ let mut r = PageRenderer::new(Arc::new(pdf.to_vec()), RenderConfig::default());+ let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 });+ assert!(p.error.is_none(), "{:?}", p.error);+ let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..4].to_vec();+ assert_eq!(px(20, 80), vec![255, 0, 0, 255], "checkbox must show its /Yes state");+ assert_eq!(px(75, 25), vec![255, 255, 255, 255], "NoView annotation must not be drawn");+ }++ #[test]+ fn inline_pool_renders_in_priority_order() {+ let pool = RenderPool::new_inline(Arc::new(ONE_PAGE.to_vec()), RenderConfig::default());+ assert!(pool.is_inline());+ assert!(pool.try_recv().is_none());+ pool.set_queue(vec![+ RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 1 },+ RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 0.5, tag: 2 },+ ]);+ assert_eq!(pool.try_recv().map(|p| p.request.tag), Some(1));+ assert_eq!(pool.try_recv().map(|p| (p.request.tag, p.width)), Some((2, 50)));+ assert!(pool.try_recv().is_none());+ }++ #[test]+ fn extracts_text_with_positions() {+ let pdf = b"%PDF-1.7+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj+4 0 obj << /Length 60 >> stream+BT /F1 12 Tf 20 70 Td (Hello World) Tj 0 -30 Td (Second) Tj ET+endstream endobj+5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj+trailer << /Root 1 0 R >>+%%EOF";+ let mut r = PageRenderer::new(Arc::new(pdf.to_vec()), RenderConfig::default());+ let out = r.render(RenderRequest { page: 0, kind: RequestKind::Text, tile: None, scale: 1.0, tag: 0 });+ assert!(out.error.is_none(), "{:?}", out.error);+ let t = out.text.expect("text");+ assert_eq!(t.plain_text(), "Hello World\nSecond");+ // "H" sits at x=20, baseline y=70 (y-up) → view y ≈ 100-70 = 30 at the baseline.+ let h = &t.glyphs[0].rect;+ assert!((h[0] - 20.0).abs() < 0.5 && h[1] < 30.0 && h[3] > 30.0, "{h:?}");+ assert_eq!(t.find("world").len(), 1);+ }++ #[test]+ fn layer_override_hides_content() {+ let pdf = b"%PDF-1.7+1 0 obj << /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R] /D << /Order [5 0 R] >> >> >> endobj+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << /Properties << /L1 5 0 R >> >> >> endobj+4 0 obj << /Length 44 >> stream+/OC /L1 BDC 1 0 0 rg 0 0 100 100 re f EMC+endstream endobj+5 0 obj << /Type /OCG /Name (Red) >> endobj+trailer << /Root 1 0 R >>+%%EOF";+ let px = |cfg: RenderConfig| {+ let mut r = PageRenderer::new(Arc::new(pdf.to_vec()), cfg);+ let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 0.5, tag: 0 });+ p.rgba[..4].to_vec()+ };+ assert_eq!(px(RenderConfig::default()), vec![255, 0, 0, 255], "layer is on by default");+ let off = RenderConfig { layers: Arc::new(vec![(5, 0, false)]), ..Default::default() };+ assert_eq!(px(off), vec![255, 255, 255, 255], "toggled-off layer must not draw");+ }++ #[test]+ fn tiles_match_full_render() {+ let mut r = PageRenderer::new(Arc::new(ONE_PAGE.to_vec()), RenderConfig::default());+ let full = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 2.0, tag: 0 });+ let tile = Tile { x: 30, y: 40, w: 50, h: 30 };+ let part = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: Some(tile), scale: 2.0, tag: 0 });+ assert_eq!((part.width, part.height), (50, 30));+ for y in 0..30u32 {+ for x in 0..50u32 {+ let a = &full.rgba[(((y + 40) * full.width + x + 30) * 4) as usize..][..4];+ let b = &part.rgba[((y * 50 + x) * 4) as usize..][..4];+ assert_eq!(a, b, "pixel {x},{y}");+ }+ }+ }++ /// An alpha soft mask whose transparency group has no /CS (as Chrome writes gradient text)+ /// must still mask. Regression test for the vendored hayro-interpret patch.+ #[test]+ fn soft_mask_without_group_colour_space_is_applied() {+ let pdf = b"%PDF-1.7+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << /ExtGState << /M 5 0 R >> >> >> endobj+4 0 obj << /Length 31 >> stream+/M gs 1 0 0 rg 0 0 100 100 re f+endstream endobj+5 0 obj << /Type /ExtGState /SMask << /Type /Mask /S /Alpha /G 6 0 R >> >> endobj+6 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /I true >> /Length 20 >> stream+0 g 0 0 50 100 re f+endstream endobj+trailer << /Root 1 0 R >>+%%EOF";+ let mut r = PageRenderer::new(Arc::new(pdf.to_vec()), RenderConfig::default());+ let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 });+ let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..4].to_vec();+ assert_eq!(px(25, 50), vec![255, 0, 0, 255], "inside the mask");+ assert_eq!(px(75, 50), vec![255, 255, 255, 255], "outside the mask");+ }}diff --git a/crates/render/src/text.rs b/crates/render/src/text.rsnew file mode 100644index 000000000..0b7316a2c--- /dev/null+++ b/crates/render/src/text.rs@@ -0,0 +1,512 @@+//! Text extraction (bootstrap for `printcraft-text`, architecture §8).+//!+//! A hayro `Device` that ignores paint and records every glyph: its Unicode value (ToUnicode →+//! encoding → glyph name fallbacks, handled by hayro) and its box in *page view space*, i.e.+//! points with the origin at the top-left of the displayed page, rotation applied, y down. The UI+//! maps view space to the screen with a single scale.+//!+//! On top of the glyph list: line grouping (baseline clustering), word gaps, plain-text output,+//! case-insensitive search and reading-order selection.++use hayro::hayro_interpret::font::Glyph;+use hayro::hayro_interpret::hayro_syntax::Pdf;+use hayro::hayro_interpret::{+ BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, interpret_page,+};+use kurbo::{Affine, BezPath, Rect, Shape};++/// One glyph on the page.+#[derive(Clone, Debug, PartialEq)]+pub struct TextGlyph {+ pub text: String,+ /// Box in page view space (points, y down): [x0, y0, x1, y1].+ pub rect: [f32; 4],+}++/// The text of one page, in content order, with line structure.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct PageText {+ pub glyphs: Vec<TextGlyph>,+ /// For each glyph: its line index (lines are in reading order, top to bottom).+ pub line_of: Vec<u32>,+ /// `true` when a word break precedes the glyph on the same line.+ pub space_before: Vec<bool>,+}++impl PageText {+ pub fn is_empty(&self) -> bool {+ self.glyphs.is_empty()+ }++ /// Text of glyphs `range` with spaces and line breaks reconstructed.+ pub fn text_of(&self, range: std::ops::Range<usize>) -> String {+ let mut s = String::new();+ let mut prev_line = None;+ for i in range.clone() {+ let Some(g) = self.glyphs.get(i) else { break };+ if i != range.start {+ if prev_line != Some(self.line_of[i]) {+ s.push('\n');+ } else if self.space_before[i] {+ s.push(' ');+ }+ }+ s.push_str(&g.text);+ prev_line = Some(self.line_of[i]);+ }+ s+ }++ pub fn plain_text(&self) -> String {+ self.text_of(0..self.glyphs.len())+ }++ /// Case-insensitive search. Returns glyph ranges of every match (words may span line breaks,+ /// which count as a single space).+ pub fn find(&self, needle: &str) -> Vec<std::ops::Range<usize>> {+ let needle: Vec<char> = needle.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();+ if needle.is_empty() {+ return Vec::new();+ }+ // Flatten to chars with the glyph index each char came from.+ let mut chars: Vec<(char, usize)> = Vec::new();+ for (i, g) in self.glyphs.iter().enumerate() {+ if i > 0 && (self.space_before[i] || self.line_of[i] != self.line_of[i - 1]) && chars.last().is_some_and(|c| c.0 != ' ') {+ chars.push((' ', i));+ }+ for c in g.text.chars().flat_map(char::to_lowercase) {+ chars.push((if c.is_whitespace() { ' ' } else { c }, i));+ }+ }+ let mut out = Vec::new();+ let mut i = 0;+ while i + needle.len() <= chars.len() {+ if chars[i..i + needle.len()].iter().map(|c| c.0).eq(needle.iter().copied()) {+ let start = chars[i].1;+ let end = chars[i + needle.len() - 1].1 + 1;+ out.push(start..end);+ i += needle.len();+ } else {+ i += 1;+ }+ }+ out+ }++ /// Index of the glyph nearest to a view-space point (for selection anchors).+ pub fn nearest(&self, x: f32, y: f32) -> Option<usize> {+ self.glyphs+ .iter()+ .enumerate()+ .map(|(i, g)| {+ let dx = if x < g.rect[0] {+ g.rect[0] - x+ } else if x > g.rect[2] {+ x - g.rect[2]+ } else {+ 0.0+ };+ let dy = if y < g.rect[1] {+ g.rect[1] - y+ } else if y > g.rect[3] {+ y - g.rect[3]+ } else {+ 0.0+ };+ // Prefer the same line: vertical distance weighs more.+ (i, dx + dy * 3.0)+ })+ .min_by(|a, b| a.1.total_cmp(&b.1))+ .map(|(i, _)| i)+ }++ /// Merge the boxes of `range` into one rectangle per line (for highlighting).+ pub fn line_rects(&self, range: std::ops::Range<usize>) -> Vec<[f32; 4]> {+ let mut out: Vec<(u32, [f32; 4])> = Vec::new();+ for i in range {+ let Some(g) = self.glyphs.get(i) else { break };+ let line = self.line_of[i];+ match out.last_mut() {+ Some((l, r)) if *l == line => {+ r[0] = r[0].min(g.rect[0]);+ r[1] = r[1].min(g.rect[1]);+ r[2] = r[2].max(g.rect[2]);+ r[3] = r[3].max(g.rect[3]);+ }+ _ => out.push((line, g.rect)),+ }+ }+ out.into_iter().map(|(_, r)| r).collect()+ }+}++struct TextDevice {+ glyphs: Vec<TextGlyph>,+}++impl<'a> Device<'a> for TextDevice {+ fn set_soft_mask(&mut self, _: Option<SoftMask<'a>>) {}+ fn set_blend_mode(&mut self, _: BlendMode) {}+ fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'a>, _: &PathDrawMode) {}+ fn push_clip_path(&mut self, _: &ClipPath) {}+ fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}+ fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, _: &Paint<'a>, _: &GlyphDrawMode) {+ let Some(u) = glyph.as_unicode() else {+ if std::env::var_os("PRINTCRAFT_TEXT_DEBUG").is_some() {+ eprintln!("NOUNICODE {} {:?}", if matches!(glyph, Glyph::Type3(_)) { "t3" } else { "ol" }, (transform * glyph_transform).as_coeffs());+ }+ return;+ };+ let text = match u {+ hayro::hayro_interpret::hayro_cmap::BfString::Char(c) => c.to_string(),+ hayro::hayro_interpret::hayro_cmap::BfString::String(s) => s,+ };+ if text.chars().all(|c| c.is_control()) {+ return;+ }+ // Glyph space → view space. Glyph space uses 1000 units per em for outline glyphs; the em+ // box spans descender (−200) to ascender (800), the advance gives the width.+ let t = transform * glyph_transform;+ if std::env::var_os("PRINTCRAFT_TEXT_DEBUG").is_some() {+ let kind = if matches!(glyph, Glyph::Type3(_)) { "t3" } else { "ol" };+ eprintln!("{kind} {text:?} transform={:?} glyph_transform={:?}", transform.as_coeffs(), glyph_transform.as_coeffs());+ }+ let advance = match glyph {+ Glyph::Outline(g) => {+ g.advance_width().filter(|a| *a > 0.0).map(f64::from).unwrap_or_else(|| g.outline().bounding_box().width().max(500.0))+ }+ Glyph::Type3(g) => g.advance_width().filter(|a| a.is_finite() && *a > 0.0).map(f64::from).unwrap_or(600.0),+ };+ let em = Rect::new(0.0, -200.0, advance, 800.0);+ let b = (t * em.to_path(0.1)).bounding_box();+ if !(b.x0.is_finite() && b.y0.is_finite() && b.x1.is_finite() && b.y1.is_finite()) || b.width() > 10_000.0 || b.height() > 10_000.0 {+ return;+ }+ for (i, ch) in text.chars().enumerate() {+ // Ligatures (e.g. "ffi") share the glyph box, split evenly.+ let n = text.chars().count().max(1) as f64;+ let w = b.width() / n;+ let x0 = b.x0 + w * i as f64;+ self.glyphs.push(TextGlyph { text: ch.to_string(), rect: [x0 as f32, b.y0 as f32, (x0 + w) as f32, b.y1 as f32] });+ }+ }+ fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {}+ fn pop_clip_path(&mut self) {}+ fn pop_transparency_group(&mut self) {}+}++/// Extract the text of one page. Panics inside the interpreter are the caller's to catch.+pub(crate) fn extract_page(pdf: &Pdf, page: usize, settings: &InterpreterSettings) -> Option<PageText> {+ let pages = pdf.pages();+ let p = pages.get(page)?;+ let (w, h) = p.render_dimensions();+ let cache = InterpreterCache::new();+ // Annotation appearances are included: form-field values and comment text are searchable,+ // as in Acrobat, and match what other extractors report.+ let settings = settings.clone();+ let initial = p.initial_transform(true).to_kurbo();+ let mut ctx = Context::new(initial, Rect::new(0.0, 0.0, w as f64, h as f64), &cache, p.xref(), settings);+ let mut dev = TextDevice { glyphs: Vec::new() };+ interpret_page(p, &mut ctx, &mut dev);+ Some(layout(dev.glyphs))+}++use hayro::hayro_interpret::TransformExt;++fn is_rtl(c: char) -> bool {+ matches!(c as u32, 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF)+}++/// Scripts written with explicit spaces whose combining signs can sit apart from their base+/// (Indic, Thai, Lao, Myanmar, Khmer): never infer a space inside a tight cluster.+fn is_complex(c: char) -> bool {+ matches!(c as u32, 0x0300..=0x036F | 0x0900..=0x0DFF | 0x0E00..=0x0EFF | 0x1000..=0x109F | 0x1780..=0x17FF)+}++fn is_cjk(c: char) -> bool {+ matches!(c as u32, 0x2E80..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF | 0xFF00..=0xFFEF | 0x20000..=0x3134F | 0x1100..=0x11FF)+}++struct Seg {+ idx: Vec<usize>,+ bbox: [f32; 4],+ h: f32,+}++impl Seg {+ fn cy(&self) -> f32 {+ (self.bbox[1] + self.bbox[3]) / 2.0+ }+}++fn union(a: &mut [f32; 4], b: &[f32; 4]) {+ a[0] = a[0].min(b[0]);+ a[1] = a[1].min(b[1]);+ a[2] = a[2].max(b[2]);+ a[3] = a[3].max(b[3]);+}++/// Reading-order layout. Glyphs are reordered so that `glyphs` is in reading order, lines are+/// numbered in that order, and word gaps are inferred per line.+///+/// Heuristics (documented so they can be tuned and tested; plan/architecture.md §8):+/// 1. *Segments:* consecutive glyphs (content order) on one baseline with no column-sized gap.+/// Segments on the same baseline that nearly touch are merged (text drawn out of order).+/// 2. *Blocks:* segments stacked with line-sized gaps and overlapping horizontally.+/// 3. *Block order:* repeatedly take the top-most remaining block, preferring a block to its left+/// that overlaps it vertically (so columns read left, then right).+/// 4. Within a segment glyphs run left to right; runs of right-to-left script are reversed so the+/// text comes out in logical order.+pub fn layout(glyphs: Vec<TextGlyph>) -> PageText {+ // Drop "fake bold" duplicates: the same character redrawn at (almost) the same place.+ let mut glyphs = glyphs;+ let mut keep = vec![true; glyphs.len()];+ for i in 1..glyphs.len() {+ let g = &glyphs[i];+ let h = (g.rect[3] - g.rect[1]).max(0.1);+ for j in (i.saturating_sub(4)..i).rev() {+ let p = &glyphs[j];+ if keep[j] && p.text == g.text && (p.rect[0] - g.rect[0]).abs() < h * 0.2 && (p.rect[1] - g.rect[1]).abs() < h * 0.2 {+ keep[i] = false;+ break;+ }+ }+ }+ if keep.iter().any(|k| !k) {+ let mut it = keep.iter();+ glyphs.retain(|_| *it.next().unwrap_or(&true));+ }+ let n = glyphs.len();+ if n == 0 {+ return PageText::default();+ }+ let height = |i: usize| (glyphs[i].rect[3] - glyphs[i].rect[1]).max(0.1);+ let cy = |i: usize| (glyphs[i].rect[1] + glyphs[i].rect[3]) / 2.0;++ // 1. Segments in content order.+ let mut segs: Vec<Seg> = Vec::new();+ for i in 0..n {+ let g = glyphs[i].rect;+ let cont = segs.last().is_some_and(|s| {+ let p = *s.idx.last().expect("non-empty");+ let ph = height(p).min(height(i));+ let gap = g[0] - glyphs[p].rect[2];+ (cy(i) - cy(p)).abs() < ph * 0.5 && gap < ph * 3.0 && g[0] > glyphs[p].rect[0] - ph * 2.0+ });+ if cont {+ let s = segs.last_mut().expect("non-empty");+ s.idx.push(i);+ union(&mut s.bbox, &g);+ s.h = s.h.max(height(i));+ } else {+ segs.push(Seg { idx: vec![i], bbox: g, h: height(i) });+ }+ }+ // Merge same-baseline segments that nearly touch.+ let mut merged = true;+ while merged {+ merged = false;+ 'outer: for a in 0..segs.len() {+ for b in 0..segs.len() {+ if a == b {+ continue;+ }+ let (sa, sb) = (&segs[a], &segs[b]);+ let h = sa.h.min(sb.h);+ let gap = (sb.bbox[0] - sa.bbox[2]).max(sa.bbox[0] - sb.bbox[2]);+ if (sa.cy() - sb.cy()).abs() < h * 0.3 && (sa.h / sb.h - 1.0).abs() < 0.35 && gap < h * 1.2 {+ let sb = segs.remove(b);+ let a = if b < a { a - 1 } else { a };+ let sa = &mut segs[a];+ sa.idx.extend(sb.idx);+ union(&mut sa.bbox, &sb.bbox);+ sa.h = sa.h.max(sb.h);+ merged = true;+ break 'outer;+ }+ }+ }+ }+ for s in &mut segs {+ s.idx.sort_by(|a, b| glyphs[*a].rect[0].total_cmp(&glyphs[*b].rect[0]));+ }++ // 2. Blocks.+ let mut by_top: Vec<usize> = (0..segs.len()).collect();+ by_top.sort_by(|a, b| segs[*a].bbox[1].total_cmp(&segs[*b].bbox[1]));+ let mut blocks: Vec<(Vec<usize>, [f32; 4])> = Vec::new();+ for si in by_top {+ let s = &segs[si];+ let target = blocks.iter().position(|(members, bb)| {+ let last = &segs[*members.last().expect("non-empty")];+ let vgap = s.bbox[1] - last.bbox[3];+ let overlap = s.bbox[2].min(bb[2]) - s.bbox[0].max(bb[0]);+ let minw = (s.bbox[2] - s.bbox[0]).min(bb[2] - bb[0]).max(1.0);+ vgap > -last.h * 0.5 && vgap < last.h.max(s.h) * 1.1 && overlap > minw * 0.3 && (last.h / s.h - 1.0).abs() < 0.6+ });+ match target {+ Some(b) => {+ blocks[b].0.push(si);+ let bb = s.bbox;+ union(&mut blocks[b].1, &bb);+ }+ None => blocks.push((vec![si], s.bbox)),+ }+ }++ // 3. Block order.+ let mut remaining: Vec<usize> = (0..blocks.len()).collect();+ let mut block_order = Vec::with_capacity(blocks.len());+ while !remaining.is_empty() {+ let top = *remaining.iter().min_by(|a, b| blocks[**a].1[1].total_cmp(&blocks[**b].1[1])).expect("non-empty");+ let tb = blocks[top].1;+ let pick = remaining+ .iter()+ .copied()+ .filter(|c| {+ let cb = blocks[*c].1;+ let v = cb[3].min(tb[3]) - cb[1].max(tb[1]);+ cb[2] <= tb[0] + 1.0 && v > 0.5 * (cb[3] - cb[1]).min(tb[3] - tb[1])+ })+ .min_by(|a, b| blocks[*a].1[0].total_cmp(&blocks[*b].1[0]))+ .unwrap_or(top);+ remaining.retain(|r| *r != pick);+ block_order.push(pick);+ }++ // 4. Emit glyphs in reading order with line numbers and word gaps.+ let mut order: Vec<usize> = Vec::with_capacity(n);+ let mut line_of = Vec::with_capacity(n);+ let mut space_before = Vec::with_capacity(n);+ let mut line = 0u32;+ for b in block_order {+ for si in &blocks[b].0 {+ let s = &segs[*si];+ let mut idx = s.idx.clone();+ // Reverse right-to-left runs (visual → logical).+ let rtl = |i: usize| glyphs[i].text.chars().any(is_rtl);+ let mut k = 0;+ while k < idx.len() {+ if rtl(idx[k]) {+ let mut e = k;+ while e + 1 < idx.len()+ && (rtl(idx[e + 1]) || (glyphs[idx[e + 1]].text.trim().is_empty() && e + 2 < idx.len() && rtl(idx[e + 2])))+ {+ e += 1;+ }+ idx[k..=e].reverse();+ k = e + 1;+ } else {+ k += 1;+ }+ }+ // Word gaps relative to this line's typical letter gap (handles tracking).+ let mut gaps: Vec<f32> = s.idx.windows(2).map(|w| glyphs[w[1]].rect[0] - glyphs[w[0]].rect[2]).collect();+ gaps.sort_by(f32::total_cmp);+ let typical = gaps.get(gaps.len() / 3).copied().unwrap_or(0.0).max(0.0);+ let threshold = (typical + s.h * 0.15).max(s.h * 0.15);+ let mut spaces = vec![false; idx.len()];+ for w in 1..s.idx.len() {+ let (p, c) = (s.idx[w - 1], s.idx[w]);+ let gap = glyphs[c].rect[0] - glyphs[p].rect[2];+ let (pt, ct) = (&glyphs[p].text, &glyphs[c].text);+ let cjk = pt.chars().any(is_cjk) && ct.chars().any(is_cjk) && gap < s.h * 0.5;+ let tight_cluster = (pt.chars().any(is_complex) || ct.chars().any(is_complex)) && gap < s.h * 0.6;+ if gap > threshold && !cjk && !tight_cluster && !pt.trim().is_empty() && !ct.trim().is_empty() {+ // Mark the space before glyph `c` wherever it ended up after RTL reversal.+ if let Some(pos) = idx.iter().position(|x| *x == c.max(p)) {+ spaces[pos] = true;+ }+ }+ }+ for (k, g) in idx.iter().enumerate() {+ order.push(*g);+ line_of.push(line);+ space_before.push(k > 0 && spaces[k]);+ }+ line += 1;+ }+ }+ let mut slots: Vec<Option<TextGlyph>> = glyphs.into_iter().map(Some).collect();+ let glyphs = order.iter().map(|i| slots[*i].take().expect("each glyph emitted once")).collect();+ PageText { glyphs, line_of, space_before }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn g(t: &str, x0: f32, y0: f32, x1: f32) -> TextGlyph {+ TextGlyph { text: t.into(), rect: [x0, y0, x1, y0 + 10.0] }+ }++ #[test]+ fn lines_words_and_search() {+ // "Hello world" on line 1, "Next" on line 2.+ let mut v = Vec::new();+ for (i, c) in "Hello".chars().enumerate() {+ v.push(g(&c.to_string(), 10.0 + i as f32 * 6.0, 10.0, 16.0 + i as f32 * 6.0));+ }+ for (i, c) in "world".chars().enumerate() {+ v.push(g(&c.to_string(), 50.0 + i as f32 * 6.0, 10.0, 56.0 + i as f32 * 6.0));+ }+ for (i, c) in "Next".chars().enumerate() {+ v.push(g(&c.to_string(), 10.0 + i as f32 * 6.0, 30.0, 16.0 + i as f32 * 6.0));+ }+ let t = layout(v);+ assert_eq!(t.plain_text(), "Hello world\nNext");+ assert_eq!(t.find("WORLD next"), vec![5..14]);+ assert_eq!(t.find("o"), vec![4..5, 6..7]);+ assert_eq!(t.line_rects(3..12).len(), 2);+ assert_eq!(t.nearest(52.0, 14.0), Some(5));+ }++ fn word(v: &mut Vec<TextGlyph>, s: &str, x: f32, y: f32, advance: f32) {+ for (i, c) in s.chars().enumerate() {+ let x0 = x + i as f32 * advance;+ v.push(g(&c.to_string(), x0, y, x0 + 6.0));+ }+ }++ #[test]+ fn fake_bold_duplicates_are_removed() {+ let mut v = Vec::new();+ for (i, c) in "Bold".chars().enumerate() {+ let x = 10.0 + i as f32 * 7.0;+ v.push(g(&c.to_string(), x, 10.0, x + 6.0));+ v.push(g(&c.to_string(), x + 0.3, 10.0, x + 6.3));+ }+ assert_eq!(layout(v).plain_text(), "Bold");+ }++ #[test]+ fn two_columns_read_left_then_right_even_if_drawn_interleaved() {+ let mut v = Vec::new();+ // Drawn row by row across both columns, as some producers do.+ word(&mut v, "Left1", 10.0, 10.0, 6.0);+ word(&mut v, "Right1", 200.0, 10.0, 6.0);+ word(&mut v, "Left2", 10.0, 24.0, 6.0);+ word(&mut v, "Right2", 200.0, 24.0, 6.0);+ let t = layout(v);+ assert_eq!(t.plain_text(), "Left1\nLeft2\nRight1\nRight2");+ }++ #[test]+ fn tracked_text_keeps_letters_together() {+ let mut v = Vec::new();+ word(&mut v, "CHAPTER", 10.0, 10.0, 9.0); // 3pt tracking between 6pt-wide letters+ word(&mut v, "FOUR", 10.0 + 7.0 * 9.0 + 5.0, 10.0, 9.0);+ assert_eq!(layout(v).plain_text(), "CHAPTER FOUR");+ }++ #[test]+ fn rtl_runs_come_out_in_logical_order_and_cjk_has_no_spaces() {+ let mut v = Vec::new();+ // Hebrew "שלום" drawn visually right-to-left: ם ו ל ש from left to right.+ word(&mut v, "םולש", 10.0, 10.0, 6.0);+ assert_eq!(layout(v).plain_text(), "שלום");+ let mut v = Vec::new();+ word(&mut v, "每个字", 10.0, 10.0, 9.0);+ assert_eq!(layout(v).plain_text(), "每个字");+ }+}diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.tomlindex 4d29ff6ed..bd9686a4f 100644--- a/crates/ui-egui/Cargo.toml+++ b/crates/ui-egui/Cargo.toml@@ -13,8 +13,19 @@ printcraft-engine = { workspace = true }printcraft-render = { workspace = true }egui = { workspace = true }egui_extras = { workspace = true }-eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }+eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] }serde = { workspace = true }+serde_json = { workspace = true }+log = { workspace = true }-[target.'cfg(not(target_arch = "wasm32"))'.dependencies]rfd = { workspace = true }++[target.'cfg(target_arch = "wasm32")'.dependencies]+wasm-bindgen-futures = "0.4"+wasm-bindgen = "0.2"+js-sys = "0.3"+web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url"] }++[dev-dependencies]+egui_kittest = { workspace = true, features = ["eframe", "wgpu"] }+image = { version = "0.25", default-features = false, features = ["png"] }diff --git a/crates/ui-egui/examples/shot.rs b/crates/ui-egui/examples/shot.rsnew file mode 100644index 000000000..92ff8d086--- /dev/null+++ b/crates/ui-egui/examples/shot.rs@@ -0,0 +1,64 @@+//! Headless screenshot of the real PrintCraft shell (egui_kittest + wgpu, no window needed).+//!+//! ```text+//! cargo run -p printcraft-ui-egui --example shot -- out.png [file.pdf] [--size 1440x900] [--scale 2] [--page 3 --panel pages …]+//! ```+//! Any `--key value` pair other than size/scale is passed to `PrintCraftApp::set_option`+//! (the same verbs as the desktop app's command-line flags and the future control channel).++use std::time::{Duration, Instant};++use egui_kittest::Harness;+use printcraft_ui_egui::PrintCraftApp;++fn main() -> Result<(), String> {+ let mut args = std::env::args().skip(1);+ let out = args.next().ok_or("usage: shot <out.png> [file.pdf] [--option value …]")?;+ let (mut file, mut opts) = (None, Vec::new());+ let (mut size, mut scale) = (egui::vec2(1440.0, 900.0), 2.0f32);+ while let Some(a) = args.next() {+ match a.strip_prefix("--") {+ Some("size") => {+ let v = args.next().unwrap_or_default();+ let (w, h) = v.split_once('x').ok_or("--size WxH")?;+ size = egui::vec2(w.parse().map_err(|_| "bad width")?, h.parse().map_err(|_| "bad height")?);+ }+ Some("scale") => scale = args.next().and_then(|v| v.parse().ok()).ok_or("bad --scale")?,+ Some(k) => opts.push((k.to_string(), args.next().unwrap_or_default())),+ None => file = Some(a),+ }+ }+ let mut harness = Harness::builder().with_size(size).with_pixels_per_point(scale).build_eframe(move |_cc| {+ let mut app = PrintCraftApp::new();+ if let Some(f) = &file {+ let bytes = std::fs::read(f).unwrap_or_default();+ let name = std::path::Path::new(f).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ if let Err(e) = app.open_bytes(&name, Some(f.clone()), bytes) {+ eprintln!("shot: {f}: {e}");+ }+ }+ for (k, v) in &opts {+ if let Err(e) = app.set_option(k, v) {+ eprintln!("shot: --{k} {v}: {e}");+ }+ }+ app+ });+ // Let fonts install, layout settle and background renders arrive.+ let start = Instant::now();+ harness.run_steps(4);+ while start.elapsed() < Duration::from_secs(20) {+ harness.run_steps(2);+ if !harness.state().render_pending() {+ harness.run_steps(3);+ if !harness.state().render_pending() {+ break;+ }+ }+ std::thread::sleep(Duration::from_millis(30));+ }+ let image = harness.render()?;+ image.save(&out).map_err(|e| e.to_string())?;+ eprintln!("shot: wrote {out} ({}×{})", image.width(), image.height());+ Ok(())+}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 71b951d5a..d266595ba 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -4,14 +4,16 @@//! Page images come from the engine's render pool as whole-page rasters at the current zoom;//! stale rasters are shown stretched until the sharp one arrives (tiling comes in M3.3).-use std::collections::HashMap;+use std::collections::{BTreeSet, HashMap, HashSet};+use std::ops::Range;+use std::sync::Arc;use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, TextureHandle, TextureOptions, Vec2, pos2, vec2};-use printcraft_engine::DocId;-use printcraft_render::{DocInfo, LinkTarget, RenderPool, RenderRequest};+use printcraft_engine::{DocId, Edit};+use printcraft_render::{DocInfo, LinkTarget, PageText, RenderPool, RenderRequest, RequestKind, Tile};use crate::theme::{self, Tokens};-use crate::{PrintCraftApp, QuickTool, RightPanel, icons};+use crate::{PrintCraftApp, QuickTool, RightPanel, icons, widgets};/// Logical pixels per PDF point at 100% (96 dpi, like browsers).pub const PT: f32 = 96.0 / 72.0;@@ -20,6 +22,12 @@ const MARGIN: f32 = 28.0;/// Horizontal gutter that keeps pages clear of the floating quick-action bar.const SIDE: f32 = 70.0;const THUMB_TAG: u64 = 1 << 63;+const TEXT_TAG: u64 = 1 << 62;+/// Pages whose raster would exceed this many device pixels on a side are drawn in tiles.+const TILE_THRESHOLD: f32 = 4096.0;+const TILE: u32 = 1024;+/// Longest side of the low-resolution backdrop drawn under tiles.+const BASE_SIDE: f32 = 2048.0;const THUMB_W: f32 = 132.0;#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -36,6 +44,31 @@ pub enum PageLayout {Single,}+/// The find bar (⌘F): query, matches across the document, current match.+#[derive(Default)]+pub struct Find {+ pub query: String,+ /// (page, glyph range) in document order.+ pub matches: Vec<(usize, Range<usize>)>,+ pub current: Option<usize>,+ pub focus: bool,+ pub case_query: String,+}++/// A text selection on one page, in reading-order glyph indices.+#[derive(Clone, Copy, Debug, PartialEq)]+struct Selection {+ page: usize,+ anchor: usize,+ head: usize,+}++impl Selection {+ fn range(&self) -> Range<usize> {+ self.anchor.min(self.head)..self.anchor.max(self.head) + 1+ }+}+struct PageTex {tag: u64,tex: TextureHandle,@@ -46,6 +79,8 @@ pub struct DocView {pub zoom: f32,pub fit: Fit,pub layout: PageLayout,+ /// View rotation in degrees clockwise (0, 90, 180, 270); display only, never saved.+ pub rotation: u16,pub current: usize,pub organize: bool,pub highlight_fields: bool,@@ -56,11 +91,37 @@ pub struct DocView {/// Briefly outline an annotation after navigating to it from a panel.pub flash: Option<(usize, [f32; 4], f64)>,pages: HashMap<usize, PageTex>,+ /// Pages the renderer could not draw, with the reason (never re-requested).+ errors: HashMap<usize, String>,+ /// When each still-missing page was first shown, to flag unusually slow renders.+ waiting_since: HashMap<usize, f64>,thumbs: HashMap<usize, TextureHandle>,+ /// Sharp tiles of large pages: (page, tile x, tile y) → (scale tag, texture).+ tiles: HashMap<(usize, u32, u32), (u64, TextureHandle)>,+ /// Text layers, extracted in the background on demand (selection, find, copy).+ texts: HashMap<usize, Arc<PageText>>,+ text_failed: HashSet<usize>,+ pub find: Option<Find>,+ selection: Option<Selection>,last_queue: Vec<RenderRequest>,viewport_w: f32,viewport_h: f32,page_count: usize,+ /// Page heights in points (view space), for mapping text positions to scroll offsets.+ page_heights: Vec<f32>,+ /// Screen rects of the pages drawn last frame (hit-testing, tests, automation).+ screen_rects: Vec<(usize, Rect)>,+ screen_xforms: Vec<(usize, PageXform)>,+ /// The scroll viewport on screen last frame.+ viewport_screen: Rect,+ /// Pending zoom anchor: page, position within it (0..1), and offset from the viewport corner.+ zoom_anchor: Option<(usize, f32, f32, Vec2)>,+ /// Pages selected in the organize grid (0-based). Empty means "the current page".+ pub selected: BTreeSet<usize>,+ /// Anchor for ⇧-click range selection in the organize grid.+ select_anchor: Option<usize>,+ /// An edit requested by the view (organize toolbar, keys), applied by the app this frame.+ pub pending_edit: Option<Edit>,}impl DocView {@@ -70,6 +131,7 @@ impl DocView {zoom: 1.0,fit: Fit::Width,layout: PageLayout::Continuous,+ rotation: 0,current: 0,organize: false,highlight_fields: false,@@ -78,12 +140,163 @@ impl DocView {goto: None,flash: None,pages: HashMap::new(),+ errors: HashMap::new(),+ waiting_since: HashMap::new(),thumbs: HashMap::new(),+ tiles: HashMap::new(),+ texts: HashMap::new(),+ text_failed: HashSet::new(),+ find: None,+ selection: None,last_queue: Vec::new(),viewport_w: 800.0,viewport_h: 600.0,page_count: info.pages.len(),+ page_heights: info.pages.iter().map(|p| p.height).collect(),+ screen_rects: Vec::new(),+ screen_xforms: Vec::new(),+ viewport_screen: Rect::NOTHING,+ zoom_anchor: None,+ selected: BTreeSet::new(),+ select_anchor: None,+ pending_edit: None,+ }+ }++ /// The document's content or page list changed (an edit, undo or redo): drop caches and+ /// adopt the new page geometry, keeping the reader's place where possible.+ pub fn document_changed(&mut self, info: &DocInfo) {+ self.invalidate_content();+ self.page_count = info.pages.len();+ self.page_heights = info.pages.iter().map(|p| p.height).collect();+ let last = self.page_count.saturating_sub(1);+ self.current = self.current.min(last);+ self.page_input = (self.current + 1).to_string();+ self.selected.retain(|p| *p <= last);+ if self.select_anchor.is_some_and(|a| a > last) {+ self.select_anchor = None;}+ self.goto = None;+ self.zoom_anchor = None;+ self.flash = None;+ }++ /// Pages an organize command acts on: the selection, or the current page.+ pub fn target_pages(&self) -> Vec<usize> {+ if self.selected.is_empty() { vec![self.current] } else { self.selected.iter().copied().collect() }+ }++ /// Select pages in the organize grid (tests, automation). Empty clears the selection.+ pub fn select_pages(&mut self, pages: &[usize]) {+ self.selected = pages.iter().copied().filter(|p| *p < self.page_count).collect();+ if let Some(first) = self.selected.first() {+ self.current = *first;+ }+ }++ pub fn render_pending(&self) -> bool {+ !self.last_queue.is_empty()+ }++ /// Drop every cached raster and text layer (the document's appearance changed, e.g. a layer+ /// was toggled). Pages re-render on the next frame; the old textures are simply released.+ pub fn invalidate_content(&mut self) {+ self.pages.clear();+ self.thumbs.clear();+ self.tiles.clear();+ self.texts.clear();+ self.text_failed.clear();+ self.errors.clear();+ self.waiting_since.clear();+ self.last_queue.clear();+ self.selection = None;+ if let Some(f) = self.find.as_mut() {+ f.matches.clear();+ f.current = None;+ }+ }++ /// Open the find bar (or focus it if already open).+ pub fn open_find(&mut self) {+ let f = self.find.get_or_insert_with(Find::default);+ f.focus = true;+ }++ /// Re-run the search on all pages whose text is known (after the query changed).+ pub fn rerun_find(&mut self) {+ let Some(f) = self.find.as_mut() else { return };+ f.case_query = f.query.clone();+ f.matches.clear();+ f.current = None;+ let pages: Vec<usize> = self.texts.keys().copied().collect();+ for p in pages {+ self.refresh_find_page(p);+ }+ }++ fn refresh_find_page(&mut self, page: usize) {+ let (Some(f), Some(text)) = (self.find.as_mut(), self.texts.get(&page)) else { return };+ if f.case_query.trim().is_empty() {+ return;+ }+ let current_key = f.current.and_then(|c| f.matches.get(c).cloned());+ f.matches.retain(|(p, _)| *p != page);+ f.matches.extend(text.find(&f.case_query).into_iter().map(|r| (page, r)));+ f.matches.sort_by_key(|(p, r)| (*p, r.start));+ f.current = match current_key {+ Some(k) => f.matches.iter().position(|m| *m == k),+ None => None,+ };+ if f.current.is_none() && !f.matches.is_empty() {+ // First match at or after the page being viewed.+ let cur = self.current;+ let i = f.matches.iter().position(|(p, _)| *p >= cur).unwrap_or(0);+ f.current = Some(i);+ let (p, _) = f.matches[i];+ self.flash_match(p);+ }+ }++ /// Move to the next/previous match.+ pub fn find_step(&mut self, forward: bool) {+ let Some(f) = self.find.as_mut() else { return };+ if f.matches.is_empty() {+ return;+ }+ let n = f.matches.len();+ let c = f.current.unwrap_or(0);+ let next = if forward { (c + 1) % n } else { (c + n - 1) % n };+ f.current = Some(next);+ let p = f.matches[next].0;+ self.flash_match(p);+ }++ fn flash_match(&mut self, page: usize) {+ let frac = self+ .find+ .as_ref()+ .and_then(|f| f.current.and_then(|c| f.matches.get(c)))+ .and_then(|(p, r)| self.texts.get(p).and_then(|t| t.glyphs.get(r.start)).map(|g| g.rect[1]))+ .zip(self.page_heights.get(page).copied())+ .map(|(y, h)| ((y - 60.0) / h).clamp(0.0, 1.0))+ .unwrap_or(0.0);+ self.goto = Some((page, frac));+ self.current = page;+ }++ /// Screen position of the centre of glyph `glyph` on `page`, if that page is on screen and its+ /// text layer is loaded (used by UI tests and automation to aim pointer input).+ pub fn glyph_screen_pos(&self, page: usize, glyph: usize) -> Option<Pos2> {+ let (_, xf) = self.screen_xforms.iter().find(|(p, _)| *p == page)?;+ let g = self.texts.get(&page)?.glyphs.get(glyph)?;+ Some(xf.view_rect(g.rect).center())+ }++ /// Selected text, if any (⌘C).+ pub fn selected_text(&self) -> Option<String> {+ let s = self.selection?;+ let t = self.texts.get(&s.page)?;+ Some(t.text_of(s.range())).filter(|x| !x.is_empty())}pub fn thumb(&self, page: usize) -> Option<&TextureHandle> {@@ -97,11 +310,36 @@ impl DocView {self.page_input = (page + 1).to_string();}+ /// Rotate the view 90° clockwise or counter-clockwise (View ▸ Rotate View, ⇧⌘+ / ⇧⌘−).+ pub fn rotate_view(&mut self, clockwise: bool) {+ self.rotation = (self.rotation + if clockwise { 90 } else { 270 }) % 360;+ self.goto = Some((self.current, 0.0));+ }++ /// Displayed page size in points for this view rotation.+ fn display_size(&self, p: &printcraft_render::PageInfo) -> (f32, f32) {+ if self.rotation % 180 == 90 { (p.height, p.width) } else { (p.width, p.height) }+ }++ /// Zoom keeping the centre of the view still.pub fn set_zoom(&mut self, zoom: f32) {- let frac = 0.0;+ let centre = self.viewport_screen.center();+ self.zoom_at(zoom, centre);+ }++ /// Zoom keeping the document point under `screen_pos` still (pinch, ⌘-scroll).+ pub fn zoom_at(&mut self, zoom: f32, screen_pos: Pos2) {+ let anchor = self.screen_rects.iter().find(|(_, r)| r.expand(GAP).contains(screen_pos)).map(|(p, r)| {+ let f = (screen_pos - r.min) / r.size();+ (*p, f.x.clamp(0.0, 1.0), f.y.clamp(0.0, 1.0), screen_pos - self.viewport_screen.min)+ });self.zoom = zoom.clamp(0.08, 64.0);self.fit = Fit::None;- self.goto = Some((self.current, frac));+ match anchor {+ Some(a) => self.zoom_anchor = Some(a),+ // Nothing on screen yet (e.g. a launch option): align the current page instead.+ None => self.goto = Some((self.current, 0.0)),+ }}/// Standard zoom steps (as in Acrobat's zoom menu).@@ -117,16 +355,46 @@ impl DocView {/// Pull finished renders into textures.pub fn receive(&mut self, ctx: &egui::Context, pool: &RenderPool) {let mut got = false;- while let Some(r) = pool.try_recv() {+ // Inline (single-threaded, e.g. web) rendering happens inside try_recv: one page per frame.+ let budget = if pool.is_inline() { 1 } else { usize::MAX };+ let mut n = 0;+ while n < budget+ && let Some(r) = pool.try_recv()+ {+ n += 1;got = true;+ if r.request.kind == RequestKind::Text {+ match r.text {+ Some(t) => {+ self.texts.insert(r.request.page, t);+ self.refresh_find_page(r.request.page);+ }+ None => {+ log::warn!("page {} text: {}", r.request.page + 1, r.error.unwrap_or_default());+ self.text_failed.insert(r.request.page);+ }+ }+ continue;+ }+ if let Some(e) = r.error {+ log::warn!("page {}: {e}", r.request.page + 1);+ self.errors.insert(r.request.page, e);+ continue;+ }let img = egui::ColorImage::from_rgba_premultiplied([r.width as usize, r.height as usize], &r.rgba);let page = r.request.page;+ if let Some(t) = r.request.tile {+ let tex = ctx.load_texture(format!("tile-{:?}-{page}-{}-{}", self.id, t.x, t.y), img, TextureOptions::LINEAR);+ self.tiles.insert((page, t.x / TILE, t.y / TILE), (r.request.tag, tex));+ continue;+ }if r.request.tag & THUMB_TAG != 0 {let tex = ctx.load_texture(format!("thumb-{:?}-{page}", self.id), img, TextureOptions::LINEAR);self.thumbs.insert(page, tex);} else {let tex = ctx.load_texture(format!("page-{:?}-{page}", self.id), img, TextureOptions::LINEAR);self.pages.insert(page, PageTex { tag: r.request.tag, tex });+ self.waiting_since.remove(&page);}}if got {@@ -135,15 +403,15 @@ impl DocView {}fn fit_zoom(&mut self, info: &DocInfo) {- let max_w = info.pages.iter().map(|p| p.width).fold(1.0, f32::max);+ let max_w = info.pages.iter().map(|p| self.display_size(p).0).fold(1.0, f32::max);let avail_w = (self.viewport_w - 2.0 * SIDE).max(100.0);let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };match self.fit {Fit::Width => self.zoom = (avail_w - GAP * (per_row - 1.0)) / (max_w * PT * per_row),Fit::Page => {- let p = &info.pages[self.current.min(info.pages.len() - 1)];- let zw = (avail_w - GAP * (per_row - 1.0)) / (p.width * PT * per_row);- let zh = (self.viewport_h - 2.0 * MARGIN) / (p.height * PT);+ let (w, h) = self.display_size(&info.pages[self.current.min(info.pages.len() - 1)]);+ let zw = (avail_w - GAP * (per_row - 1.0)) / (w * PT * per_row);+ let zh = (self.viewport_h - 2.0 * MARGIN) / (h * PT);self.zoom = zw.min(zh);}Fit::None => {}@@ -159,14 +427,15 @@ impl DocView {match self.layout {PageLayout::Continuous | PageLayout::Single => {for p in &info.pages {- let size = vec2(p.width * s, p.height * s);+ let (w, h) = self.display_size(p);+ let size = vec2(w * s, h * s);rects.push(Rect::from_min_size(pos2(((content_w - size.x) / 2.0).max(SIDE), y), size));y += size.y + GAP;}}PageLayout::TwoUp => {for pair in info.pages.chunks(2) {- let sizes: Vec<Vec2> = pair.iter().map(|p| vec2(p.width * s, p.height * s)).collect();+ let sizes: Vec<Vec2> = pair.iter().map(|p| self.display_size(p)).map(|(w, h)| vec2(w * s, h * s)).collect();let row_w: f32 = sizes.iter().map(|v| v.x).sum::<f32>() + GAP * (sizes.len() as f32 - 1.0);let row_h = sizes.iter().map(|v| v.y).fold(0.0, f32::max);let mut x = ((content_w - row_w) / 2.0).max(SIDE);@@ -187,32 +456,103 @@ impl DocView {}}-/// Map a user-space rect on a page to screen space, honouring crop box and rotation.-pub fn page_to_screen(info: &DocInfo, page: usize, page_rect: Rect, r: [f32; 4]) -> Rect {- let p = &info.pages[page];- let [cx0, cy0, cx1, cy1] = p.crop;- let (cw, ch) = ((cx1 - cx0).max(1.0), (cy1 - cy0).max(1.0));- let map = |x: f32, y: f32| -> Pos2 {- // Normalised coordinates in the unrotated crop box, y down.- let (u, v) = ((x - cx0) / cw, (cy1 - y) / ch);- let (u, v) = match p.rotation {+/// Maps between a page's coordinate spaces and the screen, including view rotation.+///+/// *View space* is the page as rendered (points, y down, the document's own `/Rotate` applied);+/// normalised page coordinates `(u, v)` are view space divided by the page size. The view+/// rotation (View ▸ Rotate View) turns the page clockwise on screen by `rot` degrees.+#[derive(Clone, Copy)]+pub struct PageXform {+ /// The page's rectangle on screen (already rotated, so width/height may be swapped).+ pub rect: Rect,+ pub rot: u16,+ /// Page size in view space (unrotated by the view).+ pub pw: f32,+ pub ph: f32,+}++impl PageXform {+ pub fn norm_to_screen(&self, u: f32, v: f32) -> Pos2 {+ let (a, b) = match self.rot {90 => (1.0 - v, u),180 => (1.0 - u, 1.0 - v),270 => (v, 1.0 - u),_ => (u, v),};- pos2(page_rect.left() + u * page_rect.width(), page_rect.top() + v * page_rect.height())- };- Rect::from_two_pos(map(r[0], r[1]), map(r[2], r[3]))+ pos2(self.rect.left() + a * self.rect.width(), self.rect.top() + b * self.rect.height())+ }++ pub fn screen_to_norm(&self, p: Pos2) -> (f32, f32) {+ let (a, b) = ((p.x - self.rect.left()) / self.rect.width().max(1e-3), (p.y - self.rect.top()) / self.rect.height().max(1e-3));+ match self.rot {+ 90 => (b, 1.0 - a),+ 180 => (1.0 - a, 1.0 - b),+ 270 => (1.0 - b, a),+ _ => (a, b),+ }+ }++ /// Screen point → view space (points).+ pub fn screen_to_view(&self, p: Pos2) -> (f32, f32) {+ let (u, v) = self.screen_to_norm(p);+ (u * self.pw, v * self.ph)+ }++ /// A view-space rect [x0, y0, x1, y1] → screen rect.+ pub fn view_rect(&self, g: [f32; 4]) -> Rect {+ Rect::from_two_pos(self.norm_to_screen(g[0] / self.pw, g[1] / self.ph), self.norm_to_screen(g[2] / self.pw, g[3] / self.ph))+ }++ /// A PDF user-space rect (crop box, document `/Rotate`) → screen rect.+ pub fn user_rect(&self, info: &DocInfo, page: usize, r: [f32; 4]) -> Rect {+ let p = &info.pages[page];+ let [cx0, cy0, cx1, cy1] = p.crop;+ let (cw, ch) = ((cx1 - cx0).max(1.0), (cy1 - cy0).max(1.0));+ let norm = |x: f32, y: f32| -> (f32, f32) {+ let (u, v) = ((x - cx0) / cw, (cy1 - y) / ch);+ match p.rotation {+ 90 => (1.0 - v, u),+ 180 => (1.0 - u, 1.0 - v),+ 270 => (v, 1.0 - u),+ _ => (u, v),+ }+ };+ let (a, b) = (norm(r[0], r[1]), norm(r[2], r[3]));+ Rect::from_two_pos(self.norm_to_screen(a.0, a.1), self.norm_to_screen(b.0, b.1))+ }++ /// Draw a texture covering the normalised page region, rotated with the view.+ pub fn paint_image(&self, painter: &egui::Painter, tex: egui::TextureId, u0: f32, v0: f32, u1: f32, v1: f32) {+ let mut mesh = egui::Mesh::with_texture(tex);+ let corners = [(u0, v0, 0.0, 0.0), (u1, v0, 1.0, 0.0), (u1, v1, 1.0, 1.0), (u0, v1, 0.0, 1.0)];+ for (u, v, tu, tv) in corners {+ mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(u, v), uv: pos2(tu, tv), color: Color32::WHITE });+ }+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(0, 2, 3);+ painter.add(egui::Shape::mesh(mesh));+ }}pub fn shortcuts(view: &mut DocView, ctx: &egui::Context) {use egui::{Key, KeyboardShortcut, Modifiers};+ if ctx.input_mut(|i| i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::F))) {+ view.open_find();+ }if ctx.egui_wants_keyboard_input() {return;}let cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);let pressed = |s: KeyboardShortcut| ctx.input_mut(|i| i.consume_shortcut(&s));+ // Rotation first: egui matches ⌘+ loosely with respect to Shift.+ if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Plus))+ || pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Equals))+ {+ view.rotate_view(true);+ }+ if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Minus)) {+ view.rotate_view(false);+ }if pressed(cmd(Key::Plus)) || pressed(cmd(Key::Equals)) {view.zoom_step(true);}@@ -230,7 +570,25 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context) {view.fit = Fit::Width;view.goto = Some((view.current, 0.0));}+ if pressed(cmd(Key::G)) {+ view.find_step(true);+ }+ if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::G)) {+ view.find_step(false);+ }+ // ⌘C arrives as a Copy event on most platforms.+ let copy = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Copy)));+ if copy && let Some(text) = view.selected_text() {+ ctx.copy_text(text);+ }let key = |k| ctx.input(|i| i.key_pressed(k));+ if key(Key::Escape) {+ if view.selection.is_some() {+ view.selection = None;+ } else {+ view.find = None;+ }+ }if key(Key::Home) {view.go_to_page(0);}@@ -259,7 +617,7 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {let view = &mut app.views[index];notices(view, info, ui, &t);if view.organize {- organize_grid(view, info, &doc.renderer, ui, &t);+ organize_grid(view, info, &doc.renderer, doc.editable(), ui, &t);return;}@@ -272,10 +630,17 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {let zoom_delta = ui.input(|i| i.zoom_delta());if (zoom_delta - 1.0).abs() > 0.001 && ui.rect_contains_pointer(avail) {let z = view.zoom * zoom_delta;- view.set_zoom(z);+ match ui.input(|i| i.pointer.hover_pos()) {+ Some(p) => view.zoom_at(z, p),+ None => view.set_zoom(z),+ }}+ view.viewport_screen = avail;- let max_w = info.pages.iter().map(|p| p.width).fold(0.0, f32::max) * view.zoom * PT * if view.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };+ let max_w = info.pages.iter().map(|p| view.display_size(p).0).fold(0.0, f32::max)+ * view.zoom+ * PT+ * if view.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };let content_w = (max_w + 2.0 * SIDE).max(avail.width());let rects = view.layout(info, content_w);let visible_pages: Vec<usize> = match view.layout {@@ -294,7 +659,11 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {drag: if app.quick_tool == QuickTool::Hand { egui::scroll_area::DragScroll::Always } else { egui::scroll_area::DragScroll::OnTouch },..Default::default()});- if let Some((page, frac)) = view.goto.take() {+ if let Some((page, fx, fy, rel)) = view.zoom_anchor.take() {+ let r = rects[page.min(rects.len() - 1)];+ let point = pos2(r.left() + fx * r.width(), r.top() - y_shift + fy * r.height());+ scroll = scroll.scroll_offset(vec2((point.x - rel.x).max(0.0), (point.y - rel.y).max(0.0)));+ } else if let Some((page, frac)) = view.goto.take() {let page = page.min(rects.len() - 1);let r = rects[page];scroll = scroll.vertical_scroll_offset((r.top() - y_shift - GAP + frac * r.height()).max(0.0));@@ -307,11 +676,14 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {let mut clicked_link: Option<LinkTarget> = None;let out = scroll.show_viewport(ui, |ui, viewport| {- let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), Sense::click());+ let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), Sense::click_and_drag());let origin = resp_rect.min - vec2(0.0, y_shift);let painter = ui.painter();let visible = viewport.translate(resp_rect.min.to_vec2());let mut wanted = Vec::new();+ let mut visible_now = Vec::new();+ view.screen_rects.clear();+ view.screen_xforms.clear();let mut current = view.current;let mut best_overlap = -1.0f32;let pointer = ui.input(|i| i.pointer.hover_pos());@@ -320,33 +692,163 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {if !r.intersects(visible.expand(400.0)) {continue;}+ if r.intersects(visible) {+ visible_now.push(i);+ view.screen_rects.push((i, r));+ view.screen_xforms+ .push((i, PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) }));+ }let overlap = r.intersect(visible).height();if overlap > best_overlap {best_overlap = overlap;current = i;}- // Shadow + paper.- painter.rect_filled(r.translate(vec2(0.0, 2.0)).expand(1.5), CornerRadius::same(2), t.page_shadow);+ let xf = PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) };+ // Soft shadow + paper.+ painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));painter.rect_filled(r, CornerRadius::ZERO, Color32::WHITE);- match view.pages.get(&i) {- Some(p) => {- painter.image(p.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);- if p.tag != tag {- wanted.push(i);+ if let Some(err) = view.errors.get(&i) {+ painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));+ icons::paint(+ ui,+ Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),+ "triangle-alert",+ 26.0,+ Color32::from_rgb(0xC8, 0x3A, 0x3A),+ );+ let msg = ui.fonts_mut(|f| {+ f.layout(+ format!("This page couldn't be displayed.\n{err}"),+ theme::regular(12.5),+ Color32::from_rgb(0x6A, 0x2A, 0x2A),+ (r.width() - 40.0).max(80.0),+ )+ });+ painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);+ } else {+ let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));+ let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD;+ // Whole-page raster: sharp when small, a low-res backdrop when tiled.+ let (want_scale, want_tag) = if tiled {+ let bs = BASE_SIDE / pw_pt.max(ph_pt);+ (bs, (bs * 1000.0) as u64)+ } else {+ (scale, tag)+ };+ match view.pages.get(&i) {+ Some(p) => {+ xf.paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);+ if p.tag != want_tag {+ wanted.push((i, want_scale, want_tag, None));+ }+ }+ None => {+ wanted.push((i, want_scale, want_tag, None));+ let now = ui.input(|inp| inp.time);+ let since = *view.waiting_since.entry(i).or_insert(now);+ let msg = if now - since > 6.0 { "Still rendering — this page is unusually complex…" } else { "Rendering…" };+ painter.text(r.center(), Align2::CENTER_CENTER, msg, theme::regular(12.0), t.text_faint);}}- None => {- wanted.push(i);- painter.text(r.center(), Align2::CENTER_CENTER, "Rendering…", theme::regular(12.0), t.text_faint);+ if tiled && r.intersects(visible) {+ // Device-pixel geometry of the scaled page, and the visible part of it+ // (found by mapping the visible screen corners back into the page).+ let (dw, dh) = ((pw_pt * scale).round() as u32, (ph_pt * scale).round() as u32);+ let vis = r.intersect(visible);+ let corners = [vis.left_top(), vis.right_top(), vis.right_bottom(), vis.left_bottom()].map(|c| xf.screen_to_norm(c));+ let (u0, u1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.0), b.max(c.0)));+ let (v0, v1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.1), b.max(c.1)));+ let (vx0, vy0) = ((u0.max(0.0) * dw as f32) as u32, (v0.max(0.0) * dh as f32) as u32);+ let (vx1, vy1) = (((u1.min(1.0) * dw as f32).ceil() as u32).min(dw), ((v1.min(1.0) * dh as f32).ceil() as u32).min(dh));+ for ty in vy0 / TILE..=(vy1.saturating_sub(1)) / TILE {+ for tx in vx0 / TILE..=(vx1.saturating_sub(1)) / TILE {+ let (x, y) = (tx * TILE, ty * TILE);+ let (w, h) = (TILE.min(dw.saturating_sub(x)), TILE.min(dh.saturating_sub(y)));+ if w == 0 || h == 0 {+ continue;+ }+ match view.tiles.get(&(i, tx, ty)) {+ Some((ttag, tex)) if *ttag == tag => {+ let (fw, fh) = (dw as f32, dh as f32);+ xf.paint_image(painter, tex.id(), x as f32 / fw, y as f32 / fh, (x + w) as f32 / fw, (y + h) as f32 / fh);+ }+ _ => wanted.push((i, scale, tag, Some(Tile { x, y, w, h }))),+ }+ }+ }+ }+ }+ painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside);++ // Text layer: find matches, selection, I-beam and drag-to-select.+ let to_screen = |g: [f32; 4]| xf.view_rect(g);+ if let Some(text) = view.texts.get(&i).cloned() {+ if let Some(f) = &view.find {+ for (k, (mp, range)) in f.matches.iter().enumerate() {+ if *mp != i {+ continue;+ }+ let current = f.current == Some(k);+ for lr in text.line_rects(range.clone()) {+ let fill = if current {+ Color32::from_rgba_unmultiplied(255, 140, 0, 110)+ } else {+ Color32::from_rgba_unmultiplied(255, 214, 0, 90)+ };+ painter.rect_filled(to_screen(lr).expand(1.0), CornerRadius::same(2), fill);+ }+ }+ }+ if let Some(sel) = view.selection.filter(|s| s.page == i) {+ for lr in text.line_rects(sel.range()) {+ painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));+ }+ }+ if !hand && let Some(p) = pointer.filter(|p| r.contains(*p)) {+ let (vx, vy) = xf.screen_to_view(p);+ let over_text = text.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]);+ let over_link = info.links.iter().any(|l| l.page == i && xf.user_rect(info, i, l.rect).contains(p));+ if over_text && !over_link {+ ui.ctx().set_cursor_icon(egui::CursorIcon::Text);+ }+ let press_here = ui.input(|inp| inp.pointer.press_origin()).is_some_and(|o| r.contains(o));+ if resp.drag_started() && press_here && !over_link {+ let origin = ui.input(|inp| inp.pointer.press_origin()).unwrap_or(p);+ let (ox, oy) = xf.screen_to_view(origin);+ view.selection = text.nearest(ox, oy).map(|a| Selection { page: i, anchor: a, head: a });+ }+ if resp.dragged()+ && let Some(sel) = view.selection.as_mut().filter(|s| s.page == i)+ && let Some(h) = text.nearest(vx, vy)+ {+ sel.head = h;+ }+ if resp.double_clicked() && over_text {+ if let Some(a) = text.nearest(vx, vy) {+ // Expand to the word: stop at inferred spaces, explicit spaces and line ends.+ let is_break = |k: usize| text.glyphs[k].text.trim().is_empty();+ let mut s0 = a;+ while s0 > 0 && !text.space_before[s0] && text.line_of[s0 - 1] == text.line_of[s0] && !is_break(s0 - 1) {+ s0 -= 1;+ }+ let mut e = a;+ while e + 1 < text.glyphs.len() && !text.space_before[e + 1] && text.line_of[e + 1] == text.line_of[e] && !is_break(e + 1)+ {+ e += 1;+ }+ view.selection = Some(Selection { page: i, anchor: s0, head: e });+ }+ } else if resp.clicked() && !over_link {+ view.selection = None;+ }}}- painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);// Form-field highlight (Acrobat's "Highlight existing fields").if view.highlight_fields {for f in info.fields.iter().filter(|f| f.page == Some(i)) {if let Some(fr) = f.rect {- let sr = page_to_screen(info, i, r, fr);+ let sr = xf.user_rect(info, i, fr);painter.rect_filled(sr, CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48));painter.rect_stroke(sr,@@ -360,7 +862,7 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {// Link hover + click.if let Some(p) = pointer {for l in info.links.iter().filter(|l| l.page == i) {- let sr = page_to_screen(info, i, r, l.rect);+ let sr = xf.user_rect(info, i, l.rect);if sr.contains(p) {ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);let label = match &l.target {@@ -376,7 +878,7 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {}// Annotation hover shows the comment, as Acrobat's popups do.for a in info.annotations.iter().filter(|a| a.page == i) {- let sr = page_to_screen(info, i, r, a.rect);+ let sr = xf.user_rect(info, i, a.rect);if sr.contains(p) && hover_text.is_none() {let who = a.author.clone().unwrap_or_else(|| a.subtype.clone());let body = a.contents.clone().unwrap_or_default();@@ -393,7 +895,7 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {let age = (now - t0) as f32;if age < 1.6 {let a = ((1.6 - age) / 1.6 * 255.0) as u8;- let sr = page_to_screen(info, i, r, fr).expand(4.0);+ let sr = xf.user_rect(info, i, fr).expand(4.0);painter.rect_stroke(sr,CornerRadius::same(3),@@ -412,19 +914,37 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {view.page_input = (current + 1).to_string();}}- wanted+ (wanted, visible_now)});+ // Bound texture memory: keep sharp rasters only near the current page.+ if view.pages.len() > 24 {+ let cur = view.current;+ view.pages.retain(|&p, _| p.abs_diff(cur) <= 8);+ }// Schedule renders: visible pages first (nearest the current page), then thumbnails.- let mut wanted = out.inner;+ let (mut wanted, visible_now) = out.inner;let cur = view.current;- wanted.sort_by_key(|&p| (p as isize - cur as isize).unsigned_abs());- let mut queue: Vec<RenderRequest> = wanted.into_iter().map(|page| RenderRequest { page, scale, tag }).collect();+ // Nearest pages first; for each page, the backdrop before its tiles.+ wanted.sort_by_key(|w| ((w.0 as isize - cur as isize).unsigned_abs(), w.3.is_some()));+ // Tiles for other zoom levels or far-away pages are useless: free them.+ view.tiles.retain(|(p, _, _), (t, _)| *t == tag && p.abs_diff(cur) <= 2);+ let mut queue: Vec<RenderRequest> =+ wanted.iter().map(|&(page, scale, tag, tile)| RenderRequest { page, kind: RequestKind::Pixels, tile, scale, tag }).collect();+ // Text layers: visible pages for selection, every page while a search is active.+ let need_text = |p: &usize| !view.texts.contains_key(p) && !view.text_failed.contains(p);+ let mut text_pages: Vec<usize> = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() };+ if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {+ let n = info.pages.len();+ let rest: Vec<usize> = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect();+ text_pages.extend(rest);+ }+ queue.extend(text_pages.into_iter().map(|page| RenderRequest { page, kind: RequestKind::Text, tile: None, scale: 1.0, tag: TEXT_TAG }));if want_thumbs {let s = THUMB_W * ppp / info.pages.iter().map(|p| p.width).fold(1.0, f32::max);for page in 0..info.pages.len() {- if !view.thumbs.contains_key(&page) {- queue.push(RenderRequest { page, scale: s, tag: THUMB_TAG });+ if !view.thumbs.contains_key(&page) && !view.errors.contains_key(&page) {+ queue.push(RenderRequest { page, kind: RequestKind::Pixels, tile: None, scale: s, tag: THUMB_TAG });}}}@@ -444,6 +964,7 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {});});}+ find_bar(view, info.pages.len(), avail, ui, &t);match clicked_link {Some(LinkTarget::Page(p)) => view.go_to_page(p),Some(LinkTarget::Uri(u)) => ui.ctx().open_url(egui::OpenUrl::new_tab(u)),@@ -453,6 +974,76 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {quick_bar(app, avail, ui);}+/// Acrobat-style floating find bar at the top-right of the document area.+fn find_bar(view: &mut DocView, pages: usize, area: Rect, ui: &mut egui::Ui, t: &Tokens) {+ let Some(find) = view.find.as_mut() else { return };+ let mut close = false;+ let mut step: Option<bool> = None;+ let searched = view.texts.len() + view.text_failed.len();+ egui::Area::new(egui::Id::new("find-bar"))+ .order(egui::Order::Middle)+ .pivot(Align2::RIGHT_TOP)+ .fixed_pos(area.right_top() + vec2(-18.0, 12.0))+ .show(ui.ctx(), |ui| {+ egui::Frame::NONE+ .fill(t.card)+ .stroke(Stroke::new(1.0, t.border))+ .corner_radius(CornerRadius::same(10))+ .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 90 } else { 30 }) })+ .inner_margin(egui::Margin::symmetric(10, 6))+ .show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.add(icons::image("search", 16.0, t.text_muted));+ let edit = egui::TextEdit::singleline(&mut find.query)+ .id(egui::Id::new("find-input"))+ .hint_text("Find text")+ .desired_width(220.0)+ .frame(egui::Frame::NONE);+ let r = ui.add(edit);+ if find.focus {+ r.request_focus();+ find.focus = false;+ }+ if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {+ step = Some(!ui.input(|i| i.modifiers.shift));+ r.request_focus();+ }+ if r.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ close = true;+ }+ let status = if find.query.trim().is_empty() {+ String::new()+ } else if find.matches.is_empty() {+ if searched < pages { format!("Searching… {searched}/{pages}") } else { "No matches".into() }+ } else {+ let more = if searched < pages { "+" } else { "" };+ format!("{} of {}{more}", find.current.map(|c| c + 1).unwrap_or(0), find.matches.len())+ };+ ui.label(egui::RichText::new(status).font(theme::regular(12.0)).color(t.text_muted));+ if icons::button(ui, "chevron-up", 26.0, false, "Previous (⇧⌘G)").clicked() {+ step = Some(false);+ }+ if icons::button(ui, "chevron-down", 26.0, false, "Next (⌘G)").clicked() {+ step = Some(true);+ }+ if icons::button(ui, "x", 26.0, false, "Close (Esc)").clicked() {+ close = true;+ }+ });+ });+ });+ if close {+ view.find = None;+ return;+ }+ if find.query != find.case_query {+ view.rerun_find();+ }+ if let Some(forward) = step {+ view.find_step(forward);+ }+}+fn notices(view: &mut DocView, info: &DocInfo, ui: &mut egui::Ui, t: &Tokens) {if view.notice_dismissed {return;@@ -519,11 +1110,80 @@ fn quick_bar(app: &mut PrintCraftApp, area: Rect, ui: &mut egui::Ui) {});}-/// Organize pages: a thumbnail grid (Acrobat's Organize Pages view).-fn organize_grid(view: &mut DocView, info: &DocInfo, pool: &RenderPool, ui: &mut egui::Ui, t: &Tokens) {+/// The organize toolbar: page operations on the selection (Acrobat's Organize Pages bar).+fn organize_toolbar(view: &mut DocView, info: &DocInfo, editable: bool, ui: &mut egui::Ui, t: &Tokens) {+ let targets = view.target_pages();+ let n = info.pages.len();+ let (first, last) = (targets.first().copied().unwrap_or(0), targets.last().copied().unwrap_or(0));+ egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(16, 8)).show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ let label = match view.selected.len() {+ 0 => format!("Page {} of {n}", view.current + 1),+ 1 => "1 page selected".to_string(),+ k => format!("{k} pages selected"),+ };+ // Fixed width so the buttons never shift as the selection text changes.+ ui.add_sized([150.0, 30.0], egui::Label::new(egui::RichText::new(label).font(theme::medium(13.0)).color(t.text_muted)).truncate());+ ui.add_enabled_ui(editable, |ui| {+ if icons::button(ui, "rotate-ccw", 30.0, false, "Rotate counterclockwise").clicked() {+ view.pending_edit = Some(Edit::RotatePages { pages: targets.clone(), degrees: -90 });+ }+ if icons::button(ui, "rotate-cw", 30.0, false, "Rotate clockwise").clicked() {+ view.pending_edit = Some(Edit::RotatePages { pages: targets.clone(), degrees: 90 });+ }+ let can_delete = targets.len() < n;+ if ui.add_enabled_ui(can_delete, |ui| icons::button(ui, "trash-2", 30.0, false, "Delete pages (Delete)")).inner.clicked() {+ view.pending_edit = Some(Edit::DeletePages { pages: targets.clone() });+ }+ if icons::button(ui, "file-plus", 30.0, false, "Insert a blank page after the selection").clicked() {+ let c = info.pages[last].crop;+ let (w, h) = ((c[2] - c[0]).abs().max(1.0) as f64, (c[3] - c[1]).abs().max(1.0) as f64);+ view.pending_edit = Some(Edit::InsertBlankPage { at: last + 1, width: w, height: h });+ }+ if ui.add_enabled_ui(first > 0, |ui| icons::button(ui, "chevron-left", 30.0, false, "Move earlier")).inner.clicked() {+ view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first - 1 });+ }+ if ui.add_enabled_ui(last + 1 < n, |ui| icons::button(ui, "chevron-right", 30.0, false, "Move later")).inner.clicked() {+ view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first + 1 });+ }+ });+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if widgets::ghost_button(ui, "x", "Close").on_hover_text("Back to the document").clicked() {+ view.organize = false;+ }+ });+ });+ });+ // Keys act on the selection unless a text field has focus.+ if editable && !ui.ctx().egui_wants_keyboard_input() {+ use egui::{Key, KeyboardShortcut, Modifiers};+ let (del, all, esc) = ui.input_mut(|i| {+ (+ i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace),+ i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::A)),+ i.consume_key(Modifiers::NONE, Key::Escape),+ )+ });+ if del && targets.len() < n {+ view.pending_edit = Some(Edit::DeletePages { pages: targets });+ }+ if all {+ view.selected = (0..n).collect();+ }+ if esc {+ view.selected.clear();+ }+ }+}++/// Organize pages: a thumbnail grid (Acrobat's Organize Pages view). Click selects, ⌘-click+/// toggles, ⇧-click extends; double-click opens the page.+fn organize_grid(view: &mut DocView, info: &DocInfo, pool: &RenderPool, editable: bool, ui: &mut egui::Ui, t: &Tokens) {let ppp = ui.ctx().pixels_per_point();let cell = vec2(190.0, 250.0);let mut open_page = None;+ organize_toolbar(view, info, editable, ui, t);egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {ui.add_space(20.0);let cols = ((ui.available_width() - 40.0) / cell.x).floor().max(1.0) as usize;@@ -536,13 +1196,19 @@ fn organize_grid(view: &mut DocView, info: &DocInfo, pool: &RenderPool, ui: &mutlet Some(p) = info.pages.get(i) else { break };let c = Rect::from_min_size(pos2(row_rect.left() + left + col as f32 * cell.x, row_rect.top()), cell);let resp = ui.interact(c, ui.id().with(("org", i)), Sense::click());+ resp.widget_info(|| {+ egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, view.selected.contains(&i), format!("Page {}", p.label))+ });let s = (cell.x - 44.0) / p.width.max(1.0);let size = vec2(p.width * s, p.height * s).min(vec2(cell.x - 44.0, cell.y - 56.0));let pr = Rect::from_center_size(pos2(c.center().x, c.top() + 16.0 + size.y / 2.0), size);- let selected = i == view.current;+ let selected = view.selected.contains(&i) || (view.selected.is_empty() && i == view.current);if selected || resp.hovered() {ui.painter().rect_filled(c.shrink(6.0), CornerRadius::same(8), if selected { t.accent_soft } else { t.hover });}+ if view.selected.contains(&i) {+ ui.painter().rect_stroke(c.shrink(6.0), CornerRadius::same(8), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);+ }ui.painter().rect_filled(pr.translate(vec2(0.0, 1.5)), CornerRadius::same(1), t.page_shadow);ui.painter().rect_filled(pr, CornerRadius::ZERO, Color32::WHITE);if let Some(tex) = view.thumbs.get(&i) {@@ -551,6 +1217,19 @@ fn organize_grid(view: &mut DocView, info: &DocInfo, pool: &RenderPool, ui: &mutui.painter().rect_stroke(pr, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);ui.painter().text(pos2(c.center().x, pr.bottom() + 16.0), Align2::CENTER_CENTER, &p.label, theme::medium(12.0), t.text_muted);if resp.clicked() {+ let m = ui.input(|i| i.modifiers);+ if m.shift {+ let a = view.select_anchor.unwrap_or(view.current);+ view.selected = (a.min(i)..=a.max(i)).collect();+ } else if m.command {+ if !view.selected.remove(&i) {+ view.selected.insert(i);+ }+ view.select_anchor = Some(i);+ } else {+ view.selected = [i].into();+ view.select_anchor = Some(i);+ }view.current = i;}if resp.double_clicked() {@@ -560,8 +1239,10 @@ fn organize_grid(view: &mut DocView, info: &DocInfo, pool: &RenderPool, ui: &mut}});let s = THUMB_W * ppp / info.pages.iter().map(|p| p.width).fold(1.0, f32::max);- let queue: Vec<RenderRequest> =- (0..info.pages.len()).filter(|p| !view.thumbs.contains_key(p)).map(|page| RenderRequest { page, scale: s, tag: THUMB_TAG }).collect();+ let queue: Vec<RenderRequest> = (0..info.pages.len())+ .filter(|p| !view.thumbs.contains_key(p) && !view.errors.contains_key(p))+ .map(|page| RenderRequest { page, kind: RequestKind::Pixels, tile: None, scale: s, tag: THUMB_TAG })+ .collect();if queue != view.last_queue {pool.set_queue(queue.clone());view.last_queue = queue;diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rsindex c58aab9f1..a1eb6eed4 100644--- a/crates/ui-egui/src/chrome.rs+++ b/crates/ui-egui/src/chrome.rs@@ -30,13 +30,13 @@ pub fn tab_strip(app: &mut PrintCraftApp, ui: &mut egui::Ui) {let mut close = None;for i in 0..app.views.len() {let Some(doc) = app.session.get(app.views[i].id) else { continue };- let name = doc.name.clone();- if tab(ui, &t, &name, app.active == Some(i), &mut close, i).clicked() {+ let (name, dirty) = (doc.name.clone(), doc.dirty);+ if tab(ui, &t, &name, dirty, app.active == Some(i), &mut close, i).clicked() {app.active = Some(i);}}if let Some(i) = close {- app.close_tab(i);+ app.request_close_tab(i);}ui.add_space(4.0);if widgets::ghost_button(ui, "plus", "Open").on_hover_text("Open a PDF (⌘O)").clicked() {@@ -59,11 +59,13 @@ pub fn tab_strip(app: &mut PrintCraftApp, ui: &mut egui::Ui) {});}-fn tab(ui: &mut egui::Ui, t: &Tokens, name: &str, active: bool, close: &mut Option<usize>, index: usize) -> egui::Response {+fn tab(ui: &mut egui::Ui, t: &Tokens, name: &str, dirty: bool, active: bool, close: &mut Option<usize>, index: usize) -> egui::Response {let font = theme::regular(13.0);let label: String = if name.chars().count() > 28 { format!("{}…", name.chars().take(27).collect::<String>()) } else { name.to_string() };let text_w = ui.fonts_mut(|f| f.layout_no_wrap(label.clone(), font.clone(), t.text).size().x);let (rect, resp) = ui.allocate_exact_size(vec2(text_w + 64.0, 30.0), Sense::click());+ let a11y = if dirty { format!("{name} (edited)") } else { name.to_string() };+ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, active, &a11y));let bg = if active {t.chrome} else if resp.hovered() {@@ -85,13 +87,16 @@ fn tab(ui: &mut egui::Ui, t: &Tokens, name: &str, active: bool, close: &mut Optiif x.hovered() {ui.painter().rect_filled(x_rect, CornerRadius::same(4), t.pressed);}- if active || resp.hovered() || x.hovered() {+ // Unsaved changes: a dot where the close button sits, until the tab is hovered.+ if dirty && !resp.hovered() && !x.hovered() {+ ui.painter().circle_filled(x_rect.center(), 4.0, if active { t.text } else { t.text_muted });+ } else if active || resp.hovered() || x.hovered() {icons::paint(ui, x_rect, "x", 13.0, t.text_muted);}if x.clicked() {*close = Some(index);}- resp.on_hover_text(name)+ resp.on_hover_text(if dirty { format!("{name} — unsaved changes") } else { name.to_string() })}pub fn mode_bar(app: &mut PrintCraftApp, ui: &mut egui::Ui) {@@ -156,13 +161,43 @@ fn main_menu(app: &mut PrintCraftApp, ui: &mut egui::Ui) {if ui.add_enabled(has, egui::Button::new("Close file").shortcut_text("⌘W")).clicked()&& let Some(i) = app.active{- app.close_tab(i);+ app.request_close_tab(i);+ }+ let dirty = app.active_ids().and_then(|(_, id)| app.session.get(id)).is_some_and(|d| d.dirty);+ if ui.add_enabled(has && dirty, egui::Button::new("Save").shortcut_text("⌘S")).clicked() {+ app.save_active(crate::SaveTarget::InPlace);+ }+ if ui.add_enabled(has, egui::Button::new("Save as…").shortcut_text("⇧⌘S")).clicked() {+ app.save_active(crate::SaveTarget::As);+ }+ ui.separator();+ if ui.add_enabled(has, egui::Button::new("Find…").shortcut_text("⌘F")).clicked()+ && let Some(i) = app.active+ {+ app.views[i].open_find();}ui.separator();if ui.add_enabled(has, egui::Button::new("Document properties…").shortcut_text("⌘D")).clicked() {app.dialog = Some(Dialog::Properties(PropsTab::Description));}});+ ui.menu_button("Edit", |ui| {+ let doc = app.active_ids().and_then(|(_, id)| app.session.get(id));+ let undo = doc.and_then(|d| d.can_undo()).map(str::to_owned);+ let redo = doc.and_then(|d| d.can_redo()).map(str::to_owned);+ let label = |verb: &str, what: &Option<String>| what.as_ref().map(|w| format!("{verb} {w}")).unwrap_or_else(|| verb.to_string());+ if ui.add_enabled(undo.is_some(), egui::Button::new(label("Undo", &undo)).shortcut_text("⌘Z")).clicked() {+ app.undo();+ }+ if ui.add_enabled(redo.is_some(), egui::Button::new(label("Redo", &redo)).shortcut_text("⇧⌘Z")).clicked() {+ app.redo();+ }+ ui.separator();+ let has = app.active.is_some();+ if ui.add_enabled(has, egui::Button::new("Organize pages")).clicked() {+ app.run_command("page.organize");+ }+ });ui.menu_button("View", |ui| {if let Some(i) = app.active {let v = &mut app.views[i];@@ -182,6 +217,12 @@ fn main_menu(app: &mut PrintCraftApp, ui: &mut egui::Ui) {if widgets::menu_item(ui, "Zoom out", "⌘−").clicked() {v.zoom_step(false);}+ if widgets::menu_item(ui, "Rotate view clockwise", "⇧⌘+").clicked() {+ v.rotate_view(true);+ }+ if widgets::menu_item(ui, "Rotate view counterclockwise", "⇧⌘−").clicked() {+ v.rotate_view(false);+ }ui.separator();ui.label(egui::RichText::new("Page display").color(t.text_faint).small());for (l, label) in@@ -194,6 +235,10 @@ fn main_menu(app: &mut PrintCraftApp, ui: &mut egui::Ui) {}ui.separator();}+ if app.active.is_some() && widgets::menu_item(ui, "Full screen mode", "⌘L").clicked() {+ let ctx = ui.ctx().clone();+ app.set_full_screen(&ctx, true);+ }if widgets::menu_item(ui, "Read mode", "⌃⌘H").clicked() {app.mode = if app.mode == Mode::Read { Mode::AllTools } else { Mode::Read };}@@ -278,6 +323,9 @@ pub fn right_rail(app: &mut PrintCraftApp, ui: &mut egui::Ui) {if icons::button(ui, "zoom-in", 32.0, false, "Zoom in (⌘+)").clicked() {view.zoom_step(true);}+ if icons::button(ui, "rotate-cw", 32.0, false, "Rotate view clockwise (⇧⌘+)").clicked() {+ view.rotate_view(true);+ }let fit_icon = if view.fit == Fit::Width { "maximize" } else { "columns-2" };if icons::button(ui, fit_icon, 32.0, false, "Toggle fit page / fit width").clicked() {view.fit = if view.fit == Fit::Width { Fit::Page } else { Fit::Width };diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 90c3c7baf..19c8f110e 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -1,12 +1,29 @@//! Modal dialogs: Document Properties, Keyboard Shortcuts, About.-use egui::{Align, Layout, vec2};+use egui::{Align, Layout};use crate::theme::{self, Tokens};-use crate::{Dialog, PrintCraftApp, PropsTab, panels::human_size, widgets};+use printcraft_engine::Edit;++use crate::{CloseRequest, Dialog, PrintCraftApp, PropsTab, panels::human_size, widgets};++const INFO_KEYS: [&str; 4] = ["Title", "Author", "Subject", "Keywords"];pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {- let Some(dialog) = app.dialog else { return };+ password(app, ctx);+ save_prompt(app, ctx);+ let Some(dialog) = app.dialog else {+ app.props_draft = None;+ return;+ };+ // Seed the editable Description fields from the document when the dialog opens.+ if let (Dialog::Properties(_), Some((_, id))) = (dialog, app.active_ids())+ && app.props_draft.as_ref().is_none_or(|(d, _)| *d != id)+ && let Some(doc) = app.session.get(id)+ {+ app.props_draft = Some((id, INFO_KEYS.map(|k| doc.info_value(k).unwrap_or_default())));+ }+ let mut apply = false;let t = Tokens::get(ctx);let mut close = false;let mut next = dialog;@@ -17,7 +34,12 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {ui.label(egui::RichText::new("Document Properties").font(theme::semibold(18.0)));ui.add_space(8.0);ui.horizontal(|ui| {- for (tb, label) in [(PropsTab::Description, "Description"), (PropsTab::Security, "Security"), (PropsTab::Advanced, "Advanced")] {+ for (tb, label) in [+ (PropsTab::Description, "Description"),+ (PropsTab::Security, "Security"),+ (PropsTab::Fonts, "Fonts"),+ (PropsTab::Advanced, "Advanced"),+ ] {if widgets::mode_tab(ui, label, tab == tb).clicked() {next = Dialog::Properties(tb);}@@ -32,44 +54,76 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {ui.label(if v.is_empty() { egui::RichText::new("—").color(t.text_faint) } else { egui::RichText::new(v) });ui.end_row();};- egui::Grid::new("props").num_columns(2).spacing([18.0, 8.0]).min_col_width(140.0).show(ui, |ui| match tab {- PropsTab::Description => {- row(ui, "File", doc.name.clone());- row(ui, "Title", i.title.clone().unwrap_or_default());- row(ui, "Author", i.author.clone().unwrap_or_default());- row(ui, "Subject", i.subject.clone().unwrap_or_default());- row(ui, "Keywords", i.keywords.clone().unwrap_or_default());- row(ui, "Application", i.creator.clone().unwrap_or_default());- row(ui, "PDF producer", i.producer.clone().unwrap_or_default());- }- PropsTab::Security => {- row(ui, "Security method", if i.encrypted { "Password security".into() } else { "No security".into() });- for k in [- "Printing",- "Changing the document",- "Document assembly",- "Content copying",- "Commenting",- "Filling of form fields",- "Signing",- ] {- row(ui, k, if i.encrypted { "See permissions (M8)".into() } else { "Allowed".into() });+ egui::ScrollArea::vertical().max_height(460.0).auto_shrink([false, true]).show(ui, |ui| {+ egui::Grid::new("props").num_columns(2).spacing([18.0, 8.0]).min_col_width(140.0).show(ui, |ui| match tab {+ PropsTab::Description => {+ row(ui, "File", doc.name.clone());+ match app.props_draft.as_mut() {+ Some((_, draft)) if doc.editable() => {+ for (k, v) in INFO_KEYS.iter().zip(draft.iter_mut()) {+ let l = ui.label(egui::RichText::new(*k).color(t.text_muted));+ ui.add(egui::TextEdit::singleline(v).desired_width(f32::INFINITY).id_salt(("info", *k))).labelled_by(l.id);+ ui.end_row();+ }+ }+ _ => {+ row(ui, "Title", i.title.clone().unwrap_or_default());+ row(ui, "Author", i.author.clone().unwrap_or_default());+ row(ui, "Subject", i.subject.clone().unwrap_or_default());+ row(ui, "Keywords", i.keywords.clone().unwrap_or_default());+ }+ }+ row(ui, "Application", i.creator.clone().unwrap_or_default());+ row(ui, "PDF producer", i.producer.clone().unwrap_or_default());}- }- PropsTab::Advanced => {- row(ui, "PDF version", i.pdf_version.replace("Pdf", "").replace('_', "."));- row(ui, "Location", doc.path.clone().unwrap_or_default());- row(ui, "File size", format!("{} ({} bytes)", human_size(i.file_size), i.file_size));- let p = &i.pages[0];- row(ui, "Page size", format!("{:.2} × {:.2} in", p.width / 72.0, p.height / 72.0));- row(ui, "Number of pages", i.pages.len().to_string());- row(ui, "Tagged PDF", yes(i.tagged));- row(ui, "Form fields", i.fields.len().to_string());- row(ui, "Comments", i.annotations.len().to_string());- row(ui, "Layers", i.layers.len().to_string());- row(ui, "Attachments", i.attachments.len().to_string());- row(ui, "JavaScript", yes(i.has_javascript));- }+ PropsTab::Security => {+ row(ui, "Security method", if i.encrypted { "Password security".into() } else { "No security".into() });+ for k in [+ "Printing",+ "Changing the document",+ "Document assembly",+ "Content copying",+ "Commenting",+ "Filling of form fields",+ "Signing",+ ] {+ row(ui, k, if i.encrypted { "See permissions (M8)".into() } else { "Allowed".into() });+ }+ }+ PropsTab::Fonts => {+ if i.fonts.is_empty() {+ row(ui, "Fonts", "No fonts are referenced by the pages.".into());+ }+ for f in &i.fonts {+ let mut detail = f.kind.clone();+ if let Some(e) = &f.encoding {+ detail.push_str(&format!(" · {e}"));+ }+ detail.push_str(if f.subset {+ " · Embedded subset"+ } else if f.embedded {+ " · Embedded"+ } else {+ " · Not embedded (substituted)"+ });+ row(ui, &f.name, detail);+ }+ }+ PropsTab::Advanced => {+ row(ui, "PDF version", i.pdf_version.replace("Pdf", "").replace('_', "."));+ row(ui, "Location", doc.path.clone().unwrap_or_default());+ row(ui, "File size", format!("{} ({} bytes)", human_size(i.file_size), i.file_size));+ let p = &i.pages[0];+ row(ui, "Page size", format!("{:.2} × {:.2} in", p.width / 72.0, p.height / 72.0));+ row(ui, "Number of pages", i.pages.len().to_string());+ row(ui, "Tagged PDF", yes(i.tagged));+ row(ui, "Form fields", i.fields.len().to_string());+ row(ui, "Comments", i.annotations.len().to_string());+ row(ui, "Layers", i.layers.len().to_string());+ row(ui, "Attachments", i.attachments.len().to_string());+ row(ui, "JavaScript", yes(i.has_javascript));+ }+ })});}Dialog::Shortcuts => {@@ -79,8 +133,16 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {for (k, v) in [("⌘O", "Open"),("⌘W", "Close file"),+ ("⌘S / ⇧⌘S", "Save / Save as"),+ ("⌘Z / ⇧⌘Z", "Undo / Redo"),+ ("Delete", "Delete selected pages (Organize)"),("⌘D", "Document properties"),("⌘K", "Find tools and commands"),+ ("⌘F", "Find text in the document"),+ ("⌘G / ⇧⌘G", "Next / previous match"),+ ("⌘C", "Copy selected text"),+ ("Double-click", "Select a word"),+ ("Esc", "Clear selection / close find"),("⌘1", "Actual size"),("⌘0", "Zoom to page level"),("⌘2", "Fit to width"),@@ -108,20 +170,132 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {}}ui.add_space(12.0);+ let changed = draft_changes(app).is_some_and(|c| !c.is_empty());ui.with_layout(Layout::right_to_left(Align::Center), |ui| {- if widgets::pill_button(ui, "Close", true).clicked() {+ if changed {+ if widgets::pill_button(ui, "OK", true).clicked() {+ apply = true;+ close = true;+ }+ if widgets::pill_button(ui, "Cancel", false).clicked() {+ close = true;+ }+ } else if widgets::pill_button(ui, "Close", true).clicked() {close = true;}});- let _ = vec2(0.0, 0.0);});+ if apply && let Some(edits) = draft_changes(app) {+ app.apply_edit(Edit::Batch { label: "Change document properties".into(), edits });+ }if modal.should_close() || close {app.dialog = None;+ app.props_draft = None;} else {app.dialog = Some(next);}}+/// Info edits needed to make the document match the Description draft.+fn draft_changes(app: &PrintCraftApp) -> Option<Vec<Edit>> {+ let (id, draft) = app.props_draft.as_ref()?;+ let doc = app.session.get(*id)?;+ Some(+ INFO_KEYS+ .iter()+ .zip(draft.iter())+ .filter(|(k, v)| doc.info_value(k).unwrap_or_default().trim() != v.trim())+ .map(|(k, v)| Edit::SetInfo { key: (*k).to_string(), value: v.clone() })+ .collect(),+ )+}++/// "Save changes?" when closing a tab or quitting with unsaved edits.+fn save_prompt(app: &mut PrintCraftApp, ctx: &egui::Context) {+ let Some(req) = app.close_request else { return };+ let index = match req {+ CloseRequest::Tab(i) => Some(i),+ CloseRequest::Quit => app.first_dirty(),+ };+ let Some(name) = index.and_then(|i| app.views.get(i)).and_then(|v| app.session.get(v.id)).map(|d| d.name.clone()) else {+ // Nothing left to ask about (tab already gone or no dirty documents).+ app.resolve_close(ctx, Some(false));+ return;+ };+ let t = Tokens::get(ctx);+ let mut choice: Option<Option<bool>> = None;+ let modal = egui::Modal::new(egui::Id::new("save_prompt")).show(ctx, |ui| {+ ui.set_width(420.0);+ ui.horizontal(|ui| {+ ui.add(crate::icons::image("save", 22.0, t.accent));+ ui.label(egui::RichText::new(format!("Save changes to “{name}” before closing?")).font(theme::semibold(16.0)));+ });+ ui.add_space(6.0);+ ui.label(egui::RichText::new("Your changes will be lost if you don't save them.").color(t.text_muted));+ ui.add_space(14.0);+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ if widgets::pill_button(ui, "Save", true).clicked() {+ choice = Some(Some(true));+ }+ if widgets::pill_button(ui, "Cancel", false).clicked() {+ choice = Some(None);+ }+ ui.add_space(24.0);+ if widgets::pill_button(ui, "Don't save", false).clicked() {+ choice = Some(Some(false));+ }+ });+ });+ if choice.is_none() && modal.should_close() {+ choice = Some(None);+ }+ if let Some(c) = choice {+ app.resolve_close(ctx, c);+ }+}+fn yes(b: bool) -> String {if b { "Yes".into() } else { "No".into() }}++/// Password prompt for encrypted documents (Acrobat: "Password" dialog on open).+fn password(app: &mut PrintCraftApp, ctx: &egui::Context) {+ let Some(prompt) = app.password_prompt.as_mut() else { return };+ let t = Tokens::get(ctx);+ let mut submit = false;+ let mut cancel = false;+ let modal = egui::Modal::new(egui::Id::new("password")).show(ctx, |ui| {+ ui.set_width(400.0);+ ui.horizontal(|ui| {+ ui.add(crate::icons::image("lock", 22.0, t.accent));+ ui.label(egui::RichText::new("Password required").font(theme::semibold(17.0)));+ });+ ui.add_space(6.0);+ ui.label(format!("“{}” is protected. Enter a password to open it.", prompt.name));+ ui.add_space(8.0);+ let r = ui.add(egui::TextEdit::singleline(&mut prompt.input).password(true).hint_text("Password").desired_width(f32::INFINITY));+ r.request_focus();+ if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {+ submit = true;+ }+ if let Some(e) = &prompt.error {+ ui.add_space(4.0);+ ui.label(egui::RichText::new(e).color(egui::Color32::from_rgb(0xD1, 0x3B, 0x3B)));+ }+ ui.add_space(12.0);+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ if widgets::pill_button(ui, "Open", true).clicked() {+ submit = true;+ }+ if widgets::pill_button(ui, "Cancel", false).clicked() {+ cancel = true;+ }+ });+ });+ if submit {+ let pw = prompt.input.clone();+ app.submit_password(Some(pw));+ } else if cancel || modal.should_close() {+ app.submit_password(None);+ }+}diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rsnew file mode 100644index 000000000..18c119ff4--- /dev/null+++ b/crates/ui-egui/src/editing.rs@@ -0,0 +1,263 @@+//! Editing glue: apply engine edits from the UI, undo/redo, save/save-as, and the+//! "save changes?" prompt when closing a tab or quitting with unsaved edits.++use printcraft_engine::Edit;++use crate::PrintCraftApp;++/// What the user was doing when we asked whether to save.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CloseRequest {+ /// Close this tab (index into `views`).+ Tab(usize),+ /// Quit the application once every dirty document is resolved.+ Quit,+}++/// Where Save writes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum SaveTarget {+ /// The file's own path; asks for one if the document has none (e.g. opened from bytes).+ InPlace,+ /// Always ask for a new location.+ As,+}++impl PrintCraftApp {+ /// Apply an edit to the active document. Returns `true` on success; failures are shown.+ pub fn apply_edit(&mut self, edit: Edit) -> bool {+ let Some((i, id)) = self.active_ids() else { return false };+ let label = edit.label();+ match self.session.apply(id, edit.clone()) {+ Ok(()) => {+ let info = &self.session.get(id).expect("exists").info;+ let view = &mut self.views[i];+ view.document_changed(info);+ // Keep the pages the user acted on selected, where they now are.+ match edit {+ Edit::MovePages { pages, to } => {+ let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();+ let to = to.min(info.pages.len() - n);+ view.select_pages(&(to..to + n).collect::<Vec<_>>());+ }+ Edit::InsertBlankPage { at, .. } => view.select_pages(&[at.min(info.pages.len() - 1)]),+ Edit::DeletePages { .. } => view.select_pages(&[]),+ _ => {}+ }+ true+ }+ Err(e) => {+ self.notify(format!("{label} failed: {e}"));+ false+ }+ }+ }++ pub fn undo(&mut self) {+ self.history_step(true);+ }++ pub fn redo(&mut self) {+ self.history_step(false);+ }++ fn history_step(&mut self, undo: bool) {+ let Some((i, id)) = self.active_ids() else { return };+ let result = if undo { self.session.undo(id) } else { self.session.redo(id) };+ match result {+ Ok(label) => {+ let info = &self.session.get(id).expect("exists").info;+ self.views[i].document_changed(info);+ self.notify(format!("{} {label}", if undo { "Undid" } else { "Redid" }));+ }+ Err(e) => self.notify(e.to_string()),+ }+ }++ /// Apply any edit a view queued this frame (organize toolbar, keys).+ pub(crate) fn process_pending_edits(&mut self) {+ let Some(i) = self.active else { return };+ if let Some(edit) = self.views.get_mut(i).and_then(|v| v.pending_edit.take()) {+ self.apply_edit(edit);+ }+ }++ /// Save the active document. Returns `true` if it was written.+ pub fn save_active(&mut self, target: SaveTarget) -> bool {+ match self.active {+ Some(i) => self.save_view(i, target),+ None => false,+ }+ }++ /// Save the document shown in tab `index`. Returns `true` if it was written.+ pub fn save_view(&mut self, index: usize, target: SaveTarget) -> bool {+ let Some(id) = self.views.get(index).map(|v| v.id) else { return false };+ let Some(doc) = self.session.get(id) else { return false };+ let (name, path) = (doc.name.clone(), doc.path.clone());+ let bytes = match self.session.save_bytes(id) {+ Ok(b) => b,+ Err(e) => {+ self.notify(format!("Couldn't save {name}: {e}"));+ return false;+ }+ };+ let destination = match (target, path, &self.save_override) {+ (_, _, Some(p)) => Some(p.clone()),+ (SaveTarget::InPlace, Some(p), _) => Some(p),+ _ => self.ask_save_path(&name),+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ let Some(dest) = destination else { return false };+ if let Err(e) = write_atomically(&dest, &bytes) {+ self.notify(format!("Couldn't save {dest}: {e}"));+ return false;+ }+ match self.session.mark_saved(id, bytes, Some(dest.clone())) {+ Ok(()) => {+ let info = &self.session.get(id).expect("exists").info;+ self.views[index].document_changed(info);+ self.notify(format!("Saved {}", short_name(&dest)));+ true+ }+ Err(e) => {+ self.notify(format!("Saved, but reopening failed: {e}"));+ false+ }+ }+ }+ #[cfg(target_arch = "wasm32")]+ {+ let _ = destination;+ match download(&name, &bytes) {+ Ok(()) => {+ let _ = self.session.mark_saved(id, bytes, None);+ let info = &self.session.get(id).expect("exists").info;+ self.views[index].document_changed(info);+ self.notify(format!("Downloaded {name}"));+ true+ }+ Err(e) => {+ self.notify(format!("Couldn't download {name}: {e}"));+ false+ }+ }+ }+ }++ #[cfg(not(target_arch = "wasm32"))]+ fn ask_save_path(&self, name: &str) -> Option<String> {+ let name = if name.to_ascii_lowercase().ends_with(".pdf") { name.to_string() } else { format!("{name}.pdf") };+ rfd::FileDialog::new().add_filter("PDF", &["pdf"]).set_file_name(name).save_file().map(|p| p.to_string_lossy().into_owned())+ }++ #[cfg(target_arch = "wasm32")]+ fn ask_save_path(&self, _name: &str) -> Option<String> {+ None // browsers download instead+ }++ /// Close a tab, asking first if it has unsaved changes.+ pub fn request_close_tab(&mut self, index: usize) {+ let dirty = self.views.get(index).and_then(|v| self.session.get(v.id)).is_some_and(|d| d.dirty);+ if dirty {+ self.close_request = Some(CloseRequest::Tab(index));+ } else {+ self.close_tab(index);+ }+ }++ /// The first tab with unsaved changes.+ pub fn first_dirty(&self) -> Option<usize> {+ self.views.iter().position(|v| self.session.get(v.id).is_some_and(|d| d.dirty))+ }++ /// Answer the save prompt: `Some(true)` save, `Some(false)` discard, `None` cancel.+ pub fn resolve_close(&mut self, ctx: &egui::Context, choice: Option<bool>) {+ let Some(req) = self.close_request.take() else { return };+ let index = match req {+ CloseRequest::Tab(i) => i,+ CloseRequest::Quit => match self.first_dirty() {+ Some(i) => i,+ None => {+ self.quit(ctx);+ return;+ }+ },+ };+ match choice {+ None => {} // cancelled: nothing closes+ Some(save) => {+ if save && !self.save_view(index, SaveTarget::InPlace) {+ return; // save failed or was cancelled: keep the document open+ }+ self.close_tab(index);+ if req == CloseRequest::Quit {+ // Ask about the next dirty document, or quit.+ match self.first_dirty() {+ Some(_) => self.close_request = Some(CloseRequest::Quit),+ None => self.quit(ctx),+ }+ }+ }+ }+ }++ fn quit(&mut self, ctx: &egui::Context) {+ self.allow_quit = true;+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);+ }++ /// Intercept window close while documents have unsaved changes.+ pub(crate) fn guard_quit(&mut self, ctx: &egui::Context) {+ if ctx.input(|i| i.viewport().close_requested()) && !self.allow_quit && self.first_dirty().is_some() {+ ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);+ self.close_request = Some(CloseRequest::Quit);+ }+ }+}++/// Write via a temporary file in the same directory and rename over the target, so a crash or+/// full disk never leaves a half-written PDF where the original was.+#[cfg(not(target_arch = "wasm32"))]+pub fn write_atomically(path: &str, bytes: &[u8]) -> std::io::Result<()> {+ use std::io::Write;+ let target = std::path::Path::new(path);+ let dir = target.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(std::path::Path::new("."));+ let tmp = dir.join(format!(".{}.printcraft-{}.tmp", target.file_name().and_then(|n| n.to_str()).unwrap_or("save"), std::process::id()));+ let result = (|| {+ let mut f = std::fs::File::create(&tmp)?;+ f.write_all(bytes)?;+ f.sync_all()?;+ std::fs::rename(&tmp, target)+ })();+ if result.is_err() {+ let _ = std::fs::remove_file(&tmp);+ }+ result+}++#[cfg(not(target_arch = "wasm32"))]+fn short_name(path: &str) -> String {+ std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string())+}++/// Offer bytes as a browser download.+#[cfg(target_arch = "wasm32")]+fn download(name: &str, bytes: &[u8]) -> Result<(), String> {+ use wasm_bindgen::JsCast;+ let err = |e: wasm_bindgen::JsValue| format!("{e:?}");+ let array = js_sys::Uint8Array::from(bytes);+ let parts = js_sys::Array::of1(&array);+ let opts = web_sys::BlobPropertyBag::new();+ opts.set_type("application/pdf");+ let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(err)?;+ let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(err)?;+ let document = web_sys::window().and_then(|w| w.document()).ok_or("no document")?;+ let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(err)?.dyn_into().map_err(|_| "anchor")?;+ a.set_href(&url);+ a.set_download(name);+ a.click();+ let _ = web_sys::Url::revoke_object_url(&url);+ Ok(())+}diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rsindex 7a5582a6b..5e5aa6ad4 100644--- a/crates/ui-egui/src/home.rs+++ b/crates/ui-egui/src/home.rs@@ -32,6 +32,7 @@ pub fn show(app: &mut PrintCraftApp, ui: &mut egui::Ui) {for id in RECOMMENDED {let Some(g) = catalog::group(id) else { continue };let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 104.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, g.label));let fill = if resp.hovered() { t.hover } else { t.card };ui.painter().rect(rect, CornerRadius::same(10), fill, Stroke::new(1.0, t.divider), egui::StrokeKind::Inside);let color = egui::Color32::from_rgb(g.hue[0], g.hue[1], g.hue[2]);@@ -57,6 +58,7 @@ pub fn show(app: &mut PrintCraftApp, ui: &mut egui::Ui) {}}let (rect, resp) = ui.allocate_exact_size(vec2(170.0, 104.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Open file"));ui.painter().rect(rect,CornerRadius::same(10),@@ -81,6 +83,7 @@ pub fn show(app: &mut PrintCraftApp, ui: &mut egui::Ui) {let mut open = None;for r in &app.recent {let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 46.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &r.name));if resp.hovered() {ui.painter().rect_filled(rect, CornerRadius::same(8), t.hover);}diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rsindex 949a41117..32c7bdb43 100644--- a/crates/ui-egui/src/icons.rs+++ b/crates/ui-egui/src/icons.rs@@ -42,6 +42,8 @@ pub fn paint(ui: &egui::Ui, rect: Rect, name: &str, size: f32, tint: Color32) {pub fn button(ui: &mut egui::Ui, name: &str, box_size: f32, selected: bool, tooltip: &str) -> Response {let t = Tokens::get(ui.ctx());let (rect, resp) = ui.allocate_exact_size(Vec2::splat(box_size), Sense::click());+ let label = if tooltip.is_empty() { name } else { tooltip };+ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), selected, label));let hovered = resp.hovered();if selected {ui.painter().rect_filled(rect, t.radius, t.accent_soft);diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex b5c1f33ae..e40bfa030 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -8,6 +8,7 @@mod canvas;mod chrome;mod dialogs;+mod editing;mod home;mod icon_data;pub mod icons;@@ -19,6 +20,7 @@ mod widgets;use printcraft_engine::{DocId, Session};pub use canvas::DocView;+pub use editing::{CloseRequest, SaveTarget};use theme::ThemeKind;/// Top-level workspace modes (Acrobat's mode bar).@@ -67,9 +69,22 @@ pub enum Dialog {pub enum PropsTab {Description,Security,+ Fonts,Advanced,}+/// Files delivered asynchronously: (name, bytes).+pub type Inbox = std::sync::Arc<std::sync::Mutex<Vec<(String, Vec<u8>)>>>;++pub struct PasswordPrompt {+ pub name: String,+ pub path: Option<String>,+ pub bytes: std::sync::Arc<Vec<u8>>,+ pub input: String,+ pub error: Option<String>,+}++#[derive(serde::Serialize, serde::Deserialize)]pub struct RecentFile {pub name: String,pub path: String,@@ -96,6 +111,17 @@ pub struct PrintCraftApp {pub toast: Option<(String, f64)>,/// Whether the macOS title bar is drawn by us (traffic lights over our tab strip).pub integrated_titlebar: bool,+ pub password_prompt: Option<PasswordPrompt>,+ pub full_screen: bool,+ /// Files delivered asynchronously (web drag-and-drop, web file picker).+ pub inbox: Inbox,+ /// A pending "save changes?" question (closing a dirty tab or quitting).+ pub close_request: Option<CloseRequest>,+ /// Save to this path instead of asking (tests and automation).+ pub save_override: Option<String>,+ /// Document Properties ▸ Description fields being edited: (document, Title/Author/Subject/Keywords).+ pub props_draft: Option<(DocId, [String; 4])>,+ allow_quit: bool,pending_theme: Option<ThemeKind>,styled: bool,fonts_ready: bool,@@ -126,16 +152,37 @@ impl PrintCraftApp {recent: Vec::new(),toast: None,integrated_titlebar: false,+ password_prompt: None,+ full_screen: false,+ inbox: Default::default(),+ close_request: None,+ save_override: None,+ props_draft: None,+ allow_quit: false,pending_theme: None,styled: false,fonts_ready: false,}}- /// Open a document and make it the active tab.+ /// Open a document and make it the active tab. Encrypted files raise the password prompt.pub fn open_bytes(&mut self, name: &str, path: Option<String>, bytes: Vec<u8>) -> Result<(), String> {+ self.try_open(name, path, std::sync::Arc::new(bytes), None)+ }++ fn try_open(&mut self, name: &str, path: Option<String>, bytes: std::sync::Arc<Vec<u8>>, password: Option<&str>) -> Result<(), String> {+ use printcraft_render::OpenError;let size = bytes.len();- let id = self.session.open(name, path.clone(), bytes).map_err(|e| e.to_string())?;+ let id = match self.session.open(name, path.clone(), bytes.clone(), password) {+ Ok(id) => id,+ Err(e @ (OpenError::NeedsPassword | OpenError::WrongPassword)) => {+ let error = matches!(e, OpenError::WrongPassword).then(|| "Incorrect password. Try again.".to_string());+ self.password_prompt = Some(PasswordPrompt { name: name.to_string(), path, bytes, input: String::new(), error });+ return Ok(());+ }+ Err(e) => return Err(e.to_string()),+ };+ self.password_prompt = None;let doc = self.session.get(id).expect("just opened");let pages = doc.info.pages.len();// Acrobat opens straight to the Comments panel when a document has comments.@@ -158,6 +205,81 @@ impl PrintCraftApp {Ok(())}+ #[cfg(not(target_arch = "wasm32"))]+ fn open_dropped(&mut self, f: egui::DroppedFileHandle, _ctx: &egui::Context) {+ let p = f.path().to_string_lossy().into_owned();+ if !p.is_empty() && f.path().is_absolute() {+ self.open_path(&p);+ return;+ }+ let name = f.path().file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "dropped.pdf".into());+ match f.bytes() {+ Ok(bytes) => {+ if let Err(e) = self.open_bytes(&name, None, bytes) {+ self.notify(format!("Couldn't open {name}: {e}"));+ }+ }+ Err(e) => self.notify(format!("Couldn't read {name}: {e}")),+ }+ }++ /// Browsers read dropped files asynchronously; the bytes land in `inbox` and open next frame.+ #[cfg(target_arch = "wasm32")]+ fn open_dropped(&mut self, f: egui::DroppedFileHandle, ctx: &egui::Context) {+ let inbox = self.inbox.clone();+ let ctx = ctx.clone();+ wasm_bindgen_futures::spawn_local(async move {+ let name = f.path().file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "dropped.pdf".into());+ if let Ok(bytes) = f.bytes_async().await+ && let Ok(mut q) = inbox.lock()+ {+ q.push((name, bytes));+ ctx.request_repaint();+ }+ });+ }++ /// Save an attachment to disk, or open a PDF attachment in a new tab.+ pub fn attachment_action(&mut self, doc: DocId, index: usize, open: bool) {+ let Some(d) = self.session.get(doc) else { return };+ let Some(att) = d.info.attachments.get(index).cloned() else { return };+ let data = printcraft_render::attachment_data(&d.bytes, d.password.as_deref(), &att);+ match (data, open) {+ (Err(e), _) => self.notify(format!("Couldn't read {}: {e}", att.name)),+ (Ok(bytes), true) => {+ if let Err(e) = self.open_bytes(&att.name, None, bytes) {+ self.notify(format!("Couldn't open {}: {e}", att.name));+ }+ }+ (Ok(bytes), false) => {+ #[cfg(not(target_arch = "wasm32"))]+ if let Some(path) = rfd::FileDialog::new().set_file_name(&att.name).save_file() {+ match std::fs::write(&path, &bytes) {+ Ok(()) => self.notify(format!("Saved {}", path.display())),+ Err(e) => self.notify(format!("Couldn't save: {e}")),+ }+ }+ #[cfg(target_arch = "wasm32")]+ self.notify(format!("Downloading attachments on the web arrives with M3.10 ({} bytes ready)", bytes.len()));+ }+ }+ }++ /// Enter or leave full-screen reading (Acrobat: View ▸ Full Screen Mode, ⌘L).+ pub fn set_full_screen(&mut self, ctx: &egui::Context, on: bool) {+ self.full_screen = on;+ ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(on));+ }++ /// Answer the password prompt (`None` cancels).+ pub fn submit_password(&mut self, password: Option<String>) {+ let Some(p) = self.password_prompt.take() else { return };+ let Some(pw) = password else { return };+ if let Err(e) = self.try_open(&p.name, p.path, p.bytes, Some(&pw)) {+ self.notify(format!("Couldn't open {}: {e}", p.name));+ }+ }+#[cfg(not(target_arch = "wasm32"))]pub fn open_path(&mut self, path: &str) {let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string());@@ -176,6 +298,19 @@ impl PrintCraftApp {if let Some(p) = rfd::FileDialog::new().add_filter("PDF", &["pdf"]).pick_file() {self.open_path(&p.to_string_lossy());}+ // Browsers pick files asynchronously; the bytes arrive through `inbox`.+ #[cfg(target_arch = "wasm32")]+ {+ let inbox = self.inbox.clone();+ wasm_bindgen_futures::spawn_local(async move {+ if let Some(h) = rfd::AsyncFileDialog::new().add_filter("PDF", &["pdf"]).pick_file().await {+ let bytes = h.read().await;+ if let Ok(mut q) = inbox.lock() {+ q.push((h.file_name(), bytes));+ }+ }+ });+ }}pub fn close_tab(&mut self, index: usize) {@@ -233,6 +368,30 @@ impl PrintCraftApp {}}+ /// Serialize the user's persistent state (recent files, theme). Local only.+ pub fn persist(&self) -> String {+ serde_json::json!({ "recent": self.recent, "theme": self.theme }).to_string()+ }++ /// Restore state written by `persist`. Unknown or malformed data is ignored.+ pub fn restore(&mut self, json: &str) {+ let Ok(v) = serde_json::from_str::<serde_json::Value>(json) else { return };+ if let Ok(r) = serde_json::from_value::<Vec<RecentFile>>(v["recent"].clone()) {+ // Only keep entries whose files still exist.+ #[cfg(not(target_arch = "wasm32"))]+ let r: Vec<RecentFile> = r.into_iter().filter(|f| std::path::Path::new(&f.path).exists()).collect();+ self.recent = r;+ }+ if let Ok(t) = serde_json::from_value::<ThemeKind>(v["theme"].clone()) {+ self.theme = t;+ }+ }++ /// `true` while any open document still waits for page renders (used by headless capture).+ pub fn render_pending(&self) -> bool {+ self.views.iter().any(|v| v.render_pending())+ }+/// Apply a named view option (`--page 3`, `--panel bookmarks`, `--theme dark`, …).////// This is the seed of the UI control channel (M3.9): the same verbs become `ui.set` calls.@@ -289,8 +448,37 @@ impl PrintCraftApp {}}("organize", Some(v)) => v.organize = value != "off",+ ("rotate", Some(v)) => {+ let deg: u16 = value.parse().map_err(|_| "rotate: 0, 90, 180 or 270")?;+ if !deg.is_multiple_of(90) {+ return Err("rotate: 0, 90, 180 or 270".into());+ }+ v.rotation = deg % 360;+ }+ ("layer", _) => {+ // `--layer "Name=off"` / `"Name=on"`+ let (name, state) = value.rsplit_once('=').ok_or("expected NAME=on|off")?;+ let (i, id) = self.active_ids().ok_or("`layer` needs an open document")?;+ let idx = self+ .session+ .get(id)+ .and_then(|d| d.info.layers.iter().position(|l| l.name == name))+ .ok_or_else(|| format!("no layer named {name}"))?;+ if self.session.set_layer_visible(id, idx, state != "off") {+ self.views[i].invalidate_content();+ }+ }+ ("find", Some(v)) => {+ v.open_find();+ if let Some(f) = v.find.as_mut() {+ f.query = value.to_string();+ }+ v.rerun_find();+ }("fields", Some(v)) => v.highlight_fields = value != "off",- (k, None) if ["page", "zoom", "layout", "organize", "fields"].contains(&k) => return Err(format!("`{k}` needs an open document")),+ (k, None) if ["page", "zoom", "layout", "organize", "fields", "find", "rotate"].contains(&k) => {+ return Err(format!("`{k}` needs an open document"));+ }(other, _) => return Err(format!("unknown option {other}")),}Ok(())@@ -312,7 +500,28 @@ impl PrintCraftApp {if pressed(cmd(Key::W))&& let Some(i) = self.active{- self.close_tab(i);+ self.request_close_tab(i);+ }+ if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::S)) && self.active.is_some() {+ self.save_active(SaveTarget::As);+ }+ if pressed(cmd(Key::S)) && self.active.is_some() {+ self.save_active(SaveTarget::InPlace);+ }+ // Text fields keep their own undo; otherwise ⌘Z/⇧⌘Z step the document history.+ if !ctx.egui_wants_keyboard_input() && self.active.is_some() {+ if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z)) {+ self.redo();+ } else if pressed(cmd(Key::Z)) {+ self.undo();+ }+ }+ if pressed(cmd(Key::L)) && self.active.is_some() {+ let on = !self.full_screen;+ self.set_full_screen(ctx, on);+ }+ if self.full_screen && ctx.input(|i| i.key_pressed(Key::Escape)) {+ self.set_full_screen(ctx, false);}if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::CTRL, Key::H)) {self.mode = if self.mode == Mode::Read { Mode::AllTools } else { Mode::Read };@@ -324,6 +533,10 @@ impl PrintCraftApp {}impl eframe::App for PrintCraftApp {+ fn save(&mut self, storage: &mut dyn eframe::Storage) {+ storage.set_string("printcraft", self.persist());+ }+fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {if !self.styled {egui_extras::install_image_loaders(ctx);@@ -338,25 +551,17 @@ impl eframe::App for PrintCraftApp {}let dropped = ctx.input(|i| i.raw.dropped_files.clone());for f in dropped {- #[cfg(not(target_arch = "wasm32"))]- {- let p = f.path().to_string_lossy().into_owned();- if !p.is_empty() {- self.open_path(&p);- continue;- }- }- let name = f.path().file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "dropped.pdf".into());- match f.bytes() {- Ok(bytes) => {- if let Err(e) = self.open_bytes(&name, None, bytes) {- self.notify(format!("Couldn't open {name}: {e}"));- }- }- Err(e) => self.notify(format!("Couldn't read {name}: {e}")),+ self.open_dropped(f, ctx);+ }+ let arrived: Vec<(String, Vec<u8>)> = self.inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, bytes) in arrived {+ if let Err(e) = self.open_bytes(&name, None, bytes) {+ self.notify(format!("Couldn't open {name}: {e}"));}}+ self.guard_quit(ctx);self.shortcuts(ctx);+ self.process_pending_edits();// Pull finished renders into textures for every open document.for view in &mut self.views {if let Some(doc) = self.session.get(view.id) {@@ -372,6 +577,20 @@ impl eframe::App for PrintCraftApp {ctx.request_repaint();return;}+ if self.full_screen && self.active.is_some() {+ // Full screen: the page, nothing else (Esc or ⌘L to leave).+ let t = theme::Tokens::get(&ctx);+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(if t.dark() { t.pasteboard } else { egui::Color32::from_gray(32) })).show(+ ui,+ |ui| {+ if let Some(i) = self.active {+ canvas::document_area(self, i, ui);+ }+ },+ );+ dialogs::show(self, &ctx);+ return;+ }chrome::tab_strip(self, ui);chrome::mode_bar(self, ui);if self.active.is_some() {@@ -388,6 +607,7 @@ impl eframe::App for PrintCraftApp {None => home::show(self, ui),Some(i) => canvas::document_area(self, i, ui),});+ self.process_pending_edits();palette::show(self, &ctx);dialogs::show(self, &ctx);widgets::toast(self, &ctx);diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex b302f8495..fcad6f8f2 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -74,23 +74,31 @@ fn all_tools(app: &mut PrintCraftApp, ui: &mut egui::Ui, t: &Tokens) {fn tool_row(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup) -> egui::Response {let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, g.label));if resp.hovered() {ui.painter().rect_filled(rect, CornerRadius::same(6), t.hover);}icons::paint(ui, Rect::from_min_size(rect.min + vec2(6.0, 7.0), vec2(20.0, 20.0)), g.icon, 19.0, hue(g));ui.painter().text(rect.left_center() + vec2(36.0, 0.0), Align2::LEFT_CENTER, g.label, theme::regular(13.5), t.text);- let (chip, fill) = match (g.badge, g.availability) {- (Some(b), _) => (Some(b.to_string()), t.badge_new),- (None, Availability::Planned(m)) => (Some(m.to_string()), t.pressed),- _ => (None, t.pressed),- };- if let Some(c) = chip {- let font = theme::semibold(9.5);- let fg = if fill == t.badge_new { Color32::WHITE } else { t.text_muted };- let w = ui.fonts_mut(|f| f.layout_no_wrap(c.clone(), font.clone(), fg).size().x);- let r = Rect::from_center_size(rect.right_center() - vec2(w / 2.0 + 10.0, 0.0), vec2(w + 10.0, 16.0));- ui.painter().rect_filled(r, CornerRadius::same(4), fill);- ui.painter().text(r.center(), Align2::CENTER_CENTER, c, font, fg);+ match (g.badge, g.availability) {+ (Some(b), _) => {+ let font = theme::semibold(9.5);+ let w = ui.fonts_mut(|f| f.layout_no_wrap(b.to_string(), font.clone(), Color32::WHITE).size().x);+ let r = Rect::from_center_size(rect.right_center() - vec2(w / 2.0 + 10.0, 0.0), vec2(w + 10.0, 16.0));+ ui.painter().rect_filled(r, CornerRadius::same(4), t.badge_new);+ ui.painter().text(r.center(), Align2::CENTER_CENTER, b, font, Color32::WHITE);+ }+ // Planned tools: a quiet milestone hint instead of a chip, so the list stays calm.+ (None, Availability::Planned(m)) if resp.hovered() => {+ ui.painter().text(+ rect.right_center() - vec2(10.0, 0.0),+ Align2::RIGHT_CENTER,+ format!("Planned · {m}"),+ theme::medium(10.5),+ t.text_faint,+ );+ }+ _ => {}}let tip = match g.availability {Availability::Ready => "Available".to_string(),@@ -123,6 +131,7 @@ fn tool_detail(app: &mut PrintCraftApp, ui: &mut egui::Ui, t: &Tokens, g: &'statwidgets::section_title(ui, s.title);for item in s.items {let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, item.label));let ready = item.availability == Availability::Ready;if resp.hovered() {ui.painter().rect_filled(rect, CornerRadius::same(6), t.hover);@@ -170,7 +179,8 @@ pub fn right_panel(app: &mut PrintCraftApp, ui: &mut egui::Ui) {let Some(panel) = app.right else { return };let mut nav: Option<Nav> = None;let mut close = false;- let mut layer_toast = false;+ let mut toggle_layer: Option<(usize, bool)> = None;+ let mut attachment_action: Option<(usize, bool)> = None; // (index, open instead of save){let Some(doc) = app.session.get(id) else { return };let info = &doc.info;@@ -222,8 +232,9 @@ pub fn right_panel(app: &mut PrintCraftApp, ui: &mut egui::Ui) {if info.layers.is_empty() {empty(ui, &t, "layers", "This document has no layers.");}- for l in &info.layers {+ for (li, l) in info.layers.iter().enumerate() {let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, l.visible, &l.name));if resp.hovered() {ui.painter().rect_filled(rect, CornerRadius::same(6), t.hover);}@@ -234,9 +245,10 @@ pub fn right_panel(app: &mut PrintCraftApp, ui: &mut egui::Ui) {16.0,t.icon,);- ui.painter().text(rect.left_center() + vec2(32.0, 0.0), Align2::LEFT_CENTER, &l.name, theme::regular(13.0), t.text);- if resp.clicked() {- layer_toast = true;+ let fg = if l.visible { t.text } else { t.text_faint };+ ui.painter().text(rect.left_center() + vec2(32.0, 0.0), Align2::LEFT_CENTER, &l.name, theme::regular(13.0), fg);+ if resp.on_hover_text(if l.visible { "Hide layer" } else { "Show layer" }).clicked() {+ toggle_layer = Some((li, !l.visible));}}}@@ -244,19 +256,34 @@ pub fn right_panel(app: &mut PrintCraftApp, ui: &mut egui::Ui) {if info.attachments.is_empty() {empty(ui, &t, "paperclip", "This document has no attachments.");}- for a in &info.attachments {- ui.horizontal(|ui| {- ui.add(icons::image("paperclip", 16.0, t.icon));- ui.vertical(|ui| {- ui.label(egui::RichText::new(&a.name).font(theme::medium(13.0)));- let mut meta = a.size.map(human_size).unwrap_or_default();- if let Some(d) = &a.description {- meta = format!("{meta} · {d}");- }- ui.label(egui::RichText::new(meta).color(t.text_faint).small());+ for (ai, a) in info.attachments.iter().enumerate() {+ egui::Frame::NONE.inner_margin(egui::Margin::symmetric(4, 6)).show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.add(icons::image("paperclip", 16.0, t.icon));+ ui.vertical(|ui| {+ ui.set_width(ui.available_width() - 70.0);+ ui.add(egui::Label::new(egui::RichText::new(&a.name).font(theme::medium(13.0))).truncate());+ let mut meta = a.size.map(human_size).unwrap_or_default();+ if let printcraft_render::AttachmentSource::Annotation { page, .. } = a.source {+ meta = format!("{meta} · on page {}", info.pages.get(page).map(|p| p.label.as_str()).unwrap_or("?"));+ }+ if let Some(d) = &a.description {+ meta = format!("{meta} · {d}");+ }+ ui.add(egui::Label::new(egui::RichText::new(meta).color(t.text_faint).small()).truncate());+ });+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ if icons::button(ui, "file-down", 28.0, false, "Save attachment…").clicked() {+ attachment_action = Some((ai, false));+ }+ if a.name.to_lowercase().ends_with(".pdf")+ && icons::button(ui, "file-input", 28.0, false, "Open in a new tab").clicked()+ {+ attachment_action = Some((ai, true));+ }+ });});});- ui.add_space(6.0);}}});@@ -265,8 +292,13 @@ pub fn right_panel(app: &mut PrintCraftApp, ui: &mut egui::Ui) {if close {app.right = None;}- if layer_toast {- app.notify("Toggling layer visibility re-renders with optional content states — ships with the M2 renderer device");+ if let Some((ai, open)) = attachment_action {+ app.attachment_action(id, ai, open);+ }+ if let Some((layer, visible)) = toggle_layer+ && app.session.set_layer_visible(id, layer, visible)+ {+ app.views[index].invalidate_content();}match nav {Some(Nav::Page(p)) => app.views[index].go_to_page(p),@@ -336,50 +368,86 @@ fn comments(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, nav: &mut Option<Nav>}}+/// Reader-friendly names for annotation subtypes (the PDF names are shown in tooltips).+fn subtype_label(s: &str) -> &str {+ match s {+ "Text" => "Note",+ "FreeText" => "Text box",+ "StrikeOut" => "Strikethrough",+ "Square" => "Rectangle",+ "Circle" => "Oval",+ "Ink" => "Drawing",+ "PolyLine" => "Polyline",+ "FileAttachment" => "Attachment",+ "Caret" => "Insert text",+ other => other,+ }+}++/// Darken very light annotation colours (e.g. note yellow) so their icon stays legible.+fn legible(c: Color32, t: &Tokens) -> Color32 {+ let lum = 0.2126 * c.r() as f32 + 0.7152 * c.g() as f32 + 0.0722 * c.b() as f32;+ if !t.dark() && lum > 170.0 {+ Color32::from_rgb((c.r() as f32 * 0.62) as u8, (c.g() as f32 * 0.62) as u8, (c.b() as f32 * 0.62) as u8)+ } else {+ c+ }+}+fn comment_card(ui: &mut egui::Ui, t: &Tokens, a: &Annotation, replies: &[&Annotation]) -> egui::Response {- let accent = a.color.map(|c| Color32::from_rgb((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8)).unwrap_or(t.accent);+ let color = a.color.map(|c| Color32::from_rgb((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8)).unwrap_or(t.accent);+ let id = ui.id().with(("comment", a.page, a.rect[0].to_bits(), a.rect[1].to_bits()));+ let hovered = ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(false);let resp = egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.divider))+ .fill(if hovered { t.hover } else { Color32::TRANSPARENT }).corner_radius(CornerRadius::same(8))- .inner_margin(egui::Margin::same(10))+ .inner_margin(egui::Margin { left: 8, right: 8, top: 10, bottom: 10 }).show(ui, |ui| {ui.set_width(ui.available_width());ui.horizontal(|ui| {- let (r, _) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::hover());- ui.painter().circle_filled(r.center(), 13.0, accent.gamma_multiply(0.22));- icons::paint(ui, r, subtype_icon(&a.subtype), 14.0, accent.gamma_multiply(1.0));+ let (r, _) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::hover());+ ui.painter().circle_filled(r.center(), 14.0, color.gamma_multiply(if t.dark() { 0.35 } else { 0.28 }));+ icons::paint(ui, r, subtype_icon(&a.subtype), 14.0, legible(color, t));ui.vertical(|ui| {ui.spacing_mut().item_spacing.y = 1.0;- ui.label(egui::RichText::new(a.author.as_deref().unwrap_or("Unknown author")).font(theme::semibold(13.0)));- let meta = format!("{}{}", a.subtype, a.modified.as_deref().map(|m| format!(" · {m}")).unwrap_or_default());- ui.label(egui::RichText::new(meta).color(t.text_faint).font(theme::regular(11.0)));+ ui.add(+ egui::Label::new(egui::RichText::new(a.author.as_deref().unwrap_or("Unknown author")).font(theme::semibold(13.0))).truncate(),+ );+ let meta = format!("{}{}", subtype_label(&a.subtype), a.modified.as_deref().map(|m| format!(" · {m}")).unwrap_or_default());+ ui.add(egui::Label::new(egui::RichText::new(meta).color(t.text_faint).font(theme::regular(11.0))).truncate());});});- if let Some(c) = &a.contents {- ui.add_space(4.0);- ui.label(egui::RichText::new(c).color(t.text));- }- for r in replies {- ui.add_space(6.0);- ui.horizontal(|ui| {- ui.add_space(8.0);- let (bar, _) = ui.allocate_exact_size(vec2(2.0, 30.0), Sense::hover());- ui.painter().rect_filled(bar, CornerRadius::same(1), t.divider);- ui.vertical(|ui| {+ // Body and replies are indented under the avatar and must wrap to the panel width.+ egui::Frame::NONE.inner_margin(egui::Margin { left: 36, right: 0, top: 4, bottom: 0 }).show(ui, |ui| {+ ui.set_width(ui.available_width());+ if let Some(c) = &a.contents {+ ui.add(egui::Label::new(egui::RichText::new(c).color(t.text)).wrap());+ }+ for r in replies {+ ui.add_space(6.0);+ let resp = egui::Frame::NONE.inner_margin(egui::Margin { left: 10, right: 0, top: 2, bottom: 2 }).show(ui, |ui| {+ ui.set_width(ui.available_width());ui.spacing_mut().item_spacing.y = 1.0;- ui.label(egui::RichText::new(r.author.as_deref().unwrap_or("Reply")).font(theme::semibold(12.0)));+ ui.add(egui::Label::new(egui::RichText::new(r.author.as_deref().unwrap_or("Reply")).font(theme::semibold(12.0))).truncate());if let Some(c) = &r.contents {- ui.label(egui::RichText::new(c).color(t.text_muted).font(theme::regular(12.0)));+ ui.add(egui::Label::new(egui::RichText::new(c).color(t.text_muted).font(theme::regular(12.0))).wrap());}});- });- }+ let b = resp.response.rect;+ ui.painter().vline(b.left() + 1.0, b.y_range(), Stroke::new(2.0, t.border));+ }+ });}).response;- ui.add_space(6.0);- ui.interact(resp.rect, ui.id().with(("comment", a.page, a.rect[0].to_bits(), a.rect[1].to_bits())), Sense::click())+ let div_y = resp.rect.bottom() + 2.0;+ ui.painter().hline(resp.rect.x_range().shrink(8.0), div_y, Stroke::new(1.0, t.divider));+ ui.add_space(5.0);+ let click = ui+ .interact(resp.rect, id.with("click"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand)+ .on_hover_text(format!("/{} annotation — click to show it on the page", a.subtype));+ ui.data_mut(|d| d.insert_temp(id, click.hovered()));+ click}fn outline_item(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, item: &OutlineItem, depth: usize, nav: &mut Option<Nav>) {@@ -391,6 +459,7 @@ fn outline_item(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, item: &OutlineItelet galley = ui.fonts_mut(|f| f.layout(item.title.clone(), font, t.text, wrap_w));let h = (galley.size().y + 12.0).max(28.0);let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &item.title));if resp.hovered() {ui.painter().rect_filled(rect, CornerRadius::same(6), t.hover);}@@ -425,6 +494,7 @@ fn pages(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, view: &crate::DocView, nui.vertical_centered(|ui| {let h = w * p.height / p.width.max(1.0);let (rect, resp) = ui.allocate_exact_size(vec2(w + 16.0, h + 16.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("Page {}", p.label)));let selected = i == view.current;if selected {ui.painter().rect_filled(rect, CornerRadius::same(8), t.accent_soft);@@ -475,6 +545,7 @@ fn fields(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, nav: &mut Option<Nav>)FieldKind::Unknown => "square",};let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &f.name));if resp.hovered() {ui.painter().rect_filled(rect, CornerRadius::same(6), t.hover);}diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex 2c0f6b0eb..acc29f302 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -11,6 +11,7 @@ pub fn mode_tab(ui: &mut egui::Ui, label: &str, active: bool) -> Response {let font = if active { theme::semibold(13.5) } else { theme::medium(13.5) };let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font.clone(), t.text).size().x);let (rect, resp) = ui.allocate_exact_size(vec2(w + 22.0, 48.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), active, label));if resp.hovered() && !active {ui.painter().rect_filled(rect.shrink2(vec2(2.0, 9.0)), CornerRadius::same(6), t.hover);}@@ -28,6 +29,7 @@ pub fn pill_button(ui: &mut egui::Ui, label: &str, primary: bool) -> Response {let font = theme::medium(12.5);let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font.clone(), t.text).size().x);let (rect, resp) = ui.allocate_exact_size(vec2(w + 26.0, 28.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label));let (fill, stroke, text) = if primary {(if resp.hovered() { t.accent_text } else { t.accent }, Stroke::NONE, Color32::WHITE)} else {@@ -44,6 +46,7 @@ pub fn ghost_button(ui: &mut egui::Ui, icon: &str, label: &str) -> Response {let font = theme::medium(13.0);let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font.clone(), t.text).size().x);let (rect, resp) = ui.allocate_exact_size(vec2(w + 38.0, 30.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label));if resp.hovered() {ui.painter().rect_filled(rect, CornerRadius::same(6), t.hover);}@@ -56,6 +59,7 @@ pub fn ghost_button(ui: &mut egui::Ui, icon: &str, label: &str) -> Response {pub fn search_box(ui: &mut egui::Ui, placeholder: &str, width: f32) -> Response {let t = Tokens::get(ui.ctx());let (rect, resp) = ui.allocate_exact_size(vec2(width, 32.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), placeholder));let fill = if resp.hovered() { t.hover } else { t.field };ui.painter().rect(rect, CornerRadius::same(16), fill, Stroke::new(1.0, t.border), egui::StrokeKind::Inside);icons::paint(ui, Rect::from_min_size(rect.min + vec2(10.0, 8.0), vec2(16.0, 16.0)), "search", 15.0, t.text_muted);diff --git a/crates/ui-egui/tests/editing.rs b/crates/ui-egui/tests/editing.rsnew file mode 100644index 000000000..03bf17587--- /dev/null+++ b/crates/ui-egui/tests/editing.rs@@ -0,0 +1,303 @@+//! Headless UI tests for editing and saving: the organize toolbar, selection, undo/redo keys,+//! save/save-as, the unsaved-changes prompt and editable document properties.++use egui::accesskit::Role;+use egui::{Key, Modifiers};+use egui_kittest::Harness;+use egui_kittest::kittest::Queryable;+use printcraft_render::{PageRenderer, RenderRequest, RequestKind};+use printcraft_ui_egui::{CloseRequest, PrintCraftApp};++/// An `n`-page document with a proper xref table; page `i` shows "Page i+1".+fn fixture(n: usize) -> Vec<u8> {+ let mut objs: Vec<String> = vec!["<< /Type /Catalog /Pages 2 0 R >>".into()];+ let kids: Vec<String> = (0..n).map(|i| format!("{} 0 R", 4 + 2 * i)).collect();+ objs.push(format!("<< /Type /Pages /Kids [{}] /Count {n} /MediaBox [0 0 200 300] >>", kids.join(" ")));+ objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into());+ for i in 0..n {+ objs.push(format!("<< /Type /Page /Parent 2 0 R /Contents {} 0 R /Resources << /Font << /F1 3 0 R >> >> >>", 5 + 2 * i));+ let body = format!("BT /F1 24 Tf 20 150 Td (Page {}) Tj ET", i + 1);+ objs.push(format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()));+ }+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ out+}++fn harness(pages: usize, setup: impl FnOnce(&mut PrintCraftApp) + 'static) -> Harness<'static, PrintCraftApp> {+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {+ let mut app = PrintCraftApp::new();+ app.open_bytes("doc.pdf", None, fixture(pages)).expect("fixture opens");+ setup(&mut app);+ app+ });+ h.run_steps(4);+ h+}++fn organize(pages: usize) -> Harness<'static, PrintCraftApp> {+ harness(pages, |app| app.set_option("organize", "on").unwrap())+}++/// Page labels of the active document, read back from its current bytes.+fn page_texts(app: &PrintCraftApp) -> Vec<String> {+ let doc = app.session.get(app.views[0].id).unwrap();+ let mut r = PageRenderer::new(doc.bytes.clone(), Default::default());+ (0..r.page_count())+ .map(|p| {+ let out = r.render(RenderRequest { page: p, kind: RequestKind::Text, scale: 1.0, ..Default::default() });+ out.text.map(|t| t.plain_text().trim().to_string()).unwrap_or_default()+ })+ .collect()+}++fn dirty(h: &Harness<'static, PrintCraftApp>) -> bool {+ let app = h.state();+ app.session.get(app.views[0].id).is_some_and(|d| d.dirty)+}++fn temp_path(name: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!("printcraft-ui-tests-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ dir.join(name)+}++#[test]+fn organize_delete_then_undo_and_redo_with_keys() {+ let mut h = organize(3);+ h.get_by_label("Page 2").click();+ h.run_steps(2);+ h.get_by_label_contains("1 page selected");+ h.get_by_label("Delete pages (Delete)").click();+ h.run_steps(3);+ assert_eq!(page_texts(h.state()), ["Page 1", "Page 3"]);+ assert!(dirty(&h));+ h.get_by_label("doc.pdf (edited)"); // the tab shows unsaved changes++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(3);+ assert_eq!(page_texts(h.state()), ["Page 1", "Page 2", "Page 3"]);+ h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);+ h.run_steps(3);+ assert_eq!(page_texts(h.state()), ["Page 1", "Page 3"]);+}++#[test]+fn shift_click_selects_a_range_and_moves_it() {+ let mut h = organize(4);+ h.get_by_label("Page 1").click();+ h.run_steps(1);+ h.get_by_label("Page 2").click_modifiers(Modifiers::SHIFT);+ h.run_steps(2);+ h.get_by_label_contains("2 pages selected");+ h.get_by_label("Move later").click();+ h.run_steps(3);+ assert_eq!(page_texts(h.state()), ["Page 3", "Page 1", "Page 2", "Page 4"]);+ // The moved pages stay selected at their new position, so repeated clicks keep moving them.+ assert_eq!(h.state().views[0].selected.iter().copied().collect::<Vec<_>>(), [1, 2]);+ h.get_by_label("Move later").click();+ h.run_steps(3);+ assert_eq!(page_texts(h.state()), ["Page 3", "Page 4", "Page 1", "Page 2"]);+}++#[test]+fn command_click_toggles_and_rotation_applies_to_selection() {+ let mut h = organize(3);+ h.get_by_label("Page 1").click();+ h.run_steps(1);+ h.get_by_label("Page 3").click_modifiers(Modifiers::COMMAND);+ h.run_steps(2);+ h.get_by_label("Rotate clockwise").click();+ h.run_steps(3);+ let rot: Vec<u16> = {+ let app = h.state();+ app.session.get(app.views[0].id).unwrap().info.pages.iter().map(|p| p.rotation).collect()+ };+ assert_eq!(rot, [90, 0, 90]);+}++#[test]+fn delete_is_refused_when_it_would_remove_every_page() {+ let mut h = organize(2);+ h.state_mut().views[0].select_pages(&[0, 1]);+ h.run_steps(2);+ h.key_press(Key::Delete);+ h.run_steps(3);+ assert_eq!(page_texts(h.state()).len(), 2, "a document keeps at least one page");+ assert!(!dirty(&h));+}++#[test]+fn insert_blank_page_after_selection() {+ let mut h = organize(2);+ h.get_by_label("Page 1").click();+ h.run_steps(1);+ h.get_by_label("Insert a blank page after the selection").click();+ h.run_steps(3);+ assert_eq!(page_texts(h.state()), ["Page 1", "", "Page 2"]);+ let app = h.state();+ let info = &app.session.get(app.views[0].id).unwrap().info;+ assert_eq!((info.pages[1].width, info.pages[1].height), (200.0, 300.0), "matches the neighbouring page");+}++#[test]+fn save_writes_an_incremental_update_and_clears_dirty() {+ let out = temp_path("saved.pdf");+ let original = fixture(3);+ let target = out.to_string_lossy().into_owned();+ let mut h = organize(3);+ h.state_mut().save_override = Some(target.clone());+ h.get_by_label("Page 3").click();+ h.run_steps(1);+ h.get_by_label("Rotate counterclockwise").click();+ h.run_steps(3);+ h.key_press_modifiers(Modifiers::COMMAND, Key::S);+ h.run_steps(3);+ let saved = std::fs::read(&out).expect("file written");+ assert_eq!(&saved[..original.len()], &original[..], "original bytes untouched");+ assert!(!dirty(&h));+ h.get_by_label("saved.pdf"); // the tab takes the new name, no edited marker+ // What was written is what the app now shows.+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().bytes.as_slice(), saved.as_slice());+ let reopened = printcraft_render::inspect(std::sync::Arc::new(saved), None).unwrap();+ assert_eq!(reopened.pages[2].rotation, 270);+ let _ = std::fs::remove_file(out);+}++#[test]+fn closing_a_dirty_tab_asks_and_cancel_keeps_it() {+ let mut h = organize(2);+ h.get_by_label("Rotate clockwise").click();+ h.run_steps(3);+ h.key_press_modifiers(Modifiers::COMMAND, Key::W);+ h.run_steps(3);+ h.get_by_label_contains("Save changes to “doc.pdf”");+ h.get_by_label("Cancel").click();+ h.run_steps(3);+ assert_eq!(h.state().views.len(), 1, "cancel keeps the document open");+ assert!(dirty(&h));+ assert!(h.state().close_request.is_none());++ h.key_press_modifiers(Modifiers::COMMAND, Key::W);+ h.run_steps(3);+ h.get_by_label("Don't save").click();+ h.run_steps(3);+ assert!(h.state().views.is_empty(), "discarding closes the tab");+}++#[test]+fn closing_a_dirty_tab_can_save_first() {+ let out = temp_path("closed.pdf");+ let mut h = organize(2);+ h.state_mut().save_override = Some(out.to_string_lossy().into_owned());+ h.get_by_label("Rotate clockwise").click();+ h.run_steps(3);+ h.state_mut().request_close_tab(0);+ h.run_steps(2);+ h.get_by_label("Save").click();+ h.run_steps(3);+ assert!(h.state().views.is_empty());+ let saved = printcraft_render::inspect(std::sync::Arc::new(std::fs::read(&out).unwrap()), None).unwrap();+ assert_eq!(saved.pages[0].rotation, 90);+ let _ = std::fs::remove_file(out);+}++#[test]+fn clean_tabs_close_without_asking() {+ let mut h = harness(1, |_| {});+ h.key_press_modifiers(Modifiers::COMMAND, Key::W);+ h.run_steps(3);+ assert!(h.state().views.is_empty());+ assert!(h.query_by_label("Don't save").is_none());+}++#[test]+fn quitting_with_unsaved_changes_asks_for_each_document() {+ let mut h = harness(2, |app| {+ app.open_bytes("second.pdf", None, fixture(1)).unwrap();+ });+ // Edit both documents.+ for tab in 0..2 {+ h.state_mut().active = Some(tab);+ h.state_mut().views[tab].select_pages(&[0]);+ h.state_mut().apply_edit(printcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 });+ }+ h.state_mut().close_request = Some(CloseRequest::Quit);+ h.run_steps(3);+ h.get_by_label_contains("Save changes to “doc.pdf”");+ h.get_by_label("Don't save").click();+ h.run_steps(3);+ h.get_by_label_contains("Save changes to “second.pdf”");+ h.get_by_label("Don't save").click();+ h.run_steps(3);+ assert!(h.state().views.is_empty());+ assert!(h.state().close_request.is_none());+}++#[test]+fn document_properties_edit_is_one_undoable_step() {+ let mut h = harness(1, |app| app.set_option("dialog", "properties").unwrap());+ let title = h.get_by_role_and_label(Role::TextInput, "Title");+ title.focus();+ title.type_text("Annual report");+ h.run_steps(2);+ let author = h.get_by_role_and_label(Role::TextInput, "Author");+ author.focus();+ author.type_text("Finance team");+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ let app = h.state();+ let doc = app.session.get(app.views[0].id).unwrap();+ assert_eq!(doc.info.title.as_deref(), Some("Annual report"), "inspection sees the new title");+ assert_eq!(doc.info_value("Author").as_deref(), Some("Finance team"));+ assert_eq!(doc.can_undo(), Some("Change document properties"));+ assert!(app.dialog.is_none());++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(3);+ let app = h.state();+ let doc = app.session.get(app.views[0].id).unwrap();+ assert_eq!(doc.info.title, None);+ assert_eq!(doc.info_value("Author"), None);+}++#[test]+fn cancelling_properties_discards_the_draft() {+ let mut h = harness(1, |app| app.set_option("dialog", "properties").unwrap());+ let title = h.get_by_role_and_label(Role::TextInput, "Title");+ title.focus();+ title.type_text("Draft");+ h.run_steps(2);+ h.get_by_label("Cancel").click();+ h.run_steps(3);+ assert!(!dirty(&h));+ assert!(h.state().props_draft.is_none());+}++#[test]+fn edit_menu_names_the_step_to_undo() {+ let mut h = harness(2, |app| {+ app.apply_edit(printcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 });+ });+ h.get_by_label("Menu").click();+ h.run_steps(2);+ h.get_by_label("Edit ⏵").hover(); // submenus open on hover; their labels carry the arrow+ h.run_steps(3);+ h.get_by_label_contains("Undo Rotate page").click(); // the label includes the shortcut+ h.run_steps(3);+ let app = h.state();+ let doc = app.session.get(app.views[0].id).unwrap();+ assert_eq!(doc.can_redo(), Some("Rotate page"));+ assert_eq!(doc.info.pages[0].rotation, 0);+}diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rsnew file mode 100644index 000000000..bab498b81--- /dev/null+++ b/crates/ui-egui/tests/ui.rs@@ -0,0 +1,214 @@+//! Headless UI tests (egui_kittest + AccessKit). They drive the real app shell without a window.++use egui_kittest::Harness;+use egui_kittest::kittest::Queryable;+use printcraft_ui_egui::PrintCraftApp;++/// A tiny PDF with two pages, two bookmarks and one sticky note.+const FIXTURE: &[u8] = b"%PDF-1.7+1 0 obj << /Type /Catalog /Pages 2 0 R /Outlines 6 0 R >> endobj+2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] /Annots [9 0 R] >> endobj+4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] >> endobj+6 0 obj << /Type /Outlines /First 7 0 R /Last 8 0 R /Count 2 >> endobj+7 0 obj << /Title (Alpha section) /Parent 6 0 R /Next 8 0 R /Dest [3 0 R /Fit] >> endobj+8 0 obj << /Title (Beta section) /Parent 6 0 R /Prev 7 0 R /Dest [4 0 R /Fit] >> endobj+9 0 obj << /Type /Annot /Subtype /Text /Rect [10 370 30 390] /T (Tester) /Contents (Check the numbers) >> endobj+trailer << /Root 1 0 R >>+%%EOF";++fn harness(setup: impl FnOnce(&mut PrintCraftApp) + 'static) -> Harness<'static, PrintCraftApp> {+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {+ let mut app = PrintCraftApp::new();+ setup(&mut app);+ app+ });+ // Fonts install on frame 1 and apply on frame 2.+ h.run_steps(4);+ h+}++#[test]+fn home_shows_welcome_and_tools() {+ let h = harness(|_| {});+ h.get_by_label_contains("Welcome to PrintCraft");+ assert!(h.query_all_by_label("Organize pages").count() >= 2, "tool list + home card");+ h.get_by_label("Open file");+}++#[test]+fn every_catalog_tool_is_listed_after_view_more() {+ let mut h = harness(|_| {});+ h.get_by_label("View more").click();+ h.run_steps(3);+ for g in printcraft_engine::catalog::TOOL_GROUPS {+ assert!(h.query_all_by_label(g.label).count() >= 1, "tool {} missing from All tools", g.label);+ }+}++#[test]+fn opening_a_pdf_shows_comments_and_bookmarks() {+ let mut h = harness(|app| app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).expect("fixture opens"));+ // Documents with comments open on the Comments panel, like Acrobat.+ h.get_by_label_contains("Check the numbers");+ h.get_by_label("Bookmarks").click();+ h.run_steps(3);+ h.get_by_label("Alpha section");+ h.get_by_label("Beta section");+}++#[test]+fn garbage_input_is_rejected_without_panicking() {+ let mut app = PrintCraftApp::new();+ assert!(app.open_bytes("junk.pdf", None, b"this is not a pdf".to_vec()).is_err());+ assert!(app.open_bytes("empty.pdf", None, Vec::new()).is_err());+ let mut truncated = FIXTURE.to_vec();+ truncated.truncate(FIXTURE.len() / 3);+ // A truncated file either repairs or fails cleanly; it must not panic.+ let _ = app.open_bytes("truncated.pdf", None, truncated);+}++#[test]+fn theme_and_view_options_apply() {+ let mut h = harness(|app| {+ app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).expect("fixture opens");+ app.set_option("theme", "dark").unwrap();+ app.set_option("panel", "pages").unwrap();+ app.set_option("page", "2").unwrap();+ });+ h.run_steps(3);+ h.get_by_label("Page 2");+ assert!(h.state_mut().set_option("panel", "nope").is_err());+}++/// Two pages of real text.+const TEXT_FIXTURE: &[u8] = b"%PDF-1.7+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj+2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Contents 5 0 R /Resources << /Font << /F1 7 0 R >> >> >> endobj+4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Contents 6 0 R /Resources << /Font << /F1 7 0 R >> >> >> endobj+5 0 obj << /Length 55 >> stream+BT /F1 14 Tf 20 150 Td (The quick brown fox) Tj ET+endstream endobj+6 0 obj << /Length 58 >> stream+BT /F1 14 Tf 20 150 Td (A second brown animal) Tj ET+endstream endobj+7 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj+trailer << /Root 1 0 R >>+%%EOF";++fn settle(h: &mut Harness<'static, PrintCraftApp>) {+ for _ in 0..200 {+ h.run_steps(2);+ if !h.state().render_pending() {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+}++#[test]+fn find_counts_matches_across_pages() {+ let mut h = harness(|app| {+ app.open_bytes("text.pdf", None, TEXT_FIXTURE.to_vec()).expect("opens");+ app.set_option("find", "brown").unwrap();+ });+ settle(&mut h);+ h.get_by_label_contains("of 2");+ let v = &h.state().views[0];+ let f = v.find.as_ref().expect("find open");+ assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![0, 1]);+}++#[test]+fn find_reports_no_matches() {+ let mut h = harness(|app| {+ app.open_bytes("text.pdf", None, TEXT_FIXTURE.to_vec()).expect("opens");+ app.set_option("find", "zebra").unwrap();+ });+ settle(&mut h);+ h.get_by_label("No matches");+}++#[test]+fn drag_selects_text_and_copy_returns_it() {+ let mut h = harness(|app| {+ app.open_bytes("text.pdf", None, TEXT_FIXTURE.to_vec()).expect("opens");+ app.set_option("left", "closed").unwrap();+ });+ settle(&mut h);+ // "The quick brown fox": glyph 4 = 'q', glyph 14 = 'n' of "brown".+ let (a, b) = {+ let v = &h.state().views[0];+ (v.glyph_screen_pos(0, 4).expect("text layer loaded"), v.glyph_screen_pos(0, 14).expect("glyph"))+ };+ h.hover_at(a);+ h.run_steps(1);+ h.drag_at(a);+ h.run_steps(1);+ h.hover_at(a + (b - a) * 0.5);+ h.run_steps(1);+ h.hover_at(b);+ h.run_steps(2);+ h.drop_at(b);+ h.run_steps(2);+ assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick brown"));+}++#[test]+fn persistence_round_trips_and_tolerates_garbage() {+ let mut a = PrintCraftApp::new();+ a.theme = printcraft_ui_egui::theme::ThemeKind::Dark;+ let json = a.persist();+ let mut b = PrintCraftApp::new();+ b.restore(&json);+ assert_eq!(b.theme, printcraft_ui_egui::theme::ThemeKind::Dark);+ b.restore("{not json");+ b.restore("{\"recent\": 5, \"theme\": \"Purple\"}");+ assert_eq!(b.theme, printcraft_ui_egui::theme::ThemeKind::Dark);+}++#[test]+fn zoom_keeps_the_point_under_the_cursor_still() {+ let mut h = harness(|app| {+ app.open_bytes("text.pdf", None, TEXT_FIXTURE.to_vec()).expect("opens");+ app.set_option("left", "closed").unwrap();+ app.set_option("panel", "none").unwrap();+ });+ settle(&mut h);+ let before = h.state().views[0].glyph_screen_pos(0, 4).expect("glyph on screen");+ let z = h.state().views[0].zoom;+ h.state_mut().views[0].zoom_at(z * 2.0, before);+ h.run_steps(4);+ let after = h.state().views[0].glyph_screen_pos(0, 4).expect("glyph still on screen");+ assert!((after - before).length() < 2.0, "moved from {before:?} to {after:?}");+}++#[test]+fn selection_works_in_every_view_rotation() {+ for deg in ["90", "180", "270"] {+ let mut h = harness(move |app| {+ app.open_bytes("text.pdf", None, TEXT_FIXTURE.to_vec()).expect("opens");+ app.set_option("left", "closed").unwrap();+ app.set_option("rotate", deg).unwrap();+ // Keep the whole rotated page on screen.+ app.set_option("zoom", "60").unwrap();+ });+ settle(&mut h);+ let (a, b) = {+ let v = &h.state().views[0];+ (v.glyph_screen_pos(0, 4).expect("glyph"), v.glyph_screen_pos(0, 14).expect("glyph"))+ };+ h.hover_at(a);+ h.run_steps(1);+ h.drag_at(a);+ h.run_steps(1);+ h.hover_at(a + (b - a) * 0.5);+ h.run_steps(1);+ h.hover_at(b);+ h.run_steps(2);+ h.drop_at(b);+ h.run_steps(2);+ assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick brown"), "rotation {deg}");+ }+}diff --git a/docs/images/printcraft-organize.png b/docs/images/printcraft-organize.pngnew file mode 100644index 000000000..f49b3c886Binary files /dev/null and b/docs/images/printcraft-organize.png differdiff --git a/docs/images/printcraft-viewer.png b/docs/images/printcraft-viewer.pngnew file mode 100644index 000000000..8e7143802Binary files /dev/null and b/docs/images/printcraft-viewer.png differdiff --git a/vendor/README.md b/vendor/README.mdnew file mode 100644index 000000000..6362e5351--- /dev/null+++ b/vendor/README.md@@ -0,0 +1,14 @@+# Vendored crates++Permissively licensed crates we carry small patches for. Each directory keeps the upstream+licence files unchanged. Every patch is marked `PrintCraft patch:` in the source, is covered by a+PrintCraft test, and should be proposed upstream. Remove the vendored copy once upstream releases+the fix. Vendoring copyleft code is never allowed (plan/adr/0001).++| Crate | Version | Licence | Patches | Test |+|---|---|---|---|---|+| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text) | (1) `raster::tests::widget_appearance_states`; (2, 3) `xtask text-oracle` on corpus/pdfjs issue918; (4) `raster::tests::layer_override_hides_content`; (5) `raster::tests::soft_mask_without_group_colour_space_is_applied` |++| hayro | 0.7.1 | Apache-2.0 OR MIT | `RenderSettings::{x_offset, y_offset}` to render one tile of a large page | `raster::tests::tiles_match_full_render` |++Temporary: hayro is the bootstrap renderer (ADR-0004); M2.6 replaces it with our own devices.diff --git a/vendor/hayro-interpret/.cargo-ok b/vendor/hayro-interpret/.cargo-oknew file mode 100644index 000000000..5f8b79583--- /dev/null+++ b/vendor/hayro-interpret/.cargo-ok@@ -0,0 +1 @@+{"v":1}\ No newline at end of filediff --git a/vendor/hayro-interpret/.cargo_vcs_info.json b/vendor/hayro-interpret/.cargo_vcs_info.jsonnew file mode 100644index 000000000..d89fbc1b6--- /dev/null+++ b/vendor/hayro-interpret/.cargo_vcs_info.json@@ -0,0 +1,6 @@+{+ "git": {+ "sha1": "0c98904d2ced8e37b63ed2bd1e60f95bc0c7c774"+ },+ "path_in_vcs": "hayro-interpret"+}\ No newline at end of filediff --git a/vendor/hayro-interpret/Cargo.lock b/vendor/hayro-interpret/Cargo.locknew file mode 100644index 000000000..c10e17498--- /dev/null+++ b/vendor/hayro-interpret/Cargo.lock@@ -0,0 +1,529 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[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 = "arrayvec"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"++[[package]]+name = "autocfg"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"++[[package]]+name = "bitflags"+version = "2.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"++[[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 = "bytemuck"+version = "1.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "crc32fast"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"+dependencies = [+ "cfg-if",+]++[[package]]+name = "euclid"+version = "0.22.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"+dependencies = [+ "num-traits",+]++[[package]]+name = "fastrand"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "fearless_simd"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76258897e51fd156ee03b6246ea53f3e0eb395d0b327e9961c4fc4c8b2fa151a"++[[package]]+name = "flate2"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"+dependencies = [+ "crc32fast",+ "miniz_oxide",+ "zlib-rs",+]++[[package]]+name = "font-types"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"+dependencies = [+ "bytemuck",+]++[[package]]+name = "hayro-ccitt"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+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",+]++[[package]]+name = "hayro-interpret"+version = "0.7.0"+dependencies = [+ "bitflags",+ "hayro-cmap",+ "hayro-syntax",+ "image",+ "kurbo",+ "log",+ "moxcms",+ "phf",+ "rustc-hash",+ "siphasher",+ "skrifa",+ "smallvec",+ "yoke",+]++[[package]]+name = "hayro-jbig2"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d"+dependencies = [+ "fearless_simd",+ "hayro-ccitt",+]++[[package]]+name = "hayro-jpeg2000"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"+dependencies = [+ "fearless_simd",+ "log",+]++[[package]]+name = "hayro-postscript"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"++[[package]]+name = "hayro-syntax"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6cff966952259902703369bf0f565ab757de6e022deb25db3a8734f39eca6d17"+dependencies = [+ "flate2",+ "hayro-ccitt",+ "hayro-jbig2",+ "hayro-jpeg2000",+ "log",+ "memchr",+ "rustc-hash",+ "smallvec",+ "zune-jpeg",+]++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "moxcms",+ "num-traits",+ "png",+]++[[package]]+name = "kurbo"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"+dependencies = [+ "arrayvec",+ "euclid",+ "polycool",+ "smallvec",+]++[[package]]+name = "log"+version = "0.4.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"++[[package]]+name = "memchr"+version = "2.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "phf"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"+dependencies = [+ "phf_macros",+ "phf_shared",+]++[[package]]+name = "phf_generator"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"+dependencies = [+ "fastrand",+ "phf_shared",+]++[[package]]+name = "phf_macros"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"+dependencies = [+ "phf_generator",+ "phf_shared",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "phf_shared"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"+dependencies = [+ "siphasher",+]++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide",+]++[[package]]+name = "polycool"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"+dependencies = [+ "arrayvec",+]++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "pxfm"+version = "0.1.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5a041e753da8b807c9255f28de81879c78c876392ff2469cde94799b2896b9d"++[[package]]+name = "quote"+version = "1.0.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "read-fonts"+version = "0.39.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"+dependencies = [+ "bytemuck",+ "font-types",+]++[[package]]+name = "rustc-hash"+version = "2.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"++[[package]]+name = "simd-adler32"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"++[[package]]+name = "siphasher"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e"++[[package]]+name = "skrifa"+version = "0.42.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"+dependencies = [+ "bytemuck",+ "read-fonts",+]++[[package]]+name = "smallvec"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "syn"+version = "2.0.117"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "yoke"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerofrom"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zlib-rs"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3be3d40e40a133f9c916ee3f9f4fa2d9d63435b5fbe1bfc6d9dae0aa0ada1513"++[[package]]+name = "zune-core"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]diff --git a/vendor/hayro-interpret/Cargo.toml b/vendor/hayro-interpret/Cargo.tomlnew file mode 100644index 000000000..3d1911606--- /dev/null+++ b/vendor/hayro-interpret/Cargo.toml@@ -0,0 +1,139 @@+# 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"+rust-version = "1.92"+name = "hayro-interpret"+version = "0.7.0"+authors = ["Laurenz Stampfl <[email protected]>"]+build = false+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "A crate for interpreting PDF files."+readme = "README.md"+license = "Apache-2.0 OR MIT"+repository = "https://github.com/LaurenzV/hayro"+resolver = "2"++[features]+default = [+ "embed-fonts",+ "embed-cmaps",+]+embed-cmaps = ["hayro-cmap/embed-cmaps"]+embed-fonts = []+logging = [+ "dep:log",+ "hayro-syntax/logging",+]++[lib]+name = "hayro_interpret"+path = "src/lib.rs"++[[example]]+name = "extract_html"+path = "examples/extract_html.rs"++[[example]]+name = "extract_images"+path = "examples/extract_images.rs"++[dependencies.bitflags]+version = "2.10"++[dependencies.hayro-cmap]+version = "0.1.0"+default-features = false++[dependencies.hayro-syntax]+version = "0.7.0"+features = [+ "std",+ "images",+ "unsafe",+]+default-features = false++[dependencies.kurbo]+version = "0.13.0"++[dependencies.log]+version = "0.4"+optional = true++[dependencies.moxcms]+version = "0.8.1"++[dependencies.phf]+version = "0.13.1"+features = ["macros"]+default-features = false++[dependencies.rustc-hash]+version = "2"++[dependencies.siphasher]+version = "1"++[dependencies.skrifa]+version = "0.42.0"++[dependencies.smallvec]+version = "1"++[dependencies.yoke]+version = "0.8"+features = ["derive"]++[dev-dependencies.image]+version = "0.25"+features = ["png"]+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-interpret/Cargo.toml.orig b/vendor/hayro-interpret/Cargo.toml.orignew file mode 100644index 000000000..4d0abc721--- /dev/null+++ b/vendor/hayro-interpret/Cargo.toml.orig@@ -0,0 +1,38 @@+[package]+name = "hayro-interpret"+version = "0.7.0"+description = "A crate for interpreting PDF files."+edition = { workspace = true }+rust-version = { workspace = true }+authors = { workspace = true }+repository = { workspace = true }+license = { workspace = true }+readme = "README.md"++[dependencies]+hayro-cmap = { workspace = true }+hayro-syntax = { workspace = true, features = ["std", "images", "unsafe"] }+kurbo = { workspace = true }+smallvec = { workspace = true }+log = { workspace = true, optional = true }+moxcms = { workspace = true }+phf = { workspace = true, features = ["macros"] }+skrifa = { workspace = true }+yoke = { workspace = true, features = ["derive"]}+siphasher = { workspace = true }+bitflags = { workspace = true }+rustc-hash = { workspace = true }++[dev-dependencies]+image = { workspace = true, features = ["png"] }++[features]+default = ["embed-fonts", "embed-cmaps"]+# Embed a light-weight set of fonts (around 240KB) that can be used as a substitute for the 14 PDF standard fonts.+embed-fonts = []+# Embed the 61 predefined cmaps into the binary. Adds about ~250KB of brotli-encoded data.+embed-cmaps = ["hayro-cmap/embed-cmaps"]+logging = ["dep:log", "hayro-syntax/logging"]++[lints]+workspace = truediff --git a/vendor/hayro-interpret/LICENSE-APACHE b/vendor/hayro-interpret/LICENSE-APACHEnew file mode 100644index 000000000..4947287f7--- /dev/null+++ b/vendor/hayro-interpret/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 filediff --git a/vendor/hayro-interpret/LICENSE-MIT b/vendor/hayro-interpret/LICENSE-MITnew file mode 100644index 000000000..ae3742de4--- /dev/null+++ b/vendor/hayro-interpret/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 filediff --git a/vendor/hayro-interpret/README.md b/vendor/hayro-interpret/README.mdnew file mode 100644index 000000000..effd44596--- /dev/null+++ b/vendor/hayro-interpret/README.md@@ -0,0 +1,41 @@+# hayro-interpret++[](https://crates.io/crates/hayro-interpret)+[](https://docs.rs/hayro-interpret)++<!-- cargo-rdme start -->++A crate for interpreting PDF files.++This crate provides an abstraction to interpret the content of a PDF file and render them+into an abstract [`Device`], which clients can implement as needed. This allows you, for+example, to render PDF files to bitmaps (which is what the `hayro` crate does), or other formats+such as SVG.++It should be noted that this crate is still very much in development. Therefore it currently+lacks pretty much any documentation on how to use it. It's current API also only really makes it+useful for rendering to PNG or SVG, though this will be improved upon in the future.++## Examples+See the `examples` folder on the GitHub repository. Apart from that, you can also consult+the implementation of `hayro` and `hayro-svg` to get an idea on how to use this crate.++## Safety+This crate forbids unsafe code via a crate-level attribute.++## Cargo features+This crate has one optional feature:+- `embed-fonts`: PDF processors are required to support 14 predefined fonts that do not need to be+ embedded into a PDF file. If you enable this feature, hayro will embed a (permissively-licensed)+ substitute for each font, so that you don't have to implement your custom font loading logic. This+ will add around ~240KB to your binary.++<!-- cargo-rdme end -->++## License+Licensed under either of++- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)+- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)++at your option.diff --git a/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc b/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.iccnew file mode 100644index 000000000..b5a73495bBinary files /dev/null and b/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc differdiff --git a/vendor/hayro-interpret/assets/CGATS_LICENSE.txt b/vendor/hayro-interpret/assets/CGATS_LICENSE.txtnew file mode 100644index 000000000..550e190e5--- /dev/null+++ b/vendor/hayro-interpret/assets/CGATS_LICENSE.txt@@ -0,0 +1,116 @@+CC0 1.0 Universal++Statement of Purpose++The laws of most jurisdictions throughout the world automatically confer+exclusive Copyright and Related Rights (defined below) upon the creator and+subsequent owner(s) (each and all, an "owner") of an original work of+authorship and/or a database (each, a "Work").++Certain owners wish to permanently relinquish those rights to a Work for the+purpose of contributing to a commons of creative, cultural and scientific+works ("Commons") that the public can reliably and without fear of later+claims of infringement build upon, modify, incorporate in other works, reuse+and redistribute as freely as possible in any form whatsoever and for any+purposes, including without limitation commercial purposes. These owners may+contribute to the Commons to promote the ideal of a free culture and the+further production of creative, cultural and scientific works, or to gain+reputation or greater distribution for their Work in part through the use and+efforts of others.++For these and/or other purposes and motivations, and without any expectation+of additional consideration or compensation, the person associating CC0 with a+Work (the "Affirmer"), to the extent that he or she is an owner of Copyright+and Related Rights in the Work, voluntarily elects to apply CC0 to the Work+and publicly distribute the Work under its terms, with knowledge of his or her+Copyright and Related Rights in the Work and the meaning and intended legal+effect of CC0 on those rights.++1. Copyright and Related Rights. A Work made available under CC0 may be+protected by copyright and related or neighboring rights ("Copyright and+Related Rights"). Copyright and Related Rights include, but are not limited+to, the following:++ i. the right to reproduce, adapt, distribute, perform, display, communicate,+ and translate a Work;++ ii. moral rights retained by the original author(s) and/or performer(s);++ iii. publicity and privacy rights pertaining to a person's image or likeness+ depicted in a Work;++ iv. rights protecting against unfair competition in regards to a Work,+ subject to the limitations in paragraph 4(a), below;++ v. rights protecting the extraction, dissemination, use and reuse of data in+ a Work;++ vi. database rights (such as those arising under Directive 96/9/EC of the+ European Parliament and of the Council of 11 March 1996 on the legal+ protection of databases, and under any national implementation thereof,+ including any amended or successor version of such directive); and++ vii. other similar, equivalent or corresponding rights throughout the world+ based on applicable law or treaty, and any national implementations thereof.++2. Waiver. To the greatest extent permitted by, but not in contravention of,+applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and+unconditionally waives, abandons, and surrenders all of Affirmer's Copyright+and Related Rights and associated claims and causes of action, whether now+known or unknown (including existing as well as future claims and causes of+action), in the Work (i) in all territories worldwide, (ii) for the maximum+duration provided by applicable law or treaty (including future time+extensions), (iii) in any current or future medium and for any number of+copies, and (iv) for any purpose whatsoever, including without limitation+commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes+the Waiver for the benefit of each member of the public at large and to the+detriment of Affirmer's heirs and successors, fully intending that such Waiver+shall not be subject to revocation, rescission, cancellation, termination, or+any other legal or equitable action to disrupt the quiet enjoyment of the Work+by the public as contemplated by Affirmer's express Statement of Purpose.++3. Public License Fallback. Should any part of the Waiver for any reason be+judged legally invalid or ineffective under applicable law, then the Waiver+shall be preserved to the maximum extent permitted taking into account+Affirmer's express Statement of Purpose. In addition, to the extent the Waiver+is so judged Affirmer hereby grants to each affected person a royalty-free,+non transferable, non sublicensable, non exclusive, irrevocable and+unconditional license to exercise Affirmer's Copyright and Related Rights in+the Work (i) in all territories worldwide, (ii) for the maximum duration+provided by applicable law or treaty (including future time extensions), (iii)+in any current or future medium and for any number of copies, and (iv) for any+purpose whatsoever, including without limitation commercial, advertising or+promotional purposes (the "License"). The License shall be deemed effective as+of the date CC0 was applied by Affirmer to the Work. Should any part of the+License for any reason be judged legally invalid or ineffective under+applicable law, such partial invalidity or ineffectiveness shall not+invalidate the remainder of the License, and in such case Affirmer hereby+affirms that he or she will not (i) exercise any of his or her remaining+Copyright and Related Rights in the Work or (ii) assert any associated claims+and causes of action with respect to the Work, in either case contrary to+Affirmer's express Statement of Purpose.++4. Limitations and Disclaimers.++ a. No trademark or patent rights held by Affirmer are waived, abandoned,+ surrendered, licensed or otherwise affected by this document.++ b. Affirmer offers the Work as-is and makes no representations or warranties+ of any kind concerning the Work, express, implied, statutory or otherwise,+ including without limitation warranties of title, merchantability, fitness+ for a particular purpose, non infringement, or the absence of latent or+ other defects, accuracy, or the present or absence of errors, whether or not+ discoverable, all to the greatest extent permissible under applicable law.++ c. Affirmer disclaims responsibility for clearing rights of other persons+ that may apply to the Work or any use thereof, including without limitation+ any person's Copyright and Related Rights in the Work. Further, Affirmer+ disclaims responsibility for obtaining any necessary consents, permissions+ or other rights required for any use of the Work.++ d. Affirmer understands and acknowledges that Creative Commons is not a+ party to this document and has no duty or obligation with respect to this+ CC0 or use of the Work.++For more information, please see+http://creativecommons.org/publicdomain/zero/1.0/\ No newline at end of filediff --git a/vendor/hayro-interpret/assets/FoxitDingbats.pfb b/vendor/hayro-interpret/assets/FoxitDingbats.pfbnew file mode 100644index 000000000..30d52963eBinary files /dev/null and b/vendor/hayro-interpret/assets/FoxitDingbats.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitFixed.pfb b/vendor/hayro-interpret/assets/FoxitFixed.pfbnew file mode 100644index 000000000..f12dcbce5Binary files /dev/null and b/vendor/hayro-interpret/assets/FoxitFixed.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitFixedBold.pfb b/vendor/hayro-interpret/assets/FoxitFixedBold.pfbnew file mode 100644index 000000000..cf8e24aeeBinary files /dev/null and b/vendor/hayro-interpret/assets/FoxitFixedBold.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb b/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfbnew file mode 100644index 000000000..d2880017cBinary files /dev/null and b/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb b/vendor/hayro-interpret/assets/FoxitFixedItalic.pfbnew file mode 100644index 000000000..d71697d4bBinary files /dev/null and b/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitSans.pfb b/vendor/hayro-interpret/assets/FoxitSans.pfbnew file mode 100644index 000000000..37f244bd9Binary files /dev/null and b/vendor/hayro-interpret/assets/FoxitSans.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitSansBold.pfb b/vendor/hayro-interpret/assets/FoxitSansBold.pfbnew file mode 100644index 000000000..affcf316dBinary files /dev/null and b/vendor/hayro-interpret/assets/FoxitSansBold.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb b/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfbnew file mode 100644index 000000000..e1f60b754Binary files /dev/null and b/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitSansItalic.pfb b/vendor/hayro-interpret/assets/FoxitSansItalic.pfbnew file mode 100644index 000000000..c04b0a5aeBinary files /dev/null and b/vendor/hayro-interpret/assets/FoxitSansItalic.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitSerif.pfb b/vendor/hayro-interpret/assets/FoxitSerif.pfbnew file mode 100644index 000000000..3fa682efbBinary files /dev/null and b/vendor/hayro-interpret/assets/FoxitSerif.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitSerifBold.pfb b/vendor/hayro-interpret/assets/FoxitSerifBold.pfbnew file mode 100644index 000000000..ff7c6ddecBinary files /dev/null and b/vendor/hayro-interpret/assets/FoxitSerifBold.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb b/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfbnew file mode 100644index 000000000..460231fb8Binary files /dev/null and b/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb b/vendor/hayro-interpret/assets/FoxitSerifItalic.pfbnew file mode 100644index 000000000..d03a7c781Binary files /dev/null and b/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb differdiff --git a/vendor/hayro-interpret/assets/FoxitSymbol.pfb b/vendor/hayro-interpret/assets/FoxitSymbol.pfbnew file mode 100644index 000000000..c8f9bca78Binary files /dev/null and b/vendor/hayro-interpret/assets/FoxitSymbol.pfb differdiff --git a/vendor/hayro-interpret/assets/LAB.icc b/vendor/hayro-interpret/assets/LAB.iccnew file mode 100644index 000000000..23feae1adBinary files /dev/null and b/vendor/hayro-interpret/assets/LAB.icc differdiff --git a/vendor/hayro-interpret/assets/LICENSE_FOXIT b/vendor/hayro-interpret/assets/LICENSE_FOXITnew file mode 100644index 000000000..8b4ed6ddd--- /dev/null+++ b/vendor/hayro-interpret/assets/LICENSE_FOXIT@@ -0,0 +1,27 @@+// Copyright 2014 PDFium Authors. 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 Google Inc. 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+// OWNER 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-interpret/assets/README.md b/vendor/hayro-interpret/assets/README.mdnew file mode 100644index 000000000..6603fb467--- /dev/null+++ b/vendor/hayro-interpret/assets/README.md@@ -0,0 +1,15 @@+The CMYK profile is from: https://github.com/saucecontrol/Compact-ICC-Profiles?tab=readme-ov-file#cmyk, available under the CC0-1.0 License++The pfb files in this directory were extracted from Pdfium++Original copyright notice:++```+Copyright 2014 PDFium Authors. All rights reserved.+ Use of this source code is governed by a BSD-style license that can be+ found in the LICENSE file.++Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com+```++The LAB.icc profile was generated with LCMS2.\ No newline at end of filediff --git a/vendor/hayro-interpret/examples/extract_html.rs b/vendor/hayro-interpret/examples/extract_html.rsnew file mode 100644index 000000000..8e5933b1e--- /dev/null+++ b/vendor/hayro-interpret/examples/extract_html.rs@@ -0,0 +1,122 @@+//! A small example that shows how you can extract unicode characters from+//! glyphs. Please note that Unicode extraction is still experimental, so it+//! might not work fully correctly in certain cases. Note also that generating+//! div elements for every single character is clearly not desirable and there+//! should be some word/sentence merging algorithm in-place, but this is+//! out-of-scope for this example.++use hayro_interpret::font::Glyph;+use hayro_interpret::{+ BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache,+ InterpreterSettings, Paint, PathDrawMode, SoftMask, interpret_page,+};+use hayro_syntax::Pdf;++use std::fmt::Write;++use hayro_cmap::BfString;+use kurbo::{Affine, BezPath, Point, Rect};+use std::path::PathBuf;++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let relative_path = args+ .get(1)+ .expect("Please provide a relative path to the PDF file as the first argument");+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(relative_path);+ let data = std::fs::read(path).unwrap();++ let pdf = Pdf::new(data).unwrap();++ let settings = InterpreterSettings::default();+ let cache = InterpreterCache::new();+ // Pass dummy values for bbox and initial transform, since we don't care about those.+ let mut context = Context::new(+ Affine::IDENTITY,+ Rect::new(0.0, 0.0, 1.0, 1.0),+ &cache,+ pdf.xref(),+ settings,+ );++ // Run everything!+ let page = &pdf.pages()[0];++ let mut extractor = TextExtractor {+ dimensions: page.render_dimensions(),+ ..Default::default()+ };++ writeln!(extractor.text, "<meta charset='utf-8' /> ").unwrap();+ writeln!(extractor.text, "<!-- page {} -->", 0).unwrap();+ writeln!(+ extractor.text,+ "<div id='page{}' style='position: relative; width: {}px; height: {}px; border: 1px black solid'>",+ 0,+ extractor.dimensions.0,+ extractor.dimensions.1+ ).unwrap();++ interpret_page(page, &mut context, &mut extractor);++ writeln!(extractor.text, "</div>").unwrap();++ print!("{}", extractor.text);+}++#[derive(Default)]+struct TextExtractor {+ text: String,+ dimensions: (f32, f32),+}++/// Implement `Device` for `TextExtractor`. We extract Unicode text from glyphs.+impl Device<'_> for TextExtractor {+ fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}++ fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'_>, _: &PathDrawMode) {}++ fn push_clip_path(&mut self, _: &ClipPath) {}++ fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}++ fn draw_glyph(+ &mut self,+ glyph: &Glyph<'_>,+ transform: Affine,+ glyph_transform: Affine,+ _: &Paint<'_>,+ _: &GlyphDrawMode,+ ) {+ if let Some(unicode_char) = glyph.as_unicode() {+ // Apply vertical flip transformation to combined transform+ // to place origin at top-left corner.+ let flip_transform = Affine::translate((0.0, self.dimensions.1 as f64))+ * Affine::scale_non_uniform(1.0, -1.0);+ let transform = flip_transform * transform * glyph_transform;++ let point = Point::new(0.0, 0.0);+ let position = transform * point;++ writeln!(+ self.text,+ "<div style='position: absolute; color: black; left: {}px; top: {}px; font-size: {}pt'>{}</div>",+ position.x, position.y, 6, match unicode_char {+ BfString::Char(c) => c.to_string(),+ BfString::String(s) => s+ }+ ).unwrap();+ } else {+ // Fallback for glyphs without Unicode mapping.+ self.text.push('�');+ }+ }++ fn pop_clip_path(&mut self) {}++ fn pop_transparency_group(&mut self) {}++ fn draw_image(&mut self, _: Image<'_, '_>, _: Affine) {}++ fn set_blend_mode(&mut self, _: BlendMode) {}+}diff --git a/vendor/hayro-interpret/examples/extract_images.rs b/vendor/hayro-interpret/examples/extract_images.rsnew file mode 100644index 000000000..07e440617--- /dev/null+++ b/vendor/hayro-interpret/examples/extract_images.rs@@ -0,0 +1,147 @@+//! This example demonstrates how you can extract all images used on a page and save them as+//! PNG.+//!+//! Note that you must have downloaded the corresponding PDF file for the example to work.++use hayro_interpret::font::Glyph;+use hayro_interpret::{+ BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, ImageData, InterpreterCache,+ InterpreterSettings, Paint, PathDrawMode, SoftMask, interpret_page,+};+use hayro_syntax::Pdf;+use image::{DynamicImage, ImageBuffer};+use kurbo::{Affine, BezPath, Rect};+use std::path::PathBuf;++fn main() {+ let data = std::fs::read(+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../hayro-tests/pdfs/custom/image_rgb8.pdf"),+ )+ .unwrap();++ let pdf = Pdf::new(data).unwrap();++ let mut extractor = ImageExtractor::new();+ let settings = InterpreterSettings::default();+ let cache = InterpreterCache::new();+ // Pass dummy values for bbox and initial transform, since we don't care about those.+ let mut context = Context::new(+ Affine::IDENTITY,+ Rect::new(0.0, 0.0, 1.0, 1.0),+ &cache,+ pdf.xref(),+ settings,+ );++ // Run everything!+ let page = &pdf.pages()[0];+ interpret_page(page, &mut context, &mut extractor);++ // Then just save all of the images!+ for (idx, img) in extractor.0.iter().enumerate() {+ img.save(format!("image_{idx}.png")).unwrap();+ }+}++struct ImageExtractor(Vec<DynamicImage>);++impl ImageExtractor {+ fn new() -> Self {+ Self(Vec::new())+ }+}++/// Implement `Device` for `ImageExtractor`. We can ignore most operations and only+/// need to implement `draw_rgba_image` and `draw_stencil_image`.+impl Device<'_> for ImageExtractor {+ fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}++ fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'_>, _: &PathDrawMode) {}++ fn push_clip_path(&mut self, _: &ClipPath) {}++ fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}++ fn draw_glyph(+ &mut self,+ _: &Glyph<'_>,+ _: Affine,+ _: Affine,+ _: &Paint<'_>,+ _: &GlyphDrawMode,+ ) {+ }++ fn pop_clip_path(&mut self) {}++ fn pop_transparency_group(&mut self) {}++ fn draw_image(&mut self, image: Image<'_, '_>, _: Affine) {+ match image {+ Image::Stencil(s) => {+ s.with_stencil(+ |stencil, _paint| {+ // Stencil images are gray-channel images that should be painted using the color stored in+ // `paint`. For simplicity, we just store them as gray-channel for now.+ self.0.push(DynamicImage::ImageLuma8(+ ImageBuffer::from_raw(+ stencil.width,+ stencil.height,+ stencil.data.clone(),+ )+ .unwrap(),+ ));+ },+ None,+ );+ }+ Image::Raster(r) => {+ // The alpha and RGB channels are provided separately.+ r.with_rgba(+ |image, alpha| {+ let (rgb_data, width, height) = match image {+ ImageData::Rgb(rgb) => (rgb.data, rgb.width, rgb.height),+ ImageData::Luma(luma) => {+ let rgb = luma+ .data+ .iter()+ .flat_map(|g| [*g, *g, *g])+ .collect::<Vec<_>>();+ (rgb, luma.width, luma.height)+ }+ };++ let image = if let Some(alpha) = alpha {+ // This is not complete, as it can in theory happen that the alpha channel has a different+ // dimension than the RGB channel. We ignore this edge case for this example.+ if alpha.width == width && alpha.height == height {+ let interleaved = rgb_data+ .chunks(3)+ .zip(alpha.data)+ .flat_map(|(rgb, a)| [rgb[0], rgb[1], rgb[2], a])+ .collect::<Vec<u8>>();++ DynamicImage::ImageRgba8(+ ImageBuffer::from_raw(width, height, interleaved).unwrap(),+ )+ } else {+ DynamicImage::ImageRgb8(+ ImageBuffer::from_raw(width, height, rgb_data).unwrap(),+ )+ }+ } else {+ DynamicImage::ImageRgb8(+ ImageBuffer::from_raw(width, height, rgb_data).unwrap(),+ )+ };++ self.0.push(image);+ },+ None,+ );+ }+ }+ }++ fn set_blend_mode(&mut self, _: BlendMode) {}+}diff --git a/vendor/hayro-interpret/src/cache.rs b/vendor/hayro-interpret/src/cache.rsnew file mode 100644index 000000000..01bbf46c4--- /dev/null+++ b/vendor/hayro-interpret/src/cache.rs@@ -0,0 +1,161 @@+use crate::util::hash128;+use hayro_syntax::object::{Array, Dict, MaybeRef, Name, Null, ObjRef, Object, Stream};+use kurbo::Affine;+use std::any::Any;+use std::collections::HashMap;+use std::collections::hash_map::Entry;+use std::sync::{Arc, Mutex};++type CacheMap = HashMap<u128, Option<Box<dyn Any + Send + Sync>>>;+#[derive(Clone)]+pub(crate) struct Cache(Arc<Mutex<CacheMap>>);++impl Default for Cache {+ fn default() -> Self {+ Self::new()+ }+}++impl Cache {+ pub(crate) fn new() -> Self {+ Self(Arc::new(Mutex::new(HashMap::new())))+ }++ pub(crate) fn get_or_insert_with<T: Clone + Send + Sync + 'static>(+ &self,+ id: u128,+ f: impl FnOnce() -> Option<T>,+ ) -> Option<T> {+ let mut locked = self.0.lock().unwrap();++ // We can't use `get_or_insert_with` here, because if the closure makes another access to the+ // cache, we end up with a deadlock.+ match locked.entry(id) {+ Entry::Occupied(o) => o+ .get()+ .as_ref()+ .and_then(|val| val.downcast_ref::<T>().cloned()),+ Entry::Vacant(_) => {+ drop(locked);+ let val = f();+ self.0.lock().unwrap().insert(+ id,+ val.clone()+ .map(|val| Box::new(val) as Box<dyn Any + Send + Sync>),+ );++ val+ }+ }+ }+}++/// A trait for objects that can generate a unique cache key.+pub trait CacheKey {+ /// Returns the cache key for this object.+ fn cache_key(&self) -> u128;+}++impl<T: CacheKey, U: CacheKey> CacheKey for (T, U) {+ fn cache_key(&self) -> u128 {+ hash128(&(self.0.cache_key(), self.1.cache_key()))+ }+}++impl CacheKey for Dict<'_> {+ fn cache_key(&self) -> u128 {+ hash128(self.data())+ }+}++impl CacheKey for Stream<'_> {+ fn cache_key(&self) -> u128 {+ self.dict().cache_key()+ }+}++impl CacheKey for Null {+ fn cache_key(&self) -> u128 {+ hash128(self)+ }+}++impl CacheKey for bool {+ fn cache_key(&self) -> u128 {+ hash128(self)+ }+}++impl CacheKey for hayro_syntax::object::Number {+ fn cache_key(&self) -> u128 {+ hash128(&self.as_f64().to_bits())+ }+}++impl CacheKey for hayro_syntax::object::String<'_> {+ fn cache_key(&self) -> u128 {+ hash128(self.as_ref())+ }+}++impl CacheKey for Name<'_> {+ fn cache_key(&self) -> u128 {+ hash128(self)+ }+}++impl CacheKey for Array<'_> {+ fn cache_key(&self) -> u128 {+ hash128(self.data())+ }+}++impl CacheKey for Object<'_> {+ fn cache_key(&self) -> u128 {+ match self {+ Object::Null(n) => n.cache_key(),+ Object::Boolean(b) => b.cache_key(),+ Object::Number(n) => n.cache_key(),+ Object::String(s) => s.cache_key(),+ Object::Name(n) => n.cache_key(),+ Object::Dict(d) => d.cache_key(),+ Object::Array(a) => a.cache_key(),+ Object::Stream(s) => s.cache_key(),+ }+ }+}++impl CacheKey for ObjRef {+ fn cache_key(&self) -> u128 {+ hash128(self)+ }+}++impl<T: CacheKey> CacheKey for MaybeRef<T> {+ fn cache_key(&self) -> u128 {+ match self {+ Self::Ref(r) => r.cache_key(),+ Self::NotRef(o) => o.cache_key(),+ }+ }+}++impl CacheKey for Affine {+ fn cache_key(&self) -> u128 {+ let c = self.as_coeffs();+ hash128(&[+ c[0].to_bits(),+ c[1].to_bits(),+ c[2].to_bits(),+ c[3].to_bits(),+ c[4].to_bits(),+ c[5].to_bits(),+ ])+ }+}++impl CacheKey for u128 {+ fn cache_key(&self) -> u128 {+ hash128(self)+ }+}diff --git a/vendor/hayro-interpret/src/color.rs b/vendor/hayro-interpret/src/color.rsnew file mode 100644index 000000000..de3db8046--- /dev/null+++ b/vendor/hayro-interpret/src/color.rs@@ -0,0 +1,1124 @@+//! PDF colors and color spaces.++use crate::cache::{Cache, CacheKey};+use crate::function::Function;+use hayro_syntax::object;+use hayro_syntax::object::Array;+use hayro_syntax::object::Dict;+use hayro_syntax::object::Name;+use hayro_syntax::object::Object;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::*;+use moxcms::{+ ColorProfile, DataColorSpace, Layout, Transform8BitExecutor, TransformF32Executor,+ TransformOptions, Xyzd,+};+use smallvec::{SmallVec, ToSmallVec, smallvec};+use std::borrow::Cow;+use std::fmt::{Debug, Formatter};+use std::ops::Deref;+use std::sync::{Arc, LazyLock, OnceLock};++/// A storage for the components of colors.+pub type ColorComponents = SmallVec<[f32; 4]>;++/// An RGB color with an alpha channel.+#[derive(Debug, Copy, Clone)]+pub struct AlphaColor {+ components: [f32; 4],+}++impl AlphaColor {+ /// A black color.+ pub const BLACK: Self = Self::new([0., 0., 0., 1.]);++ /// A transparent color.+ pub const TRANSPARENT: Self = Self::new([0., 0., 0., 0.]);++ /// A white color.+ pub const WHITE: Self = Self::new([1., 1., 1., 1.]);++ /// Create a new color from the given components.+ pub const fn new(components: [f32; 4]) -> Self {+ Self { components }+ }++ /// Create a new color from RGB8 values.+ pub const fn from_rgb8(r: u8, g: u8, b: u8) -> Self {+ let components = [u8_to_f32(r), u8_to_f32(g), u8_to_f32(b), 1.];+ Self::new(components)+ }++ /// Return the color as premulitplied RGBF32.+ pub fn premultiplied(&self) -> [f32; 4] {+ [+ self.components[0] * self.components[3],+ self.components[1] * self.components[3],+ self.components[2] * self.components[3],+ self.components[3],+ ]+ }++ /// Create a new color from RGBA8 values.+ pub const fn from_rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {+ let components = [u8_to_f32(r), u8_to_f32(g), u8_to_f32(b), u8_to_f32(a)];+ Self::new(components)+ }++ /// Return the color as RGBA8.+ pub fn to_rgba8(&self) -> [u8; 4] {+ [+ (self.components[0] * 255.0 + 0.5) as u8,+ (self.components[1] * 255.0 + 0.5) as u8,+ (self.components[2] * 255.0 + 0.5) as u8,+ (self.components[3] * 255.0 + 0.5) as u8,+ ]+ }++ /// Return the components of the color as RGBF32.+ pub fn components(&self) -> [f32; 4] {+ self.components+ }+}++const fn u8_to_f32(x: u8) -> f32 {+ x as f32 * (1.0 / 255.0)+}++#[derive(Debug, Clone)]+pub(crate) enum ColorSpaceType {+ DeviceCmyk,+ DeviceGray,+ DeviceRgb,+ Pattern(ColorSpace),+ Indexed(Indexed),+ ICCBased(ICCProfile),+ CalGray(CalGray),+ CalRgb(CalRgb),+ Lab(Lab),+ Separation(Separation),+ DeviceN(DeviceN),+}++impl ColorSpaceType {+ fn new(object: Object<'_>, cache: &Cache) -> Option<Self> {+ Self::new_inner(object, cache)+ }++ fn new_inner(object: Object<'_>, cache: &Cache) -> Option<Self> {+ if let Object::Name(name) = object {+ return Self::new_from_name(&name);+ } else if let Object::Array(color_array) = object {+ let mut iter = color_array.flex_iter();+ let name = iter.next::<Name<'_>>()?;++ match name.deref() {+ ICC_BASED => {+ let icc_stream = iter.next::<Stream<'_>>()?;+ let dict = icc_stream.dict();+ let num_components = dict.get::<usize>(N)?;++ return cache.get_or_insert_with(icc_stream.cache_key(), || {+ if let Some(decoded) = icc_stream.decoded().ok().as_ref() {+ ICCProfile::new(decoded, num_components)+ .map(|icc| {+ // TODO: For SVG and PNG we can assume that the output color space is+ // sRGB. If we ever implement PDF-to-PDF, we probably want to+ // let the user pass the native color type and don't make this optimization+ // if it's not sRGB.+ if icc.is_srgb() {+ Self::DeviceRgb+ } else {+ Self::ICCBased(icc)+ }+ })+ .or_else(|| {+ dict.get::<Object<'_>>(ALTERNATE)+ .and_then(|o| Self::new(o, cache))+ })+ .or_else(|| match dict.get::<u8>(N) {+ Some(1) => Some(Self::DeviceGray),+ Some(3) => Some(Self::DeviceRgb),+ Some(4) => Some(Self::DeviceCmyk),+ _ => None,+ })+ } else {+ None+ }+ });+ }+ CALCMYK => return Some(Self::DeviceCmyk),+ CALGRAY => {+ let cal_dict = iter.next::<Dict<'_>>()?;+ return Some(Self::CalGray(CalGray::new(&cal_dict)?));+ }+ CALRGB => {+ let cal_dict = iter.next::<Dict<'_>>()?;+ return Some(Self::CalRgb(CalRgb::new(&cal_dict)?));+ }+ DEVICE_RGB | RGB => return Some(Self::DeviceRgb),+ DEVICE_GRAY | G => return Some(Self::DeviceGray),+ DEVICE_CMYK | CMYK => return Some(Self::DeviceCmyk),+ LAB => {+ let lab_dict = iter.next::<Dict<'_>>()?;+ return Some(Self::Lab(Lab::new(&lab_dict)?));+ }+ INDEXED | I => {+ return Some(Self::Indexed(Indexed::new(&color_array, cache)?));+ }+ SEPARATION => {+ return Some(Self::Separation(Separation::new(&color_array, cache)?));+ }+ DEVICE_N => {+ return Some(Self::DeviceN(DeviceN::new(&color_array, cache)?));+ }+ PATTERN => {+ let _ = iter.next::<Name<'_>>();+ let cs = iter+ .next::<Object<'_>>()+ .and_then(|o| ColorSpace::new(o, cache))+ .unwrap_or(ColorSpace::device_rgb());+ return Some(Self::Pattern(cs));+ }+ _ => {+ warn!("unsupported color space: {}", name.as_str());+ return None;+ }+ }+ }++ None+ }++ fn new_from_name(name: &Name<'_>) -> Option<Self> {+ match name.deref() {+ DEVICE_RGB | RGB => Some(Self::DeviceRgb),+ DEVICE_GRAY | G => Some(Self::DeviceGray),+ DEVICE_CMYK | CMYK => Some(Self::DeviceCmyk),+ CALCMYK => Some(Self::DeviceCmyk),+ PATTERN => Some(Self::Pattern(ColorSpace::device_rgb())),+ _ => None,+ }+ }+}++/// A PDF color space.+#[derive(Debug, Clone)]+pub struct ColorSpace(Arc<ColorSpaceType>);++impl ColorSpace {+ /// Create a new color space from the given object.+ pub(crate) fn new(object: Object<'_>, cache: &Cache) -> Option<Self> {+ Some(Self(Arc::new(ColorSpaceType::new(object, cache)?)))+ }++ /// Create a new color space from the name.+ pub(crate) fn new_from_name(name: &Name<'_>) -> Option<Self> {+ ColorSpaceType::new_from_name(name).map(|c| Self(Arc::new(c)))+ }++ /// Return the device gray color space.+ pub(crate) fn device_gray() -> Self {+ Self(Arc::new(ColorSpaceType::DeviceGray))+ }++ /// Return the device RGB color space.+ pub(crate) fn device_rgb() -> Self {+ Self(Arc::new(ColorSpaceType::DeviceRgb))+ }++ /// Return the device CMYK color space.+ pub(crate) fn device_cmyk() -> Self {+ Self(Arc::new(ColorSpaceType::DeviceCmyk))+ }++ /// Return the pattern color space.+ pub(crate) fn pattern() -> Self {+ Self(Arc::new(ColorSpaceType::Pattern(Self::device_gray())))+ }++ pub(crate) fn pattern_cs(&self) -> Option<Self> {+ match self.0.as_ref() {+ ColorSpaceType::Pattern(cs) => Some(cs.clone()),+ _ => None,+ }+ }++ /// Return `true` if the current color space is the pattern color space.+ pub(crate) fn is_pattern(&self) -> bool {+ matches!(self.0.as_ref(), ColorSpaceType::Pattern(_))+ }++ /// Return `true` if the current color space is an indexed color space.+ pub(crate) fn is_indexed(&self) -> bool {+ matches!(self.0.as_ref(), ColorSpaceType::Indexed(_))+ }++ /// Get the default decode array for the color space.+ pub(crate) fn default_decode_arr(&self, n: f32) -> SmallVec<[(f32, f32); 4]> {+ match self.0.as_ref() {+ ColorSpaceType::DeviceCmyk => smallvec![(0.0, 1.0), (0.0, 1.0), (0.0, 1.0), (0.0, 1.0)],+ ColorSpaceType::DeviceGray => smallvec![(0.0, 1.0)],+ ColorSpaceType::DeviceRgb => smallvec![(0.0, 1.0), (0.0, 1.0), (0.0, 1.0)],+ ColorSpaceType::ICCBased(i) => smallvec![(0.0, 1.0); i.0.number_components],+ ColorSpaceType::CalGray(_) => smallvec![(0.0, 1.0)],+ ColorSpaceType::CalRgb(_) => smallvec![(0.0, 1.0), (0.0, 1.0), (0.0, 1.0)],+ ColorSpaceType::Lab(l) => smallvec![+ (0.0, 100.0),+ (l.range[0], l.range[1]),+ (l.range[2], l.range[3]),+ ],+ ColorSpaceType::Indexed(_) => smallvec![(0.0, 2.0_f32.powf(n) - 1.0)],+ ColorSpaceType::Separation(_) => smallvec![(0.0, 1.0)],+ ColorSpaceType::DeviceN(d) => smallvec![(0.0, 1.0); d.num_components as usize],+ // Not a valid image color space.+ ColorSpaceType::Pattern(_) => smallvec![(0.0, 1.0)],+ }+ }++ pub(crate) fn inverted_default_decode_arr(&self, n: f32) -> SmallVec<[(f32, f32); 4]> {+ self.default_decode_arr(n)+ .iter()+ .map(|(min, max)| (*max, *min))+ .collect()+ }++ /// Get the initial color of the color space.+ pub(crate) fn initial_color(&self) -> ColorComponents {+ match self.0.as_ref() {+ ColorSpaceType::DeviceCmyk => smallvec![0.0, 0.0, 0.0, 1.0],+ ColorSpaceType::DeviceGray => smallvec![0.0],+ ColorSpaceType::DeviceRgb => smallvec![0.0, 0.0, 0.0],+ ColorSpaceType::ICCBased(icc) => match icc.0.number_components {+ 1 => smallvec![0.0],+ 3 => smallvec![0.0, 0.0, 0.0],+ 4 => smallvec![0.0, 0.0, 0.0, 1.0],+ _ => unreachable!(),+ },+ ColorSpaceType::CalGray(_) => smallvec![0.0],+ ColorSpaceType::CalRgb(_) => smallvec![0.0, 0.0, 0.0],+ ColorSpaceType::Lab(_) => smallvec![0.0, 0.0, 0.0],+ ColorSpaceType::Indexed(_) => smallvec![0.0],+ ColorSpaceType::Separation(_) => smallvec![1.0],+ ColorSpaceType::Pattern(c) => c.initial_color(),+ ColorSpaceType::DeviceN(d) => smallvec![1.0; d.num_components as usize],+ }+ }++ pub(crate) fn is_device_gray(&self) -> bool {+ matches!(self.0.as_ref(), ColorSpaceType::DeviceGray)+ }++ /// Get the number of components of the color space.+ pub(crate) fn num_components(&self) -> u8 {+ match self.0.as_ref() {+ ColorSpaceType::DeviceCmyk => 4,+ ColorSpaceType::DeviceGray => 1,+ ColorSpaceType::DeviceRgb => 3,+ ColorSpaceType::ICCBased(icc) => icc.0.number_components as u8,+ ColorSpaceType::CalGray(_) => 1,+ ColorSpaceType::CalRgb(_) => 3,+ ColorSpaceType::Lab(_) => 3,+ ColorSpaceType::Indexed(_) => 1,+ ColorSpaceType::Separation(_) => 1,+ ColorSpaceType::Pattern(p) => p.num_components(),+ ColorSpaceType::DeviceN(d) => d.num_components,+ }+ }++ /// Turn the given component values and opacity into an RGBA color.+ pub fn to_rgba(&self, c: &[f32], opacity: f32, manual_scale: bool) -> AlphaColor {+ self.to_alpha_color(c, opacity, manual_scale)+ .unwrap_or(AlphaColor::BLACK)+ }+}++impl ToRgb for ColorSpace {+ fn convert_f32(&self, input: &[f32], output: &mut [u8], manual_scale: bool) -> Option<()> {+ match self.0.as_ref() {+ ColorSpaceType::DeviceCmyk => {+ if input.len() == 4 {+ let converted = [+ f32_to_u8(input[0]),+ f32_to_u8(input[1]),+ f32_to_u8(input[2]),+ f32_to_u8(input[3]),+ ];+ CMYK_TRANSFORM.convert_u8(&converted, output)+ } else {+ let converted = input.iter().copied().map(f32_to_u8).collect::<Vec<_>>();+ CMYK_TRANSFORM.convert_u8(&converted, output)+ }+ }+ ColorSpaceType::DeviceGray => {+ for (gray, output) in input.iter().zip(output.chunks_exact_mut(3)) {+ let gray = f32_to_u8(*gray);+ output.copy_from_slice(&[gray, gray, gray]);+ }++ Some(())+ }+ ColorSpaceType::DeviceRgb => {+ for (input, output) in input.iter().copied().zip(output) {+ *output = f32_to_u8(input);+ }++ Some(())+ }+ ColorSpaceType::Pattern(i) => i.convert_f32(input, output, manual_scale),+ ColorSpaceType::Indexed(i) => i.convert_f32(input, output, manual_scale),+ ColorSpaceType::ICCBased(i) => i.convert_f32(input, output, manual_scale),+ ColorSpaceType::CalGray(i) => i.convert_f32(input, output, manual_scale),+ ColorSpaceType::CalRgb(i) => i.convert_f32(input, output, manual_scale),+ ColorSpaceType::Lab(i) => i.convert_f32(input, output, manual_scale),+ ColorSpaceType::Separation(i) => i.convert_f32(input, output, manual_scale),+ ColorSpaceType::DeviceN(i) => i.convert_f32(input, output, manual_scale),+ }+ }++ fn supports_u8(&self) -> bool {+ match self.0.as_ref() {+ ColorSpaceType::DeviceCmyk => true,+ ColorSpaceType::DeviceGray => true,+ ColorSpaceType::DeviceRgb => true,+ ColorSpaceType::Pattern(i) => i.supports_u8(),+ ColorSpaceType::Indexed(i) => i.supports_u8(),+ ColorSpaceType::ICCBased(i) => i.supports_u8(),+ ColorSpaceType::CalGray(i) => i.supports_u8(),+ ColorSpaceType::CalRgb(i) => i.supports_u8(),+ ColorSpaceType::Lab(i) => i.supports_u8(),+ ColorSpaceType::Separation(i) => i.supports_u8(),+ ColorSpaceType::DeviceN(i) => i.supports_u8(),+ }+ }++ fn convert_u8(&self, input: &[u8], output: &mut [u8]) -> Option<()> {+ match self.0.as_ref() {+ ColorSpaceType::DeviceCmyk => CMYK_TRANSFORM.convert_u8(input, output),+ ColorSpaceType::DeviceGray => {+ for (input, output) in input.iter().zip(output.chunks_exact_mut(3)) {+ output.copy_from_slice(&[*input, *input, *input]);+ }++ Some(())+ }+ ColorSpaceType::DeviceRgb => {+ for (input, output) in input.iter().zip(output.iter_mut()) {+ *output = *input;+ }++ Some(())+ }+ ColorSpaceType::Pattern(i) => i.convert_u8(input, output),+ ColorSpaceType::Indexed(i) => i.convert_u8(input, output),+ ColorSpaceType::ICCBased(i) => i.convert_u8(input, output),+ ColorSpaceType::CalGray(i) => i.convert_u8(input, output),+ ColorSpaceType::CalRgb(i) => i.convert_u8(input, output),+ ColorSpaceType::Lab(i) => i.convert_u8(input, output),+ ColorSpaceType::Separation(i) => i.convert_u8(input, output),+ ColorSpaceType::DeviceN(i) => i.convert_u8(input, output),+ }+ }++ fn is_none(&self) -> bool {+ match self.0.as_ref() {+ ColorSpaceType::Separation(s) => s.is_none(),+ ColorSpaceType::DeviceN(d) => d.is_none(),+ _ => false,+ }+ }+}++#[derive(Debug, Clone)]+pub(crate) struct CalGray {+ white_point: [f32; 3],+ black_point: [f32; 3],+ gamma: f32,+}++// See <https://github.com/mozilla/pdf.js/blob/06f44916c8936b92f464d337fe3a0a6b2b78d5b4/src/core/colorspace.js#L752>+impl CalGray {+ fn new(dict: &Dict<'_>) -> Option<Self> {+ let white_point = dict.get::<[f32; 3]>(WHITE_POINT).unwrap_or([1.0, 1.0, 1.0]);+ let black_point = dict.get::<[f32; 3]>(BLACK_POINT).unwrap_or([0.0, 0.0, 0.0]);+ let gamma = dict.get::<f32>(GAMMA).unwrap_or(1.0);++ Some(Self {+ white_point,+ black_point,+ gamma,+ })+ }+}++impl ToRgb for CalGray {+ fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {+ for (input, output) in input.iter().copied().zip(output.chunks_exact_mut(3)) {+ let g = self.gamma;+ let (_xw, yw, _zw) = {+ let wp = self.white_point;+ (wp[0], wp[1], wp[2])+ };+ let (_xb, _yb, _zb) = {+ let bp = self.black_point;+ (bp[0], bp[1], bp[2])+ };++ let a = input;+ let ag = a.powf(g);+ let l = yw * ag;+ let val = (0.0_f32.max(295.8 * l.powf(0.333_333_34) - 40.8) + 0.5) as u8;++ output.copy_from_slice(&[val, val, val]);+ }++ Some(())+ }+}++#[derive(Debug, Clone)]+pub(crate) struct CalRgb {+ white_point: [f32; 3],+ black_point: [f32; 3],+ matrix: [f32; 9],+ gamma: [f32; 3],+}++// See <https://github.com/mozilla/pdf.js/blob/06f44916c8936b92f464d337fe3a0a6b2b78d5b4/src/core/colorspace.js#L846>+// Completely copied from there without really understanding the logic, but we get the same results as Firefox+// which should be good enough (and by viewing the `calrgb.pdf` test file in different viewers you will+// see that in many cases each viewer does whatever it wants, even Acrobat), so this is good enough for us.+impl CalRgb {+ fn new(dict: &Dict<'_>) -> Option<Self> {+ let white_point = dict.get::<[f32; 3]>(WHITE_POINT).unwrap_or([1.0, 1.0, 1.0]);+ let black_point = dict.get::<[f32; 3]>(BLACK_POINT).unwrap_or([0.0, 0.0, 0.0]);+ let matrix = dict+ .get::<[f32; 9]>(MATRIX)+ .unwrap_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);+ let gamma = dict.get::<[f32; 3]>(GAMMA).unwrap_or([1.0, 1.0, 1.0]);++ Some(Self {+ white_point,+ black_point,+ matrix,+ gamma,+ })+ }++ const BRADFORD_SCALE_MATRIX: [f32; 9] = [+ 0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296,+ ];++ const BRADFORD_SCALE_INVERSE_MATRIX: [f32; 9] = [+ 0.9869929, -0.1470543, 0.1599627, 0.4323053, 0.5183603, 0.0492912, -0.0085287, 0.0400428,+ 0.9684867,+ ];++ const SRGB_D65_XYZ_TO_RGB_MATRIX: [f32; 9] = [+ 3.2404542, -1.5371385, -0.4985314, -0.969_266, 1.8760108, 0.0415560, 0.0556434, -0.2040259,+ 1.0572252,+ ];++ const FLAT_WHITEPOINT: [f32; 3] = [1.0, 1.0, 1.0];+ const D65_WHITEPOINT: [f32; 3] = [0.95047, 1.0, 1.08883];++ fn decode_l_constant() -> f32 {+ ((8.0_f32 + 16.0) / 116.0).powi(3) / 8.0+ }++ fn srgb_transfer_function(color: f32) -> f32 {+ if color <= 0.0031308 {+ (12.92 * color).clamp(0.0, 1.0)+ } else if color >= 0.99554525 {+ 1.0+ } else {+ ((1.0 + 0.055) * color.powf(1.0 / 2.4) - 0.055).clamp(0.0, 1.0)+ }+ }++ fn matrix_product(a: &[f32; 9], b: &[f32; 3]) -> [f32; 3] {+ [+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2],+ a[3] * b[0] + a[4] * b[1] + a[5] * b[2],+ a[6] * b[0] + a[7] * b[1] + a[8] * b[2],+ ]+ }++ fn to_flat(source_white_point: &[f32; 3], lms: &[f32; 3]) -> [f32; 3] {+ [+ lms[0] / source_white_point[0],+ lms[1] / source_white_point[1],+ lms[2] / source_white_point[2],+ ]+ }++ fn to_d65(source_white_point: &[f32; 3], lms: &[f32; 3]) -> [f32; 3] {+ [+ lms[0] * Self::D65_WHITEPOINT[0] / source_white_point[0],+ lms[1] * Self::D65_WHITEPOINT[1] / source_white_point[1],+ lms[2] * Self::D65_WHITEPOINT[2] / source_white_point[2],+ ]+ }++ fn decode_l(l: f32) -> f32 {+ if l < 0.0 {+ -Self::decode_l(-l)+ } else if l > 8.0 {+ ((l + 16.0) / 116.0).powi(3)+ } else {+ l * Self::decode_l_constant()+ }+ }++ fn compensate_black_point(source_bp: &[f32; 3], xyz_flat: &[f32; 3]) -> [f32; 3] {+ if source_bp == &[0.0, 0.0, 0.0] {+ return *xyz_flat;+ }++ let zero_decode_l = Self::decode_l(0.0);++ let mut out = [0.0; 3];+ for i in 0..3 {+ let src = Self::decode_l(source_bp[i]);+ let scale = (1.0 - zero_decode_l) / (1.0 - src);+ let offset = 1.0 - scale;+ out[i] = xyz_flat[i] * scale + offset;+ }++ out+ }++ fn normalize_white_point_to_flat(+ &self,+ source_white_point: &[f32; 3],+ xyz: &[f32; 3],+ ) -> [f32; 3] {+ if source_white_point[0] == 1.0 && source_white_point[2] == 1.0 {+ return *xyz;+ }+ let lms = Self::matrix_product(&Self::BRADFORD_SCALE_MATRIX, xyz);+ let lms_flat = Self::to_flat(source_white_point, &lms);+ Self::matrix_product(&Self::BRADFORD_SCALE_INVERSE_MATRIX, &lms_flat)+ }++ fn normalize_white_point_to_d65(+ &self,+ source_white_point: &[f32; 3],+ xyz: &[f32; 3],+ ) -> [f32; 3] {+ let lms = Self::matrix_product(&Self::BRADFORD_SCALE_MATRIX, xyz);+ let lms_d65 = Self::to_d65(source_white_point, &lms);+ Self::matrix_product(&Self::BRADFORD_SCALE_INVERSE_MATRIX, &lms_d65)+ }+}++impl ToRgb for CalRgb {+ fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {+ for (input, output) in input.chunks_exact(3).zip(output.chunks_exact_mut(3)) {+ let input = [+ input[0].clamp(0.0, 1.0),+ input[1].clamp(0.0, 1.0),+ input[2].clamp(0.0, 1.0),+ ];++ let [r, g, b] = input;+ let [gr, gg, gb] = self.gamma;+ let [agr, bgg, cgb] = [+ if r == 1.0 { 1.0 } else { r.powf(gr) },+ if g == 1.0 { 1.0 } else { g.powf(gg) },+ if b == 1.0 { 1.0 } else { b.powf(gb) },+ ];++ let m = &self.matrix;+ let x = m[0] * agr + m[3] * bgg + m[6] * cgb;+ let y = m[1] * agr + m[4] * bgg + m[7] * cgb;+ let z = m[2] * agr + m[5] * bgg + m[8] * cgb;+ let xyz = [x, y, z];++ let xyz_flat = self.normalize_white_point_to_flat(&self.white_point, &xyz);+ let xyz_black = Self::compensate_black_point(&self.black_point, &xyz_flat);+ let xyz_d65 = self.normalize_white_point_to_d65(&Self::FLAT_WHITEPOINT, &xyz_black);+ let srgb_xyz = Self::matrix_product(&Self::SRGB_D65_XYZ_TO_RGB_MATRIX, &xyz_d65);++ output.copy_from_slice(&[+ (Self::srgb_transfer_function(srgb_xyz[0]) * 255.0 + 0.5) as u8,+ (Self::srgb_transfer_function(srgb_xyz[1]) * 255.0 + 0.5) as u8,+ (Self::srgb_transfer_function(srgb_xyz[2]) * 255.0 + 0.5) as u8,+ ]);+ }++ Some(())+ }+}++#[derive(Debug, Clone)]+pub(crate) struct Lab {+ range: [f32; 4],+ profile: ICCProfile,+}++impl Lab {+ fn new(dict: &Dict<'_>) -> Option<Self> {+ let white_point = dict.get::<[f32; 3]>(WHITE_POINT).unwrap_or([1.0, 1.0, 1.0]);+ // Not sure how this should be used.+ let _black_point = dict.get::<[f32; 3]>(BLACK_POINT).unwrap_or([0.0, 0.0, 0.0]);+ let range = dict+ .get::<[f32; 4]>(RANGE)+ .unwrap_or([-100.0, 100.0, -100.0, 100.0]);++ let mut profile = ColorProfile::new_from_slice(include_bytes!("../assets/LAB.icc")).ok()?;+ profile.white_point = Xyzd::new(+ white_point[0] as f64,+ white_point[1] as f64,+ white_point[2] as f64,+ );++ let profile = ICCProfile::new_from_src_profile(+ profile, false,+ // This flag is only used to scale the values to [0.0, 1.0], but+ // we already take care of this in the `convert_f32` method.+ // Therefore, leave this as false, even though this is a LAB profile.+ false, 3,+ )?;++ Some(Self { range, profile })+ }+}++impl ToRgb for Lab {+ fn convert_f32(&self, input: &[f32], output: &mut [u8], manual_scale: bool) -> Option<()> {+ if !manual_scale {+ // moxcms expects values between 0.0 and 1.0, so we need to undo+ // the scaling.++ let input = input+ .chunks_exact(3)+ .flat_map(|i| {+ let l = i[0] / 100.0;+ let a = (i[1] + 128.0) / 255.0;+ let b = (i[2] + 128.0) / 255.0;++ [l, a, b]+ })+ .collect::<Vec<_>>();++ self.profile.convert_f32(&input, output, manual_scale)+ } else {+ self.profile.convert_f32(input, output, manual_scale)+ }+ }+}++#[derive(Debug, Clone)]+pub(crate) struct Indexed {+ values: Vec<Vec<f32>>,+ hival: u8,+ base: Box<ColorSpace>,+}++impl Indexed {+ fn new(array: &Array<'_>, cache: &Cache) -> Option<Self> {+ let mut iter = array.flex_iter();+ // Skip name+ let _ = iter.next::<Name<'_>>()?;+ let base_color_space = ColorSpace::new(iter.next::<Object<'_>>()?, cache)?;+ let hival = iter.next::<u32>()?.min(u8::MAX as u32) as u8;++ let values = {+ let data = iter+ .next::<Stream<'_>>()+ .and_then(|s| s.decoded().ok())+ .or_else(|| {+ iter.next::<object::String<'_>>()+ .map(|s| Cow::Owned(s.to_vec()))+ })?;++ let num_components = base_color_space.num_components();++ let mut byte_iter = data.iter().copied();++ let mut vals = vec![];+ for _ in 0..=hival {+ let mut temp = vec![];++ for _ in 0..num_components {+ temp.push(byte_iter.next()? as f32 / 255.0);+ }++ vals.push(temp);+ }++ vals+ };++ Some(Self {+ values,+ hival,+ base: Box::new(base_color_space),+ })+ }+}++impl ToRgb for Indexed {+ fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {+ let mut indexed = vec![0.0; input.len() * self.base.num_components() as usize];++ for (input, output) in input+ .iter()+ .copied()+ .zip(indexed.chunks_exact_mut(self.base.num_components() as usize))+ {+ let idx = (input.clamp(0.0, self.hival as f32) + 0.5) as usize;+ output.copy_from_slice(&self.values[idx]);+ }++ self.base.convert_f32(&indexed, output, true)+ }+}++#[derive(Debug, Clone)]+pub(crate) struct Separation {+ alternate_space: ColorSpace,+ tint_transform: Function,+ is_none_separation: bool,+}++impl Separation {+ fn new(array: &Array<'_>, cache: &Cache) -> Option<Self> {+ let mut iter = array.flex_iter();+ // Skip `/Separation`+ let _ = iter.next::<Name<'_>>()?;+ let name = iter.next::<Name<'_>>()?;+ let alternate_space = ColorSpace::new(iter.next::<Object<'_>>()?, cache)?;+ let tint_transform = Function::new(&iter.next::<Object<'_>>()?)?;+ // Either I did something wrong, or no other viewers properly handles+ // `All`, so let's just ignore it as well.+ let is_none_separation = name.as_str() == "None";++ Some(Self {+ alternate_space,+ tint_transform,+ is_none_separation,+ })+ }+}++impl ToRgb for Separation {+ fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {+ let evaluated = input+ .iter()+ .flat_map(|n| {+ self.tint_transform+ .eval(smallvec![*n])+ .unwrap_or(self.alternate_space.initial_color())+ })+ .collect::<Vec<_>>();+ self.alternate_space.convert_f32(&evaluated, output, false)+ }++ fn is_none(&self) -> bool {+ self.is_none_separation+ }+}++#[derive(Debug, Clone)]+pub(crate) struct DeviceN {+ alternate_space: ColorSpace,+ num_components: u8,+ tint_transform: Function,+ is_none: bool,+}++impl DeviceN {+ fn new(array: &Array<'_>, cache: &Cache) -> Option<Self> {+ let mut iter = array.flex_iter();+ // Skip `/DeviceN`+ let _ = iter.next::<Name<'_>>()?;+ // Skip `Name`.+ let names = iter+ .next::<Array<'_>>()?+ .iter::<Name<'_>>()+ .collect::<Vec<_>>();+ let num_components = u8::try_from(names.len()).ok()?;+ let all_none = names.iter().all(|n| n.as_str() == "None");+ let alternate_space = ColorSpace::new(iter.next::<Object<'_>>()?, cache)?;+ let tint_transform = Function::new(&iter.next::<Object<'_>>()?)?;++ if num_components == 0 {+ return None;+ }++ Some(Self {+ alternate_space,+ num_components,+ tint_transform,+ is_none: all_none,+ })+ }+}++impl ToRgb for DeviceN {+ fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {+ let evaluated = input+ .chunks_exact(self.num_components as usize)+ .flat_map(|n| {+ self.tint_transform+ .eval(n.to_smallvec())+ .unwrap_or(self.alternate_space.initial_color())+ })+ .collect::<Vec<_>>();+ self.alternate_space.convert_f32(&evaluated, output, false)+ }++ fn is_none(&self) -> bool {+ self.is_none+ }+}++struct ICCColorRepr {+ src_profile: ColorProfile,+ src_layout: Layout,+ number_components: usize,+ is_srgb: bool,+ is_lab: bool,+ transform_u8: Arc<Transform8BitExecutor>,+ transform_f32: OnceLock<Arc<TransformF32Executor>>,+}++#[derive(Clone)]+pub(crate) struct ICCProfile(Arc<ICCColorRepr>);++impl Debug for ICCProfile {+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {+ write!(f, "ICCColor {{..}}")+ }+}++impl ICCProfile {+ fn new(profile: &[u8], number_components: usize) -> Option<Self> {+ let src_profile = ColorProfile::new_from_slice(profile).ok()?;++ const SRGB_MARKER: &[u8] = b"sRGB";++ let is_srgb = profile+ .get(52..56)+ .map(|device_model| device_model == SRGB_MARKER)+ .unwrap_or(false);+ let is_lab = src_profile.color_space == DataColorSpace::Lab;++ Self::new_from_src_profile(src_profile, is_srgb, is_lab, number_components)+ }++ fn new_from_src_profile(+ src_profile: ColorProfile,+ is_srgb: bool,+ is_lab: bool,+ number_components: usize,+ ) -> Option<Self> {+ let src_layout = match number_components {+ 1 => Layout::Gray,+ 3 => Layout::Rgb,+ 4 => Layout::Rgba,+ _ => {+ warn!("unsupported number of components {number_components} for ICC profile");++ return None;+ }+ };++ let dest_profile = ColorProfile::new_srgb();+ let transform_u8 = src_profile+ .clone()+ .create_transform_8bit(+ src_layout,+ &dest_profile,+ Layout::Rgb,+ TransformOptions::default(),+ )+ .ok()?;++ Some(Self(Arc::new(ICCColorRepr {+ src_profile,+ src_layout,+ number_components,+ is_srgb,+ is_lab,+ transform_u8,+ transform_f32: OnceLock::new(),+ })))+ }++ fn is_srgb(&self) -> bool {+ self.0.is_srgb+ }++ fn is_lab(&self) -> bool {+ self.0.is_lab+ }++ fn transform_u8(&self) -> &Arc<Transform8BitExecutor> {+ &self.0.transform_u8+ }++ fn transform_f32(&self) -> &Arc<TransformF32Executor> {+ // From my benchmarking, creating the f32 transforms is usually much+ // more expensive than u8. Therefore, we only create it lazily when+ // really needed.+ self.0.transform_f32.get_or_init(|| {+ let dest_profile = ColorProfile::new_srgb();+ self.0+ .src_profile+ .clone()+ .create_transform_f32(+ self.0.src_layout,+ &dest_profile,+ Layout::Rgb,+ TransformOptions::default(),+ )+ // Since the u8 version was valid, hopefully this should never panic?+ .unwrap()+ })+ }+}++impl ToRgb for ICCProfile {+ fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {+ let mut temp = vec![0.0_f32; output.len()];++ if self.is_lab() {+ // moxcms expects normalized values.+ let scaled = input+ .chunks_exact(3)+ .flat_map(|i| {+ [+ i[0] * (1.0 / 100.0),+ (i[1] + 128.0) * (1.0 / 255.0),+ (i[2] + 128.0) * (1.0 / 255.0),+ ]+ })+ .collect::<Vec<_>>();+ self.transform_f32().transform(&scaled, &mut temp).ok()?;+ } else {+ self.transform_f32().transform(input, &mut temp).ok()?;+ };++ for (input, output) in temp.iter().zip(output.iter_mut()) {+ *output = (input * 255.0 + 0.5) as u8;+ }++ Some(())+ }++ fn supports_u8(&self) -> bool {+ true+ }++ fn convert_u8(&self, input: &[u8], output: &mut [u8]) -> Option<()> {+ if self.is_srgb() {+ output.copy_from_slice(input);+ } else {+ self.transform_u8().transform(input, output).ok()?;+ }++ Some(())+ }+}++#[inline(always)]+fn f32_to_u8(val: f32) -> u8 {+ (val * 255.0 + 0.5) as u8+}++#[derive(Debug, Clone)]+/// A color.+pub struct Color {+ color_space: ColorSpace,+ components: ColorComponents,+ opacity: f32,+}++impl Color {+ pub(crate) fn new(color_space: ColorSpace, components: ColorComponents, opacity: f32) -> Self {+ Self {+ color_space,+ components,+ opacity,+ }+ }++ /// Return the color as an RGBA color.+ pub fn to_rgba(&self) -> AlphaColor {+ self.color_space+ .to_rgba(&self.components, self.opacity, false)+ }++ /// Create a color from RGBA.+ pub fn from_rgba(rgba: AlphaColor) -> Self {+ let c = rgba.components();+ Self {+ color_space: ColorSpace::device_rgb(),+ components: smallvec![c[0], c[1], c[2]],+ opacity: c[3],+ }+ }+}++static CMYK_TRANSFORM: LazyLock<ICCProfile> = LazyLock::new(|| {+ ICCProfile::new(include_bytes!("../assets/CGATS001Compat-v2-micro.icc"), 4).unwrap()+});++pub(crate) trait ToRgb {+ fn convert_sample(&self, input: &[f32], output: &mut [u8], manual_scale: bool) -> Option<()> {+ // We prefer using the u8 variant for single samples, which is especially+ // important for ICC profiles to avoid constructing the (more expensive)+ // f32 variant.+ if self.supports_u8() {+ let converted = input+ .iter()+ .copied()+ .map(f32_to_u8)+ .collect::<SmallVec<[u8; 4]>>();++ if self.convert_u8(&converted, output).is_some() {+ return Some(());+ }+ }++ self.convert_f32(input, output, manual_scale)+ }++ fn convert_f32(&self, input: &[f32], output: &mut [u8], manual_scale: bool) -> Option<()>;+ fn supports_u8(&self) -> bool {+ false+ }+ fn convert_u8(&self, _: &[u8], _: &mut [u8]) -> Option<()> {+ unimplemented!();+ }+ fn is_none(&self) -> bool {+ false+ }+ fn to_alpha_color(+ &self,+ input: &[f32],+ mut opacity: f32,+ manual_scale: bool,+ ) -> Option<AlphaColor> {+ let mut output = [0; 3];+ self.convert_sample(input, &mut output, manual_scale)?;++ // For separation color spaces:+ // "The special colourant name None shall not produce any visible output.+ // Painting operations in a Separation space with this colourant name+ // shall have no effect on the current page."+ if self.is_none() {+ opacity = 0.0;+ }++ Some(AlphaColor::from_rgba8(+ output[0],+ output[1],+ output[2],+ (opacity * 255.0 + 0.5) as u8,+ ))+ }+}diff --git a/vendor/hayro-interpret/src/context.rs b/vendor/hayro-interpret/src/context.rsnew file mode 100644index 000000000..64073571f--- /dev/null+++ b/vendor/hayro-interpret/src/context.rs@@ -0,0 +1,373 @@+use crate::cache::{Cache, CacheKey};+use crate::color::ColorSpace;+use crate::convert::convert_transform;+use crate::font::{Font, StandardFont};+use crate::interpret::state::{ClipType, State, TextStateFont};+use crate::ocg::OcgState;+use crate::util::{BezPathExt, Float64Ext};+use crate::{ClipPath, Device, FillRule, InterpreterSettings, StrokeProps};+use hayro_syntax::content::ops::Transform;+use hayro_syntax::object::Dict;+use hayro_syntax::object::Name;+use hayro_syntax::page::Resources;+use hayro_syntax::xref::XRef;+use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape};+use std::cell::RefCell;+use std::collections::HashMap;+use std::rc::Rc;++/// Maximum nesting depth for interpreting `XObject`'s/patterns/streams.+pub(crate) const MAX_NESTED_INTERPRETATION_DEPTH: u32 = 50;++/// A cache used by the interpreter.+///+/// Ideally, such a cache should be constructed once per PDF and then reused across+/// multiple interpreter invocations on the same document.+#[derive(Clone)]+pub struct InterpreterCache<'a> {+ pub(crate) font_cache: Rc<RefCell<HashMap<u128, Option<Font<'a>>>>>,+ pub(crate) object_cache: Cache,+}++impl<'a> Default for InterpreterCache<'a> {+ fn default() -> Self {+ Self::new()+ }+}++impl<'a> InterpreterCache<'a> {+ /// Create a new interpreter cache.+ pub fn new() -> Self {+ Self {+ font_cache: Rc::new(RefCell::new(HashMap::new())),+ object_cache: Cache::new(),+ }+ }+}++/// A per-page interpretation context that borrows shared data from an [`InterpreterCache`].+pub struct Context<'a> {+ states: Vec<State<'a>>,+ path: BezPath,+ sub_path_start: Point,+ last_point: Point,+ clip: Option<FillRule>,+ root_transforms: Vec<Affine>,+ bbox: Vec<Rect>,+ pub(crate) settings: InterpreterSettings,+ pub(crate) interpreter_cache: InterpreterCache<'a>,+ pub(crate) xref: &'a XRef,+ pub(crate) ocg_state: OcgState,+ nesting_depth: u32,+}++impl<'a> Context<'a> {+ /// Create a new context.+ pub fn new(+ initial_transform: Affine,+ bbox: Rect,+ cache: &InterpreterCache<'a>,+ xref: &'a XRef,+ settings: InterpreterSettings,+ ) -> Self {+ let state = State::new(initial_transform);++ Self::new_with(initial_transform, bbox, cache, xref, settings, state, 0)+ }++ pub(crate) fn new_with(+ initial_transform: Affine,+ bbox: Rect,+ cache: &InterpreterCache<'a>,+ xref: &'a XRef,+ settings: InterpreterSettings,+ state: State<'a>,+ nesting_depth: u32,+ ) -> Self {+ let mut ocg_state = {+ let root_ref = xref.root_id();+ xref.get::<Dict<'_>>(root_ref)+ .map(|catalog| OcgState::from_catalog(&catalog))+ .unwrap_or_default()+ };+ // PrintCraft patch: apply viewer layer toggles.+ for (num, generation, visible) in settings.ocg_overrides.iter() {+ ocg_state.set_active(hayro_syntax::object::ObjectIdentifier::new(*num, *generation), *visible);+ }++ Self {+ states: vec![state],+ settings,+ xref,+ root_transforms: vec![initial_transform],+ last_point: Point::default(),+ sub_path_start: Point::default(),+ clip: None,+ bbox: vec![bbox],+ path: BezPath::new(),+ interpreter_cache: cache.clone(),+ ocg_state,+ nesting_depth,+ }+ }++ pub(crate) fn save_state(&mut self) {+ let Some(cur) = self.states.last().cloned() else {+ warn!("attempted to save state without existing state");+ return;+ };++ self.states.push(cur);+ }++ pub(crate) fn bbox(&self) -> Rect {+ self.bbox.last().copied().unwrap_or_else(|| {+ warn!("failed to get a bbox");++ Rect::new(0.0, 0.0, 1.0, 1.0)+ })+ }++ fn push_bbox(&mut self, bbox: Rect) {+ let new = self.bbox().intersect(bbox);+ self.bbox.push(new);+ }++ pub(crate) fn push_clip_path(+ &mut self,+ clip_path: BezPath,+ fill: FillRule,+ device: &mut impl Device<'a>,+ ) {+ if let Some(clip_rect) = path_as_rect(&clip_path) {+ let cur_bbox = self.bbox();++ // If the clip path is a rect and completely covers the current bbox, don't emit it.+ if cur_bbox+ .min_x()+ .is_nearly_greater_or_equal(clip_rect.min_x())+ && cur_bbox+ .min_y()+ .is_nearly_greater_or_equal(clip_rect.min_y())+ && cur_bbox.max_x().is_nearly_less_or_equal(clip_rect.max_x())+ && cur_bbox.max_y().is_nearly_less_or_equal(clip_rect.max_y())+ {+ self.get_mut().clips.push(ClipType::Dummy);+ return;+ }+ }++ let bbox = clip_path.bounding_box();+ device.push_clip_path(&ClipPath {+ path: clip_path,+ fill,+ });+ self.push_bbox(bbox);+ self.get_mut().clips.push(ClipType::Real);+ }++ pub(crate) fn pop_clip_path(&mut self, device: &mut impl Device<'a>) {+ if let Some(ClipType::Real) = self.get_mut().clips.pop() {+ device.pop_clip_path();+ self.pop_bbox();+ }+ }++ fn pop_bbox(&mut self) {+ self.bbox.pop();+ }++ pub(crate) fn push_root_transform(&mut self) {+ self.root_transforms.push(self.get().ctm);+ }++ pub(crate) fn pop_root_transform(&mut self) {+ self.root_transforms.pop();+ }++ pub(crate) fn root_transform(&self) -> Affine {+ self.root_transforms+ .last()+ .copied()+ .unwrap_or(Affine::IDENTITY)+ }++ pub(crate) fn restore_state(&mut self, device: &mut impl Device<'a>) {+ let Some(target_clips) = self+ .states+ .get(self.states.len().saturating_sub(2))+ .map(|s| s.clips.len())+ else {+ warn!("underflowed graphics state");+ return;+ };++ while self.get().clips.len() > target_clips {+ self.pop_clip_path(device);+ }++ // The first state should never be popped.+ if self.states.len() > 1 {+ self.states.pop();+ }++ device.set_soft_mask(+ self.states+ .last()+ .and_then(|l| l.graphics_state.soft_mask.clone()),+ );+ }++ pub(crate) fn path(&self) -> &BezPath {+ &self.path+ }++ pub(crate) fn path_mut(&mut self) -> &mut BezPath {+ &mut self.path+ }++ pub(crate) fn sub_path_start(&self) -> &Point {+ &self.sub_path_start+ }++ pub(crate) fn sub_path_start_mut(&mut self) -> &mut Point {+ &mut self.sub_path_start+ }++ pub(crate) fn last_point(&self) -> &Point {+ &self.last_point+ }++ pub(crate) fn last_point_mut(&mut self) -> &mut Point {+ &mut self.last_point+ }++ pub(crate) fn clip(&self) -> &Option<FillRule> {+ &self.clip+ }++ pub(crate) fn clip_mut(&mut self) -> &mut Option<FillRule> {+ &mut self.clip+ }++ pub(crate) fn get(&self) -> &State<'a> {+ self.states.last().unwrap()+ }++ pub(crate) fn get_mut(&mut self) -> &mut State<'a> {+ self.states.last_mut().unwrap()+ }++ pub(crate) fn pre_concat_transform(&mut self, transform: Transform) {+ self.pre_concat_affine(convert_transform(transform));+ }++ pub(crate) fn pre_concat_affine(&mut self, transform: Affine) {+ self.get_mut().ctm *= transform;+ }++ pub(crate) fn get_color_space(+ &mut self,+ resources: &Resources<'_>,+ name: &Name<'_>,+ ) -> Option<ColorSpace> {+ let cs_object = resources.get_color_space(name)?;+ self.interpreter_cache+ .object_cache+ .get_or_insert_with(cs_object.cache_key(), || {+ ColorSpace::new(cs_object.clone(), &self.interpreter_cache.object_cache)+ })+ }++ pub(crate) fn stroke_props(&self) -> StrokeProps {+ self.get().graphics_state.stroke_props.clone()+ }++ pub(crate) fn num_states(&self) -> usize {+ self.states.len()+ }++ pub(crate) fn nesting_depth(&self) -> u32 {+ self.nesting_depth+ }++ pub(crate) fn begin_nested_interpretation(&mut self) -> bool {+ if self.nesting_depth >= MAX_NESTED_INTERPRETATION_DEPTH {+ warn!("interpreter nesting depth exceeded");++ return false;+ }++ self.nesting_depth += 1;++ true+ }++ pub(crate) fn end_nested_interpretation(&mut self) {+ self.nesting_depth = self.nesting_depth.saturating_sub(1);+ }+ pub(crate) fn resolve_font(&mut self, font_dict: &Dict<'a>) -> Option<TextStateFont<'a>> {+ let cache_key = font_dict.cache_key();++ let resolved = {+ let mut font_cache = self.interpreter_cache.font_cache.borrow_mut();+ font_cache+ .entry(cache_key)+ .or_insert_with(|| {+ Font::new(+ font_dict,+ &self.settings.font_resolver,+ &self.settings.cmap_resolver,+ )+ })+ .clone()+ };++ if let Some(resolved) = resolved {+ Some(TextStateFont::Font(resolved))+ } else {+ Font::new_standard(StandardFont::Helvetica, &self.settings.font_resolver)+ .map(TextStateFont::Fallback)+ }+ }+}++pub(crate) fn path_as_rect(path: &BezPath) -> Option<Rect> {+ // One MoveTo, three LineTo, one ClosePath+ if path.elements().len() != 5 {+ return None;+ }++ let bbox = path.fast_bounding_box();+ let (min_x, min_y, max_x, max_y) = (bbox.min_x(), bbox.min_y(), bbox.max_x(), bbox.max_y());+ let mut corners = [false; 4];++ let mut check_point = |p: Point| {+ corners[0] |= p.x.is_nearly_equal(min_x) && p.y.is_nearly_equal(min_y);+ corners[1] |= p.x.is_nearly_equal(min_x) && p.y.is_nearly_equal(max_y);+ corners[2] |= p.x.is_nearly_equal(max_x) && p.y.is_nearly_equal(min_y);+ corners[3] |= p.x.is_nearly_equal(max_x) && p.y.is_nearly_equal(max_y);+ };++ for (idx, el) in path.elements().iter().enumerate() {+ match el {+ PathEl::MoveTo(p) => {+ if idx != 0 {+ return None;+ }++ check_point(*p);+ }+ PathEl::LineTo(l) => check_point(*l),+ PathEl::QuadTo(_, _) => return None,+ PathEl::CurveTo(_, _, _) => return None,+ PathEl::ClosePath => {}+ }+ }++ if corners[0] && corners[1] && corners[2] && corners[3] {+ Some(bbox)+ } else {+ None+ }+}diff --git a/vendor/hayro-interpret/src/convert.rs b/vendor/hayro-interpret/src/convert.rsnew file mode 100644index 000000000..e76891141--- /dev/null+++ b/vendor/hayro-interpret/src/convert.rs@@ -0,0 +1,30 @@+use hayro_syntax::content::ops::{LineCap, LineJoin, Transform};++pub(crate) fn convert_transform(t: Transform) -> kurbo::Affine {+ kurbo::Affine::new([+ t.0.as_f64(),+ t.1.as_f64(),+ t.2.as_f64(),+ t.3.as_f64(),+ t.4.as_f64(),+ t.5.as_f64(),+ ])+}++pub(crate) fn convert_line_cap(lc: LineCap) -> kurbo::Cap {+ match lc.0.as_i64() {+ 0 => kurbo::Cap::Butt,+ 1 => kurbo::Cap::Round,+ 2 => kurbo::Cap::Square,+ _ => kurbo::Cap::Butt,+ }+}++pub(crate) fn convert_line_join(lc: LineJoin) -> kurbo::Join {+ match lc.0.as_i64() {+ 0 => kurbo::Join::Miter,+ 1 => kurbo::Join::Round,+ 2 => kurbo::Join::Bevel,+ _ => kurbo::Join::Miter,+ }+}diff --git a/vendor/hayro-interpret/src/device.rs b/vendor/hayro-interpret/src/device.rsnew file mode 100644index 000000000..8b511ca49--- /dev/null+++ b/vendor/hayro-interpret/src/device.rs@@ -0,0 +1,87 @@+use crate::font::Glyph;+use crate::soft_mask::SoftMask;+use crate::{BlendMode, ClipPath, Image};+use crate::{GlyphDrawMode, Paint, PathDrawMode};+use kurbo::{Affine, BezPath, Rect, Shape};++/// A trait for a device that can be used to process PDF drawing instructions.+pub trait Device<'a> {+ /// Set the properties for future stroking operations.+ /// Set a soft mask to be used for future drawing instructions.+ fn set_soft_mask(&mut self, mask: Option<SoftMask<'a>>);+ /// Set the blend mode that should be used for rendering operations.+ fn set_blend_mode(&mut self, blend_mode: BlendMode);+ /// Draw a path.+ fn draw_path(+ &mut self,+ path: &BezPath,+ transform: Affine,+ paint: &Paint<'a>,+ draw_mode: &PathDrawMode,+ );+ /// Push a new clip path to the clip stack.+ fn push_clip_path(&mut self, clip_path: &ClipPath);+ /// Push a new transparency group to the blend stack.+ fn push_transparency_group(+ &mut self,+ opacity: f32,+ mask: Option<SoftMask<'a>>,+ blend_mode: BlendMode,+ );+ /// Draw a glyph.+ fn draw_glyph(+ &mut self,+ glyph: &Glyph<'a>,+ transform: Affine,+ glyph_transform: Affine,+ paint: &Paint<'a>,+ // TODO: Move this into outline glyph.+ draw_mode: &GlyphDrawMode,+ );+ /// Draw an image.+ fn draw_image(&mut self, image: Image<'a, '_>, transform: Affine);+ /// Pop the last clip path from the clip stack.+ fn pop_clip_path(&mut self);+ /// Pop the last transparency group from the blend stack.+ fn pop_transparency_group(&mut self);+ /// Draw a rectangle directly, without going through the general path pipeline.+ fn draw_rect(+ &mut self,+ rect: &Rect,+ transform: Affine,+ paint: &Paint<'a>,+ draw_mode: &PathDrawMode,+ ) {+ self.draw_path(&rect.to_path(0.1), transform, paint, draw_mode);+ }+ /// Called at the beginning of a marked content sequence (BMC/BDC).+ ///+ /// The tag is the marked content tag (e.g. b"P", b"Span"). The mcid is+ /// the marked content identifier from the properties dict, if present.+ fn begin_marked_content(&mut self, _tag: &[u8], _mcid: Option<i32>) {}+ /// Called at the end of a marked content sequence (EMC).+ fn end_marked_content(&mut self) {}+}++/// A device that discards all drawing operations.+pub struct DummyDevice;++impl Device<'_> for DummyDevice {+ fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}+ fn set_blend_mode(&mut self, _: BlendMode) {}+ fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'_>, _: &PathDrawMode) {}+ fn push_clip_path(&mut self, _: &ClipPath) {}+ fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}+ fn draw_glyph(+ &mut self,+ _: &Glyph<'_>,+ _: Affine,+ _: Affine,+ _: &Paint<'_>,+ _: &GlyphDrawMode,+ ) {+ }+ fn draw_image(&mut self, _: Image<'_, '_>, _: Affine) {}+ fn pop_clip_path(&mut self) {}+ fn pop_transparency_group(&mut self) {}+}diff --git a/vendor/hayro-interpret/src/encode.rs b/vendor/hayro-interpret/src/encode.rsnew file mode 100644index 000000000..d6b943ec0--- /dev/null+++ b/vendor/hayro-interpret/src/encode.rs@@ -0,0 +1,426 @@+//! Encoding shading patterns for easy sampling.++use crate::color::{AlphaColor, ColorComponents, ColorSpace};+use crate::interpret::state::ActiveTransferFunction;+use crate::pattern::ShadingPattern;+use crate::shading::{ShadingFunction, ShadingType, Triangle};+use kurbo::{Affine, Point};+use rustc_hash::FxHashMap;+use smallvec::{ToSmallVec, smallvec};++/// A shading pattern that was encoded so it can be sampled.+#[derive(Debug)]+pub struct EncodedShadingPattern {+ /// The base transform of the shading pattern.+ pub base_transform: Affine,+ pub(crate) color_space: ColorSpace,+ pub(crate) background_color: AlphaColor,+ pub(crate) shading_type: EncodedShadingType,+ pub(crate) opacity: f32,+ pub(crate) transfer_function: Option<ActiveTransferFunction>,+}++impl EncodedShadingPattern {+ /// Sample the shading at the given position.+ #[inline]+ pub fn sample(&self, pos: Point) -> [f32; 4] {+ self.shading_type+ .eval(pos, self.background_color, &self.color_space)+ .map(|v| {+ let mut components = v.components();+ components[3] *= self.opacity;++ if let Some(tf) = &self.transfer_function {+ return tf.apply(&AlphaColor::new(components)).components();+ }++ components+ })+ .unwrap_or([0.0, 0.0, 0.0, 0.0])+ }+}++impl ShadingPattern {+ /// Encode the shading pattern.+ pub fn encode(&self) -> EncodedShadingPattern {+ let base_transform;++ let shading_type = match self.shading.shading_type.as_ref() {+ ShadingType::FunctionBased {+ domain,+ matrix,+ function,+ } => {+ base_transform = (self.matrix * *matrix).inverse();+ encode_function_shading(domain, function)+ }+ ShadingType::RadialAxial {+ coords,+ domain,+ function,+ extend,+ axial,+ } => {+ let (encoded, initial_transform) =+ encode_axial_shading(*coords, *domain, function, *extend, *axial);++ base_transform = initial_transform * self.matrix.inverse();++ encoded+ }+ ShadingType::TriangleMesh {+ triangles,+ function,+ } => {+ let full_transform = self.matrix;+ let samples = sample_triangles(triangles, full_transform);++ base_transform = Affine::IDENTITY;++ EncodedShadingType::Sampled {+ samples,+ function: function.clone(),+ }+ }+ ShadingType::CoonsPatchMesh { patches, function } => {+ let mut triangles = vec![];+ for patch in patches {+ patch.to_triangles(&mut triangles);+ }++ let full_transform = self.matrix;+ let samples = sample_triangles(&triangles, full_transform);++ base_transform = Affine::IDENTITY;++ EncodedShadingType::Sampled {+ samples,+ function: function.clone(),+ }+ }+ ShadingType::TensorProductPatchMesh { patches, function } => {+ let mut triangles = vec![];+ for patch in patches {+ patch.to_triangles(&mut triangles);+ }++ let full_transform = self.matrix;+ let samples = sample_triangles(&triangles, full_transform);++ base_transform = Affine::IDENTITY;++ EncodedShadingType::Sampled {+ samples,+ function: function.clone(),+ }+ }+ ShadingType::Dummy => {+ base_transform = Affine::IDENTITY;++ EncodedShadingType::Dummy+ }+ };++ let color_space = self.shading.color_space.clone();++ let background_color = self+ .shading+ .background+ .as_ref()+ .map(|b| color_space.to_rgba(b, 1.0, false))+ .unwrap_or(AlphaColor::TRANSPARENT);++ EncodedShadingPattern {+ color_space,+ background_color,+ shading_type,+ base_transform,+ opacity: self.opacity,+ transfer_function: self.transfer_function.clone(),+ }+ }+}++fn encode_axial_shading(+ coords: [f32; 6],+ domain: [f32; 2],+ function: &ShadingFunction,+ extend: [bool; 2],+ is_axial: bool,+) -> (EncodedShadingType, Affine) {+ let initial_transform;++ let params = if is_axial {+ let [x_0, y_0, x_1, y_1, _, _] = coords;++ initial_transform = ts_from_line_to_line(+ Point::new(x_0 as f64, y_0 as f64),+ Point::new(x_1 as f64, y_1 as f64),+ Point::ZERO,+ Point::new(1.0, 0.0),+ );++ RadialAxialParams::Axial+ } else {+ let [x_0, y_0, r0, x_1, y_1, r_1] = coords;++ initial_transform = Affine::translate((-x_0 as f64, -y_0 as f64));+ let new_x1 = x_1 - x_0;+ let new_y1 = y_1 - y_0;++ let p1 = Point::new(new_x1 as f64, new_y1 as f64);+ let r = Point::new(r0 as f64, r_1 as f64);++ RadialAxialParams::Radial { p1, r }+ };++ (+ EncodedShadingType::RadialAxial {+ function: function.clone(),+ params,+ domain,+ extend,+ },+ initial_transform,+ )+}++fn sample_triangles(+ triangles: &[Triangle],+ transform: Affine,+) -> FxHashMap<(u16, u16), ColorComponents> {+ let mut map = FxHashMap::default();++ for t in triangles {+ let t = {+ let p0 = transform * t.p0.point;+ let p1 = transform * t.p1.point;+ let p2 = transform * t.p2.point;++ let mut v0 = t.p0.clone();+ v0.point = p0;+ let mut v1 = t.p1.clone();+ v1.point = p1;+ let mut v2 = t.p2.clone();+ v2.point = p2;++ Triangle::new(v0, v1, v2)+ };++ let bbox = t.bounding_box();++ for y in (bbox.y0.floor() as u16)..(bbox.y1.ceil() as u16) {+ for x in (bbox.x0.floor() as u16)..(bbox.x1.ceil() as u16) {+ let point = Point::new(x as f64, y as f64);+ if t.contains_point(point) {+ map.insert((x, y), t.interpolate(point));+ }+ }+ }+ }++ map+}++fn encode_function_shading(domain: &[f32; 4], function: &ShadingFunction) -> EncodedShadingType {+ let domain = kurbo::Rect::new(+ domain[0] as f64,+ domain[2] as f64,+ domain[1] as f64,+ domain[3] as f64,+ );++ EncodedShadingType::FunctionBased {+ domain,+ function: function.clone(),+ }+}++#[derive(Debug)]+pub(crate) enum RadialAxialParams {+ Axial,+ Radial { p1: Point, r: Point },+}++#[derive(Debug)]+pub(crate) enum EncodedShadingType {+ FunctionBased {+ domain: kurbo::Rect,+ function: ShadingFunction,+ },+ RadialAxial {+ function: ShadingFunction,+ params: RadialAxialParams,+ domain: [f32; 2],+ extend: [bool; 2],+ },+ Sampled {+ samples: FxHashMap<(u16, u16), ColorComponents>,+ function: Option<ShadingFunction>,+ },+ Dummy,+}++impl EncodedShadingType {+ pub(crate) fn eval(+ &self,+ pos: Point,+ bg_color: AlphaColor,+ color_space: &ColorSpace,+ ) -> Option<AlphaColor> {+ match self {+ Self::FunctionBased { domain, function } => {+ if !domain.contains(pos) {+ Some(bg_color)+ } else {+ let out = function.eval(&smallvec![pos.x as f32, pos.y as f32])?;+ // TODO: Clamp out-of-range values.+ Some(color_space.to_rgba(&out, 1.0, false))+ }+ }+ Self::RadialAxial {+ function,+ params,+ domain,+ extend,+ } => {+ let (t0, t1) = (domain[0], domain[1]);++ let mut t = match params {+ RadialAxialParams::Axial => pos.x as f32,+ RadialAxialParams::Radial { p1, r } => {+ radial_pos(&pos, p1, *r, extend[0], extend[1]).unwrap_or(f32::MIN)+ }+ };++ if t == f32::MIN {+ return Some(bg_color);+ }++ if t < 0.0 {+ if extend[0] {+ t = 0.0;+ } else {+ return Some(bg_color);+ }+ } else if t > 1.0 {+ if extend[1] {+ t = 1.0;+ } else {+ return Some(bg_color);+ }+ }++ let t = t0 + (t1 - t0) * t;++ let val = function.eval(&smallvec![t])?;++ Some(color_space.to_rgba(&val, 1.0, false))+ }+ Self::Sampled { samples, function } => {+ let sample_point = (pos.x as u16, pos.y as u16);++ if let Some(color) = samples.get(&sample_point) {+ if let Some(function) = function {+ let val = function.eval(&color.to_smallvec())?;+ Some(color_space.to_rgba(&val, 1.0, false))+ } else {+ Some(color_space.to_rgba(color, 1.0, false))+ }+ } else {+ Some(bg_color)+ }+ }+ Self::Dummy => Some(AlphaColor::TRANSPARENT),+ }+ }+}++fn ts_from_line_to_line(src1: Point, src2: Point, dst1: Point, dst2: Point) -> Affine {+ let unit_to_line1 = unit_to_line(src1, src2);+ let line1_to_unit = unit_to_line1.inverse();+ let unit_to_line2 = unit_to_line(dst1, dst2);++ unit_to_line2 * line1_to_unit+}++fn unit_to_line(p0: Point, p1: Point) -> Affine {+ Affine::new([+ p1.y - p0.y,+ p0.x - p1.x,+ p1.x - p0.x,+ p1.y - p0.y,+ p0.x,+ p0.y,+ ])+}++fn radial_pos(+ pos: &Point,+ p1: &Point,+ r: Point,+ min_extend: bool,+ max_extend: bool,+) -> Option<f32> {+ let r0 = r.x as f32;+ let dx = p1.x as f32;+ let dy = p1.y as f32;+ let dr = r.y as f32 - r0;++ let px = pos.x as f32;+ let py = pos.y as f32;++ let a = dx * dx + dy * dy - dr * dr;+ let b = -2.0 * (px * dx + py * dy + r0 * dr);+ let c = px * px + py * py - r0 * r0;++ let discriminant = b * b - 4.0 * a * c;++ // No solution available.+ if discriminant < 0.0 {+ return None;+ }++ if a.abs() < 1e-6 {+ if b.abs() < 1e-6 {+ return None;+ }++ let t = -c / b;++ if (!min_extend && t < 0.0) || (!max_extend && t > 1.0) {+ return None;+ }++ let r_t = r0 + dr * t;+ if r_t < 0.0 {+ return None;+ }++ return Some(t);+ }++ let sqrt_d = discriminant.sqrt();+ let t1 = (-b - sqrt_d) / (2.0 * a);+ let t2 = (-b + sqrt_d) / (2.0 * a);++ let max = t1.max(t2);+ let mut take_max = Some(max);+ let min = t1.min(t2);+ let mut take_min = Some(min);++ if (!min_extend && min < 0.0) || r0 + dr * min < 0.0 {+ take_min = None;+ }++ if (!max_extend && max > 1.0) || r0 + dr * max < 0.0 {+ take_max = None;+ }++ match (take_min, take_max) {+ (Some(_), Some(max)) => Some(max),+ (Some(min), None) => Some(min),+ (None, Some(max)) => Some(max),+ (None, None) => None,+ }+}diff --git a/vendor/hayro-interpret/src/font/blob.rs b/vendor/hayro-interpret/src/font/blob.rsnew file mode 100644index 000000000..d2868a6c1--- /dev/null+++ b/vendor/hayro-interpret/src/font/blob.rs@@ -0,0 +1,335 @@+use crate::font::UNITS_PER_EM;+use crate::font::outline::OutlinePath;+use kurbo::BezPath;+use skrifa::instance::{LocationRef, Size};+use skrifa::metrics::GlyphMetrics;+use skrifa::outline::{DrawSettings, Engine, HintingInstance, HintingOptions, Target};+use skrifa::raw::TableProvider;+use skrifa::raw::ps::cff::{CffFontRef, Subfont, charset::Charset, v1::Cff};+use skrifa::raw::ps::string::Sid;+use skrifa::raw::ps::type1::Type1Font;+use skrifa::raw::tables::post::DEFAULT_GLYPH_NAMES;+use skrifa::raw::{FontData as ReadFontData, FontRead};+use skrifa::{FontRef, GlyphId, MetadataProvider, OutlineGlyphCollection};+use std::collections::HashMap;+use std::fmt::{Debug, Formatter};+use std::sync::Arc;+use yoke::{Yoke, Yokeable};++type FontData = Arc<dyn AsRef<[u8]> + Send + Sync>;+type OpenTypeFontYoke = Yoke<OTFYoke<'static>, FontData>;+type CffFontYoke = Yoke<CFFYoke<'static>, FontData>;++/// A font blob for type 1 fonts.+#[derive(Clone)]+pub(crate) struct Type1FontBlob(Arc<Type1Font>);++impl Debug for Type1FontBlob {+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {+ write!(f, "Type1 Font {{ .. }}")+ }+}++impl Type1FontBlob {+ pub(crate) fn new(data: FontData) -> Option<Self> {+ let table = Type1Font::new(data.as_ref().as_ref()).ok()?;+ Some(Self(Arc::new(table)))+ }++ pub(crate) fn table(&self) -> &Type1Font {+ self.0.as_ref()+ }++ pub(crate) fn outline_glyph(&self, gid: GlyphId) -> BezPath {+ let mut path = OutlinePath::new();+ let _ = self.table().draw(gid, Some(UNITS_PER_EM), &mut path);++ path.take()+ }+}++/// A font blob for CFF-based fonts.+#[derive(Clone)]+pub(crate) struct CffFontBlob(Arc<CffFontYoke>);++impl Debug for CffFontBlob {+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {+ write!(f, "Type1 Font {{ .. }}")+ }+}++impl CffFontBlob {+ pub(crate) fn new(data: FontData) -> Option<Self> {+ let font = CffFontRef::new(data.as_ref().as_ref(), 0, None).ok()?;+ let cff = Cff::read(ReadFontData::new(data.as_ref().as_ref())).ok()?;+ let charset = font.charset();+ let subfonts = (0..font.num_subfonts())+ .map(|index| font.subfont(index, &[]).ok())+ .collect::<Option<Vec<_>>>()?;++ let yoke = Yoke::<CFFYoke<'static>, FontData>::attach_to_cart(data.clone(), |data| {+ let bytes = data.as_ref();+ let font = CffFontRef::new(bytes, 0, None).unwrap();+ let cff = Cff::read(ReadFontData::new(bytes)).unwrap();+ let charset = font.charset();+ let subfonts = (0..font.num_subfonts())+ .map(|index| font.subfont(index, &[]).unwrap())+ .collect();+ CFFYoke {+ font,+ cff,+ charset,+ subfonts,+ }+ });++ let _ = (cff, charset, subfonts);+ Some(Self(Arc::new(yoke)))+ }++ pub(crate) fn font_data(&self) -> FontData {+ self.0.backing_cart().clone()+ }++ pub(crate) fn font(&self) -> &CffFontRef<'_> {+ &self.0.as_ref().get().font+ }++ fn charset(&self) -> Option<&Charset<'_>> {+ self.0.as_ref().get().charset.as_ref()+ }++ fn subfont(&self, glyph: GlyphId) -> Option<&Subfont> {+ let index = self.font().subfont_index(glyph)? as usize;+ self.0.as_ref().get().subfonts.get(index)+ }++ pub(crate) fn outline_glyph(&self, glyph: GlyphId) -> BezPath {+ let mut path = OutlinePath::new();+ let Some(subfont) = self.subfont(glyph) else {+ return BezPath::new();+ };++ let _ = self+ .font()+ .draw(subfont, glyph, &[], Some(UNITS_PER_EM), &mut path);++ path.take()+ }++ pub(crate) fn glyph_names(&self) -> Vec<(GlyphId, String)> {+ let Some(charset) = self.charset() else {+ return Vec::new();+ };++ // TODO: Avoid collecting here.+ charset+ .iter()+ .filter_map(|(gid, sid)| {+ let bytes = self.0.as_ref().get().cff.string(sid)?;+ let name = std::str::from_utf8(bytes).ok()?.to_string();+ Some((gid, name))+ })+ .collect()+ }++ pub(crate) fn glyph_index_by_name(&self, name: &str) -> Option<GlyphId> {+ // TODO: This is probably slow to do repeatedly?+ self.charset()?.iter().find_map(|(gid, sid)| {+ let bytes = self.0.as_ref().get().cff.string(sid)?;+ (bytes == name.as_bytes()).then_some(gid)+ })+ }++ pub(crate) fn glyph_index_by_cid(&self, cid: u16) -> Option<GlyphId> {+ self.charset()?.glyph_id(Sid::new(cid)).ok()+ }++ pub(crate) fn glyph_index(&self, code: u8) -> Option<GlyphId> {+ self.font()+ .encoding()+ .and_then(|encoding| encoding.map(code))+ }++ pub(crate) fn num_glyphs(&self) -> u32 {+ self.font().num_glyphs()+ }++ pub(crate) fn is_cid(&self) -> bool {+ self.font().is_cid()+ }+}++/// A font blob for OpenType fonts.+#[derive(Clone)]+pub(crate) struct OpenTypeFontBlob {+ yoke: Arc<OpenTypeFontYoke>,+ cff_blob: Option<CffFontBlob>,+}++impl Debug for OpenTypeFontBlob {+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {+ write!(f, "OpenType Font {{ .. }}")+ }+}++impl OpenTypeFontBlob {+ pub(crate) fn new(data: FontData, index: u32) -> Option<Self> {+ // Check first whether the font is valid so we can unwrap in the closure.+ let f = FontRef::from_index(data.as_ref().as_ref(), index).ok()?;+ // Reject fonts with invalid post table version, fixes pdf.js issue 9462. Not sure if there+ // is a better fix, for some reason skrifa accepts the font which is completely invalid.+ let invalid = f.post().is_ok_and(|p| {+ !matches!(+ p.version().to_major_minor(),+ (1, 0) | (2, 0) | (2, 5) | (3, 0)+ )+ });++ if invalid {+ return None;+ }++ // We store this separately because we want to be able to cache the subfonts+ // of a CFF OpenType font, which is not possible using the current skrifa API.+ // Hopefully there will be some way in the future.+ let cff_blob = f+ .cff()+ .ok()+ .map(|cff| Arc::new(cff.offset_data().as_ref().to_vec()) as FontData)+ .and_then(CffFontBlob::new);++ let font_ref_yoke =+ Yoke::<OTFYoke<'static>, FontData>::attach_to_cart(data.clone(), |data| {+ let font_ref = FontRef::from_index(data.as_ref(), index).unwrap();++ let hinting_instance = if font_ref.outline_glyphs().require_interpreter() {+ HintingInstance::new(+ &font_ref.outline_glyphs(),+ Size::new(UNITS_PER_EM),+ LocationRef::default(),+ HintingOptions {+ engine: Engine::Interpreter,+ target: Target::Mono,+ },+ )+ .ok()+ } else {+ None+ };++ OTFYoke {+ font_ref: font_ref.clone(),+ outline_glyphs: font_ref.outline_glyphs(),+ hinting_instance,+ glyph_metrics: font_ref+ .glyph_metrics(Size::new(UNITS_PER_EM), LocationRef::default()),+ }+ });++ Some(Self {+ yoke: Arc::new(font_ref_yoke),+ cff_blob,+ })+ }++ pub(crate) fn font_data(&self) -> FontData {+ self.yoke.backing_cart().clone()+ }++ pub(crate) fn font_ref(&self) -> &FontRef<'_> {+ &self.yoke.as_ref().get().font_ref+ }++ pub(crate) fn glyph_metrics(&self) -> &GlyphMetrics<'_> {+ &self.yoke.as_ref().get().glyph_metrics+ }++ pub(crate) fn glyph_names(&self) -> HashMap<String, GlyphId> {+ // Note: We don't call the `glyph_name` method provided by read-fonts because+ // calling it repeatedly is very slow.+ let mut glyph_names = HashMap::new();+ let Ok(post) = self.font_ref().post() else {+ return glyph_names;+ };++ match post.version().to_major_minor() {+ (1, 0) => {+ for (gid, name) in DEFAULT_GLYPH_NAMES.iter().enumerate() {+ glyph_names.insert((*name).to_string(), GlyphId::new(gid as u32));+ }+ }+ (2, 0) => {+ let Some(name_indices) = post.glyph_name_index() else {+ return glyph_names;+ };+ let Some(string_data) = post.string_data() else {+ return glyph_names;+ };+ let custom_names = string_data+ .iter()+ .map(|entry| entry.ok().map(|name| name.as_str()))+ .collect::<Vec<_>>();++ for (gid, idx) in name_indices.iter().enumerate() {+ let idx = idx.get() as usize;+ if let Some(name) = DEFAULT_GLYPH_NAMES.get(idx).copied().or_else(|| {+ custom_names+ .get(idx.saturating_sub(DEFAULT_GLYPH_NAMES.len()))+ .copied()+ .flatten()+ }) {+ glyph_names.insert(name.to_string(), GlyphId::new(gid as u32));+ }+ }+ }+ _ => {}+ }++ glyph_names+ }++ fn outline_glyphs(&self) -> &OutlineGlyphCollection<'_> {+ &self.yoke.as_ref().get().outline_glyphs+ }++ pub(crate) fn outline_glyph(&self, glyph: GlyphId) -> BezPath {+ if let Some(cff_blob) = self.cff_blob.as_ref() {+ return cff_blob.outline_glyph(glyph);+ }++ let mut path = OutlinePath::new();++ let draw_settings = if let Some(instance) = self.yoke.get().hinting_instance.as_ref() {+ // Note: We always hint at the font size `UNITS_PER_EM`, which obviously isn't very useful. We don't do this+ // for better text quality (right now), but instead because there are some PDFs with obscure fonts that+ // actually render wrongly if hinting is disabled!+ DrawSettings::hinted(instance, false)+ } else {+ DrawSettings::unhinted(Size::new(UNITS_PER_EM), LocationRef::default())+ };++ let Some(outline) = self.outline_glyphs().get(glyph) else {+ return BezPath::new();+ };++ let _ = outline.draw(draw_settings, &mut path);+ path.take()+ }+}++#[derive(Yokeable, Clone)]+struct OTFYoke<'a> {+ font_ref: FontRef<'a>,+ glyph_metrics: GlyphMetrics<'a>,+ hinting_instance: Option<HintingInstance>,+ outline_glyphs: OutlineGlyphCollection<'a>,+}++#[derive(Yokeable, Clone)]+struct CFFYoke<'a> {+ font: CffFontRef<'a>,+ cff: Cff<'a>,+ charset: Option<Charset<'a>>,+ subfonts: Vec<Subfont>,+}diff --git a/vendor/hayro-interpret/src/font/cid.rs b/vendor/hayro-interpret/src/font/cid.rsnew file mode 100644index 000000000..dd724e370--- /dev/null+++ b/vendor/hayro-interpret/src/font/cid.rs@@ -0,0 +1,592 @@+use crate::font::blob::{CffFontBlob, OpenTypeFontBlob, Type1FontBlob};+use crate::font::generated::glyph_names;+use crate::font::standard_font::select_standard_font;+use crate::font::{+ FallbackFontQuery, FontFlags, FontQuery, read_to_unicode, stretch_glyph, strip_subset_prefix,+};+use crate::{CMapResolverFn, CacheKey, FontResolverFn};+use hayro_cmap::{BfString, CMap, CharacterCollection, CidFamily, WritingMode};+use hayro_syntax::object;+use hayro_syntax::object::Dict;+use hayro_syntax::object::Name;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::*;+use hayro_syntax::object::{Array, Object};+use kurbo::{BezPath, Vec2};+use skrifa::attribute::Style;+use skrifa::raw::collections::int_set::Domain;+use skrifa::{FontRef, GlyphId, MetadataProvider};+use std::collections::HashMap;+use std::ops::Deref;+use std::sync::Arc;++#[derive(Debug)]+pub(crate) struct Type0Font {+ font_type: FontType,+ horizontal: bool,+ cache_key: u128,+ dw: f32,+ dw2: (f32, f32),+ widths: HashMap<u32, f32>,+ encoding: CMap,+ to_unicode: Option<CMap>,+ widths2: HashMap<u32, [f32; 3]>,+ cid_to_gid_map: CidToGIdMap,+ /// PostScript name from the PDF.+ postscript_name: Option<String>,+ /// Font flags from the font descriptor.+ font_flags: Option<FontFlags>,+ /// Whether this font is using a fallback (non-embedded) font.+ fallback: bool,+ /// Whether the `to_unicode` map is a UCS2 `CMap` (CID-indexed) rather than+ /// a `ToUnicode` `CMap` (code-indexed).+ to_unicode_is_cid_indexed: bool,+}++impl Type0Font {+ pub(crate) fn new(+ dict: &Dict<'_>,+ font_resolver: &FontResolverFn,+ cmap_resolver: &CMapResolverFn,+ ) -> Option<Self> {+ let cmap = read_encoding(&dict.get::<Object<'_>>(ENCODING)?, cmap_resolver)?;++ let horizontal = cmap.metadata().writing_mode != Some(WritingMode::Vertical);++ let descendant_font = dict+ .get::<Array<'_>>(DESCENDANT_FONTS)?+ .iter::<Dict<'_>>()+ .next()?;+ let font_descriptor = descendant_font+ .get::<Dict<'_>>(FONT_DESC)+ .unwrap_or_default();++ let character_collection = cmap+ .metadata()+ .character_collection+ .clone()+ .filter(|cc| cc.family != CidFamily::AdobeIdentity)+ .or_else(|| read_cid_system_info(&descendant_font));++ let (font_type, fallback, _is_standard_fallback) = match FontType::new(&font_descriptor) {+ Some(ft) => (ft, false, false),+ None => {+ let (query, is_standard) =+ if let Some((standard, _)) = select_standard_font(dict, &font_descriptor) {+ (FontQuery::Standard(standard), true)+ } else {+ let mut query = FallbackFontQuery::new(dict);+ query.character_collection = character_collection.clone();++ warn!(+ "unable to load CID font {} ({:?}), attempting fallback",+ query.post_script_name.as_deref().unwrap_or("(no name)"),+ dict.obj_id()+ );++ (FontQuery::Fallback(query), false)+ };++ let (data, index) = font_resolver(&query)?;+ let blob = OpenTypeFontBlob::new(data.clone(), index)+ .map(FontType::OpenType)+ .or_else(|| CffFontBlob::new(data).map(FontType::Cff))?;+ (blob, true, is_standard)+ }+ };++ let default_width = descendant_font.get::<f32>(DW).unwrap_or(1000.0);+ let dw2 = descendant_font+ .get::<[f32; 2]>(DW2)+ .map(|v| (v[0], v[1]))+ .unwrap_or((880.0, -1000.0));++ let widths = descendant_font+ .get::<Array<'_>>(W)+ .and_then(|a| read_widths(&a))+ .unwrap_or_default();+ let widths2 = descendant_font+ .get::<Array<'_>>(W2)+ .and_then(|a| read_widths2(&a))+ .unwrap_or_default();+ let cid_to_gid_map = CidToGIdMap::new(&descendant_font).unwrap_or_default();+ let cache_key = dict.cache_key();++ let mut to_unicode = read_to_unicode(dict, cmap_resolver);+ let mut to_unicode_is_cid_indexed = false;++ // If there is no ToUnicode map, try to get the UCS2 CMap.+ if fallback+ && to_unicode.is_none()+ && let Some(cc) = character_collection.as_ref()+ && let Some(ucs2_name) = cc.family.ucs2_cmap()+ && let Some(data) = (cmap_resolver)(ucs2_name)+ {+ let resolver = cmap_resolver.clone();+ if let Some(ucs2_cmap) = CMap::parse(data, move |n| (resolver)(n)) {+ to_unicode = Some(ucs2_cmap);+ to_unicode_is_cid_indexed = true;+ }+ }++ let postscript_name = dict+ .get::<Name<'_>>(BASE_FONT)+ .map(|n| strip_subset_prefix(n.as_str()).to_string());++ // Extract font flags from descriptor+ let font_flags = font_descriptor+ .get::<u32>(FLAGS)+ .and_then(FontFlags::from_bits);++ Some(Self {+ cache_key,+ horizontal,+ encoding: cmap,+ to_unicode,+ font_type,+ dw: default_width,+ dw2,+ widths,+ widths2,+ cid_to_gid_map,+ postscript_name,+ font_flags,+ fallback,+ to_unicode_is_cid_indexed,+ })+ }++ pub(crate) fn map_code(&self, code: u32) -> GlyphId {+ let Some(cid) = self.code_to_cid(code) else {+ return GlyphId::NOTDEF;+ };++ // UCS2 maps are indexed by CIDs, while embededd `ToUnicode` maps are+ // indexed by character code.+ let to_unicode_key = if self.to_unicode_is_cid_indexed {+ cid+ } else {+ code+ };++ if self.fallback+ && let Some(glyph) = self.map_via_unicode(to_unicode_key)+ {+ // Yay, Unicode worked!+ return glyph;+ }++ // At this point, not much we can do anymore. Just hope that the+ // selected font has the right glyph order, and map via that.++ match &self.font_type {+ FontType::OpenType(_) => self.cid_to_gid_map.map(cid as u16),+ FontType::Cff(c) => {+ if c.is_cid() {+ // Very confusing stuff going on here, see https://github.com/mozilla/pdf.js/pull/15563.+ // The PDF spec makes it sounds like cid-to-gid map should only be used for TrueType fonts,+ // but Acrobat also seems to support it for CFF fonts with some weird behavior.+ if matches!(self.cid_to_gid_map, CidToGIdMap::Identity) {+ c.glyph_index_by_cid(cid as u16).unwrap_or(GlyphId::NOTDEF)+ } else {+ GlyphId::new(self.cid_to_gid_map.inverse_map(GlyphId::new(cid)) as u32)+ }+ } else {+ self.cid_to_gid_map.map(cid as u16)+ }+ }+ // Maybe we need similar processing to CFF fonts? But since+ // Type1 fonts are invalid anyway, let's just ignore for now.+ FontType::Type1(_) => GlyphId::new(cid),+ }+ }++ /// Map a character code (or CID) to a glyph ID+ /// by first getting its Unicode and then looking up the codepoint in the+ /// font's cmap.+ fn map_via_unicode(&self, key: u32) -> Option<GlyphId> {+ let to_unicode = self.to_unicode.as_ref()?;++ let character = to_unicode+ .lookup_bf_string(key)+ .or_else(|| {+ for len in 0..4 {+ if let Some(code) = to_unicode.lookup_cid_code(key, len)+ && let Some(code) = char::from_u32(code.to_u32())+ {+ return Some(BfString::Char(code));+ }+ }++ None+ })+ .and_then(|bf| match bf {+ BfString::Char(c) => Some(c),+ BfString::String(_) => None,+ })?;++ match &self.font_type {+ FontType::OpenType(t) => t.font_ref().charmap().map(character),+ FontType::Cff(c) => {+ // Map codepoint to glyph name via AFL, and then look it up.+ if let Some(name) = glyph_names::get_reverse(character)+ && let Some(gid) = c.glyph_index_by_name(name)+ {+ Some(gid)+ } else {+ None+ }+ }+ FontType::Type1(_) => {+ // We could in theory map to a glyph via AFL and then look up+ // the glyph index in the encoding, but since skrifa doesn't have+ // an API for that and this is only really necessary for fallback+ // fonts (which currently only supports OpenType and CFF as fallback),+ // so we don't support this for now.+ None+ }+ }+ }++ fn code_to_cid(&self, code: u32) -> Option<u32> {+ for byte_len in 1..=4_u8 {+ if let Some(cid) = self.encoding.lookup_cid_code(code, byte_len) {+ return Some(cid);+ }+ }++ None+ }++ pub(crate) fn outline_glyph(&self, glyph: GlyphId, code: u32) -> BezPath {+ let path = match &self.font_type {+ FontType::OpenType(t) => t.outline_glyph(glyph),+ FontType::Cff(c) => c.outline_glyph(glyph),+ FontType::Type1(t) => t.outline_glyph(glyph),+ };++ if self.fallback+ && let FontType::OpenType(t) = &self.font_type+ && let Some(cid) = self.code_to_cid(code)+ && let Some(actual_width) = t.glyph_metrics().advance_width(glyph)+ // Only use an expected width if there is an explicit /W array,+ // not the default width, as it leads to weird results from my testing.+ && let Some(expected_width) = self.widths.get(&cid).copied()+ {+ return stretch_glyph(path, expected_width, actual_width);+ }++ path+ }++ pub(crate) fn font_data(&self) -> Option<crate::font::FontData> {+ match &self.font_type {+ FontType::OpenType(t) => Some(t.font_data()),+ FontType::Cff(c) => Some(c.font_data()),+ FontType::Type1(_) => None,+ }+ }++ /// Get the PostScript name.+ pub(crate) fn postscript_name(&self) -> Option<&str> {+ self.postscript_name.as_deref()+ }++ /// Get the font weight (100-900, 400=normal, 700=bold).+ ///+ /// Returns `None` if weight cannot be determined (CFF fonts or invalid weight).+ pub(crate) fn weight(&self) -> Option<u32> {+ match &self.font_type {+ FontType::OpenType(t) => {+ let weight = t.font_ref().attributes().weight.value().round() as u32;+ if weight > 0 { Some(weight) } else { None }+ }+ FontType::Cff(_) | FontType::Type1(_) => None,+ }+ }++ /// Check if font is italic based on font flags or font attributes.+ pub(crate) fn is_italic(&self) -> bool {+ if let Some(flags) = &self.font_flags+ && flags.contains(FontFlags::ITALIC)+ {+ return true;+ }+ match &self.font_type {+ FontType::OpenType(t) => t.font_ref().attributes().style != Style::Normal,+ FontType::Cff(_) | FontType::Type1(_) => false,+ }+ }++ /// Check if font is serif based on font flags.+ pub(crate) fn is_serif(&self) -> bool {+ self.font_flags+ .as_ref()+ .is_some_and(|f| f.contains(FontFlags::SERIF))+ }++ /// Check if font is monospace based on font flags or font metrics.+ pub(crate) fn is_monospace(&self) -> bool {+ if let Some(flags) = &self.font_flags+ && flags.contains(FontFlags::FIXED_PITCH)+ {+ return true;+ }+ match &self.font_type {+ FontType::OpenType(t) => {+ t.font_ref()+ .metrics(+ skrifa::instance::Size::unscaled(),+ skrifa::instance::LocationRef::default(),+ )+ .is_monospace+ }+ FontType::Cff(_) | FontType::Type1(_) => false,+ }+ }++ pub(crate) fn code_advance(&self, code: u32) -> Vec2 {+ let cid = self.code_to_cid(code).unwrap_or(0);+ if self.horizontal {+ Vec2::new(self.horizontal_width(cid) as f64, 0.0)+ } else if let Some([w, _, _]) = self.widths2.get(&cid) {+ Vec2::new(0.0, *w as f64)+ } else {+ Vec2::new(0.0, self.dw2.1 as f64)+ }+ }++ fn horizontal_width(&self, cid: u32) -> f32 {+ self.widths.get(&cid).copied().unwrap_or(self.dw)+ }++ pub(crate) fn is_horizontal(&self) -> bool {+ self.horizontal+ }++ pub(crate) fn read_code(&self, bytes: &[u8], offset: usize) -> (u32, usize) {+ let mut code = 0_u32;+ let remaining = bytes.len() - offset;++ for n in 0..4.min(remaining) {+ code = (code << 8) | bytes[offset + n] as u32;++ if self.encoding.lookup_cid_code(code, (n + 1) as u8).is_some() {+ return (code, n + 1);+ }+ }++ (0, 1)+ }++ pub(crate) fn origin_displacement(&self, code: u32) -> Vec2 {+ let cid = self.code_to_cid(code).unwrap_or(0);++ if self.is_horizontal() {+ Vec2::default()+ } else if let Some([_, v1, v2]) = self.widths2.get(&cid) {+ Vec2::new(-*v1 as f64, -*v2 as f64)+ } else {+ Vec2::new(-self.horizontal_width(cid) as f64 / 2.0, -self.dw2.0 as f64)+ }+ }++ pub(crate) fn char_code_to_unicode(&self, code: u32) -> Option<BfString> {+ if let Some(to_unicode) = &self.to_unicode {+ let key = if self.to_unicode_is_cid_indexed {+ self.code_to_cid(code).unwrap_or(0)+ } else {+ code+ };+ return to_unicode.lookup_bf_string(key);+ }++ None+ }+}++impl CacheKey for Type0Font {+ fn cache_key(&self) -> u128 {+ self.cache_key+ }+}++#[derive(Debug)]+enum FontType {+ /// An OpenType font.+ OpenType(OpenTypeFontBlob),+ /// A CFF font.+ Cff(CffFontBlob),+ /// A Type1 font. (Yes, there actually exist PDFs that embed a Type1 font in a+ /// CID font :))+ Type1(Type1FontBlob),+}++impl FontType {+ fn new(descriptor: &Dict<'_>) -> Option<Self> {+ // PDF has a distinction between CIDFontType0 and CIDFontType 2, with+ // specific requirements what font type can appear where. However, some+ // PDFs use wrong metadata, so we simply bruteforce without even looking+ // at the metadata.++ let data = descriptor+ .get::<Stream<'_>>(FONT_FILE2)+ .or_else(|| descriptor.get::<Stream<'_>>(FONT_FILE3))+ // See PDFBOX-2599. Apparently, Acrobat accepts this as well.+ .or_else(|| descriptor.get::<Stream<'_>>(FONT_FILE))?+ .decoded()+ .ok()?;++ let data = Arc::new(data.into_owned());++ let parsed = if let Ok(_font_ref) = FontRef::from_index(data.as_ref(), 0) {+ // It's an OpenType font, either TrueType or CFF.+ Self::OpenType(OpenTypeFontBlob::new(data, 0)?)+ } else if let Some(cff) = CffFontBlob::new(data.clone()) {+ // It's a CFF font.+ Self::Cff(cff)+ } else if let Some(t1) = Type1FontBlob::new(data) {+ // It's a Type1 (PFB) font.+ Self::Type1(t1)+ } else {+ return None;+ };++ Some(parsed)+ }+}++#[derive(Debug, Default)]+enum CidToGIdMap {+ #[default]+ Identity,+ Mapped {+ forward: HashMap<u16, GlyphId>,+ inverse: HashMap<GlyphId, u16>,+ },+}++impl CidToGIdMap {+ fn new(dict: &Dict<'_>) -> Option<Self> {+ if let Some(name) = dict.get::<Name<'_>>(CID_TO_GID_MAP) {+ if name.deref() == IDENTITY {+ Some(Self::Identity)+ } else {+ None+ }+ } else if let Some(stream) = dict.get::<Stream<'_>>(CID_TO_GID_MAP) {+ let decoded = stream.decoded().ok()?;+ let mut forward = HashMap::new();+ let mut inverse = HashMap::new();++ for (cid, gid) in decoded.chunks_exact(2).enumerate() {+ let gid = GlyphId::new(u16::from_be_bytes([gid[0], gid[1]]) as u32);++ forward.insert(cid as u16, gid);+ inverse.insert(gid, cid as u16);+ }++ Some(Self::Mapped { forward, inverse })+ } else {+ None+ }+ }++ fn map(&self, code: u16) -> GlyphId {+ match self {+ Self::Identity => GlyphId::new(code as u32),+ Self::Mapped { forward, .. } => forward.get(&code).copied().unwrap_or(GlyphId::NOTDEF),+ }+ }++ fn inverse_map(&self, gid: GlyphId) -> u16 {+ match self {+ Self::Identity => gid.to_u32() as u16,+ Self::Mapped { inverse, .. } => {+ inverse.get(&gid).copied().unwrap_or(gid.to_u32() as u16)+ }+ }+ }+}++fn read_widths(arr: &Array<'_>) -> Option<HashMap<u32, f32>> {+ let mut map = HashMap::new();+ let mut iter = arr.flex_iter();++ loop {+ if let Some((mut first, range)) = iter.next::<(u32, Array<'_>)>() {+ for width in range.iter::<f32>() {+ map.insert(first, width);+ first = first.checked_add(1)?;+ }+ } else if let Some((first, second, width)) = iter.next::<(u32, u32, f32)>() {+ for i in first..=second {+ map.insert(i, width);+ }+ } else {+ break;+ }+ }++ Some(map)+}++fn read_widths2(arr: &Array<'_>) -> Option<HashMap<u32, [f32; 3]>> {+ let mut map = HashMap::new();+ let mut iter = arr.flex_iter();++ loop {+ if let Some((mut first, range)) = iter.next::<(u32, Array<'_>)>() {+ let mut iter = range.iter::<f32>();++ while let Some(w) = iter.next() {+ let v1 = iter.next()?;+ let v2 = iter.next()?;+ map.insert(first, [w, v1, v2]);+ first = first.checked_add(1)?;+ }+ } else if let Some((first, second, w, v1, v2)) = iter.next::<(u32, u32, f32, f32, f32)>() {+ for i in first..=second {+ map.insert(i, [w, v1, v2]);+ }+ } else {+ break;+ }+ }++ Some(map)+}++fn read_cid_system_info(descendant_font: &Dict<'_>) -> Option<CharacterCollection> {+ let info = descendant_font.get::<Dict<'_>>(CIDSYSTEMINFO)?;+ let registry = info.get::<object::String<'_>>(REGISTRY)?;+ let ordering = info.get::<object::String<'_>>(ORDERING)?;+ let supplement = info.get::<i32>(SUPPLEMENT).unwrap_or(0);+ let family = CidFamily::from_registry_ordering(registry.deref(), ordering.deref());++ Some(CharacterCollection { family, supplement })+}++fn read_encoding(object: &Object<'_>, cmap_resolver: &CMapResolverFn) -> Option<CMap> {+ // TODO: Support fetching CMaps referenced via `usecmap` in the PDF.+ match object {+ Object::Name(n) => {+ let cmap_type = hayro_cmap::CMapName::from_bytes(n.deref());+ match cmap_type {+ hayro_cmap::CMapName::IdentityH => Some(CMap::identity_h()),+ hayro_cmap::CMapName::IdentityV => Some(CMap::identity_v()),+ _ => {+ let data = (cmap_resolver)(cmap_type)?;+ let resolver = cmap_resolver.clone();+ CMap::parse(data, move |n| (resolver)(n))+ }+ }+ }+ Object::Stream(s) => {+ let decoded = s.decoded().ok()?;+ let resolver = cmap_resolver.clone();+ CMap::parse(&decoded, move |n| (resolver)(n))+ }+ _ => None,+ }+}diff --git a/vendor/hayro-interpret/src/font/generated/glyph_names.rs b/vendor/hayro-interpret/src/font/generated/glyph_names.rsnew file mode 100644index 000000000..b2dd9ab05--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/glyph_names.rs@@ -0,0 +1,8119 @@+use phf::phf_map;++pub(crate) fn get(name: &str) -> Option<&'static str> {+ GLYPH_NAMES.get(name).copied()+}++pub(crate) fn get_reverse(unicode: char) -> Option<&'static str> {+ REVERSE_GLYPH_NAMES.get(&unicode).copied()+}++static GLYPH_NAMES: phf::Map<&'static str, &'static str> = phf_map! {+ "A" => "\u{0041}",+ "AE" => "\u{00C6}",+ "AEacute" => "\u{01FC}",+ "AEmacron" => "\u{01E2}",+ "AEsmall" => "\u{F7E6}",+ "Aacute" => "\u{00C1}",+ "Aacutesmall" => "\u{F7E1}",+ "Abreve" => "\u{0102}",+ "Abreveacute" => "\u{1EAE}",+ "Abrevecyrillic" => "\u{04D0}",+ "Abrevedotbelow" => "\u{1EB6}",+ "Abrevegrave" => "\u{1EB0}",+ "Abrevehookabove" => "\u{1EB2}",+ "Abrevetilde" => "\u{1EB4}",+ "Acaron" => "\u{01CD}",+ "Acircle" => "\u{24B6}",+ "Acircumflex" => "\u{00C2}",+ "Acircumflexacute" => "\u{1EA4}",+ "Acircumflexdotbelow" => "\u{1EAC}",+ "Acircumflexgrave" => "\u{1EA6}",+ "Acircumflexhookabove" => "\u{1EA8}",+ "Acircumflexsmall" => "\u{F7E2}",+ "Acircumflextilde" => "\u{1EAA}",+ "Acute" => "\u{F6C9}",+ "Acutesmall" => "\u{F7B4}",+ "Acyrillic" => "\u{0410}",+ "Adblgrave" => "\u{0200}",+ "Adieresis" => "\u{00C4}",+ "Adieresiscyrillic" => "\u{04D2}",+ "Adieresismacron" => "\u{01DE}",+ "Adieresissmall" => "\u{F7E4}",+ "Adotbelow" => "\u{1EA0}",+ "Adotmacron" => "\u{01E0}",+ "Agrave" => "\u{00C0}",+ "Agravesmall" => "\u{F7E0}",+ "Ahookabove" => "\u{1EA2}",+ "Aiecyrillic" => "\u{04D4}",+ "Ainvertedbreve" => "\u{0202}",+ "Alpha" => "\u{0391}",+ "Alphatonos" => "\u{0386}",+ "Amacron" => "\u{0100}",+ "Amonospace" => "\u{FF21}",+ "Aogonek" => "\u{0104}",+ "Aring" => "\u{00C5}",+ "Aringacute" => "\u{01FA}",+ "Aringbelow" => "\u{1E00}",+ "Aringsmall" => "\u{F7E5}",+ "Asmall" => "\u{F761}",+ "Atilde" => "\u{00C3}",+ "Atildesmall" => "\u{F7E3}",+ "Aybarmenian" => "\u{0531}",+ "B" => "\u{0042}",+ "Bcircle" => "\u{24B7}",+ "Bdotaccent" => "\u{1E02}",+ "Bdotbelow" => "\u{1E04}",+ "Becyrillic" => "\u{0411}",+ "Benarmenian" => "\u{0532}",+ "Beta" => "\u{0392}",+ "Bhook" => "\u{0181}",+ "Blinebelow" => "\u{1E06}",+ "Bmonospace" => "\u{FF22}",+ "Brevesmall" => "\u{F6F4}",+ "Bsmall" => "\u{F762}",+ "Btopbar" => "\u{0182}",+ "C" => "\u{0043}",+ "Caarmenian" => "\u{053E}",+ "Cacute" => "\u{0106}",+ "Caron" => "\u{F6CA}",+ "Caronsmall" => "\u{F6F5}",+ "Ccaron" => "\u{010C}",+ "Ccedilla" => "\u{00C7}",+ "Ccedillaacute" => "\u{1E08}",+ "Ccedillasmall" => "\u{F7E7}",+ "Ccircle" => "\u{24B8}",+ "Ccircumflex" => "\u{0108}",+ "Cdot" => "\u{010A}",+ "Cdotaccent" => "\u{010A}",+ "Cedillasmall" => "\u{F7B8}",+ "Chaarmenian" => "\u{0549}",+ "Cheabkhasiancyrillic" => "\u{04BC}",+ "Checyrillic" => "\u{0427}",+ "Chedescenderabkhasiancyrillic" => "\u{04BE}",+ "Chedescendercyrillic" => "\u{04B6}",+ "Chedieresiscyrillic" => "\u{04F4}",+ "Cheharmenian" => "\u{0543}",+ "Chekhakassiancyrillic" => "\u{04CB}",+ "Cheverticalstrokecyrillic" => "\u{04B8}",+ "Chi" => "\u{03A7}",+ "Chook" => "\u{0187}",+ "Circumflexsmall" => "\u{F6F6}",+ "Cmonospace" => "\u{FF23}",+ "Coarmenian" => "\u{0551}",+ "Csmall" => "\u{F763}",+ "D" => "\u{0044}",+ "DZ" => "\u{01F1}",+ "DZcaron" => "\u{01C4}",+ "Daarmenian" => "\u{0534}",+ "Dafrican" => "\u{0189}",+ "Dcaron" => "\u{010E}",+ "Dcedilla" => "\u{1E10}",+ "Dcircle" => "\u{24B9}",+ "Dcircumflexbelow" => "\u{1E12}",+ "Dcroat" => "\u{0110}",+ "Ddotaccent" => "\u{1E0A}",+ "Ddotbelow" => "\u{1E0C}",+ "Decyrillic" => "\u{0414}",+ "Deicoptic" => "\u{03EE}",+ "Delta" => "\u{2206}",+ "Deltagreek" => "\u{0394}",+ "Dhook" => "\u{018A}",+ "Dieresis" => "\u{F6CB}",+ "DieresisAcute" => "\u{F6CC}",+ "DieresisGrave" => "\u{F6CD}",+ "Dieresissmall" => "\u{F7A8}",+ "Digammagreek" => "\u{03DC}",+ "Djecyrillic" => "\u{0402}",+ "Dlinebelow" => "\u{1E0E}",+ "Dmonospace" => "\u{FF24}",+ "Dotaccentsmall" => "\u{F6F7}",+ "Dslash" => "\u{0110}",+ "Dsmall" => "\u{F764}",+ "Dtopbar" => "\u{018B}",+ "Dz" => "\u{01F2}",+ "Dzcaron" => "\u{01C5}",+ "Dzeabkhasiancyrillic" => "\u{04E0}",+ "Dzecyrillic" => "\u{0405}",+ "Dzhecyrillic" => "\u{040F}",+ "E" => "\u{0045}",+ "Eacute" => "\u{00C9}",+ "Eacutesmall" => "\u{F7E9}",+ "Ebreve" => "\u{0114}",+ "Ecaron" => "\u{011A}",+ "Ecedillabreve" => "\u{1E1C}",+ "Echarmenian" => "\u{0535}",+ "Ecircle" => "\u{24BA}",+ "Ecircumflex" => "\u{00CA}",+ "Ecircumflexacute" => "\u{1EBE}",+ "Ecircumflexbelow" => "\u{1E18}",+ "Ecircumflexdotbelow" => "\u{1EC6}",+ "Ecircumflexgrave" => "\u{1EC0}",+ "Ecircumflexhookabove" => "\u{1EC2}",+ "Ecircumflexsmall" => "\u{F7EA}",+ "Ecircumflextilde" => "\u{1EC4}",+ "Ecyrillic" => "\u{0404}",+ "Edblgrave" => "\u{0204}",+ "Edieresis" => "\u{00CB}",+ "Edieresissmall" => "\u{F7EB}",+ "Edot" => "\u{0116}",+ "Edotaccent" => "\u{0116}",+ "Edotbelow" => "\u{1EB8}",+ "Efcyrillic" => "\u{0424}",+ "Egrave" => "\u{00C8}",+ "Egravesmall" => "\u{F7E8}",+ "Eharmenian" => "\u{0537}",+ "Ehookabove" => "\u{1EBA}",+ "Eightroman" => "\u{2167}",+ "Einvertedbreve" => "\u{0206}",+ "Eiotifiedcyrillic" => "\u{0464}",+ "Elcyrillic" => "\u{041B}",+ "Elevenroman" => "\u{216A}",+ "Emacron" => "\u{0112}",+ "Emacronacute" => "\u{1E16}",+ "Emacrongrave" => "\u{1E14}",+ "Emcyrillic" => "\u{041C}",+ "Emonospace" => "\u{FF25}",+ "Encyrillic" => "\u{041D}",+ "Endescendercyrillic" => "\u{04A2}",+ "Eng" => "\u{014A}",+ "Enghecyrillic" => "\u{04A4}",+ "Enhookcyrillic" => "\u{04C7}",+ "Eogonek" => "\u{0118}",+ "Eopen" => "\u{0190}",+ "Epsilon" => "\u{0395}",+ "Epsilontonos" => "\u{0388}",+ "Ercyrillic" => "\u{0420}",+ "Ereversed" => "\u{018E}",+ "Ereversedcyrillic" => "\u{042D}",+ "Escyrillic" => "\u{0421}",+ "Esdescendercyrillic" => "\u{04AA}",+ "Esh" => "\u{01A9}",+ "Esmall" => "\u{F765}",+ "Eta" => "\u{0397}",+ "Etarmenian" => "\u{0538}",+ "Etatonos" => "\u{0389}",+ "Eth" => "\u{00D0}",+ "Ethsmall" => "\u{F7F0}",+ "Etilde" => "\u{1EBC}",+ "Etildebelow" => "\u{1E1A}",+ "Euro" => "\u{20AC}",+ "Ezh" => "\u{01B7}",+ "Ezhcaron" => "\u{01EE}",+ "Ezhreversed" => "\u{01B8}",+ "F" => "\u{0046}",+ "Fcircle" => "\u{24BB}",+ "Fdotaccent" => "\u{1E1E}",+ "Feharmenian" => "\u{0556}",+ "Feicoptic" => "\u{03E4}",+ "Fhook" => "\u{0191}",+ "Fitacyrillic" => "\u{0472}",+ "Fiveroman" => "\u{2164}",+ "Fmonospace" => "\u{FF26}",+ "Fourroman" => "\u{2163}",+ "Fsmall" => "\u{F766}",+ "G" => "\u{0047}",+ "GBsquare" => "\u{3387}",+ "Gacute" => "\u{01F4}",+ "Gamma" => "\u{0393}",+ "Gammaafrican" => "\u{0194}",+ "Gangiacoptic" => "\u{03EA}",+ "Gbreve" => "\u{011E}",+ "Gcaron" => "\u{01E6}",+ "Gcedilla" => "\u{0122}",+ "Gcircle" => "\u{24BC}",+ "Gcircumflex" => "\u{011C}",+ "Gcommaaccent" => "\u{0122}",+ "Gdot" => "\u{0120}",+ "Gdotaccent" => "\u{0120}",+ "Gecyrillic" => "\u{0413}",+ "Ghadarmenian" => "\u{0542}",+ "Ghemiddlehookcyrillic" => "\u{0494}",+ "Ghestrokecyrillic" => "\u{0492}",+ "Gheupturncyrillic" => "\u{0490}",+ "Ghook" => "\u{0193}",+ "Gimarmenian" => "\u{0533}",+ "Gjecyrillic" => "\u{0403}",+ "Gmacron" => "\u{1E20}",+ "Gmonospace" => "\u{FF27}",+ "Grave" => "\u{F6CE}",+ "Gravesmall" => "\u{F760}",+ "Gsmall" => "\u{F767}",+ "Gsmallhook" => "\u{029B}",+ "Gstroke" => "\u{01E4}",+ "H" => "\u{0048}",+ "H18533" => "\u{25CF}",+ "H18543" => "\u{25AA}",+ "H18551" => "\u{25AB}",+ "H22073" => "\u{25A1}",+ "HPsquare" => "\u{33CB}",+ "Haabkhasiancyrillic" => "\u{04A8}",+ "Hadescendercyrillic" => "\u{04B2}",+ "Hardsigncyrillic" => "\u{042A}",+ "Hbar" => "\u{0126}",+ "Hbrevebelow" => "\u{1E2A}",+ "Hcedilla" => "\u{1E28}",+ "Hcircle" => "\u{24BD}",+ "Hcircumflex" => "\u{0124}",+ "Hdieresis" => "\u{1E26}",+ "Hdotaccent" => "\u{1E22}",+ "Hdotbelow" => "\u{1E24}",+ "Hmonospace" => "\u{FF28}",+ "Hoarmenian" => "\u{0540}",+ "Horicoptic" => "\u{03E8}",+ "Hsmall" => "\u{F768}",+ "Hungarumlaut" => "\u{F6CF}",+ "Hungarumlautsmall" => "\u{F6F8}",+ "Hzsquare" => "\u{3390}",+ "I" => "\u{0049}",+ "IAcyrillic" => "\u{042F}",+ "IJ" => "\u{0132}",+ "IUcyrillic" => "\u{042E}",+ "Iacute" => "\u{00CD}",+ "Iacutesmall" => "\u{F7ED}",+ "Ibreve" => "\u{012C}",+ "Icaron" => "\u{01CF}",+ "Icircle" => "\u{24BE}",+ "Icircumflex" => "\u{00CE}",+ "Icircumflexsmall" => "\u{F7EE}",+ "Icyrillic" => "\u{0406}",+ "Idblgrave" => "\u{0208}",+ "Idieresis" => "\u{00CF}",+ "Idieresisacute" => "\u{1E2E}",+ "Idieresiscyrillic" => "\u{04E4}",+ "Idieresissmall" => "\u{F7EF}",+ "Idot" => "\u{0130}",+ "Idotaccent" => "\u{0130}",+ "Idotbelow" => "\u{1ECA}",+ "Iebrevecyrillic" => "\u{04D6}",+ "Iecyrillic" => "\u{0415}",+ "Ifraktur" => "\u{2111}",+ "Igrave" => "\u{00CC}",+ "Igravesmall" => "\u{F7EC}",+ "Ihookabove" => "\u{1EC8}",+ "Iicyrillic" => "\u{0418}",+ "Iinvertedbreve" => "\u{020A}",+ "Iishortcyrillic" => "\u{0419}",+ "Imacron" => "\u{012A}",+ "Imacroncyrillic" => "\u{04E2}",+ "Imonospace" => "\u{FF29}",+ "Iniarmenian" => "\u{053B}",+ "Iocyrillic" => "\u{0401}",+ "Iogonek" => "\u{012E}",+ "Iota" => "\u{0399}",+ "Iotaafrican" => "\u{0196}",+ "Iotadieresis" => "\u{03AA}",+ "Iotatonos" => "\u{038A}",+ "Ismall" => "\u{F769}",+ "Istroke" => "\u{0197}",+ "Itilde" => "\u{0128}",+ "Itildebelow" => "\u{1E2C}",+ "Izhitsacyrillic" => "\u{0474}",+ "Izhitsadblgravecyrillic" => "\u{0476}",+ "J" => "\u{004A}",+ "Jaarmenian" => "\u{0541}",+ "Jcircle" => "\u{24BF}",+ "Jcircumflex" => "\u{0134}",+ "Jecyrillic" => "\u{0408}",+ "Jheharmenian" => "\u{054B}",+ "Jmonospace" => "\u{FF2A}",+ "Jsmall" => "\u{F76A}",+ "K" => "\u{004B}",+ "KBsquare" => "\u{3385}",+ "KKsquare" => "\u{33CD}",+ "Kabashkircyrillic" => "\u{04A0}",+ "Kacute" => "\u{1E30}",+ "Kacyrillic" => "\u{041A}",+ "Kadescendercyrillic" => "\u{049A}",+ "Kahookcyrillic" => "\u{04C3}",+ "Kappa" => "\u{039A}",+ "Kastrokecyrillic" => "\u{049E}",+ "Kaverticalstrokecyrillic" => "\u{049C}",+ "Kcaron" => "\u{01E8}",+ "Kcedilla" => "\u{0136}",+ "Kcircle" => "\u{24C0}",+ "Kcommaaccent" => "\u{0136}",+ "Kdotbelow" => "\u{1E32}",+ "Keharmenian" => "\u{0554}",+ "Kenarmenian" => "\u{053F}",+ "Khacyrillic" => "\u{0425}",+ "Kheicoptic" => "\u{03E6}",+ "Khook" => "\u{0198}",+ "Kjecyrillic" => "\u{040C}",+ "Klinebelow" => "\u{1E34}",+ "Kmonospace" => "\u{FF2B}",+ "Koppacyrillic" => "\u{0480}",+ "Koppagreek" => "\u{03DE}",+ "Ksicyrillic" => "\u{046E}",+ "Ksmall" => "\u{F76B}",+ "L" => "\u{004C}",+ "LJ" => "\u{01C7}",+ "LL" => "\u{F6BF}",+ "Lacute" => "\u{0139}",+ "Lambda" => "\u{039B}",+ "Lcaron" => "\u{013D}",+ "Lcedilla" => "\u{013B}",+ "Lcircle" => "\u{24C1}",+ "Lcircumflexbelow" => "\u{1E3C}",+ "Lcommaaccent" => "\u{013B}",+ "Ldot" => "\u{013F}",+ "Ldotaccent" => "\u{013F}",+ "Ldotbelow" => "\u{1E36}",+ "Ldotbelowmacron" => "\u{1E38}",+ "Liwnarmenian" => "\u{053C}",+ "Lj" => "\u{01C8}",+ "Ljecyrillic" => "\u{0409}",+ "Llinebelow" => "\u{1E3A}",+ "Lmonospace" => "\u{FF2C}",+ "Lslash" => "\u{0141}",+ "Lslashsmall" => "\u{F6F9}",+ "Lsmall" => "\u{F76C}",+ "M" => "\u{004D}",+ "MBsquare" => "\u{3386}",+ "Macron" => "\u{F6D0}",+ "Macronsmall" => "\u{F7AF}",+ "Macute" => "\u{1E3E}",+ "Mcircle" => "\u{24C2}",+ "Mdotaccent" => "\u{1E40}",+ "Mdotbelow" => "\u{1E42}",+ "Menarmenian" => "\u{0544}",+ "Mmonospace" => "\u{FF2D}",+ "Msmall" => "\u{F76D}",+ "Mturned" => "\u{019C}",+ "Mu" => "\u{039C}",+ "N" => "\u{004E}",+ "NJ" => "\u{01CA}",+ "Nacute" => "\u{0143}",+ "Ncaron" => "\u{0147}",+ "Ncedilla" => "\u{0145}",+ "Ncircle" => "\u{24C3}",+ "Ncircumflexbelow" => "\u{1E4A}",+ "Ncommaaccent" => "\u{0145}",+ "Ndotaccent" => "\u{1E44}",+ "Ndotbelow" => "\u{1E46}",+ "Nhookleft" => "\u{019D}",+ "Nineroman" => "\u{2168}",+ "Nj" => "\u{01CB}",+ "Njecyrillic" => "\u{040A}",+ "Nlinebelow" => "\u{1E48}",+ "Nmonospace" => "\u{FF2E}",+ "Nowarmenian" => "\u{0546}",+ "Nsmall" => "\u{F76E}",+ "Ntilde" => "\u{00D1}",+ "Ntildesmall" => "\u{F7F1}",+ "Nu" => "\u{039D}",+ "O" => "\u{004F}",+ "OE" => "\u{0152}",+ "OEsmall" => "\u{F6FA}",+ "Oacute" => "\u{00D3}",+ "Oacutesmall" => "\u{F7F3}",+ "Obarredcyrillic" => "\u{04E8}",+ "Obarreddieresiscyrillic" => "\u{04EA}",+ "Obreve" => "\u{014E}",+ "Ocaron" => "\u{01D1}",+ "Ocenteredtilde" => "\u{019F}",+ "Ocircle" => "\u{24C4}",+ "Ocircumflex" => "\u{00D4}",+ "Ocircumflexacute" => "\u{1ED0}",+ "Ocircumflexdotbelow" => "\u{1ED8}",+ "Ocircumflexgrave" => "\u{1ED2}",+ "Ocircumflexhookabove" => "\u{1ED4}",+ "Ocircumflexsmall" => "\u{F7F4}",+ "Ocircumflextilde" => "\u{1ED6}",+ "Ocyrillic" => "\u{041E}",+ "Odblacute" => "\u{0150}",+ "Odblgrave" => "\u{020C}",+ "Odieresis" => "\u{00D6}",+ "Odieresiscyrillic" => "\u{04E6}",+ "Odieresissmall" => "\u{F7F6}",+ "Odotbelow" => "\u{1ECC}",+ "Ogoneksmall" => "\u{F6FB}",+ "Ograve" => "\u{00D2}",+ "Ogravesmall" => "\u{F7F2}",+ "Oharmenian" => "\u{0555}",+ "Ohm" => "\u{2126}",+ "Ohookabove" => "\u{1ECE}",+ "Ohorn" => "\u{01A0}",+ "Ohornacute" => "\u{1EDA}",+ "Ohorndotbelow" => "\u{1EE2}",+ "Ohorngrave" => "\u{1EDC}",+ "Ohornhookabove" => "\u{1EDE}",+ "Ohorntilde" => "\u{1EE0}",+ "Ohungarumlaut" => "\u{0150}",+ "Oi" => "\u{01A2}",+ "Oinvertedbreve" => "\u{020E}",+ "Omacron" => "\u{014C}",+ "Omacronacute" => "\u{1E52}",+ "Omacrongrave" => "\u{1E50}",+ "Omega" => "\u{2126}",+ "Omegacyrillic" => "\u{0460}",+ "Omegagreek" => "\u{03A9}",+ "Omegaroundcyrillic" => "\u{047A}",+ "Omegatitlocyrillic" => "\u{047C}",+ "Omegatonos" => "\u{038F}",+ "Omicron" => "\u{039F}",+ "Omicrontonos" => "\u{038C}",+ "Omonospace" => "\u{FF2F}",+ "Oneroman" => "\u{2160}",+ "Oogonek" => "\u{01EA}",+ "Oogonekmacron" => "\u{01EC}",+ "Oopen" => "\u{0186}",+ "Oslash" => "\u{00D8}",+ "Oslashacute" => "\u{01FE}",+ "Oslashsmall" => "\u{F7F8}",+ "Osmall" => "\u{F76F}",+ "Ostrokeacute" => "\u{01FE}",+ "Otcyrillic" => "\u{047E}",+ "Otilde" => "\u{00D5}",+ "Otildeacute" => "\u{1E4C}",+ "Otildedieresis" => "\u{1E4E}",+ "Otildesmall" => "\u{F7F5}",+ "P" => "\u{0050}",+ "Pacute" => "\u{1E54}",+ "Pcircle" => "\u{24C5}",+ "Pdotaccent" => "\u{1E56}",+ "Pecyrillic" => "\u{041F}",+ "Peharmenian" => "\u{054A}",+ "Pemiddlehookcyrillic" => "\u{04A6}",+ "Phi" => "\u{03A6}",+ "Phook" => "\u{01A4}",+ "Pi" => "\u{03A0}",+ "Piwrarmenian" => "\u{0553}",+ "Pmonospace" => "\u{FF30}",+ "Psi" => "\u{03A8}",+ "Psicyrillic" => "\u{0470}",+ "Psmall" => "\u{F770}",+ "Q" => "\u{0051}",+ "Qcircle" => "\u{24C6}",+ "Qmonospace" => "\u{FF31}",+ "Qsmall" => "\u{F771}",+ "R" => "\u{0052}",+ "Raarmenian" => "\u{054C}",+ "Racute" => "\u{0154}",+ "Rcaron" => "\u{0158}",+ "Rcedilla" => "\u{0156}",+ "Rcircle" => "\u{24C7}",+ "Rcommaaccent" => "\u{0156}",+ "Rdblgrave" => "\u{0210}",+ "Rdotaccent" => "\u{1E58}",+ "Rdotbelow" => "\u{1E5A}",+ "Rdotbelowmacron" => "\u{1E5C}",+ "Reharmenian" => "\u{0550}",+ "Rfraktur" => "\u{211C}",+ "Rho" => "\u{03A1}",+ "Ringsmall" => "\u{F6FC}",+ "Rinvertedbreve" => "\u{0212}",+ "Rlinebelow" => "\u{1E5E}",+ "Rmonospace" => "\u{FF32}",+ "Rsmall" => "\u{F772}",+ "Rsmallinverted" => "\u{0281}",+ "Rsmallinvertedsuperior" => "\u{02B6}",+ "S" => "\u{0053}",+ "SF010000" => "\u{250C}",+ "SF020000" => "\u{2514}",+ "SF030000" => "\u{2510}",+ "SF040000" => "\u{2518}",+ "SF050000" => "\u{253C}",+ "SF060000" => "\u{252C}",+ "SF070000" => "\u{2534}",+ "SF080000" => "\u{251C}",+ "SF090000" => "\u{2524}",+ "SF100000" => "\u{2500}",+ "SF110000" => "\u{2502}",+ "SF190000" => "\u{2561}",+ "SF200000" => "\u{2562}",+ "SF210000" => "\u{2556}",+ "SF220000" => "\u{2555}",+ "SF230000" => "\u{2563}",+ "SF240000" => "\u{2551}",+ "SF250000" => "\u{2557}",+ "SF260000" => "\u{255D}",+ "SF270000" => "\u{255C}",+ "SF280000" => "\u{255B}",+ "SF360000" => "\u{255E}",+ "SF370000" => "\u{255F}",+ "SF380000" => "\u{255A}",+ "SF390000" => "\u{2554}",+ "SF400000" => "\u{2569}",+ "SF410000" => "\u{2566}",+ "SF420000" => "\u{2560}",+ "SF430000" => "\u{2550}",+ "SF440000" => "\u{256C}",+ "SF450000" => "\u{2567}",+ "SF460000" => "\u{2568}",+ "SF470000" => "\u{2564}",+ "SF480000" => "\u{2565}",+ "SF490000" => "\u{2559}",+ "SF500000" => "\u{2558}",+ "SF510000" => "\u{2552}",+ "SF520000" => "\u{2553}",+ "SF530000" => "\u{256B}",+ "SF540000" => "\u{256A}",+ "Sacute" => "\u{015A}",+ "Sacutedotaccent" => "\u{1E64}",+ "Sampigreek" => "\u{03E0}",+ "Scaron" => "\u{0160}",+ "Scarondotaccent" => "\u{1E66}",+ "Scaronsmall" => "\u{F6FD}",+ "Scedilla" => "\u{015E}",+ "Schwa" => "\u{018F}",+ "Schwacyrillic" => "\u{04D8}",+ "Schwadieresiscyrillic" => "\u{04DA}",+ "Scircle" => "\u{24C8}",+ "Scircumflex" => "\u{015C}",+ "Scommaaccent" => "\u{0218}",+ "Sdotaccent" => "\u{1E60}",+ "Sdotbelow" => "\u{1E62}",+ "Sdotbelowdotaccent" => "\u{1E68}",+ "Seharmenian" => "\u{054D}",+ "Sevenroman" => "\u{2166}",+ "Shaarmenian" => "\u{0547}",+ "Shacyrillic" => "\u{0428}",+ "Shchacyrillic" => "\u{0429}",+ "Sheicoptic" => "\u{03E2}",+ "Shhacyrillic" => "\u{04BA}",+ "Shimacoptic" => "\u{03EC}",+ "Sigma" => "\u{03A3}",+ "Sixroman" => "\u{2165}",+ "Smonospace" => "\u{FF33}",+ "Softsigncyrillic" => "\u{042C}",+ "Ssmall" => "\u{F773}",+ "Stigmagreek" => "\u{03DA}",+ "T" => "\u{0054}",+ "Tau" => "\u{03A4}",+ "Tbar" => "\u{0166}",+ "Tcaron" => "\u{0164}",+ "Tcedilla" => "\u{0162}",+ "Tcircle" => "\u{24C9}",+ "Tcircumflexbelow" => "\u{1E70}",+ "Tcommaaccent" => "\u{0162}",+ "Tdotaccent" => "\u{1E6A}",+ "Tdotbelow" => "\u{1E6C}",+ "Tecyrillic" => "\u{0422}",+ "Tedescendercyrillic" => "\u{04AC}",+ "Tenroman" => "\u{2169}",+ "Tetsecyrillic" => "\u{04B4}",+ "Theta" => "\u{0398}",+ "Thook" => "\u{01AC}",+ "Thorn" => "\u{00DE}",+ "Thornsmall" => "\u{F7FE}",+ "Threeroman" => "\u{2162}",+ "Tildesmall" => "\u{F6FE}",+ "Tiwnarmenian" => "\u{054F}",+ "Tlinebelow" => "\u{1E6E}",+ "Tmonospace" => "\u{FF34}",+ "Toarmenian" => "\u{0539}",+ "Tonefive" => "\u{01BC}",+ "Tonesix" => "\u{0184}",+ "Tonetwo" => "\u{01A7}",+ "Tretroflexhook" => "\u{01AE}",+ "Tsecyrillic" => "\u{0426}",+ "Tshecyrillic" => "\u{040B}",+ "Tsmall" => "\u{F774}",+ "Twelveroman" => "\u{216B}",+ "Tworoman" => "\u{2161}",+ "U" => "\u{0055}",+ "Uacute" => "\u{00DA}",+ "Uacutesmall" => "\u{F7FA}",+ "Ubreve" => "\u{016C}",+ "Ucaron" => "\u{01D3}",+ "Ucircle" => "\u{24CA}",+ "Ucircumflex" => "\u{00DB}",+ "Ucircumflexbelow" => "\u{1E76}",+ "Ucircumflexsmall" => "\u{F7FB}",+ "Ucyrillic" => "\u{0423}",+ "Udblacute" => "\u{0170}",+ "Udblgrave" => "\u{0214}",+ "Udieresis" => "\u{00DC}",+ "Udieresisacute" => "\u{01D7}",+ "Udieresisbelow" => "\u{1E72}",+ "Udieresiscaron" => "\u{01D9}",+ "Udieresiscyrillic" => "\u{04F0}",+ "Udieresisgrave" => "\u{01DB}",+ "Udieresismacron" => "\u{01D5}",+ "Udieresissmall" => "\u{F7FC}",+ "Udotbelow" => "\u{1EE4}",+ "Ugrave" => "\u{00D9}",+ "Ugravesmall" => "\u{F7F9}",+ "Uhookabove" => "\u{1EE6}",+ "Uhorn" => "\u{01AF}",+ "Uhornacute" => "\u{1EE8}",+ "Uhorndotbelow" => "\u{1EF0}",+ "Uhorngrave" => "\u{1EEA}",+ "Uhornhookabove" => "\u{1EEC}",+ "Uhorntilde" => "\u{1EEE}",+ "Uhungarumlaut" => "\u{0170}",+ "Uhungarumlautcyrillic" => "\u{04F2}",+ "Uinvertedbreve" => "\u{0216}",+ "Ukcyrillic" => "\u{0478}",+ "Umacron" => "\u{016A}",+ "Umacroncyrillic" => "\u{04EE}",+ "Umacrondieresis" => "\u{1E7A}",+ "Umonospace" => "\u{FF35}",+ "Uogonek" => "\u{0172}",+ "Upsilon" => "\u{03A5}",+ "Upsilon1" => "\u{03D2}",+ "Upsilonacutehooksymbolgreek" => "\u{03D3}",+ "Upsilonafrican" => "\u{01B1}",+ "Upsilondieresis" => "\u{03AB}",+ "Upsilondieresishooksymbolgreek" => "\u{03D4}",+ "Upsilonhooksymbol" => "\u{03D2}",+ "Upsilontonos" => "\u{038E}",+ "Uring" => "\u{016E}",+ "Ushortcyrillic" => "\u{040E}",+ "Usmall" => "\u{F775}",+ "Ustraightcyrillic" => "\u{04AE}",+ "Ustraightstrokecyrillic" => "\u{04B0}",+ "Utilde" => "\u{0168}",+ "Utildeacute" => "\u{1E78}",+ "Utildebelow" => "\u{1E74}",+ "V" => "\u{0056}",+ "Vcircle" => "\u{24CB}",+ "Vdotbelow" => "\u{1E7E}",+ "Vecyrillic" => "\u{0412}",+ "Vewarmenian" => "\u{054E}",+ "Vhook" => "\u{01B2}",+ "Vmonospace" => "\u{FF36}",+ "Voarmenian" => "\u{0548}",+ "Vsmall" => "\u{F776}",+ "Vtilde" => "\u{1E7C}",+ "W" => "\u{0057}",+ "Wacute" => "\u{1E82}",+ "Wcircle" => "\u{24CC}",+ "Wcircumflex" => "\u{0174}",+ "Wdieresis" => "\u{1E84}",+ "Wdotaccent" => "\u{1E86}",+ "Wdotbelow" => "\u{1E88}",+ "Wgrave" => "\u{1E80}",+ "Wmonospace" => "\u{FF37}",+ "Wsmall" => "\u{F777}",+ "X" => "\u{0058}",+ "Xcircle" => "\u{24CD}",+ "Xdieresis" => "\u{1E8C}",+ "Xdotaccent" => "\u{1E8A}",+ "Xeharmenian" => "\u{053D}",+ "Xi" => "\u{039E}",+ "Xmonospace" => "\u{FF38}",+ "Xsmall" => "\u{F778}",+ "Y" => "\u{0059}",+ "Yacute" => "\u{00DD}",+ "Yacutesmall" => "\u{F7FD}",+ "Yatcyrillic" => "\u{0462}",+ "Ycircle" => "\u{24CE}",+ "Ycircumflex" => "\u{0176}",+ "Ydieresis" => "\u{0178}",+ "Ydieresissmall" => "\u{F7FF}",+ "Ydotaccent" => "\u{1E8E}",+ "Ydotbelow" => "\u{1EF4}",+ "Yericyrillic" => "\u{042B}",+ "Yerudieresiscyrillic" => "\u{04F8}",+ "Ygrave" => "\u{1EF2}",+ "Yhook" => "\u{01B3}",+ "Yhookabove" => "\u{1EF6}",+ "Yiarmenian" => "\u{0545}",+ "Yicyrillic" => "\u{0407}",+ "Yiwnarmenian" => "\u{0552}",+ "Ymonospace" => "\u{FF39}",+ "Ysmall" => "\u{F779}",+ "Ytilde" => "\u{1EF8}",+ "Yusbigcyrillic" => "\u{046A}",+ "Yusbigiotifiedcyrillic" => "\u{046C}",+ "Yuslittlecyrillic" => "\u{0466}",+ "Yuslittleiotifiedcyrillic" => "\u{0468}",+ "Z" => "\u{005A}",+ "Zaarmenian" => "\u{0536}",+ "Zacute" => "\u{0179}",+ "Zcaron" => "\u{017D}",+ "Zcaronsmall" => "\u{F6FF}",+ "Zcircle" => "\u{24CF}",+ "Zcircumflex" => "\u{1E90}",+ "Zdot" => "\u{017B}",+ "Zdotaccent" => "\u{017B}",+ "Zdotbelow" => "\u{1E92}",+ "Zecyrillic" => "\u{0417}",+ "Zedescendercyrillic" => "\u{0498}",+ "Zedieresiscyrillic" => "\u{04DE}",+ "Zeta" => "\u{0396}",+ "Zhearmenian" => "\u{053A}",+ "Zhebrevecyrillic" => "\u{04C1}",+ "Zhecyrillic" => "\u{0416}",+ "Zhedescendercyrillic" => "\u{0496}",+ "Zhedieresiscyrillic" => "\u{04DC}",+ "Zlinebelow" => "\u{1E94}",+ "Zmonospace" => "\u{FF3A}",+ "Zsmall" => "\u{F77A}",+ "Zstroke" => "\u{01B5}",+ "a" => "\u{0061}",+ "aabengali" => "\u{0986}",+ "aacute" => "\u{00E1}",+ "aadeva" => "\u{0906}",+ "aagujarati" => "\u{0A86}",+ "aagurmukhi" => "\u{0A06}",+ "aamatragurmukhi" => "\u{0A3E}",+ "aarusquare" => "\u{3303}",+ "aavowelsignbengali" => "\u{09BE}",+ "aavowelsigndeva" => "\u{093E}",+ "aavowelsigngujarati" => "\u{0ABE}",+ "abbreviationmarkarmenian" => "\u{055F}",+ "abbreviationsigndeva" => "\u{0970}",+ "abengali" => "\u{0985}",+ "abopomofo" => "\u{311A}",+ "abreve" => "\u{0103}",+ "abreveacute" => "\u{1EAF}",+ "abrevecyrillic" => "\u{04D1}",+ "abrevedotbelow" => "\u{1EB7}",+ "abrevegrave" => "\u{1EB1}",+ "abrevehookabove" => "\u{1EB3}",+ "abrevetilde" => "\u{1EB5}",+ "acaron" => "\u{01CE}",+ "acircle" => "\u{24D0}",+ "acircumflex" => "\u{00E2}",+ "acircumflexacute" => "\u{1EA5}",+ "acircumflexdotbelow" => "\u{1EAD}",+ "acircumflexgrave" => "\u{1EA7}",+ "acircumflexhookabove" => "\u{1EA9}",+ "acircumflextilde" => "\u{1EAB}",+ "acute" => "\u{00B4}",+ "acutebelowcmb" => "\u{0317}",+ "acutecmb" => "\u{0301}",+ "acutecomb" => "\u{0301}",+ "acutedeva" => "\u{0954}",+ "acutelowmod" => "\u{02CF}",+ "acutetonecmb" => "\u{0341}",+ "acyrillic" => "\u{0430}",+ "adblgrave" => "\u{0201}",+ "addakgurmukhi" => "\u{0A71}",+ "adeva" => "\u{0905}",+ "adieresis" => "\u{00E4}",+ "adieresiscyrillic" => "\u{04D3}",+ "adieresismacron" => "\u{01DF}",+ "adotbelow" => "\u{1EA1}",+ "adotmacron" => "\u{01E1}",+ "ae" => "\u{00E6}",+ "aeacute" => "\u{01FD}",+ "aekorean" => "\u{3150}",+ "aemacron" => "\u{01E3}",+ "afii00208" => "\u{2015}",+ "afii08941" => "\u{20A4}",+ "afii10017" => "\u{0410}",+ "afii10018" => "\u{0411}",+ "afii10019" => "\u{0412}",+ "afii10020" => "\u{0413}",+ "afii10021" => "\u{0414}",+ "afii10022" => "\u{0415}",+ "afii10023" => "\u{0401}",+ "afii10024" => "\u{0416}",+ "afii10025" => "\u{0417}",+ "afii10026" => "\u{0418}",+ "afii10027" => "\u{0419}",+ "afii10028" => "\u{041A}",+ "afii10029" => "\u{041B}",+ "afii10030" => "\u{041C}",+ "afii10031" => "\u{041D}",+ "afii10032" => "\u{041E}",+ "afii10033" => "\u{041F}",+ "afii10034" => "\u{0420}",+ "afii10035" => "\u{0421}",+ "afii10036" => "\u{0422}",+ "afii10037" => "\u{0423}",+ "afii10038" => "\u{0424}",+ "afii10039" => "\u{0425}",+ "afii10040" => "\u{0426}",+ "afii10041" => "\u{0427}",+ "afii10042" => "\u{0428}",+ "afii10043" => "\u{0429}",+ "afii10044" => "\u{042A}",+ "afii10045" => "\u{042B}",+ "afii10046" => "\u{042C}",+ "afii10047" => "\u{042D}",+ "afii10048" => "\u{042E}",+ "afii10049" => "\u{042F}",+ "afii10050" => "\u{0490}",+ "afii10051" => "\u{0402}",+ "afii10052" => "\u{0403}",+ "afii10053" => "\u{0404}",+ "afii10054" => "\u{0405}",+ "afii10055" => "\u{0406}",+ "afii10056" => "\u{0407}",+ "afii10057" => "\u{0408}",+ "afii10058" => "\u{0409}",+ "afii10059" => "\u{040A}",+ "afii10060" => "\u{040B}",+ "afii10061" => "\u{040C}",+ "afii10062" => "\u{040E}",+ "afii10063" => "\u{F6C4}",+ "afii10064" => "\u{F6C5}",+ "afii10065" => "\u{0430}",+ "afii10066" => "\u{0431}",+ "afii10067" => "\u{0432}",+ "afii10068" => "\u{0433}",+ "afii10069" => "\u{0434}",+ "afii10070" => "\u{0435}",+ "afii10071" => "\u{0451}",+ "afii10072" => "\u{0436}",+ "afii10073" => "\u{0437}",+ "afii10074" => "\u{0438}",+ "afii10075" => "\u{0439}",+ "afii10076" => "\u{043A}",+ "afii10077" => "\u{043B}",+ "afii10078" => "\u{043C}",+ "afii10079" => "\u{043D}",+ "afii10080" => "\u{043E}",+ "afii10081" => "\u{043F}",+ "afii10082" => "\u{0440}",+ "afii10083" => "\u{0441}",+ "afii10084" => "\u{0442}",+ "afii10085" => "\u{0443}",+ "afii10086" => "\u{0444}",+ "afii10087" => "\u{0445}",+ "afii10088" => "\u{0446}",+ "afii10089" => "\u{0447}",+ "afii10090" => "\u{0448}",+ "afii10091" => "\u{0449}",+ "afii10092" => "\u{044A}",+ "afii10093" => "\u{044B}",+ "afii10094" => "\u{044C}",+ "afii10095" => "\u{044D}",+ "afii10096" => "\u{044E}",+ "afii10097" => "\u{044F}",+ "afii10098" => "\u{0491}",+ "afii10099" => "\u{0452}",+ "afii10100" => "\u{0453}",+ "afii10101" => "\u{0454}",+ "afii10102" => "\u{0455}",+ "afii10103" => "\u{0456}",+ "afii10104" => "\u{0457}",+ "afii10105" => "\u{0458}",+ "afii10106" => "\u{0459}",+ "afii10107" => "\u{045A}",+ "afii10108" => "\u{045B}",+ "afii10109" => "\u{045C}",+ "afii10110" => "\u{045E}",+ "afii10145" => "\u{040F}",+ "afii10146" => "\u{0462}",+ "afii10147" => "\u{0472}",+ "afii10148" => "\u{0474}",+ "afii10192" => "\u{F6C6}",+ "afii10193" => "\u{045F}",+ "afii10194" => "\u{0463}",+ "afii10195" => "\u{0473}",+ "afii10196" => "\u{0475}",+ "afii10831" => "\u{F6C7}",+ "afii10832" => "\u{F6C8}",+ "afii10846" => "\u{04D9}",+ "afii299" => "\u{200E}",+ "afii300" => "\u{200F}",+ "afii301" => "\u{200D}",+ "afii57381" => "\u{066A}",+ "afii57388" => "\u{060C}",+ "afii57392" => "\u{0660}",+ "afii57393" => "\u{0661}",+ "afii57394" => "\u{0662}",+ "afii57395" => "\u{0663}",+ "afii57396" => "\u{0664}",+ "afii57397" => "\u{0665}",+ "afii57398" => "\u{0666}",+ "afii57399" => "\u{0667}",+ "afii57400" => "\u{0668}",+ "afii57401" => "\u{0669}",+ "afii57403" => "\u{061B}",+ "afii57407" => "\u{061F}",+ "afii57409" => "\u{0621}",+ "afii57410" => "\u{0622}",+ "afii57411" => "\u{0623}",+ "afii57412" => "\u{0624}",+ "afii57413" => "\u{0625}",+ "afii57414" => "\u{0626}",+ "afii57415" => "\u{0627}",+ "afii57416" => "\u{0628}",+ "afii57417" => "\u{0629}",+ "afii57418" => "\u{062A}",+ "afii57419" => "\u{062B}",+ "afii57420" => "\u{062C}",+ "afii57421" => "\u{062D}",+ "afii57422" => "\u{062E}",+ "afii57423" => "\u{062F}",+ "afii57424" => "\u{0630}",+ "afii57425" => "\u{0631}",+ "afii57426" => "\u{0632}",+ "afii57427" => "\u{0633}",+ "afii57428" => "\u{0634}",+ "afii57429" => "\u{0635}",+ "afii57430" => "\u{0636}",+ "afii57431" => "\u{0637}",+ "afii57432" => "\u{0638}",+ "afii57433" => "\u{0639}",+ "afii57434" => "\u{063A}",+ "afii57440" => "\u{0640}",+ "afii57441" => "\u{0641}",+ "afii57442" => "\u{0642}",+ "afii57443" => "\u{0643}",+ "afii57444" => "\u{0644}",+ "afii57445" => "\u{0645}",+ "afii57446" => "\u{0646}",+ "afii57448" => "\u{0648}",+ "afii57449" => "\u{0649}",+ "afii57450" => "\u{064A}",+ "afii57451" => "\u{064B}",+ "afii57452" => "\u{064C}",+ "afii57453" => "\u{064D}",+ "afii57454" => "\u{064E}",+ "afii57455" => "\u{064F}",+ "afii57456" => "\u{0650}",+ "afii57457" => "\u{0651}",+ "afii57458" => "\u{0652}",+ "afii57470" => "\u{0647}",+ "afii57505" => "\u{06A4}",+ "afii57506" => "\u{067E}",+ "afii57507" => "\u{0686}",+ "afii57508" => "\u{0698}",+ "afii57509" => "\u{06AF}",+ "afii57511" => "\u{0679}",+ "afii57512" => "\u{0688}",+ "afii57513" => "\u{0691}",+ "afii57514" => "\u{06BA}",+ "afii57519" => "\u{06D2}",+ "afii57534" => "\u{06D5}",+ "afii57636" => "\u{20AA}",+ "afii57645" => "\u{05BE}",+ "afii57658" => "\u{05C3}",+ "afii57664" => "\u{05D0}",+ "afii57665" => "\u{05D1}",+ "afii57666" => "\u{05D2}",+ "afii57667" => "\u{05D3}",+ "afii57668" => "\u{05D4}",+ "afii57669" => "\u{05D5}",+ "afii57670" => "\u{05D6}",+ "afii57671" => "\u{05D7}",+ "afii57672" => "\u{05D8}",+ "afii57673" => "\u{05D9}",+ "afii57674" => "\u{05DA}",+ "afii57675" => "\u{05DB}",+ "afii57676" => "\u{05DC}",+ "afii57677" => "\u{05DD}",+ "afii57678" => "\u{05DE}",+ "afii57679" => "\u{05DF}",+ "afii57680" => "\u{05E0}",+ "afii57681" => "\u{05E1}",+ "afii57682" => "\u{05E2}",+ "afii57683" => "\u{05E3}",+ "afii57684" => "\u{05E4}",+ "afii57685" => "\u{05E5}",+ "afii57686" => "\u{05E6}",+ "afii57687" => "\u{05E7}",+ "afii57688" => "\u{05E8}",+ "afii57689" => "\u{05E9}",+ "afii57690" => "\u{05EA}",+ "afii57694" => "\u{FB2A}",+ "afii57695" => "\u{FB2B}",+ "afii57700" => "\u{FB4B}",+ "afii57705" => "\u{FB1F}",+ "afii57716" => "\u{05F0}",+ "afii57717" => "\u{05F1}",+ "afii57718" => "\u{05F2}",+ "afii57723" => "\u{FB35}",+ "afii57793" => "\u{05B4}",+ "afii57794" => "\u{05B5}",+ "afii57795" => "\u{05B6}",+ "afii57796" => "\u{05BB}",+ "afii57797" => "\u{05B8}",+ "afii57798" => "\u{05B7}",+ "afii57799" => "\u{05B0}",+ "afii57800" => "\u{05B2}",+ "afii57801" => "\u{05B1}",+ "afii57802" => "\u{05B3}",+ "afii57803" => "\u{05C2}",+ "afii57804" => "\u{05C1}",+ "afii57806" => "\u{05B9}",+ "afii57807" => "\u{05BC}",+ "afii57839" => "\u{05BD}",+ "afii57841" => "\u{05BF}",+ "afii57842" => "\u{05C0}",+ "afii57929" => "\u{02BC}",+ "afii61248" => "\u{2105}",+ "afii61289" => "\u{2113}",+ "afii61352" => "\u{2116}",+ "afii61573" => "\u{202C}",+ "afii61574" => "\u{202D}",+ "afii61575" => "\u{202E}",+ "afii61664" => "\u{200C}",+ "afii63167" => "\u{066D}",+ "afii64937" => "\u{02BD}",+ "agrave" => "\u{00E0}",+ "agujarati" => "\u{0A85}",+ "agurmukhi" => "\u{0A05}",+ "ahiragana" => "\u{3042}",+ "ahookabove" => "\u{1EA3}",+ "aibengali" => "\u{0990}",+ "aibopomofo" => "\u{311E}",+ "aideva" => "\u{0910}",+ "aiecyrillic" => "\u{04D5}",+ "aigujarati" => "\u{0A90}",+ "aigurmukhi" => "\u{0A10}",+ "aimatragurmukhi" => "\u{0A48}",+ "ainarabic" => "\u{0639}",+ "ainfinalarabic" => "\u{FECA}",+ "aininitialarabic" => "\u{FECB}",+ "ainmedialarabic" => "\u{FECC}",+ "ainvertedbreve" => "\u{0203}",+ "aivowelsignbengali" => "\u{09C8}",+ "aivowelsigndeva" => "\u{0948}",+ "aivowelsigngujarati" => "\u{0AC8}",+ "akatakana" => "\u{30A2}",+ "akatakanahalfwidth" => "\u{FF71}",+ "akorean" => "\u{314F}",+ "alef" => "\u{05D0}",+ "alefarabic" => "\u{0627}",+ "alefdageshhebrew" => "\u{FB30}",+ "aleffinalarabic" => "\u{FE8E}",+ "alefhamzaabovearabic" => "\u{0623}",+ "alefhamzaabovefinalarabic" => "\u{FE84}",+ "alefhamzabelowarabic" => "\u{0625}",+ "alefhamzabelowfinalarabic" => "\u{FE88}",+ "alefhebrew" => "\u{05D0}",+ "aleflamedhebrew" => "\u{FB4F}",+ "alefmaddaabovearabic" => "\u{0622}",+ "alefmaddaabovefinalarabic" => "\u{FE82}",+ "alefmaksuraarabic" => "\u{0649}",+ "alefmaksurafinalarabic" => "\u{FEF0}",+ "alefmaksurainitialarabic" => "\u{FEF3}",+ "alefmaksuramedialarabic" => "\u{FEF4}",+ "alefpatahhebrew" => "\u{FB2E}",+ "alefqamatshebrew" => "\u{FB2F}",+ "aleph" => "\u{2135}",+ "allequal" => "\u{224C}",+ "alpha" => "\u{03B1}",+ "alphatonos" => "\u{03AC}",+ "amacron" => "\u{0101}",+ "amonospace" => "\u{FF41}",+ "ampersand" => "\u{0026}",+ "ampersandmonospace" => "\u{FF06}",+ "ampersandsmall" => "\u{F726}",+ "amsquare" => "\u{33C2}",+ "anbopomofo" => "\u{3122}",+ "angbopomofo" => "\u{3124}",+ "angkhankhuthai" => "\u{0E5A}",+ "angle" => "\u{2220}",+ "anglebracketleft" => "\u{3008}",+ "anglebracketleftvertical" => "\u{FE3F}",+ "anglebracketright" => "\u{3009}",+ "anglebracketrightvertical" => "\u{FE40}",+ "angleleft" => "\u{2329}",+ "angleright" => "\u{232A}",+ "angstrom" => "\u{212B}",+ "anoteleia" => "\u{0387}",+ "anudattadeva" => "\u{0952}",+ "anusvarabengali" => "\u{0982}",+ "anusvaradeva" => "\u{0902}",+ "anusvaragujarati" => "\u{0A82}",+ "aogonek" => "\u{0105}",+ "apaatosquare" => "\u{3300}",+ "aparen" => "\u{249C}",+ "apostrophearmenian" => "\u{055A}",+ "apostrophemod" => "\u{02BC}",+ "apple" => "\u{F8FF}",+ "approaches" => "\u{2250}",+ "approxequal" => "\u{2248}",+ "approxequalorimage" => "\u{2252}",+ "approximatelyequal" => "\u{2245}",+ "araeaekorean" => "\u{318E}",+ "araeakorean" => "\u{318D}",+ "arc" => "\u{2312}",+ "arighthalfring" => "\u{1E9A}",+ "aring" => "\u{00E5}",+ "aringacute" => "\u{01FB}",+ "aringbelow" => "\u{1E01}",+ "arrowboth" => "\u{2194}",+ "arrowdashdown" => "\u{21E3}",+ "arrowdashleft" => "\u{21E0}",+ "arrowdashright" => "\u{21E2}",+ "arrowdashup" => "\u{21E1}",+ "arrowdblboth" => "\u{21D4}",+ "arrowdbldown" => "\u{21D3}",+ "arrowdblleft" => "\u{21D0}",+ "arrowdblright" => "\u{21D2}",+ "arrowdblup" => "\u{21D1}",+ "arrowdown" => "\u{2193}",+ "arrowdownleft" => "\u{2199}",+ "arrowdownright" => "\u{2198}",+ "arrowdownwhite" => "\u{21E9}",+ "arrowheaddownmod" => "\u{02C5}",+ "arrowheadleftmod" => "\u{02C2}",+ "arrowheadrightmod" => "\u{02C3}",+ "arrowheadupmod" => "\u{02C4}",+ "arrowhorizex" => "\u{F8E7}",+ "arrowleft" => "\u{2190}",+ "arrowleftdbl" => "\u{21D0}",+ "arrowleftdblstroke" => "\u{21CD}",+ "arrowleftoverright" => "\u{21C6}",+ "arrowleftwhite" => "\u{21E6}",+ "arrowright" => "\u{2192}",+ "arrowrightdblstroke" => "\u{21CF}",+ "arrowrightheavy" => "\u{279E}",+ "arrowrightoverleft" => "\u{21C4}",+ "arrowrightwhite" => "\u{21E8}",+ "arrowtableft" => "\u{21E4}",+ "arrowtabright" => "\u{21E5}",+ "arrowup" => "\u{2191}",+ "arrowupdn" => "\u{2195}",+ "arrowupdnbse" => "\u{21A8}",+ "arrowupdownbase" => "\u{21A8}",+ "arrowupleft" => "\u{2196}",+ "arrowupleftofdown" => "\u{21C5}",+ "arrowupright" => "\u{2197}",+ "arrowupwhite" => "\u{21E7}",+ "arrowvertex" => "\u{F8E6}",+ "asciicircum" => "\u{005E}",+ "asciicircummonospace" => "\u{FF3E}",+ "asciitilde" => "\u{007E}",+ "asciitildemonospace" => "\u{FF5E}",+ "ascript" => "\u{0251}",+ "ascriptturned" => "\u{0252}",+ "asmallhiragana" => "\u{3041}",+ "asmallkatakana" => "\u{30A1}",+ "asmallkatakanahalfwidth" => "\u{FF67}",+ "asterisk" => "\u{002A}",+ "asteriskaltonearabic" => "\u{066D}",+ "asteriskarabic" => "\u{066D}",+ "asteriskmath" => "\u{2217}",+ "asteriskmonospace" => "\u{FF0A}",+ "asterisksmall" => "\u{FE61}",+ "asterism" => "\u{2042}",+ "asuperior" => "\u{F6E9}",+ "asymptoticallyequal" => "\u{2243}",+ "at" => "\u{0040}",+ "atilde" => "\u{00E3}",+ "atmonospace" => "\u{FF20}",+ "atsmall" => "\u{FE6B}",+ "aturned" => "\u{0250}",+ "aubengali" => "\u{0994}",+ "aubopomofo" => "\u{3120}",+ "audeva" => "\u{0914}",+ "augujarati" => "\u{0A94}",+ "augurmukhi" => "\u{0A14}",+ "aulengthmarkbengali" => "\u{09D7}",+ "aumatragurmukhi" => "\u{0A4C}",+ "auvowelsignbengali" => "\u{09CC}",+ "auvowelsigndeva" => "\u{094C}",+ "auvowelsigngujarati" => "\u{0ACC}",+ "avagrahadeva" => "\u{093D}",+ "aybarmenian" => "\u{0561}",+ "ayin" => "\u{05E2}",+ "ayinaltonehebrew" => "\u{FB20}",+ "ayinhebrew" => "\u{05E2}",+ "b" => "\u{0062}",+ "babengali" => "\u{09AC}",+ "backslash" => "\u{005C}",+ "backslashmonospace" => "\u{FF3C}",+ "badeva" => "\u{092C}",+ "bagujarati" => "\u{0AAC}",+ "bagurmukhi" => "\u{0A2C}",+ "bahiragana" => "\u{3070}",+ "bahtthai" => "\u{0E3F}",+ "bakatakana" => "\u{30D0}",+ "bar" => "\u{007C}",+ "barmonospace" => "\u{FF5C}",+ "bbopomofo" => "\u{3105}",+ "bcircle" => "\u{24D1}",+ "bdotaccent" => "\u{1E03}",+ "bdotbelow" => "\u{1E05}",+ "beamedsixteenthnotes" => "\u{266C}",+ "because" => "\u{2235}",+ "becyrillic" => "\u{0431}",+ "beharabic" => "\u{0628}",+ "behfinalarabic" => "\u{FE90}",+ "behinitialarabic" => "\u{FE91}",+ "behiragana" => "\u{3079}",+ "behmedialarabic" => "\u{FE92}",+ "behmeeminitialarabic" => "\u{FC9F}",+ "behmeemisolatedarabic" => "\u{FC08}",+ "behnoonfinalarabic" => "\u{FC6D}",+ "bekatakana" => "\u{30D9}",+ "benarmenian" => "\u{0562}",+ "bet" => "\u{05D1}",+ "beta" => "\u{03B2}",+ "betasymbolgreek" => "\u{03D0}",+ "betdagesh" => "\u{FB31}",+ "betdageshhebrew" => "\u{FB31}",+ "bethebrew" => "\u{05D1}",+ "betrafehebrew" => "\u{FB4C}",+ "bhabengali" => "\u{09AD}",+ "bhadeva" => "\u{092D}",+ "bhagujarati" => "\u{0AAD}",+ "bhagurmukhi" => "\u{0A2D}",+ "bhook" => "\u{0253}",+ "bihiragana" => "\u{3073}",+ "bikatakana" => "\u{30D3}",+ "bilabialclick" => "\u{0298}",+ "bindigurmukhi" => "\u{0A02}",+ "birusquare" => "\u{3331}",+ "blackcircle" => "\u{25CF}",+ "blackdiamond" => "\u{25C6}",+ "blackdownpointingtriangle" => "\u{25BC}",+ "blackleftpointingpointer" => "\u{25C4}",+ "blackleftpointingtriangle" => "\u{25C0}",+ "blacklenticularbracketleft" => "\u{3010}",+ "blacklenticularbracketleftvertical" => "\u{FE3B}",+ "blacklenticularbracketright" => "\u{3011}",+ "blacklenticularbracketrightvertical" => "\u{FE3C}",+ "blacklowerlefttriangle" => "\u{25E3}",+ "blacklowerrighttriangle" => "\u{25E2}",+ "blackrectangle" => "\u{25AC}",+ "blackrightpointingpointer" => "\u{25BA}",+ "blackrightpointingtriangle" => "\u{25B6}",+ "blacksmallsquare" => "\u{25AA}",+ "blacksmilingface" => "\u{263B}",+ "blacksquare" => "\u{25A0}",+ "blackstar" => "\u{2605}",+ "blackupperlefttriangle" => "\u{25E4}",+ "blackupperrighttriangle" => "\u{25E5}",+ "blackuppointingsmalltriangle" => "\u{25B4}",+ "blackuppointingtriangle" => "\u{25B2}",+ "blank" => "\u{2423}",+ "blinebelow" => "\u{1E07}",+ "block" => "\u{2588}",+ "bmonospace" => "\u{FF42}",+ "bobaimaithai" => "\u{0E1A}",+ "bohiragana" => "\u{307C}",+ "bokatakana" => "\u{30DC}",+ "bparen" => "\u{249D}",+ "bqsquare" => "\u{33C3}",+ "braceex" => "\u{F8F4}",+ "braceleft" => "\u{007B}",+ "braceleftbt" => "\u{F8F3}",+ "braceleftmid" => "\u{F8F2}",+ "braceleftmonospace" => "\u{FF5B}",+ "braceleftsmall" => "\u{FE5B}",+ "bracelefttp" => "\u{F8F1}",+ "braceleftvertical" => "\u{FE37}",+ "braceright" => "\u{007D}",+ "bracerightbt" => "\u{F8FE}",+ "bracerightmid" => "\u{F8FD}",+ "bracerightmonospace" => "\u{FF5D}",+ "bracerightsmall" => "\u{FE5C}",+ "bracerighttp" => "\u{F8FC}",+ "bracerightvertical" => "\u{FE38}",+ "bracketleft" => "\u{005B}",+ "bracketleftbt" => "\u{F8F0}",+ "bracketleftex" => "\u{F8EF}",+ "bracketleftmonospace" => "\u{FF3B}",+ "bracketlefttp" => "\u{F8EE}",+ "bracketright" => "\u{005D}",+ "bracketrightbt" => "\u{F8FB}",+ "bracketrightex" => "\u{F8FA}",+ "bracketrightmonospace" => "\u{FF3D}",+ "bracketrighttp" => "\u{F8F9}",+ "breve" => "\u{02D8}",+ "brevebelowcmb" => "\u{032E}",+ "brevecmb" => "\u{0306}",+ "breveinvertedbelowcmb" => "\u{032F}",+ "breveinvertedcmb" => "\u{0311}",+ "breveinverteddoublecmb" => "\u{0361}",+ "bridgebelowcmb" => "\u{032A}",+ "bridgeinvertedbelowcmb" => "\u{033A}",+ "brokenbar" => "\u{00A6}",+ "bstroke" => "\u{0180}",+ "bsuperior" => "\u{F6EA}",+ "btopbar" => "\u{0183}",+ "buhiragana" => "\u{3076}",+ "bukatakana" => "\u{30D6}",+ "bullet" => "\u{2022}",+ "bulletinverse" => "\u{25D8}",+ "bulletoperator" => "\u{2219}",+ "bullseye" => "\u{25CE}",+ "c" => "\u{0063}",+ "caarmenian" => "\u{056E}",+ "cabengali" => "\u{099A}",+ "cacute" => "\u{0107}",+ "cadeva" => "\u{091A}",+ "cagujarati" => "\u{0A9A}",+ "cagurmukhi" => "\u{0A1A}",+ "calsquare" => "\u{3388}",+ "candrabindubengali" => "\u{0981}",+ "candrabinducmb" => "\u{0310}",+ "candrabindudeva" => "\u{0901}",+ "candrabindugujarati" => "\u{0A81}",+ "capslock" => "\u{21EA}",+ "careof" => "\u{2105}",+ "caron" => "\u{02C7}",+ "caronbelowcmb" => "\u{032C}",+ "caroncmb" => "\u{030C}",+ "carriagereturn" => "\u{21B5}",+ "cbopomofo" => "\u{3118}",+ "ccaron" => "\u{010D}",+ "ccedilla" => "\u{00E7}",+ "ccedillaacute" => "\u{1E09}",+ "ccircle" => "\u{24D2}",+ "ccircumflex" => "\u{0109}",+ "ccurl" => "\u{0255}",+ "cdot" => "\u{010B}",+ "cdotaccent" => "\u{010B}",+ "cdsquare" => "\u{33C5}",+ "cedilla" => "\u{00B8}",+ "cedillacmb" => "\u{0327}",+ "cent" => "\u{00A2}",+ "centigrade" => "\u{2103}",+ "centinferior" => "\u{F6DF}",+ "centmonospace" => "\u{FFE0}",+ "centoldstyle" => "\u{F7A2}",+ "centsuperior" => "\u{F6E0}",+ "chaarmenian" => "\u{0579}",+ "chabengali" => "\u{099B}",+ "chadeva" => "\u{091B}",+ "chagujarati" => "\u{0A9B}",+ "chagurmukhi" => "\u{0A1B}",+ "chbopomofo" => "\u{3114}",+ "cheabkhasiancyrillic" => "\u{04BD}",+ "checkmark" => "\u{2713}",+ "checyrillic" => "\u{0447}",+ "chedescenderabkhasiancyrillic" => "\u{04BF}",+ "chedescendercyrillic" => "\u{04B7}",+ "chedieresiscyrillic" => "\u{04F5}",+ "cheharmenian" => "\u{0573}",+ "chekhakassiancyrillic" => "\u{04CC}",+ "cheverticalstrokecyrillic" => "\u{04B9}",+ "chi" => "\u{03C7}",+ "chieuchacirclekorean" => "\u{3277}",+ "chieuchaparenkorean" => "\u{3217}",+ "chieuchcirclekorean" => "\u{3269}",+ "chieuchkorean" => "\u{314A}",+ "chieuchparenkorean" => "\u{3209}",+ "chochangthai" => "\u{0E0A}",+ "chochanthai" => "\u{0E08}",+ "chochingthai" => "\u{0E09}",+ "chochoethai" => "\u{0E0C}",+ "chook" => "\u{0188}",+ "cieucacirclekorean" => "\u{3276}",+ "cieucaparenkorean" => "\u{3216}",+ "cieuccirclekorean" => "\u{3268}",+ "cieuckorean" => "\u{3148}",+ "cieucparenkorean" => "\u{3208}",+ "cieucuparenkorean" => "\u{321C}",+ "circle" => "\u{25CB}",+ "circlemultiply" => "\u{2297}",+ "circleot" => "\u{2299}",+ "circleplus" => "\u{2295}",+ "circlepostalmark" => "\u{3036}",+ "circlewithlefthalfblack" => "\u{25D0}",+ "circlewithrighthalfblack" => "\u{25D1}",+ "circumflex" => "\u{02C6}",+ "circumflexbelowcmb" => "\u{032D}",+ "circumflexcmb" => "\u{0302}",+ "clear" => "\u{2327}",+ "clickalveolar" => "\u{01C2}",+ "clickdental" => "\u{01C0}",+ "clicklateral" => "\u{01C1}",+ "clickretroflex" => "\u{01C3}",+ "club" => "\u{2663}",+ "clubsuitblack" => "\u{2663}",+ "clubsuitwhite" => "\u{2667}",+ "cmcubedsquare" => "\u{33A4}",+ "cmonospace" => "\u{FF43}",+ "cmsquaredsquare" => "\u{33A0}",+ "coarmenian" => "\u{0581}",+ "colon" => "\u{003A}",+ "colonmonetary" => "\u{20A1}",+ "colonmonospace" => "\u{FF1A}",+ "colonsign" => "\u{20A1}",+ "colonsmall" => "\u{FE55}",+ "colontriangularhalfmod" => "\u{02D1}",+ "colontriangularmod" => "\u{02D0}",+ "comma" => "\u{002C}",+ "commaabovecmb" => "\u{0313}",+ "commaaboverightcmb" => "\u{0315}",+ "commaaccent" => "\u{F6C3}",+ "commaarabic" => "\u{060C}",+ "commaarmenian" => "\u{055D}",+ "commainferior" => "\u{F6E1}",+ "commamonospace" => "\u{FF0C}",+ "commareversedabovecmb" => "\u{0314}",+ "commareversedmod" => "\u{02BD}",+ "commasmall" => "\u{FE50}",+ "commasuperior" => "\u{F6E2}",+ "commaturnedabovecmb" => "\u{0312}",+ "commaturnedmod" => "\u{02BB}",+ "compass" => "\u{263C}",+ "congruent" => "\u{2245}",+ "contourintegral" => "\u{222E}",+ "control" => "\u{2303}",+ "controlACK" => "\u{0006}",+ "controlBEL" => "\u{0007}",+ "controlBS" => "\u{0008}",+ "controlCAN" => "\u{0018}",+ "controlCR" => "\u{000D}",+ "controlDC1" => "\u{0011}",+ "controlDC2" => "\u{0012}",+ "controlDC3" => "\u{0013}",+ "controlDC4" => "\u{0014}",+ "controlDEL" => "\u{007F}",+ "controlDLE" => "\u{0010}",+ "controlEM" => "\u{0019}",+ "controlENQ" => "\u{0005}",+ "controlEOT" => "\u{0004}",+ "controlESC" => "\u{001B}",+ "controlETB" => "\u{0017}",+ "controlETX" => "\u{0003}",+ "controlFF" => "\u{000C}",+ "controlFS" => "\u{001C}",+ "controlGS" => "\u{001D}",+ "controlHT" => "\u{0009}",+ "controlLF" => "\u{000A}",+ "controlNAK" => "\u{0015}",+ "controlRS" => "\u{001E}",+ "controlSI" => "\u{000F}",+ "controlSO" => "\u{000E}",+ "controlSOT" => "\u{0002}",+ "controlSTX" => "\u{0001}",+ "controlSUB" => "\u{001A}",+ "controlSYN" => "\u{0016}",+ "controlUS" => "\u{001F}",+ "controlVT" => "\u{000B}",+ "copyright" => "\u{00A9}",+ "copyrightsans" => "\u{F8E9}",+ "copyrightserif" => "\u{F6D9}",+ "cornerbracketleft" => "\u{300C}",+ "cornerbracketlefthalfwidth" => "\u{FF62}",+ "cornerbracketleftvertical" => "\u{FE41}",+ "cornerbracketright" => "\u{300D}",+ "cornerbracketrighthalfwidth" => "\u{FF63}",+ "cornerbracketrightvertical" => "\u{FE42}",+ "corporationsquare" => "\u{337F}",+ "cosquare" => "\u{33C7}",+ "coverkgsquare" => "\u{33C6}",+ "cparen" => "\u{249E}",+ "cruzeiro" => "\u{20A2}",+ "cstretched" => "\u{0297}",+ "curlyand" => "\u{22CF}",+ "curlyor" => "\u{22CE}",+ "currency" => "\u{00A4}",+ "cyrBreve" => "\u{F6D1}",+ "cyrFlex" => "\u{F6D2}",+ "cyrbreve" => "\u{F6D4}",+ "cyrflex" => "\u{F6D5}",+ "d" => "\u{0064}",+ "daarmenian" => "\u{0564}",+ "dabengali" => "\u{09A6}",+ "dadarabic" => "\u{0636}",+ "dadeva" => "\u{0926}",+ "dadfinalarabic" => "\u{FEBE}",+ "dadinitialarabic" => "\u{FEBF}",+ "dadmedialarabic" => "\u{FEC0}",+ "dagesh" => "\u{05BC}",+ "dageshhebrew" => "\u{05BC}",+ "dagger" => "\u{2020}",+ "daggerdbl" => "\u{2021}",+ "dagujarati" => "\u{0AA6}",+ "dagurmukhi" => "\u{0A26}",+ "dahiragana" => "\u{3060}",+ "dakatakana" => "\u{30C0}",+ "dalarabic" => "\u{062F}",+ "dalet" => "\u{05D3}",+ "daletdagesh" => "\u{FB33}",+ "daletdageshhebrew" => "\u{FB33}",+ "dalethatafpatah" => "\u{05D3}\u{05B2}",+ "dalethatafpatahhebrew" => "\u{05D3}\u{05B2}",+ "dalethatafsegol" => "\u{05D3}\u{05B1}",+ "dalethatafsegolhebrew" => "\u{05D3}\u{05B1}",+ "dalethebrew" => "\u{05D3}",+ "dalethiriq" => "\u{05D3}\u{05B4}",+ "dalethiriqhebrew" => "\u{05D3}\u{05B4}",+ "daletholam" => "\u{05D3}\u{05B9}",+ "daletholamhebrew" => "\u{05D3}\u{05B9}",+ "daletpatah" => "\u{05D3}\u{05B7}",+ "daletpatahhebrew" => "\u{05D3}\u{05B7}",+ "daletqamats" => "\u{05D3}\u{05B8}",+ "daletqamatshebrew" => "\u{05D3}\u{05B8}",+ "daletqubuts" => "\u{05D3}\u{05BB}",+ "daletqubutshebrew" => "\u{05D3}\u{05BB}",+ "daletsegol" => "\u{05D3}\u{05B6}",+ "daletsegolhebrew" => "\u{05D3}\u{05B6}",+ "daletsheva" => "\u{05D3}\u{05B0}",+ "daletshevahebrew" => "\u{05D3}\u{05B0}",+ "dalettsere" => "\u{05D3}\u{05B5}",+ "dalettserehebrew" => "\u{05D3}\u{05B5}",+ "dalfinalarabic" => "\u{FEAA}",+ "dammaarabic" => "\u{064F}",+ "dammalowarabic" => "\u{064F}",+ "dammatanaltonearabic" => "\u{064C}",+ "dammatanarabic" => "\u{064C}",+ "danda" => "\u{0964}",+ "dargahebrew" => "\u{05A7}",+ "dargalefthebrew" => "\u{05A7}",+ "dasiapneumatacyrilliccmb" => "\u{0485}",+ "dblGrave" => "\u{F6D3}",+ "dblanglebracketleft" => "\u{300A}",+ "dblanglebracketleftvertical" => "\u{FE3D}",+ "dblanglebracketright" => "\u{300B}",+ "dblanglebracketrightvertical" => "\u{FE3E}",+ "dblarchinvertedbelowcmb" => "\u{032B}",+ "dblarrowleft" => "\u{21D4}",+ "dblarrowright" => "\u{21D2}",+ "dbldanda" => "\u{0965}",+ "dblgrave" => "\u{F6D6}",+ "dblgravecmb" => "\u{030F}",+ "dblintegral" => "\u{222C}",+ "dbllowline" => "\u{2017}",+ "dbllowlinecmb" => "\u{0333}",+ "dbloverlinecmb" => "\u{033F}",+ "dblprimemod" => "\u{02BA}",+ "dblverticalbar" => "\u{2016}",+ "dblverticallineabovecmb" => "\u{030E}",+ "dbopomofo" => "\u{3109}",+ "dbsquare" => "\u{33C8}",+ "dcaron" => "\u{010F}",+ "dcedilla" => "\u{1E11}",+ "dcircle" => "\u{24D3}",+ "dcircumflexbelow" => "\u{1E13}",+ "dcroat" => "\u{0111}",+ "ddabengali" => "\u{09A1}",+ "ddadeva" => "\u{0921}",+ "ddagujarati" => "\u{0AA1}",+ "ddagurmukhi" => "\u{0A21}",+ "ddalarabic" => "\u{0688}",+ "ddalfinalarabic" => "\u{FB89}",+ "dddhadeva" => "\u{095C}",+ "ddhabengali" => "\u{09A2}",+ "ddhadeva" => "\u{0922}",+ "ddhagujarati" => "\u{0AA2}",+ "ddhagurmukhi" => "\u{0A22}",+ "ddotaccent" => "\u{1E0B}",+ "ddotbelow" => "\u{1E0D}",+ "decimalseparatorarabic" => "\u{066B}",+ "decimalseparatorpersian" => "\u{066B}",+ "decyrillic" => "\u{0434}",+ "degree" => "\u{00B0}",+ "dehihebrew" => "\u{05AD}",+ "dehiragana" => "\u{3067}",+ "deicoptic" => "\u{03EF}",+ "dekatakana" => "\u{30C7}",+ "deleteleft" => "\u{232B}",+ "deleteright" => "\u{2326}",+ "delta" => "\u{03B4}",+ "deltaturned" => "\u{018D}",+ "denominatorminusonenumeratorbengali" => "\u{09F8}",+ "dezh" => "\u{02A4}",+ "dhabengali" => "\u{09A7}",+ "dhadeva" => "\u{0927}",+ "dhagujarati" => "\u{0AA7}",+ "dhagurmukhi" => "\u{0A27}",+ "dhook" => "\u{0257}",+ "dialytikatonos" => "\u{0385}",+ "dialytikatonoscmb" => "\u{0344}",+ "diamond" => "\u{2666}",+ "diamondsuitwhite" => "\u{2662}",+ "dieresis" => "\u{00A8}",+ "dieresisacute" => "\u{F6D7}",+ "dieresisbelowcmb" => "\u{0324}",+ "dieresiscmb" => "\u{0308}",+ "dieresisgrave" => "\u{F6D8}",+ "dieresistonos" => "\u{0385}",+ "dihiragana" => "\u{3062}",+ "dikatakana" => "\u{30C2}",+ "dittomark" => "\u{3003}",+ "divide" => "\u{00F7}",+ "divides" => "\u{2223}",+ "divisionslash" => "\u{2215}",+ "djecyrillic" => "\u{0452}",+ "dkshade" => "\u{2593}",+ "dlinebelow" => "\u{1E0F}",+ "dlsquare" => "\u{3397}",+ "dmacron" => "\u{0111}",+ "dmonospace" => "\u{FF44}",+ "dnblock" => "\u{2584}",+ "dochadathai" => "\u{0E0E}",+ "dodekthai" => "\u{0E14}",+ "dohiragana" => "\u{3069}",+ "dokatakana" => "\u{30C9}",+ "dollar" => "\u{0024}",+ "dollarinferior" => "\u{F6E3}",+ "dollarmonospace" => "\u{FF04}",+ "dollaroldstyle" => "\u{F724}",+ "dollarsmall" => "\u{FE69}",+ "dollarsuperior" => "\u{F6E4}",+ "dong" => "\u{20AB}",+ "dorusquare" => "\u{3326}",+ "dotaccent" => "\u{02D9}",+ "dotaccentcmb" => "\u{0307}",+ "dotbelowcmb" => "\u{0323}",+ "dotbelowcomb" => "\u{0323}",+ "dotkatakana" => "\u{30FB}",+ "dotlessi" => "\u{0131}",+ "dotlessj" => "\u{F6BE}",+ "dotlessjstrokehook" => "\u{0284}",+ "dotmath" => "\u{22C5}",+ "dottedcircle" => "\u{25CC}",+ "doubleyodpatah" => "\u{FB1F}",+ "doubleyodpatahhebrew" => "\u{FB1F}",+ "downtackbelowcmb" => "\u{031E}",+ "downtackmod" => "\u{02D5}",+ "dparen" => "\u{249F}",+ "dsuperior" => "\u{F6EB}",+ "dtail" => "\u{0256}",+ "dtopbar" => "\u{018C}",+ "duhiragana" => "\u{3065}",+ "dukatakana" => "\u{30C5}",+ "dz" => "\u{01F3}",+ "dzaltone" => "\u{02A3}",+ "dzcaron" => "\u{01C6}",+ "dzcurl" => "\u{02A5}",+ "dzeabkhasiancyrillic" => "\u{04E1}",+ "dzecyrillic" => "\u{0455}",+ "dzhecyrillic" => "\u{045F}",+ "e" => "\u{0065}",+ "eacute" => "\u{00E9}",+ "earth" => "\u{2641}",+ "ebengali" => "\u{098F}",+ "ebopomofo" => "\u{311C}",+ "ebreve" => "\u{0115}",+ "ecandradeva" => "\u{090D}",+ "ecandragujarati" => "\u{0A8D}",+ "ecandravowelsigndeva" => "\u{0945}",+ "ecandravowelsigngujarati" => "\u{0AC5}",+ "ecaron" => "\u{011B}",+ "ecedillabreve" => "\u{1E1D}",+ "echarmenian" => "\u{0565}",+ "echyiwnarmenian" => "\u{0587}",+ "ecircle" => "\u{24D4}",+ "ecircumflex" => "\u{00EA}",+ "ecircumflexacute" => "\u{1EBF}",+ "ecircumflexbelow" => "\u{1E19}",+ "ecircumflexdotbelow" => "\u{1EC7}",+ "ecircumflexgrave" => "\u{1EC1}",+ "ecircumflexhookabove" => "\u{1EC3}",+ "ecircumflextilde" => "\u{1EC5}",+ "ecyrillic" => "\u{0454}",+ "edblgrave" => "\u{0205}",+ "edeva" => "\u{090F}",+ "edieresis" => "\u{00EB}",+ "edot" => "\u{0117}",+ "edotaccent" => "\u{0117}",+ "edotbelow" => "\u{1EB9}",+ "eegurmukhi" => "\u{0A0F}",+ "eematragurmukhi" => "\u{0A47}",+ "efcyrillic" => "\u{0444}",+ "egrave" => "\u{00E8}",+ "egujarati" => "\u{0A8F}",+ "eharmenian" => "\u{0567}",+ "ehbopomofo" => "\u{311D}",+ "ehiragana" => "\u{3048}",+ "ehookabove" => "\u{1EBB}",+ "eibopomofo" => "\u{311F}",+ "eight" => "\u{0038}",+ "eightarabic" => "\u{0668}",+ "eightbengali" => "\u{09EE}",+ "eightcircle" => "\u{2467}",+ "eightcircleinversesansserif" => "\u{2791}",+ "eightdeva" => "\u{096E}",+ "eighteencircle" => "\u{2471}",+ "eighteenparen" => "\u{2485}",+ "eighteenperiod" => "\u{2499}",+ "eightgujarati" => "\u{0AEE}",+ "eightgurmukhi" => "\u{0A6E}",+ "eighthackarabic" => "\u{0668}",+ "eighthangzhou" => "\u{3028}",+ "eighthnotebeamed" => "\u{266B}",+ "eightideographicparen" => "\u{3227}",+ "eightinferior" => "\u{2088}",+ "eightmonospace" => "\u{FF18}",+ "eightoldstyle" => "\u{F738}",+ "eightparen" => "\u{247B}",+ "eightperiod" => "\u{248F}",+ "eightpersian" => "\u{06F8}",+ "eightroman" => "\u{2177}",+ "eightsuperior" => "\u{2078}",+ "eightthai" => "\u{0E58}",+ "einvertedbreve" => "\u{0207}",+ "eiotifiedcyrillic" => "\u{0465}",+ "ekatakana" => "\u{30A8}",+ "ekatakanahalfwidth" => "\u{FF74}",+ "ekonkargurmukhi" => "\u{0A74}",+ "ekorean" => "\u{3154}",+ "elcyrillic" => "\u{043B}",+ "element" => "\u{2208}",+ "elevencircle" => "\u{246A}",+ "elevenparen" => "\u{247E}",+ "elevenperiod" => "\u{2492}",+ "elevenroman" => "\u{217A}",+ "ellipsis" => "\u{2026}",+ "ellipsisvertical" => "\u{22EE}",+ "emacron" => "\u{0113}",+ "emacronacute" => "\u{1E17}",+ "emacrongrave" => "\u{1E15}",+ "emcyrillic" => "\u{043C}",+ "emdash" => "\u{2014}",+ "emdashvertical" => "\u{FE31}",+ "emonospace" => "\u{FF45}",+ "emphasismarkarmenian" => "\u{055B}",+ "emptyset" => "\u{2205}",+ "enbopomofo" => "\u{3123}",+ "encyrillic" => "\u{043D}",+ "endash" => "\u{2013}",+ "endashvertical" => "\u{FE32}",+ "endescendercyrillic" => "\u{04A3}",+ "eng" => "\u{014B}",+ "engbopomofo" => "\u{3125}",+ "enghecyrillic" => "\u{04A5}",+ "enhookcyrillic" => "\u{04C8}",+ "enspace" => "\u{2002}",+ "eogonek" => "\u{0119}",+ "eokorean" => "\u{3153}",+ "eopen" => "\u{025B}",+ "eopenclosed" => "\u{029A}",+ "eopenreversed" => "\u{025C}",+ "eopenreversedclosed" => "\u{025E}",+ "eopenreversedhook" => "\u{025D}",+ "eparen" => "\u{24A0}",+ "epsilon" => "\u{03B5}",+ "epsilontonos" => "\u{03AD}",+ "equal" => "\u{003D}",+ "equalmonospace" => "\u{FF1D}",+ "equalsmall" => "\u{FE66}",+ "equalsuperior" => "\u{207C}",+ "equivalence" => "\u{2261}",+ "erbopomofo" => "\u{3126}",+ "ercyrillic" => "\u{0440}",+ "ereversed" => "\u{0258}",+ "ereversedcyrillic" => "\u{044D}",+ "escyrillic" => "\u{0441}",+ "esdescendercyrillic" => "\u{04AB}",+ "esh" => "\u{0283}",+ "eshcurl" => "\u{0286}",+ "eshortdeva" => "\u{090E}",+ "eshortvowelsigndeva" => "\u{0946}",+ "eshreversedloop" => "\u{01AA}",+ "eshsquatreversed" => "\u{0285}",+ "esmallhiragana" => "\u{3047}",+ "esmallkatakana" => "\u{30A7}",+ "esmallkatakanahalfwidth" => "\u{FF6A}",+ "estimated" => "\u{212E}",+ "esuperior" => "\u{F6EC}",+ "eta" => "\u{03B7}",+ "etarmenian" => "\u{0568}",+ "etatonos" => "\u{03AE}",+ "eth" => "\u{00F0}",+ "etilde" => "\u{1EBD}",+ "etildebelow" => "\u{1E1B}",+ "etnahtafoukhhebrew" => "\u{0591}",+ "etnahtafoukhlefthebrew" => "\u{0591}",+ "etnahtahebrew" => "\u{0591}",+ "etnahtalefthebrew" => "\u{0591}",+ "eturned" => "\u{01DD}",+ "eukorean" => "\u{3161}",+ "euro" => "\u{20AC}",+ "evowelsignbengali" => "\u{09C7}",+ "evowelsigndeva" => "\u{0947}",+ "evowelsigngujarati" => "\u{0AC7}",+ "exclam" => "\u{0021}",+ "exclamarmenian" => "\u{055C}",+ "exclamdbl" => "\u{203C}",+ "exclamdown" => "\u{00A1}",+ "exclamdownsmall" => "\u{F7A1}",+ "exclammonospace" => "\u{FF01}",+ "exclamsmall" => "\u{F721}",+ "existential" => "\u{2203}",+ "ezh" => "\u{0292}",+ "ezhcaron" => "\u{01EF}",+ "ezhcurl" => "\u{0293}",+ "ezhreversed" => "\u{01B9}",+ "ezhtail" => "\u{01BA}",+ "f" => "\u{0066}",+ "fadeva" => "\u{095E}",+ "fagurmukhi" => "\u{0A5E}",+ "fahrenheit" => "\u{2109}",+ "fathaarabic" => "\u{064E}",+ "fathalowarabic" => "\u{064E}",+ "fathatanarabic" => "\u{064B}",+ "fbopomofo" => "\u{3108}",+ "fcircle" => "\u{24D5}",+ "fdotaccent" => "\u{1E1F}",+ "feharabic" => "\u{0641}",+ "feharmenian" => "\u{0586}",+ "fehfinalarabic" => "\u{FED2}",+ "fehinitialarabic" => "\u{FED3}",+ "fehmedialarabic" => "\u{FED4}",+ "feicoptic" => "\u{03E5}",+ "female" => "\u{2640}",+ "ff" => "\u{FB00}",+ "ffi" => "\u{FB03}",+ "ffl" => "\u{FB04}",+ "fi" => "\u{FB01}",+ "fifteencircle" => "\u{246E}",+ "fifteenparen" => "\u{2482}",+ "fifteenperiod" => "\u{2496}",+ "figuredash" => "\u{2012}",+ "filledbox" => "\u{25A0}",+ "filledrect" => "\u{25AC}",+ "finalkaf" => "\u{05DA}",+ "finalkafdagesh" => "\u{FB3A}",+ "finalkafdageshhebrew" => "\u{FB3A}",+ "finalkafhebrew" => "\u{05DA}",+ "finalkafqamats" => "\u{05DA}\u{05B8}",+ "finalkafqamatshebrew" => "\u{05DA}\u{05B8}",+ "finalkafsheva" => "\u{05DA}\u{05B0}",+ "finalkafshevahebrew" => "\u{05DA}\u{05B0}",+ "finalmem" => "\u{05DD}",+ "finalmemhebrew" => "\u{05DD}",+ "finalnun" => "\u{05DF}",+ "finalnunhebrew" => "\u{05DF}",+ "finalpe" => "\u{05E3}",+ "finalpehebrew" => "\u{05E3}",+ "finaltsadi" => "\u{05E5}",+ "finaltsadihebrew" => "\u{05E5}",+ "firsttonechinese" => "\u{02C9}",+ "fisheye" => "\u{25C9}",+ "fitacyrillic" => "\u{0473}",+ "five" => "\u{0035}",+ "fivearabic" => "\u{0665}",+ "fivebengali" => "\u{09EB}",+ "fivecircle" => "\u{2464}",+ "fivecircleinversesansserif" => "\u{278E}",+ "fivedeva" => "\u{096B}",+ "fiveeighths" => "\u{215D}",+ "fivegujarati" => "\u{0AEB}",+ "fivegurmukhi" => "\u{0A6B}",+ "fivehackarabic" => "\u{0665}",+ "fivehangzhou" => "\u{3025}",+ "fiveideographicparen" => "\u{3224}",+ "fiveinferior" => "\u{2085}",+ "fivemonospace" => "\u{FF15}",+ "fiveoldstyle" => "\u{F735}",+ "fiveparen" => "\u{2478}",+ "fiveperiod" => "\u{248C}",+ "fivepersian" => "\u{06F5}",+ "fiveroman" => "\u{2174}",+ "fivesuperior" => "\u{2075}",+ "fivethai" => "\u{0E55}",+ "fl" => "\u{FB02}",+ "florin" => "\u{0192}",+ "fmonospace" => "\u{FF46}",+ "fmsquare" => "\u{3399}",+ "fofanthai" => "\u{0E1F}",+ "fofathai" => "\u{0E1D}",+ "fongmanthai" => "\u{0E4F}",+ "forall" => "\u{2200}",+ "four" => "\u{0034}",+ "fourarabic" => "\u{0664}",+ "fourbengali" => "\u{09EA}",+ "fourcircle" => "\u{2463}",+ "fourcircleinversesansserif" => "\u{278D}",+ "fourdeva" => "\u{096A}",+ "fourgujarati" => "\u{0AEA}",+ "fourgurmukhi" => "\u{0A6A}",+ "fourhackarabic" => "\u{0664}",+ "fourhangzhou" => "\u{3024}",+ "fourideographicparen" => "\u{3223}",+ "fourinferior" => "\u{2084}",+ "fourmonospace" => "\u{FF14}",+ "fournumeratorbengali" => "\u{09F7}",+ "fouroldstyle" => "\u{F734}",+ "fourparen" => "\u{2477}",+ "fourperiod" => "\u{248B}",+ "fourpersian" => "\u{06F4}",+ "fourroman" => "\u{2173}",+ "foursuperior" => "\u{2074}",+ "fourteencircle" => "\u{246D}",+ "fourteenparen" => "\u{2481}",+ "fourteenperiod" => "\u{2495}",+ "fourthai" => "\u{0E54}",+ "fourthtonechinese" => "\u{02CB}",+ "fparen" => "\u{24A1}",+ "fraction" => "\u{2044}",+ "franc" => "\u{20A3}",+ "g" => "\u{0067}",+ "gabengali" => "\u{0997}",+ "gacute" => "\u{01F5}",+ "gadeva" => "\u{0917}",+ "gafarabic" => "\u{06AF}",+ "gaffinalarabic" => "\u{FB93}",+ "gafinitialarabic" => "\u{FB94}",+ "gafmedialarabic" => "\u{FB95}",+ "gagujarati" => "\u{0A97}",+ "gagurmukhi" => "\u{0A17}",+ "gahiragana" => "\u{304C}",+ "gakatakana" => "\u{30AC}",+ "gamma" => "\u{03B3}",+ "gammalatinsmall" => "\u{0263}",+ "gammasuperior" => "\u{02E0}",+ "gangiacoptic" => "\u{03EB}",+ "gbopomofo" => "\u{310D}",+ "gbreve" => "\u{011F}",+ "gcaron" => "\u{01E7}",+ "gcedilla" => "\u{0123}",+ "gcircle" => "\u{24D6}",+ "gcircumflex" => "\u{011D}",+ "gcommaaccent" => "\u{0123}",+ "gdot" => "\u{0121}",+ "gdotaccent" => "\u{0121}",+ "gecyrillic" => "\u{0433}",+ "gehiragana" => "\u{3052}",+ "gekatakana" => "\u{30B2}",+ "geometricallyequal" => "\u{2251}",+ "gereshaccenthebrew" => "\u{059C}",+ "gereshhebrew" => "\u{05F3}",+ "gereshmuqdamhebrew" => "\u{059D}",+ "germandbls" => "\u{00DF}",+ "gershayimaccenthebrew" => "\u{059E}",+ "gershayimhebrew" => "\u{05F4}",+ "getamark" => "\u{3013}",+ "ghabengali" => "\u{0998}",+ "ghadarmenian" => "\u{0572}",+ "ghadeva" => "\u{0918}",+ "ghagujarati" => "\u{0A98}",+ "ghagurmukhi" => "\u{0A18}",+ "ghainarabic" => "\u{063A}",+ "ghainfinalarabic" => "\u{FECE}",+ "ghaininitialarabic" => "\u{FECF}",+ "ghainmedialarabic" => "\u{FED0}",+ "ghemiddlehookcyrillic" => "\u{0495}",+ "ghestrokecyrillic" => "\u{0493}",+ "gheupturncyrillic" => "\u{0491}",+ "ghhadeva" => "\u{095A}",+ "ghhagurmukhi" => "\u{0A5A}",+ "ghook" => "\u{0260}",+ "ghzsquare" => "\u{3393}",+ "gihiragana" => "\u{304E}",+ "gikatakana" => "\u{30AE}",+ "gimarmenian" => "\u{0563}",+ "gimel" => "\u{05D2}",+ "gimeldagesh" => "\u{FB32}",+ "gimeldageshhebrew" => "\u{FB32}",+ "gimelhebrew" => "\u{05D2}",+ "gjecyrillic" => "\u{0453}",+ "glottalinvertedstroke" => "\u{01BE}",+ "glottalstop" => "\u{0294}",+ "glottalstopinverted" => "\u{0296}",+ "glottalstopmod" => "\u{02C0}",+ "glottalstopreversed" => "\u{0295}",+ "glottalstopreversedmod" => "\u{02C1}",+ "glottalstopreversedsuperior" => "\u{02E4}",+ "glottalstopstroke" => "\u{02A1}",+ "glottalstopstrokereversed" => "\u{02A2}",+ "gmacron" => "\u{1E21}",+ "gmonospace" => "\u{FF47}",+ "gohiragana" => "\u{3054}",+ "gokatakana" => "\u{30B4}",+ "gparen" => "\u{24A2}",+ "gpasquare" => "\u{33AC}",+ "gradient" => "\u{2207}",+ "grave" => "\u{0060}",+ "gravebelowcmb" => "\u{0316}",+ "gravecmb" => "\u{0300}",+ "gravecomb" => "\u{0300}",+ "gravedeva" => "\u{0953}",+ "gravelowmod" => "\u{02CE}",+ "gravemonospace" => "\u{FF40}",+ "gravetonecmb" => "\u{0340}",+ "greater" => "\u{003E}",+ "greaterequal" => "\u{2265}",+ "greaterequalorless" => "\u{22DB}",+ "greatermonospace" => "\u{FF1E}",+ "greaterorequivalent" => "\u{2273}",+ "greaterorless" => "\u{2277}",+ "greateroverequal" => "\u{2267}",+ "greatersmall" => "\u{FE65}",+ "gscript" => "\u{0261}",+ "gstroke" => "\u{01E5}",+ "guhiragana" => "\u{3050}",+ "guillemotleft" => "\u{00AB}",+ "guillemotright" => "\u{00BB}",+ "guilsinglleft" => "\u{2039}",+ "guilsinglright" => "\u{203A}",+ "gukatakana" => "\u{30B0}",+ "guramusquare" => "\u{3318}",+ "gysquare" => "\u{33C9}",+ "h" => "\u{0068}",+ "haabkhasiancyrillic" => "\u{04A9}",+ "haaltonearabic" => "\u{06C1}",+ "habengali" => "\u{09B9}",+ "hadescendercyrillic" => "\u{04B3}",+ "hadeva" => "\u{0939}",+ "hagujarati" => "\u{0AB9}",+ "hagurmukhi" => "\u{0A39}",+ "haharabic" => "\u{062D}",+ "hahfinalarabic" => "\u{FEA2}",+ "hahinitialarabic" => "\u{FEA3}",+ "hahiragana" => "\u{306F}",+ "hahmedialarabic" => "\u{FEA4}",+ "haitusquare" => "\u{332A}",+ "hakatakana" => "\u{30CF}",+ "hakatakanahalfwidth" => "\u{FF8A}",+ "halantgurmukhi" => "\u{0A4D}",+ "hamzaarabic" => "\u{0621}",+ "hamzadammaarabic" => "\u{0621}\u{064F}",+ "hamzadammatanarabic" => "\u{0621}\u{064C}",+ "hamzafathaarabic" => "\u{0621}\u{064E}",+ "hamzafathatanarabic" => "\u{0621}\u{064B}",+ "hamzalowarabic" => "\u{0621}",+ "hamzalowkasraarabic" => "\u{0621}\u{0650}",+ "hamzalowkasratanarabic" => "\u{0621}\u{064D}",+ "hamzasukunarabic" => "\u{0621}\u{0652}",+ "hangulfiller" => "\u{3164}",+ "hardsigncyrillic" => "\u{044A}",+ "harpoonleftbarbup" => "\u{21BC}",+ "harpoonrightbarbup" => "\u{21C0}",+ "hasquare" => "\u{33CA}",+ "hatafpatah" => "\u{05B2}",+ "hatafpatah16" => "\u{05B2}",+ "hatafpatah23" => "\u{05B2}",+ "hatafpatah2f" => "\u{05B2}",+ "hatafpatahhebrew" => "\u{05B2}",+ "hatafpatahnarrowhebrew" => "\u{05B2}",+ "hatafpatahquarterhebrew" => "\u{05B2}",+ "hatafpatahwidehebrew" => "\u{05B2}",+ "hatafqamats" => "\u{05B3}",+ "hatafqamats1b" => "\u{05B3}",+ "hatafqamats28" => "\u{05B3}",+ "hatafqamats34" => "\u{05B3}",+ "hatafqamatshebrew" => "\u{05B3}",+ "hatafqamatsnarrowhebrew" => "\u{05B3}",+ "hatafqamatsquarterhebrew" => "\u{05B3}",+ "hatafqamatswidehebrew" => "\u{05B3}",+ "hatafsegol" => "\u{05B1}",+ "hatafsegol17" => "\u{05B1}",+ "hatafsegol24" => "\u{05B1}",+ "hatafsegol30" => "\u{05B1}",+ "hatafsegolhebrew" => "\u{05B1}",+ "hatafsegolnarrowhebrew" => "\u{05B1}",+ "hatafsegolquarterhebrew" => "\u{05B1}",+ "hatafsegolwidehebrew" => "\u{05B1}",+ "hbar" => "\u{0127}",+ "hbopomofo" => "\u{310F}",+ "hbrevebelow" => "\u{1E2B}",+ "hcedilla" => "\u{1E29}",+ "hcircle" => "\u{24D7}",+ "hcircumflex" => "\u{0125}",+ "hdieresis" => "\u{1E27}",+ "hdotaccent" => "\u{1E23}",+ "hdotbelow" => "\u{1E25}",+ "he" => "\u{05D4}",+ "heart" => "\u{2665}",+ "heartsuitblack" => "\u{2665}",+ "heartsuitwhite" => "\u{2661}",+ "hedagesh" => "\u{FB34}",+ "hedageshhebrew" => "\u{FB34}",+ "hehaltonearabic" => "\u{06C1}",+ "heharabic" => "\u{0647}",+ "hehebrew" => "\u{05D4}",+ "hehfinalaltonearabic" => "\u{FBA7}",+ "hehfinalalttwoarabic" => "\u{FEEA}",+ "hehfinalarabic" => "\u{FEEA}",+ "hehhamzaabovefinalarabic" => "\u{FBA5}",+ "hehhamzaaboveisolatedarabic" => "\u{FBA4}",+ "hehinitialaltonearabic" => "\u{FBA8}",+ "hehinitialarabic" => "\u{FEEB}",+ "hehiragana" => "\u{3078}",+ "hehmedialaltonearabic" => "\u{FBA9}",+ "hehmedialarabic" => "\u{FEEC}",+ "heiseierasquare" => "\u{337B}",+ "hekatakana" => "\u{30D8}",+ "hekatakanahalfwidth" => "\u{FF8D}",+ "hekutaarusquare" => "\u{3336}",+ "henghook" => "\u{0267}",+ "herutusquare" => "\u{3339}",+ "het" => "\u{05D7}",+ "hethebrew" => "\u{05D7}",+ "hhook" => "\u{0266}",+ "hhooksuperior" => "\u{02B1}",+ "hieuhacirclekorean" => "\u{327B}",+ "hieuhaparenkorean" => "\u{321B}",+ "hieuhcirclekorean" => "\u{326D}",+ "hieuhkorean" => "\u{314E}",+ "hieuhparenkorean" => "\u{320D}",+ "hihiragana" => "\u{3072}",+ "hikatakana" => "\u{30D2}",+ "hikatakanahalfwidth" => "\u{FF8B}",+ "hiriq" => "\u{05B4}",+ "hiriq14" => "\u{05B4}",+ "hiriq21" => "\u{05B4}",+ "hiriq2d" => "\u{05B4}",+ "hiriqhebrew" => "\u{05B4}",+ "hiriqnarrowhebrew" => "\u{05B4}",+ "hiriqquarterhebrew" => "\u{05B4}",+ "hiriqwidehebrew" => "\u{05B4}",+ "hlinebelow" => "\u{1E96}",+ "hmonospace" => "\u{FF48}",+ "hoarmenian" => "\u{0570}",+ "hohipthai" => "\u{0E2B}",+ "hohiragana" => "\u{307B}",+ "hokatakana" => "\u{30DB}",+ "hokatakanahalfwidth" => "\u{FF8E}",+ "holam" => "\u{05B9}",+ "holam19" => "\u{05B9}",+ "holam26" => "\u{05B9}",+ "holam32" => "\u{05B9}",+ "holamhebrew" => "\u{05B9}",+ "holamnarrowhebrew" => "\u{05B9}",+ "holamquarterhebrew" => "\u{05B9}",+ "holamwidehebrew" => "\u{05B9}",+ "honokhukthai" => "\u{0E2E}",+ "hookabovecomb" => "\u{0309}",+ "hookcmb" => "\u{0309}",+ "hookpalatalizedbelowcmb" => "\u{0321}",+ "hookretroflexbelowcmb" => "\u{0322}",+ "hoonsquare" => "\u{3342}",+ "horicoptic" => "\u{03E9}",+ "horizontalbar" => "\u{2015}",+ "horncmb" => "\u{031B}",+ "hotsprings" => "\u{2668}",+ "house" => "\u{2302}",+ "hparen" => "\u{24A3}",+ "hsuperior" => "\u{02B0}",+ "hturned" => "\u{0265}",+ "huhiragana" => "\u{3075}",+ "huiitosquare" => "\u{3333}",+ "hukatakana" => "\u{30D5}",+ "hukatakanahalfwidth" => "\u{FF8C}",+ "hungarumlaut" => "\u{02DD}",+ "hungarumlautcmb" => "\u{030B}",+ "hv" => "\u{0195}",+ "hyphen" => "\u{002D}",+ "hypheninferior" => "\u{F6E5}",+ "hyphenmonospace" => "\u{FF0D}",+ "hyphensmall" => "\u{FE63}",+ "hyphensuperior" => "\u{F6E6}",+ "hyphentwo" => "\u{2010}",+ "i" => "\u{0069}",+ "iacute" => "\u{00ED}",+ "iacyrillic" => "\u{044F}",+ "ibengali" => "\u{0987}",+ "ibopomofo" => "\u{3127}",+ "ibreve" => "\u{012D}",+ "icaron" => "\u{01D0}",+ "icircle" => "\u{24D8}",+ "icircumflex" => "\u{00EE}",+ "icyrillic" => "\u{0456}",+ "idblgrave" => "\u{0209}",+ "ideographearthcircle" => "\u{328F}",+ "ideographfirecircle" => "\u{328B}",+ "ideographicallianceparen" => "\u{323F}",+ "ideographiccallparen" => "\u{323A}",+ "ideographiccentrecircle" => "\u{32A5}",+ "ideographicclose" => "\u{3006}",+ "ideographiccomma" => "\u{3001}",+ "ideographiccommaleft" => "\u{FF64}",+ "ideographiccongratulationparen" => "\u{3237}",+ "ideographiccorrectcircle" => "\u{32A3}",+ "ideographicearthparen" => "\u{322F}",+ "ideographicenterpriseparen" => "\u{323D}",+ "ideographicexcellentcircle" => "\u{329D}",+ "ideographicfestivalparen" => "\u{3240}",+ "ideographicfinancialcircle" => "\u{3296}",+ "ideographicfinancialparen" => "\u{3236}",+ "ideographicfireparen" => "\u{322B}",+ "ideographichaveparen" => "\u{3232}",+ "ideographichighcircle" => "\u{32A4}",+ "ideographiciterationmark" => "\u{3005}",+ "ideographiclaborcircle" => "\u{3298}",+ "ideographiclaborparen" => "\u{3238}",+ "ideographicleftcircle" => "\u{32A7}",+ "ideographiclowcircle" => "\u{32A6}",+ "ideographicmedicinecircle" => "\u{32A9}",+ "ideographicmetalparen" => "\u{322E}",+ "ideographicmoonparen" => "\u{322A}",+ "ideographicnameparen" => "\u{3234}",+ "ideographicperiod" => "\u{3002}",+ "ideographicprintcircle" => "\u{329E}",+ "ideographicreachparen" => "\u{3243}",+ "ideographicrepresentparen" => "\u{3239}",+ "ideographicresourceparen" => "\u{323E}",+ "ideographicrightcircle" => "\u{32A8}",+ "ideographicsecretcircle" => "\u{3299}",+ "ideographicselfparen" => "\u{3242}",+ "ideographicsocietyparen" => "\u{3233}",+ "ideographicspace" => "\u{3000}",+ "ideographicspecialparen" => "\u{3235}",+ "ideographicstockparen" => "\u{3231}",+ "ideographicstudyparen" => "\u{323B}",+ "ideographicsunparen" => "\u{3230}",+ "ideographicsuperviseparen" => "\u{323C}",+ "ideographicwaterparen" => "\u{322C}",+ "ideographicwoodparen" => "\u{322D}",+ "ideographiczero" => "\u{3007}",+ "ideographmetalcircle" => "\u{328E}",+ "ideographmooncircle" => "\u{328A}",+ "ideographnamecircle" => "\u{3294}",+ "ideographsuncircle" => "\u{3290}",+ "ideographwatercircle" => "\u{328C}",+ "ideographwoodcircle" => "\u{328D}",+ "ideva" => "\u{0907}",+ "idieresis" => "\u{00EF}",+ "idieresisacute" => "\u{1E2F}",+ "idieresiscyrillic" => "\u{04E5}",+ "idotbelow" => "\u{1ECB}",+ "iebrevecyrillic" => "\u{04D7}",+ "iecyrillic" => "\u{0435}",+ "ieungacirclekorean" => "\u{3275}",+ "ieungaparenkorean" => "\u{3215}",+ "ieungcirclekorean" => "\u{3267}",+ "ieungkorean" => "\u{3147}",+ "ieungparenkorean" => "\u{3207}",+ "igrave" => "\u{00EC}",+ "igujarati" => "\u{0A87}",+ "igurmukhi" => "\u{0A07}",+ "ihiragana" => "\u{3044}",+ "ihookabove" => "\u{1EC9}",+ "iibengali" => "\u{0988}",+ "iicyrillic" => "\u{0438}",+ "iideva" => "\u{0908}",+ "iigujarati" => "\u{0A88}",+ "iigurmukhi" => "\u{0A08}",+ "iimatragurmukhi" => "\u{0A40}",+ "iinvertedbreve" => "\u{020B}",+ "iishortcyrillic" => "\u{0439}",+ "iivowelsignbengali" => "\u{09C0}",+ "iivowelsigndeva" => "\u{0940}",+ "iivowelsigngujarati" => "\u{0AC0}",+ "ij" => "\u{0133}",+ "ikatakana" => "\u{30A4}",+ "ikatakanahalfwidth" => "\u{FF72}",+ "ikorean" => "\u{3163}",+ "ilde" => "\u{02DC}",+ "iluyhebrew" => "\u{05AC}",+ "imacron" => "\u{012B}",+ "imacroncyrillic" => "\u{04E3}",+ "imageorapproximatelyequal" => "\u{2253}",+ "imatragurmukhi" => "\u{0A3F}",+ "imonospace" => "\u{FF49}",+ "increment" => "\u{2206}",+ "infinity" => "\u{221E}",+ "iniarmenian" => "\u{056B}",+ "integral" => "\u{222B}",+ "integralbottom" => "\u{2321}",+ "integralbt" => "\u{2321}",+ "integralex" => "\u{F8F5}",+ "integraltop" => "\u{2320}",+ "integraltp" => "\u{2320}",+ "intersection" => "\u{2229}",+ "intisquare" => "\u{3305}",+ "invbullet" => "\u{25D8}",+ "invcircle" => "\u{25D9}",+ "invsmileface" => "\u{263B}",+ "iocyrillic" => "\u{0451}",+ "iogonek" => "\u{012F}",+ "iota" => "\u{03B9}",+ "iotadieresis" => "\u{03CA}",+ "iotadieresistonos" => "\u{0390}",+ "iotalatin" => "\u{0269}",+ "iotatonos" => "\u{03AF}",+ "iparen" => "\u{24A4}",+ "irigurmukhi" => "\u{0A72}",+ "ismallhiragana" => "\u{3043}",+ "ismallkatakana" => "\u{30A3}",+ "ismallkatakanahalfwidth" => "\u{FF68}",+ "issharbengali" => "\u{09FA}",+ "istroke" => "\u{0268}",+ "isuperior" => "\u{F6ED}",+ "iterationhiragana" => "\u{309D}",+ "iterationkatakana" => "\u{30FD}",+ "itilde" => "\u{0129}",+ "itildebelow" => "\u{1E2D}",+ "iubopomofo" => "\u{3129}",+ "iucyrillic" => "\u{044E}",+ "ivowelsignbengali" => "\u{09BF}",+ "ivowelsigndeva" => "\u{093F}",+ "ivowelsigngujarati" => "\u{0ABF}",+ "izhitsacyrillic" => "\u{0475}",+ "izhitsadblgravecyrillic" => "\u{0477}",+ "j" => "\u{006A}",+ "jaarmenian" => "\u{0571}",+ "jabengali" => "\u{099C}",+ "jadeva" => "\u{091C}",+ "jagujarati" => "\u{0A9C}",+ "jagurmukhi" => "\u{0A1C}",+ "jbopomofo" => "\u{3110}",+ "jcaron" => "\u{01F0}",+ "jcircle" => "\u{24D9}",+ "jcircumflex" => "\u{0135}",+ "jcrossedtail" => "\u{029D}",+ "jdotlessstroke" => "\u{025F}",+ "jecyrillic" => "\u{0458}",+ "jeemarabic" => "\u{062C}",+ "jeemfinalarabic" => "\u{FE9E}",+ "jeeminitialarabic" => "\u{FE9F}",+ "jeemmedialarabic" => "\u{FEA0}",+ "jeharabic" => "\u{0698}",+ "jehfinalarabic" => "\u{FB8B}",+ "jhabengali" => "\u{099D}",+ "jhadeva" => "\u{091D}",+ "jhagujarati" => "\u{0A9D}",+ "jhagurmukhi" => "\u{0A1D}",+ "jheharmenian" => "\u{057B}",+ "jis" => "\u{3004}",+ "jmonospace" => "\u{FF4A}",+ "jparen" => "\u{24A5}",+ "jsuperior" => "\u{02B2}",+ "k" => "\u{006B}",+ "kabashkircyrillic" => "\u{04A1}",+ "kabengali" => "\u{0995}",+ "kacute" => "\u{1E31}",+ "kacyrillic" => "\u{043A}",+ "kadescendercyrillic" => "\u{049B}",+ "kadeva" => "\u{0915}",+ "kaf" => "\u{05DB}",+ "kafarabic" => "\u{0643}",+ "kafdagesh" => "\u{FB3B}",+ "kafdageshhebrew" => "\u{FB3B}",+ "kaffinalarabic" => "\u{FEDA}",+ "kafhebrew" => "\u{05DB}",+ "kafinitialarabic" => "\u{FEDB}",+ "kafmedialarabic" => "\u{FEDC}",+ "kafrafehebrew" => "\u{FB4D}",+ "kagujarati" => "\u{0A95}",+ "kagurmukhi" => "\u{0A15}",+ "kahiragana" => "\u{304B}",+ "kahookcyrillic" => "\u{04C4}",+ "kakatakana" => "\u{30AB}",+ "kakatakanahalfwidth" => "\u{FF76}",+ "kappa" => "\u{03BA}",+ "kappasymbolgreek" => "\u{03F0}",+ "kapyeounmieumkorean" => "\u{3171}",+ "kapyeounphieuphkorean" => "\u{3184}",+ "kapyeounpieupkorean" => "\u{3178}",+ "kapyeounssangpieupkorean" => "\u{3179}",+ "karoriisquare" => "\u{330D}",+ "kashidaautoarabic" => "\u{0640}",+ "kashidaautonosidebearingarabic" => "\u{0640}",+ "kasmallkatakana" => "\u{30F5}",+ "kasquare" => "\u{3384}",+ "kasraarabic" => "\u{0650}",+ "kasratanarabic" => "\u{064D}",+ "kastrokecyrillic" => "\u{049F}",+ "katahiraprolongmarkhalfwidth" => "\u{FF70}",+ "kaverticalstrokecyrillic" => "\u{049D}",+ "kbopomofo" => "\u{310E}",+ "kcalsquare" => "\u{3389}",+ "kcaron" => "\u{01E9}",+ "kcedilla" => "\u{0137}",+ "kcircle" => "\u{24DA}",+ "kcommaaccent" => "\u{0137}",+ "kdotbelow" => "\u{1E33}",+ "keharmenian" => "\u{0584}",+ "kehiragana" => "\u{3051}",+ "kekatakana" => "\u{30B1}",+ "kekatakanahalfwidth" => "\u{FF79}",+ "kenarmenian" => "\u{056F}",+ "kesmallkatakana" => "\u{30F6}",+ "kgreenlandic" => "\u{0138}",+ "khabengali" => "\u{0996}",+ "khacyrillic" => "\u{0445}",+ "khadeva" => "\u{0916}",+ "khagujarati" => "\u{0A96}",+ "khagurmukhi" => "\u{0A16}",+ "khaharabic" => "\u{062E}",+ "khahfinalarabic" => "\u{FEA6}",+ "khahinitialarabic" => "\u{FEA7}",+ "khahmedialarabic" => "\u{FEA8}",+ "kheicoptic" => "\u{03E7}",+ "khhadeva" => "\u{0959}",+ "khhagurmukhi" => "\u{0A59}",+ "khieukhacirclekorean" => "\u{3278}",+ "khieukhaparenkorean" => "\u{3218}",+ "khieukhcirclekorean" => "\u{326A}",+ "khieukhkorean" => "\u{314B}",+ "khieukhparenkorean" => "\u{320A}",+ "khokhaithai" => "\u{0E02}",+ "khokhonthai" => "\u{0E05}",+ "khokhuatthai" => "\u{0E03}",+ "khokhwaithai" => "\u{0E04}",+ "khomutthai" => "\u{0E5B}",+ "khook" => "\u{0199}",+ "khorakhangthai" => "\u{0E06}",+ "khzsquare" => "\u{3391}",+ "kihiragana" => "\u{304D}",+ "kikatakana" => "\u{30AD}",+ "kikatakanahalfwidth" => "\u{FF77}",+ "kiroguramusquare" => "\u{3315}",+ "kiromeetorusquare" => "\u{3316}",+ "kirosquare" => "\u{3314}",+ "kiyeokacirclekorean" => "\u{326E}",+ "kiyeokaparenkorean" => "\u{320E}",+ "kiyeokcirclekorean" => "\u{3260}",+ "kiyeokkorean" => "\u{3131}",+ "kiyeokparenkorean" => "\u{3200}",+ "kiyeoksioskorean" => "\u{3133}",+ "kjecyrillic" => "\u{045C}",+ "klinebelow" => "\u{1E35}",+ "klsquare" => "\u{3398}",+ "kmcubedsquare" => "\u{33A6}",+ "kmonospace" => "\u{FF4B}",+ "kmsquaredsquare" => "\u{33A2}",+ "kohiragana" => "\u{3053}",+ "kohmsquare" => "\u{33C0}",+ "kokaithai" => "\u{0E01}",+ "kokatakana" => "\u{30B3}",+ "kokatakanahalfwidth" => "\u{FF7A}",+ "kooposquare" => "\u{331E}",+ "koppacyrillic" => "\u{0481}",+ "koreanstandardsymbol" => "\u{327F}",+ "koroniscmb" => "\u{0343}",+ "kparen" => "\u{24A6}",+ "kpasquare" => "\u{33AA}",+ "ksicyrillic" => "\u{046F}",+ "ktsquare" => "\u{33CF}",+ "kturned" => "\u{029E}",+ "kuhiragana" => "\u{304F}",+ "kukatakana" => "\u{30AF}",+ "kukatakanahalfwidth" => "\u{FF78}",+ "kvsquare" => "\u{33B8}",+ "kwsquare" => "\u{33BE}",+ "l" => "\u{006C}",+ "labengali" => "\u{09B2}",+ "lacute" => "\u{013A}",+ "ladeva" => "\u{0932}",+ "lagujarati" => "\u{0AB2}",+ "lagurmukhi" => "\u{0A32}",+ "lakkhangyaothai" => "\u{0E45}",+ "lamaleffinalarabic" => "\u{FEFC}",+ "lamalefhamzaabovefinalarabic" => "\u{FEF8}",+ "lamalefhamzaaboveisolatedarabic" => "\u{FEF7}",+ "lamalefhamzabelowfinalarabic" => "\u{FEFA}",+ "lamalefhamzabelowisolatedarabic" => "\u{FEF9}",+ "lamalefisolatedarabic" => "\u{FEFB}",+ "lamalefmaddaabovefinalarabic" => "\u{FEF6}",+ "lamalefmaddaaboveisolatedarabic" => "\u{FEF5}",+ "lamarabic" => "\u{0644}",+ "lambda" => "\u{03BB}",+ "lambdastroke" => "\u{019B}",+ "lamed" => "\u{05DC}",+ "lameddagesh" => "\u{FB3C}",+ "lameddageshhebrew" => "\u{FB3C}",+ "lamedhebrew" => "\u{05DC}",+ "lamedholam" => "\u{05DC}\u{05B9}",+ "lamedholamdagesh" => "\u{05DC}\u{05B9}\u{05BC}",+ "lamedholamdageshhebrew" => "\u{05DC}\u{05B9}\u{05BC}",+ "lamedholamhebrew" => "\u{05DC}\u{05B9}",+ "lamfinalarabic" => "\u{FEDE}",+ "lamhahinitialarabic" => "\u{FCCA}",+ "laminitialarabic" => "\u{FEDF}",+ "lamjeeminitialarabic" => "\u{FCC9}",+ "lamkhahinitialarabic" => "\u{FCCB}",+ "lamlamhehisolatedarabic" => "\u{FDF2}",+ "lammedialarabic" => "\u{FEE0}",+ "lammeemhahinitialarabic" => "\u{FD88}",+ "lammeeminitialarabic" => "\u{FCCC}",+ "lammeemjeeminitialarabic" => "\u{FEDF}\u{FEE4}\u{FEA0}",+ "lammeemkhahinitialarabic" => "\u{FEDF}\u{FEE4}\u{FEA8}",+ "largecircle" => "\u{25EF}",+ "lbar" => "\u{019A}",+ "lbelt" => "\u{026C}",+ "lbopomofo" => "\u{310C}",+ "lcaron" => "\u{013E}",+ "lcedilla" => "\u{013C}",+ "lcircle" => "\u{24DB}",+ "lcircumflexbelow" => "\u{1E3D}",+ "lcommaaccent" => "\u{013C}",+ "ldot" => "\u{0140}",+ "ldotaccent" => "\u{0140}",+ "ldotbelow" => "\u{1E37}",+ "ldotbelowmacron" => "\u{1E39}",+ "leftangleabovecmb" => "\u{031A}",+ "lefttackbelowcmb" => "\u{0318}",+ "less" => "\u{003C}",+ "lessequal" => "\u{2264}",+ "lessequalorgreater" => "\u{22DA}",+ "lessmonospace" => "\u{FF1C}",+ "lessorequivalent" => "\u{2272}",+ "lessorgreater" => "\u{2276}",+ "lessoverequal" => "\u{2266}",+ "lesssmall" => "\u{FE64}",+ "lezh" => "\u{026E}",+ "lfblock" => "\u{258C}",+ "lhookretroflex" => "\u{026D}",+ "lira" => "\u{20A4}",+ "liwnarmenian" => "\u{056C}",+ "lj" => "\u{01C9}",+ "ljecyrillic" => "\u{0459}",+ "ll" => "\u{F6C0}",+ "lladeva" => "\u{0933}",+ "llagujarati" => "\u{0AB3}",+ "llinebelow" => "\u{1E3B}",+ "llladeva" => "\u{0934}",+ "llvocalicbengali" => "\u{09E1}",+ "llvocalicdeva" => "\u{0961}",+ "llvocalicvowelsignbengali" => "\u{09E3}",+ "llvocalicvowelsigndeva" => "\u{0963}",+ "lmiddletilde" => "\u{026B}",+ "lmonospace" => "\u{FF4C}",+ "lmsquare" => "\u{33D0}",+ "lochulathai" => "\u{0E2C}",+ "logicaland" => "\u{2227}",+ "logicalnot" => "\u{00AC}",+ "logicalnotreversed" => "\u{2310}",+ "logicalor" => "\u{2228}",+ "lolingthai" => "\u{0E25}",+ "longs" => "\u{017F}",+ "lowlinecenterline" => "\u{FE4E}",+ "lowlinecmb" => "\u{0332}",+ "lowlinedashed" => "\u{FE4D}",+ "lozenge" => "\u{25CA}",+ "lparen" => "\u{24A7}",+ "lslash" => "\u{0142}",+ "lsquare" => "\u{2113}",+ "lsuperior" => "\u{F6EE}",+ "ltshade" => "\u{2591}",+ "luthai" => "\u{0E26}",+ "lvocalicbengali" => "\u{098C}",+ "lvocalicdeva" => "\u{090C}",+ "lvocalicvowelsignbengali" => "\u{09E2}",+ "lvocalicvowelsigndeva" => "\u{0962}",+ "lxsquare" => "\u{33D3}",+ "m" => "\u{006D}",+ "mabengali" => "\u{09AE}",+ "macron" => "\u{00AF}",+ "macronbelowcmb" => "\u{0331}",+ "macroncmb" => "\u{0304}",+ "macronlowmod" => "\u{02CD}",+ "macronmonospace" => "\u{FFE3}",+ "macute" => "\u{1E3F}",+ "madeva" => "\u{092E}",+ "magujarati" => "\u{0AAE}",+ "magurmukhi" => "\u{0A2E}",+ "mahapakhhebrew" => "\u{05A4}",+ "mahapakhlefthebrew" => "\u{05A4}",+ "mahiragana" => "\u{307E}",+ "maichattawalowleftthai" => "\u{F895}",+ "maichattawalowrightthai" => "\u{F894}",+ "maichattawathai" => "\u{0E4B}",+ "maichattawaupperleftthai" => "\u{F893}",+ "maieklowleftthai" => "\u{F88C}",+ "maieklowrightthai" => "\u{F88B}",+ "maiekthai" => "\u{0E48}",+ "maiekupperleftthai" => "\u{F88A}",+ "maihanakatleftthai" => "\u{F884}",+ "maihanakatthai" => "\u{0E31}",+ "maitaikhuleftthai" => "\u{F889}",+ "maitaikhuthai" => "\u{0E47}",+ "maitholowleftthai" => "\u{F88F}",+ "maitholowrightthai" => "\u{F88E}",+ "maithothai" => "\u{0E49}",+ "maithoupperleftthai" => "\u{F88D}",+ "maitrilowleftthai" => "\u{F892}",+ "maitrilowrightthai" => "\u{F891}",+ "maitrithai" => "\u{0E4A}",+ "maitriupperleftthai" => "\u{F890}",+ "maiyamokthai" => "\u{0E46}",+ "makatakana" => "\u{30DE}",+ "makatakanahalfwidth" => "\u{FF8F}",+ "male" => "\u{2642}",+ "mansyonsquare" => "\u{3347}",+ "maqafhebrew" => "\u{05BE}",+ "mars" => "\u{2642}",+ "masoracirclehebrew" => "\u{05AF}",+ "masquare" => "\u{3383}",+ "mbopomofo" => "\u{3107}",+ "mbsquare" => "\u{33D4}",+ "mcircle" => "\u{24DC}",+ "mcubedsquare" => "\u{33A5}",+ "mdotaccent" => "\u{1E41}",+ "mdotbelow" => "\u{1E43}",+ "meemarabic" => "\u{0645}",+ "meemfinalarabic" => "\u{FEE2}",+ "meeminitialarabic" => "\u{FEE3}",+ "meemmedialarabic" => "\u{FEE4}",+ "meemmeeminitialarabic" => "\u{FCD1}",+ "meemmeemisolatedarabic" => "\u{FC48}",+ "meetorusquare" => "\u{334D}",+ "mehiragana" => "\u{3081}",+ "meizierasquare" => "\u{337E}",+ "mekatakana" => "\u{30E1}",+ "mekatakanahalfwidth" => "\u{FF92}",+ "mem" => "\u{05DE}",+ "memdagesh" => "\u{FB3E}",+ "memdageshhebrew" => "\u{FB3E}",+ "memhebrew" => "\u{05DE}",+ "menarmenian" => "\u{0574}",+ "merkhahebrew" => "\u{05A5}",+ "merkhakefulahebrew" => "\u{05A6}",+ "merkhakefulalefthebrew" => "\u{05A6}",+ "merkhalefthebrew" => "\u{05A5}",+ "mhook" => "\u{0271}",+ "mhzsquare" => "\u{3392}",+ "middledotkatakanahalfwidth" => "\u{FF65}",+ "middot" => "\u{00B7}",+ "mieumacirclekorean" => "\u{3272}",+ "mieumaparenkorean" => "\u{3212}",+ "mieumcirclekorean" => "\u{3264}",+ "mieumkorean" => "\u{3141}",+ "mieumpansioskorean" => "\u{3170}",+ "mieumparenkorean" => "\u{3204}",+ "mieumpieupkorean" => "\u{316E}",+ "mieumsioskorean" => "\u{316F}",+ "mihiragana" => "\u{307F}",+ "mikatakana" => "\u{30DF}",+ "mikatakanahalfwidth" => "\u{FF90}",+ "minus" => "\u{2212}",+ "minusbelowcmb" => "\u{0320}",+ "minuscircle" => "\u{2296}",+ "minusmod" => "\u{02D7}",+ "minusplus" => "\u{2213}",+ "minute" => "\u{2032}",+ "miribaarusquare" => "\u{334A}",+ "mirisquare" => "\u{3349}",+ "mlonglegturned" => "\u{0270}",+ "mlsquare" => "\u{3396}",+ "mmcubedsquare" => "\u{33A3}",+ "mmonospace" => "\u{FF4D}",+ "mmsquaredsquare" => "\u{339F}",+ "mohiragana" => "\u{3082}",+ "mohmsquare" => "\u{33C1}",+ "mokatakana" => "\u{30E2}",+ "mokatakanahalfwidth" => "\u{FF93}",+ "molsquare" => "\u{33D6}",+ "momathai" => "\u{0E21}",+ "moverssquare" => "\u{33A7}",+ "moverssquaredsquare" => "\u{33A8}",+ "mparen" => "\u{24A8}",+ "mpasquare" => "\u{33AB}",+ "mssquare" => "\u{33B3}",+ "msuperior" => "\u{F6EF}",+ "mturned" => "\u{026F}",+ "mu" => "\u{00B5}",+ "mu1" => "\u{00B5}",+ "muasquare" => "\u{3382}",+ "muchgreater" => "\u{226B}",+ "muchless" => "\u{226A}",+ "mufsquare" => "\u{338C}",+ "mugreek" => "\u{03BC}",+ "mugsquare" => "\u{338D}",+ "muhiragana" => "\u{3080}",+ "mukatakana" => "\u{30E0}",+ "mukatakanahalfwidth" => "\u{FF91}",+ "mulsquare" => "\u{3395}",+ "multiply" => "\u{00D7}",+ "mumsquare" => "\u{339B}",+ "munahhebrew" => "\u{05A3}",+ "munahlefthebrew" => "\u{05A3}",+ "musicalnote" => "\u{266A}",+ "musicalnotedbl" => "\u{266B}",+ "musicflatsign" => "\u{266D}",+ "musicsharpsign" => "\u{266F}",+ "mussquare" => "\u{33B2}",+ "muvsquare" => "\u{33B6}",+ "muwsquare" => "\u{33BC}",+ "mvmegasquare" => "\u{33B9}",+ "mvsquare" => "\u{33B7}",+ "mwmegasquare" => "\u{33BF}",+ "mwsquare" => "\u{33BD}",+ "n" => "\u{006E}",+ "nabengali" => "\u{09A8}",+ "nabla" => "\u{2207}",+ "nacute" => "\u{0144}",+ "nadeva" => "\u{0928}",+ "nagujarati" => "\u{0AA8}",+ "nagurmukhi" => "\u{0A28}",+ "nahiragana" => "\u{306A}",+ "nakatakana" => "\u{30CA}",+ "nakatakanahalfwidth" => "\u{FF85}",+ "napostrophe" => "\u{0149}",+ "nasquare" => "\u{3381}",+ "nbopomofo" => "\u{310B}",+ "nbspace" => "\u{00A0}",+ "ncaron" => "\u{0148}",+ "ncedilla" => "\u{0146}",+ "ncircle" => "\u{24DD}",+ "ncircumflexbelow" => "\u{1E4B}",+ "ncommaaccent" => "\u{0146}",+ "ndotaccent" => "\u{1E45}",+ "ndotbelow" => "\u{1E47}",+ "nehiragana" => "\u{306D}",+ "nekatakana" => "\u{30CD}",+ "nekatakanahalfwidth" => "\u{FF88}",+ "newsheqelsign" => "\u{20AA}",+ "nfsquare" => "\u{338B}",+ "ngabengali" => "\u{0999}",+ "ngadeva" => "\u{0919}",+ "ngagujarati" => "\u{0A99}",+ "ngagurmukhi" => "\u{0A19}",+ "ngonguthai" => "\u{0E07}",+ "nhiragana" => "\u{3093}",+ "nhookleft" => "\u{0272}",+ "nhookretroflex" => "\u{0273}",+ "nieunacirclekorean" => "\u{326F}",+ "nieunaparenkorean" => "\u{320F}",+ "nieuncieuckorean" => "\u{3135}",+ "nieuncirclekorean" => "\u{3261}",+ "nieunhieuhkorean" => "\u{3136}",+ "nieunkorean" => "\u{3134}",+ "nieunpansioskorean" => "\u{3168}",+ "nieunparenkorean" => "\u{3201}",+ "nieunsioskorean" => "\u{3167}",+ "nieuntikeutkorean" => "\u{3166}",+ "nihiragana" => "\u{306B}",+ "nikatakana" => "\u{30CB}",+ "nikatakanahalfwidth" => "\u{FF86}",+ "nikhahitleftthai" => "\u{F899}",+ "nikhahitthai" => "\u{0E4D}",+ "nine" => "\u{0039}",+ "ninearabic" => "\u{0669}",+ "ninebengali" => "\u{09EF}",+ "ninecircle" => "\u{2468}",+ "ninecircleinversesansserif" => "\u{2792}",+ "ninedeva" => "\u{096F}",+ "ninegujarati" => "\u{0AEF}",+ "ninegurmukhi" => "\u{0A6F}",+ "ninehackarabic" => "\u{0669}",+ "ninehangzhou" => "\u{3029}",+ "nineideographicparen" => "\u{3228}",+ "nineinferior" => "\u{2089}",+ "ninemonospace" => "\u{FF19}",+ "nineoldstyle" => "\u{F739}",+ "nineparen" => "\u{247C}",+ "nineperiod" => "\u{2490}",+ "ninepersian" => "\u{06F9}",+ "nineroman" => "\u{2178}",+ "ninesuperior" => "\u{2079}",+ "nineteencircle" => "\u{2472}",+ "nineteenparen" => "\u{2486}",+ "nineteenperiod" => "\u{249A}",+ "ninethai" => "\u{0E59}",+ "nj" => "\u{01CC}",+ "njecyrillic" => "\u{045A}",+ "nkatakana" => "\u{30F3}",+ "nkatakanahalfwidth" => "\u{FF9D}",+ "nlegrightlong" => "\u{019E}",+ "nlinebelow" => "\u{1E49}",+ "nmonospace" => "\u{FF4E}",+ "nmsquare" => "\u{339A}",+ "nnabengali" => "\u{09A3}",+ "nnadeva" => "\u{0923}",+ "nnagujarati" => "\u{0AA3}",+ "nnagurmukhi" => "\u{0A23}",+ "nnnadeva" => "\u{0929}",+ "nohiragana" => "\u{306E}",+ "nokatakana" => "\u{30CE}",+ "nokatakanahalfwidth" => "\u{FF89}",+ "nonbreakingspace" => "\u{00A0}",+ "nonenthai" => "\u{0E13}",+ "nonuthai" => "\u{0E19}",+ "noonarabic" => "\u{0646}",+ "noonfinalarabic" => "\u{FEE6}",+ "noonghunnaarabic" => "\u{06BA}",+ "noonghunnafinalarabic" => "\u{FB9F}",+ "noonhehinitialarabic" => "\u{FEE7}\u{FEEC}",+ "nooninitialarabic" => "\u{FEE7}",+ "noonjeeminitialarabic" => "\u{FCD2}",+ "noonjeemisolatedarabic" => "\u{FC4B}",+ "noonmedialarabic" => "\u{FEE8}",+ "noonmeeminitialarabic" => "\u{FCD5}",+ "noonmeemisolatedarabic" => "\u{FC4E}",+ "noonnoonfinalarabic" => "\u{FC8D}",+ "notcontains" => "\u{220C}",+ "notelement" => "\u{2209}",+ "notelementof" => "\u{2209}",+ "notequal" => "\u{2260}",+ "notgreater" => "\u{226F}",+ "notgreaternorequal" => "\u{2271}",+ "notgreaternorless" => "\u{2279}",+ "notidentical" => "\u{2262}",+ "notless" => "\u{226E}",+ "notlessnorequal" => "\u{2270}",+ "notparallel" => "\u{2226}",+ "notprecedes" => "\u{2280}",+ "notsubset" => "\u{2284}",+ "notsucceeds" => "\u{2281}",+ "notsuperset" => "\u{2285}",+ "nowarmenian" => "\u{0576}",+ "nparen" => "\u{24A9}",+ "nssquare" => "\u{33B1}",+ "nsuperior" => "\u{207F}",+ "ntilde" => "\u{00F1}",+ "nu" => "\u{03BD}",+ "nuhiragana" => "\u{306C}",+ "nukatakana" => "\u{30CC}",+ "nukatakanahalfwidth" => "\u{FF87}",+ "nuktabengali" => "\u{09BC}",+ "nuktadeva" => "\u{093C}",+ "nuktagujarati" => "\u{0ABC}",+ "nuktagurmukhi" => "\u{0A3C}",+ "numbersign" => "\u{0023}",+ "numbersignmonospace" => "\u{FF03}",+ "numbersignsmall" => "\u{FE5F}",+ "numeralsigngreek" => "\u{0374}",+ "numeralsignlowergreek" => "\u{0375}",+ "numero" => "\u{2116}",+ "nun" => "\u{05E0}",+ "nundagesh" => "\u{FB40}",+ "nundageshhebrew" => "\u{FB40}",+ "nunhebrew" => "\u{05E0}",+ "nvsquare" => "\u{33B5}",+ "nwsquare" => "\u{33BB}",+ "nyabengali" => "\u{099E}",+ "nyadeva" => "\u{091E}",+ "nyagujarati" => "\u{0A9E}",+ "nyagurmukhi" => "\u{0A1E}",+ "o" => "\u{006F}",+ "oacute" => "\u{00F3}",+ "oangthai" => "\u{0E2D}",+ "obarred" => "\u{0275}",+ "obarredcyrillic" => "\u{04E9}",+ "obarreddieresiscyrillic" => "\u{04EB}",+ "obengali" => "\u{0993}",+ "obopomofo" => "\u{311B}",+ "obreve" => "\u{014F}",+ "ocandradeva" => "\u{0911}",+ "ocandragujarati" => "\u{0A91}",+ "ocandravowelsigndeva" => "\u{0949}",+ "ocandravowelsigngujarati" => "\u{0AC9}",+ "ocaron" => "\u{01D2}",+ "ocircle" => "\u{24DE}",+ "ocircumflex" => "\u{00F4}",+ "ocircumflexacute" => "\u{1ED1}",+ "ocircumflexdotbelow" => "\u{1ED9}",+ "ocircumflexgrave" => "\u{1ED3}",+ "ocircumflexhookabove" => "\u{1ED5}",+ "ocircumflextilde" => "\u{1ED7}",+ "ocyrillic" => "\u{043E}",+ "odblacute" => "\u{0151}",+ "odblgrave" => "\u{020D}",+ "odeva" => "\u{0913}",+ "odieresis" => "\u{00F6}",+ "odieresiscyrillic" => "\u{04E7}",+ "odotbelow" => "\u{1ECD}",+ "oe" => "\u{0153}",+ "oekorean" => "\u{315A}",+ "ogonek" => "\u{02DB}",+ "ogonekcmb" => "\u{0328}",+ "ograve" => "\u{00F2}",+ "ogujarati" => "\u{0A93}",+ "oharmenian" => "\u{0585}",+ "ohiragana" => "\u{304A}",+ "ohookabove" => "\u{1ECF}",+ "ohorn" => "\u{01A1}",+ "ohornacute" => "\u{1EDB}",+ "ohorndotbelow" => "\u{1EE3}",+ "ohorngrave" => "\u{1EDD}",+ "ohornhookabove" => "\u{1EDF}",+ "ohorntilde" => "\u{1EE1}",+ "ohungarumlaut" => "\u{0151}",+ "oi" => "\u{01A3}",+ "oinvertedbreve" => "\u{020F}",+ "okatakana" => "\u{30AA}",+ "okatakanahalfwidth" => "\u{FF75}",+ "okorean" => "\u{3157}",+ "olehebrew" => "\u{05AB}",+ "omacron" => "\u{014D}",+ "omacronacute" => "\u{1E53}",+ "omacrongrave" => "\u{1E51}",+ "omdeva" => "\u{0950}",+ "omega" => "\u{03C9}",+ "omega1" => "\u{03D6}",+ "omegacyrillic" => "\u{0461}",+ "omegalatinclosed" => "\u{0277}",+ "omegaroundcyrillic" => "\u{047B}",+ "omegatitlocyrillic" => "\u{047D}",+ "omegatonos" => "\u{03CE}",+ "omgujarati" => "\u{0AD0}",+ "omicron" => "\u{03BF}",+ "omicrontonos" => "\u{03CC}",+ "omonospace" => "\u{FF4F}",+ "one" => "\u{0031}",+ "onearabic" => "\u{0661}",+ "onebengali" => "\u{09E7}",+ "onecircle" => "\u{2460}",+ "onecircleinversesansserif" => "\u{278A}",+ "onedeva" => "\u{0967}",+ "onedotenleader" => "\u{2024}",+ "oneeighth" => "\u{215B}",+ "onefitted" => "\u{F6DC}",+ "onegujarati" => "\u{0AE7}",+ "onegurmukhi" => "\u{0A67}",+ "onehackarabic" => "\u{0661}",+ "onehalf" => "\u{00BD}",+ "onehangzhou" => "\u{3021}",+ "oneideographicparen" => "\u{3220}",+ "oneinferior" => "\u{2081}",+ "onemonospace" => "\u{FF11}",+ "onenumeratorbengali" => "\u{09F4}",+ "oneoldstyle" => "\u{F731}",+ "oneparen" => "\u{2474}",+ "oneperiod" => "\u{2488}",+ "onepersian" => "\u{06F1}",+ "onequarter" => "\u{00BC}",+ "oneroman" => "\u{2170}",+ "onesuperior" => "\u{00B9}",+ "onethai" => "\u{0E51}",+ "onethird" => "\u{2153}",+ "oogonek" => "\u{01EB}",+ "oogonekmacron" => "\u{01ED}",+ "oogurmukhi" => "\u{0A13}",+ "oomatragurmukhi" => "\u{0A4B}",+ "oopen" => "\u{0254}",+ "oparen" => "\u{24AA}",+ "openbullet" => "\u{25E6}",+ "option" => "\u{2325}",+ "ordfeminine" => "\u{00AA}",+ "ordmasculine" => "\u{00BA}",+ "orthogonal" => "\u{221F}",+ "oshortdeva" => "\u{0912}",+ "oshortvowelsigndeva" => "\u{094A}",+ "oslash" => "\u{00F8}",+ "oslashacute" => "\u{01FF}",+ "osmallhiragana" => "\u{3049}",+ "osmallkatakana" => "\u{30A9}",+ "osmallkatakanahalfwidth" => "\u{FF6B}",+ "ostrokeacute" => "\u{01FF}",+ "osuperior" => "\u{F6F0}",+ "otcyrillic" => "\u{047F}",+ "otilde" => "\u{00F5}",+ "otildeacute" => "\u{1E4D}",+ "otildedieresis" => "\u{1E4F}",+ "oubopomofo" => "\u{3121}",+ "overline" => "\u{203E}",+ "overlinecenterline" => "\u{FE4A}",+ "overlinecmb" => "\u{0305}",+ "overlinedashed" => "\u{FE49}",+ "overlinedblwavy" => "\u{FE4C}",+ "overlinewavy" => "\u{FE4B}",+ "overscore" => "\u{00AF}",+ "ovowelsignbengali" => "\u{09CB}",+ "ovowelsigndeva" => "\u{094B}",+ "ovowelsigngujarati" => "\u{0ACB}",+ "p" => "\u{0070}",+ "paampssquare" => "\u{3380}",+ "paasentosquare" => "\u{332B}",+ "pabengali" => "\u{09AA}",+ "pacute" => "\u{1E55}",+ "padeva" => "\u{092A}",+ "pagedown" => "\u{21DF}",+ "pageup" => "\u{21DE}",+ "pagujarati" => "\u{0AAA}",+ "pagurmukhi" => "\u{0A2A}",+ "pahiragana" => "\u{3071}",+ "paiyannoithai" => "\u{0E2F}",+ "pakatakana" => "\u{30D1}",+ "palatalizationcyrilliccmb" => "\u{0484}",+ "palochkacyrillic" => "\u{04C0}",+ "pansioskorean" => "\u{317F}",+ "paragraph" => "\u{00B6}",+ "parallel" => "\u{2225}",+ "parenleft" => "\u{0028}",+ "parenleftaltonearabic" => "\u{FD3E}",+ "parenleftbt" => "\u{F8ED}",+ "parenleftex" => "\u{F8EC}",+ "parenleftinferior" => "\u{208D}",+ "parenleftmonospace" => "\u{FF08}",+ "parenleftsmall" => "\u{FE59}",+ "parenleftsuperior" => "\u{207D}",+ "parenlefttp" => "\u{F8EB}",+ "parenleftvertical" => "\u{FE35}",+ "parenright" => "\u{0029}",+ "parenrightaltonearabic" => "\u{FD3F}",+ "parenrightbt" => "\u{F8F8}",+ "parenrightex" => "\u{F8F7}",+ "parenrightinferior" => "\u{208E}",+ "parenrightmonospace" => "\u{FF09}",+ "parenrightsmall" => "\u{FE5A}",+ "parenrightsuperior" => "\u{207E}",+ "parenrighttp" => "\u{F8F6}",+ "parenrightvertical" => "\u{FE36}",+ "partialdiff" => "\u{2202}",+ "paseqhebrew" => "\u{05C0}",+ "pashtahebrew" => "\u{0599}",+ "pasquare" => "\u{33A9}",+ "patah" => "\u{05B7}",+ "patah11" => "\u{05B7}",+ "patah1d" => "\u{05B7}",+ "patah2a" => "\u{05B7}",+ "patahhebrew" => "\u{05B7}",+ "patahnarrowhebrew" => "\u{05B7}",+ "patahquarterhebrew" => "\u{05B7}",+ "patahwidehebrew" => "\u{05B7}",+ "pazerhebrew" => "\u{05A1}",+ "pbopomofo" => "\u{3106}",+ "pcircle" => "\u{24DF}",+ "pdotaccent" => "\u{1E57}",+ "pe" => "\u{05E4}",+ "pecyrillic" => "\u{043F}",+ "pedagesh" => "\u{FB44}",+ "pedageshhebrew" => "\u{FB44}",+ "peezisquare" => "\u{333B}",+ "pefinaldageshhebrew" => "\u{FB43}",+ "peharabic" => "\u{067E}",+ "peharmenian" => "\u{057A}",+ "pehebrew" => "\u{05E4}",+ "pehfinalarabic" => "\u{FB57}",+ "pehinitialarabic" => "\u{FB58}",+ "pehiragana" => "\u{307A}",+ "pehmedialarabic" => "\u{FB59}",+ "pekatakana" => "\u{30DA}",+ "pemiddlehookcyrillic" => "\u{04A7}",+ "perafehebrew" => "\u{FB4E}",+ "percent" => "\u{0025}",+ "percentarabic" => "\u{066A}",+ "percentmonospace" => "\u{FF05}",+ "percentsmall" => "\u{FE6A}",+ "period" => "\u{002E}",+ "periodarmenian" => "\u{0589}",+ "periodcentered" => "\u{00B7}",+ "periodhalfwidth" => "\u{FF61}",+ "periodinferior" => "\u{F6E7}",+ "periodmonospace" => "\u{FF0E}",+ "periodsmall" => "\u{FE52}",+ "periodsuperior" => "\u{F6E8}",+ "perispomenigreekcmb" => "\u{0342}",+ "perpendicular" => "\u{22A5}",+ "perthousand" => "\u{2030}",+ "peseta" => "\u{20A7}",+ "pfsquare" => "\u{338A}",+ "phabengali" => "\u{09AB}",+ "phadeva" => "\u{092B}",+ "phagujarati" => "\u{0AAB}",+ "phagurmukhi" => "\u{0A2B}",+ "phi" => "\u{03C6}",+ "phi1" => "\u{03D5}",+ "phieuphacirclekorean" => "\u{327A}",+ "phieuphaparenkorean" => "\u{321A}",+ "phieuphcirclekorean" => "\u{326C}",+ "phieuphkorean" => "\u{314D}",+ "phieuphparenkorean" => "\u{320C}",+ "philatin" => "\u{0278}",+ "phinthuthai" => "\u{0E3A}",+ "phisymbolgreek" => "\u{03D5}",+ "phook" => "\u{01A5}",+ "phophanthai" => "\u{0E1E}",+ "phophungthai" => "\u{0E1C}",+ "phosamphaothai" => "\u{0E20}",+ "pi" => "\u{03C0}",+ "pieupacirclekorean" => "\u{3273}",+ "pieupaparenkorean" => "\u{3213}",+ "pieupcieuckorean" => "\u{3176}",+ "pieupcirclekorean" => "\u{3265}",+ "pieupkiyeokkorean" => "\u{3172}",+ "pieupkorean" => "\u{3142}",+ "pieupparenkorean" => "\u{3205}",+ "pieupsioskiyeokkorean" => "\u{3174}",+ "pieupsioskorean" => "\u{3144}",+ "pieupsiostikeutkorean" => "\u{3175}",+ "pieupthieuthkorean" => "\u{3177}",+ "pieuptikeutkorean" => "\u{3173}",+ "pihiragana" => "\u{3074}",+ "pikatakana" => "\u{30D4}",+ "pisymbolgreek" => "\u{03D6}",+ "piwrarmenian" => "\u{0583}",+ "plus" => "\u{002B}",+ "plusbelowcmb" => "\u{031F}",+ "pluscircle" => "\u{2295}",+ "plusminus" => "\u{00B1}",+ "plusmod" => "\u{02D6}",+ "plusmonospace" => "\u{FF0B}",+ "plussmall" => "\u{FE62}",+ "plussuperior" => "\u{207A}",+ "pmonospace" => "\u{FF50}",+ "pmsquare" => "\u{33D8}",+ "pohiragana" => "\u{307D}",+ "pointingindexdownwhite" => "\u{261F}",+ "pointingindexleftwhite" => "\u{261C}",+ "pointingindexrightwhite" => "\u{261E}",+ "pointingindexupwhite" => "\u{261D}",+ "pokatakana" => "\u{30DD}",+ "poplathai" => "\u{0E1B}",+ "postalmark" => "\u{3012}",+ "postalmarkface" => "\u{3020}",+ "pparen" => "\u{24AB}",+ "precedes" => "\u{227A}",+ "prescription" => "\u{211E}",+ "primemod" => "\u{02B9}",+ "primereversed" => "\u{2035}",+ "product" => "\u{220F}",+ "projective" => "\u{2305}",+ "prolongedkana" => "\u{30FC}",+ "propellor" => "\u{2318}",+ "propersubset" => "\u{2282}",+ "propersuperset" => "\u{2283}",+ "proportion" => "\u{2237}",+ "proportional" => "\u{221D}",+ "psi" => "\u{03C8}",+ "psicyrillic" => "\u{0471}",+ "psilipneumatacyrilliccmb" => "\u{0486}",+ "pssquare" => "\u{33B0}",+ "puhiragana" => "\u{3077}",+ "pukatakana" => "\u{30D7}",+ "pvsquare" => "\u{33B4}",+ "pwsquare" => "\u{33BA}",+ "q" => "\u{0071}",+ "qadeva" => "\u{0958}",+ "qadmahebrew" => "\u{05A8}",+ "qafarabic" => "\u{0642}",+ "qaffinalarabic" => "\u{FED6}",+ "qafinitialarabic" => "\u{FED7}",+ "qafmedialarabic" => "\u{FED8}",+ "qamats" => "\u{05B8}",+ "qamats10" => "\u{05B8}",+ "qamats1a" => "\u{05B8}",+ "qamats1c" => "\u{05B8}",+ "qamats27" => "\u{05B8}",+ "qamats29" => "\u{05B8}",+ "qamats33" => "\u{05B8}",+ "qamatsde" => "\u{05B8}",+ "qamatshebrew" => "\u{05B8}",+ "qamatsnarrowhebrew" => "\u{05B8}",+ "qamatsqatanhebrew" => "\u{05B8}",+ "qamatsqatannarrowhebrew" => "\u{05B8}",+ "qamatsqatanquarterhebrew" => "\u{05B8}",+ "qamatsqatanwidehebrew" => "\u{05B8}",+ "qamatsquarterhebrew" => "\u{05B8}",+ "qamatswidehebrew" => "\u{05B8}",+ "qarneyparahebrew" => "\u{059F}",+ "qbopomofo" => "\u{3111}",+ "qcircle" => "\u{24E0}",+ "qhook" => "\u{02A0}",+ "qmonospace" => "\u{FF51}",+ "qof" => "\u{05E7}",+ "qofdagesh" => "\u{FB47}",+ "qofdageshhebrew" => "\u{FB47}",+ "qofhatafpatah" => "\u{05E7}\u{05B2}",+ "qofhatafpatahhebrew" => "\u{05E7}\u{05B2}",+ "qofhatafsegol" => "\u{05E7}\u{05B1}",+ "qofhatafsegolhebrew" => "\u{05E7}\u{05B1}",+ "qofhebrew" => "\u{05E7}",+ "qofhiriq" => "\u{05E7}\u{05B4}",+ "qofhiriqhebrew" => "\u{05E7}\u{05B4}",+ "qofholam" => "\u{05E7}\u{05B9}",+ "qofholamhebrew" => "\u{05E7}\u{05B9}",+ "qofpatah" => "\u{05E7}\u{05B7}",+ "qofpatahhebrew" => "\u{05E7}\u{05B7}",+ "qofqamats" => "\u{05E7}\u{05B8}",+ "qofqamatshebrew" => "\u{05E7}\u{05B8}",+ "qofqubuts" => "\u{05E7}\u{05BB}",+ "qofqubutshebrew" => "\u{05E7}\u{05BB}",+ "qofsegol" => "\u{05E7}\u{05B6}",+ "qofsegolhebrew" => "\u{05E7}\u{05B6}",+ "qofsheva" => "\u{05E7}\u{05B0}",+ "qofshevahebrew" => "\u{05E7}\u{05B0}",+ "qoftsere" => "\u{05E7}\u{05B5}",+ "qoftserehebrew" => "\u{05E7}\u{05B5}",+ "qparen" => "\u{24AC}",+ "quarternote" => "\u{2669}",+ "qubuts" => "\u{05BB}",+ "qubuts18" => "\u{05BB}",+ "qubuts25" => "\u{05BB}",+ "qubuts31" => "\u{05BB}",+ "qubutshebrew" => "\u{05BB}",+ "qubutsnarrowhebrew" => "\u{05BB}",+ "qubutsquarterhebrew" => "\u{05BB}",+ "qubutswidehebrew" => "\u{05BB}",+ "question" => "\u{003F}",+ "questionarabic" => "\u{061F}",+ "questionarmenian" => "\u{055E}",+ "questiondown" => "\u{00BF}",+ "questiondownsmall" => "\u{F7BF}",+ "questiongreek" => "\u{037E}",+ "questionmonospace" => "\u{FF1F}",+ "questionsmall" => "\u{F73F}",+ "quotedbl" => "\u{0022}",+ "quotedblbase" => "\u{201E}",+ "quotedblleft" => "\u{201C}",+ "quotedblmonospace" => "\u{FF02}",+ "quotedblprime" => "\u{301E}",+ "quotedblprimereversed" => "\u{301D}",+ "quotedblright" => "\u{201D}",+ "quoteleft" => "\u{2018}",+ "quoteleftreversed" => "\u{201B}",+ "quotereversed" => "\u{201B}",+ "quoteright" => "\u{2019}",+ "quoterightn" => "\u{0149}",+ "quotesinglbase" => "\u{201A}",+ "quotesingle" => "\u{0027}",+ "quotesinglemonospace" => "\u{FF07}",+ "r" => "\u{0072}",+ "raarmenian" => "\u{057C}",+ "rabengali" => "\u{09B0}",+ "racute" => "\u{0155}",+ "radeva" => "\u{0930}",+ "radical" => "\u{221A}",+ "radicalex" => "\u{F8E5}",+ "radoverssquare" => "\u{33AE}",+ "radoverssquaredsquare" => "\u{33AF}",+ "radsquare" => "\u{33AD}",+ "rafe" => "\u{05BF}",+ "rafehebrew" => "\u{05BF}",+ "ragujarati" => "\u{0AB0}",+ "ragurmukhi" => "\u{0A30}",+ "rahiragana" => "\u{3089}",+ "rakatakana" => "\u{30E9}",+ "rakatakanahalfwidth" => "\u{FF97}",+ "ralowerdiagonalbengali" => "\u{09F1}",+ "ramiddlediagonalbengali" => "\u{09F0}",+ "ramshorn" => "\u{0264}",+ "ratio" => "\u{2236}",+ "rbopomofo" => "\u{3116}",+ "rcaron" => "\u{0159}",+ "rcedilla" => "\u{0157}",+ "rcircle" => "\u{24E1}",+ "rcommaaccent" => "\u{0157}",+ "rdblgrave" => "\u{0211}",+ "rdotaccent" => "\u{1E59}",+ "rdotbelow" => "\u{1E5B}",+ "rdotbelowmacron" => "\u{1E5D}",+ "referencemark" => "\u{203B}",+ "reflexsubset" => "\u{2286}",+ "reflexsuperset" => "\u{2287}",+ "registered" => "\u{00AE}",+ "registersans" => "\u{F8E8}",+ "registerserif" => "\u{F6DA}",+ "reharabic" => "\u{0631}",+ "reharmenian" => "\u{0580}",+ "rehfinalarabic" => "\u{FEAE}",+ "rehiragana" => "\u{308C}",+ "rehyehaleflamarabic" => "\u{0631}\u{FEF3}\u{FE8E}\u{0644}",+ "rekatakana" => "\u{30EC}",+ "rekatakanahalfwidth" => "\u{FF9A}",+ "resh" => "\u{05E8}",+ "reshdageshhebrew" => "\u{FB48}",+ "reshhatafpatah" => "\u{05E8}\u{05B2}",+ "reshhatafpatahhebrew" => "\u{05E8}\u{05B2}",+ "reshhatafsegol" => "\u{05E8}\u{05B1}",+ "reshhatafsegolhebrew" => "\u{05E8}\u{05B1}",+ "reshhebrew" => "\u{05E8}",+ "reshhiriq" => "\u{05E8}\u{05B4}",+ "reshhiriqhebrew" => "\u{05E8}\u{05B4}",+ "reshholam" => "\u{05E8}\u{05B9}",+ "reshholamhebrew" => "\u{05E8}\u{05B9}",+ "reshpatah" => "\u{05E8}\u{05B7}",+ "reshpatahhebrew" => "\u{05E8}\u{05B7}",+ "reshqamats" => "\u{05E8}\u{05B8}",+ "reshqamatshebrew" => "\u{05E8}\u{05B8}",+ "reshqubuts" => "\u{05E8}\u{05BB}",+ "reshqubutshebrew" => "\u{05E8}\u{05BB}",+ "reshsegol" => "\u{05E8}\u{05B6}",+ "reshsegolhebrew" => "\u{05E8}\u{05B6}",+ "reshsheva" => "\u{05E8}\u{05B0}",+ "reshshevahebrew" => "\u{05E8}\u{05B0}",+ "reshtsere" => "\u{05E8}\u{05B5}",+ "reshtserehebrew" => "\u{05E8}\u{05B5}",+ "reversedtilde" => "\u{223D}",+ "reviahebrew" => "\u{0597}",+ "reviamugrashhebrew" => "\u{0597}",+ "revlogicalnot" => "\u{2310}",+ "rfishhook" => "\u{027E}",+ "rfishhookreversed" => "\u{027F}",+ "rhabengali" => "\u{09DD}",+ "rhadeva" => "\u{095D}",+ "rho" => "\u{03C1}",+ "rhook" => "\u{027D}",+ "rhookturned" => "\u{027B}",+ "rhookturnedsuperior" => "\u{02B5}",+ "rhosymbolgreek" => "\u{03F1}",+ "rhotichookmod" => "\u{02DE}",+ "rieulacirclekorean" => "\u{3271}",+ "rieulaparenkorean" => "\u{3211}",+ "rieulcirclekorean" => "\u{3263}",+ "rieulhieuhkorean" => "\u{3140}",+ "rieulkiyeokkorean" => "\u{313A}",+ "rieulkiyeoksioskorean" => "\u{3169}",+ "rieulkorean" => "\u{3139}",+ "rieulmieumkorean" => "\u{313B}",+ "rieulpansioskorean" => "\u{316C}",+ "rieulparenkorean" => "\u{3203}",+ "rieulphieuphkorean" => "\u{313F}",+ "rieulpieupkorean" => "\u{313C}",+ "rieulpieupsioskorean" => "\u{316B}",+ "rieulsioskorean" => "\u{313D}",+ "rieulthieuthkorean" => "\u{313E}",+ "rieultikeutkorean" => "\u{316A}",+ "rieulyeorinhieuhkorean" => "\u{316D}",+ "rightangle" => "\u{221F}",+ "righttackbelowcmb" => "\u{0319}",+ "righttriangle" => "\u{22BF}",+ "rihiragana" => "\u{308A}",+ "rikatakana" => "\u{30EA}",+ "rikatakanahalfwidth" => "\u{FF98}",+ "ring" => "\u{02DA}",+ "ringbelowcmb" => "\u{0325}",+ "ringcmb" => "\u{030A}",+ "ringhalfleft" => "\u{02BF}",+ "ringhalfleftarmenian" => "\u{0559}",+ "ringhalfleftbelowcmb" => "\u{031C}",+ "ringhalfleftcentered" => "\u{02D3}",+ "ringhalfright" => "\u{02BE}",+ "ringhalfrightbelowcmb" => "\u{0339}",+ "ringhalfrightcentered" => "\u{02D2}",+ "rinvertedbreve" => "\u{0213}",+ "rittorusquare" => "\u{3351}",+ "rlinebelow" => "\u{1E5F}",+ "rlongleg" => "\u{027C}",+ "rlonglegturned" => "\u{027A}",+ "rmonospace" => "\u{FF52}",+ "rohiragana" => "\u{308D}",+ "rokatakana" => "\u{30ED}",+ "rokatakanahalfwidth" => "\u{FF9B}",+ "roruathai" => "\u{0E23}",+ "rparen" => "\u{24AD}",+ "rrabengali" => "\u{09DC}",+ "rradeva" => "\u{0931}",+ "rragurmukhi" => "\u{0A5C}",+ "rreharabic" => "\u{0691}",+ "rrehfinalarabic" => "\u{FB8D}",+ "rrvocalicbengali" => "\u{09E0}",+ "rrvocalicdeva" => "\u{0960}",+ "rrvocalicgujarati" => "\u{0AE0}",+ "rrvocalicvowelsignbengali" => "\u{09C4}",+ "rrvocalicvowelsigndeva" => "\u{0944}",+ "rrvocalicvowelsigngujarati" => "\u{0AC4}",+ "rsuperior" => "\u{F6F1}",+ "rtblock" => "\u{2590}",+ "rturned" => "\u{0279}",+ "rturnedsuperior" => "\u{02B4}",+ "ruhiragana" => "\u{308B}",+ "rukatakana" => "\u{30EB}",+ "rukatakanahalfwidth" => "\u{FF99}",+ "rupeemarkbengali" => "\u{09F2}",+ "rupeesignbengali" => "\u{09F3}",+ "rupiah" => "\u{F6DD}",+ "ruthai" => "\u{0E24}",+ "rvocalicbengali" => "\u{098B}",+ "rvocalicdeva" => "\u{090B}",+ "rvocalicgujarati" => "\u{0A8B}",+ "rvocalicvowelsignbengali" => "\u{09C3}",+ "rvocalicvowelsigndeva" => "\u{0943}",+ "rvocalicvowelsigngujarati" => "\u{0AC3}",+ "s" => "\u{0073}",+ "sabengali" => "\u{09B8}",+ "sacute" => "\u{015B}",+ "sacutedotaccent" => "\u{1E65}",+ "sadarabic" => "\u{0635}",+ "sadeva" => "\u{0938}",+ "sadfinalarabic" => "\u{FEBA}",+ "sadinitialarabic" => "\u{FEBB}",+ "sadmedialarabic" => "\u{FEBC}",+ "sagujarati" => "\u{0AB8}",+ "sagurmukhi" => "\u{0A38}",+ "sahiragana" => "\u{3055}",+ "sakatakana" => "\u{30B5}",+ "sakatakanahalfwidth" => "\u{FF7B}",+ "sallallahoualayhewasallamarabic" => "\u{FDFA}",+ "samekh" => "\u{05E1}",+ "samekhdagesh" => "\u{FB41}",+ "samekhdageshhebrew" => "\u{FB41}",+ "samekhhebrew" => "\u{05E1}",+ "saraaathai" => "\u{0E32}",+ "saraaethai" => "\u{0E41}",+ "saraaimaimalaithai" => "\u{0E44}",+ "saraaimaimuanthai" => "\u{0E43}",+ "saraamthai" => "\u{0E33}",+ "saraathai" => "\u{0E30}",+ "saraethai" => "\u{0E40}",+ "saraiileftthai" => "\u{F886}",+ "saraiithai" => "\u{0E35}",+ "saraileftthai" => "\u{F885}",+ "saraithai" => "\u{0E34}",+ "saraothai" => "\u{0E42}",+ "saraueeleftthai" => "\u{F888}",+ "saraueethai" => "\u{0E37}",+ "saraueleftthai" => "\u{F887}",+ "sarauethai" => "\u{0E36}",+ "sarauthai" => "\u{0E38}",+ "sarauuthai" => "\u{0E39}",+ "sbopomofo" => "\u{3119}",+ "scaron" => "\u{0161}",+ "scarondotaccent" => "\u{1E67}",+ "scedilla" => "\u{015F}",+ "schwa" => "\u{0259}",+ "schwacyrillic" => "\u{04D9}",+ "schwadieresiscyrillic" => "\u{04DB}",+ "schwahook" => "\u{025A}",+ "scircle" => "\u{24E2}",+ "scircumflex" => "\u{015D}",+ "scommaaccent" => "\u{0219}",+ "sdotaccent" => "\u{1E61}",+ "sdotbelow" => "\u{1E63}",+ "sdotbelowdotaccent" => "\u{1E69}",+ "seagullbelowcmb" => "\u{033C}",+ "second" => "\u{2033}",+ "secondtonechinese" => "\u{02CA}",+ "section" => "\u{00A7}",+ "seenarabic" => "\u{0633}",+ "seenfinalarabic" => "\u{FEB2}",+ "seeninitialarabic" => "\u{FEB3}",+ "seenmedialarabic" => "\u{FEB4}",+ "segol" => "\u{05B6}",+ "segol13" => "\u{05B6}",+ "segol1f" => "\u{05B6}",+ "segol2c" => "\u{05B6}",+ "segolhebrew" => "\u{05B6}",+ "segolnarrowhebrew" => "\u{05B6}",+ "segolquarterhebrew" => "\u{05B6}",+ "segoltahebrew" => "\u{0592}",+ "segolwidehebrew" => "\u{05B6}",+ "seharmenian" => "\u{057D}",+ "sehiragana" => "\u{305B}",+ "sekatakana" => "\u{30BB}",+ "sekatakanahalfwidth" => "\u{FF7E}",+ "semicolon" => "\u{003B}",+ "semicolonarabic" => "\u{061B}",+ "semicolonmonospace" => "\u{FF1B}",+ "semicolonsmall" => "\u{FE54}",+ "semivoicedmarkkana" => "\u{309C}",+ "semivoicedmarkkanahalfwidth" => "\u{FF9F}",+ "sentisquare" => "\u{3322}",+ "sentosquare" => "\u{3323}",+ "seven" => "\u{0037}",+ "sevenarabic" => "\u{0667}",+ "sevenbengali" => "\u{09ED}",+ "sevencircle" => "\u{2466}",+ "sevencircleinversesansserif" => "\u{2790}",+ "sevendeva" => "\u{096D}",+ "seveneighths" => "\u{215E}",+ "sevengujarati" => "\u{0AED}",+ "sevengurmukhi" => "\u{0A6D}",+ "sevenhackarabic" => "\u{0667}",+ "sevenhangzhou" => "\u{3027}",+ "sevenideographicparen" => "\u{3226}",+ "seveninferior" => "\u{2087}",+ "sevenmonospace" => "\u{FF17}",+ "sevenoldstyle" => "\u{F737}",+ "sevenparen" => "\u{247A}",+ "sevenperiod" => "\u{248E}",+ "sevenpersian" => "\u{06F7}",+ "sevenroman" => "\u{2176}",+ "sevensuperior" => "\u{2077}",+ "seventeencircle" => "\u{2470}",+ "seventeenparen" => "\u{2484}",+ "seventeenperiod" => "\u{2498}",+ "seventhai" => "\u{0E57}",+ "sfthyphen" => "\u{00AD}",+ "shaarmenian" => "\u{0577}",+ "shabengali" => "\u{09B6}",+ "shacyrillic" => "\u{0448}",+ "shaddaarabic" => "\u{0651}",+ "shaddadammaarabic" => "\u{FC61}",+ "shaddadammatanarabic" => "\u{FC5E}",+ "shaddafathaarabic" => "\u{FC60}",+ "shaddafathatanarabic" => "\u{0651}\u{064B}",+ "shaddakasraarabic" => "\u{FC62}",+ "shaddakasratanarabic" => "\u{FC5F}",+ "shade" => "\u{2592}",+ "shadedark" => "\u{2593}",+ "shadelight" => "\u{2591}",+ "shademedium" => "\u{2592}",+ "shadeva" => "\u{0936}",+ "shagujarati" => "\u{0AB6}",+ "shagurmukhi" => "\u{0A36}",+ "shalshelethebrew" => "\u{0593}",+ "shbopomofo" => "\u{3115}",+ "shchacyrillic" => "\u{0449}",+ "sheenarabic" => "\u{0634}",+ "sheenfinalarabic" => "\u{FEB6}",+ "sheeninitialarabic" => "\u{FEB7}",+ "sheenmedialarabic" => "\u{FEB8}",+ "sheicoptic" => "\u{03E3}",+ "sheqel" => "\u{20AA}",+ "sheqelhebrew" => "\u{20AA}",+ "sheva" => "\u{05B0}",+ "sheva115" => "\u{05B0}",+ "sheva15" => "\u{05B0}",+ "sheva22" => "\u{05B0}",+ "sheva2e" => "\u{05B0}",+ "shevahebrew" => "\u{05B0}",+ "shevanarrowhebrew" => "\u{05B0}",+ "shevaquarterhebrew" => "\u{05B0}",+ "shevawidehebrew" => "\u{05B0}",+ "shhacyrillic" => "\u{04BB}",+ "shimacoptic" => "\u{03ED}",+ "shin" => "\u{05E9}",+ "shindagesh" => "\u{FB49}",+ "shindageshhebrew" => "\u{FB49}",+ "shindageshshindot" => "\u{FB2C}",+ "shindageshshindothebrew" => "\u{FB2C}",+ "shindageshsindot" => "\u{FB2D}",+ "shindageshsindothebrew" => "\u{FB2D}",+ "shindothebrew" => "\u{05C1}",+ "shinhebrew" => "\u{05E9}",+ "shinshindot" => "\u{FB2A}",+ "shinshindothebrew" => "\u{FB2A}",+ "shinsindot" => "\u{FB2B}",+ "shinsindothebrew" => "\u{FB2B}",+ "shook" => "\u{0282}",+ "sigma" => "\u{03C3}",+ "sigma1" => "\u{03C2}",+ "sigmafinal" => "\u{03C2}",+ "sigmalunatesymbolgreek" => "\u{03F2}",+ "sihiragana" => "\u{3057}",+ "sikatakana" => "\u{30B7}",+ "sikatakanahalfwidth" => "\u{FF7C}",+ "siluqhebrew" => "\u{05BD}",+ "siluqlefthebrew" => "\u{05BD}",+ "similar" => "\u{223C}",+ "sindothebrew" => "\u{05C2}",+ "siosacirclekorean" => "\u{3274}",+ "siosaparenkorean" => "\u{3214}",+ "sioscieuckorean" => "\u{317E}",+ "sioscirclekorean" => "\u{3266}",+ "sioskiyeokkorean" => "\u{317A}",+ "sioskorean" => "\u{3145}",+ "siosnieunkorean" => "\u{317B}",+ "siosparenkorean" => "\u{3206}",+ "siospieupkorean" => "\u{317D}",+ "siostikeutkorean" => "\u{317C}",+ "six" => "\u{0036}",+ "sixarabic" => "\u{0666}",+ "sixbengali" => "\u{09EC}",+ "sixcircle" => "\u{2465}",+ "sixcircleinversesansserif" => "\u{278F}",+ "sixdeva" => "\u{096C}",+ "sixgujarati" => "\u{0AEC}",+ "sixgurmukhi" => "\u{0A6C}",+ "sixhackarabic" => "\u{0666}",+ "sixhangzhou" => "\u{3026}",+ "sixideographicparen" => "\u{3225}",+ "sixinferior" => "\u{2086}",+ "sixmonospace" => "\u{FF16}",+ "sixoldstyle" => "\u{F736}",+ "sixparen" => "\u{2479}",+ "sixperiod" => "\u{248D}",+ "sixpersian" => "\u{06F6}",+ "sixroman" => "\u{2175}",+ "sixsuperior" => "\u{2076}",+ "sixteencircle" => "\u{246F}",+ "sixteencurrencydenominatorbengali" => "\u{09F9}",+ "sixteenparen" => "\u{2483}",+ "sixteenperiod" => "\u{2497}",+ "sixthai" => "\u{0E56}",+ "slash" => "\u{002F}",+ "slashmonospace" => "\u{FF0F}",+ "slong" => "\u{017F}",+ "slongdotaccent" => "\u{1E9B}",+ "smileface" => "\u{263A}",+ "smonospace" => "\u{FF53}",+ "sofpasuqhebrew" => "\u{05C3}",+ "softhyphen" => "\u{00AD}",+ "softsigncyrillic" => "\u{044C}",+ "sohiragana" => "\u{305D}",+ "sokatakana" => "\u{30BD}",+ "sokatakanahalfwidth" => "\u{FF7F}",+ "soliduslongoverlaycmb" => "\u{0338}",+ "solidusshortoverlaycmb" => "\u{0337}",+ "sorusithai" => "\u{0E29}",+ "sosalathai" => "\u{0E28}",+ "sosothai" => "\u{0E0B}",+ "sosuathai" => "\u{0E2A}",+ "space" => "\u{0020}",+ "spacehackarabic" => "\u{0020}",+ "spade" => "\u{2660}",+ "spadesuitblack" => "\u{2660}",+ "spadesuitwhite" => "\u{2664}",+ "sparen" => "\u{24AE}",+ "squarebelowcmb" => "\u{033B}",+ "squarecc" => "\u{33C4}",+ "squarecm" => "\u{339D}",+ "squarediagonalcrosshatchfill" => "\u{25A9}",+ "squarehorizontalfill" => "\u{25A4}",+ "squarekg" => "\u{338F}",+ "squarekm" => "\u{339E}",+ "squarekmcapital" => "\u{33CE}",+ "squareln" => "\u{33D1}",+ "squarelog" => "\u{33D2}",+ "squaremg" => "\u{338E}",+ "squaremil" => "\u{33D5}",+ "squaremm" => "\u{339C}",+ "squaremsquared" => "\u{33A1}",+ "squareorthogonalcrosshatchfill" => "\u{25A6}",+ "squareupperlefttolowerrightfill" => "\u{25A7}",+ "squareupperrighttolowerleftfill" => "\u{25A8}",+ "squareverticalfill" => "\u{25A5}",+ "squarewhitewithsmallblack" => "\u{25A3}",+ "srsquare" => "\u{33DB}",+ "ssabengali" => "\u{09B7}",+ "ssadeva" => "\u{0937}",+ "ssagujarati" => "\u{0AB7}",+ "ssangcieuckorean" => "\u{3149}",+ "ssanghieuhkorean" => "\u{3185}",+ "ssangieungkorean" => "\u{3180}",+ "ssangkiyeokkorean" => "\u{3132}",+ "ssangnieunkorean" => "\u{3165}",+ "ssangpieupkorean" => "\u{3143}",+ "ssangsioskorean" => "\u{3146}",+ "ssangtikeutkorean" => "\u{3138}",+ "ssuperior" => "\u{F6F2}",+ "sterling" => "\u{00A3}",+ "sterlingmonospace" => "\u{FFE1}",+ "strokelongoverlaycmb" => "\u{0336}",+ "strokeshortoverlaycmb" => "\u{0335}",+ "subset" => "\u{2282}",+ "subsetnotequal" => "\u{228A}",+ "subsetorequal" => "\u{2286}",+ "succeeds" => "\u{227B}",+ "suchthat" => "\u{220B}",+ "suhiragana" => "\u{3059}",+ "sukatakana" => "\u{30B9}",+ "sukatakanahalfwidth" => "\u{FF7D}",+ "sukunarabic" => "\u{0652}",+ "summation" => "\u{2211}",+ "sun" => "\u{263C}",+ "superset" => "\u{2283}",+ "supersetnotequal" => "\u{228B}",+ "supersetorequal" => "\u{2287}",+ "svsquare" => "\u{33DC}",+ "syouwaerasquare" => "\u{337C}",+ "t" => "\u{0074}",+ "tabengali" => "\u{09A4}",+ "tackdown" => "\u{22A4}",+ "tackleft" => "\u{22A3}",+ "tadeva" => "\u{0924}",+ "tagujarati" => "\u{0AA4}",+ "tagurmukhi" => "\u{0A24}",+ "taharabic" => "\u{0637}",+ "tahfinalarabic" => "\u{FEC2}",+ "tahinitialarabic" => "\u{FEC3}",+ "tahiragana" => "\u{305F}",+ "tahmedialarabic" => "\u{FEC4}",+ "taisyouerasquare" => "\u{337D}",+ "takatakana" => "\u{30BF}",+ "takatakanahalfwidth" => "\u{FF80}",+ "tatweelarabic" => "\u{0640}",+ "tau" => "\u{03C4}",+ "tav" => "\u{05EA}",+ "tavdages" => "\u{FB4A}",+ "tavdagesh" => "\u{FB4A}",+ "tavdageshhebrew" => "\u{FB4A}",+ "tavhebrew" => "\u{05EA}",+ "tbar" => "\u{0167}",+ "tbopomofo" => "\u{310A}",+ "tcaron" => "\u{0165}",+ "tccurl" => "\u{02A8}",+ "tcedilla" => "\u{0163}",+ "tcheharabic" => "\u{0686}",+ "tchehfinalarabic" => "\u{FB7B}",+ "tchehinitialarabic" => "\u{FB7C}",+ "tchehmedialarabic" => "\u{FB7D}",+ "tchehmeeminitialarabic" => "\u{FB7C}\u{FEE4}",+ "tcircle" => "\u{24E3}",+ "tcircumflexbelow" => "\u{1E71}",+ "tcommaaccent" => "\u{0163}",+ "tdieresis" => "\u{1E97}",+ "tdotaccent" => "\u{1E6B}",+ "tdotbelow" => "\u{1E6D}",+ "tecyrillic" => "\u{0442}",+ "tedescendercyrillic" => "\u{04AD}",+ "teharabic" => "\u{062A}",+ "tehfinalarabic" => "\u{FE96}",+ "tehhahinitialarabic" => "\u{FCA2}",+ "tehhahisolatedarabic" => "\u{FC0C}",+ "tehinitialarabic" => "\u{FE97}",+ "tehiragana" => "\u{3066}",+ "tehjeeminitialarabic" => "\u{FCA1}",+ "tehjeemisolatedarabic" => "\u{FC0B}",+ "tehmarbutaarabic" => "\u{0629}",+ "tehmarbutafinalarabic" => "\u{FE94}",+ "tehmedialarabic" => "\u{FE98}",+ "tehmeeminitialarabic" => "\u{FCA4}",+ "tehmeemisolatedarabic" => "\u{FC0E}",+ "tehnoonfinalarabic" => "\u{FC73}",+ "tekatakana" => "\u{30C6}",+ "tekatakanahalfwidth" => "\u{FF83}",+ "telephone" => "\u{2121}",+ "telephoneblack" => "\u{260E}",+ "telishagedolahebrew" => "\u{05A0}",+ "telishaqetanahebrew" => "\u{05A9}",+ "tencircle" => "\u{2469}",+ "tenideographicparen" => "\u{3229}",+ "tenparen" => "\u{247D}",+ "tenperiod" => "\u{2491}",+ "tenroman" => "\u{2179}",+ "tesh" => "\u{02A7}",+ "tet" => "\u{05D8}",+ "tetdagesh" => "\u{FB38}",+ "tetdageshhebrew" => "\u{FB38}",+ "tethebrew" => "\u{05D8}",+ "tetsecyrillic" => "\u{04B5}",+ "tevirhebrew" => "\u{059B}",+ "tevirlefthebrew" => "\u{059B}",+ "thabengali" => "\u{09A5}",+ "thadeva" => "\u{0925}",+ "thagujarati" => "\u{0AA5}",+ "thagurmukhi" => "\u{0A25}",+ "thalarabic" => "\u{0630}",+ "thalfinalarabic" => "\u{FEAC}",+ "thanthakhatlowleftthai" => "\u{F898}",+ "thanthakhatlowrightthai" => "\u{F897}",+ "thanthakhatthai" => "\u{0E4C}",+ "thanthakhatupperleftthai" => "\u{F896}",+ "theharabic" => "\u{062B}",+ "thehfinalarabic" => "\u{FE9A}",+ "thehinitialarabic" => "\u{FE9B}",+ "thehmedialarabic" => "\u{FE9C}",+ "thereexists" => "\u{2203}",+ "therefore" => "\u{2234}",+ "theta" => "\u{03B8}",+ "theta1" => "\u{03D1}",+ "thetasymbolgreek" => "\u{03D1}",+ "thieuthacirclekorean" => "\u{3279}",+ "thieuthaparenkorean" => "\u{3219}",+ "thieuthcirclekorean" => "\u{326B}",+ "thieuthkorean" => "\u{314C}",+ "thieuthparenkorean" => "\u{320B}",+ "thirteencircle" => "\u{246C}",+ "thirteenparen" => "\u{2480}",+ "thirteenperiod" => "\u{2494}",+ "thonangmonthothai" => "\u{0E11}",+ "thook" => "\u{01AD}",+ "thophuthaothai" => "\u{0E12}",+ "thorn" => "\u{00FE}",+ "thothahanthai" => "\u{0E17}",+ "thothanthai" => "\u{0E10}",+ "thothongthai" => "\u{0E18}",+ "thothungthai" => "\u{0E16}",+ "thousandcyrillic" => "\u{0482}",+ "thousandsseparatorarabic" => "\u{066C}",+ "thousandsseparatorpersian" => "\u{066C}",+ "three" => "\u{0033}",+ "threearabic" => "\u{0663}",+ "threebengali" => "\u{09E9}",+ "threecircle" => "\u{2462}",+ "threecircleinversesansserif" => "\u{278C}",+ "threedeva" => "\u{0969}",+ "threeeighths" => "\u{215C}",+ "threegujarati" => "\u{0AE9}",+ "threegurmukhi" => "\u{0A69}",+ "threehackarabic" => "\u{0663}",+ "threehangzhou" => "\u{3023}",+ "threeideographicparen" => "\u{3222}",+ "threeinferior" => "\u{2083}",+ "threemonospace" => "\u{FF13}",+ "threenumeratorbengali" => "\u{09F6}",+ "threeoldstyle" => "\u{F733}",+ "threeparen" => "\u{2476}",+ "threeperiod" => "\u{248A}",+ "threepersian" => "\u{06F3}",+ "threequarters" => "\u{00BE}",+ "threequartersemdash" => "\u{F6DE}",+ "threeroman" => "\u{2172}",+ "threesuperior" => "\u{00B3}",+ "threethai" => "\u{0E53}",+ "thzsquare" => "\u{3394}",+ "tihiragana" => "\u{3061}",+ "tikatakana" => "\u{30C1}",+ "tikatakanahalfwidth" => "\u{FF81}",+ "tikeutacirclekorean" => "\u{3270}",+ "tikeutaparenkorean" => "\u{3210}",+ "tikeutcirclekorean" => "\u{3262}",+ "tikeutkorean" => "\u{3137}",+ "tikeutparenkorean" => "\u{3202}",+ "tilde" => "\u{02DC}",+ "tildebelowcmb" => "\u{0330}",+ "tildecmb" => "\u{0303}",+ "tildecomb" => "\u{0303}",+ "tildedoublecmb" => "\u{0360}",+ "tildeoperator" => "\u{223C}",+ "tildeoverlaycmb" => "\u{0334}",+ "tildeverticalcmb" => "\u{033E}",+ "timescircle" => "\u{2297}",+ "tipehahebrew" => "\u{0596}",+ "tipehalefthebrew" => "\u{0596}",+ "tippigurmukhi" => "\u{0A70}",+ "titlocyrilliccmb" => "\u{0483}",+ "tiwnarmenian" => "\u{057F}",+ "tlinebelow" => "\u{1E6F}",+ "tmonospace" => "\u{FF54}",+ "toarmenian" => "\u{0569}",+ "tohiragana" => "\u{3068}",+ "tokatakana" => "\u{30C8}",+ "tokatakanahalfwidth" => "\u{FF84}",+ "tonebarextrahighmod" => "\u{02E5}",+ "tonebarextralowmod" => "\u{02E9}",+ "tonebarhighmod" => "\u{02E6}",+ "tonebarlowmod" => "\u{02E8}",+ "tonebarmidmod" => "\u{02E7}",+ "tonefive" => "\u{01BD}",+ "tonesix" => "\u{0185}",+ "tonetwo" => "\u{01A8}",+ "tonos" => "\u{0384}",+ "tonsquare" => "\u{3327}",+ "topatakthai" => "\u{0E0F}",+ "tortoiseshellbracketleft" => "\u{3014}",+ "tortoiseshellbracketleftsmall" => "\u{FE5D}",+ "tortoiseshellbracketleftvertical" => "\u{FE39}",+ "tortoiseshellbracketright" => "\u{3015}",+ "tortoiseshellbracketrightsmall" => "\u{FE5E}",+ "tortoiseshellbracketrightvertical" => "\u{FE3A}",+ "totaothai" => "\u{0E15}",+ "tpalatalhook" => "\u{01AB}",+ "tparen" => "\u{24AF}",+ "trademark" => "\u{2122}",+ "trademarksans" => "\u{F8EA}",+ "trademarkserif" => "\u{F6DB}",+ "tretroflexhook" => "\u{0288}",+ "triagdn" => "\u{25BC}",+ "triaglf" => "\u{25C4}",+ "triagrt" => "\u{25BA}",+ "triagup" => "\u{25B2}",+ "ts" => "\u{02A6}",+ "tsadi" => "\u{05E6}",+ "tsadidagesh" => "\u{FB46}",+ "tsadidageshhebrew" => "\u{FB46}",+ "tsadihebrew" => "\u{05E6}",+ "tsecyrillic" => "\u{0446}",+ "tsere" => "\u{05B5}",+ "tsere12" => "\u{05B5}",+ "tsere1e" => "\u{05B5}",+ "tsere2b" => "\u{05B5}",+ "tserehebrew" => "\u{05B5}",+ "tserenarrowhebrew" => "\u{05B5}",+ "tserequarterhebrew" => "\u{05B5}",+ "tserewidehebrew" => "\u{05B5}",+ "tshecyrillic" => "\u{045B}",+ "tsuperior" => "\u{F6F3}",+ "ttabengali" => "\u{099F}",+ "ttadeva" => "\u{091F}",+ "ttagujarati" => "\u{0A9F}",+ "ttagurmukhi" => "\u{0A1F}",+ "tteharabic" => "\u{0679}",+ "ttehfinalarabic" => "\u{FB67}",+ "ttehinitialarabic" => "\u{FB68}",+ "ttehmedialarabic" => "\u{FB69}",+ "tthabengali" => "\u{09A0}",+ "tthadeva" => "\u{0920}",+ "tthagujarati" => "\u{0AA0}",+ "tthagurmukhi" => "\u{0A20}",+ "tturned" => "\u{0287}",+ "tuhiragana" => "\u{3064}",+ "tukatakana" => "\u{30C4}",+ "tukatakanahalfwidth" => "\u{FF82}",+ "tusmallhiragana" => "\u{3063}",+ "tusmallkatakana" => "\u{30C3}",+ "tusmallkatakanahalfwidth" => "\u{FF6F}",+ "twelvecircle" => "\u{246B}",+ "twelveparen" => "\u{247F}",+ "twelveperiod" => "\u{2493}",+ "twelveroman" => "\u{217B}",+ "twentycircle" => "\u{2473}",+ "twentyhangzhou" => "\u{5344}",+ "twentyparen" => "\u{2487}",+ "twentyperiod" => "\u{249B}",+ "two" => "\u{0032}",+ "twoarabic" => "\u{0662}",+ "twobengali" => "\u{09E8}",+ "twocircle" => "\u{2461}",+ "twocircleinversesansserif" => "\u{278B}",+ "twodeva" => "\u{0968}",+ "twodotenleader" => "\u{2025}",+ "twodotleader" => "\u{2025}",+ "twodotleadervertical" => "\u{FE30}",+ "twogujarati" => "\u{0AE8}",+ "twogurmukhi" => "\u{0A68}",+ "twohackarabic" => "\u{0662}",+ "twohangzhou" => "\u{3022}",+ "twoideographicparen" => "\u{3221}",+ "twoinferior" => "\u{2082}",+ "twomonospace" => "\u{FF12}",+ "twonumeratorbengali" => "\u{09F5}",+ "twooldstyle" => "\u{F732}",+ "twoparen" => "\u{2475}",+ "twoperiod" => "\u{2489}",+ "twopersian" => "\u{06F2}",+ "tworoman" => "\u{2171}",+ "twostroke" => "\u{01BB}",+ "twosuperior" => "\u{00B2}",+ "twothai" => "\u{0E52}",+ "twothirds" => "\u{2154}",+ "u" => "\u{0075}",+ "uacute" => "\u{00FA}",+ "ubar" => "\u{0289}",+ "ubengali" => "\u{0989}",+ "ubopomofo" => "\u{3128}",+ "ubreve" => "\u{016D}",+ "ucaron" => "\u{01D4}",+ "ucircle" => "\u{24E4}",+ "ucircumflex" => "\u{00FB}",+ "ucircumflexbelow" => "\u{1E77}",+ "ucyrillic" => "\u{0443}",+ "udattadeva" => "\u{0951}",+ "udblacute" => "\u{0171}",+ "udblgrave" => "\u{0215}",+ "udeva" => "\u{0909}",+ "udieresis" => "\u{00FC}",+ "udieresisacute" => "\u{01D8}",+ "udieresisbelow" => "\u{1E73}",+ "udieresiscaron" => "\u{01DA}",+ "udieresiscyrillic" => "\u{04F1}",+ "udieresisgrave" => "\u{01DC}",+ "udieresismacron" => "\u{01D6}",+ "udotbelow" => "\u{1EE5}",+ "ugrave" => "\u{00F9}",+ "ugujarati" => "\u{0A89}",+ "ugurmukhi" => "\u{0A09}",+ "uhiragana" => "\u{3046}",+ "uhookabove" => "\u{1EE7}",+ "uhorn" => "\u{01B0}",+ "uhornacute" => "\u{1EE9}",+ "uhorndotbelow" => "\u{1EF1}",+ "uhorngrave" => "\u{1EEB}",+ "uhornhookabove" => "\u{1EED}",+ "uhorntilde" => "\u{1EEF}",+ "uhungarumlaut" => "\u{0171}",+ "uhungarumlautcyrillic" => "\u{04F3}",+ "uinvertedbreve" => "\u{0217}",+ "ukatakana" => "\u{30A6}",+ "ukatakanahalfwidth" => "\u{FF73}",+ "ukcyrillic" => "\u{0479}",+ "ukorean" => "\u{315C}",+ "umacron" => "\u{016B}",+ "umacroncyrillic" => "\u{04EF}",+ "umacrondieresis" => "\u{1E7B}",+ "umatragurmukhi" => "\u{0A41}",+ "umonospace" => "\u{FF55}",+ "underscore" => "\u{005F}",+ "underscoredbl" => "\u{2017}",+ "underscoremonospace" => "\u{FF3F}",+ "underscorevertical" => "\u{FE33}",+ "underscorewavy" => "\u{FE4F}",+ "union" => "\u{222A}",+ "universal" => "\u{2200}",+ "uogonek" => "\u{0173}",+ "uparen" => "\u{24B0}",+ "upblock" => "\u{2580}",+ "upperdothebrew" => "\u{05C4}",+ "upsilon" => "\u{03C5}",+ "upsilondieresis" => "\u{03CB}",+ "upsilondieresistonos" => "\u{03B0}",+ "upsilonlatin" => "\u{028A}",+ "upsilontonos" => "\u{03CD}",+ "uptackbelowcmb" => "\u{031D}",+ "uptackmod" => "\u{02D4}",+ "uragurmukhi" => "\u{0A73}",+ "uring" => "\u{016F}",+ "ushortcyrillic" => "\u{045E}",+ "usmallhiragana" => "\u{3045}",+ "usmallkatakana" => "\u{30A5}",+ "usmallkatakanahalfwidth" => "\u{FF69}",+ "ustraightcyrillic" => "\u{04AF}",+ "ustraightstrokecyrillic" => "\u{04B1}",+ "utilde" => "\u{0169}",+ "utildeacute" => "\u{1E79}",+ "utildebelow" => "\u{1E75}",+ "uubengali" => "\u{098A}",+ "uudeva" => "\u{090A}",+ "uugujarati" => "\u{0A8A}",+ "uugurmukhi" => "\u{0A0A}",+ "uumatragurmukhi" => "\u{0A42}",+ "uuvowelsignbengali" => "\u{09C2}",+ "uuvowelsigndeva" => "\u{0942}",+ "uuvowelsigngujarati" => "\u{0AC2}",+ "uvowelsignbengali" => "\u{09C1}",+ "uvowelsigndeva" => "\u{0941}",+ "uvowelsigngujarati" => "\u{0AC1}",+ "v" => "\u{0076}",+ "vadeva" => "\u{0935}",+ "vagujarati" => "\u{0AB5}",+ "vagurmukhi" => "\u{0A35}",+ "vakatakana" => "\u{30F7}",+ "vav" => "\u{05D5}",+ "vavdagesh" => "\u{FB35}",+ "vavdagesh65" => "\u{FB35}",+ "vavdageshhebrew" => "\u{FB35}",+ "vavhebrew" => "\u{05D5}",+ "vavholam" => "\u{FB4B}",+ "vavholamhebrew" => "\u{FB4B}",+ "vavvavhebrew" => "\u{05F0}",+ "vavyodhebrew" => "\u{05F1}",+ "vcircle" => "\u{24E5}",+ "vdotbelow" => "\u{1E7F}",+ "vecyrillic" => "\u{0432}",+ "veharabic" => "\u{06A4}",+ "vehfinalarabic" => "\u{FB6B}",+ "vehinitialarabic" => "\u{FB6C}",+ "vehmedialarabic" => "\u{FB6D}",+ "vekatakana" => "\u{30F9}",+ "venus" => "\u{2640}",+ "verticalbar" => "\u{007C}",+ "verticallineabovecmb" => "\u{030D}",+ "verticallinebelowcmb" => "\u{0329}",+ "verticallinelowmod" => "\u{02CC}",+ "verticallinemod" => "\u{02C8}",+ "vewarmenian" => "\u{057E}",+ "vhook" => "\u{028B}",+ "vikatakana" => "\u{30F8}",+ "viramabengali" => "\u{09CD}",+ "viramadeva" => "\u{094D}",+ "viramagujarati" => "\u{0ACD}",+ "visargabengali" => "\u{0983}",+ "visargadeva" => "\u{0903}",+ "visargagujarati" => "\u{0A83}",+ "vmonospace" => "\u{FF56}",+ "voarmenian" => "\u{0578}",+ "voicediterationhiragana" => "\u{309E}",+ "voicediterationkatakana" => "\u{30FE}",+ "voicedmarkkana" => "\u{309B}",+ "voicedmarkkanahalfwidth" => "\u{FF9E}",+ "vokatakana" => "\u{30FA}",+ "vparen" => "\u{24B1}",+ "vtilde" => "\u{1E7D}",+ "vturned" => "\u{028C}",+ "vuhiragana" => "\u{3094}",+ "vukatakana" => "\u{30F4}",+ "w" => "\u{0077}",+ "wacute" => "\u{1E83}",+ "waekorean" => "\u{3159}",+ "wahiragana" => "\u{308F}",+ "wakatakana" => "\u{30EF}",+ "wakatakanahalfwidth" => "\u{FF9C}",+ "wakorean" => "\u{3158}",+ "wasmallhiragana" => "\u{308E}",+ "wasmallkatakana" => "\u{30EE}",+ "wattosquare" => "\u{3357}",+ "wavedash" => "\u{301C}",+ "wavyunderscorevertical" => "\u{FE34}",+ "wawarabic" => "\u{0648}",+ "wawfinalarabic" => "\u{FEEE}",+ "wawhamzaabovearabic" => "\u{0624}",+ "wawhamzaabovefinalarabic" => "\u{FE86}",+ "wbsquare" => "\u{33DD}",+ "wcircle" => "\u{24E6}",+ "wcircumflex" => "\u{0175}",+ "wdieresis" => "\u{1E85}",+ "wdotaccent" => "\u{1E87}",+ "wdotbelow" => "\u{1E89}",+ "wehiragana" => "\u{3091}",+ "weierstrass" => "\u{2118}",+ "wekatakana" => "\u{30F1}",+ "wekorean" => "\u{315E}",+ "weokorean" => "\u{315D}",+ "wgrave" => "\u{1E81}",+ "whitebullet" => "\u{25E6}",+ "whitecircle" => "\u{25CB}",+ "whitecircleinverse" => "\u{25D9}",+ "whitecornerbracketleft" => "\u{300E}",+ "whitecornerbracketleftvertical" => "\u{FE43}",+ "whitecornerbracketright" => "\u{300F}",+ "whitecornerbracketrightvertical" => "\u{FE44}",+ "whitediamond" => "\u{25C7}",+ "whitediamondcontainingblacksmalldiamond" => "\u{25C8}",+ "whitedownpointingsmalltriangle" => "\u{25BF}",+ "whitedownpointingtriangle" => "\u{25BD}",+ "whiteleftpointingsmalltriangle" => "\u{25C3}",+ "whiteleftpointingtriangle" => "\u{25C1}",+ "whitelenticularbracketleft" => "\u{3016}",+ "whitelenticularbracketright" => "\u{3017}",+ "whiterightpointingsmalltriangle" => "\u{25B9}",+ "whiterightpointingtriangle" => "\u{25B7}",+ "whitesmallsquare" => "\u{25AB}",+ "whitesmilingface" => "\u{263A}",+ "whitesquare" => "\u{25A1}",+ "whitestar" => "\u{2606}",+ "whitetelephone" => "\u{260F}",+ "whitetortoiseshellbracketleft" => "\u{3018}",+ "whitetortoiseshellbracketright" => "\u{3019}",+ "whiteuppointingsmalltriangle" => "\u{25B5}",+ "whiteuppointingtriangle" => "\u{25B3}",+ "wihiragana" => "\u{3090}",+ "wikatakana" => "\u{30F0}",+ "wikorean" => "\u{315F}",+ "wmonospace" => "\u{FF57}",+ "wohiragana" => "\u{3092}",+ "wokatakana" => "\u{30F2}",+ "wokatakanahalfwidth" => "\u{FF66}",+ "won" => "\u{20A9}",+ "wonmonospace" => "\u{FFE6}",+ "wowaenthai" => "\u{0E27}",+ "wparen" => "\u{24B2}",+ "wring" => "\u{1E98}",+ "wsuperior" => "\u{02B7}",+ "wturned" => "\u{028D}",+ "wynn" => "\u{01BF}",+ "x" => "\u{0078}",+ "xabovecmb" => "\u{033D}",+ "xbopomofo" => "\u{3112}",+ "xcircle" => "\u{24E7}",+ "xdieresis" => "\u{1E8D}",+ "xdotaccent" => "\u{1E8B}",+ "xeharmenian" => "\u{056D}",+ "xi" => "\u{03BE}",+ "xmonospace" => "\u{FF58}",+ "xparen" => "\u{24B3}",+ "xsuperior" => "\u{02E3}",+ "y" => "\u{0079}",+ "yaadosquare" => "\u{334E}",+ "yabengali" => "\u{09AF}",+ "yacute" => "\u{00FD}",+ "yadeva" => "\u{092F}",+ "yaekorean" => "\u{3152}",+ "yagujarati" => "\u{0AAF}",+ "yagurmukhi" => "\u{0A2F}",+ "yahiragana" => "\u{3084}",+ "yakatakana" => "\u{30E4}",+ "yakatakanahalfwidth" => "\u{FF94}",+ "yakorean" => "\u{3151}",+ "yamakkanthai" => "\u{0E4E}",+ "yasmallhiragana" => "\u{3083}",+ "yasmallkatakana" => "\u{30E3}",+ "yasmallkatakanahalfwidth" => "\u{FF6C}",+ "yatcyrillic" => "\u{0463}",+ "ycircle" => "\u{24E8}",+ "ycircumflex" => "\u{0177}",+ "ydieresis" => "\u{00FF}",+ "ydotaccent" => "\u{1E8F}",+ "ydotbelow" => "\u{1EF5}",+ "yeharabic" => "\u{064A}",+ "yehbarreearabic" => "\u{06D2}",+ "yehbarreefinalarabic" => "\u{FBAF}",+ "yehfinalarabic" => "\u{FEF2}",+ "yehhamzaabovearabic" => "\u{0626}",+ "yehhamzaabovefinalarabic" => "\u{FE8A}",+ "yehhamzaaboveinitialarabic" => "\u{FE8B}",+ "yehhamzaabovemedialarabic" => "\u{FE8C}",+ "yehinitialarabic" => "\u{FEF3}",+ "yehmedialarabic" => "\u{FEF4}",+ "yehmeeminitialarabic" => "\u{FCDD}",+ "yehmeemisolatedarabic" => "\u{FC58}",+ "yehnoonfinalarabic" => "\u{FC94}",+ "yehthreedotsbelowarabic" => "\u{06D1}",+ "yekorean" => "\u{3156}",+ "yen" => "\u{00A5}",+ "yenmonospace" => "\u{FFE5}",+ "yeokorean" => "\u{3155}",+ "yeorinhieuhkorean" => "\u{3186}",+ "yerahbenyomohebrew" => "\u{05AA}",+ "yerahbenyomolefthebrew" => "\u{05AA}",+ "yericyrillic" => "\u{044B}",+ "yerudieresiscyrillic" => "\u{04F9}",+ "yesieungkorean" => "\u{3181}",+ "yesieungpansioskorean" => "\u{3183}",+ "yesieungsioskorean" => "\u{3182}",+ "yetivhebrew" => "\u{059A}",+ "ygrave" => "\u{1EF3}",+ "yhook" => "\u{01B4}",+ "yhookabove" => "\u{1EF7}",+ "yiarmenian" => "\u{0575}",+ "yicyrillic" => "\u{0457}",+ "yikorean" => "\u{3162}",+ "yinyang" => "\u{262F}",+ "yiwnarmenian" => "\u{0582}",+ "ymonospace" => "\u{FF59}",+ "yod" => "\u{05D9}",+ "yoddagesh" => "\u{FB39}",+ "yoddageshhebrew" => "\u{FB39}",+ "yodhebrew" => "\u{05D9}",+ "yodyodhebrew" => "\u{05F2}",+ "yodyodpatahhebrew" => "\u{FB1F}",+ "yohiragana" => "\u{3088}",+ "yoikorean" => "\u{3189}",+ "yokatakana" => "\u{30E8}",+ "yokatakanahalfwidth" => "\u{FF96}",+ "yokorean" => "\u{315B}",+ "yosmallhiragana" => "\u{3087}",+ "yosmallkatakana" => "\u{30E7}",+ "yosmallkatakanahalfwidth" => "\u{FF6E}",+ "yotgreek" => "\u{03F3}",+ "yoyaekorean" => "\u{3188}",+ "yoyakorean" => "\u{3187}",+ "yoyakthai" => "\u{0E22}",+ "yoyingthai" => "\u{0E0D}",+ "yparen" => "\u{24B4}",+ "ypogegrammeni" => "\u{037A}",+ "ypogegrammenigreekcmb" => "\u{0345}",+ "yr" => "\u{01A6}",+ "yring" => "\u{1E99}",+ "ysuperior" => "\u{02B8}",+ "ytilde" => "\u{1EF9}",+ "yturned" => "\u{028E}",+ "yuhiragana" => "\u{3086}",+ "yuikorean" => "\u{318C}",+ "yukatakana" => "\u{30E6}",+ "yukatakanahalfwidth" => "\u{FF95}",+ "yukorean" => "\u{3160}",+ "yusbigcyrillic" => "\u{046B}",+ "yusbigiotifiedcyrillic" => "\u{046D}",+ "yuslittlecyrillic" => "\u{0467}",+ "yuslittleiotifiedcyrillic" => "\u{0469}",+ "yusmallhiragana" => "\u{3085}",+ "yusmallkatakana" => "\u{30E5}",+ "yusmallkatakanahalfwidth" => "\u{FF6D}",+ "yuyekorean" => "\u{318B}",+ "yuyeokorean" => "\u{318A}",+ "yyabengali" => "\u{09DF}",+ "yyadeva" => "\u{095F}",+ "z" => "\u{007A}",+ "zaarmenian" => "\u{0566}",+ "zacute" => "\u{017A}",+ "zadeva" => "\u{095B}",+ "zagurmukhi" => "\u{0A5B}",+ "zaharabic" => "\u{0638}",+ "zahfinalarabic" => "\u{FEC6}",+ "zahinitialarabic" => "\u{FEC7}",+ "zahiragana" => "\u{3056}",+ "zahmedialarabic" => "\u{FEC8}",+ "zainarabic" => "\u{0632}",+ "zainfinalarabic" => "\u{FEB0}",+ "zakatakana" => "\u{30B6}",+ "zaqefgadolhebrew" => "\u{0595}",+ "zaqefqatanhebrew" => "\u{0594}",+ "zarqahebrew" => "\u{0598}",+ "zayin" => "\u{05D6}",+ "zayindagesh" => "\u{FB36}",+ "zayindageshhebrew" => "\u{FB36}",+ "zayinhebrew" => "\u{05D6}",+ "zbopomofo" => "\u{3117}",+ "zcaron" => "\u{017E}",+ "zcircle" => "\u{24E9}",+ "zcircumflex" => "\u{1E91}",+ "zcurl" => "\u{0291}",+ "zdot" => "\u{017C}",+ "zdotaccent" => "\u{017C}",+ "zdotbelow" => "\u{1E93}",+ "zecyrillic" => "\u{0437}",+ "zedescendercyrillic" => "\u{0499}",+ "zedieresiscyrillic" => "\u{04DF}",+ "zehiragana" => "\u{305C}",+ "zekatakana" => "\u{30BC}",+ "zero" => "\u{0030}",+ "zeroarabic" => "\u{0660}",+ "zerobengali" => "\u{09E6}",+ "zerodeva" => "\u{0966}",+ "zerogujarati" => "\u{0AE6}",+ "zerogurmukhi" => "\u{0A66}",+ "zerohackarabic" => "\u{0660}",+ "zeroinferior" => "\u{2080}",+ "zeromonospace" => "\u{FF10}",+ "zerooldstyle" => "\u{F730}",+ "zeropersian" => "\u{06F0}",+ "zerosuperior" => "\u{2070}",+ "zerothai" => "\u{0E50}",+ "zerowidthjoiner" => "\u{FEFF}",+ "zerowidthnonjoiner" => "\u{200C}",+ "zerowidthspace" => "\u{200B}",+ "zeta" => "\u{03B6}",+ "zhbopomofo" => "\u{3113}",+ "zhearmenian" => "\u{056A}",+ "zhebrevecyrillic" => "\u{04C2}",+ "zhecyrillic" => "\u{0436}",+ "zhedescendercyrillic" => "\u{0497}",+ "zhedieresiscyrillic" => "\u{04DD}",+ "zihiragana" => "\u{3058}",+ "zikatakana" => "\u{30B8}",+ "zinorhebrew" => "\u{05AE}",+ "zlinebelow" => "\u{1E95}",+ "zmonospace" => "\u{FF5A}",+ "zohiragana" => "\u{305E}",+ "zokatakana" => "\u{30BE}",+ "zparen" => "\u{24B5}",+ "zretroflexhook" => "\u{0290}",+ "zstroke" => "\u{01B6}",+ "zuhiragana" => "\u{305A}",+ "zukatakana" => "\u{30BA}",+ "angbracketleft" => "\u{3008}",+ "angbracketright" => "\u{3009}",+ "circlecopyrt" => "\u{00A9}",+ "controlNULL" => "\u{0000}",+ "angbracketleftbig" => "\u{2329}",+ "angbracketleftBig" => "\u{2329}",+ "angbracketleftbigg" => "\u{2329}",+ "angbracketleftBigg" => "\u{2329}",+ "angbracketrightBig" => "\u{232A}",+ "angbracketrightbig" => "\u{232A}",+ "angbracketrightBigg" => "\u{232A}",+ "angbracketrightbigg" => "\u{232A}",+ "arrowhookleft" => "\u{21AA}",+ "arrowhookright" => "\u{21A9}",+ "arrowlefttophalf" => "\u{21BC}",+ "arrowleftbothalf" => "\u{21BD}",+ "arrownortheast" => "\u{2197}",+ "arrownorthwest" => "\u{2196}",+ "arrowrighttophalf" => "\u{21C0}",+ "arrowrightbothalf" => "\u{21C1}",+ "arrowsoutheast" => "\u{2198}",+ "arrowsouthwest" => "\u{2199}",+ "backslashbig" => "\u{2216}",+ "backslashBig" => "\u{2216}",+ "backslashBigg" => "\u{2216}",+ "backslashbigg" => "\u{2216}",+ "bardbl" => "\u{2016}",+ "bracehtipdownleft" => "\u{FE37}",+ "bracehtipdownright" => "\u{FE37}",+ "bracehtipupleft" => "\u{FE38}",+ "bracehtipupright" => "\u{FE38}",+ "braceleftBig" => "\u{007B}",+ "braceleftbig" => "\u{007B}",+ "braceleftbigg" => "\u{007B}",+ "braceleftBigg" => "\u{007B}",+ "bracerightBig" => "\u{007D}",+ "bracerightbig" => "\u{007D}",+ "bracerightbigg" => "\u{007D}",+ "bracerightBigg" => "\u{007D}",+ "bracketleftbig" => "\u{005B}",+ "bracketleftBig" => "\u{005B}",+ "bracketleftbigg" => "\u{005B}",+ "bracketleftBigg" => "\u{005B}",+ "bracketleftmath" => "\u{005B}",+ "bracketrightBig" => "\u{005D}",+ "bracketrightbig" => "\u{005D}",+ "bracketrightbigg" => "\u{005D}",+ "bracketrightBigg" => "\u{005D}",+ "bracketrightmath" => "\u{005D}",+ "ceilingleftbig" => "\u{2308}",+ "ceilingleftBig" => "\u{2308}",+ "ceilingleftBigg" => "\u{2308}",+ "ceilingleftbigg" => "\u{2308}",+ "ceilingrightbig" => "\u{2309}",+ "ceilingrightBig" => "\u{2309}",+ "ceilingrightbigg" => "\u{2309}",+ "ceilingrightBigg" => "\u{2309}",+ "circledotdisplay" => "\u{2299}",+ "circledottext" => "\u{2299}",+ "circlemultiplydisplay" => "\u{2297}",+ "circlemultiplytext" => "\u{2297}",+ "circleplusdisplay" => "\u{2295}",+ "circleplustext" => "\u{2295}",+ "contintegraldisplay" => "\u{222E}",+ "contintegraltext" => "\u{222E}",+ "coproductdisplay" => "\u{2210}",+ "coproducttext" => "\u{2210}",+ "epsilon1" => "\u{03B5}",+ "equalmath" => "\u{003D}",+ "floorleftBig" => "\u{230A}",+ "floorleftbig" => "\u{230A}",+ "floorleftbigg" => "\u{230A}",+ "floorleftBigg" => "\u{230A}",+ "floorrightbig" => "\u{230B}",+ "floorrightBig" => "\u{230B}",+ "floorrightBigg" => "\u{230B}",+ "floorrightbigg" => "\u{230B}",+ "hatwide" => "\u{0302}",+ "hatwider" => "\u{0302}",+ "hatwidest" => "\u{0302}",+ "intercal" => "\u{1D40}",+ "integraldisplay" => "\u{222B}",+ "integraltext" => "\u{222B}",+ "intersectiondisplay" => "\u{22C2}",+ "intersectiontext" => "\u{22C2}",+ "logicalanddisplay" => "\u{2227}",+ "logicalandtext" => "\u{2227}",+ "logicalordisplay" => "\u{2228}",+ "logicalortext" => "\u{2228}",+ "parenleftBig" => "\u{0028}",+ "parenleftbig" => "\u{0028}",+ "parenleftBigg" => "\u{0028}",+ "parenleftbigg" => "\u{0028}",+ "parenleftmath" => "\u{0028}",+ "parenrightBig" => "\u{0029}",+ "parenrightbig" => "\u{0029}",+ "parenrightBigg" => "\u{0029}",+ "parenrightbigg" => "\u{0029}",+ "parenrightmath" => "\u{0029}",+ "plusmath" => "\u{002B}",+ "prime" => "\u{2032}",+ "productdisplay" => "\u{220F}",+ "producttext" => "\u{220F}",+ "radicalbig" => "\u{221A}",+ "radicalBig" => "\u{221A}",+ "radicalBigg" => "\u{221A}",+ "radicalbigg" => "\u{221A}",+ "radicalbt" => "\u{221A}",+ "radicaltp" => "\u{221A}",+ "radicalvertex" => "\u{221A}",+ "slashbig" => "\u{002F}",+ "slashBig" => "\u{002F}",+ "slashBigg" => "\u{002F}",+ "slashbigg" => "\u{002F}",+ "summationdisplay" => "\u{2211}",+ "summationtext" => "\u{2211}",+ "tildewide" => "\u{02DC}",+ "tildewider" => "\u{02DC}",+ "tildewidest" => "\u{02DC}",+ "uniondisplay" => "\u{22C3}",+ "unionmultidisplay" => "\u{228E}",+ "unionmultitext" => "\u{228E}",+ "unionsqdisplay" => "\u{2294}",+ "unionsqtext" => "\u{2294}",+ "uniontext" => "\u{22C3}",+ "vextenddouble" => "\u{2225}",+ "vextendsingle" => "\u{2223}",+};++static REVERSE_GLYPH_NAMES: phf::Map<char, &'static str> = phf_map! {+ '\u{0000}' => "controlNULL",+ '\u{0001}' => "controlSTX",+ '\u{0002}' => "controlSOT",+ '\u{0003}' => "controlETX",+ '\u{0004}' => "controlEOT",+ '\u{0005}' => "controlENQ",+ '\u{0006}' => "controlACK",+ '\u{0007}' => "controlBEL",+ '\u{0008}' => "controlBS",+ '\u{0009}' => "controlHT",+ '\u{000A}' => "controlLF",+ '\u{000B}' => "controlVT",+ '\u{000C}' => "controlFF",+ '\u{000D}' => "controlCR",+ '\u{000E}' => "controlSO",+ '\u{000F}' => "controlSI",+ '\u{0010}' => "controlDLE",+ '\u{0011}' => "controlDC1",+ '\u{0012}' => "controlDC2",+ '\u{0013}' => "controlDC3",+ '\u{0014}' => "controlDC4",+ '\u{0015}' => "controlNAK",+ '\u{0016}' => "controlSYN",+ '\u{0017}' => "controlETB",+ '\u{0018}' => "controlCAN",+ '\u{0019}' => "controlEM",+ '\u{001A}' => "controlSUB",+ '\u{001B}' => "controlESC",+ '\u{001C}' => "controlFS",+ '\u{001D}' => "controlGS",+ '\u{001E}' => "controlRS",+ '\u{001F}' => "controlUS",+ '\u{0020}' => "space",+ '\u{0021}' => "exclam",+ '\u{0022}' => "quotedbl",+ '\u{0023}' => "numbersign",+ '\u{0024}' => "dollar",+ '\u{0025}' => "percent",+ '\u{0026}' => "ampersand",+ '\u{0027}' => "quotesingle",+ '\u{0028}' => "parenleft",+ '\u{0029}' => "parenright",+ '\u{002A}' => "asterisk",+ '\u{002B}' => "plus",+ '\u{002C}' => "comma",+ '\u{002D}' => "hyphen",+ '\u{002E}' => "period",+ '\u{002F}' => "slash",+ '\u{0030}' => "zero",+ '\u{0031}' => "one",+ '\u{0032}' => "two",+ '\u{0033}' => "three",+ '\u{0034}' => "four",+ '\u{0035}' => "five",+ '\u{0036}' => "six",+ '\u{0037}' => "seven",+ '\u{0038}' => "eight",+ '\u{0039}' => "nine",+ '\u{003A}' => "colon",+ '\u{003B}' => "semicolon",+ '\u{003C}' => "less",+ '\u{003D}' => "equal",+ '\u{003E}' => "greater",+ '\u{003F}' => "question",+ '\u{0040}' => "at",+ '\u{0041}' => "A",+ '\u{0042}' => "B",+ '\u{0043}' => "C",+ '\u{0044}' => "D",+ '\u{0045}' => "E",+ '\u{0046}' => "F",+ '\u{0047}' => "G",+ '\u{0048}' => "H",+ '\u{0049}' => "I",+ '\u{004A}' => "J",+ '\u{004B}' => "K",+ '\u{004C}' => "L",+ '\u{004D}' => "M",+ '\u{004E}' => "N",+ '\u{004F}' => "O",+ '\u{0050}' => "P",+ '\u{0051}' => "Q",+ '\u{0052}' => "R",+ '\u{0053}' => "S",+ '\u{0054}' => "T",+ '\u{0055}' => "U",+ '\u{0056}' => "V",+ '\u{0057}' => "W",+ '\u{0058}' => "X",+ '\u{0059}' => "Y",+ '\u{005A}' => "Z",+ '\u{005B}' => "bracketleft",+ '\u{005C}' => "backslash",+ '\u{005D}' => "bracketright",+ '\u{005E}' => "asciicircum",+ '\u{005F}' => "underscore",+ '\u{0060}' => "grave",+ '\u{0061}' => "a",+ '\u{0062}' => "b",+ '\u{0063}' => "c",+ '\u{0064}' => "d",+ '\u{0065}' => "e",+ '\u{0066}' => "f",+ '\u{0067}' => "g",+ '\u{0068}' => "h",+ '\u{0069}' => "i",+ '\u{006A}' => "j",+ '\u{006B}' => "k",+ '\u{006C}' => "l",+ '\u{006D}' => "m",+ '\u{006E}' => "n",+ '\u{006F}' => "o",+ '\u{0070}' => "p",+ '\u{0071}' => "q",+ '\u{0072}' => "r",+ '\u{0073}' => "s",+ '\u{0074}' => "t",+ '\u{0075}' => "u",+ '\u{0076}' => "v",+ '\u{0077}' => "w",+ '\u{0078}' => "x",+ '\u{0079}' => "y",+ '\u{007A}' => "z",+ '\u{007B}' => "braceleft",+ '\u{007C}' => "bar",+ '\u{007D}' => "braceright",+ '\u{007E}' => "asciitilde",+ '\u{007F}' => "controlDEL",+ '\u{00A0}' => "nbspace",+ '\u{00A1}' => "exclamdown",+ '\u{00A2}' => "cent",+ '\u{00A3}' => "sterling",+ '\u{00A4}' => "currency",+ '\u{00A5}' => "yen",+ '\u{00A6}' => "brokenbar",+ '\u{00A7}' => "section",+ '\u{00A8}' => "dieresis",+ '\u{00A9}' => "copyright",+ '\u{00AA}' => "ordfeminine",+ '\u{00AB}' => "guillemotleft",+ '\u{00AC}' => "logicalnot",+ '\u{00AD}' => "sfthyphen",+ '\u{00AE}' => "registered",+ '\u{00AF}' => "macron",+ '\u{00B0}' => "degree",+ '\u{00B1}' => "plusminus",+ '\u{00B2}' => "twosuperior",+ '\u{00B3}' => "threesuperior",+ '\u{00B4}' => "acute",+ '\u{00B5}' => "mu",+ '\u{00B6}' => "paragraph",+ '\u{00B7}' => "middot",+ '\u{00B8}' => "cedilla",+ '\u{00B9}' => "onesuperior",+ '\u{00BA}' => "ordmasculine",+ '\u{00BB}' => "guillemotright",+ '\u{00BC}' => "onequarter",+ '\u{00BD}' => "onehalf",+ '\u{00BE}' => "threequarters",+ '\u{00BF}' => "questiondown",+ '\u{00C0}' => "Agrave",+ '\u{00C1}' => "Aacute",+ '\u{00C2}' => "Acircumflex",+ '\u{00C3}' => "Atilde",+ '\u{00C4}' => "Adieresis",+ '\u{00C5}' => "Aring",+ '\u{00C6}' => "AE",+ '\u{00C7}' => "Ccedilla",+ '\u{00C8}' => "Egrave",+ '\u{00C9}' => "Eacute",+ '\u{00CA}' => "Ecircumflex",+ '\u{00CB}' => "Edieresis",+ '\u{00CC}' => "Igrave",+ '\u{00CD}' => "Iacute",+ '\u{00CE}' => "Icircumflex",+ '\u{00CF}' => "Idieresis",+ '\u{00D0}' => "Eth",+ '\u{00D1}' => "Ntilde",+ '\u{00D2}' => "Ograve",+ '\u{00D3}' => "Oacute",+ '\u{00D4}' => "Ocircumflex",+ '\u{00D5}' => "Otilde",+ '\u{00D6}' => "Odieresis",+ '\u{00D7}' => "multiply",+ '\u{00D8}' => "Oslash",+ '\u{00D9}' => "Ugrave",+ '\u{00DA}' => "Uacute",+ '\u{00DB}' => "Ucircumflex",+ '\u{00DC}' => "Udieresis",+ '\u{00DD}' => "Yacute",+ '\u{00DE}' => "Thorn",+ '\u{00DF}' => "germandbls",+ '\u{00E0}' => "agrave",+ '\u{00E1}' => "aacute",+ '\u{00E2}' => "acircumflex",+ '\u{00E3}' => "atilde",+ '\u{00E4}' => "adieresis",+ '\u{00E5}' => "aring",+ '\u{00E6}' => "ae",+ '\u{00E7}' => "ccedilla",+ '\u{00E8}' => "egrave",+ '\u{00E9}' => "eacute",+ '\u{00EA}' => "ecircumflex",+ '\u{00EB}' => "edieresis",+ '\u{00EC}' => "igrave",+ '\u{00ED}' => "iacute",+ '\u{00EE}' => "icircumflex",+ '\u{00EF}' => "idieresis",+ '\u{00F0}' => "eth",+ '\u{00F1}' => "ntilde",+ '\u{00F2}' => "ograve",+ '\u{00F3}' => "oacute",+ '\u{00F4}' => "ocircumflex",+ '\u{00F5}' => "otilde",+ '\u{00F6}' => "odieresis",+ '\u{00F7}' => "divide",+ '\u{00F8}' => "oslash",+ '\u{00F9}' => "ugrave",+ '\u{00FA}' => "uacute",+ '\u{00FB}' => "ucircumflex",+ '\u{00FC}' => "udieresis",+ '\u{00FD}' => "yacute",+ '\u{00FE}' => "thorn",+ '\u{00FF}' => "ydieresis",+ '\u{0100}' => "Amacron",+ '\u{0101}' => "amacron",+ '\u{0102}' => "Abreve",+ '\u{0103}' => "abreve",+ '\u{0104}' => "Aogonek",+ '\u{0105}' => "aogonek",+ '\u{0106}' => "Cacute",+ '\u{0107}' => "cacute",+ '\u{0108}' => "Ccircumflex",+ '\u{0109}' => "ccircumflex",+ '\u{010A}' => "Cdot",+ '\u{010B}' => "cdot",+ '\u{010C}' => "Ccaron",+ '\u{010D}' => "ccaron",+ '\u{010E}' => "Dcaron",+ '\u{010F}' => "dcaron",+ '\u{0110}' => "Dcroat",+ '\u{0111}' => "dcroat",+ '\u{0112}' => "Emacron",+ '\u{0113}' => "emacron",+ '\u{0114}' => "Ebreve",+ '\u{0115}' => "ebreve",+ '\u{0116}' => "Edot",+ '\u{0117}' => "edot",+ '\u{0118}' => "Eogonek",+ '\u{0119}' => "eogonek",+ '\u{011A}' => "Ecaron",+ '\u{011B}' => "ecaron",+ '\u{011C}' => "Gcircumflex",+ '\u{011D}' => "gcircumflex",+ '\u{011E}' => "Gbreve",+ '\u{011F}' => "gbreve",+ '\u{0120}' => "Gdot",+ '\u{0121}' => "gdot",+ '\u{0122}' => "Gcedilla",+ '\u{0123}' => "gcedilla",+ '\u{0124}' => "Hcircumflex",+ '\u{0125}' => "hcircumflex",+ '\u{0126}' => "Hbar",+ '\u{0127}' => "hbar",+ '\u{0128}' => "Itilde",+ '\u{0129}' => "itilde",+ '\u{012A}' => "Imacron",+ '\u{012B}' => "imacron",+ '\u{012C}' => "Ibreve",+ '\u{012D}' => "ibreve",+ '\u{012E}' => "Iogonek",+ '\u{012F}' => "iogonek",+ '\u{0130}' => "Idot",+ '\u{0131}' => "dotlessi",+ '\u{0132}' => "IJ",+ '\u{0133}' => "ij",+ '\u{0134}' => "Jcircumflex",+ '\u{0135}' => "jcircumflex",+ '\u{0136}' => "Kcedilla",+ '\u{0137}' => "kcedilla",+ '\u{0138}' => "kgreenlandic",+ '\u{0139}' => "Lacute",+ '\u{013A}' => "lacute",+ '\u{013B}' => "Lcedilla",+ '\u{013C}' => "lcedilla",+ '\u{013D}' => "Lcaron",+ '\u{013E}' => "lcaron",+ '\u{013F}' => "Ldot",+ '\u{0140}' => "ldot",+ '\u{0141}' => "Lslash",+ '\u{0142}' => "lslash",+ '\u{0143}' => "Nacute",+ '\u{0144}' => "nacute",+ '\u{0145}' => "Ncedilla",+ '\u{0146}' => "ncedilla",+ '\u{0147}' => "Ncaron",+ '\u{0148}' => "ncaron",+ '\u{0149}' => "napostrophe",+ '\u{014A}' => "Eng",+ '\u{014B}' => "eng",+ '\u{014C}' => "Omacron",+ '\u{014D}' => "omacron",+ '\u{014E}' => "Obreve",+ '\u{014F}' => "obreve",+ '\u{0150}' => "Odblacute",+ '\u{0151}' => "odblacute",+ '\u{0152}' => "OE",+ '\u{0153}' => "oe",+ '\u{0154}' => "Racute",+ '\u{0155}' => "racute",+ '\u{0156}' => "Rcedilla",+ '\u{0157}' => "rcedilla",+ '\u{0158}' => "Rcaron",+ '\u{0159}' => "rcaron",+ '\u{015A}' => "Sacute",+ '\u{015B}' => "sacute",+ '\u{015C}' => "Scircumflex",+ '\u{015D}' => "scircumflex",+ '\u{015E}' => "Scedilla",+ '\u{015F}' => "scedilla",+ '\u{0160}' => "Scaron",+ '\u{0161}' => "scaron",+ '\u{0162}' => "Tcedilla",+ '\u{0163}' => "tcedilla",+ '\u{0164}' => "Tcaron",+ '\u{0165}' => "tcaron",+ '\u{0166}' => "Tbar",+ '\u{0167}' => "tbar",+ '\u{0168}' => "Utilde",+ '\u{0169}' => "utilde",+ '\u{016A}' => "Umacron",+ '\u{016B}' => "umacron",+ '\u{016C}' => "Ubreve",+ '\u{016D}' => "ubreve",+ '\u{016E}' => "Uring",+ '\u{016F}' => "uring",+ '\u{0170}' => "Udblacute",+ '\u{0171}' => "udblacute",+ '\u{0172}' => "Uogonek",+ '\u{0173}' => "uogonek",+ '\u{0174}' => "Wcircumflex",+ '\u{0175}' => "wcircumflex",+ '\u{0176}' => "Ycircumflex",+ '\u{0177}' => "ycircumflex",+ '\u{0178}' => "Ydieresis",+ '\u{0179}' => "Zacute",+ '\u{017A}' => "zacute",+ '\u{017B}' => "Zdot",+ '\u{017C}' => "zdot",+ '\u{017D}' => "Zcaron",+ '\u{017E}' => "zcaron",+ '\u{017F}' => "longs",+ '\u{0180}' => "bstroke",+ '\u{0181}' => "Bhook",+ '\u{0182}' => "Btopbar",+ '\u{0183}' => "btopbar",+ '\u{0184}' => "Tonesix",+ '\u{0185}' => "tonesix",+ '\u{0186}' => "Oopen",+ '\u{0187}' => "Chook",+ '\u{0188}' => "chook",+ '\u{0189}' => "Dafrican",+ '\u{018A}' => "Dhook",+ '\u{018B}' => "Dtopbar",+ '\u{018C}' => "dtopbar",+ '\u{018D}' => "deltaturned",+ '\u{018E}' => "Ereversed",+ '\u{018F}' => "Schwa",+ '\u{0190}' => "Eopen",+ '\u{0191}' => "Fhook",+ '\u{0192}' => "florin",+ '\u{0193}' => "Ghook",+ '\u{0194}' => "Gammaafrican",+ '\u{0195}' => "hv",+ '\u{0196}' => "Iotaafrican",+ '\u{0197}' => "Istroke",+ '\u{0198}' => "Khook",+ '\u{0199}' => "khook",+ '\u{019A}' => "lbar",+ '\u{019B}' => "lambdastroke",+ '\u{019C}' => "Mturned",+ '\u{019D}' => "Nhookleft",+ '\u{019E}' => "nlegrightlong",+ '\u{019F}' => "Ocenteredtilde",+ '\u{01A0}' => "Ohorn",+ '\u{01A1}' => "ohorn",+ '\u{01A2}' => "Oi",+ '\u{01A3}' => "oi",+ '\u{01A4}' => "Phook",+ '\u{01A5}' => "phook",+ '\u{01A6}' => "yr",+ '\u{01A7}' => "Tonetwo",+ '\u{01A8}' => "tonetwo",+ '\u{01A9}' => "Esh",+ '\u{01AA}' => "eshreversedloop",+ '\u{01AB}' => "tpalatalhook",+ '\u{01AC}' => "Thook",+ '\u{01AD}' => "thook",+ '\u{01AE}' => "Tretroflexhook",+ '\u{01AF}' => "Uhorn",+ '\u{01B0}' => "uhorn",+ '\u{01B1}' => "Upsilonafrican",+ '\u{01B2}' => "Vhook",+ '\u{01B3}' => "Yhook",+ '\u{01B4}' => "yhook",+ '\u{01B5}' => "Zstroke",+ '\u{01B6}' => "zstroke",+ '\u{01B7}' => "Ezh",+ '\u{01B8}' => "Ezhreversed",+ '\u{01B9}' => "ezhreversed",+ '\u{01BA}' => "ezhtail",+ '\u{01BB}' => "twostroke",+ '\u{01BC}' => "Tonefive",+ '\u{01BD}' => "tonefive",+ '\u{01BE}' => "glottalinvertedstroke",+ '\u{01BF}' => "wynn",+ '\u{01C0}' => "clickdental",+ '\u{01C1}' => "clicklateral",+ '\u{01C2}' => "clickalveolar",+ '\u{01C3}' => "clickretroflex",+ '\u{01C4}' => "DZcaron",+ '\u{01C5}' => "Dzcaron",+ '\u{01C6}' => "dzcaron",+ '\u{01C7}' => "LJ",+ '\u{01C8}' => "Lj",+ '\u{01C9}' => "lj",+ '\u{01CA}' => "NJ",+ '\u{01CB}' => "Nj",+ '\u{01CC}' => "nj",+ '\u{01CD}' => "Acaron",+ '\u{01CE}' => "acaron",+ '\u{01CF}' => "Icaron",+ '\u{01D0}' => "icaron",+ '\u{01D1}' => "Ocaron",+ '\u{01D2}' => "ocaron",+ '\u{01D3}' => "Ucaron",+ '\u{01D4}' => "ucaron",+ '\u{01D5}' => "Udieresismacron",+ '\u{01D6}' => "udieresismacron",+ '\u{01D7}' => "Udieresisacute",+ '\u{01D8}' => "udieresisacute",+ '\u{01D9}' => "Udieresiscaron",+ '\u{01DA}' => "udieresiscaron",+ '\u{01DB}' => "Udieresisgrave",+ '\u{01DC}' => "udieresisgrave",+ '\u{01DD}' => "eturned",+ '\u{01DE}' => "Adieresismacron",+ '\u{01DF}' => "adieresismacron",+ '\u{01E0}' => "Adotmacron",+ '\u{01E1}' => "adotmacron",+ '\u{01E2}' => "AEmacron",+ '\u{01E3}' => "aemacron",+ '\u{01E4}' => "Gstroke",+ '\u{01E5}' => "gstroke",+ '\u{01E6}' => "Gcaron",+ '\u{01E7}' => "gcaron",+ '\u{01E8}' => "Kcaron",+ '\u{01E9}' => "kcaron",+ '\u{01EA}' => "Oogonek",+ '\u{01EB}' => "oogonek",+ '\u{01EC}' => "Oogonekmacron",+ '\u{01ED}' => "oogonekmacron",+ '\u{01EE}' => "Ezhcaron",+ '\u{01EF}' => "ezhcaron",+ '\u{01F0}' => "jcaron",+ '\u{01F1}' => "DZ",+ '\u{01F2}' => "Dz",+ '\u{01F3}' => "dz",+ '\u{01F4}' => "Gacute",+ '\u{01F5}' => "gacute",+ '\u{01FA}' => "Aringacute",+ '\u{01FB}' => "aringacute",+ '\u{01FC}' => "AEacute",+ '\u{01FD}' => "aeacute",+ '\u{01FE}' => "Oslashacute",+ '\u{01FF}' => "oslashacute",+ '\u{0200}' => "Adblgrave",+ '\u{0201}' => "adblgrave",+ '\u{0202}' => "Ainvertedbreve",+ '\u{0203}' => "ainvertedbreve",+ '\u{0204}' => "Edblgrave",+ '\u{0205}' => "edblgrave",+ '\u{0206}' => "Einvertedbreve",+ '\u{0207}' => "einvertedbreve",+ '\u{0208}' => "Idblgrave",+ '\u{0209}' => "idblgrave",+ '\u{020A}' => "Iinvertedbreve",+ '\u{020B}' => "iinvertedbreve",+ '\u{020C}' => "Odblgrave",+ '\u{020D}' => "odblgrave",+ '\u{020E}' => "Oinvertedbreve",+ '\u{020F}' => "oinvertedbreve",+ '\u{0210}' => "Rdblgrave",+ '\u{0211}' => "rdblgrave",+ '\u{0212}' => "Rinvertedbreve",+ '\u{0213}' => "rinvertedbreve",+ '\u{0214}' => "Udblgrave",+ '\u{0215}' => "udblgrave",+ '\u{0216}' => "Uinvertedbreve",+ '\u{0217}' => "uinvertedbreve",+ '\u{0218}' => "Scommaaccent",+ '\u{0219}' => "scommaaccent",+ '\u{0250}' => "aturned",+ '\u{0251}' => "ascript",+ '\u{0252}' => "ascriptturned",+ '\u{0253}' => "bhook",+ '\u{0254}' => "oopen",+ '\u{0255}' => "ccurl",+ '\u{0256}' => "dtail",+ '\u{0257}' => "dhook",+ '\u{0258}' => "ereversed",+ '\u{0259}' => "schwa",+ '\u{025A}' => "schwahook",+ '\u{025B}' => "eopen",+ '\u{025C}' => "eopenreversed",+ '\u{025D}' => "eopenreversedhook",+ '\u{025E}' => "eopenreversedclosed",+ '\u{025F}' => "jdotlessstroke",+ '\u{0260}' => "ghook",+ '\u{0261}' => "gscript",+ '\u{0263}' => "gammalatinsmall",+ '\u{0264}' => "ramshorn",+ '\u{0265}' => "hturned",+ '\u{0266}' => "hhook",+ '\u{0267}' => "henghook",+ '\u{0268}' => "istroke",+ '\u{0269}' => "iotalatin",+ '\u{026B}' => "lmiddletilde",+ '\u{026C}' => "lbelt",+ '\u{026D}' => "lhookretroflex",+ '\u{026E}' => "lezh",+ '\u{026F}' => "mturned",+ '\u{0270}' => "mlonglegturned",+ '\u{0271}' => "mhook",+ '\u{0272}' => "nhookleft",+ '\u{0273}' => "nhookretroflex",+ '\u{0275}' => "obarred",+ '\u{0277}' => "omegalatinclosed",+ '\u{0278}' => "philatin",+ '\u{0279}' => "rturned",+ '\u{027A}' => "rlonglegturned",+ '\u{027B}' => "rhookturned",+ '\u{027C}' => "rlongleg",+ '\u{027D}' => "rhook",+ '\u{027E}' => "rfishhook",+ '\u{027F}' => "rfishhookreversed",+ '\u{0281}' => "Rsmallinverted",+ '\u{0282}' => "shook",+ '\u{0283}' => "esh",+ '\u{0284}' => "dotlessjstrokehook",+ '\u{0285}' => "eshsquatreversed",+ '\u{0286}' => "eshcurl",+ '\u{0287}' => "tturned",+ '\u{0288}' => "tretroflexhook",+ '\u{0289}' => "ubar",+ '\u{028A}' => "upsilonlatin",+ '\u{028B}' => "vhook",+ '\u{028C}' => "vturned",+ '\u{028D}' => "wturned",+ '\u{028E}' => "yturned",+ '\u{0290}' => "zretroflexhook",+ '\u{0291}' => "zcurl",+ '\u{0292}' => "ezh",+ '\u{0293}' => "ezhcurl",+ '\u{0294}' => "glottalstop",+ '\u{0295}' => "glottalstopreversed",+ '\u{0296}' => "glottalstopinverted",+ '\u{0297}' => "cstretched",+ '\u{0298}' => "bilabialclick",+ '\u{029A}' => "eopenclosed",+ '\u{029B}' => "Gsmallhook",+ '\u{029D}' => "jcrossedtail",+ '\u{029E}' => "kturned",+ '\u{02A0}' => "qhook",+ '\u{02A1}' => "glottalstopstroke",+ '\u{02A2}' => "glottalstopstrokereversed",+ '\u{02A3}' => "dzaltone",+ '\u{02A4}' => "dezh",+ '\u{02A5}' => "dzcurl",+ '\u{02A6}' => "ts",+ '\u{02A7}' => "tesh",+ '\u{02A8}' => "tccurl",+ '\u{02B0}' => "hsuperior",+ '\u{02B1}' => "hhooksuperior",+ '\u{02B2}' => "jsuperior",+ '\u{02B4}' => "rturnedsuperior",+ '\u{02B5}' => "rhookturnedsuperior",+ '\u{02B6}' => "Rsmallinvertedsuperior",+ '\u{02B7}' => "wsuperior",+ '\u{02B8}' => "ysuperior",+ '\u{02B9}' => "primemod",+ '\u{02BA}' => "dblprimemod",+ '\u{02BB}' => "commaturnedmod",+ '\u{02BC}' => "afii57929",+ '\u{02BD}' => "afii64937",+ '\u{02BE}' => "ringhalfright",+ '\u{02BF}' => "ringhalfleft",+ '\u{02C0}' => "glottalstopmod",+ '\u{02C1}' => "glottalstopreversedmod",+ '\u{02C2}' => "arrowheadleftmod",+ '\u{02C3}' => "arrowheadrightmod",+ '\u{02C4}' => "arrowheadupmod",+ '\u{02C5}' => "arrowheaddownmod",+ '\u{02C6}' => "circumflex",+ '\u{02C7}' => "caron",+ '\u{02C8}' => "verticallinemod",+ '\u{02C9}' => "firsttonechinese",+ '\u{02CA}' => "secondtonechinese",+ '\u{02CB}' => "fourthtonechinese",+ '\u{02CC}' => "verticallinelowmod",+ '\u{02CD}' => "macronlowmod",+ '\u{02CE}' => "gravelowmod",+ '\u{02CF}' => "acutelowmod",+ '\u{02D0}' => "colontriangularmod",+ '\u{02D1}' => "colontriangularhalfmod",+ '\u{02D2}' => "ringhalfrightcentered",+ '\u{02D3}' => "ringhalfleftcentered",+ '\u{02D4}' => "uptackmod",+ '\u{02D5}' => "downtackmod",+ '\u{02D6}' => "plusmod",+ '\u{02D7}' => "minusmod",+ '\u{02D8}' => "breve",+ '\u{02D9}' => "dotaccent",+ '\u{02DA}' => "ring",+ '\u{02DB}' => "ogonek",+ '\u{02DC}' => "ilde",+ '\u{02DD}' => "hungarumlaut",+ '\u{02DE}' => "rhotichookmod",+ '\u{02E0}' => "gammasuperior",+ '\u{02E3}' => "xsuperior",+ '\u{02E4}' => "glottalstopreversedsuperior",+ '\u{02E5}' => "tonebarextrahighmod",+ '\u{02E6}' => "tonebarhighmod",+ '\u{02E7}' => "tonebarmidmod",+ '\u{02E8}' => "tonebarlowmod",+ '\u{02E9}' => "tonebarextralowmod",+ '\u{0300}' => "gravecmb",+ '\u{0301}' => "acutecmb",+ '\u{0302}' => "circumflexcmb",+ '\u{0303}' => "tildecmb",+ '\u{0304}' => "macroncmb",+ '\u{0305}' => "overlinecmb",+ '\u{0306}' => "brevecmb",+ '\u{0307}' => "dotaccentcmb",+ '\u{0308}' => "dieresiscmb",+ '\u{0309}' => "hookabovecomb",+ '\u{030A}' => "ringcmb",+ '\u{030B}' => "hungarumlautcmb",+ '\u{030C}' => "caroncmb",+ '\u{030D}' => "verticallineabovecmb",+ '\u{030E}' => "dblverticallineabovecmb",+ '\u{030F}' => "dblgravecmb",+ '\u{0310}' => "candrabinducmb",+ '\u{0311}' => "breveinvertedcmb",+ '\u{0312}' => "commaturnedabovecmb",+ '\u{0313}' => "commaabovecmb",+ '\u{0314}' => "commareversedabovecmb",+ '\u{0315}' => "commaaboverightcmb",+ '\u{0316}' => "gravebelowcmb",+ '\u{0317}' => "acutebelowcmb",+ '\u{0318}' => "lefttackbelowcmb",+ '\u{0319}' => "righttackbelowcmb",+ '\u{031A}' => "leftangleabovecmb",+ '\u{031B}' => "horncmb",+ '\u{031C}' => "ringhalfleftbelowcmb",+ '\u{031D}' => "uptackbelowcmb",+ '\u{031E}' => "downtackbelowcmb",+ '\u{031F}' => "plusbelowcmb",+ '\u{0320}' => "minusbelowcmb",+ '\u{0321}' => "hookpalatalizedbelowcmb",+ '\u{0322}' => "hookretroflexbelowcmb",+ '\u{0323}' => "dotbelowcmb",+ '\u{0324}' => "dieresisbelowcmb",+ '\u{0325}' => "ringbelowcmb",+ '\u{0327}' => "cedillacmb",+ '\u{0328}' => "ogonekcmb",+ '\u{0329}' => "verticallinebelowcmb",+ '\u{032A}' => "bridgebelowcmb",+ '\u{032B}' => "dblarchinvertedbelowcmb",+ '\u{032C}' => "caronbelowcmb",+ '\u{032D}' => "circumflexbelowcmb",+ '\u{032E}' => "brevebelowcmb",+ '\u{032F}' => "breveinvertedbelowcmb",+ '\u{0330}' => "tildebelowcmb",+ '\u{0331}' => "macronbelowcmb",+ '\u{0332}' => "lowlinecmb",+ '\u{0333}' => "dbllowlinecmb",+ '\u{0334}' => "tildeoverlaycmb",+ '\u{0335}' => "strokeshortoverlaycmb",+ '\u{0336}' => "strokelongoverlaycmb",+ '\u{0337}' => "solidusshortoverlaycmb",+ '\u{0338}' => "soliduslongoverlaycmb",+ '\u{0339}' => "ringhalfrightbelowcmb",+ '\u{033A}' => "bridgeinvertedbelowcmb",+ '\u{033B}' => "squarebelowcmb",+ '\u{033C}' => "seagullbelowcmb",+ '\u{033D}' => "xabovecmb",+ '\u{033E}' => "tildeverticalcmb",+ '\u{033F}' => "dbloverlinecmb",+ '\u{0340}' => "gravetonecmb",+ '\u{0341}' => "acutetonecmb",+ '\u{0342}' => "perispomenigreekcmb",+ '\u{0343}' => "koroniscmb",+ '\u{0344}' => "dialytikatonoscmb",+ '\u{0345}' => "ypogegrammenigreekcmb",+ '\u{0360}' => "tildedoublecmb",+ '\u{0361}' => "breveinverteddoublecmb",+ '\u{0374}' => "numeralsigngreek",+ '\u{0375}' => "numeralsignlowergreek",+ '\u{037A}' => "ypogegrammeni",+ '\u{037E}' => "questiongreek",+ '\u{0384}' => "tonos",+ '\u{0385}' => "dialytikatonos",+ '\u{0386}' => "Alphatonos",+ '\u{0387}' => "anoteleia",+ '\u{0388}' => "Epsilontonos",+ '\u{0389}' => "Etatonos",+ '\u{038A}' => "Iotatonos",+ '\u{038C}' => "Omicrontonos",+ '\u{038E}' => "Upsilontonos",+ '\u{038F}' => "Omegatonos",+ '\u{0390}' => "iotadieresistonos",+ '\u{0391}' => "Alpha",+ '\u{0392}' => "Beta",+ '\u{0393}' => "Gamma",+ '\u{0394}' => "Deltagreek",+ '\u{0395}' => "Epsilon",+ '\u{0396}' => "Zeta",+ '\u{0397}' => "Eta",+ '\u{0398}' => "Theta",+ '\u{0399}' => "Iota",+ '\u{039A}' => "Kappa",+ '\u{039B}' => "Lambda",+ '\u{039C}' => "Mu",+ '\u{039D}' => "Nu",+ '\u{039E}' => "Xi",+ '\u{039F}' => "Omicron",+ '\u{03A0}' => "Pi",+ '\u{03A1}' => "Rho",+ '\u{03A3}' => "Sigma",+ '\u{03A4}' => "Tau",+ '\u{03A5}' => "Upsilon",+ '\u{03A6}' => "Phi",+ '\u{03A7}' => "Chi",+ '\u{03A8}' => "Psi",+ '\u{03A9}' => "Omegagreek",+ '\u{03AA}' => "Iotadieresis",+ '\u{03AB}' => "Upsilondieresis",+ '\u{03AC}' => "alphatonos",+ '\u{03AD}' => "epsilontonos",+ '\u{03AE}' => "etatonos",+ '\u{03AF}' => "iotatonos",+ '\u{03B0}' => "upsilondieresistonos",+ '\u{03B1}' => "alpha",+ '\u{03B2}' => "beta",+ '\u{03B3}' => "gamma",+ '\u{03B4}' => "delta",+ '\u{03B5}' => "epsilon",+ '\u{03B6}' => "zeta",+ '\u{03B7}' => "eta",+ '\u{03B8}' => "theta",+ '\u{03B9}' => "iota",+ '\u{03BA}' => "kappa",+ '\u{03BB}' => "lambda",+ '\u{03BC}' => "mugreek",+ '\u{03BD}' => "nu",+ '\u{03BE}' => "xi",+ '\u{03BF}' => "omicron",+ '\u{03C0}' => "pi",+ '\u{03C1}' => "rho",+ '\u{03C2}' => "sigma1",+ '\u{03C3}' => "sigma",+ '\u{03C4}' => "tau",+ '\u{03C5}' => "upsilon",+ '\u{03C6}' => "phi",+ '\u{03C7}' => "chi",+ '\u{03C8}' => "psi",+ '\u{03C9}' => "omega",+ '\u{03CA}' => "iotadieresis",+ '\u{03CB}' => "upsilondieresis",+ '\u{03CC}' => "omicrontonos",+ '\u{03CD}' => "upsilontonos",+ '\u{03CE}' => "omegatonos",+ '\u{03D0}' => "betasymbolgreek",+ '\u{03D1}' => "theta1",+ '\u{03D2}' => "Upsilon1",+ '\u{03D3}' => "Upsilonacutehooksymbolgreek",+ '\u{03D4}' => "Upsilondieresishooksymbolgreek",+ '\u{03D5}' => "phi1",+ '\u{03D6}' => "omega1",+ '\u{03DA}' => "Stigmagreek",+ '\u{03DC}' => "Digammagreek",+ '\u{03DE}' => "Koppagreek",+ '\u{03E0}' => "Sampigreek",+ '\u{03E2}' => "Sheicoptic",+ '\u{03E3}' => "sheicoptic",+ '\u{03E4}' => "Feicoptic",+ '\u{03E5}' => "feicoptic",+ '\u{03E6}' => "Kheicoptic",+ '\u{03E7}' => "kheicoptic",+ '\u{03E8}' => "Horicoptic",+ '\u{03E9}' => "horicoptic",+ '\u{03EA}' => "Gangiacoptic",+ '\u{03EB}' => "gangiacoptic",+ '\u{03EC}' => "Shimacoptic",+ '\u{03ED}' => "shimacoptic",+ '\u{03EE}' => "Deicoptic",+ '\u{03EF}' => "deicoptic",+ '\u{03F0}' => "kappasymbolgreek",+ '\u{03F1}' => "rhosymbolgreek",+ '\u{03F2}' => "sigmalunatesymbolgreek",+ '\u{03F3}' => "yotgreek",+ '\u{0401}' => "Iocyrillic",+ '\u{0402}' => "Djecyrillic",+ '\u{0403}' => "Gjecyrillic",+ '\u{0404}' => "Ecyrillic",+ '\u{0405}' => "Dzecyrillic",+ '\u{0406}' => "Icyrillic",+ '\u{0407}' => "Yicyrillic",+ '\u{0408}' => "Jecyrillic",+ '\u{0409}' => "Ljecyrillic",+ '\u{040A}' => "Njecyrillic",+ '\u{040B}' => "Tshecyrillic",+ '\u{040C}' => "Kjecyrillic",+ '\u{040E}' => "Ushortcyrillic",+ '\u{040F}' => "Dzhecyrillic",+ '\u{0410}' => "Acyrillic",+ '\u{0411}' => "Becyrillic",+ '\u{0412}' => "Vecyrillic",+ '\u{0413}' => "Gecyrillic",+ '\u{0414}' => "Decyrillic",+ '\u{0415}' => "Iecyrillic",+ '\u{0416}' => "Zhecyrillic",+ '\u{0417}' => "Zecyrillic",+ '\u{0418}' => "Iicyrillic",+ '\u{0419}' => "Iishortcyrillic",+ '\u{041A}' => "Kacyrillic",+ '\u{041B}' => "Elcyrillic",+ '\u{041C}' => "Emcyrillic",+ '\u{041D}' => "Encyrillic",+ '\u{041E}' => "Ocyrillic",+ '\u{041F}' => "Pecyrillic",+ '\u{0420}' => "Ercyrillic",+ '\u{0421}' => "Escyrillic",+ '\u{0422}' => "Tecyrillic",+ '\u{0423}' => "Ucyrillic",+ '\u{0424}' => "Efcyrillic",+ '\u{0425}' => "Khacyrillic",+ '\u{0426}' => "Tsecyrillic",+ '\u{0427}' => "Checyrillic",+ '\u{0428}' => "Shacyrillic",+ '\u{0429}' => "Shchacyrillic",+ '\u{042A}' => "Hardsigncyrillic",+ '\u{042B}' => "Yericyrillic",+ '\u{042C}' => "Softsigncyrillic",+ '\u{042D}' => "Ereversedcyrillic",+ '\u{042E}' => "IUcyrillic",+ '\u{042F}' => "IAcyrillic",+ '\u{0430}' => "acyrillic",+ '\u{0431}' => "afii10066",+ '\u{0432}' => "afii10067",+ '\u{0433}' => "afii10068",+ '\u{0434}' => "afii10069",+ '\u{0435}' => "afii10070",+ '\u{0436}' => "afii10072",+ '\u{0437}' => "afii10073",+ '\u{0438}' => "afii10074",+ '\u{0439}' => "afii10075",+ '\u{043A}' => "afii10076",+ '\u{043B}' => "afii10077",+ '\u{043C}' => "afii10078",+ '\u{043D}' => "afii10079",+ '\u{043E}' => "afii10080",+ '\u{043F}' => "afii10081",+ '\u{0440}' => "afii10082",+ '\u{0441}' => "afii10083",+ '\u{0442}' => "afii10084",+ '\u{0443}' => "afii10085",+ '\u{0444}' => "afii10086",+ '\u{0445}' => "afii10087",+ '\u{0446}' => "afii10088",+ '\u{0447}' => "afii10089",+ '\u{0448}' => "afii10090",+ '\u{0449}' => "afii10091",+ '\u{044A}' => "afii10092",+ '\u{044B}' => "afii10093",+ '\u{044C}' => "afii10094",+ '\u{044D}' => "afii10095",+ '\u{044E}' => "afii10096",+ '\u{044F}' => "afii10097",+ '\u{0451}' => "afii10071",+ '\u{0452}' => "afii10099",+ '\u{0453}' => "afii10100",+ '\u{0454}' => "afii10101",+ '\u{0455}' => "afii10102",+ '\u{0456}' => "afii10103",+ '\u{0457}' => "afii10104",+ '\u{0458}' => "afii10105",+ '\u{0459}' => "afii10106",+ '\u{045A}' => "afii10107",+ '\u{045B}' => "afii10108",+ '\u{045C}' => "afii10109",+ '\u{045E}' => "afii10110",+ '\u{045F}' => "afii10193",+ '\u{0460}' => "Omegacyrillic",+ '\u{0461}' => "omegacyrillic",+ '\u{0462}' => "Yatcyrillic",+ '\u{0463}' => "afii10194",+ '\u{0464}' => "Eiotifiedcyrillic",+ '\u{0465}' => "eiotifiedcyrillic",+ '\u{0466}' => "Yuslittlecyrillic",+ '\u{0467}' => "yuslittlecyrillic",+ '\u{0468}' => "Yuslittleiotifiedcyrillic",+ '\u{0469}' => "yuslittleiotifiedcyrillic",+ '\u{046A}' => "Yusbigcyrillic",+ '\u{046B}' => "yusbigcyrillic",+ '\u{046C}' => "Yusbigiotifiedcyrillic",+ '\u{046D}' => "yusbigiotifiedcyrillic",+ '\u{046E}' => "Ksicyrillic",+ '\u{046F}' => "ksicyrillic",+ '\u{0470}' => "Psicyrillic",+ '\u{0471}' => "psicyrillic",+ '\u{0472}' => "Fitacyrillic",+ '\u{0473}' => "afii10195",+ '\u{0474}' => "Izhitsacyrillic",+ '\u{0475}' => "afii10196",+ '\u{0476}' => "Izhitsadblgravecyrillic",+ '\u{0477}' => "izhitsadblgravecyrillic",+ '\u{0478}' => "Ukcyrillic",+ '\u{0479}' => "ukcyrillic",+ '\u{047A}' => "Omegaroundcyrillic",+ '\u{047B}' => "omegaroundcyrillic",+ '\u{047C}' => "Omegatitlocyrillic",+ '\u{047D}' => "omegatitlocyrillic",+ '\u{047E}' => "Otcyrillic",+ '\u{047F}' => "otcyrillic",+ '\u{0480}' => "Koppacyrillic",+ '\u{0481}' => "koppacyrillic",+ '\u{0482}' => "thousandcyrillic",+ '\u{0483}' => "titlocyrilliccmb",+ '\u{0484}' => "palatalizationcyrilliccmb",+ '\u{0485}' => "dasiapneumatacyrilliccmb",+ '\u{0486}' => "psilipneumatacyrilliccmb",+ '\u{0490}' => "Gheupturncyrillic",+ '\u{0491}' => "afii10098",+ '\u{0492}' => "Ghestrokecyrillic",+ '\u{0493}' => "ghestrokecyrillic",+ '\u{0494}' => "Ghemiddlehookcyrillic",+ '\u{0495}' => "ghemiddlehookcyrillic",+ '\u{0496}' => "Zhedescendercyrillic",+ '\u{0497}' => "zhedescendercyrillic",+ '\u{0498}' => "Zedescendercyrillic",+ '\u{0499}' => "zedescendercyrillic",+ '\u{049A}' => "Kadescendercyrillic",+ '\u{049B}' => "kadescendercyrillic",+ '\u{049C}' => "Kaverticalstrokecyrillic",+ '\u{049D}' => "kaverticalstrokecyrillic",+ '\u{049E}' => "Kastrokecyrillic",+ '\u{049F}' => "kastrokecyrillic",+ '\u{04A0}' => "Kabashkircyrillic",+ '\u{04A1}' => "kabashkircyrillic",+ '\u{04A2}' => "Endescendercyrillic",+ '\u{04A3}' => "endescendercyrillic",+ '\u{04A4}' => "Enghecyrillic",+ '\u{04A5}' => "enghecyrillic",+ '\u{04A6}' => "Pemiddlehookcyrillic",+ '\u{04A7}' => "pemiddlehookcyrillic",+ '\u{04A8}' => "Haabkhasiancyrillic",+ '\u{04A9}' => "haabkhasiancyrillic",+ '\u{04AA}' => "Esdescendercyrillic",+ '\u{04AB}' => "esdescendercyrillic",+ '\u{04AC}' => "Tedescendercyrillic",+ '\u{04AD}' => "tedescendercyrillic",+ '\u{04AE}' => "Ustraightcyrillic",+ '\u{04AF}' => "ustraightcyrillic",+ '\u{04B0}' => "Ustraightstrokecyrillic",+ '\u{04B1}' => "ustraightstrokecyrillic",+ '\u{04B2}' => "Hadescendercyrillic",+ '\u{04B3}' => "hadescendercyrillic",+ '\u{04B4}' => "Tetsecyrillic",+ '\u{04B5}' => "tetsecyrillic",+ '\u{04B6}' => "Chedescendercyrillic",+ '\u{04B7}' => "chedescendercyrillic",+ '\u{04B8}' => "Cheverticalstrokecyrillic",+ '\u{04B9}' => "cheverticalstrokecyrillic",+ '\u{04BA}' => "Shhacyrillic",+ '\u{04BB}' => "shhacyrillic",+ '\u{04BC}' => "Cheabkhasiancyrillic",+ '\u{04BD}' => "cheabkhasiancyrillic",+ '\u{04BE}' => "Chedescenderabkhasiancyrillic",+ '\u{04BF}' => "chedescenderabkhasiancyrillic",+ '\u{04C0}' => "palochkacyrillic",+ '\u{04C1}' => "Zhebrevecyrillic",+ '\u{04C2}' => "zhebrevecyrillic",+ '\u{04C3}' => "Kahookcyrillic",+ '\u{04C4}' => "kahookcyrillic",+ '\u{04C7}' => "Enhookcyrillic",+ '\u{04C8}' => "enhookcyrillic",+ '\u{04CB}' => "Chekhakassiancyrillic",+ '\u{04CC}' => "chekhakassiancyrillic",+ '\u{04D0}' => "Abrevecyrillic",+ '\u{04D1}' => "abrevecyrillic",+ '\u{04D2}' => "Adieresiscyrillic",+ '\u{04D3}' => "adieresiscyrillic",+ '\u{04D4}' => "Aiecyrillic",+ '\u{04D5}' => "aiecyrillic",+ '\u{04D6}' => "Iebrevecyrillic",+ '\u{04D7}' => "iebrevecyrillic",+ '\u{04D8}' => "Schwacyrillic",+ '\u{04D9}' => "afii10846",+ '\u{04DA}' => "Schwadieresiscyrillic",+ '\u{04DB}' => "schwadieresiscyrillic",+ '\u{04DC}' => "Zhedieresiscyrillic",+ '\u{04DD}' => "zhedieresiscyrillic",+ '\u{04DE}' => "Zedieresiscyrillic",+ '\u{04DF}' => "zedieresiscyrillic",+ '\u{04E0}' => "Dzeabkhasiancyrillic",+ '\u{04E1}' => "dzeabkhasiancyrillic",+ '\u{04E2}' => "Imacroncyrillic",+ '\u{04E3}' => "imacroncyrillic",+ '\u{04E4}' => "Idieresiscyrillic",+ '\u{04E5}' => "idieresiscyrillic",+ '\u{04E6}' => "Odieresiscyrillic",+ '\u{04E7}' => "odieresiscyrillic",+ '\u{04E8}' => "Obarredcyrillic",+ '\u{04E9}' => "obarredcyrillic",+ '\u{04EA}' => "Obarreddieresiscyrillic",+ '\u{04EB}' => "obarreddieresiscyrillic",+ '\u{04EE}' => "Umacroncyrillic",+ '\u{04EF}' => "umacroncyrillic",+ '\u{04F0}' => "Udieresiscyrillic",+ '\u{04F1}' => "udieresiscyrillic",+ '\u{04F2}' => "Uhungarumlautcyrillic",+ '\u{04F3}' => "uhungarumlautcyrillic",+ '\u{04F4}' => "Chedieresiscyrillic",+ '\u{04F5}' => "chedieresiscyrillic",+ '\u{04F8}' => "Yerudieresiscyrillic",+ '\u{04F9}' => "yerudieresiscyrillic",+ '\u{0531}' => "Aybarmenian",+ '\u{0532}' => "Benarmenian",+ '\u{0533}' => "Gimarmenian",+ '\u{0534}' => "Daarmenian",+ '\u{0535}' => "Echarmenian",+ '\u{0536}' => "Zaarmenian",+ '\u{0537}' => "Eharmenian",+ '\u{0538}' => "Etarmenian",+ '\u{0539}' => "Toarmenian",+ '\u{053A}' => "Zhearmenian",+ '\u{053B}' => "Iniarmenian",+ '\u{053C}' => "Liwnarmenian",+ '\u{053D}' => "Xeharmenian",+ '\u{053E}' => "Caarmenian",+ '\u{053F}' => "Kenarmenian",+ '\u{0540}' => "Hoarmenian",+ '\u{0541}' => "Jaarmenian",+ '\u{0542}' => "Ghadarmenian",+ '\u{0543}' => "Cheharmenian",+ '\u{0544}' => "Menarmenian",+ '\u{0545}' => "Yiarmenian",+ '\u{0546}' => "Nowarmenian",+ '\u{0547}' => "Shaarmenian",+ '\u{0548}' => "Voarmenian",+ '\u{0549}' => "Chaarmenian",+ '\u{054A}' => "Peharmenian",+ '\u{054B}' => "Jheharmenian",+ '\u{054C}' => "Raarmenian",+ '\u{054D}' => "Seharmenian",+ '\u{054E}' => "Vewarmenian",+ '\u{054F}' => "Tiwnarmenian",+ '\u{0550}' => "Reharmenian",+ '\u{0551}' => "Coarmenian",+ '\u{0552}' => "Yiwnarmenian",+ '\u{0553}' => "Piwrarmenian",+ '\u{0554}' => "Keharmenian",+ '\u{0555}' => "Oharmenian",+ '\u{0556}' => "Feharmenian",+ '\u{0559}' => "ringhalfleftarmenian",+ '\u{055A}' => "apostrophearmenian",+ '\u{055B}' => "emphasismarkarmenian",+ '\u{055C}' => "exclamarmenian",+ '\u{055D}' => "commaarmenian",+ '\u{055E}' => "questionarmenian",+ '\u{055F}' => "abbreviationmarkarmenian",+ '\u{0561}' => "aybarmenian",+ '\u{0562}' => "benarmenian",+ '\u{0563}' => "gimarmenian",+ '\u{0564}' => "daarmenian",+ '\u{0565}' => "echarmenian",+ '\u{0566}' => "zaarmenian",+ '\u{0567}' => "eharmenian",+ '\u{0568}' => "etarmenian",+ '\u{0569}' => "toarmenian",+ '\u{056A}' => "zhearmenian",+ '\u{056B}' => "iniarmenian",+ '\u{056C}' => "liwnarmenian",+ '\u{056D}' => "xeharmenian",+ '\u{056E}' => "caarmenian",+ '\u{056F}' => "kenarmenian",+ '\u{0570}' => "hoarmenian",+ '\u{0571}' => "jaarmenian",+ '\u{0572}' => "ghadarmenian",+ '\u{0573}' => "cheharmenian",+ '\u{0574}' => "menarmenian",+ '\u{0575}' => "yiarmenian",+ '\u{0576}' => "nowarmenian",+ '\u{0577}' => "shaarmenian",+ '\u{0578}' => "voarmenian",+ '\u{0579}' => "chaarmenian",+ '\u{057A}' => "peharmenian",+ '\u{057B}' => "jheharmenian",+ '\u{057C}' => "raarmenian",+ '\u{057D}' => "seharmenian",+ '\u{057E}' => "vewarmenian",+ '\u{057F}' => "tiwnarmenian",+ '\u{0580}' => "reharmenian",+ '\u{0581}' => "coarmenian",+ '\u{0582}' => "yiwnarmenian",+ '\u{0583}' => "piwrarmenian",+ '\u{0584}' => "keharmenian",+ '\u{0585}' => "oharmenian",+ '\u{0586}' => "feharmenian",+ '\u{0587}' => "echyiwnarmenian",+ '\u{0589}' => "periodarmenian",+ '\u{0591}' => "etnahtafoukhhebrew",+ '\u{0592}' => "segoltahebrew",+ '\u{0593}' => "shalshelethebrew",+ '\u{0594}' => "zaqefqatanhebrew",+ '\u{0595}' => "zaqefgadolhebrew",+ '\u{0596}' => "tipehahebrew",+ '\u{0597}' => "reviahebrew",+ '\u{0598}' => "zarqahebrew",+ '\u{0599}' => "pashtahebrew",+ '\u{059A}' => "yetivhebrew",+ '\u{059B}' => "tevirhebrew",+ '\u{059C}' => "gereshaccenthebrew",+ '\u{059D}' => "gereshmuqdamhebrew",+ '\u{059E}' => "gershayimaccenthebrew",+ '\u{059F}' => "qarneyparahebrew",+ '\u{05A0}' => "telishagedolahebrew",+ '\u{05A1}' => "pazerhebrew",+ '\u{05A3}' => "munahhebrew",+ '\u{05A4}' => "mahapakhhebrew",+ '\u{05A5}' => "merkhahebrew",+ '\u{05A6}' => "merkhakefulahebrew",+ '\u{05A7}' => "dargahebrew",+ '\u{05A8}' => "qadmahebrew",+ '\u{05A9}' => "telishaqetanahebrew",+ '\u{05AA}' => "yerahbenyomohebrew",+ '\u{05AB}' => "olehebrew",+ '\u{05AC}' => "iluyhebrew",+ '\u{05AD}' => "dehihebrew",+ '\u{05AE}' => "zinorhebrew",+ '\u{05AF}' => "masoracirclehebrew",+ '\u{05B0}' => "afii57799",+ '\u{05B1}' => "afii57801",+ '\u{05B2}' => "afii57800",+ '\u{05B3}' => "afii57802",+ '\u{05B4}' => "afii57793",+ '\u{05B5}' => "afii57794",+ '\u{05B6}' => "afii57795",+ '\u{05B7}' => "afii57798",+ '\u{05B8}' => "afii57797",+ '\u{05B9}' => "afii57806",+ '\u{05BB}' => "afii57796",+ '\u{05BC}' => "afii57807",+ '\u{05BD}' => "afii57839",+ '\u{05BE}' => "afii57645",+ '\u{05BF}' => "afii57841",+ '\u{05C0}' => "afii57842",+ '\u{05C1}' => "afii57804",+ '\u{05C2}' => "afii57803",+ '\u{05C3}' => "afii57658",+ '\u{05C4}' => "upperdothebrew",+ '\u{05D0}' => "afii57664",+ '\u{05D1}' => "afii57665",+ '\u{05D2}' => "afii57666",+ '\u{05D3}' => "afii57667",+ '\u{05D4}' => "afii57668",+ '\u{05D5}' => "afii57669",+ '\u{05D6}' => "afii57670",+ '\u{05D7}' => "afii57671",+ '\u{05D8}' => "afii57672",+ '\u{05D9}' => "afii57673",+ '\u{05DA}' => "afii57674",+ '\u{05DB}' => "afii57675",+ '\u{05DC}' => "afii57676",+ '\u{05DD}' => "afii57677",+ '\u{05DE}' => "afii57678",+ '\u{05DF}' => "afii57679",+ '\u{05E0}' => "afii57680",+ '\u{05E1}' => "afii57681",+ '\u{05E2}' => "afii57682",+ '\u{05E3}' => "afii57683",+ '\u{05E4}' => "afii57684",+ '\u{05E5}' => "afii57685",+ '\u{05E6}' => "afii57686",+ '\u{05E7}' => "afii57687",+ '\u{05E8}' => "afii57688",+ '\u{05E9}' => "afii57689",+ '\u{05EA}' => "afii57690",+ '\u{05F0}' => "afii57716",+ '\u{05F1}' => "afii57717",+ '\u{05F2}' => "afii57718",+ '\u{05F3}' => "gereshhebrew",+ '\u{05F4}' => "gershayimhebrew",+ '\u{060C}' => "afii57388",+ '\u{061B}' => "afii57403",+ '\u{061F}' => "afii57407",+ '\u{0621}' => "afii57409",+ '\u{0622}' => "afii57410",+ '\u{0623}' => "afii57411",+ '\u{0624}' => "afii57412",+ '\u{0625}' => "afii57413",+ '\u{0626}' => "afii57414",+ '\u{0627}' => "afii57415",+ '\u{0628}' => "afii57416",+ '\u{0629}' => "afii57417",+ '\u{062A}' => "afii57418",+ '\u{062B}' => "afii57419",+ '\u{062C}' => "afii57420",+ '\u{062D}' => "afii57421",+ '\u{062E}' => "afii57422",+ '\u{062F}' => "afii57423",+ '\u{0630}' => "afii57424",+ '\u{0631}' => "afii57425",+ '\u{0632}' => "afii57426",+ '\u{0633}' => "afii57427",+ '\u{0634}' => "afii57428",+ '\u{0635}' => "afii57429",+ '\u{0636}' => "afii57430",+ '\u{0637}' => "afii57431",+ '\u{0638}' => "afii57432",+ '\u{0639}' => "afii57433",+ '\u{063A}' => "afii57434",+ '\u{0640}' => "afii57440",+ '\u{0641}' => "afii57441",+ '\u{0642}' => "afii57442",+ '\u{0643}' => "afii57443",+ '\u{0644}' => "afii57444",+ '\u{0645}' => "afii57445",+ '\u{0646}' => "afii57446",+ '\u{0647}' => "afii57470",+ '\u{0648}' => "afii57448",+ '\u{0649}' => "afii57449",+ '\u{064A}' => "afii57450",+ '\u{064B}' => "afii57451",+ '\u{064C}' => "afii57452",+ '\u{064D}' => "afii57453",+ '\u{064E}' => "afii57454",+ '\u{064F}' => "afii57455",+ '\u{0650}' => "afii57456",+ '\u{0651}' => "afii57457",+ '\u{0652}' => "afii57458",+ '\u{0660}' => "afii57392",+ '\u{0661}' => "afii57393",+ '\u{0662}' => "afii57394",+ '\u{0663}' => "afii57395",+ '\u{0664}' => "afii57396",+ '\u{0665}' => "afii57397",+ '\u{0666}' => "afii57398",+ '\u{0667}' => "afii57399",+ '\u{0668}' => "afii57400",+ '\u{0669}' => "afii57401",+ '\u{066A}' => "afii57381",+ '\u{066B}' => "decimalseparatorarabic",+ '\u{066C}' => "thousandsseparatorarabic",+ '\u{066D}' => "afii63167",+ '\u{0679}' => "afii57511",+ '\u{067E}' => "afii57506",+ '\u{0686}' => "afii57507",+ '\u{0688}' => "afii57512",+ '\u{0691}' => "afii57513",+ '\u{0698}' => "afii57508",+ '\u{06A4}' => "afii57505",+ '\u{06AF}' => "afii57509",+ '\u{06BA}' => "afii57514",+ '\u{06C1}' => "haaltonearabic",+ '\u{06D1}' => "yehthreedotsbelowarabic",+ '\u{06D2}' => "afii57519",+ '\u{06D5}' => "afii57534",+ '\u{06F0}' => "zeropersian",+ '\u{06F1}' => "onepersian",+ '\u{06F2}' => "twopersian",+ '\u{06F3}' => "threepersian",+ '\u{06F4}' => "fourpersian",+ '\u{06F5}' => "fivepersian",+ '\u{06F6}' => "sixpersian",+ '\u{06F7}' => "sevenpersian",+ '\u{06F8}' => "eightpersian",+ '\u{06F9}' => "ninepersian",+ '\u{0901}' => "candrabindudeva",+ '\u{0902}' => "anusvaradeva",+ '\u{0903}' => "visargadeva",+ '\u{0905}' => "adeva",+ '\u{0906}' => "aadeva",+ '\u{0907}' => "ideva",+ '\u{0908}' => "iideva",+ '\u{0909}' => "udeva",+ '\u{090A}' => "uudeva",+ '\u{090B}' => "rvocalicdeva",+ '\u{090C}' => "lvocalicdeva",+ '\u{090D}' => "ecandradeva",+ '\u{090E}' => "eshortdeva",+ '\u{090F}' => "edeva",+ '\u{0910}' => "aideva",+ '\u{0911}' => "ocandradeva",+ '\u{0912}' => "oshortdeva",+ '\u{0913}' => "odeva",+ '\u{0914}' => "audeva",+ '\u{0915}' => "kadeva",+ '\u{0916}' => "khadeva",+ '\u{0917}' => "gadeva",+ '\u{0918}' => "ghadeva",+ '\u{0919}' => "ngadeva",+ '\u{091A}' => "cadeva",+ '\u{091B}' => "chadeva",+ '\u{091C}' => "jadeva",+ '\u{091D}' => "jhadeva",+ '\u{091E}' => "nyadeva",+ '\u{091F}' => "ttadeva",+ '\u{0920}' => "tthadeva",+ '\u{0921}' => "ddadeva",+ '\u{0922}' => "ddhadeva",+ '\u{0923}' => "nnadeva",+ '\u{0924}' => "tadeva",+ '\u{0925}' => "thadeva",+ '\u{0926}' => "dadeva",+ '\u{0927}' => "dhadeva",+ '\u{0928}' => "nadeva",+ '\u{0929}' => "nnnadeva",+ '\u{092A}' => "padeva",+ '\u{092B}' => "phadeva",+ '\u{092C}' => "badeva",+ '\u{092D}' => "bhadeva",+ '\u{092E}' => "madeva",+ '\u{092F}' => "yadeva",+ '\u{0930}' => "radeva",+ '\u{0931}' => "rradeva",+ '\u{0932}' => "ladeva",+ '\u{0933}' => "lladeva",+ '\u{0934}' => "llladeva",+ '\u{0935}' => "vadeva",+ '\u{0936}' => "shadeva",+ '\u{0937}' => "ssadeva",+ '\u{0938}' => "sadeva",+ '\u{0939}' => "hadeva",+ '\u{093C}' => "nuktadeva",+ '\u{093D}' => "avagrahadeva",+ '\u{093E}' => "aavowelsigndeva",+ '\u{093F}' => "ivowelsigndeva",+ '\u{0940}' => "iivowelsigndeva",+ '\u{0941}' => "uvowelsigndeva",+ '\u{0942}' => "uuvowelsigndeva",+ '\u{0943}' => "rvocalicvowelsigndeva",+ '\u{0944}' => "rrvocalicvowelsigndeva",+ '\u{0945}' => "ecandravowelsigndeva",+ '\u{0946}' => "eshortvowelsigndeva",+ '\u{0947}' => "evowelsigndeva",+ '\u{0948}' => "aivowelsigndeva",+ '\u{0949}' => "ocandravowelsigndeva",+ '\u{094A}' => "oshortvowelsigndeva",+ '\u{094B}' => "ovowelsigndeva",+ '\u{094C}' => "auvowelsigndeva",+ '\u{094D}' => "viramadeva",+ '\u{0950}' => "omdeva",+ '\u{0951}' => "udattadeva",+ '\u{0952}' => "anudattadeva",+ '\u{0953}' => "gravedeva",+ '\u{0954}' => "acutedeva",+ '\u{0958}' => "qadeva",+ '\u{0959}' => "khhadeva",+ '\u{095A}' => "ghhadeva",+ '\u{095B}' => "zadeva",+ '\u{095C}' => "dddhadeva",+ '\u{095D}' => "rhadeva",+ '\u{095E}' => "fadeva",+ '\u{095F}' => "yyadeva",+ '\u{0960}' => "rrvocalicdeva",+ '\u{0961}' => "llvocalicdeva",+ '\u{0962}' => "lvocalicvowelsigndeva",+ '\u{0963}' => "llvocalicvowelsigndeva",+ '\u{0964}' => "danda",+ '\u{0965}' => "dbldanda",+ '\u{0966}' => "zerodeva",+ '\u{0967}' => "onedeva",+ '\u{0968}' => "twodeva",+ '\u{0969}' => "threedeva",+ '\u{096A}' => "fourdeva",+ '\u{096B}' => "fivedeva",+ '\u{096C}' => "sixdeva",+ '\u{096D}' => "sevendeva",+ '\u{096E}' => "eightdeva",+ '\u{096F}' => "ninedeva",+ '\u{0970}' => "abbreviationsigndeva",+ '\u{0981}' => "candrabindubengali",+ '\u{0982}' => "anusvarabengali",+ '\u{0983}' => "visargabengali",+ '\u{0985}' => "abengali",+ '\u{0986}' => "aabengali",+ '\u{0987}' => "ibengali",+ '\u{0988}' => "iibengali",+ '\u{0989}' => "ubengali",+ '\u{098A}' => "uubengali",+ '\u{098B}' => "rvocalicbengali",+ '\u{098C}' => "lvocalicbengali",+ '\u{098F}' => "ebengali",+ '\u{0990}' => "aibengali",+ '\u{0993}' => "obengali",+ '\u{0994}' => "aubengali",+ '\u{0995}' => "kabengali",+ '\u{0996}' => "khabengali",+ '\u{0997}' => "gabengali",+ '\u{0998}' => "ghabengali",+ '\u{0999}' => "ngabengali",+ '\u{099A}' => "cabengali",+ '\u{099B}' => "chabengali",+ '\u{099C}' => "jabengali",+ '\u{099D}' => "jhabengali",+ '\u{099E}' => "nyabengali",+ '\u{099F}' => "ttabengali",+ '\u{09A0}' => "tthabengali",+ '\u{09A1}' => "ddabengali",+ '\u{09A2}' => "ddhabengali",+ '\u{09A3}' => "nnabengali",+ '\u{09A4}' => "tabengali",+ '\u{09A5}' => "thabengali",+ '\u{09A6}' => "dabengali",+ '\u{09A7}' => "dhabengali",+ '\u{09A8}' => "nabengali",+ '\u{09AA}' => "pabengali",+ '\u{09AB}' => "phabengali",+ '\u{09AC}' => "babengali",+ '\u{09AD}' => "bhabengali",+ '\u{09AE}' => "mabengali",+ '\u{09AF}' => "yabengali",+ '\u{09B0}' => "rabengali",+ '\u{09B2}' => "labengali",+ '\u{09B6}' => "shabengali",+ '\u{09B7}' => "ssabengali",+ '\u{09B8}' => "sabengali",+ '\u{09B9}' => "habengali",+ '\u{09BC}' => "nuktabengali",+ '\u{09BE}' => "aavowelsignbengali",+ '\u{09BF}' => "ivowelsignbengali",+ '\u{09C0}' => "iivowelsignbengali",+ '\u{09C1}' => "uvowelsignbengali",+ '\u{09C2}' => "uuvowelsignbengali",+ '\u{09C3}' => "rvocalicvowelsignbengali",+ '\u{09C4}' => "rrvocalicvowelsignbengali",+ '\u{09C7}' => "evowelsignbengali",+ '\u{09C8}' => "aivowelsignbengali",+ '\u{09CB}' => "ovowelsignbengali",+ '\u{09CC}' => "auvowelsignbengali",+ '\u{09CD}' => "viramabengali",+ '\u{09D7}' => "aulengthmarkbengali",+ '\u{09DC}' => "rrabengali",+ '\u{09DD}' => "rhabengali",+ '\u{09DF}' => "yyabengali",+ '\u{09E0}' => "rrvocalicbengali",+ '\u{09E1}' => "llvocalicbengali",+ '\u{09E2}' => "lvocalicvowelsignbengali",+ '\u{09E3}' => "llvocalicvowelsignbengali",+ '\u{09E6}' => "zerobengali",+ '\u{09E7}' => "onebengali",+ '\u{09E8}' => "twobengali",+ '\u{09E9}' => "threebengali",+ '\u{09EA}' => "fourbengali",+ '\u{09EB}' => "fivebengali",+ '\u{09EC}' => "sixbengali",+ '\u{09ED}' => "sevenbengali",+ '\u{09EE}' => "eightbengali",+ '\u{09EF}' => "ninebengali",+ '\u{09F0}' => "ramiddlediagonalbengali",+ '\u{09F1}' => "ralowerdiagonalbengali",+ '\u{09F2}' => "rupeemarkbengali",+ '\u{09F3}' => "rupeesignbengali",+ '\u{09F4}' => "onenumeratorbengali",+ '\u{09F5}' => "twonumeratorbengali",+ '\u{09F6}' => "threenumeratorbengali",+ '\u{09F7}' => "fournumeratorbengali",+ '\u{09F8}' => "denominatorminusonenumeratorbengali",+ '\u{09F9}' => "sixteencurrencydenominatorbengali",+ '\u{09FA}' => "issharbengali",+ '\u{0A02}' => "bindigurmukhi",+ '\u{0A05}' => "agurmukhi",+ '\u{0A06}' => "aagurmukhi",+ '\u{0A07}' => "igurmukhi",+ '\u{0A08}' => "iigurmukhi",+ '\u{0A09}' => "ugurmukhi",+ '\u{0A0A}' => "uugurmukhi",+ '\u{0A0F}' => "eegurmukhi",+ '\u{0A10}' => "aigurmukhi",+ '\u{0A13}' => "oogurmukhi",+ '\u{0A14}' => "augurmukhi",+ '\u{0A15}' => "kagurmukhi",+ '\u{0A16}' => "khagurmukhi",+ '\u{0A17}' => "gagurmukhi",+ '\u{0A18}' => "ghagurmukhi",+ '\u{0A19}' => "ngagurmukhi",+ '\u{0A1A}' => "cagurmukhi",+ '\u{0A1B}' => "chagurmukhi",+ '\u{0A1C}' => "jagurmukhi",+ '\u{0A1D}' => "jhagurmukhi",+ '\u{0A1E}' => "nyagurmukhi",+ '\u{0A1F}' => "ttagurmukhi",+ '\u{0A20}' => "tthagurmukhi",+ '\u{0A21}' => "ddagurmukhi",+ '\u{0A22}' => "ddhagurmukhi",+ '\u{0A23}' => "nnagurmukhi",+ '\u{0A24}' => "tagurmukhi",+ '\u{0A25}' => "thagurmukhi",+ '\u{0A26}' => "dagurmukhi",+ '\u{0A27}' => "dhagurmukhi",+ '\u{0A28}' => "nagurmukhi",+ '\u{0A2A}' => "pagurmukhi",+ '\u{0A2B}' => "phagurmukhi",+ '\u{0A2C}' => "bagurmukhi",+ '\u{0A2D}' => "bhagurmukhi",+ '\u{0A2E}' => "magurmukhi",+ '\u{0A2F}' => "yagurmukhi",+ '\u{0A30}' => "ragurmukhi",+ '\u{0A32}' => "lagurmukhi",+ '\u{0A35}' => "vagurmukhi",+ '\u{0A36}' => "shagurmukhi",+ '\u{0A38}' => "sagurmukhi",+ '\u{0A39}' => "hagurmukhi",+ '\u{0A3C}' => "nuktagurmukhi",+ '\u{0A3E}' => "aamatragurmukhi",+ '\u{0A3F}' => "imatragurmukhi",+ '\u{0A40}' => "iimatragurmukhi",+ '\u{0A41}' => "umatragurmukhi",+ '\u{0A42}' => "uumatragurmukhi",+ '\u{0A47}' => "eematragurmukhi",+ '\u{0A48}' => "aimatragurmukhi",+ '\u{0A4B}' => "oomatragurmukhi",+ '\u{0A4C}' => "aumatragurmukhi",+ '\u{0A4D}' => "halantgurmukhi",+ '\u{0A59}' => "khhagurmukhi",+ '\u{0A5A}' => "ghhagurmukhi",+ '\u{0A5B}' => "zagurmukhi",+ '\u{0A5C}' => "rragurmukhi",+ '\u{0A5E}' => "fagurmukhi",+ '\u{0A66}' => "zerogurmukhi",+ '\u{0A67}' => "onegurmukhi",+ '\u{0A68}' => "twogurmukhi",+ '\u{0A69}' => "threegurmukhi",+ '\u{0A6A}' => "fourgurmukhi",+ '\u{0A6B}' => "fivegurmukhi",+ '\u{0A6C}' => "sixgurmukhi",+ '\u{0A6D}' => "sevengurmukhi",+ '\u{0A6E}' => "eightgurmukhi",+ '\u{0A6F}' => "ninegurmukhi",+ '\u{0A70}' => "tippigurmukhi",+ '\u{0A71}' => "addakgurmukhi",+ '\u{0A72}' => "irigurmukhi",+ '\u{0A73}' => "uragurmukhi",+ '\u{0A74}' => "ekonkargurmukhi",+ '\u{0A81}' => "candrabindugujarati",+ '\u{0A82}' => "anusvaragujarati",+ '\u{0A83}' => "visargagujarati",+ '\u{0A85}' => "agujarati",+ '\u{0A86}' => "aagujarati",+ '\u{0A87}' => "igujarati",+ '\u{0A88}' => "iigujarati",+ '\u{0A89}' => "ugujarati",+ '\u{0A8A}' => "uugujarati",+ '\u{0A8B}' => "rvocalicgujarati",+ '\u{0A8D}' => "ecandragujarati",+ '\u{0A8F}' => "egujarati",+ '\u{0A90}' => "aigujarati",+ '\u{0A91}' => "ocandragujarati",+ '\u{0A93}' => "ogujarati",+ '\u{0A94}' => "augujarati",+ '\u{0A95}' => "kagujarati",+ '\u{0A96}' => "khagujarati",+ '\u{0A97}' => "gagujarati",+ '\u{0A98}' => "ghagujarati",+ '\u{0A99}' => "ngagujarati",+ '\u{0A9A}' => "cagujarati",+ '\u{0A9B}' => "chagujarati",+ '\u{0A9C}' => "jagujarati",+ '\u{0A9D}' => "jhagujarati",+ '\u{0A9E}' => "nyagujarati",+ '\u{0A9F}' => "ttagujarati",+ '\u{0AA0}' => "tthagujarati",+ '\u{0AA1}' => "ddagujarati",+ '\u{0AA2}' => "ddhagujarati",+ '\u{0AA3}' => "nnagujarati",+ '\u{0AA4}' => "tagujarati",+ '\u{0AA5}' => "thagujarati",+ '\u{0AA6}' => "dagujarati",+ '\u{0AA7}' => "dhagujarati",+ '\u{0AA8}' => "nagujarati",+ '\u{0AAA}' => "pagujarati",+ '\u{0AAB}' => "phagujarati",+ '\u{0AAC}' => "bagujarati",+ '\u{0AAD}' => "bhagujarati",+ '\u{0AAE}' => "magujarati",+ '\u{0AAF}' => "yagujarati",+ '\u{0AB0}' => "ragujarati",+ '\u{0AB2}' => "lagujarati",+ '\u{0AB3}' => "llagujarati",+ '\u{0AB5}' => "vagujarati",+ '\u{0AB6}' => "shagujarati",+ '\u{0AB7}' => "ssagujarati",+ '\u{0AB8}' => "sagujarati",+ '\u{0AB9}' => "hagujarati",+ '\u{0ABC}' => "nuktagujarati",+ '\u{0ABE}' => "aavowelsigngujarati",+ '\u{0ABF}' => "ivowelsigngujarati",+ '\u{0AC0}' => "iivowelsigngujarati",+ '\u{0AC1}' => "uvowelsigngujarati",+ '\u{0AC2}' => "uuvowelsigngujarati",+ '\u{0AC3}' => "rvocalicvowelsigngujarati",+ '\u{0AC4}' => "rrvocalicvowelsigngujarati",+ '\u{0AC5}' => "ecandravowelsigngujarati",+ '\u{0AC7}' => "evowelsigngujarati",+ '\u{0AC8}' => "aivowelsigngujarati",+ '\u{0AC9}' => "ocandravowelsigngujarati",+ '\u{0ACB}' => "ovowelsigngujarati",+ '\u{0ACC}' => "auvowelsigngujarati",+ '\u{0ACD}' => "viramagujarati",+ '\u{0AD0}' => "omgujarati",+ '\u{0AE0}' => "rrvocalicgujarati",+ '\u{0AE6}' => "zerogujarati",+ '\u{0AE7}' => "onegujarati",+ '\u{0AE8}' => "twogujarati",+ '\u{0AE9}' => "threegujarati",+ '\u{0AEA}' => "fourgujarati",+ '\u{0AEB}' => "fivegujarati",+ '\u{0AEC}' => "sixgujarati",+ '\u{0AED}' => "sevengujarati",+ '\u{0AEE}' => "eightgujarati",+ '\u{0AEF}' => "ninegujarati",+ '\u{0E01}' => "kokaithai",+ '\u{0E02}' => "khokhaithai",+ '\u{0E03}' => "khokhuatthai",+ '\u{0E04}' => "khokhwaithai",+ '\u{0E05}' => "khokhonthai",+ '\u{0E06}' => "khorakhangthai",+ '\u{0E07}' => "ngonguthai",+ '\u{0E08}' => "chochanthai",+ '\u{0E09}' => "chochingthai",+ '\u{0E0A}' => "chochangthai",+ '\u{0E0B}' => "sosothai",+ '\u{0E0C}' => "chochoethai",+ '\u{0E0D}' => "yoyingthai",+ '\u{0E0E}' => "dochadathai",+ '\u{0E0F}' => "topatakthai",+ '\u{0E10}' => "thothanthai",+ '\u{0E11}' => "thonangmonthothai",+ '\u{0E12}' => "thophuthaothai",+ '\u{0E13}' => "nonenthai",+ '\u{0E14}' => "dodekthai",+ '\u{0E15}' => "totaothai",+ '\u{0E16}' => "thothungthai",+ '\u{0E17}' => "thothahanthai",+ '\u{0E18}' => "thothongthai",+ '\u{0E19}' => "nonuthai",+ '\u{0E1A}' => "bobaimaithai",+ '\u{0E1B}' => "poplathai",+ '\u{0E1C}' => "phophungthai",+ '\u{0E1D}' => "fofathai",+ '\u{0E1E}' => "phophanthai",+ '\u{0E1F}' => "fofanthai",+ '\u{0E20}' => "phosamphaothai",+ '\u{0E21}' => "momathai",+ '\u{0E22}' => "yoyakthai",+ '\u{0E23}' => "roruathai",+ '\u{0E24}' => "ruthai",+ '\u{0E25}' => "lolingthai",+ '\u{0E26}' => "luthai",+ '\u{0E27}' => "wowaenthai",+ '\u{0E28}' => "sosalathai",+ '\u{0E29}' => "sorusithai",+ '\u{0E2A}' => "sosuathai",+ '\u{0E2B}' => "hohipthai",+ '\u{0E2C}' => "lochulathai",+ '\u{0E2D}' => "oangthai",+ '\u{0E2E}' => "honokhukthai",+ '\u{0E2F}' => "paiyannoithai",+ '\u{0E30}' => "saraathai",+ '\u{0E31}' => "maihanakatthai",+ '\u{0E32}' => "saraaathai",+ '\u{0E33}' => "saraamthai",+ '\u{0E34}' => "saraithai",+ '\u{0E35}' => "saraiithai",+ '\u{0E36}' => "sarauethai",+ '\u{0E37}' => "saraueethai",+ '\u{0E38}' => "sarauthai",+ '\u{0E39}' => "sarauuthai",+ '\u{0E3A}' => "phinthuthai",+ '\u{0E3F}' => "bahtthai",+ '\u{0E40}' => "saraethai",+ '\u{0E41}' => "saraaethai",+ '\u{0E42}' => "saraothai",+ '\u{0E43}' => "saraaimaimuanthai",+ '\u{0E44}' => "saraaimaimalaithai",+ '\u{0E45}' => "lakkhangyaothai",+ '\u{0E46}' => "maiyamokthai",+ '\u{0E47}' => "maitaikhuthai",+ '\u{0E48}' => "maiekthai",+ '\u{0E49}' => "maithothai",+ '\u{0E4A}' => "maitrithai",+ '\u{0E4B}' => "maichattawathai",+ '\u{0E4C}' => "thanthakhatthai",+ '\u{0E4D}' => "nikhahitthai",+ '\u{0E4E}' => "yamakkanthai",+ '\u{0E4F}' => "fongmanthai",+ '\u{0E50}' => "zerothai",+ '\u{0E51}' => "onethai",+ '\u{0E52}' => "twothai",+ '\u{0E53}' => "threethai",+ '\u{0E54}' => "fourthai",+ '\u{0E55}' => "fivethai",+ '\u{0E56}' => "sixthai",+ '\u{0E57}' => "seventhai",+ '\u{0E58}' => "eightthai",+ '\u{0E59}' => "ninethai",+ '\u{0E5A}' => "angkhankhuthai",+ '\u{0E5B}' => "khomutthai",+ '\u{1D40}' => "intercal",+ '\u{1E00}' => "Aringbelow",+ '\u{1E01}' => "aringbelow",+ '\u{1E02}' => "Bdotaccent",+ '\u{1E03}' => "bdotaccent",+ '\u{1E04}' => "Bdotbelow",+ '\u{1E05}' => "bdotbelow",+ '\u{1E06}' => "Blinebelow",+ '\u{1E07}' => "blinebelow",+ '\u{1E08}' => "Ccedillaacute",+ '\u{1E09}' => "ccedillaacute",+ '\u{1E0A}' => "Ddotaccent",+ '\u{1E0B}' => "ddotaccent",+ '\u{1E0C}' => "Ddotbelow",+ '\u{1E0D}' => "ddotbelow",+ '\u{1E0E}' => "Dlinebelow",+ '\u{1E0F}' => "dlinebelow",+ '\u{1E10}' => "Dcedilla",+ '\u{1E11}' => "dcedilla",+ '\u{1E12}' => "Dcircumflexbelow",+ '\u{1E13}' => "dcircumflexbelow",+ '\u{1E14}' => "Emacrongrave",+ '\u{1E15}' => "emacrongrave",+ '\u{1E16}' => "Emacronacute",+ '\u{1E17}' => "emacronacute",+ '\u{1E18}' => "Ecircumflexbelow",+ '\u{1E19}' => "ecircumflexbelow",+ '\u{1E1A}' => "Etildebelow",+ '\u{1E1B}' => "etildebelow",+ '\u{1E1C}' => "Ecedillabreve",+ '\u{1E1D}' => "ecedillabreve",+ '\u{1E1E}' => "Fdotaccent",+ '\u{1E1F}' => "fdotaccent",+ '\u{1E20}' => "Gmacron",+ '\u{1E21}' => "gmacron",+ '\u{1E22}' => "Hdotaccent",+ '\u{1E23}' => "hdotaccent",+ '\u{1E24}' => "Hdotbelow",+ '\u{1E25}' => "hdotbelow",+ '\u{1E26}' => "Hdieresis",+ '\u{1E27}' => "hdieresis",+ '\u{1E28}' => "Hcedilla",+ '\u{1E29}' => "hcedilla",+ '\u{1E2A}' => "Hbrevebelow",+ '\u{1E2B}' => "hbrevebelow",+ '\u{1E2C}' => "Itildebelow",+ '\u{1E2D}' => "itildebelow",+ '\u{1E2E}' => "Idieresisacute",+ '\u{1E2F}' => "idieresisacute",+ '\u{1E30}' => "Kacute",+ '\u{1E31}' => "kacute",+ '\u{1E32}' => "Kdotbelow",+ '\u{1E33}' => "kdotbelow",+ '\u{1E34}' => "Klinebelow",+ '\u{1E35}' => "klinebelow",+ '\u{1E36}' => "Ldotbelow",+ '\u{1E37}' => "ldotbelow",+ '\u{1E38}' => "Ldotbelowmacron",+ '\u{1E39}' => "ldotbelowmacron",+ '\u{1E3A}' => "Llinebelow",+ '\u{1E3B}' => "llinebelow",+ '\u{1E3C}' => "Lcircumflexbelow",+ '\u{1E3D}' => "lcircumflexbelow",+ '\u{1E3E}' => "Macute",+ '\u{1E3F}' => "macute",+ '\u{1E40}' => "Mdotaccent",+ '\u{1E41}' => "mdotaccent",+ '\u{1E42}' => "Mdotbelow",+ '\u{1E43}' => "mdotbelow",+ '\u{1E44}' => "Ndotaccent",+ '\u{1E45}' => "ndotaccent",+ '\u{1E46}' => "Ndotbelow",+ '\u{1E47}' => "ndotbelow",+ '\u{1E48}' => "Nlinebelow",+ '\u{1E49}' => "nlinebelow",+ '\u{1E4A}' => "Ncircumflexbelow",+ '\u{1E4B}' => "ncircumflexbelow",+ '\u{1E4C}' => "Otildeacute",+ '\u{1E4D}' => "otildeacute",+ '\u{1E4E}' => "Otildedieresis",+ '\u{1E4F}' => "otildedieresis",+ '\u{1E50}' => "Omacrongrave",+ '\u{1E51}' => "omacrongrave",+ '\u{1E52}' => "Omacronacute",+ '\u{1E53}' => "omacronacute",+ '\u{1E54}' => "Pacute",+ '\u{1E55}' => "pacute",+ '\u{1E56}' => "Pdotaccent",+ '\u{1E57}' => "pdotaccent",+ '\u{1E58}' => "Rdotaccent",+ '\u{1E59}' => "rdotaccent",+ '\u{1E5A}' => "Rdotbelow",+ '\u{1E5B}' => "rdotbelow",+ '\u{1E5C}' => "Rdotbelowmacron",+ '\u{1E5D}' => "rdotbelowmacron",+ '\u{1E5E}' => "Rlinebelow",+ '\u{1E5F}' => "rlinebelow",+ '\u{1E60}' => "Sdotaccent",+ '\u{1E61}' => "sdotaccent",+ '\u{1E62}' => "Sdotbelow",+ '\u{1E63}' => "sdotbelow",+ '\u{1E64}' => "Sacutedotaccent",+ '\u{1E65}' => "sacutedotaccent",+ '\u{1E66}' => "Scarondotaccent",+ '\u{1E67}' => "scarondotaccent",+ '\u{1E68}' => "Sdotbelowdotaccent",+ '\u{1E69}' => "sdotbelowdotaccent",+ '\u{1E6A}' => "Tdotaccent",+ '\u{1E6B}' => "tdotaccent",+ '\u{1E6C}' => "Tdotbelow",+ '\u{1E6D}' => "tdotbelow",+ '\u{1E6E}' => "Tlinebelow",+ '\u{1E6F}' => "tlinebelow",+ '\u{1E70}' => "Tcircumflexbelow",+ '\u{1E71}' => "tcircumflexbelow",+ '\u{1E72}' => "Udieresisbelow",+ '\u{1E73}' => "udieresisbelow",+ '\u{1E74}' => "Utildebelow",+ '\u{1E75}' => "utildebelow",+ '\u{1E76}' => "Ucircumflexbelow",+ '\u{1E77}' => "ucircumflexbelow",+ '\u{1E78}' => "Utildeacute",+ '\u{1E79}' => "utildeacute",+ '\u{1E7A}' => "Umacrondieresis",+ '\u{1E7B}' => "umacrondieresis",+ '\u{1E7C}' => "Vtilde",+ '\u{1E7D}' => "vtilde",+ '\u{1E7E}' => "Vdotbelow",+ '\u{1E7F}' => "vdotbelow",+ '\u{1E80}' => "Wgrave",+ '\u{1E81}' => "wgrave",+ '\u{1E82}' => "Wacute",+ '\u{1E83}' => "wacute",+ '\u{1E84}' => "Wdieresis",+ '\u{1E85}' => "wdieresis",+ '\u{1E86}' => "Wdotaccent",+ '\u{1E87}' => "wdotaccent",+ '\u{1E88}' => "Wdotbelow",+ '\u{1E89}' => "wdotbelow",+ '\u{1E8A}' => "Xdotaccent",+ '\u{1E8B}' => "xdotaccent",+ '\u{1E8C}' => "Xdieresis",+ '\u{1E8D}' => "xdieresis",+ '\u{1E8E}' => "Ydotaccent",+ '\u{1E8F}' => "ydotaccent",+ '\u{1E90}' => "Zcircumflex",+ '\u{1E91}' => "zcircumflex",+ '\u{1E92}' => "Zdotbelow",+ '\u{1E93}' => "zdotbelow",+ '\u{1E94}' => "Zlinebelow",+ '\u{1E95}' => "zlinebelow",+ '\u{1E96}' => "hlinebelow",+ '\u{1E97}' => "tdieresis",+ '\u{1E98}' => "wring",+ '\u{1E99}' => "yring",+ '\u{1E9A}' => "arighthalfring",+ '\u{1E9B}' => "slongdotaccent",+ '\u{1EA0}' => "Adotbelow",+ '\u{1EA1}' => "adotbelow",+ '\u{1EA2}' => "Ahookabove",+ '\u{1EA3}' => "ahookabove",+ '\u{1EA4}' => "Acircumflexacute",+ '\u{1EA5}' => "acircumflexacute",+ '\u{1EA6}' => "Acircumflexgrave",+ '\u{1EA7}' => "acircumflexgrave",+ '\u{1EA8}' => "Acircumflexhookabove",+ '\u{1EA9}' => "acircumflexhookabove",+ '\u{1EAA}' => "Acircumflextilde",+ '\u{1EAB}' => "acircumflextilde",+ '\u{1EAC}' => "Acircumflexdotbelow",+ '\u{1EAD}' => "acircumflexdotbelow",+ '\u{1EAE}' => "Abreveacute",+ '\u{1EAF}' => "abreveacute",+ '\u{1EB0}' => "Abrevegrave",+ '\u{1EB1}' => "abrevegrave",+ '\u{1EB2}' => "Abrevehookabove",+ '\u{1EB3}' => "abrevehookabove",+ '\u{1EB4}' => "Abrevetilde",+ '\u{1EB5}' => "abrevetilde",+ '\u{1EB6}' => "Abrevedotbelow",+ '\u{1EB7}' => "abrevedotbelow",+ '\u{1EB8}' => "Edotbelow",+ '\u{1EB9}' => "edotbelow",+ '\u{1EBA}' => "Ehookabove",+ '\u{1EBB}' => "ehookabove",+ '\u{1EBC}' => "Etilde",+ '\u{1EBD}' => "etilde",+ '\u{1EBE}' => "Ecircumflexacute",+ '\u{1EBF}' => "ecircumflexacute",+ '\u{1EC0}' => "Ecircumflexgrave",+ '\u{1EC1}' => "ecircumflexgrave",+ '\u{1EC2}' => "Ecircumflexhookabove",+ '\u{1EC3}' => "ecircumflexhookabove",+ '\u{1EC4}' => "Ecircumflextilde",+ '\u{1EC5}' => "ecircumflextilde",+ '\u{1EC6}' => "Ecircumflexdotbelow",+ '\u{1EC7}' => "ecircumflexdotbelow",+ '\u{1EC8}' => "Ihookabove",+ '\u{1EC9}' => "ihookabove",+ '\u{1ECA}' => "Idotbelow",+ '\u{1ECB}' => "idotbelow",+ '\u{1ECC}' => "Odotbelow",+ '\u{1ECD}' => "odotbelow",+ '\u{1ECE}' => "Ohookabove",+ '\u{1ECF}' => "ohookabove",+ '\u{1ED0}' => "Ocircumflexacute",+ '\u{1ED1}' => "ocircumflexacute",+ '\u{1ED2}' => "Ocircumflexgrave",+ '\u{1ED3}' => "ocircumflexgrave",+ '\u{1ED4}' => "Ocircumflexhookabove",+ '\u{1ED5}' => "ocircumflexhookabove",+ '\u{1ED6}' => "Ocircumflextilde",+ '\u{1ED7}' => "ocircumflextilde",+ '\u{1ED8}' => "Ocircumflexdotbelow",+ '\u{1ED9}' => "ocircumflexdotbelow",+ '\u{1EDA}' => "Ohornacute",+ '\u{1EDB}' => "ohornacute",+ '\u{1EDC}' => "Ohorngrave",+ '\u{1EDD}' => "ohorngrave",+ '\u{1EDE}' => "Ohornhookabove",+ '\u{1EDF}' => "ohornhookabove",+ '\u{1EE0}' => "Ohorntilde",+ '\u{1EE1}' => "ohorntilde",+ '\u{1EE2}' => "Ohorndotbelow",+ '\u{1EE3}' => "ohorndotbelow",+ '\u{1EE4}' => "Udotbelow",+ '\u{1EE5}' => "udotbelow",+ '\u{1EE6}' => "Uhookabove",+ '\u{1EE7}' => "uhookabove",+ '\u{1EE8}' => "Uhornacute",+ '\u{1EE9}' => "uhornacute",+ '\u{1EEA}' => "Uhorngrave",+ '\u{1EEB}' => "uhorngrave",+ '\u{1EEC}' => "Uhornhookabove",+ '\u{1EED}' => "uhornhookabove",+ '\u{1EEE}' => "Uhorntilde",+ '\u{1EEF}' => "uhorntilde",+ '\u{1EF0}' => "Uhorndotbelow",+ '\u{1EF1}' => "uhorndotbelow",+ '\u{1EF2}' => "Ygrave",+ '\u{1EF3}' => "ygrave",+ '\u{1EF4}' => "Ydotbelow",+ '\u{1EF5}' => "ydotbelow",+ '\u{1EF6}' => "Yhookabove",+ '\u{1EF7}' => "yhookabove",+ '\u{1EF8}' => "Ytilde",+ '\u{1EF9}' => "ytilde",+ '\u{2002}' => "enspace",+ '\u{200B}' => "zerowidthspace",+ '\u{200C}' => "afii61664",+ '\u{200D}' => "afii301",+ '\u{200E}' => "afii299",+ '\u{200F}' => "afii300",+ '\u{2010}' => "hyphentwo",+ '\u{2012}' => "figuredash",+ '\u{2013}' => "endash",+ '\u{2014}' => "emdash",+ '\u{2015}' => "afii00208",+ '\u{2016}' => "dblverticalbar",+ '\u{2017}' => "dbllowline",+ '\u{2018}' => "quoteleft",+ '\u{2019}' => "quoteright",+ '\u{201A}' => "quotesinglbase",+ '\u{201B}' => "quoteleftreversed",+ '\u{201C}' => "quotedblleft",+ '\u{201D}' => "quotedblright",+ '\u{201E}' => "quotedblbase",+ '\u{2020}' => "dagger",+ '\u{2021}' => "daggerdbl",+ '\u{2022}' => "bullet",+ '\u{2024}' => "onedotenleader",+ '\u{2025}' => "twodotenleader",+ '\u{2026}' => "ellipsis",+ '\u{202C}' => "afii61573",+ '\u{202D}' => "afii61574",+ '\u{202E}' => "afii61575",+ '\u{2030}' => "perthousand",+ '\u{2032}' => "minute",+ '\u{2033}' => "second",+ '\u{2035}' => "primereversed",+ '\u{2039}' => "guilsinglleft",+ '\u{203A}' => "guilsinglright",+ '\u{203B}' => "referencemark",+ '\u{203C}' => "exclamdbl",+ '\u{203E}' => "overline",+ '\u{2042}' => "asterism",+ '\u{2044}' => "fraction",+ '\u{2070}' => "zerosuperior",+ '\u{2074}' => "foursuperior",+ '\u{2075}' => "fivesuperior",+ '\u{2076}' => "sixsuperior",+ '\u{2077}' => "sevensuperior",+ '\u{2078}' => "eightsuperior",+ '\u{2079}' => "ninesuperior",+ '\u{207A}' => "plussuperior",+ '\u{207C}' => "equalsuperior",+ '\u{207D}' => "parenleftsuperior",+ '\u{207E}' => "parenrightsuperior",+ '\u{207F}' => "nsuperior",+ '\u{2080}' => "zeroinferior",+ '\u{2081}' => "oneinferior",+ '\u{2082}' => "twoinferior",+ '\u{2083}' => "threeinferior",+ '\u{2084}' => "fourinferior",+ '\u{2085}' => "fiveinferior",+ '\u{2086}' => "sixinferior",+ '\u{2087}' => "seveninferior",+ '\u{2088}' => "eightinferior",+ '\u{2089}' => "nineinferior",+ '\u{208D}' => "parenleftinferior",+ '\u{208E}' => "parenrightinferior",+ '\u{20A1}' => "colonmonetary",+ '\u{20A2}' => "cruzeiro",+ '\u{20A3}' => "franc",+ '\u{20A4}' => "afii08941",+ '\u{20A7}' => "peseta",+ '\u{20A9}' => "won",+ '\u{20AA}' => "afii57636",+ '\u{20AB}' => "dong",+ '\u{20AC}' => "Euro",+ '\u{2103}' => "centigrade",+ '\u{2105}' => "afii61248",+ '\u{2109}' => "fahrenheit",+ '\u{2111}' => "Ifraktur",+ '\u{2113}' => "afii61289",+ '\u{2116}' => "afii61352",+ '\u{2118}' => "weierstrass",+ '\u{211C}' => "Rfraktur",+ '\u{211E}' => "prescription",+ '\u{2121}' => "telephone",+ '\u{2122}' => "trademark",+ '\u{2126}' => "Ohm",+ '\u{212B}' => "angstrom",+ '\u{212E}' => "estimated",+ '\u{2135}' => "aleph",+ '\u{2153}' => "onethird",+ '\u{2154}' => "twothirds",+ '\u{215B}' => "oneeighth",+ '\u{215C}' => "threeeighths",+ '\u{215D}' => "fiveeighths",+ '\u{215E}' => "seveneighths",+ '\u{2160}' => "Oneroman",+ '\u{2161}' => "Tworoman",+ '\u{2162}' => "Threeroman",+ '\u{2163}' => "Fourroman",+ '\u{2164}' => "Fiveroman",+ '\u{2165}' => "Sixroman",+ '\u{2166}' => "Sevenroman",+ '\u{2167}' => "Eightroman",+ '\u{2168}' => "Nineroman",+ '\u{2169}' => "Tenroman",+ '\u{216A}' => "Elevenroman",+ '\u{216B}' => "Twelveroman",+ '\u{2170}' => "oneroman",+ '\u{2171}' => "tworoman",+ '\u{2172}' => "threeroman",+ '\u{2173}' => "fourroman",+ '\u{2174}' => "fiveroman",+ '\u{2175}' => "sixroman",+ '\u{2176}' => "sevenroman",+ '\u{2177}' => "eightroman",+ '\u{2178}' => "nineroman",+ '\u{2179}' => "tenroman",+ '\u{217A}' => "elevenroman",+ '\u{217B}' => "twelveroman",+ '\u{2190}' => "arrowleft",+ '\u{2191}' => "arrowup",+ '\u{2192}' => "arrowright",+ '\u{2193}' => "arrowdown",+ '\u{2194}' => "arrowboth",+ '\u{2195}' => "arrowupdn",+ '\u{2196}' => "arrowupleft",+ '\u{2197}' => "arrowupright",+ '\u{2198}' => "arrowdownright",+ '\u{2199}' => "arrowdownleft",+ '\u{21A8}' => "arrowupdnbse",+ '\u{21A9}' => "arrowhookright",+ '\u{21AA}' => "arrowhookleft",+ '\u{21B5}' => "carriagereturn",+ '\u{21BC}' => "harpoonleftbarbup",+ '\u{21BD}' => "arrowleftbothalf",+ '\u{21C0}' => "harpoonrightbarbup",+ '\u{21C1}' => "arrowrightbothalf",+ '\u{21C4}' => "arrowrightoverleft",+ '\u{21C5}' => "arrowupleftofdown",+ '\u{21C6}' => "arrowleftoverright",+ '\u{21CD}' => "arrowleftdblstroke",+ '\u{21CF}' => "arrowrightdblstroke",+ '\u{21D0}' => "arrowdblleft",+ '\u{21D1}' => "arrowdblup",+ '\u{21D2}' => "arrowdblright",+ '\u{21D3}' => "arrowdbldown",+ '\u{21D4}' => "arrowdblboth",+ '\u{21DE}' => "pageup",+ '\u{21DF}' => "pagedown",+ '\u{21E0}' => "arrowdashleft",+ '\u{21E1}' => "arrowdashup",+ '\u{21E2}' => "arrowdashright",+ '\u{21E3}' => "arrowdashdown",+ '\u{21E4}' => "arrowtableft",+ '\u{21E5}' => "arrowtabright",+ '\u{21E6}' => "arrowleftwhite",+ '\u{21E7}' => "arrowupwhite",+ '\u{21E8}' => "arrowrightwhite",+ '\u{21E9}' => "arrowdownwhite",+ '\u{21EA}' => "capslock",+ '\u{2200}' => "forall",+ '\u{2202}' => "partialdiff",+ '\u{2203}' => "existential",+ '\u{2205}' => "emptyset",+ '\u{2206}' => "Delta",+ '\u{2207}' => "gradient",+ '\u{2208}' => "element",+ '\u{2209}' => "notelement",+ '\u{220B}' => "suchthat",+ '\u{220C}' => "notcontains",+ '\u{220F}' => "product",+ '\u{2210}' => "coproductdisplay",+ '\u{2211}' => "summation",+ '\u{2212}' => "minus",+ '\u{2213}' => "minusplus",+ '\u{2215}' => "divisionslash",+ '\u{2216}' => "backslashbig",+ '\u{2217}' => "asteriskmath",+ '\u{2219}' => "bulletoperator",+ '\u{221A}' => "radical",+ '\u{221D}' => "proportional",+ '\u{221E}' => "infinity",+ '\u{221F}' => "orthogonal",+ '\u{2220}' => "angle",+ '\u{2223}' => "divides",+ '\u{2225}' => "parallel",+ '\u{2226}' => "notparallel",+ '\u{2227}' => "logicaland",+ '\u{2228}' => "logicalor",+ '\u{2229}' => "intersection",+ '\u{222A}' => "union",+ '\u{222B}' => "integral",+ '\u{222C}' => "dblintegral",+ '\u{222E}' => "contourintegral",+ '\u{2234}' => "therefore",+ '\u{2235}' => "because",+ '\u{2236}' => "ratio",+ '\u{2237}' => "proportion",+ '\u{223C}' => "similar",+ '\u{223D}' => "reversedtilde",+ '\u{2243}' => "asymptoticallyequal",+ '\u{2245}' => "approximatelyequal",+ '\u{2248}' => "approxequal",+ '\u{224C}' => "allequal",+ '\u{2250}' => "approaches",+ '\u{2251}' => "geometricallyequal",+ '\u{2252}' => "approxequalorimage",+ '\u{2253}' => "imageorapproximatelyequal",+ '\u{2260}' => "notequal",+ '\u{2261}' => "equivalence",+ '\u{2262}' => "notidentical",+ '\u{2264}' => "lessequal",+ '\u{2265}' => "greaterequal",+ '\u{2266}' => "lessoverequal",+ '\u{2267}' => "greateroverequal",+ '\u{226A}' => "muchless",+ '\u{226B}' => "muchgreater",+ '\u{226E}' => "notless",+ '\u{226F}' => "notgreater",+ '\u{2270}' => "notlessnorequal",+ '\u{2271}' => "notgreaternorequal",+ '\u{2272}' => "lessorequivalent",+ '\u{2273}' => "greaterorequivalent",+ '\u{2276}' => "lessorgreater",+ '\u{2277}' => "greaterorless",+ '\u{2279}' => "notgreaternorless",+ '\u{227A}' => "precedes",+ '\u{227B}' => "succeeds",+ '\u{2280}' => "notprecedes",+ '\u{2281}' => "notsucceeds",+ '\u{2282}' => "propersubset",+ '\u{2283}' => "propersuperset",+ '\u{2284}' => "notsubset",+ '\u{2285}' => "notsuperset",+ '\u{2286}' => "reflexsubset",+ '\u{2287}' => "reflexsuperset",+ '\u{228A}' => "subsetnotequal",+ '\u{228B}' => "supersetnotequal",+ '\u{228E}' => "unionmultidisplay",+ '\u{2294}' => "unionsqdisplay",+ '\u{2295}' => "circleplus",+ '\u{2296}' => "minuscircle",+ '\u{2297}' => "circlemultiply",+ '\u{2299}' => "circleot",+ '\u{22A3}' => "tackleft",+ '\u{22A4}' => "tackdown",+ '\u{22A5}' => "perpendicular",+ '\u{22BF}' => "righttriangle",+ '\u{22C2}' => "intersectiondisplay",+ '\u{22C3}' => "uniondisplay",+ '\u{22C5}' => "dotmath",+ '\u{22CE}' => "curlyor",+ '\u{22CF}' => "curlyand",+ '\u{22DA}' => "lessequalorgreater",+ '\u{22DB}' => "greaterequalorless",+ '\u{22EE}' => "ellipsisvertical",+ '\u{2302}' => "house",+ '\u{2303}' => "control",+ '\u{2305}' => "projective",+ '\u{2308}' => "ceilingleftbig",+ '\u{2309}' => "ceilingrightbig",+ '\u{230A}' => "floorleftBig",+ '\u{230B}' => "floorrightbig",+ '\u{2310}' => "logicalnotreversed",+ '\u{2312}' => "arc",+ '\u{2318}' => "propellor",+ '\u{2320}' => "integraltop",+ '\u{2321}' => "integralbottom",+ '\u{2325}' => "option",+ '\u{2326}' => "deleteright",+ '\u{2327}' => "clear",+ '\u{2329}' => "angleleft",+ '\u{232A}' => "angleright",+ '\u{232B}' => "deleteleft",+ '\u{2423}' => "blank",+ '\u{2460}' => "onecircle",+ '\u{2461}' => "twocircle",+ '\u{2462}' => "threecircle",+ '\u{2463}' => "fourcircle",+ '\u{2464}' => "fivecircle",+ '\u{2465}' => "sixcircle",+ '\u{2466}' => "sevencircle",+ '\u{2467}' => "eightcircle",+ '\u{2468}' => "ninecircle",+ '\u{2469}' => "tencircle",+ '\u{246A}' => "elevencircle",+ '\u{246B}' => "twelvecircle",+ '\u{246C}' => "thirteencircle",+ '\u{246D}' => "fourteencircle",+ '\u{246E}' => "fifteencircle",+ '\u{246F}' => "sixteencircle",+ '\u{2470}' => "seventeencircle",+ '\u{2471}' => "eighteencircle",+ '\u{2472}' => "nineteencircle",+ '\u{2473}' => "twentycircle",+ '\u{2474}' => "oneparen",+ '\u{2475}' => "twoparen",+ '\u{2476}' => "threeparen",+ '\u{2477}' => "fourparen",+ '\u{2478}' => "fiveparen",+ '\u{2479}' => "sixparen",+ '\u{247A}' => "sevenparen",+ '\u{247B}' => "eightparen",+ '\u{247C}' => "nineparen",+ '\u{247D}' => "tenparen",+ '\u{247E}' => "elevenparen",+ '\u{247F}' => "twelveparen",+ '\u{2480}' => "thirteenparen",+ '\u{2481}' => "fourteenparen",+ '\u{2482}' => "fifteenparen",+ '\u{2483}' => "sixteenparen",+ '\u{2484}' => "seventeenparen",+ '\u{2485}' => "eighteenparen",+ '\u{2486}' => "nineteenparen",+ '\u{2487}' => "twentyparen",+ '\u{2488}' => "oneperiod",+ '\u{2489}' => "twoperiod",+ '\u{248A}' => "threeperiod",+ '\u{248B}' => "fourperiod",+ '\u{248C}' => "fiveperiod",+ '\u{248D}' => "sixperiod",+ '\u{248E}' => "sevenperiod",+ '\u{248F}' => "eightperiod",+ '\u{2490}' => "nineperiod",+ '\u{2491}' => "tenperiod",+ '\u{2492}' => "elevenperiod",+ '\u{2493}' => "twelveperiod",+ '\u{2494}' => "thirteenperiod",+ '\u{2495}' => "fourteenperiod",+ '\u{2496}' => "fifteenperiod",+ '\u{2497}' => "sixteenperiod",+ '\u{2498}' => "seventeenperiod",+ '\u{2499}' => "eighteenperiod",+ '\u{249A}' => "nineteenperiod",+ '\u{249B}' => "twentyperiod",+ '\u{249C}' => "aparen",+ '\u{249D}' => "bparen",+ '\u{249E}' => "cparen",+ '\u{249F}' => "dparen",+ '\u{24A0}' => "eparen",+ '\u{24A1}' => "fparen",+ '\u{24A2}' => "gparen",+ '\u{24A3}' => "hparen",+ '\u{24A4}' => "iparen",+ '\u{24A5}' => "jparen",+ '\u{24A6}' => "kparen",+ '\u{24A7}' => "lparen",+ '\u{24A8}' => "mparen",+ '\u{24A9}' => "nparen",+ '\u{24AA}' => "oparen",+ '\u{24AB}' => "pparen",+ '\u{24AC}' => "qparen",+ '\u{24AD}' => "rparen",+ '\u{24AE}' => "sparen",+ '\u{24AF}' => "tparen",+ '\u{24B0}' => "uparen",+ '\u{24B1}' => "vparen",+ '\u{24B2}' => "wparen",+ '\u{24B3}' => "xparen",+ '\u{24B4}' => "yparen",+ '\u{24B5}' => "zparen",+ '\u{24B6}' => "Acircle",+ '\u{24B7}' => "Bcircle",+ '\u{24B8}' => "Ccircle",+ '\u{24B9}' => "Dcircle",+ '\u{24BA}' => "Ecircle",+ '\u{24BB}' => "Fcircle",+ '\u{24BC}' => "Gcircle",+ '\u{24BD}' => "Hcircle",+ '\u{24BE}' => "Icircle",+ '\u{24BF}' => "Jcircle",+ '\u{24C0}' => "Kcircle",+ '\u{24C1}' => "Lcircle",+ '\u{24C2}' => "Mcircle",+ '\u{24C3}' => "Ncircle",+ '\u{24C4}' => "Ocircle",+ '\u{24C5}' => "Pcircle",+ '\u{24C6}' => "Qcircle",+ '\u{24C7}' => "Rcircle",+ '\u{24C8}' => "Scircle",+ '\u{24C9}' => "Tcircle",+ '\u{24CA}' => "Ucircle",+ '\u{24CB}' => "Vcircle",+ '\u{24CC}' => "Wcircle",+ '\u{24CD}' => "Xcircle",+ '\u{24CE}' => "Ycircle",+ '\u{24CF}' => "Zcircle",+ '\u{24D0}' => "acircle",+ '\u{24D1}' => "bcircle",+ '\u{24D2}' => "ccircle",+ '\u{24D3}' => "dcircle",+ '\u{24D4}' => "ecircle",+ '\u{24D5}' => "fcircle",+ '\u{24D6}' => "gcircle",+ '\u{24D7}' => "hcircle",+ '\u{24D8}' => "icircle",+ '\u{24D9}' => "jcircle",+ '\u{24DA}' => "kcircle",+ '\u{24DB}' => "lcircle",+ '\u{24DC}' => "mcircle",+ '\u{24DD}' => "ncircle",+ '\u{24DE}' => "ocircle",+ '\u{24DF}' => "pcircle",+ '\u{24E0}' => "qcircle",+ '\u{24E1}' => "rcircle",+ '\u{24E2}' => "scircle",+ '\u{24E3}' => "tcircle",+ '\u{24E4}' => "ucircle",+ '\u{24E5}' => "vcircle",+ '\u{24E6}' => "wcircle",+ '\u{24E7}' => "xcircle",+ '\u{24E8}' => "ycircle",+ '\u{24E9}' => "zcircle",+ '\u{2500}' => "SF100000",+ '\u{2502}' => "SF110000",+ '\u{250C}' => "SF010000",+ '\u{2510}' => "SF030000",+ '\u{2514}' => "SF020000",+ '\u{2518}' => "SF040000",+ '\u{251C}' => "SF080000",+ '\u{2524}' => "SF090000",+ '\u{252C}' => "SF060000",+ '\u{2534}' => "SF070000",+ '\u{253C}' => "SF050000",+ '\u{2550}' => "SF430000",+ '\u{2551}' => "SF240000",+ '\u{2552}' => "SF510000",+ '\u{2553}' => "SF520000",+ '\u{2554}' => "SF390000",+ '\u{2555}' => "SF220000",+ '\u{2556}' => "SF210000",+ '\u{2557}' => "SF250000",+ '\u{2558}' => "SF500000",+ '\u{2559}' => "SF490000",+ '\u{255A}' => "SF380000",+ '\u{255B}' => "SF280000",+ '\u{255C}' => "SF270000",+ '\u{255D}' => "SF260000",+ '\u{255E}' => "SF360000",+ '\u{255F}' => "SF370000",+ '\u{2560}' => "SF420000",+ '\u{2561}' => "SF190000",+ '\u{2562}' => "SF200000",+ '\u{2563}' => "SF230000",+ '\u{2564}' => "SF470000",+ '\u{2565}' => "SF480000",+ '\u{2566}' => "SF410000",+ '\u{2567}' => "SF450000",+ '\u{2568}' => "SF460000",+ '\u{2569}' => "SF400000",+ '\u{256A}' => "SF540000",+ '\u{256B}' => "SF530000",+ '\u{256C}' => "SF440000",+ '\u{2580}' => "upblock",+ '\u{2584}' => "dnblock",+ '\u{2588}' => "block",+ '\u{258C}' => "lfblock",+ '\u{2590}' => "rtblock",+ '\u{2591}' => "ltshade",+ '\u{2592}' => "shade",+ '\u{2593}' => "dkshade",+ '\u{25A0}' => "blacksquare",+ '\u{25A1}' => "H22073",+ '\u{25A3}' => "squarewhitewithsmallblack",+ '\u{25A4}' => "squarehorizontalfill",+ '\u{25A5}' => "squareverticalfill",+ '\u{25A6}' => "squareorthogonalcrosshatchfill",+ '\u{25A7}' => "squareupperlefttolowerrightfill",+ '\u{25A8}' => "squareupperrighttolowerleftfill",+ '\u{25A9}' => "squarediagonalcrosshatchfill",+ '\u{25AA}' => "H18543",+ '\u{25AB}' => "H18551",+ '\u{25AC}' => "blackrectangle",+ '\u{25B2}' => "blackuppointingtriangle",+ '\u{25B3}' => "whiteuppointingtriangle",+ '\u{25B4}' => "blackuppointingsmalltriangle",+ '\u{25B5}' => "whiteuppointingsmalltriangle",+ '\u{25B6}' => "blackrightpointingtriangle",+ '\u{25B7}' => "whiterightpointingtriangle",+ '\u{25B9}' => "whiterightpointingsmalltriangle",+ '\u{25BA}' => "blackrightpointingpointer",+ '\u{25BC}' => "blackdownpointingtriangle",+ '\u{25BD}' => "whitedownpointingtriangle",+ '\u{25BF}' => "whitedownpointingsmalltriangle",+ '\u{25C0}' => "blackleftpointingtriangle",+ '\u{25C1}' => "whiteleftpointingtriangle",+ '\u{25C3}' => "whiteleftpointingsmalltriangle",+ '\u{25C4}' => "blackleftpointingpointer",+ '\u{25C6}' => "blackdiamond",+ '\u{25C7}' => "whitediamond",+ '\u{25C8}' => "whitediamondcontainingblacksmalldiamond",+ '\u{25C9}' => "fisheye",+ '\u{25CA}' => "lozenge",+ '\u{25CB}' => "circle",+ '\u{25CC}' => "dottedcircle",+ '\u{25CE}' => "bullseye",+ '\u{25CF}' => "H18533",+ '\u{25D0}' => "circlewithlefthalfblack",+ '\u{25D1}' => "circlewithrighthalfblack",+ '\u{25D8}' => "bulletinverse",+ '\u{25D9}' => "invcircle",+ '\u{25E2}' => "blacklowerrighttriangle",+ '\u{25E3}' => "blacklowerlefttriangle",+ '\u{25E4}' => "blackupperlefttriangle",+ '\u{25E5}' => "blackupperrighttriangle",+ '\u{25E6}' => "openbullet",+ '\u{25EF}' => "largecircle",+ '\u{2605}' => "blackstar",+ '\u{2606}' => "whitestar",+ '\u{260E}' => "telephoneblack",+ '\u{260F}' => "whitetelephone",+ '\u{261C}' => "pointingindexleftwhite",+ '\u{261D}' => "pointingindexupwhite",+ '\u{261E}' => "pointingindexrightwhite",+ '\u{261F}' => "pointingindexdownwhite",+ '\u{262F}' => "yinyang",+ '\u{263A}' => "smileface",+ '\u{263B}' => "blacksmilingface",+ '\u{263C}' => "compass",+ '\u{2640}' => "female",+ '\u{2641}' => "earth",+ '\u{2642}' => "male",+ '\u{2660}' => "spade",+ '\u{2661}' => "heartsuitwhite",+ '\u{2662}' => "diamondsuitwhite",+ '\u{2663}' => "club",+ '\u{2664}' => "spadesuitwhite",+ '\u{2665}' => "heart",+ '\u{2666}' => "diamond",+ '\u{2667}' => "clubsuitwhite",+ '\u{2668}' => "hotsprings",+ '\u{2669}' => "quarternote",+ '\u{266A}' => "musicalnote",+ '\u{266B}' => "eighthnotebeamed",+ '\u{266C}' => "beamedsixteenthnotes",+ '\u{266D}' => "musicflatsign",+ '\u{266F}' => "musicsharpsign",+ '\u{2713}' => "checkmark",+ '\u{278A}' => "onecircleinversesansserif",+ '\u{278B}' => "twocircleinversesansserif",+ '\u{278C}' => "threecircleinversesansserif",+ '\u{278D}' => "fourcircleinversesansserif",+ '\u{278E}' => "fivecircleinversesansserif",+ '\u{278F}' => "sixcircleinversesansserif",+ '\u{2790}' => "sevencircleinversesansserif",+ '\u{2791}' => "eightcircleinversesansserif",+ '\u{2792}' => "ninecircleinversesansserif",+ '\u{279E}' => "arrowrightheavy",+ '\u{3000}' => "ideographicspace",+ '\u{3001}' => "ideographiccomma",+ '\u{3002}' => "ideographicperiod",+ '\u{3003}' => "dittomark",+ '\u{3004}' => "jis",+ '\u{3005}' => "ideographiciterationmark",+ '\u{3006}' => "ideographicclose",+ '\u{3007}' => "ideographiczero",+ '\u{3008}' => "anglebracketleft",+ '\u{3009}' => "anglebracketright",+ '\u{300A}' => "dblanglebracketleft",+ '\u{300B}' => "dblanglebracketright",+ '\u{300C}' => "cornerbracketleft",+ '\u{300D}' => "cornerbracketright",+ '\u{300E}' => "whitecornerbracketleft",+ '\u{300F}' => "whitecornerbracketright",+ '\u{3010}' => "blacklenticularbracketleft",+ '\u{3011}' => "blacklenticularbracketright",+ '\u{3012}' => "postalmark",+ '\u{3013}' => "getamark",+ '\u{3014}' => "tortoiseshellbracketleft",+ '\u{3015}' => "tortoiseshellbracketright",+ '\u{3016}' => "whitelenticularbracketleft",+ '\u{3017}' => "whitelenticularbracketright",+ '\u{3018}' => "whitetortoiseshellbracketleft",+ '\u{3019}' => "whitetortoiseshellbracketright",+ '\u{301C}' => "wavedash",+ '\u{301D}' => "quotedblprimereversed",+ '\u{301E}' => "quotedblprime",+ '\u{3020}' => "postalmarkface",+ '\u{3021}' => "onehangzhou",+ '\u{3022}' => "twohangzhou",+ '\u{3023}' => "threehangzhou",+ '\u{3024}' => "fourhangzhou",+ '\u{3025}' => "fivehangzhou",+ '\u{3026}' => "sixhangzhou",+ '\u{3027}' => "sevenhangzhou",+ '\u{3028}' => "eighthangzhou",+ '\u{3029}' => "ninehangzhou",+ '\u{3036}' => "circlepostalmark",+ '\u{3041}' => "asmallhiragana",+ '\u{3042}' => "ahiragana",+ '\u{3043}' => "ismallhiragana",+ '\u{3044}' => "ihiragana",+ '\u{3045}' => "usmallhiragana",+ '\u{3046}' => "uhiragana",+ '\u{3047}' => "esmallhiragana",+ '\u{3048}' => "ehiragana",+ '\u{3049}' => "osmallhiragana",+ '\u{304A}' => "ohiragana",+ '\u{304B}' => "kahiragana",+ '\u{304C}' => "gahiragana",+ '\u{304D}' => "kihiragana",+ '\u{304E}' => "gihiragana",+ '\u{304F}' => "kuhiragana",+ '\u{3050}' => "guhiragana",+ '\u{3051}' => "kehiragana",+ '\u{3052}' => "gehiragana",+ '\u{3053}' => "kohiragana",+ '\u{3054}' => "gohiragana",+ '\u{3055}' => "sahiragana",+ '\u{3056}' => "zahiragana",+ '\u{3057}' => "sihiragana",+ '\u{3058}' => "zihiragana",+ '\u{3059}' => "suhiragana",+ '\u{305A}' => "zuhiragana",+ '\u{305B}' => "sehiragana",+ '\u{305C}' => "zehiragana",+ '\u{305D}' => "sohiragana",+ '\u{305E}' => "zohiragana",+ '\u{305F}' => "tahiragana",+ '\u{3060}' => "dahiragana",+ '\u{3061}' => "tihiragana",+ '\u{3062}' => "dihiragana",+ '\u{3063}' => "tusmallhiragana",+ '\u{3064}' => "tuhiragana",+ '\u{3065}' => "duhiragana",+ '\u{3066}' => "tehiragana",+ '\u{3067}' => "dehiragana",+ '\u{3068}' => "tohiragana",+ '\u{3069}' => "dohiragana",+ '\u{306A}' => "nahiragana",+ '\u{306B}' => "nihiragana",+ '\u{306C}' => "nuhiragana",+ '\u{306D}' => "nehiragana",+ '\u{306E}' => "nohiragana",+ '\u{306F}' => "hahiragana",+ '\u{3070}' => "bahiragana",+ '\u{3071}' => "pahiragana",+ '\u{3072}' => "hihiragana",+ '\u{3073}' => "bihiragana",+ '\u{3074}' => "pihiragana",+ '\u{3075}' => "huhiragana",+ '\u{3076}' => "buhiragana",+ '\u{3077}' => "puhiragana",+ '\u{3078}' => "hehiragana",+ '\u{3079}' => "behiragana",+ '\u{307A}' => "pehiragana",+ '\u{307B}' => "hohiragana",+ '\u{307C}' => "bohiragana",+ '\u{307D}' => "pohiragana",+ '\u{307E}' => "mahiragana",+ '\u{307F}' => "mihiragana",+ '\u{3080}' => "muhiragana",+ '\u{3081}' => "mehiragana",+ '\u{3082}' => "mohiragana",+ '\u{3083}' => "yasmallhiragana",+ '\u{3084}' => "yahiragana",+ '\u{3085}' => "yusmallhiragana",+ '\u{3086}' => "yuhiragana",+ '\u{3087}' => "yosmallhiragana",+ '\u{3088}' => "yohiragana",+ '\u{3089}' => "rahiragana",+ '\u{308A}' => "rihiragana",+ '\u{308B}' => "ruhiragana",+ '\u{308C}' => "rehiragana",+ '\u{308D}' => "rohiragana",+ '\u{308E}' => "wasmallhiragana",+ '\u{308F}' => "wahiragana",+ '\u{3090}' => "wihiragana",+ '\u{3091}' => "wehiragana",+ '\u{3092}' => "wohiragana",+ '\u{3093}' => "nhiragana",+ '\u{3094}' => "vuhiragana",+ '\u{309B}' => "voicedmarkkana",+ '\u{309C}' => "semivoicedmarkkana",+ '\u{309D}' => "iterationhiragana",+ '\u{309E}' => "voicediterationhiragana",+ '\u{30A1}' => "asmallkatakana",+ '\u{30A2}' => "akatakana",+ '\u{30A3}' => "ismallkatakana",+ '\u{30A4}' => "ikatakana",+ '\u{30A5}' => "usmallkatakana",+ '\u{30A6}' => "ukatakana",+ '\u{30A7}' => "esmallkatakana",+ '\u{30A8}' => "ekatakana",+ '\u{30A9}' => "osmallkatakana",+ '\u{30AA}' => "okatakana",+ '\u{30AB}' => "kakatakana",+ '\u{30AC}' => "gakatakana",+ '\u{30AD}' => "kikatakana",+ '\u{30AE}' => "gikatakana",+ '\u{30AF}' => "kukatakana",+ '\u{30B0}' => "gukatakana",+ '\u{30B1}' => "kekatakana",+ '\u{30B2}' => "gekatakana",+ '\u{30B3}' => "kokatakana",+ '\u{30B4}' => "gokatakana",+ '\u{30B5}' => "sakatakana",+ '\u{30B6}' => "zakatakana",+ '\u{30B7}' => "sikatakana",+ '\u{30B8}' => "zikatakana",+ '\u{30B9}' => "sukatakana",+ '\u{30BA}' => "zukatakana",+ '\u{30BB}' => "sekatakana",+ '\u{30BC}' => "zekatakana",+ '\u{30BD}' => "sokatakana",+ '\u{30BE}' => "zokatakana",+ '\u{30BF}' => "takatakana",+ '\u{30C0}' => "dakatakana",+ '\u{30C1}' => "tikatakana",+ '\u{30C2}' => "dikatakana",+ '\u{30C3}' => "tusmallkatakana",+ '\u{30C4}' => "tukatakana",+ '\u{30C5}' => "dukatakana",+ '\u{30C6}' => "tekatakana",+ '\u{30C7}' => "dekatakana",+ '\u{30C8}' => "tokatakana",+ '\u{30C9}' => "dokatakana",+ '\u{30CA}' => "nakatakana",+ '\u{30CB}' => "nikatakana",+ '\u{30CC}' => "nukatakana",+ '\u{30CD}' => "nekatakana",+ '\u{30CE}' => "nokatakana",+ '\u{30CF}' => "hakatakana",+ '\u{30D0}' => "bakatakana",+ '\u{30D1}' => "pakatakana",+ '\u{30D2}' => "hikatakana",+ '\u{30D3}' => "bikatakana",+ '\u{30D4}' => "pikatakana",+ '\u{30D5}' => "hukatakana",+ '\u{30D6}' => "bukatakana",+ '\u{30D7}' => "pukatakana",+ '\u{30D8}' => "hekatakana",+ '\u{30D9}' => "bekatakana",+ '\u{30DA}' => "pekatakana",+ '\u{30DB}' => "hokatakana",+ '\u{30DC}' => "bokatakana",+ '\u{30DD}' => "pokatakana",+ '\u{30DE}' => "makatakana",+ '\u{30DF}' => "mikatakana",+ '\u{30E0}' => "mukatakana",+ '\u{30E1}' => "mekatakana",+ '\u{30E2}' => "mokatakana",+ '\u{30E3}' => "yasmallkatakana",+ '\u{30E4}' => "yakatakana",+ '\u{30E5}' => "yusmallkatakana",+ '\u{30E6}' => "yukatakana",+ '\u{30E7}' => "yosmallkatakana",+ '\u{30E8}' => "yokatakana",+ '\u{30E9}' => "rakatakana",+ '\u{30EA}' => "rikatakana",+ '\u{30EB}' => "rukatakana",+ '\u{30EC}' => "rekatakana",+ '\u{30ED}' => "rokatakana",+ '\u{30EE}' => "wasmallkatakana",+ '\u{30EF}' => "wakatakana",+ '\u{30F0}' => "wikatakana",+ '\u{30F1}' => "wekatakana",+ '\u{30F2}' => "wokatakana",+ '\u{30F3}' => "nkatakana",+ '\u{30F4}' => "vukatakana",+ '\u{30F5}' => "kasmallkatakana",+ '\u{30F6}' => "kesmallkatakana",+ '\u{30F7}' => "vakatakana",+ '\u{30F8}' => "vikatakana",+ '\u{30F9}' => "vekatakana",+ '\u{30FA}' => "vokatakana",+ '\u{30FB}' => "dotkatakana",+ '\u{30FC}' => "prolongedkana",+ '\u{30FD}' => "iterationkatakana",+ '\u{30FE}' => "voicediterationkatakana",+ '\u{3105}' => "bbopomofo",+ '\u{3106}' => "pbopomofo",+ '\u{3107}' => "mbopomofo",+ '\u{3108}' => "fbopomofo",+ '\u{3109}' => "dbopomofo",+ '\u{310A}' => "tbopomofo",+ '\u{310B}' => "nbopomofo",+ '\u{310C}' => "lbopomofo",+ '\u{310D}' => "gbopomofo",+ '\u{310E}' => "kbopomofo",+ '\u{310F}' => "hbopomofo",+ '\u{3110}' => "jbopomofo",+ '\u{3111}' => "qbopomofo",+ '\u{3112}' => "xbopomofo",+ '\u{3113}' => "zhbopomofo",+ '\u{3114}' => "chbopomofo",+ '\u{3115}' => "shbopomofo",+ '\u{3116}' => "rbopomofo",+ '\u{3117}' => "zbopomofo",+ '\u{3118}' => "cbopomofo",+ '\u{3119}' => "sbopomofo",+ '\u{311A}' => "abopomofo",+ '\u{311B}' => "obopomofo",+ '\u{311C}' => "ebopomofo",+ '\u{311D}' => "ehbopomofo",+ '\u{311E}' => "aibopomofo",+ '\u{311F}' => "eibopomofo",+ '\u{3120}' => "aubopomofo",+ '\u{3121}' => "oubopomofo",+ '\u{3122}' => "anbopomofo",+ '\u{3123}' => "enbopomofo",+ '\u{3124}' => "angbopomofo",+ '\u{3125}' => "engbopomofo",+ '\u{3126}' => "erbopomofo",+ '\u{3127}' => "ibopomofo",+ '\u{3128}' => "ubopomofo",+ '\u{3129}' => "iubopomofo",+ '\u{3131}' => "kiyeokkorean",+ '\u{3132}' => "ssangkiyeokkorean",+ '\u{3133}' => "kiyeoksioskorean",+ '\u{3134}' => "nieunkorean",+ '\u{3135}' => "nieuncieuckorean",+ '\u{3136}' => "nieunhieuhkorean",+ '\u{3137}' => "tikeutkorean",+ '\u{3138}' => "ssangtikeutkorean",+ '\u{3139}' => "rieulkorean",+ '\u{313A}' => "rieulkiyeokkorean",+ '\u{313B}' => "rieulmieumkorean",+ '\u{313C}' => "rieulpieupkorean",+ '\u{313D}' => "rieulsioskorean",+ '\u{313E}' => "rieulthieuthkorean",+ '\u{313F}' => "rieulphieuphkorean",+ '\u{3140}' => "rieulhieuhkorean",+ '\u{3141}' => "mieumkorean",+ '\u{3142}' => "pieupkorean",+ '\u{3143}' => "ssangpieupkorean",+ '\u{3144}' => "pieupsioskorean",+ '\u{3145}' => "sioskorean",+ '\u{3146}' => "ssangsioskorean",+ '\u{3147}' => "ieungkorean",+ '\u{3148}' => "cieuckorean",+ '\u{3149}' => "ssangcieuckorean",+ '\u{314A}' => "chieuchkorean",+ '\u{314B}' => "khieukhkorean",+ '\u{314C}' => "thieuthkorean",+ '\u{314D}' => "phieuphkorean",+ '\u{314E}' => "hieuhkorean",+ '\u{314F}' => "akorean",+ '\u{3150}' => "aekorean",+ '\u{3151}' => "yakorean",+ '\u{3152}' => "yaekorean",+ '\u{3153}' => "eokorean",+ '\u{3154}' => "ekorean",+ '\u{3155}' => "yeokorean",+ '\u{3156}' => "yekorean",+ '\u{3157}' => "okorean",+ '\u{3158}' => "wakorean",+ '\u{3159}' => "waekorean",+ '\u{315A}' => "oekorean",+ '\u{315B}' => "yokorean",+ '\u{315C}' => "ukorean",+ '\u{315D}' => "weokorean",+ '\u{315E}' => "wekorean",+ '\u{315F}' => "wikorean",+ '\u{3160}' => "yukorean",+ '\u{3161}' => "eukorean",+ '\u{3162}' => "yikorean",+ '\u{3163}' => "ikorean",+ '\u{3164}' => "hangulfiller",+ '\u{3165}' => "ssangnieunkorean",+ '\u{3166}' => "nieuntikeutkorean",+ '\u{3167}' => "nieunsioskorean",+ '\u{3168}' => "nieunpansioskorean",+ '\u{3169}' => "rieulkiyeoksioskorean",+ '\u{316A}' => "rieultikeutkorean",+ '\u{316B}' => "rieulpieupsioskorean",+ '\u{316C}' => "rieulpansioskorean",+ '\u{316D}' => "rieulyeorinhieuhkorean",+ '\u{316E}' => "mieumpieupkorean",+ '\u{316F}' => "mieumsioskorean",+ '\u{3170}' => "mieumpansioskorean",+ '\u{3171}' => "kapyeounmieumkorean",+ '\u{3172}' => "pieupkiyeokkorean",+ '\u{3173}' => "pieuptikeutkorean",+ '\u{3174}' => "pieupsioskiyeokkorean",+ '\u{3175}' => "pieupsiostikeutkorean",+ '\u{3176}' => "pieupcieuckorean",+ '\u{3177}' => "pieupthieuthkorean",+ '\u{3178}' => "kapyeounpieupkorean",+ '\u{3179}' => "kapyeounssangpieupkorean",+ '\u{317A}' => "sioskiyeokkorean",+ '\u{317B}' => "siosnieunkorean",+ '\u{317C}' => "siostikeutkorean",+ '\u{317D}' => "siospieupkorean",+ '\u{317E}' => "sioscieuckorean",+ '\u{317F}' => "pansioskorean",+ '\u{3180}' => "ssangieungkorean",+ '\u{3181}' => "yesieungkorean",+ '\u{3182}' => "yesieungsioskorean",+ '\u{3183}' => "yesieungpansioskorean",+ '\u{3184}' => "kapyeounphieuphkorean",+ '\u{3185}' => "ssanghieuhkorean",+ '\u{3186}' => "yeorinhieuhkorean",+ '\u{3187}' => "yoyakorean",+ '\u{3188}' => "yoyaekorean",+ '\u{3189}' => "yoikorean",+ '\u{318A}' => "yuyeokorean",+ '\u{318B}' => "yuyekorean",+ '\u{318C}' => "yuikorean",+ '\u{318D}' => "araeakorean",+ '\u{318E}' => "araeaekorean",+ '\u{3200}' => "kiyeokparenkorean",+ '\u{3201}' => "nieunparenkorean",+ '\u{3202}' => "tikeutparenkorean",+ '\u{3203}' => "rieulparenkorean",+ '\u{3204}' => "mieumparenkorean",+ '\u{3205}' => "pieupparenkorean",+ '\u{3206}' => "siosparenkorean",+ '\u{3207}' => "ieungparenkorean",+ '\u{3208}' => "cieucparenkorean",+ '\u{3209}' => "chieuchparenkorean",+ '\u{320A}' => "khieukhparenkorean",+ '\u{320B}' => "thieuthparenkorean",+ '\u{320C}' => "phieuphparenkorean",+ '\u{320D}' => "hieuhparenkorean",+ '\u{320E}' => "kiyeokaparenkorean",+ '\u{320F}' => "nieunaparenkorean",+ '\u{3210}' => "tikeutaparenkorean",+ '\u{3211}' => "rieulaparenkorean",+ '\u{3212}' => "mieumaparenkorean",+ '\u{3213}' => "pieupaparenkorean",+ '\u{3214}' => "siosaparenkorean",+ '\u{3215}' => "ieungaparenkorean",+ '\u{3216}' => "cieucaparenkorean",+ '\u{3217}' => "chieuchaparenkorean",+ '\u{3218}' => "khieukhaparenkorean",+ '\u{3219}' => "thieuthaparenkorean",+ '\u{321A}' => "phieuphaparenkorean",+ '\u{321B}' => "hieuhaparenkorean",+ '\u{321C}' => "cieucuparenkorean",+ '\u{3220}' => "oneideographicparen",+ '\u{3221}' => "twoideographicparen",+ '\u{3222}' => "threeideographicparen",+ '\u{3223}' => "fourideographicparen",+ '\u{3224}' => "fiveideographicparen",+ '\u{3225}' => "sixideographicparen",+ '\u{3226}' => "sevenideographicparen",+ '\u{3227}' => "eightideographicparen",+ '\u{3228}' => "nineideographicparen",+ '\u{3229}' => "tenideographicparen",+ '\u{322A}' => "ideographicmoonparen",+ '\u{322B}' => "ideographicfireparen",+ '\u{322C}' => "ideographicwaterparen",+ '\u{322D}' => "ideographicwoodparen",+ '\u{322E}' => "ideographicmetalparen",+ '\u{322F}' => "ideographicearthparen",+ '\u{3230}' => "ideographicsunparen",+ '\u{3231}' => "ideographicstockparen",+ '\u{3232}' => "ideographichaveparen",+ '\u{3233}' => "ideographicsocietyparen",+ '\u{3234}' => "ideographicnameparen",+ '\u{3235}' => "ideographicspecialparen",+ '\u{3236}' => "ideographicfinancialparen",+ '\u{3237}' => "ideographiccongratulationparen",+ '\u{3238}' => "ideographiclaborparen",+ '\u{3239}' => "ideographicrepresentparen",+ '\u{323A}' => "ideographiccallparen",+ '\u{323B}' => "ideographicstudyparen",+ '\u{323C}' => "ideographicsuperviseparen",+ '\u{323D}' => "ideographicenterpriseparen",+ '\u{323E}' => "ideographicresourceparen",+ '\u{323F}' => "ideographicallianceparen",+ '\u{3240}' => "ideographicfestivalparen",+ '\u{3242}' => "ideographicselfparen",+ '\u{3243}' => "ideographicreachparen",+ '\u{3260}' => "kiyeokcirclekorean",+ '\u{3261}' => "nieuncirclekorean",+ '\u{3262}' => "tikeutcirclekorean",+ '\u{3263}' => "rieulcirclekorean",+ '\u{3264}' => "mieumcirclekorean",+ '\u{3265}' => "pieupcirclekorean",+ '\u{3266}' => "sioscirclekorean",+ '\u{3267}' => "ieungcirclekorean",+ '\u{3268}' => "cieuccirclekorean",+ '\u{3269}' => "chieuchcirclekorean",+ '\u{326A}' => "khieukhcirclekorean",+ '\u{326B}' => "thieuthcirclekorean",+ '\u{326C}' => "phieuphcirclekorean",+ '\u{326D}' => "hieuhcirclekorean",+ '\u{326E}' => "kiyeokacirclekorean",+ '\u{326F}' => "nieunacirclekorean",+ '\u{3270}' => "tikeutacirclekorean",+ '\u{3271}' => "rieulacirclekorean",+ '\u{3272}' => "mieumacirclekorean",+ '\u{3273}' => "pieupacirclekorean",+ '\u{3274}' => "siosacirclekorean",+ '\u{3275}' => "ieungacirclekorean",+ '\u{3276}' => "cieucacirclekorean",+ '\u{3277}' => "chieuchacirclekorean",+ '\u{3278}' => "khieukhacirclekorean",+ '\u{3279}' => "thieuthacirclekorean",+ '\u{327A}' => "phieuphacirclekorean",+ '\u{327B}' => "hieuhacirclekorean",+ '\u{327F}' => "koreanstandardsymbol",+ '\u{328A}' => "ideographmooncircle",+ '\u{328B}' => "ideographfirecircle",+ '\u{328C}' => "ideographwatercircle",+ '\u{328D}' => "ideographwoodcircle",+ '\u{328E}' => "ideographmetalcircle",+ '\u{328F}' => "ideographearthcircle",+ '\u{3290}' => "ideographsuncircle",+ '\u{3294}' => "ideographnamecircle",+ '\u{3296}' => "ideographicfinancialcircle",+ '\u{3298}' => "ideographiclaborcircle",+ '\u{3299}' => "ideographicsecretcircle",+ '\u{329D}' => "ideographicexcellentcircle",+ '\u{329E}' => "ideographicprintcircle",+ '\u{32A3}' => "ideographiccorrectcircle",+ '\u{32A4}' => "ideographichighcircle",+ '\u{32A5}' => "ideographiccentrecircle",+ '\u{32A6}' => "ideographiclowcircle",+ '\u{32A7}' => "ideographicleftcircle",+ '\u{32A8}' => "ideographicrightcircle",+ '\u{32A9}' => "ideographicmedicinecircle",+ '\u{3300}' => "apaatosquare",+ '\u{3303}' => "aarusquare",+ '\u{3305}' => "intisquare",+ '\u{330D}' => "karoriisquare",+ '\u{3314}' => "kirosquare",+ '\u{3315}' => "kiroguramusquare",+ '\u{3316}' => "kiromeetorusquare",+ '\u{3318}' => "guramusquare",+ '\u{331E}' => "kooposquare",+ '\u{3322}' => "sentisquare",+ '\u{3323}' => "sentosquare",+ '\u{3326}' => "dorusquare",+ '\u{3327}' => "tonsquare",+ '\u{332A}' => "haitusquare",+ '\u{332B}' => "paasentosquare",+ '\u{3331}' => "birusquare",+ '\u{3333}' => "huiitosquare",+ '\u{3336}' => "hekutaarusquare",+ '\u{3339}' => "herutusquare",+ '\u{333B}' => "peezisquare",+ '\u{3342}' => "hoonsquare",+ '\u{3347}' => "mansyonsquare",+ '\u{3349}' => "mirisquare",+ '\u{334A}' => "miribaarusquare",+ '\u{334D}' => "meetorusquare",+ '\u{334E}' => "yaadosquare",+ '\u{3351}' => "rittorusquare",+ '\u{3357}' => "wattosquare",+ '\u{337B}' => "heiseierasquare",+ '\u{337C}' => "syouwaerasquare",+ '\u{337D}' => "taisyouerasquare",+ '\u{337E}' => "meizierasquare",+ '\u{337F}' => "corporationsquare",+ '\u{3380}' => "paampssquare",+ '\u{3381}' => "nasquare",+ '\u{3382}' => "muasquare",+ '\u{3383}' => "masquare",+ '\u{3384}' => "kasquare",+ '\u{3385}' => "KBsquare",+ '\u{3386}' => "MBsquare",+ '\u{3387}' => "GBsquare",+ '\u{3388}' => "calsquare",+ '\u{3389}' => "kcalsquare",+ '\u{338A}' => "pfsquare",+ '\u{338B}' => "nfsquare",+ '\u{338C}' => "mufsquare",+ '\u{338D}' => "mugsquare",+ '\u{338E}' => "squaremg",+ '\u{338F}' => "squarekg",+ '\u{3390}' => "Hzsquare",+ '\u{3391}' => "khzsquare",+ '\u{3392}' => "mhzsquare",+ '\u{3393}' => "ghzsquare",+ '\u{3394}' => "thzsquare",+ '\u{3395}' => "mulsquare",+ '\u{3396}' => "mlsquare",+ '\u{3397}' => "dlsquare",+ '\u{3398}' => "klsquare",+ '\u{3399}' => "fmsquare",+ '\u{339A}' => "nmsquare",+ '\u{339B}' => "mumsquare",+ '\u{339C}' => "squaremm",+ '\u{339D}' => "squarecm",+ '\u{339E}' => "squarekm",+ '\u{339F}' => "mmsquaredsquare",+ '\u{33A0}' => "cmsquaredsquare",+ '\u{33A1}' => "squaremsquared",+ '\u{33A2}' => "kmsquaredsquare",+ '\u{33A3}' => "mmcubedsquare",+ '\u{33A4}' => "cmcubedsquare",+ '\u{33A5}' => "mcubedsquare",+ '\u{33A6}' => "kmcubedsquare",+ '\u{33A7}' => "moverssquare",+ '\u{33A8}' => "moverssquaredsquare",+ '\u{33A9}' => "pasquare",+ '\u{33AA}' => "kpasquare",+ '\u{33AB}' => "mpasquare",+ '\u{33AC}' => "gpasquare",+ '\u{33AD}' => "radsquare",+ '\u{33AE}' => "radoverssquare",+ '\u{33AF}' => "radoverssquaredsquare",+ '\u{33B0}' => "pssquare",+ '\u{33B1}' => "nssquare",+ '\u{33B2}' => "mussquare",+ '\u{33B3}' => "mssquare",+ '\u{33B4}' => "pvsquare",+ '\u{33B5}' => "nvsquare",+ '\u{33B6}' => "muvsquare",+ '\u{33B7}' => "mvsquare",+ '\u{33B8}' => "kvsquare",+ '\u{33B9}' => "mvmegasquare",+ '\u{33BA}' => "pwsquare",+ '\u{33BB}' => "nwsquare",+ '\u{33BC}' => "muwsquare",+ '\u{33BD}' => "mwsquare",+ '\u{33BE}' => "kwsquare",+ '\u{33BF}' => "mwmegasquare",+ '\u{33C0}' => "kohmsquare",+ '\u{33C1}' => "mohmsquare",+ '\u{33C2}' => "amsquare",+ '\u{33C3}' => "bqsquare",+ '\u{33C4}' => "squarecc",+ '\u{33C5}' => "cdsquare",+ '\u{33C6}' => "coverkgsquare",+ '\u{33C7}' => "cosquare",+ '\u{33C8}' => "dbsquare",+ '\u{33C9}' => "gysquare",+ '\u{33CA}' => "hasquare",+ '\u{33CB}' => "HPsquare",+ '\u{33CD}' => "KKsquare",+ '\u{33CE}' => "squarekmcapital",+ '\u{33CF}' => "ktsquare",+ '\u{33D0}' => "lmsquare",+ '\u{33D1}' => "squareln",+ '\u{33D2}' => "squarelog",+ '\u{33D3}' => "lxsquare",+ '\u{33D4}' => "mbsquare",+ '\u{33D5}' => "squaremil",+ '\u{33D6}' => "molsquare",+ '\u{33D8}' => "pmsquare",+ '\u{33DB}' => "srsquare",+ '\u{33DC}' => "svsquare",+ '\u{33DD}' => "wbsquare",+ '\u{5344}' => "twentyhangzhou",+ '\u{F6BE}' => "dotlessj",+ '\u{F6BF}' => "LL",+ '\u{F6C0}' => "ll",+ '\u{F6C3}' => "commaaccent",+ '\u{F6C4}' => "afii10063",+ '\u{F6C5}' => "afii10064",+ '\u{F6C6}' => "afii10192",+ '\u{F6C7}' => "afii10831",+ '\u{F6C8}' => "afii10832",+ '\u{F6C9}' => "Acute",+ '\u{F6CA}' => "Caron",+ '\u{F6CB}' => "Dieresis",+ '\u{F6CC}' => "DieresisAcute",+ '\u{F6CD}' => "DieresisGrave",+ '\u{F6CE}' => "Grave",+ '\u{F6CF}' => "Hungarumlaut",+ '\u{F6D0}' => "Macron",+ '\u{F6D1}' => "cyrBreve",+ '\u{F6D2}' => "cyrFlex",+ '\u{F6D3}' => "dblGrave",+ '\u{F6D4}' => "cyrbreve",+ '\u{F6D5}' => "cyrflex",+ '\u{F6D6}' => "dblgrave",+ '\u{F6D7}' => "dieresisacute",+ '\u{F6D8}' => "dieresisgrave",+ '\u{F6D9}' => "copyrightserif",+ '\u{F6DA}' => "registerserif",+ '\u{F6DB}' => "trademarkserif",+ '\u{F6DC}' => "onefitted",+ '\u{F6DD}' => "rupiah",+ '\u{F6DE}' => "threequartersemdash",+ '\u{F6DF}' => "centinferior",+ '\u{F6E0}' => "centsuperior",+ '\u{F6E1}' => "commainferior",+ '\u{F6E2}' => "commasuperior",+ '\u{F6E3}' => "dollarinferior",+ '\u{F6E4}' => "dollarsuperior",+ '\u{F6E5}' => "hypheninferior",+ '\u{F6E6}' => "hyphensuperior",+ '\u{F6E7}' => "periodinferior",+ '\u{F6E8}' => "periodsuperior",+ '\u{F6E9}' => "asuperior",+ '\u{F6EA}' => "bsuperior",+ '\u{F6EB}' => "dsuperior",+ '\u{F6EC}' => "esuperior",+ '\u{F6ED}' => "isuperior",+ '\u{F6EE}' => "lsuperior",+ '\u{F6EF}' => "msuperior",+ '\u{F6F0}' => "osuperior",+ '\u{F6F1}' => "rsuperior",+ '\u{F6F2}' => "ssuperior",+ '\u{F6F3}' => "tsuperior",+ '\u{F6F4}' => "Brevesmall",+ '\u{F6F5}' => "Caronsmall",+ '\u{F6F6}' => "Circumflexsmall",+ '\u{F6F7}' => "Dotaccentsmall",+ '\u{F6F8}' => "Hungarumlautsmall",+ '\u{F6F9}' => "Lslashsmall",+ '\u{F6FA}' => "OEsmall",+ '\u{F6FB}' => "Ogoneksmall",+ '\u{F6FC}' => "Ringsmall",+ '\u{F6FD}' => "Scaronsmall",+ '\u{F6FE}' => "Tildesmall",+ '\u{F6FF}' => "Zcaronsmall",+ '\u{F721}' => "exclamsmall",+ '\u{F724}' => "dollaroldstyle",+ '\u{F726}' => "ampersandsmall",+ '\u{F730}' => "zerooldstyle",+ '\u{F731}' => "oneoldstyle",+ '\u{F732}' => "twooldstyle",+ '\u{F733}' => "threeoldstyle",+ '\u{F734}' => "fouroldstyle",+ '\u{F735}' => "fiveoldstyle",+ '\u{F736}' => "sixoldstyle",+ '\u{F737}' => "sevenoldstyle",+ '\u{F738}' => "eightoldstyle",+ '\u{F739}' => "nineoldstyle",+ '\u{F73F}' => "questionsmall",+ '\u{F760}' => "Gravesmall",+ '\u{F761}' => "Asmall",+ '\u{F762}' => "Bsmall",+ '\u{F763}' => "Csmall",+ '\u{F764}' => "Dsmall",+ '\u{F765}' => "Esmall",+ '\u{F766}' => "Fsmall",+ '\u{F767}' => "Gsmall",+ '\u{F768}' => "Hsmall",+ '\u{F769}' => "Ismall",+ '\u{F76A}' => "Jsmall",+ '\u{F76B}' => "Ksmall",+ '\u{F76C}' => "Lsmall",+ '\u{F76D}' => "Msmall",+ '\u{F76E}' => "Nsmall",+ '\u{F76F}' => "Osmall",+ '\u{F770}' => "Psmall",+ '\u{F771}' => "Qsmall",+ '\u{F772}' => "Rsmall",+ '\u{F773}' => "Ssmall",+ '\u{F774}' => "Tsmall",+ '\u{F775}' => "Usmall",+ '\u{F776}' => "Vsmall",+ '\u{F777}' => "Wsmall",+ '\u{F778}' => "Xsmall",+ '\u{F779}' => "Ysmall",+ '\u{F77A}' => "Zsmall",+ '\u{F7A1}' => "exclamdownsmall",+ '\u{F7A2}' => "centoldstyle",+ '\u{F7A8}' => "Dieresissmall",+ '\u{F7AF}' => "Macronsmall",+ '\u{F7B4}' => "Acutesmall",+ '\u{F7B8}' => "Cedillasmall",+ '\u{F7BF}' => "questiondownsmall",+ '\u{F7E0}' => "Agravesmall",+ '\u{F7E1}' => "Aacutesmall",+ '\u{F7E2}' => "Acircumflexsmall",+ '\u{F7E3}' => "Atildesmall",+ '\u{F7E4}' => "Adieresissmall",+ '\u{F7E5}' => "Aringsmall",+ '\u{F7E6}' => "AEsmall",+ '\u{F7E7}' => "Ccedillasmall",+ '\u{F7E8}' => "Egravesmall",+ '\u{F7E9}' => "Eacutesmall",+ '\u{F7EA}' => "Ecircumflexsmall",+ '\u{F7EB}' => "Edieresissmall",+ '\u{F7EC}' => "Igravesmall",+ '\u{F7ED}' => "Iacutesmall",+ '\u{F7EE}' => "Icircumflexsmall",+ '\u{F7EF}' => "Idieresissmall",+ '\u{F7F0}' => "Ethsmall",+ '\u{F7F1}' => "Ntildesmall",+ '\u{F7F2}' => "Ogravesmall",+ '\u{F7F3}' => "Oacutesmall",+ '\u{F7F4}' => "Ocircumflexsmall",+ '\u{F7F5}' => "Otildesmall",+ '\u{F7F6}' => "Odieresissmall",+ '\u{F7F8}' => "Oslashsmall",+ '\u{F7F9}' => "Ugravesmall",+ '\u{F7FA}' => "Uacutesmall",+ '\u{F7FB}' => "Ucircumflexsmall",+ '\u{F7FC}' => "Udieresissmall",+ '\u{F7FD}' => "Yacutesmall",+ '\u{F7FE}' => "Thornsmall",+ '\u{F7FF}' => "Ydieresissmall",+ '\u{F884}' => "maihanakatleftthai",+ '\u{F885}' => "saraileftthai",+ '\u{F886}' => "saraiileftthai",+ '\u{F887}' => "saraueleftthai",+ '\u{F888}' => "saraueeleftthai",+ '\u{F889}' => "maitaikhuleftthai",+ '\u{F88A}' => "maiekupperleftthai",+ '\u{F88B}' => "maieklowrightthai",+ '\u{F88C}' => "maieklowleftthai",+ '\u{F88D}' => "maithoupperleftthai",+ '\u{F88E}' => "maitholowrightthai",+ '\u{F88F}' => "maitholowleftthai",+ '\u{F890}' => "maitriupperleftthai",+ '\u{F891}' => "maitrilowrightthai",+ '\u{F892}' => "maitrilowleftthai",+ '\u{F893}' => "maichattawaupperleftthai",+ '\u{F894}' => "maichattawalowrightthai",+ '\u{F895}' => "maichattawalowleftthai",+ '\u{F896}' => "thanthakhatupperleftthai",+ '\u{F897}' => "thanthakhatlowrightthai",+ '\u{F898}' => "thanthakhatlowleftthai",+ '\u{F899}' => "nikhahitleftthai",+ '\u{F8E5}' => "radicalex",+ '\u{F8E6}' => "arrowvertex",+ '\u{F8E7}' => "arrowhorizex",+ '\u{F8E8}' => "registersans",+ '\u{F8E9}' => "copyrightsans",+ '\u{F8EA}' => "trademarksans",+ '\u{F8EB}' => "parenlefttp",+ '\u{F8EC}' => "parenleftex",+ '\u{F8ED}' => "parenleftbt",+ '\u{F8EE}' => "bracketlefttp",+ '\u{F8EF}' => "bracketleftex",+ '\u{F8F0}' => "bracketleftbt",+ '\u{F8F1}' => "bracelefttp",+ '\u{F8F2}' => "braceleftmid",+ '\u{F8F3}' => "braceleftbt",+ '\u{F8F4}' => "braceex",+ '\u{F8F5}' => "integralex",+ '\u{F8F6}' => "parenrighttp",+ '\u{F8F7}' => "parenrightex",+ '\u{F8F8}' => "parenrightbt",+ '\u{F8F9}' => "bracketrighttp",+ '\u{F8FA}' => "bracketrightex",+ '\u{F8FB}' => "bracketrightbt",+ '\u{F8FC}' => "bracerighttp",+ '\u{F8FD}' => "bracerightmid",+ '\u{F8FE}' => "bracerightbt",+ '\u{F8FF}' => "apple",+ '\u{FB00}' => "ff",+ '\u{FB01}' => "fi",+ '\u{FB02}' => "fl",+ '\u{FB03}' => "ffi",+ '\u{FB04}' => "ffl",+ '\u{FB1F}' => "afii57705",+ '\u{FB20}' => "ayinaltonehebrew",+ '\u{FB2A}' => "afii57694",+ '\u{FB2B}' => "afii57695",+ '\u{FB2C}' => "shindageshshindot",+ '\u{FB2D}' => "shindageshsindot",+ '\u{FB2E}' => "alefpatahhebrew",+ '\u{FB2F}' => "alefqamatshebrew",+ '\u{FB30}' => "alefdageshhebrew",+ '\u{FB31}' => "betdagesh",+ '\u{FB32}' => "gimeldagesh",+ '\u{FB33}' => "daletdagesh",+ '\u{FB34}' => "hedagesh",+ '\u{FB35}' => "afii57723",+ '\u{FB36}' => "zayindagesh",+ '\u{FB38}' => "tetdagesh",+ '\u{FB39}' => "yoddagesh",+ '\u{FB3A}' => "finalkafdagesh",+ '\u{FB3B}' => "kafdagesh",+ '\u{FB3C}' => "lameddagesh",+ '\u{FB3E}' => "memdagesh",+ '\u{FB40}' => "nundagesh",+ '\u{FB41}' => "samekhdagesh",+ '\u{FB43}' => "pefinaldageshhebrew",+ '\u{FB44}' => "pedagesh",+ '\u{FB46}' => "tsadidagesh",+ '\u{FB47}' => "qofdagesh",+ '\u{FB48}' => "reshdageshhebrew",+ '\u{FB49}' => "shindagesh",+ '\u{FB4A}' => "tavdages",+ '\u{FB4B}' => "afii57700",+ '\u{FB4C}' => "betrafehebrew",+ '\u{FB4D}' => "kafrafehebrew",+ '\u{FB4E}' => "perafehebrew",+ '\u{FB4F}' => "aleflamedhebrew",+ '\u{FB57}' => "pehfinalarabic",+ '\u{FB58}' => "pehinitialarabic",+ '\u{FB59}' => "pehmedialarabic",+ '\u{FB67}' => "ttehfinalarabic",+ '\u{FB68}' => "ttehinitialarabic",+ '\u{FB69}' => "ttehmedialarabic",+ '\u{FB6B}' => "vehfinalarabic",+ '\u{FB6C}' => "vehinitialarabic",+ '\u{FB6D}' => "vehmedialarabic",+ '\u{FB7B}' => "tchehfinalarabic",+ '\u{FB7C}' => "tchehinitialarabic",+ '\u{FB7D}' => "tchehmedialarabic",+ '\u{FB89}' => "ddalfinalarabic",+ '\u{FB8B}' => "jehfinalarabic",+ '\u{FB8D}' => "rrehfinalarabic",+ '\u{FB93}' => "gaffinalarabic",+ '\u{FB94}' => "gafinitialarabic",+ '\u{FB95}' => "gafmedialarabic",+ '\u{FB9F}' => "noonghunnafinalarabic",+ '\u{FBA4}' => "hehhamzaaboveisolatedarabic",+ '\u{FBA5}' => "hehhamzaabovefinalarabic",+ '\u{FBA7}' => "hehfinalaltonearabic",+ '\u{FBA8}' => "hehinitialaltonearabic",+ '\u{FBA9}' => "hehmedialaltonearabic",+ '\u{FBAF}' => "yehbarreefinalarabic",+ '\u{FC08}' => "behmeemisolatedarabic",+ '\u{FC0B}' => "tehjeemisolatedarabic",+ '\u{FC0C}' => "tehhahisolatedarabic",+ '\u{FC0E}' => "tehmeemisolatedarabic",+ '\u{FC48}' => "meemmeemisolatedarabic",+ '\u{FC4B}' => "noonjeemisolatedarabic",+ '\u{FC4E}' => "noonmeemisolatedarabic",+ '\u{FC58}' => "yehmeemisolatedarabic",+ '\u{FC5E}' => "shaddadammatanarabic",+ '\u{FC5F}' => "shaddakasratanarabic",+ '\u{FC60}' => "shaddafathaarabic",+ '\u{FC61}' => "shaddadammaarabic",+ '\u{FC62}' => "shaddakasraarabic",+ '\u{FC6D}' => "behnoonfinalarabic",+ '\u{FC73}' => "tehnoonfinalarabic",+ '\u{FC8D}' => "noonnoonfinalarabic",+ '\u{FC94}' => "yehnoonfinalarabic",+ '\u{FC9F}' => "behmeeminitialarabic",+ '\u{FCA1}' => "tehjeeminitialarabic",+ '\u{FCA2}' => "tehhahinitialarabic",+ '\u{FCA4}' => "tehmeeminitialarabic",+ '\u{FCC9}' => "lamjeeminitialarabic",+ '\u{FCCA}' => "lamhahinitialarabic",+ '\u{FCCB}' => "lamkhahinitialarabic",+ '\u{FCCC}' => "lammeeminitialarabic",+ '\u{FCD1}' => "meemmeeminitialarabic",+ '\u{FCD2}' => "noonjeeminitialarabic",+ '\u{FCD5}' => "noonmeeminitialarabic",+ '\u{FCDD}' => "yehmeeminitialarabic",+ '\u{FD3E}' => "parenleftaltonearabic",+ '\u{FD3F}' => "parenrightaltonearabic",+ '\u{FD88}' => "lammeemhahinitialarabic",+ '\u{FDF2}' => "lamlamhehisolatedarabic",+ '\u{FDFA}' => "sallallahoualayhewasallamarabic",+ '\u{FE30}' => "twodotleadervertical",+ '\u{FE31}' => "emdashvertical",+ '\u{FE32}' => "endashvertical",+ '\u{FE33}' => "underscorevertical",+ '\u{FE34}' => "wavyunderscorevertical",+ '\u{FE35}' => "parenleftvertical",+ '\u{FE36}' => "parenrightvertical",+ '\u{FE37}' => "braceleftvertical",+ '\u{FE38}' => "bracerightvertical",+ '\u{FE39}' => "tortoiseshellbracketleftvertical",+ '\u{FE3A}' => "tortoiseshellbracketrightvertical",+ '\u{FE3B}' => "blacklenticularbracketleftvertical",+ '\u{FE3C}' => "blacklenticularbracketrightvertical",+ '\u{FE3D}' => "dblanglebracketleftvertical",+ '\u{FE3E}' => "dblanglebracketrightvertical",+ '\u{FE3F}' => "anglebracketleftvertical",+ '\u{FE40}' => "anglebracketrightvertical",+ '\u{FE41}' => "cornerbracketleftvertical",+ '\u{FE42}' => "cornerbracketrightvertical",+ '\u{FE43}' => "whitecornerbracketleftvertical",+ '\u{FE44}' => "whitecornerbracketrightvertical",+ '\u{FE49}' => "overlinedashed",+ '\u{FE4A}' => "overlinecenterline",+ '\u{FE4B}' => "overlinewavy",+ '\u{FE4C}' => "overlinedblwavy",+ '\u{FE4D}' => "lowlinedashed",+ '\u{FE4E}' => "lowlinecenterline",+ '\u{FE4F}' => "underscorewavy",+ '\u{FE50}' => "commasmall",+ '\u{FE52}' => "periodsmall",+ '\u{FE54}' => "semicolonsmall",+ '\u{FE55}' => "colonsmall",+ '\u{FE59}' => "parenleftsmall",+ '\u{FE5A}' => "parenrightsmall",+ '\u{FE5B}' => "braceleftsmall",+ '\u{FE5C}' => "bracerightsmall",+ '\u{FE5D}' => "tortoiseshellbracketleftsmall",+ '\u{FE5E}' => "tortoiseshellbracketrightsmall",+ '\u{FE5F}' => "numbersignsmall",+ '\u{FE61}' => "asterisksmall",+ '\u{FE62}' => "plussmall",+ '\u{FE63}' => "hyphensmall",+ '\u{FE64}' => "lesssmall",+ '\u{FE65}' => "greatersmall",+ '\u{FE66}' => "equalsmall",+ '\u{FE69}' => "dollarsmall",+ '\u{FE6A}' => "percentsmall",+ '\u{FE6B}' => "atsmall",+ '\u{FE82}' => "alefmaddaabovefinalarabic",+ '\u{FE84}' => "alefhamzaabovefinalarabic",+ '\u{FE86}' => "wawhamzaabovefinalarabic",+ '\u{FE88}' => "alefhamzabelowfinalarabic",+ '\u{FE8A}' => "yehhamzaabovefinalarabic",+ '\u{FE8B}' => "yehhamzaaboveinitialarabic",+ '\u{FE8C}' => "yehhamzaabovemedialarabic",+ '\u{FE8E}' => "aleffinalarabic",+ '\u{FE90}' => "behfinalarabic",+ '\u{FE91}' => "behinitialarabic",+ '\u{FE92}' => "behmedialarabic",+ '\u{FE94}' => "tehmarbutafinalarabic",+ '\u{FE96}' => "tehfinalarabic",+ '\u{FE97}' => "tehinitialarabic",+ '\u{FE98}' => "tehmedialarabic",+ '\u{FE9A}' => "thehfinalarabic",+ '\u{FE9B}' => "thehinitialarabic",+ '\u{FE9C}' => "thehmedialarabic",+ '\u{FE9E}' => "jeemfinalarabic",+ '\u{FE9F}' => "jeeminitialarabic",+ '\u{FEA0}' => "jeemmedialarabic",+ '\u{FEA2}' => "hahfinalarabic",+ '\u{FEA3}' => "hahinitialarabic",+ '\u{FEA4}' => "hahmedialarabic",+ '\u{FEA6}' => "khahfinalarabic",+ '\u{FEA7}' => "khahinitialarabic",+ '\u{FEA8}' => "khahmedialarabic",+ '\u{FEAA}' => "dalfinalarabic",+ '\u{FEAC}' => "thalfinalarabic",+ '\u{FEAE}' => "rehfinalarabic",+ '\u{FEB0}' => "zainfinalarabic",+ '\u{FEB2}' => "seenfinalarabic",+ '\u{FEB3}' => "seeninitialarabic",+ '\u{FEB4}' => "seenmedialarabic",+ '\u{FEB6}' => "sheenfinalarabic",+ '\u{FEB7}' => "sheeninitialarabic",+ '\u{FEB8}' => "sheenmedialarabic",+ '\u{FEBA}' => "sadfinalarabic",+ '\u{FEBB}' => "sadinitialarabic",+ '\u{FEBC}' => "sadmedialarabic",+ '\u{FEBE}' => "dadfinalarabic",+ '\u{FEBF}' => "dadinitialarabic",+ '\u{FEC0}' => "dadmedialarabic",+ '\u{FEC2}' => "tahfinalarabic",+ '\u{FEC3}' => "tahinitialarabic",+ '\u{FEC4}' => "tahmedialarabic",+ '\u{FEC6}' => "zahfinalarabic",+ '\u{FEC7}' => "zahinitialarabic",+ '\u{FEC8}' => "zahmedialarabic",+ '\u{FECA}' => "ainfinalarabic",+ '\u{FECB}' => "aininitialarabic",+ '\u{FECC}' => "ainmedialarabic",+ '\u{FECE}' => "ghainfinalarabic",+ '\u{FECF}' => "ghaininitialarabic",+ '\u{FED0}' => "ghainmedialarabic",+ '\u{FED2}' => "fehfinalarabic",+ '\u{FED3}' => "fehinitialarabic",+ '\u{FED4}' => "fehmedialarabic",+ '\u{FED6}' => "qaffinalarabic",+ '\u{FED7}' => "qafinitialarabic",+ '\u{FED8}' => "qafmedialarabic",+ '\u{FEDA}' => "kaffinalarabic",+ '\u{FEDB}' => "kafinitialarabic",+ '\u{FEDC}' => "kafmedialarabic",+ '\u{FEDE}' => "lamfinalarabic",+ '\u{FEDF}' => "laminitialarabic",+ '\u{FEE0}' => "lammedialarabic",+ '\u{FEE2}' => "meemfinalarabic",+ '\u{FEE3}' => "meeminitialarabic",+ '\u{FEE4}' => "meemmedialarabic",+ '\u{FEE6}' => "noonfinalarabic",+ '\u{FEE7}' => "nooninitialarabic",+ '\u{FEE8}' => "noonmedialarabic",+ '\u{FEEA}' => "hehfinalalttwoarabic",+ '\u{FEEB}' => "hehinitialarabic",+ '\u{FEEC}' => "hehmedialarabic",+ '\u{FEEE}' => "wawfinalarabic",+ '\u{FEF0}' => "alefmaksurafinalarabic",+ '\u{FEF2}' => "yehfinalarabic",+ '\u{FEF3}' => "alefmaksurainitialarabic",+ '\u{FEF4}' => "alefmaksuramedialarabic",+ '\u{FEF5}' => "lamalefmaddaaboveisolatedarabic",+ '\u{FEF6}' => "lamalefmaddaabovefinalarabic",+ '\u{FEF7}' => "lamalefhamzaaboveisolatedarabic",+ '\u{FEF8}' => "lamalefhamzaabovefinalarabic",+ '\u{FEF9}' => "lamalefhamzabelowisolatedarabic",+ '\u{FEFA}' => "lamalefhamzabelowfinalarabic",+ '\u{FEFB}' => "lamalefisolatedarabic",+ '\u{FEFC}' => "lamaleffinalarabic",+ '\u{FEFF}' => "zerowidthjoiner",+ '\u{FF01}' => "exclammonospace",+ '\u{FF02}' => "quotedblmonospace",+ '\u{FF03}' => "numbersignmonospace",+ '\u{FF04}' => "dollarmonospace",+ '\u{FF05}' => "percentmonospace",+ '\u{FF06}' => "ampersandmonospace",+ '\u{FF07}' => "quotesinglemonospace",+ '\u{FF08}' => "parenleftmonospace",+ '\u{FF09}' => "parenrightmonospace",+ '\u{FF0A}' => "asteriskmonospace",+ '\u{FF0B}' => "plusmonospace",+ '\u{FF0C}' => "commamonospace",+ '\u{FF0D}' => "hyphenmonospace",+ '\u{FF0E}' => "periodmonospace",+ '\u{FF0F}' => "slashmonospace",+ '\u{FF10}' => "zeromonospace",+ '\u{FF11}' => "onemonospace",+ '\u{FF12}' => "twomonospace",+ '\u{FF13}' => "threemonospace",+ '\u{FF14}' => "fourmonospace",+ '\u{FF15}' => "fivemonospace",+ '\u{FF16}' => "sixmonospace",+ '\u{FF17}' => "sevenmonospace",+ '\u{FF18}' => "eightmonospace",+ '\u{FF19}' => "ninemonospace",+ '\u{FF1A}' => "colonmonospace",+ '\u{FF1B}' => "semicolonmonospace",+ '\u{FF1C}' => "lessmonospace",+ '\u{FF1D}' => "equalmonospace",+ '\u{FF1E}' => "greatermonospace",+ '\u{FF1F}' => "questionmonospace",+ '\u{FF20}' => "atmonospace",+ '\u{FF21}' => "Amonospace",+ '\u{FF22}' => "Bmonospace",+ '\u{FF23}' => "Cmonospace",+ '\u{FF24}' => "Dmonospace",+ '\u{FF25}' => "Emonospace",+ '\u{FF26}' => "Fmonospace",+ '\u{FF27}' => "Gmonospace",+ '\u{FF28}' => "Hmonospace",+ '\u{FF29}' => "Imonospace",+ '\u{FF2A}' => "Jmonospace",+ '\u{FF2B}' => "Kmonospace",+ '\u{FF2C}' => "Lmonospace",+ '\u{FF2D}' => "Mmonospace",+ '\u{FF2E}' => "Nmonospace",+ '\u{FF2F}' => "Omonospace",+ '\u{FF30}' => "Pmonospace",+ '\u{FF31}' => "Qmonospace",+ '\u{FF32}' => "Rmonospace",+ '\u{FF33}' => "Smonospace",+ '\u{FF34}' => "Tmonospace",+ '\u{FF35}' => "Umonospace",+ '\u{FF36}' => "Vmonospace",+ '\u{FF37}' => "Wmonospace",+ '\u{FF38}' => "Xmonospace",+ '\u{FF39}' => "Ymonospace",+ '\u{FF3A}' => "Zmonospace",+ '\u{FF3B}' => "bracketleftmonospace",+ '\u{FF3C}' => "backslashmonospace",+ '\u{FF3D}' => "bracketrightmonospace",+ '\u{FF3E}' => "asciicircummonospace",+ '\u{FF3F}' => "underscoremonospace",+ '\u{FF40}' => "gravemonospace",+ '\u{FF41}' => "amonospace",+ '\u{FF42}' => "bmonospace",+ '\u{FF43}' => "cmonospace",+ '\u{FF44}' => "dmonospace",+ '\u{FF45}' => "emonospace",+ '\u{FF46}' => "fmonospace",+ '\u{FF47}' => "gmonospace",+ '\u{FF48}' => "hmonospace",+ '\u{FF49}' => "imonospace",+ '\u{FF4A}' => "jmonospace",+ '\u{FF4B}' => "kmonospace",+ '\u{FF4C}' => "lmonospace",+ '\u{FF4D}' => "mmonospace",+ '\u{FF4E}' => "nmonospace",+ '\u{FF4F}' => "omonospace",+ '\u{FF50}' => "pmonospace",+ '\u{FF51}' => "qmonospace",+ '\u{FF52}' => "rmonospace",+ '\u{FF53}' => "smonospace",+ '\u{FF54}' => "tmonospace",+ '\u{FF55}' => "umonospace",+ '\u{FF56}' => "vmonospace",+ '\u{FF57}' => "wmonospace",+ '\u{FF58}' => "xmonospace",+ '\u{FF59}' => "ymonospace",+ '\u{FF5A}' => "zmonospace",+ '\u{FF5B}' => "braceleftmonospace",+ '\u{FF5C}' => "barmonospace",+ '\u{FF5D}' => "bracerightmonospace",+ '\u{FF5E}' => "asciitildemonospace",+ '\u{FF61}' => "periodhalfwidth",+ '\u{FF62}' => "cornerbracketlefthalfwidth",+ '\u{FF63}' => "cornerbracketrighthalfwidth",+ '\u{FF64}' => "ideographiccommaleft",+ '\u{FF65}' => "middledotkatakanahalfwidth",+ '\u{FF66}' => "wokatakanahalfwidth",+ '\u{FF67}' => "asmallkatakanahalfwidth",+ '\u{FF68}' => "ismallkatakanahalfwidth",+ '\u{FF69}' => "usmallkatakanahalfwidth",+ '\u{FF6A}' => "esmallkatakanahalfwidth",+ '\u{FF6B}' => "osmallkatakanahalfwidth",+ '\u{FF6C}' => "yasmallkatakanahalfwidth",+ '\u{FF6D}' => "yusmallkatakanahalfwidth",+ '\u{FF6E}' => "yosmallkatakanahalfwidth",+ '\u{FF6F}' => "tusmallkatakanahalfwidth",+ '\u{FF70}' => "katahiraprolongmarkhalfwidth",+ '\u{FF71}' => "akatakanahalfwidth",+ '\u{FF72}' => "ikatakanahalfwidth",+ '\u{FF73}' => "ukatakanahalfwidth",+ '\u{FF74}' => "ekatakanahalfwidth",+ '\u{FF75}' => "okatakanahalfwidth",+ '\u{FF76}' => "kakatakanahalfwidth",+ '\u{FF77}' => "kikatakanahalfwidth",+ '\u{FF78}' => "kukatakanahalfwidth",+ '\u{FF79}' => "kekatakanahalfwidth",+ '\u{FF7A}' => "kokatakanahalfwidth",+ '\u{FF7B}' => "sakatakanahalfwidth",+ '\u{FF7C}' => "sikatakanahalfwidth",+ '\u{FF7D}' => "sukatakanahalfwidth",+ '\u{FF7E}' => "sekatakanahalfwidth",+ '\u{FF7F}' => "sokatakanahalfwidth",+ '\u{FF80}' => "takatakanahalfwidth",+ '\u{FF81}' => "tikatakanahalfwidth",+ '\u{FF82}' => "tukatakanahalfwidth",+ '\u{FF83}' => "tekatakanahalfwidth",+ '\u{FF84}' => "tokatakanahalfwidth",+ '\u{FF85}' => "nakatakanahalfwidth",+ '\u{FF86}' => "nikatakanahalfwidth",+ '\u{FF87}' => "nukatakanahalfwidth",+ '\u{FF88}' => "nekatakanahalfwidth",+ '\u{FF89}' => "nokatakanahalfwidth",+ '\u{FF8A}' => "hakatakanahalfwidth",+ '\u{FF8B}' => "hikatakanahalfwidth",+ '\u{FF8C}' => "hukatakanahalfwidth",+ '\u{FF8D}' => "hekatakanahalfwidth",+ '\u{FF8E}' => "hokatakanahalfwidth",+ '\u{FF8F}' => "makatakanahalfwidth",+ '\u{FF90}' => "mikatakanahalfwidth",+ '\u{FF91}' => "mukatakanahalfwidth",+ '\u{FF92}' => "mekatakanahalfwidth",+ '\u{FF93}' => "mokatakanahalfwidth",+ '\u{FF94}' => "yakatakanahalfwidth",+ '\u{FF95}' => "yukatakanahalfwidth",+ '\u{FF96}' => "yokatakanahalfwidth",+ '\u{FF97}' => "rakatakanahalfwidth",+ '\u{FF98}' => "rikatakanahalfwidth",+ '\u{FF99}' => "rukatakanahalfwidth",+ '\u{FF9A}' => "rekatakanahalfwidth",+ '\u{FF9B}' => "rokatakanahalfwidth",+ '\u{FF9C}' => "wakatakanahalfwidth",+ '\u{FF9D}' => "nkatakanahalfwidth",+ '\u{FF9E}' => "voicedmarkkanahalfwidth",+ '\u{FF9F}' => "semivoicedmarkkanahalfwidth",+ '\u{FFE0}' => "centmonospace",+ '\u{FFE1}' => "sterlingmonospace",+ '\u{FFE3}' => "macronmonospace",+ '\u{FFE5}' => "yenmonospace",+ '\u{FFE6}' => "wonmonospace",+};diff --git a/vendor/hayro-interpret/src/font/generated/mac_expert.rs b/vendor/hayro-interpret/src/font/generated/mac_expert.rsnew file mode 100644index 000000000..3c8971b0d--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/mac_expert.rs@@ -0,0 +1,174 @@+// See <https://github.com/apache/pdfbox/blob/4438b8fdc67a3a9ebfb194595d0e81f88b708a37/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/encoding/MacExpertEncoding.java>+use phf::phf_map;++pub(crate) fn get(code: u8) -> Option<&'static str> {+ MAC_EXPERT.get(&code).copied()+}++static MAC_EXPERT: phf::Map<u8, &'static str> = phf_map! {+ 190_u8 => "AEsmall",+ 135_u8 => "Aacutesmall",+ 137_u8 => "Acircumflexsmall",+ 39_u8 => "Acutesmall",+ 138_u8 => "Adieresissmall",+ 136_u8 => "Agravesmall",+ 140_u8 => "Aringsmall",+ 97_u8 => "Asmall",+ 139_u8 => "Atildesmall",+ 243_u8 => "Brevesmall",+ 98_u8 => "Bsmall",+ 174_u8 => "Caronsmall",+ 141_u8 => "Ccedillasmall",+ 201_u8 => "Cedillasmall",+ 94_u8 => "Circumflexsmall",+ 99_u8 => "Csmall",+ 172_u8 => "Dieresissmall",+ 250_u8 => "Dotaccentsmall",+ 100_u8 => "Dsmall",+ 142_u8 => "Eacutesmall",+ 144_u8 => "Ecircumflexsmall",+ 145_u8 => "Edieresissmall",+ 143_u8 => "Egravesmall",+ 101_u8 => "Esmall",+ 68_u8 => "Ethsmall",+ 102_u8 => "Fsmall",+ 96_u8 => "Gravesmall",+ 103_u8 => "Gsmall",+ 104_u8 => "Hsmall",+ 34_u8 => "Hungarumlautsmall",+ 146_u8 => "Iacutesmall",+ 148_u8 => "Icircumflexsmall",+ 149_u8 => "Idieresissmall",+ 147_u8 => "Igravesmall",+ 105_u8 => "Ismall",+ 106_u8 => "Jsmall",+ 107_u8 => "Ksmall",+ 194_u8 => "Lslashsmall",+ 108_u8 => "Lsmall",+ 244_u8 => "Macronsmall",+ 109_u8 => "Msmall",+ 110_u8 => "Nsmall",+ 150_u8 => "Ntildesmall",+ 207_u8 => "OEsmall",+ 151_u8 => "Oacutesmall",+ 153_u8 => "Ocircumflexsmall",+ 154_u8 => "Odieresissmall",+ 242_u8 => "Ogoneksmall",+ 152_u8 => "Ogravesmall",+ 191_u8 => "Oslashsmall",+ 111_u8 => "Osmall",+ 155_u8 => "Otildesmall",+ 112_u8 => "Psmall",+ 113_u8 => "Qsmall",+ 251_u8 => "Ringsmall",+ 114_u8 => "Rsmall",+ 167_u8 => "Scaronsmall",+ 115_u8 => "Ssmall",+ 185_u8 => "Thornsmall",+ 126_u8 => "Tildesmall",+ 116_u8 => "Tsmall",+ 156_u8 => "Uacutesmall",+ 158_u8 => "Ucircumflexsmall",+ 159_u8 => "Udieresissmall",+ 157_u8 => "Ugravesmall",+ 117_u8 => "Usmall",+ 118_u8 => "Vsmall",+ 119_u8 => "Wsmall",+ 120_u8 => "Xsmall",+ 180_u8 => "Yacutesmall",+ 216_u8 => "Ydieresissmall",+ 121_u8 => "Ysmall",+ 189_u8 => "Zcaronsmall",+ 122_u8 => "Zsmall",+ 38_u8 => "ampersandsmall",+ 129_u8 => "asuperior",+ 245_u8 => "bsuperior",+ 169_u8 => "centinferior",+ 35_u8 => "centoldstyle",+ 130_u8 => "centsuperior",+ 58_u8 => "colon",+ 123_u8 => "colonmonetary",+ 44_u8 => "comma",+ 178_u8 => "commainferior",+ 248_u8 => "commasuperior",+ 182_u8 => "dollarinferior",+ 36_u8 => "dollaroldstyle",+ 37_u8 => "dollarsuperior",+ 235_u8 => "dsuperior",+ 165_u8 => "eightinferior",+ 56_u8 => "eightoldstyle",+ 161_u8 => "eightsuperior",+ 228_u8 => "esuperior",+ 214_u8 => "exclamdownsmall",+ 33_u8 => "exclamsmall",+ 86_u8 => "ff",+ 89_u8 => "ffi",+ 90_u8 => "ffl",+ 87_u8 => "fi",+ 208_u8 => "figuredash",+ 76_u8 => "fiveeighths",+ 176_u8 => "fiveinferior",+ 53_u8 => "fiveoldstyle",+ 222_u8 => "fivesuperior",+ 88_u8 => "fl",+ 162_u8 => "fourinferior",+ 52_u8 => "fouroldstyle",+ 221_u8 => "foursuperior",+ 47_u8 => "fraction",+ 45_u8 => "hyphen",+ 95_u8 => "hypheninferior",+ 209_u8 => "hyphensuperior",+ 233_u8 => "isuperior",+ 241_u8 => "lsuperior",+ 247_u8 => "msuperior",+ 187_u8 => "nineinferior",+ 57_u8 => "nineoldstyle",+ 225_u8 => "ninesuperior",+ 246_u8 => "nsuperior",+ 43_u8 => "onedotenleader",+ 74_u8 => "oneeighth",+ 124_u8 => "onefitted",+ 72_u8 => "onehalf",+ 193_u8 => "oneinferior",+ 49_u8 => "oneoldstyle",+ 71_u8 => "onequarter",+ 218_u8 => "onesuperior",+ 78_u8 => "onethird",+ 175_u8 => "osuperior",+ 91_u8 => "parenleftinferior",+ 40_u8 => "parenleftsuperior",+ 93_u8 => "parenrightinferior",+ 41_u8 => "parenrightsuperior",+ 46_u8 => "period",+ 179_u8 => "periodinferior",+ 249_u8 => "periodsuperior",+ 192_u8 => "questiondownsmall",+ 63_u8 => "questionsmall",+ 229_u8 => "rsuperior",+ 125_u8 => "rupiah",+ 59_u8 => "semicolon",+ 77_u8 => "seveneighths",+ 166_u8 => "seveninferior",+ 55_u8 => "sevenoldstyle",+ 224_u8 => "sevensuperior",+ 164_u8 => "sixinferior",+ 54_u8 => "sixoldstyle",+ 223_u8 => "sixsuperior",+ 32_u8 => "space",+ 234_u8 => "ssuperior",+ 75_u8 => "threeeighths",+ 163_u8 => "threeinferior",+ 51_u8 => "threeoldstyle",+ 73_u8 => "threequarters",+ 61_u8 => "threequartersemdash",+ 220_u8 => "threesuperior",+ 230_u8 => "tsuperior",+ 42_u8 => "twodotenleader",+ 170_u8 => "twoinferior",+ 50_u8 => "twooldstyle",+ 219_u8 => "twosuperior",+ 79_u8 => "twothirds",+ 188_u8 => "zeroinferior",+ 48_u8 => "zerooldstyle",+ 226_u8 => "zerosuperior",+};diff --git a/vendor/hayro-interpret/src/font/generated/mac_os_roman.rs b/vendor/hayro-interpret/src/font/generated/mac_os_roman.rsnew file mode 100644index 000000000..1d71ca4cb--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/mac_os_roman.rs@@ -0,0 +1,48 @@+// See <https://github.com/apache/pdfbox/blob/4438b8fdc67a3a9ebfb194595d0e81f88b708a37/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/encoding/MacOSRomanEncoding.java.java>+use phf::phf_map;++pub(crate) fn get(code: u8) -> Option<&'static str> {+ MAC_OS_ROMAN.get(&code).copied()+}++pub(crate) fn get_inverse(name: &str) -> Option<u8> {+ MAC_OS_ROMAN_INVERSE.get(name).copied()+}++static MAC_OS_ROMAN: phf::Map<u8, &'static str> = phf_map! {+ 173_u8 => "notequal",+ 176_u8 => "infinity",+ 178_u8 => "lessequal",+ 179_u8 => "greaterequal",+ 182_u8 => "partialdiff",+ 183_u8 => "summation",+ 184_u8 => "product",+ 185_u8 => "pi",+ 186_u8 => "integral",+ 189_u8 => "Omega",+ 195_u8 => "radical",+ 197_u8 => "approxequal",+ 198_u8 => "Delta",+ 215_u8 => "lozenge",+ 219_u8 => "Euro",+ 240_u8 => "apple"+};++static MAC_OS_ROMAN_INVERSE: phf::Map<&'static str, u8> = phf_map! {+ "notequal" => 0o0255_u8,+ "infinity" => 0o0260_u8,+ "lessequal" => 0o0262_u8,+ "greaterequal" => 0o0263_u8,+ "partialdiff" => 0o0266_u8,+ "summation" => 0o0267_u8,+ "product" => 0o0270_u8,+ "pi" => 0o0271_u8,+ "integral" => 0o0272_u8,+ "Omega" => 0o0275_u8,+ "radical" => 0o0303_u8,+ "approxequal" => 0o0305_u8,+ "Delta" => 0o0306_u8,+ "lozenge" => 0o0327_u8,+ "Euro" => 0o0333_u8,+ "apple" => 0o0360_u8,+};diff --git a/vendor/hayro-interpret/src/font/generated/mac_roman.rs b/vendor/hayro-interpret/src/font/generated/mac_roman.rsnew file mode 100644index 000000000..82f66da55--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/mac_roman.rs@@ -0,0 +1,432 @@+// See <https://github.com/apache/pdfbox/blob/4438b8fdc67a3a9ebfb194595d0e81f88b708a37/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/encoding/MacRomanEncoding.java>+use phf::phf_map;++pub(crate) fn get(code: u8) -> Option<&'static str> {+ MAC_ROMAN.get(&code).copied()+}++pub(crate) fn get_inverse(name: &str) -> Option<u8> {+ MAC_ROMAN_INVERSE.get(name).copied()+}++static MAC_ROMAN: phf::Map<u8, &'static str> = phf_map! {+ 65_u8 => "A",+ 174_u8 => "AE",+ 231_u8 => "Aacute",+ 229_u8 => "Acircumflex",+ 128_u8 => "Adieresis",+ 203_u8 => "Agrave",+ 129_u8 => "Aring",+ 204_u8 => "Atilde",+ 66_u8 => "B",+ 67_u8 => "C",+ 130_u8 => "Ccedilla",+ 68_u8 => "D",+ 69_u8 => "E",+ 131_u8 => "Eacute",+ 230_u8 => "Ecircumflex",+ 232_u8 => "Edieresis",+ 233_u8 => "Egrave",+ 70_u8 => "F",+ 71_u8 => "G",+ 72_u8 => "H",+ 73_u8 => "I",+ 234_u8 => "Iacute",+ 235_u8 => "Icircumflex",+ 236_u8 => "Idieresis",+ 237_u8 => "Igrave",+ 74_u8 => "J",+ 75_u8 => "K",+ 76_u8 => "L",+ 77_u8 => "M",+ 78_u8 => "N",+ 132_u8 => "Ntilde",+ 79_u8 => "O",+ 206_u8 => "OE",+ 238_u8 => "Oacute",+ 239_u8 => "Ocircumflex",+ 133_u8 => "Odieresis",+ 241_u8 => "Ograve",+ 175_u8 => "Oslash",+ 205_u8 => "Otilde",+ 80_u8 => "P",+ 81_u8 => "Q",+ 82_u8 => "R",+ 83_u8 => "S",+ 84_u8 => "T",+ 85_u8 => "U",+ 242_u8 => "Uacute",+ 243_u8 => "Ucircumflex",+ 134_u8 => "Udieresis",+ 244_u8 => "Ugrave",+ 86_u8 => "V",+ 87_u8 => "W",+ 88_u8 => "X",+ 89_u8 => "Y",+ 217_u8 => "Ydieresis",+ 90_u8 => "Z",+ 97_u8 => "a",+ 135_u8 => "aacute",+ 137_u8 => "acircumflex",+ 171_u8 => "acute",+ 138_u8 => "adieresis",+ 190_u8 => "ae",+ 136_u8 => "agrave",+ 38_u8 => "ampersand",+ 140_u8 => "aring",+ 94_u8 => "asciicircum",+ 126_u8 => "asciitilde",+ 42_u8 => "asterisk",+ 64_u8 => "at",+ 139_u8 => "atilde",+ 98_u8 => "b",+ 92_u8 => "backslash",+ 124_u8 => "bar",+ 123_u8 => "braceleft",+ 125_u8 => "braceright",+ 91_u8 => "bracketleft",+ 93_u8 => "bracketright",+ 249_u8 => "breve",+ 165_u8 => "bullet",+ 99_u8 => "c",+ 255_u8 => "caron",+ 141_u8 => "ccedilla",+ 252_u8 => "cedilla",+ 162_u8 => "cent",+ 246_u8 => "circumflex",+ 58_u8 => "colon",+ 44_u8 => "comma",+ 169_u8 => "copyright",+ 219_u8 => "currency",+ 100_u8 => "d",+ 160_u8 => "dagger",+ 224_u8 => "daggerdbl",+ 161_u8 => "degree",+ 172_u8 => "dieresis",+ 214_u8 => "divide",+ 36_u8 => "dollar",+ 250_u8 => "dotaccent",+ 245_u8 => "dotlessi",+ 101_u8 => "e",+ 142_u8 => "eacute",+ 144_u8 => "ecircumflex",+ 145_u8 => "edieresis",+ 143_u8 => "egrave",+ 56_u8 => "eight",+ 201_u8 => "ellipsis",+ 209_u8 => "emdash",+ 208_u8 => "endash",+ 61_u8 => "equal",+ 33_u8 => "exclam",+ 193_u8 => "exclamdown",+ 102_u8 => "f",+ 222_u8 => "fi",+ 53_u8 => "five",+ 223_u8 => "fl",+ 196_u8 => "florin",+ 52_u8 => "four",+ 218_u8 => "fraction",+ 103_u8 => "g",+ 167_u8 => "germandbls",+ 96_u8 => "grave",+ 62_u8 => "greater",+ 199_u8 => "guillemotleft",+ 200_u8 => "guillemotright",+ 220_u8 => "guilsinglleft",+ 221_u8 => "guilsinglright",+ 104_u8 => "h",+ 253_u8 => "hungarumlaut",+ 45_u8 => "hyphen",+ 105_u8 => "i",+ 146_u8 => "iacute",+ 148_u8 => "icircumflex",+ 149_u8 => "idieresis",+ 147_u8 => "igrave",+ 106_u8 => "j",+ 107_u8 => "k",+ 108_u8 => "l",+ 60_u8 => "less",+ 194_u8 => "logicalnot",+ 109_u8 => "m",+ 248_u8 => "macron",+ 181_u8 => "mu",+ 110_u8 => "n",+ 57_u8 => "nine",+ 150_u8 => "ntilde",+ 35_u8 => "numbersign",+ 111_u8 => "o",+ 151_u8 => "oacute",+ 153_u8 => "ocircumflex",+ 154_u8 => "odieresis",+ 207_u8 => "oe",+ 254_u8 => "ogonek",+ 152_u8 => "ograve",+ 49_u8 => "one",+ 187_u8 => "ordfeminine",+ 188_u8 => "ordmasculine",+ 191_u8 => "oslash",+ 155_u8 => "otilde",+ 112_u8 => "p",+ 166_u8 => "paragraph",+ 40_u8 => "parenleft",+ 41_u8 => "parenright",+ 37_u8 => "percent",+ 46_u8 => "period",+ 225_u8 => "periodcentered",+ 228_u8 => "perthousand",+ 43_u8 => "plus",+ 177_u8 => "plusminus",+ 113_u8 => "q",+ 63_u8 => "question",+ 192_u8 => "questiondown",+ 34_u8 => "quotedbl",+ 227_u8 => "quotedblbase",+ 210_u8 => "quotedblleft",+ 211_u8 => "quotedblright",+ 212_u8 => "quoteleft",+ 213_u8 => "quoteright",+ 226_u8 => "quotesinglbase",+ 39_u8 => "quotesingle",+ 114_u8 => "r",+ 168_u8 => "registered",+ 251_u8 => "ring",+ 115_u8 => "s",+ 164_u8 => "section",+ 59_u8 => "semicolon",+ 55_u8 => "seven",+ 54_u8 => "six",+ 47_u8 => "slash",+ 32_u8 => "space",+ 163_u8 => "sterling",+ 116_u8 => "t",+ 51_u8 => "three",+ 247_u8 => "tilde",+ 170_u8 => "trademark",+ 50_u8 => "two",+ 117_u8 => "u",+ 156_u8 => "uacute",+ 158_u8 => "ucircumflex",+ 159_u8 => "udieresis",+ 157_u8 => "ugrave",+ 95_u8 => "underscore",+ 118_u8 => "v",+ 119_u8 => "w",+ 120_u8 => "x",+ 121_u8 => "y",+ 216_u8 => "ydieresis",+ 180_u8 => "yen",+ 122_u8 => "z",+ 48_u8 => "zero",+ 202_u8 => "nbspace",+};++static MAC_ROMAN_INVERSE: phf::Map<&'static str, u8> = phf_map! {+ "A" => 65_u8,+ "AE" => 174_u8,+ "Aacute" => 231_u8,+ "Acircumflex" => 229_u8,+ "Adieresis" => 128_u8,+ "Agrave" => 203_u8,+ "Aring" => 129_u8,+ "Atilde" => 204_u8,+ "B" => 66_u8,+ "C" => 67_u8,+ "Ccedilla" => 130_u8,+ "D" => 68_u8,+ "E" => 69_u8,+ "Eacute" => 131_u8,+ "Ecircumflex" => 230_u8,+ "Edieresis" => 232_u8,+ "Egrave" => 233_u8,+ "F" => 70_u8,+ "G" => 71_u8,+ "H" => 72_u8,+ "I" => 73_u8,+ "Iacute" => 234_u8,+ "Icircumflex" => 235_u8,+ "Idieresis" => 236_u8,+ "Igrave" => 237_u8,+ "J" => 74_u8,+ "K" => 75_u8,+ "L" => 76_u8,+ "M" => 77_u8,+ "N" => 78_u8,+ "Ntilde" => 132_u8,+ "O" => 79_u8,+ "OE" => 206_u8,+ "Oacute" => 238_u8,+ "Ocircumflex" => 239_u8,+ "Odieresis" => 133_u8,+ "Ograve" => 241_u8,+ "Oslash" => 175_u8,+ "Otilde" => 205_u8,+ "P" => 80_u8,+ "Q" => 81_u8,+ "R" => 82_u8,+ "S" => 83_u8,+ "T" => 84_u8,+ "U" => 85_u8,+ "Uacute" => 242_u8,+ "Ucircumflex" => 243_u8,+ "Udieresis" => 134_u8,+ "Ugrave" => 244_u8,+ "V" => 86_u8,+ "W" => 87_u8,+ "X" => 88_u8,+ "Y" => 89_u8,+ "Ydieresis" => 217_u8,+ "Z" => 90_u8,+ "a" => 97_u8,+ "aacute" => 135_u8,+ "acircumflex" => 137_u8,+ "acute" => 171_u8,+ "adieresis" => 138_u8,+ "ae" => 190_u8,+ "agrave" => 136_u8,+ "ampersand" => 38_u8,+ "aring" => 140_u8,+ "asciicircum" => 94_u8,+ "asciitilde" => 126_u8,+ "asterisk" => 42_u8,+ "at" => 64_u8,+ "atilde" => 139_u8,+ "b" => 98_u8,+ "backslash" => 92_u8,+ "bar" => 124_u8,+ "braceleft" => 123_u8,+ "braceright" => 125_u8,+ "bracketleft" => 91_u8,+ "bracketright" => 93_u8,+ "breve" => 249_u8,+ "bullet" => 165_u8,+ "c" => 99_u8,+ "caron" => 255_u8,+ "ccedilla" => 141_u8,+ "cedilla" => 252_u8,+ "cent" => 162_u8,+ "circumflex" => 246_u8,+ "colon" => 58_u8,+ "comma" => 44_u8,+ "copyright" => 169_u8,+ "currency" => 219_u8,+ "d" => 100_u8,+ "dagger" => 160_u8,+ "daggerdbl" => 224_u8,+ "degree" => 161_u8,+ "dieresis" => 172_u8,+ "divide" => 214_u8,+ "dollar" => 36_u8,+ "dotaccent" => 250_u8,+ "dotlessi" => 245_u8,+ "e" => 101_u8,+ "eacute" => 142_u8,+ "ecircumflex" => 144_u8,+ "edieresis" => 145_u8,+ "egrave" => 143_u8,+ "eight" => 56_u8,+ "ellipsis" => 201_u8,+ "emdash" => 209_u8,+ "endash" => 208_u8,+ "equal" => 61_u8,+ "exclam" => 33_u8,+ "exclamdown" => 193_u8,+ "f" => 102_u8,+ "fi" => 222_u8,+ "five" => 53_u8,+ "fl" => 223_u8,+ "florin" => 196_u8,+ "four" => 52_u8,+ "fraction" => 218_u8,+ "g" => 103_u8,+ "germandbls" => 167_u8,+ "grave" => 96_u8,+ "greater" => 62_u8,+ "guillemotleft" => 199_u8,+ "guillemotright" => 200_u8,+ "guilsinglleft" => 220_u8,+ "guilsinglright" => 221_u8,+ "h" => 104_u8,+ "hungarumlaut" => 253_u8,+ "hyphen" => 45_u8,+ "i" => 105_u8,+ "iacute" => 146_u8,+ "icircumflex" => 148_u8,+ "idieresis" => 149_u8,+ "igrave" => 147_u8,+ "j" => 106_u8,+ "k" => 107_u8,+ "l" => 108_u8,+ "less" => 60_u8,+ "logicalnot" => 194_u8,+ "m" => 109_u8,+ "macron" => 248_u8,+ "mu" => 181_u8,+ "n" => 110_u8,+ "nine" => 57_u8,+ "ntilde" => 150_u8,+ "numbersign" => 35_u8,+ "o" => 111_u8,+ "oacute" => 151_u8,+ "ocircumflex" => 153_u8,+ "odieresis" => 154_u8,+ "oe" => 207_u8,+ "ogonek" => 254_u8,+ "ograve" => 152_u8,+ "one" => 49_u8,+ "ordfeminine" => 187_u8,+ "ordmasculine" => 188_u8,+ "oslash" => 191_u8,+ "otilde" => 155_u8,+ "p" => 112_u8,+ "paragraph" => 166_u8,+ "parenleft" => 40_u8,+ "parenright" => 41_u8,+ "percent" => 37_u8,+ "period" => 46_u8,+ "periodcentered" => 225_u8,+ "perthousand" => 228_u8,+ "plus" => 43_u8,+ "plusminus" => 177_u8,+ "q" => 113_u8,+ "question" => 63_u8,+ "questiondown" => 192_u8,+ "quotedbl" => 34_u8,+ "quotedblbase" => 227_u8,+ "quotedblleft" => 210_u8,+ "quotedblright" => 211_u8,+ "quoteleft" => 212_u8,+ "quoteright" => 213_u8,+ "quotesinglbase" => 226_u8,+ "quotesingle" => 39_u8,+ "r" => 114_u8,+ "registered" => 168_u8,+ "ring" => 251_u8,+ "s" => 115_u8,+ "section" => 164_u8,+ "semicolon" => 59_u8,+ "seven" => 55_u8,+ "six" => 54_u8,+ "slash" => 47_u8,+ "space" => 32_u8,+ "sterling" => 163_u8,+ "t" => 116_u8,+ "three" => 51_u8,+ "tilde" => 247_u8,+ "trademark" => 170_u8,+ "two" => 50_u8,+ "u" => 117_u8,+ "uacute" => 156_u8,+ "ucircumflex" => 158_u8,+ "udieresis" => 159_u8,+ "ugrave" => 157_u8,+ "underscore" => 95_u8,+ "v" => 118_u8,+ "w" => 119_u8,+ "x" => 120_u8,+ "y" => 121_u8,+ "ydieresis" => 216_u8,+ "yen" => 180_u8,+ "z" => 122_u8,+ "zero" => 48_u8,+ "nbspace" => 202_u8,+};diff --git a/vendor/hayro-interpret/src/font/generated/metrics.rs b/vendor/hayro-interpret/src/font/generated/metrics.rsnew file mode 100644index 000000000..c9ac725ee--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/metrics.rs@@ -0,0 +1,4215 @@+use phf::phf_map;++pub(crate) static COURIER: phf::Map<&'static str, f32> = phf_map! {+ "space" => 600_f32,+ "exclam" => 600_f32,+ "quotedbl" => 600_f32,+ "numbersign" => 600_f32,+ "dollar" => 600_f32,+ "percent" => 600_f32,+ "ampersand" => 600_f32,+ "quoteright" => 600_f32,+ "parenleft" => 600_f32,+ "parenright" => 600_f32,+ "asterisk" => 600_f32,+ "plus" => 600_f32,+ "comma" => 600_f32,+ "hyphen" => 600_f32,+ "period" => 600_f32,+ "slash" => 600_f32,+ "zero" => 600_f32,+ "one" => 600_f32,+ "two" => 600_f32,+ "three" => 600_f32,+ "four" => 600_f32,+ "five" => 600_f32,+ "six" => 600_f32,+ "seven" => 600_f32,+ "eight" => 600_f32,+ "nine" => 600_f32,+ "colon" => 600_f32,+ "semicolon" => 600_f32,+ "less" => 600_f32,+ "equal" => 600_f32,+ "greater" => 600_f32,+ "question" => 600_f32,+ "at" => 600_f32,+ "A" => 600_f32,+ "B" => 600_f32,+ "C" => 600_f32,+ "D" => 600_f32,+ "E" => 600_f32,+ "F" => 600_f32,+ "G" => 600_f32,+ "H" => 600_f32,+ "I" => 600_f32,+ "J" => 600_f32,+ "K" => 600_f32,+ "L" => 600_f32,+ "M" => 600_f32,+ "N" => 600_f32,+ "O" => 600_f32,+ "P" => 600_f32,+ "Q" => 600_f32,+ "R" => 600_f32,+ "S" => 600_f32,+ "T" => 600_f32,+ "U" => 600_f32,+ "V" => 600_f32,+ "W" => 600_f32,+ "X" => 600_f32,+ "Y" => 600_f32,+ "Z" => 600_f32,+ "bracketleft" => 600_f32,+ "backslash" => 600_f32,+ "bracketright" => 600_f32,+ "asciicircum" => 600_f32,+ "underscore" => 600_f32,+ "quoteleft" => 600_f32,+ "a" => 600_f32,+ "b" => 600_f32,+ "c" => 600_f32,+ "d" => 600_f32,+ "e" => 600_f32,+ "f" => 600_f32,+ "g" => 600_f32,+ "h" => 600_f32,+ "i" => 600_f32,+ "j" => 600_f32,+ "k" => 600_f32,+ "l" => 600_f32,+ "m" => 600_f32,+ "n" => 600_f32,+ "o" => 600_f32,+ "p" => 600_f32,+ "q" => 600_f32,+ "r" => 600_f32,+ "s" => 600_f32,+ "t" => 600_f32,+ "u" => 600_f32,+ "v" => 600_f32,+ "w" => 600_f32,+ "x" => 600_f32,+ "y" => 600_f32,+ "z" => 600_f32,+ "braceleft" => 600_f32,+ "bar" => 600_f32,+ "braceright" => 600_f32,+ "asciitilde" => 600_f32,+ "exclamdown" => 600_f32,+ "cent" => 600_f32,+ "sterling" => 600_f32,+ "fraction" => 600_f32,+ "yen" => 600_f32,+ "florin" => 600_f32,+ "section" => 600_f32,+ "currency" => 600_f32,+ "quotesingle" => 600_f32,+ "quotedblleft" => 600_f32,+ "guillemotleft" => 600_f32,+ "guilsinglleft" => 600_f32,+ "guilsinglright" => 600_f32,+ "fi" => 600_f32,+ "fl" => 600_f32,+ "endash" => 600_f32,+ "dagger" => 600_f32,+ "daggerdbl" => 600_f32,+ "periodcentered" => 600_f32,+ "paragraph" => 600_f32,+ "bullet" => 600_f32,+ "quotesinglbase" => 600_f32,+ "quotedblbase" => 600_f32,+ "quotedblright" => 600_f32,+ "guillemotright" => 600_f32,+ "ellipsis" => 600_f32,+ "perthousand" => 600_f32,+ "questiondown" => 600_f32,+ "grave" => 600_f32,+ "acute" => 600_f32,+ "circumflex" => 600_f32,+ "tilde" => 600_f32,+ "macron" => 600_f32,+ "breve" => 600_f32,+ "dotaccent" => 600_f32,+ "dieresis" => 600_f32,+ "ring" => 600_f32,+ "cedilla" => 600_f32,+ "hungarumlaut" => 600_f32,+ "ogonek" => 600_f32,+ "caron" => 600_f32,+ "emdash" => 600_f32,+ "AE" => 600_f32,+ "ordfeminine" => 600_f32,+ "Lslash" => 600_f32,+ "Oslash" => 600_f32,+ "OE" => 600_f32,+ "ordmasculine" => 600_f32,+ "ae" => 600_f32,+ "dotlessi" => 600_f32,+ "lslash" => 600_f32,+ "oslash" => 600_f32,+ "oe" => 600_f32,+ "germandbls" => 600_f32,+ "Idieresis" => 600_f32,+ "eacute" => 600_f32,+ "abreve" => 600_f32,+ "uhungarumlaut" => 600_f32,+ "ecaron" => 600_f32,+ "Ydieresis" => 600_f32,+ "divide" => 600_f32,+ "Yacute" => 600_f32,+ "Acircumflex" => 600_f32,+ "aacute" => 600_f32,+ "Ucircumflex" => 600_f32,+ "yacute" => 600_f32,+ "scommaaccent" => 600_f32,+ "ecircumflex" => 600_f32,+ "Uring" => 600_f32,+ "Udieresis" => 600_f32,+ "aogonek" => 600_f32,+ "Uacute" => 600_f32,+ "uogonek" => 600_f32,+ "Edieresis" => 600_f32,+ "Dcroat" => 600_f32,+ "commaaccent" => 600_f32,+ "copyright" => 600_f32,+ "Emacron" => 600_f32,+ "ccaron" => 600_f32,+ "aring" => 600_f32,+ "Ncommaaccent" => 600_f32,+ "lacute" => 600_f32,+ "agrave" => 600_f32,+ "Tcommaaccent" => 600_f32,+ "Cacute" => 600_f32,+ "atilde" => 600_f32,+ "Edotaccent" => 600_f32,+ "scaron" => 600_f32,+ "scedilla" => 600_f32,+ "iacute" => 600_f32,+ "lozenge" => 600_f32,+ "Rcaron" => 600_f32,+ "Gcommaaccent" => 600_f32,+ "ucircumflex" => 600_f32,+ "acircumflex" => 600_f32,+ "Amacron" => 600_f32,+ "rcaron" => 600_f32,+ "ccedilla" => 600_f32,+ "Zdotaccent" => 600_f32,+ "Thorn" => 600_f32,+ "Omacron" => 600_f32,+ "Racute" => 600_f32,+ "Sacute" => 600_f32,+ "dcaron" => 600_f32,+ "Umacron" => 600_f32,+ "uring" => 600_f32,+ "threesuperior" => 600_f32,+ "Ograve" => 600_f32,+ "Agrave" => 600_f32,+ "Abreve" => 600_f32,+ "multiply" => 600_f32,+ "uacute" => 600_f32,+ "Tcaron" => 600_f32,+ "partialdiff" => 600_f32,+ "ydieresis" => 600_f32,+ "Nacute" => 600_f32,+ "icircumflex" => 600_f32,+ "Ecircumflex" => 600_f32,+ "adieresis" => 600_f32,+ "edieresis" => 600_f32,+ "cacute" => 600_f32,+ "nacute" => 600_f32,+ "umacron" => 600_f32,+ "Ncaron" => 600_f32,+ "Iacute" => 600_f32,+ "plusminus" => 600_f32,+ "brokenbar" => 600_f32,+ "registered" => 600_f32,+ "Gbreve" => 600_f32,+ "Idotaccent" => 600_f32,+ "summation" => 600_f32,+ "Egrave" => 600_f32,+ "racute" => 600_f32,+ "omacron" => 600_f32,+ "Zacute" => 600_f32,+ "Zcaron" => 600_f32,+ "greaterequal" => 600_f32,+ "Eth" => 600_f32,+ "Ccedilla" => 600_f32,+ "lcommaaccent" => 600_f32,+ "tcaron" => 600_f32,+ "eogonek" => 600_f32,+ "Uogonek" => 600_f32,+ "Aacute" => 600_f32,+ "Adieresis" => 600_f32,+ "egrave" => 600_f32,+ "zacute" => 600_f32,+ "iogonek" => 600_f32,+ "Oacute" => 600_f32,+ "oacute" => 600_f32,+ "amacron" => 600_f32,+ "sacute" => 600_f32,+ "idieresis" => 600_f32,+ "Ocircumflex" => 600_f32,+ "Ugrave" => 600_f32,+ "Delta" => 600_f32,+ "thorn" => 600_f32,+ "twosuperior" => 600_f32,+ "Odieresis" => 600_f32,+ "mu" => 600_f32,+ "igrave" => 600_f32,+ "ohungarumlaut" => 600_f32,+ "Eogonek" => 600_f32,+ "dcroat" => 600_f32,+ "threequarters" => 600_f32,+ "Scedilla" => 600_f32,+ "lcaron" => 600_f32,+ "Kcommaaccent" => 600_f32,+ "Lacute" => 600_f32,+ "trademark" => 600_f32,+ "edotaccent" => 600_f32,+ "Igrave" => 600_f32,+ "Imacron" => 600_f32,+ "Lcaron" => 600_f32,+ "onehalf" => 600_f32,+ "lessequal" => 600_f32,+ "ocircumflex" => 600_f32,+ "ntilde" => 600_f32,+ "Uhungarumlaut" => 600_f32,+ "Eacute" => 600_f32,+ "emacron" => 600_f32,+ "gbreve" => 600_f32,+ "onequarter" => 600_f32,+ "Scaron" => 600_f32,+ "Scommaaccent" => 600_f32,+ "Ohungarumlaut" => 600_f32,+ "degree" => 600_f32,+ "ograve" => 600_f32,+ "Ccaron" => 600_f32,+ "ugrave" => 600_f32,+ "radical" => 600_f32,+ "Dcaron" => 600_f32,+ "rcommaaccent" => 600_f32,+ "Ntilde" => 600_f32,+ "otilde" => 600_f32,+ "Rcommaaccent" => 600_f32,+ "Lcommaaccent" => 600_f32,+ "Atilde" => 600_f32,+ "Aogonek" => 600_f32,+ "Aring" => 600_f32,+ "Otilde" => 600_f32,+ "zdotaccent" => 600_f32,+ "Ecaron" => 600_f32,+ "Iogonek" => 600_f32,+ "kcommaaccent" => 600_f32,+ "minus" => 600_f32,+ "Icircumflex" => 600_f32,+ "ncaron" => 600_f32,+ "tcommaaccent" => 600_f32,+ "logicalnot" => 600_f32,+ "odieresis" => 600_f32,+ "udieresis" => 600_f32,+ "notequal" => 600_f32,+ "gcommaaccent" => 600_f32,+ "eth" => 600_f32,+ "zcaron" => 600_f32,+ "ncommaaccent" => 600_f32,+ "onesuperior" => 600_f32,+ "imacron" => 600_f32,+ "Euro" => 600_f32,+};++pub(crate) static COURIER_BOLD: phf::Map<&'static str, f32> = phf_map! {+ "space" => 600_f32,+ "exclam" => 600_f32,+ "quotedbl" => 600_f32,+ "numbersign" => 600_f32,+ "dollar" => 600_f32,+ "percent" => 600_f32,+ "ampersand" => 600_f32,+ "quoteright" => 600_f32,+ "parenleft" => 600_f32,+ "parenright" => 600_f32,+ "asterisk" => 600_f32,+ "plus" => 600_f32,+ "comma" => 600_f32,+ "hyphen" => 600_f32,+ "period" => 600_f32,+ "slash" => 600_f32,+ "zero" => 600_f32,+ "one" => 600_f32,+ "two" => 600_f32,+ "three" => 600_f32,+ "four" => 600_f32,+ "five" => 600_f32,+ "six" => 600_f32,+ "seven" => 600_f32,+ "eight" => 600_f32,+ "nine" => 600_f32,+ "colon" => 600_f32,+ "semicolon" => 600_f32,+ "less" => 600_f32,+ "equal" => 600_f32,+ "greater" => 600_f32,+ "question" => 600_f32,+ "at" => 600_f32,+ "A" => 600_f32,+ "B" => 600_f32,+ "C" => 600_f32,+ "D" => 600_f32,+ "E" => 600_f32,+ "F" => 600_f32,+ "G" => 600_f32,+ "H" => 600_f32,+ "I" => 600_f32,+ "J" => 600_f32,+ "K" => 600_f32,+ "L" => 600_f32,+ "M" => 600_f32,+ "N" => 600_f32,+ "O" => 600_f32,+ "P" => 600_f32,+ "Q" => 600_f32,+ "R" => 600_f32,+ "S" => 600_f32,+ "T" => 600_f32,+ "U" => 600_f32,+ "V" => 600_f32,+ "W" => 600_f32,+ "X" => 600_f32,+ "Y" => 600_f32,+ "Z" => 600_f32,+ "bracketleft" => 600_f32,+ "backslash" => 600_f32,+ "bracketright" => 600_f32,+ "asciicircum" => 600_f32,+ "underscore" => 600_f32,+ "quoteleft" => 600_f32,+ "a" => 600_f32,+ "b" => 600_f32,+ "c" => 600_f32,+ "d" => 600_f32,+ "e" => 600_f32,+ "f" => 600_f32,+ "g" => 600_f32,+ "h" => 600_f32,+ "i" => 600_f32,+ "j" => 600_f32,+ "k" => 600_f32,+ "l" => 600_f32,+ "m" => 600_f32,+ "n" => 600_f32,+ "o" => 600_f32,+ "p" => 600_f32,+ "q" => 600_f32,+ "r" => 600_f32,+ "s" => 600_f32,+ "t" => 600_f32,+ "u" => 600_f32,+ "v" => 600_f32,+ "w" => 600_f32,+ "x" => 600_f32,+ "y" => 600_f32,+ "z" => 600_f32,+ "braceleft" => 600_f32,+ "bar" => 600_f32,+ "braceright" => 600_f32,+ "asciitilde" => 600_f32,+ "exclamdown" => 600_f32,+ "cent" => 600_f32,+ "sterling" => 600_f32,+ "fraction" => 600_f32,+ "yen" => 600_f32,+ "florin" => 600_f32,+ "section" => 600_f32,+ "currency" => 600_f32,+ "quotesingle" => 600_f32,+ "quotedblleft" => 600_f32,+ "guillemotleft" => 600_f32,+ "guilsinglleft" => 600_f32,+ "guilsinglright" => 600_f32,+ "fi" => 600_f32,+ "fl" => 600_f32,+ "endash" => 600_f32,+ "dagger" => 600_f32,+ "daggerdbl" => 600_f32,+ "periodcentered" => 600_f32,+ "paragraph" => 600_f32,+ "bullet" => 600_f32,+ "quotesinglbase" => 600_f32,+ "quotedblbase" => 600_f32,+ "quotedblright" => 600_f32,+ "guillemotright" => 600_f32,+ "ellipsis" => 600_f32,+ "perthousand" => 600_f32,+ "questiondown" => 600_f32,+ "grave" => 600_f32,+ "acute" => 600_f32,+ "circumflex" => 600_f32,+ "tilde" => 600_f32,+ "macron" => 600_f32,+ "breve" => 600_f32,+ "dotaccent" => 600_f32,+ "dieresis" => 600_f32,+ "ring" => 600_f32,+ "cedilla" => 600_f32,+ "hungarumlaut" => 600_f32,+ "ogonek" => 600_f32,+ "caron" => 600_f32,+ "emdash" => 600_f32,+ "AE" => 600_f32,+ "ordfeminine" => 600_f32,+ "Lslash" => 600_f32,+ "Oslash" => 600_f32,+ "OE" => 600_f32,+ "ordmasculine" => 600_f32,+ "ae" => 600_f32,+ "dotlessi" => 600_f32,+ "lslash" => 600_f32,+ "oslash" => 600_f32,+ "oe" => 600_f32,+ "germandbls" => 600_f32,+ "Idieresis" => 600_f32,+ "eacute" => 600_f32,+ "abreve" => 600_f32,+ "uhungarumlaut" => 600_f32,+ "ecaron" => 600_f32,+ "Ydieresis" => 600_f32,+ "divide" => 600_f32,+ "Yacute" => 600_f32,+ "Acircumflex" => 600_f32,+ "aacute" => 600_f32,+ "Ucircumflex" => 600_f32,+ "yacute" => 600_f32,+ "scommaaccent" => 600_f32,+ "ecircumflex" => 600_f32,+ "Uring" => 600_f32,+ "Udieresis" => 600_f32,+ "aogonek" => 600_f32,+ "Uacute" => 600_f32,+ "uogonek" => 600_f32,+ "Edieresis" => 600_f32,+ "Dcroat" => 600_f32,+ "commaaccent" => 600_f32,+ "copyright" => 600_f32,+ "Emacron" => 600_f32,+ "ccaron" => 600_f32,+ "aring" => 600_f32,+ "Ncommaaccent" => 600_f32,+ "lacute" => 600_f32,+ "agrave" => 600_f32,+ "Tcommaaccent" => 600_f32,+ "Cacute" => 600_f32,+ "atilde" => 600_f32,+ "Edotaccent" => 600_f32,+ "scaron" => 600_f32,+ "scedilla" => 600_f32,+ "iacute" => 600_f32,+ "lozenge" => 600_f32,+ "Rcaron" => 600_f32,+ "Gcommaaccent" => 600_f32,+ "ucircumflex" => 600_f32,+ "acircumflex" => 600_f32,+ "Amacron" => 600_f32,+ "rcaron" => 600_f32,+ "ccedilla" => 600_f32,+ "Zdotaccent" => 600_f32,+ "Thorn" => 600_f32,+ "Omacron" => 600_f32,+ "Racute" => 600_f32,+ "Sacute" => 600_f32,+ "dcaron" => 600_f32,+ "Umacron" => 600_f32,+ "uring" => 600_f32,+ "threesuperior" => 600_f32,+ "Ograve" => 600_f32,+ "Agrave" => 600_f32,+ "Abreve" => 600_f32,+ "multiply" => 600_f32,+ "uacute" => 600_f32,+ "Tcaron" => 600_f32,+ "partialdiff" => 600_f32,+ "ydieresis" => 600_f32,+ "Nacute" => 600_f32,+ "icircumflex" => 600_f32,+ "Ecircumflex" => 600_f32,+ "adieresis" => 600_f32,+ "edieresis" => 600_f32,+ "cacute" => 600_f32,+ "nacute" => 600_f32,+ "umacron" => 600_f32,+ "Ncaron" => 600_f32,+ "Iacute" => 600_f32,+ "plusminus" => 600_f32,+ "brokenbar" => 600_f32,+ "registered" => 600_f32,+ "Gbreve" => 600_f32,+ "Idotaccent" => 600_f32,+ "summation" => 600_f32,+ "Egrave" => 600_f32,+ "racute" => 600_f32,+ "omacron" => 600_f32,+ "Zacute" => 600_f32,+ "Zcaron" => 600_f32,+ "greaterequal" => 600_f32,+ "Eth" => 600_f32,+ "Ccedilla" => 600_f32,+ "lcommaaccent" => 600_f32,+ "tcaron" => 600_f32,+ "eogonek" => 600_f32,+ "Uogonek" => 600_f32,+ "Aacute" => 600_f32,+ "Adieresis" => 600_f32,+ "egrave" => 600_f32,+ "zacute" => 600_f32,+ "iogonek" => 600_f32,+ "Oacute" => 600_f32,+ "oacute" => 600_f32,+ "amacron" => 600_f32,+ "sacute" => 600_f32,+ "idieresis" => 600_f32,+ "Ocircumflex" => 600_f32,+ "Ugrave" => 600_f32,+ "Delta" => 600_f32,+ "thorn" => 600_f32,+ "twosuperior" => 600_f32,+ "Odieresis" => 600_f32,+ "mu" => 600_f32,+ "igrave" => 600_f32,+ "ohungarumlaut" => 600_f32,+ "Eogonek" => 600_f32,+ "dcroat" => 600_f32,+ "threequarters" => 600_f32,+ "Scedilla" => 600_f32,+ "lcaron" => 600_f32,+ "Kcommaaccent" => 600_f32,+ "Lacute" => 600_f32,+ "trademark" => 600_f32,+ "edotaccent" => 600_f32,+ "Igrave" => 600_f32,+ "Imacron" => 600_f32,+ "Lcaron" => 600_f32,+ "onehalf" => 600_f32,+ "lessequal" => 600_f32,+ "ocircumflex" => 600_f32,+ "ntilde" => 600_f32,+ "Uhungarumlaut" => 600_f32,+ "Eacute" => 600_f32,+ "emacron" => 600_f32,+ "gbreve" => 600_f32,+ "onequarter" => 600_f32,+ "Scaron" => 600_f32,+ "Scommaaccent" => 600_f32,+ "Ohungarumlaut" => 600_f32,+ "degree" => 600_f32,+ "ograve" => 600_f32,+ "Ccaron" => 600_f32,+ "ugrave" => 600_f32,+ "radical" => 600_f32,+ "Dcaron" => 600_f32,+ "rcommaaccent" => 600_f32,+ "Ntilde" => 600_f32,+ "otilde" => 600_f32,+ "Rcommaaccent" => 600_f32,+ "Lcommaaccent" => 600_f32,+ "Atilde" => 600_f32,+ "Aogonek" => 600_f32,+ "Aring" => 600_f32,+ "Otilde" => 600_f32,+ "zdotaccent" => 600_f32,+ "Ecaron" => 600_f32,+ "Iogonek" => 600_f32,+ "kcommaaccent" => 600_f32,+ "minus" => 600_f32,+ "Icircumflex" => 600_f32,+ "ncaron" => 600_f32,+ "tcommaaccent" => 600_f32,+ "logicalnot" => 600_f32,+ "odieresis" => 600_f32,+ "udieresis" => 600_f32,+ "notequal" => 600_f32,+ "gcommaaccent" => 600_f32,+ "eth" => 600_f32,+ "zcaron" => 600_f32,+ "ncommaaccent" => 600_f32,+ "onesuperior" => 600_f32,+ "imacron" => 600_f32,+ "Euro" => 600_f32,+};++pub(crate) static COURIER_BOLD_OBLIQUE: phf::Map<&'static str, f32> = phf_map! {+ "space" => 600_f32,+ "exclam" => 600_f32,+ "quotedbl" => 600_f32,+ "numbersign" => 600_f32,+ "dollar" => 600_f32,+ "percent" => 600_f32,+ "ampersand" => 600_f32,+ "quoteright" => 600_f32,+ "parenleft" => 600_f32,+ "parenright" => 600_f32,+ "asterisk" => 600_f32,+ "plus" => 600_f32,+ "comma" => 600_f32,+ "hyphen" => 600_f32,+ "period" => 600_f32,+ "slash" => 600_f32,+ "zero" => 600_f32,+ "one" => 600_f32,+ "two" => 600_f32,+ "three" => 600_f32,+ "four" => 600_f32,+ "five" => 600_f32,+ "six" => 600_f32,+ "seven" => 600_f32,+ "eight" => 600_f32,+ "nine" => 600_f32,+ "colon" => 600_f32,+ "semicolon" => 600_f32,+ "less" => 600_f32,+ "equal" => 600_f32,+ "greater" => 600_f32,+ "question" => 600_f32,+ "at" => 600_f32,+ "A" => 600_f32,+ "B" => 600_f32,+ "C" => 600_f32,+ "D" => 600_f32,+ "E" => 600_f32,+ "F" => 600_f32,+ "G" => 600_f32,+ "H" => 600_f32,+ "I" => 600_f32,+ "J" => 600_f32,+ "K" => 600_f32,+ "L" => 600_f32,+ "M" => 600_f32,+ "N" => 600_f32,+ "O" => 600_f32,+ "P" => 600_f32,+ "Q" => 600_f32,+ "R" => 600_f32,+ "S" => 600_f32,+ "T" => 600_f32,+ "U" => 600_f32,+ "V" => 600_f32,+ "W" => 600_f32,+ "X" => 600_f32,+ "Y" => 600_f32,+ "Z" => 600_f32,+ "bracketleft" => 600_f32,+ "backslash" => 600_f32,+ "bracketright" => 600_f32,+ "asciicircum" => 600_f32,+ "underscore" => 600_f32,+ "quoteleft" => 600_f32,+ "a" => 600_f32,+ "b" => 600_f32,+ "c" => 600_f32,+ "d" => 600_f32,+ "e" => 600_f32,+ "f" => 600_f32,+ "g" => 600_f32,+ "h" => 600_f32,+ "i" => 600_f32,+ "j" => 600_f32,+ "k" => 600_f32,+ "l" => 600_f32,+ "m" => 600_f32,+ "n" => 600_f32,+ "o" => 600_f32,+ "p" => 600_f32,+ "q" => 600_f32,+ "r" => 600_f32,+ "s" => 600_f32,+ "t" => 600_f32,+ "u" => 600_f32,+ "v" => 600_f32,+ "w" => 600_f32,+ "x" => 600_f32,+ "y" => 600_f32,+ "z" => 600_f32,+ "braceleft" => 600_f32,+ "bar" => 600_f32,+ "braceright" => 600_f32,+ "asciitilde" => 600_f32,+ "exclamdown" => 600_f32,+ "cent" => 600_f32,+ "sterling" => 600_f32,+ "fraction" => 600_f32,+ "yen" => 600_f32,+ "florin" => 600_f32,+ "section" => 600_f32,+ "currency" => 600_f32,+ "quotesingle" => 600_f32,+ "quotedblleft" => 600_f32,+ "guillemotleft" => 600_f32,+ "guilsinglleft" => 600_f32,+ "guilsinglright" => 600_f32,+ "fi" => 600_f32,+ "fl" => 600_f32,+ "endash" => 600_f32,+ "dagger" => 600_f32,+ "daggerdbl" => 600_f32,+ "periodcentered" => 600_f32,+ "paragraph" => 600_f32,+ "bullet" => 600_f32,+ "quotesinglbase" => 600_f32,+ "quotedblbase" => 600_f32,+ "quotedblright" => 600_f32,+ "guillemotright" => 600_f32,+ "ellipsis" => 600_f32,+ "perthousand" => 600_f32,+ "questiondown" => 600_f32,+ "grave" => 600_f32,+ "acute" => 600_f32,+ "circumflex" => 600_f32,+ "tilde" => 600_f32,+ "macron" => 600_f32,+ "breve" => 600_f32,+ "dotaccent" => 600_f32,+ "dieresis" => 600_f32,+ "ring" => 600_f32,+ "cedilla" => 600_f32,+ "hungarumlaut" => 600_f32,+ "ogonek" => 600_f32,+ "caron" => 600_f32,+ "emdash" => 600_f32,+ "AE" => 600_f32,+ "ordfeminine" => 600_f32,+ "Lslash" => 600_f32,+ "Oslash" => 600_f32,+ "OE" => 600_f32,+ "ordmasculine" => 600_f32,+ "ae" => 600_f32,+ "dotlessi" => 600_f32,+ "lslash" => 600_f32,+ "oslash" => 600_f32,+ "oe" => 600_f32,+ "germandbls" => 600_f32,+ "Idieresis" => 600_f32,+ "eacute" => 600_f32,+ "abreve" => 600_f32,+ "uhungarumlaut" => 600_f32,+ "ecaron" => 600_f32,+ "Ydieresis" => 600_f32,+ "divide" => 600_f32,+ "Yacute" => 600_f32,+ "Acircumflex" => 600_f32,+ "aacute" => 600_f32,+ "Ucircumflex" => 600_f32,+ "yacute" => 600_f32,+ "scommaaccent" => 600_f32,+ "ecircumflex" => 600_f32,+ "Uring" => 600_f32,+ "Udieresis" => 600_f32,+ "aogonek" => 600_f32,+ "Uacute" => 600_f32,+ "uogonek" => 600_f32,+ "Edieresis" => 600_f32,+ "Dcroat" => 600_f32,+ "commaaccent" => 600_f32,+ "copyright" => 600_f32,+ "Emacron" => 600_f32,+ "ccaron" => 600_f32,+ "aring" => 600_f32,+ "Ncommaaccent" => 600_f32,+ "lacute" => 600_f32,+ "agrave" => 600_f32,+ "Tcommaaccent" => 600_f32,+ "Cacute" => 600_f32,+ "atilde" => 600_f32,+ "Edotaccent" => 600_f32,+ "scaron" => 600_f32,+ "scedilla" => 600_f32,+ "iacute" => 600_f32,+ "lozenge" => 600_f32,+ "Rcaron" => 600_f32,+ "Gcommaaccent" => 600_f32,+ "ucircumflex" => 600_f32,+ "acircumflex" => 600_f32,+ "Amacron" => 600_f32,+ "rcaron" => 600_f32,+ "ccedilla" => 600_f32,+ "Zdotaccent" => 600_f32,+ "Thorn" => 600_f32,+ "Omacron" => 600_f32,+ "Racute" => 600_f32,+ "Sacute" => 600_f32,+ "dcaron" => 600_f32,+ "Umacron" => 600_f32,+ "uring" => 600_f32,+ "threesuperior" => 600_f32,+ "Ograve" => 600_f32,+ "Agrave" => 600_f32,+ "Abreve" => 600_f32,+ "multiply" => 600_f32,+ "uacute" => 600_f32,+ "Tcaron" => 600_f32,+ "partialdiff" => 600_f32,+ "ydieresis" => 600_f32,+ "Nacute" => 600_f32,+ "icircumflex" => 600_f32,+ "Ecircumflex" => 600_f32,+ "adieresis" => 600_f32,+ "edieresis" => 600_f32,+ "cacute" => 600_f32,+ "nacute" => 600_f32,+ "umacron" => 600_f32,+ "Ncaron" => 600_f32,+ "Iacute" => 600_f32,+ "plusminus" => 600_f32,+ "brokenbar" => 600_f32,+ "registered" => 600_f32,+ "Gbreve" => 600_f32,+ "Idotaccent" => 600_f32,+ "summation" => 600_f32,+ "Egrave" => 600_f32,+ "racute" => 600_f32,+ "omacron" => 600_f32,+ "Zacute" => 600_f32,+ "Zcaron" => 600_f32,+ "greaterequal" => 600_f32,+ "Eth" => 600_f32,+ "Ccedilla" => 600_f32,+ "lcommaaccent" => 600_f32,+ "tcaron" => 600_f32,+ "eogonek" => 600_f32,+ "Uogonek" => 600_f32,+ "Aacute" => 600_f32,+ "Adieresis" => 600_f32,+ "egrave" => 600_f32,+ "zacute" => 600_f32,+ "iogonek" => 600_f32,+ "Oacute" => 600_f32,+ "oacute" => 600_f32,+ "amacron" => 600_f32,+ "sacute" => 600_f32,+ "idieresis" => 600_f32,+ "Ocircumflex" => 600_f32,+ "Ugrave" => 600_f32,+ "Delta" => 600_f32,+ "thorn" => 600_f32,+ "twosuperior" => 600_f32,+ "Odieresis" => 600_f32,+ "mu" => 600_f32,+ "igrave" => 600_f32,+ "ohungarumlaut" => 600_f32,+ "Eogonek" => 600_f32,+ "dcroat" => 600_f32,+ "threequarters" => 600_f32,+ "Scedilla" => 600_f32,+ "lcaron" => 600_f32,+ "Kcommaaccent" => 600_f32,+ "Lacute" => 600_f32,+ "trademark" => 600_f32,+ "edotaccent" => 600_f32,+ "Igrave" => 600_f32,+ "Imacron" => 600_f32,+ "Lcaron" => 600_f32,+ "onehalf" => 600_f32,+ "lessequal" => 600_f32,+ "ocircumflex" => 600_f32,+ "ntilde" => 600_f32,+ "Uhungarumlaut" => 600_f32,+ "Eacute" => 600_f32,+ "emacron" => 600_f32,+ "gbreve" => 600_f32,+ "onequarter" => 600_f32,+ "Scaron" => 600_f32,+ "Scommaaccent" => 600_f32,+ "Ohungarumlaut" => 600_f32,+ "degree" => 600_f32,+ "ograve" => 600_f32,+ "Ccaron" => 600_f32,+ "ugrave" => 600_f32,+ "radical" => 600_f32,+ "Dcaron" => 600_f32,+ "rcommaaccent" => 600_f32,+ "Ntilde" => 600_f32,+ "otilde" => 600_f32,+ "Rcommaaccent" => 600_f32,+ "Lcommaaccent" => 600_f32,+ "Atilde" => 600_f32,+ "Aogonek" => 600_f32,+ "Aring" => 600_f32,+ "Otilde" => 600_f32,+ "zdotaccent" => 600_f32,+ "Ecaron" => 600_f32,+ "Iogonek" => 600_f32,+ "kcommaaccent" => 600_f32,+ "minus" => 600_f32,+ "Icircumflex" => 600_f32,+ "ncaron" => 600_f32,+ "tcommaaccent" => 600_f32,+ "logicalnot" => 600_f32,+ "odieresis" => 600_f32,+ "udieresis" => 600_f32,+ "notequal" => 600_f32,+ "gcommaaccent" => 600_f32,+ "eth" => 600_f32,+ "zcaron" => 600_f32,+ "ncommaaccent" => 600_f32,+ "onesuperior" => 600_f32,+ "imacron" => 600_f32,+ "Euro" => 600_f32,+};++pub(crate) static COURIER_OBLIQUE: phf::Map<&'static str, f32> = phf_map! {+ "space" => 600_f32,+ "exclam" => 600_f32,+ "quotedbl" => 600_f32,+ "numbersign" => 600_f32,+ "dollar" => 600_f32,+ "percent" => 600_f32,+ "ampersand" => 600_f32,+ "quoteright" => 600_f32,+ "parenleft" => 600_f32,+ "parenright" => 600_f32,+ "asterisk" => 600_f32,+ "plus" => 600_f32,+ "comma" => 600_f32,+ "hyphen" => 600_f32,+ "period" => 600_f32,+ "slash" => 600_f32,+ "zero" => 600_f32,+ "one" => 600_f32,+ "two" => 600_f32,+ "three" => 600_f32,+ "four" => 600_f32,+ "five" => 600_f32,+ "six" => 600_f32,+ "seven" => 600_f32,+ "eight" => 600_f32,+ "nine" => 600_f32,+ "colon" => 600_f32,+ "semicolon" => 600_f32,+ "less" => 600_f32,+ "equal" => 600_f32,+ "greater" => 600_f32,+ "question" => 600_f32,+ "at" => 600_f32,+ "A" => 600_f32,+ "B" => 600_f32,+ "C" => 600_f32,+ "D" => 600_f32,+ "E" => 600_f32,+ "F" => 600_f32,+ "G" => 600_f32,+ "H" => 600_f32,+ "I" => 600_f32,+ "J" => 600_f32,+ "K" => 600_f32,+ "L" => 600_f32,+ "M" => 600_f32,+ "N" => 600_f32,+ "O" => 600_f32,+ "P" => 600_f32,+ "Q" => 600_f32,+ "R" => 600_f32,+ "S" => 600_f32,+ "T" => 600_f32,+ "U" => 600_f32,+ "V" => 600_f32,+ "W" => 600_f32,+ "X" => 600_f32,+ "Y" => 600_f32,+ "Z" => 600_f32,+ "bracketleft" => 600_f32,+ "backslash" => 600_f32,+ "bracketright" => 600_f32,+ "asciicircum" => 600_f32,+ "underscore" => 600_f32,+ "quoteleft" => 600_f32,+ "a" => 600_f32,+ "b" => 600_f32,+ "c" => 600_f32,+ "d" => 600_f32,+ "e" => 600_f32,+ "f" => 600_f32,+ "g" => 600_f32,+ "h" => 600_f32,+ "i" => 600_f32,+ "j" => 600_f32,+ "k" => 600_f32,+ "l" => 600_f32,+ "m" => 600_f32,+ "n" => 600_f32,+ "o" => 600_f32,+ "p" => 600_f32,+ "q" => 600_f32,+ "r" => 600_f32,+ "s" => 600_f32,+ "t" => 600_f32,+ "u" => 600_f32,+ "v" => 600_f32,+ "w" => 600_f32,+ "x" => 600_f32,+ "y" => 600_f32,+ "z" => 600_f32,+ "braceleft" => 600_f32,+ "bar" => 600_f32,+ "braceright" => 600_f32,+ "asciitilde" => 600_f32,+ "exclamdown" => 600_f32,+ "cent" => 600_f32,+ "sterling" => 600_f32,+ "fraction" => 600_f32,+ "yen" => 600_f32,+ "florin" => 600_f32,+ "section" => 600_f32,+ "currency" => 600_f32,+ "quotesingle" => 600_f32,+ "quotedblleft" => 600_f32,+ "guillemotleft" => 600_f32,+ "guilsinglleft" => 600_f32,+ "guilsinglright" => 600_f32,+ "fi" => 600_f32,+ "fl" => 600_f32,+ "endash" => 600_f32,+ "dagger" => 600_f32,+ "daggerdbl" => 600_f32,+ "periodcentered" => 600_f32,+ "paragraph" => 600_f32,+ "bullet" => 600_f32,+ "quotesinglbase" => 600_f32,+ "quotedblbase" => 600_f32,+ "quotedblright" => 600_f32,+ "guillemotright" => 600_f32,+ "ellipsis" => 600_f32,+ "perthousand" => 600_f32,+ "questiondown" => 600_f32,+ "grave" => 600_f32,+ "acute" => 600_f32,+ "circumflex" => 600_f32,+ "tilde" => 600_f32,+ "macron" => 600_f32,+ "breve" => 600_f32,+ "dotaccent" => 600_f32,+ "dieresis" => 600_f32,+ "ring" => 600_f32,+ "cedilla" => 600_f32,+ "hungarumlaut" => 600_f32,+ "ogonek" => 600_f32,+ "caron" => 600_f32,+ "emdash" => 600_f32,+ "AE" => 600_f32,+ "ordfeminine" => 600_f32,+ "Lslash" => 600_f32,+ "Oslash" => 600_f32,+ "OE" => 600_f32,+ "ordmasculine" => 600_f32,+ "ae" => 600_f32,+ "dotlessi" => 600_f32,+ "lslash" => 600_f32,+ "oslash" => 600_f32,+ "oe" => 600_f32,+ "germandbls" => 600_f32,+ "Idieresis" => 600_f32,+ "eacute" => 600_f32,+ "abreve" => 600_f32,+ "uhungarumlaut" => 600_f32,+ "ecaron" => 600_f32,+ "Ydieresis" => 600_f32,+ "divide" => 600_f32,+ "Yacute" => 600_f32,+ "Acircumflex" => 600_f32,+ "aacute" => 600_f32,+ "Ucircumflex" => 600_f32,+ "yacute" => 600_f32,+ "scommaaccent" => 600_f32,+ "ecircumflex" => 600_f32,+ "Uring" => 600_f32,+ "Udieresis" => 600_f32,+ "aogonek" => 600_f32,+ "Uacute" => 600_f32,+ "uogonek" => 600_f32,+ "Edieresis" => 600_f32,+ "Dcroat" => 600_f32,+ "commaaccent" => 600_f32,+ "copyright" => 600_f32,+ "Emacron" => 600_f32,+ "ccaron" => 600_f32,+ "aring" => 600_f32,+ "Ncommaaccent" => 600_f32,+ "lacute" => 600_f32,+ "agrave" => 600_f32,+ "Tcommaaccent" => 600_f32,+ "Cacute" => 600_f32,+ "atilde" => 600_f32,+ "Edotaccent" => 600_f32,+ "scaron" => 600_f32,+ "scedilla" => 600_f32,+ "iacute" => 600_f32,+ "lozenge" => 600_f32,+ "Rcaron" => 600_f32,+ "Gcommaaccent" => 600_f32,+ "ucircumflex" => 600_f32,+ "acircumflex" => 600_f32,+ "Amacron" => 600_f32,+ "rcaron" => 600_f32,+ "ccedilla" => 600_f32,+ "Zdotaccent" => 600_f32,+ "Thorn" => 600_f32,+ "Omacron" => 600_f32,+ "Racute" => 600_f32,+ "Sacute" => 600_f32,+ "dcaron" => 600_f32,+ "Umacron" => 600_f32,+ "uring" => 600_f32,+ "threesuperior" => 600_f32,+ "Ograve" => 600_f32,+ "Agrave" => 600_f32,+ "Abreve" => 600_f32,+ "multiply" => 600_f32,+ "uacute" => 600_f32,+ "Tcaron" => 600_f32,+ "partialdiff" => 600_f32,+ "ydieresis" => 600_f32,+ "Nacute" => 600_f32,+ "icircumflex" => 600_f32,+ "Ecircumflex" => 600_f32,+ "adieresis" => 600_f32,+ "edieresis" => 600_f32,+ "cacute" => 600_f32,+ "nacute" => 600_f32,+ "umacron" => 600_f32,+ "Ncaron" => 600_f32,+ "Iacute" => 600_f32,+ "plusminus" => 600_f32,+ "brokenbar" => 600_f32,+ "registered" => 600_f32,+ "Gbreve" => 600_f32,+ "Idotaccent" => 600_f32,+ "summation" => 600_f32,+ "Egrave" => 600_f32,+ "racute" => 600_f32,+ "omacron" => 600_f32,+ "Zacute" => 600_f32,+ "Zcaron" => 600_f32,+ "greaterequal" => 600_f32,+ "Eth" => 600_f32,+ "Ccedilla" => 600_f32,+ "lcommaaccent" => 600_f32,+ "tcaron" => 600_f32,+ "eogonek" => 600_f32,+ "Uogonek" => 600_f32,+ "Aacute" => 600_f32,+ "Adieresis" => 600_f32,+ "egrave" => 600_f32,+ "zacute" => 600_f32,+ "iogonek" => 600_f32,+ "Oacute" => 600_f32,+ "oacute" => 600_f32,+ "amacron" => 600_f32,+ "sacute" => 600_f32,+ "idieresis" => 600_f32,+ "Ocircumflex" => 600_f32,+ "Ugrave" => 600_f32,+ "Delta" => 600_f32,+ "thorn" => 600_f32,+ "twosuperior" => 600_f32,+ "Odieresis" => 600_f32,+ "mu" => 600_f32,+ "igrave" => 600_f32,+ "ohungarumlaut" => 600_f32,+ "Eogonek" => 600_f32,+ "dcroat" => 600_f32,+ "threequarters" => 600_f32,+ "Scedilla" => 600_f32,+ "lcaron" => 600_f32,+ "Kcommaaccent" => 600_f32,+ "Lacute" => 600_f32,+ "trademark" => 600_f32,+ "edotaccent" => 600_f32,+ "Igrave" => 600_f32,+ "Imacron" => 600_f32,+ "Lcaron" => 600_f32,+ "onehalf" => 600_f32,+ "lessequal" => 600_f32,+ "ocircumflex" => 600_f32,+ "ntilde" => 600_f32,+ "Uhungarumlaut" => 600_f32,+ "Eacute" => 600_f32,+ "emacron" => 600_f32,+ "gbreve" => 600_f32,+ "onequarter" => 600_f32,+ "Scaron" => 600_f32,+ "Scommaaccent" => 600_f32,+ "Ohungarumlaut" => 600_f32,+ "degree" => 600_f32,+ "ograve" => 600_f32,+ "Ccaron" => 600_f32,+ "ugrave" => 600_f32,+ "radical" => 600_f32,+ "Dcaron" => 600_f32,+ "rcommaaccent" => 600_f32,+ "Ntilde" => 600_f32,+ "otilde" => 600_f32,+ "Rcommaaccent" => 600_f32,+ "Lcommaaccent" => 600_f32,+ "Atilde" => 600_f32,+ "Aogonek" => 600_f32,+ "Aring" => 600_f32,+ "Otilde" => 600_f32,+ "zdotaccent" => 600_f32,+ "Ecaron" => 600_f32,+ "Iogonek" => 600_f32,+ "kcommaaccent" => 600_f32,+ "minus" => 600_f32,+ "Icircumflex" => 600_f32,+ "ncaron" => 600_f32,+ "tcommaaccent" => 600_f32,+ "logicalnot" => 600_f32,+ "odieresis" => 600_f32,+ "udieresis" => 600_f32,+ "notequal" => 600_f32,+ "gcommaaccent" => 600_f32,+ "eth" => 600_f32,+ "zcaron" => 600_f32,+ "ncommaaccent" => 600_f32,+ "onesuperior" => 600_f32,+ "imacron" => 600_f32,+ "Euro" => 600_f32,+};++pub(crate) static HELVETICA: phf::Map<&'static str, f32> = phf_map! {+ "space" => 278_f32,+ "exclam" => 278_f32,+ "quotedbl" => 355_f32,+ "numbersign" => 556_f32,+ "dollar" => 556_f32,+ "percent" => 889_f32,+ "ampersand" => 667_f32,+ "quoteright" => 222_f32,+ "parenleft" => 333_f32,+ "parenright" => 333_f32,+ "asterisk" => 389_f32,+ "plus" => 584_f32,+ "comma" => 278_f32,+ "hyphen" => 333_f32,+ "period" => 278_f32,+ "slash" => 278_f32,+ "zero" => 556_f32,+ "one" => 556_f32,+ "two" => 556_f32,+ "three" => 556_f32,+ "four" => 556_f32,+ "five" => 556_f32,+ "six" => 556_f32,+ "seven" => 556_f32,+ "eight" => 556_f32,+ "nine" => 556_f32,+ "colon" => 278_f32,+ "semicolon" => 278_f32,+ "less" => 584_f32,+ "equal" => 584_f32,+ "greater" => 584_f32,+ "question" => 556_f32,+ "at" => 1015_f32,+ "A" => 667_f32,+ "B" => 667_f32,+ "C" => 722_f32,+ "D" => 722_f32,+ "E" => 667_f32,+ "F" => 611_f32,+ "G" => 778_f32,+ "H" => 722_f32,+ "I" => 278_f32,+ "J" => 500_f32,+ "K" => 667_f32,+ "L" => 556_f32,+ "M" => 833_f32,+ "N" => 722_f32,+ "O" => 778_f32,+ "P" => 667_f32,+ "Q" => 778_f32,+ "R" => 722_f32,+ "S" => 667_f32,+ "T" => 611_f32,+ "U" => 722_f32,+ "V" => 667_f32,+ "W" => 944_f32,+ "X" => 667_f32,+ "Y" => 667_f32,+ "Z" => 611_f32,+ "bracketleft" => 278_f32,+ "backslash" => 278_f32,+ "bracketright" => 278_f32,+ "asciicircum" => 469_f32,+ "underscore" => 556_f32,+ "quoteleft" => 222_f32,+ "a" => 556_f32,+ "b" => 556_f32,+ "c" => 500_f32,+ "d" => 556_f32,+ "e" => 556_f32,+ "f" => 278_f32,+ "g" => 556_f32,+ "h" => 556_f32,+ "i" => 222_f32,+ "j" => 222_f32,+ "k" => 500_f32,+ "l" => 222_f32,+ "m" => 833_f32,+ "n" => 556_f32,+ "o" => 556_f32,+ "p" => 556_f32,+ "q" => 556_f32,+ "r" => 333_f32,+ "s" => 500_f32,+ "t" => 278_f32,+ "u" => 556_f32,+ "v" => 500_f32,+ "w" => 722_f32,+ "x" => 500_f32,+ "y" => 500_f32,+ "z" => 500_f32,+ "braceleft" => 334_f32,+ "bar" => 260_f32,+ "braceright" => 334_f32,+ "asciitilde" => 584_f32,+ "exclamdown" => 333_f32,+ "cent" => 556_f32,+ "sterling" => 556_f32,+ "fraction" => 167_f32,+ "yen" => 556_f32,+ "florin" => 556_f32,+ "section" => 556_f32,+ "currency" => 556_f32,+ "quotesingle" => 191_f32,+ "quotedblleft" => 333_f32,+ "guillemotleft" => 556_f32,+ "guilsinglleft" => 333_f32,+ "guilsinglright" => 333_f32,+ "fi" => 500_f32,+ "fl" => 500_f32,+ "endash" => 556_f32,+ "dagger" => 556_f32,+ "daggerdbl" => 556_f32,+ "periodcentered" => 278_f32,+ "paragraph" => 537_f32,+ "bullet" => 350_f32,+ "quotesinglbase" => 222_f32,+ "quotedblbase" => 333_f32,+ "quotedblright" => 333_f32,+ "guillemotright" => 556_f32,+ "ellipsis" => 1000_f32,+ "perthousand" => 1000_f32,+ "questiondown" => 611_f32,+ "grave" => 333_f32,+ "acute" => 333_f32,+ "circumflex" => 333_f32,+ "tilde" => 333_f32,+ "macron" => 333_f32,+ "breve" => 333_f32,+ "dotaccent" => 333_f32,+ "dieresis" => 333_f32,+ "ring" => 333_f32,+ "cedilla" => 333_f32,+ "hungarumlaut" => 333_f32,+ "ogonek" => 333_f32,+ "caron" => 333_f32,+ "emdash" => 1000_f32,+ "AE" => 1000_f32,+ "ordfeminine" => 370_f32,+ "Lslash" => 556_f32,+ "Oslash" => 778_f32,+ "OE" => 1000_f32,+ "ordmasculine" => 365_f32,+ "ae" => 889_f32,+ "dotlessi" => 278_f32,+ "lslash" => 222_f32,+ "oslash" => 611_f32,+ "oe" => 944_f32,+ "germandbls" => 611_f32,+ "Idieresis" => 278_f32,+ "eacute" => 556_f32,+ "abreve" => 556_f32,+ "uhungarumlaut" => 556_f32,+ "ecaron" => 556_f32,+ "Ydieresis" => 667_f32,+ "divide" => 584_f32,+ "Yacute" => 667_f32,+ "Acircumflex" => 667_f32,+ "aacute" => 556_f32,+ "Ucircumflex" => 722_f32,+ "yacute" => 500_f32,+ "scommaaccent" => 500_f32,+ "ecircumflex" => 556_f32,+ "Uring" => 722_f32,+ "Udieresis" => 722_f32,+ "aogonek" => 556_f32,+ "Uacute" => 722_f32,+ "uogonek" => 556_f32,+ "Edieresis" => 667_f32,+ "Dcroat" => 722_f32,+ "commaaccent" => 250_f32,+ "copyright" => 737_f32,+ "Emacron" => 667_f32,+ "ccaron" => 500_f32,+ "aring" => 556_f32,+ "Ncommaaccent" => 722_f32,+ "lacute" => 222_f32,+ "agrave" => 556_f32,+ "Tcommaaccent" => 611_f32,+ "Cacute" => 722_f32,+ "atilde" => 556_f32,+ "Edotaccent" => 667_f32,+ "scaron" => 500_f32,+ "scedilla" => 500_f32,+ "iacute" => 278_f32,+ "lozenge" => 471_f32,+ "Rcaron" => 722_f32,+ "Gcommaaccent" => 778_f32,+ "ucircumflex" => 556_f32,+ "acircumflex" => 556_f32,+ "Amacron" => 667_f32,+ "rcaron" => 333_f32,+ "ccedilla" => 500_f32,+ "Zdotaccent" => 611_f32,+ "Thorn" => 667_f32,+ "Omacron" => 778_f32,+ "Racute" => 722_f32,+ "Sacute" => 667_f32,+ "dcaron" => 643_f32,+ "Umacron" => 722_f32,+ "uring" => 556_f32,+ "threesuperior" => 333_f32,+ "Ograve" => 778_f32,+ "Agrave" => 667_f32,+ "Abreve" => 667_f32,+ "multiply" => 584_f32,+ "uacute" => 556_f32,+ "Tcaron" => 611_f32,+ "partialdiff" => 476_f32,+ "ydieresis" => 500_f32,+ "Nacute" => 722_f32,+ "icircumflex" => 278_f32,+ "Ecircumflex" => 667_f32,+ "adieresis" => 556_f32,+ "edieresis" => 556_f32,+ "cacute" => 500_f32,+ "nacute" => 556_f32,+ "umacron" => 556_f32,+ "Ncaron" => 722_f32,+ "Iacute" => 278_f32,+ "plusminus" => 584_f32,+ "brokenbar" => 260_f32,+ "registered" => 737_f32,+ "Gbreve" => 778_f32,+ "Idotaccent" => 278_f32,+ "summation" => 600_f32,+ "Egrave" => 667_f32,+ "racute" => 333_f32,+ "omacron" => 556_f32,+ "Zacute" => 611_f32,+ "Zcaron" => 611_f32,+ "greaterequal" => 549_f32,+ "Eth" => 722_f32,+ "Ccedilla" => 722_f32,+ "lcommaaccent" => 222_f32,+ "tcaron" => 317_f32,+ "eogonek" => 556_f32,+ "Uogonek" => 722_f32,+ "Aacute" => 667_f32,+ "Adieresis" => 667_f32,+ "egrave" => 556_f32,+ "zacute" => 500_f32,+ "iogonek" => 222_f32,+ "Oacute" => 778_f32,+ "oacute" => 556_f32,+ "amacron" => 556_f32,+ "sacute" => 500_f32,+ "idieresis" => 278_f32,+ "Ocircumflex" => 778_f32,+ "Ugrave" => 722_f32,+ "Delta" => 612_f32,+ "thorn" => 556_f32,+ "twosuperior" => 333_f32,+ "Odieresis" => 778_f32,+ "mu" => 556_f32,+ "igrave" => 278_f32,+ "ohungarumlaut" => 556_f32,+ "Eogonek" => 667_f32,+ "dcroat" => 556_f32,+ "threequarters" => 834_f32,+ "Scedilla" => 667_f32,+ "lcaron" => 299_f32,+ "Kcommaaccent" => 667_f32,+ "Lacute" => 556_f32,+ "trademark" => 1000_f32,+ "edotaccent" => 556_f32,+ "Igrave" => 278_f32,+ "Imacron" => 278_f32,+ "Lcaron" => 556_f32,+ "onehalf" => 834_f32,+ "lessequal" => 549_f32,+ "ocircumflex" => 556_f32,+ "ntilde" => 556_f32,+ "Uhungarumlaut" => 722_f32,+ "Eacute" => 667_f32,+ "emacron" => 556_f32,+ "gbreve" => 556_f32,+ "onequarter" => 834_f32,+ "Scaron" => 667_f32,+ "Scommaaccent" => 667_f32,+ "Ohungarumlaut" => 778_f32,+ "degree" => 400_f32,+ "ograve" => 556_f32,+ "Ccaron" => 722_f32,+ "ugrave" => 556_f32,+ "radical" => 453_f32,+ "Dcaron" => 722_f32,+ "rcommaaccent" => 333_f32,+ "Ntilde" => 722_f32,+ "otilde" => 556_f32,+ "Rcommaaccent" => 722_f32,+ "Lcommaaccent" => 556_f32,+ "Atilde" => 667_f32,+ "Aogonek" => 667_f32,+ "Aring" => 667_f32,+ "Otilde" => 778_f32,+ "zdotaccent" => 500_f32,+ "Ecaron" => 667_f32,+ "Iogonek" => 278_f32,+ "kcommaaccent" => 500_f32,+ "minus" => 584_f32,+ "Icircumflex" => 278_f32,+ "ncaron" => 556_f32,+ "tcommaaccent" => 278_f32,+ "logicalnot" => 584_f32,+ "odieresis" => 556_f32,+ "udieresis" => 556_f32,+ "notequal" => 549_f32,+ "gcommaaccent" => 556_f32,+ "eth" => 556_f32,+ "zcaron" => 500_f32,+ "ncommaaccent" => 556_f32,+ "onesuperior" => 333_f32,+ "imacron" => 278_f32,+ "Euro" => 556_f32,+};++pub(crate) static HELVETICA_BOLD: phf::Map<&'static str, f32> = phf_map! {+ "space" => 278_f32,+ "exclam" => 333_f32,+ "quotedbl" => 474_f32,+ "numbersign" => 556_f32,+ "dollar" => 556_f32,+ "percent" => 889_f32,+ "ampersand" => 722_f32,+ "quoteright" => 278_f32,+ "parenleft" => 333_f32,+ "parenright" => 333_f32,+ "asterisk" => 389_f32,+ "plus" => 584_f32,+ "comma" => 278_f32,+ "hyphen" => 333_f32,+ "period" => 278_f32,+ "slash" => 278_f32,+ "zero" => 556_f32,+ "one" => 556_f32,+ "two" => 556_f32,+ "three" => 556_f32,+ "four" => 556_f32,+ "five" => 556_f32,+ "six" => 556_f32,+ "seven" => 556_f32,+ "eight" => 556_f32,+ "nine" => 556_f32,+ "colon" => 333_f32,+ "semicolon" => 333_f32,+ "less" => 584_f32,+ "equal" => 584_f32,+ "greater" => 584_f32,+ "question" => 611_f32,+ "at" => 975_f32,+ "A" => 722_f32,+ "B" => 722_f32,+ "C" => 722_f32,+ "D" => 722_f32,+ "E" => 667_f32,+ "F" => 611_f32,+ "G" => 778_f32,+ "H" => 722_f32,+ "I" => 278_f32,+ "J" => 556_f32,+ "K" => 722_f32,+ "L" => 611_f32,+ "M" => 833_f32,+ "N" => 722_f32,+ "O" => 778_f32,+ "P" => 667_f32,+ "Q" => 778_f32,+ "R" => 722_f32,+ "S" => 667_f32,+ "T" => 611_f32,+ "U" => 722_f32,+ "V" => 667_f32,+ "W" => 944_f32,+ "X" => 667_f32,+ "Y" => 667_f32,+ "Z" => 611_f32,+ "bracketleft" => 333_f32,+ "backslash" => 278_f32,+ "bracketright" => 333_f32,+ "asciicircum" => 584_f32,+ "underscore" => 556_f32,+ "quoteleft" => 278_f32,+ "a" => 556_f32,+ "b" => 611_f32,+ "c" => 556_f32,+ "d" => 611_f32,+ "e" => 556_f32,+ "f" => 333_f32,+ "g" => 611_f32,+ "h" => 611_f32,+ "i" => 278_f32,+ "j" => 278_f32,+ "k" => 556_f32,+ "l" => 278_f32,+ "m" => 889_f32,+ "n" => 611_f32,+ "o" => 611_f32,+ "p" => 611_f32,+ "q" => 611_f32,+ "r" => 389_f32,+ "s" => 556_f32,+ "t" => 333_f32,+ "u" => 611_f32,+ "v" => 556_f32,+ "w" => 778_f32,+ "x" => 556_f32,+ "y" => 556_f32,+ "z" => 500_f32,+ "braceleft" => 389_f32,+ "bar" => 280_f32,+ "braceright" => 389_f32,+ "asciitilde" => 584_f32,+ "exclamdown" => 333_f32,+ "cent" => 556_f32,+ "sterling" => 556_f32,+ "fraction" => 167_f32,+ "yen" => 556_f32,+ "florin" => 556_f32,+ "section" => 556_f32,+ "currency" => 556_f32,+ "quotesingle" => 238_f32,+ "quotedblleft" => 500_f32,+ "guillemotleft" => 556_f32,+ "guilsinglleft" => 333_f32,+ "guilsinglright" => 333_f32,+ "fi" => 611_f32,+ "fl" => 611_f32,+ "endash" => 556_f32,+ "dagger" => 556_f32,+ "daggerdbl" => 556_f32,+ "periodcentered" => 278_f32,+ "paragraph" => 556_f32,+ "bullet" => 350_f32,+ "quotesinglbase" => 278_f32,+ "quotedblbase" => 500_f32,+ "quotedblright" => 500_f32,+ "guillemotright" => 556_f32,+ "ellipsis" => 1000_f32,+ "perthousand" => 1000_f32,+ "questiondown" => 611_f32,+ "grave" => 333_f32,+ "acute" => 333_f32,+ "circumflex" => 333_f32,+ "tilde" => 333_f32,+ "macron" => 333_f32,+ "breve" => 333_f32,+ "dotaccent" => 333_f32,+ "dieresis" => 333_f32,+ "ring" => 333_f32,+ "cedilla" => 333_f32,+ "hungarumlaut" => 333_f32,+ "ogonek" => 333_f32,+ "caron" => 333_f32,+ "emdash" => 1000_f32,+ "AE" => 1000_f32,+ "ordfeminine" => 370_f32,+ "Lslash" => 611_f32,+ "Oslash" => 778_f32,+ "OE" => 1000_f32,+ "ordmasculine" => 365_f32,+ "ae" => 889_f32,+ "dotlessi" => 278_f32,+ "lslash" => 278_f32,+ "oslash" => 611_f32,+ "oe" => 944_f32,+ "germandbls" => 611_f32,+ "Idieresis" => 278_f32,+ "eacute" => 556_f32,+ "abreve" => 556_f32,+ "uhungarumlaut" => 611_f32,+ "ecaron" => 556_f32,+ "Ydieresis" => 667_f32,+ "divide" => 584_f32,+ "Yacute" => 667_f32,+ "Acircumflex" => 722_f32,+ "aacute" => 556_f32,+ "Ucircumflex" => 722_f32,+ "yacute" => 556_f32,+ "scommaaccent" => 556_f32,+ "ecircumflex" => 556_f32,+ "Uring" => 722_f32,+ "Udieresis" => 722_f32,+ "aogonek" => 556_f32,+ "Uacute" => 722_f32,+ "uogonek" => 611_f32,+ "Edieresis" => 667_f32,+ "Dcroat" => 722_f32,+ "commaaccent" => 250_f32,+ "copyright" => 737_f32,+ "Emacron" => 667_f32,+ "ccaron" => 556_f32,+ "aring" => 556_f32,+ "Ncommaaccent" => 722_f32,+ "lacute" => 278_f32,+ "agrave" => 556_f32,+ "Tcommaaccent" => 611_f32,+ "Cacute" => 722_f32,+ "atilde" => 556_f32,+ "Edotaccent" => 667_f32,+ "scaron" => 556_f32,+ "scedilla" => 556_f32,+ "iacute" => 278_f32,+ "lozenge" => 494_f32,+ "Rcaron" => 722_f32,+ "Gcommaaccent" => 778_f32,+ "ucircumflex" => 611_f32,+ "acircumflex" => 556_f32,+ "Amacron" => 722_f32,+ "rcaron" => 389_f32,+ "ccedilla" => 556_f32,+ "Zdotaccent" => 611_f32,+ "Thorn" => 667_f32,+ "Omacron" => 778_f32,+ "Racute" => 722_f32,+ "Sacute" => 667_f32,+ "dcaron" => 743_f32,+ "Umacron" => 722_f32,+ "uring" => 611_f32,+ "threesuperior" => 333_f32,+ "Ograve" => 778_f32,+ "Agrave" => 722_f32,+ "Abreve" => 722_f32,+ "multiply" => 584_f32,+ "uacute" => 611_f32,+ "Tcaron" => 611_f32,+ "partialdiff" => 494_f32,+ "ydieresis" => 556_f32,+ "Nacute" => 722_f32,+ "icircumflex" => 278_f32,+ "Ecircumflex" => 667_f32,+ "adieresis" => 556_f32,+ "edieresis" => 556_f32,+ "cacute" => 556_f32,+ "nacute" => 611_f32,+ "umacron" => 611_f32,+ "Ncaron" => 722_f32,+ "Iacute" => 278_f32,+ "plusminus" => 584_f32,+ "brokenbar" => 280_f32,+ "registered" => 737_f32,+ "Gbreve" => 778_f32,+ "Idotaccent" => 278_f32,+ "summation" => 600_f32,+ "Egrave" => 667_f32,+ "racute" => 389_f32,+ "omacron" => 611_f32,+ "Zacute" => 611_f32,+ "Zcaron" => 611_f32,+ "greaterequal" => 549_f32,+ "Eth" => 722_f32,+ "Ccedilla" => 722_f32,+ "lcommaaccent" => 278_f32,+ "tcaron" => 389_f32,+ "eogonek" => 556_f32,+ "Uogonek" => 722_f32,+ "Aacute" => 722_f32,+ "Adieresis" => 722_f32,+ "egrave" => 556_f32,+ "zacute" => 500_f32,+ "iogonek" => 278_f32,+ "Oacute" => 778_f32,+ "oacute" => 611_f32,+ "amacron" => 556_f32,+ "sacute" => 556_f32,+ "idieresis" => 278_f32,+ "Ocircumflex" => 778_f32,+ "Ugrave" => 722_f32,+ "Delta" => 612_f32,+ "thorn" => 611_f32,+ "twosuperior" => 333_f32,+ "Odieresis" => 778_f32,+ "mu" => 611_f32,+ "igrave" => 278_f32,+ "ohungarumlaut" => 611_f32,+ "Eogonek" => 667_f32,+ "dcroat" => 611_f32,+ "threequarters" => 834_f32,+ "Scedilla" => 667_f32,+ "lcaron" => 400_f32,+ "Kcommaaccent" => 722_f32,+ "Lacute" => 611_f32,+ "trademark" => 1000_f32,+ "edotaccent" => 556_f32,+ "Igrave" => 278_f32,+ "Imacron" => 278_f32,+ "Lcaron" => 611_f32,+ "onehalf" => 834_f32,+ "lessequal" => 549_f32,+ "ocircumflex" => 611_f32,+ "ntilde" => 611_f32,+ "Uhungarumlaut" => 722_f32,+ "Eacute" => 667_f32,+ "emacron" => 556_f32,+ "gbreve" => 611_f32,+ "onequarter" => 834_f32,+ "Scaron" => 667_f32,+ "Scommaaccent" => 667_f32,+ "Ohungarumlaut" => 778_f32,+ "degree" => 400_f32,+ "ograve" => 611_f32,+ "Ccaron" => 722_f32,+ "ugrave" => 611_f32,+ "radical" => 549_f32,+ "Dcaron" => 722_f32,+ "rcommaaccent" => 389_f32,+ "Ntilde" => 722_f32,+ "otilde" => 611_f32,+ "Rcommaaccent" => 722_f32,+ "Lcommaaccent" => 611_f32,+ "Atilde" => 722_f32,+ "Aogonek" => 722_f32,+ "Aring" => 722_f32,+ "Otilde" => 778_f32,+ "zdotaccent" => 500_f32,+ "Ecaron" => 667_f32,+ "Iogonek" => 278_f32,+ "kcommaaccent" => 556_f32,+ "minus" => 584_f32,+ "Icircumflex" => 278_f32,+ "ncaron" => 611_f32,+ "tcommaaccent" => 333_f32,+ "logicalnot" => 584_f32,+ "odieresis" => 611_f32,+ "udieresis" => 611_f32,+ "notequal" => 549_f32,+ "gcommaaccent" => 611_f32,+ "eth" => 611_f32,+ "zcaron" => 500_f32,+ "ncommaaccent" => 611_f32,+ "onesuperior" => 333_f32,+ "imacron" => 278_f32,+ "Euro" => 556_f32,+};++pub(crate) static HELVETICA_BOLD_OBLIQUE: phf::Map<&'static str, f32> = phf_map! {+ "space" => 278_f32,+ "exclam" => 333_f32,+ "quotedbl" => 474_f32,+ "numbersign" => 556_f32,+ "dollar" => 556_f32,+ "percent" => 889_f32,+ "ampersand" => 722_f32,+ "quoteright" => 278_f32,+ "parenleft" => 333_f32,+ "parenright" => 333_f32,+ "asterisk" => 389_f32,+ "plus" => 584_f32,+ "comma" => 278_f32,+ "hyphen" => 333_f32,+ "period" => 278_f32,+ "slash" => 278_f32,+ "zero" => 556_f32,+ "one" => 556_f32,+ "two" => 556_f32,+ "three" => 556_f32,+ "four" => 556_f32,+ "five" => 556_f32,+ "six" => 556_f32,+ "seven" => 556_f32,+ "eight" => 556_f32,+ "nine" => 556_f32,+ "colon" => 333_f32,+ "semicolon" => 333_f32,+ "less" => 584_f32,+ "equal" => 584_f32,+ "greater" => 584_f32,+ "question" => 611_f32,+ "at" => 975_f32,+ "A" => 722_f32,+ "B" => 722_f32,+ "C" => 722_f32,+ "D" => 722_f32,+ "E" => 667_f32,+ "F" => 611_f32,+ "G" => 778_f32,+ "H" => 722_f32,+ "I" => 278_f32,+ "J" => 556_f32,+ "K" => 722_f32,+ "L" => 611_f32,+ "M" => 833_f32,+ "N" => 722_f32,+ "O" => 778_f32,+ "P" => 667_f32,+ "Q" => 778_f32,+ "R" => 722_f32,+ "S" => 667_f32,+ "T" => 611_f32,+ "U" => 722_f32,+ "V" => 667_f32,+ "W" => 944_f32,+ "X" => 667_f32,+ "Y" => 667_f32,+ "Z" => 611_f32,+ "bracketleft" => 333_f32,+ "backslash" => 278_f32,+ "bracketright" => 333_f32,+ "asciicircum" => 584_f32,+ "underscore" => 556_f32,+ "quoteleft" => 278_f32,+ "a" => 556_f32,+ "b" => 611_f32,+ "c" => 556_f32,+ "d" => 611_f32,+ "e" => 556_f32,+ "f" => 333_f32,+ "g" => 611_f32,+ "h" => 611_f32,+ "i" => 278_f32,+ "j" => 278_f32,+ "k" => 556_f32,+ "l" => 278_f32,+ "m" => 889_f32,+ "n" => 611_f32,+ "o" => 611_f32,+ "p" => 611_f32,+ "q" => 611_f32,+ "r" => 389_f32,+ "s" => 556_f32,+ "t" => 333_f32,+ "u" => 611_f32,+ "v" => 556_f32,+ "w" => 778_f32,+ "x" => 556_f32,+ "y" => 556_f32,+ "z" => 500_f32,+ "braceleft" => 389_f32,+ "bar" => 280_f32,+ "braceright" => 389_f32,+ "asciitilde" => 584_f32,+ "exclamdown" => 333_f32,+ "cent" => 556_f32,+ "sterling" => 556_f32,+ "fraction" => 167_f32,+ "yen" => 556_f32,+ "florin" => 556_f32,+ "section" => 556_f32,+ "currency" => 556_f32,+ "quotesingle" => 238_f32,+ "quotedblleft" => 500_f32,+ "guillemotleft" => 556_f32,+ "guilsinglleft" => 333_f32,+ "guilsinglright" => 333_f32,+ "fi" => 611_f32,+ "fl" => 611_f32,+ "endash" => 556_f32,+ "dagger" => 556_f32,+ "daggerdbl" => 556_f32,+ "periodcentered" => 278_f32,+ "paragraph" => 556_f32,+ "bullet" => 350_f32,+ "quotesinglbase" => 278_f32,+ "quotedblbase" => 500_f32,+ "quotedblright" => 500_f32,+ "guillemotright" => 556_f32,+ "ellipsis" => 1000_f32,+ "perthousand" => 1000_f32,+ "questiondown" => 611_f32,+ "grave" => 333_f32,+ "acute" => 333_f32,+ "circumflex" => 333_f32,+ "tilde" => 333_f32,+ "macron" => 333_f32,+ "breve" => 333_f32,+ "dotaccent" => 333_f32,+ "dieresis" => 333_f32,+ "ring" => 333_f32,+ "cedilla" => 333_f32,+ "hungarumlaut" => 333_f32,+ "ogonek" => 333_f32,+ "caron" => 333_f32,+ "emdash" => 1000_f32,+ "AE" => 1000_f32,+ "ordfeminine" => 370_f32,+ "Lslash" => 611_f32,+ "Oslash" => 778_f32,+ "OE" => 1000_f32,+ "ordmasculine" => 365_f32,+ "ae" => 889_f32,+ "dotlessi" => 278_f32,+ "lslash" => 278_f32,+ "oslash" => 611_f32,+ "oe" => 944_f32,+ "germandbls" => 611_f32,+ "Idieresis" => 278_f32,+ "eacute" => 556_f32,+ "abreve" => 556_f32,+ "uhungarumlaut" => 611_f32,+ "ecaron" => 556_f32,+ "Ydieresis" => 667_f32,+ "divide" => 584_f32,+ "Yacute" => 667_f32,+ "Acircumflex" => 722_f32,+ "aacute" => 556_f32,+ "Ucircumflex" => 722_f32,+ "yacute" => 556_f32,+ "scommaaccent" => 556_f32,+ "ecircumflex" => 556_f32,+ "Uring" => 722_f32,+ "Udieresis" => 722_f32,+ "aogonek" => 556_f32,+ "Uacute" => 722_f32,+ "uogonek" => 611_f32,+ "Edieresis" => 667_f32,+ "Dcroat" => 722_f32,+ "commaaccent" => 250_f32,+ "copyright" => 737_f32,+ "Emacron" => 667_f32,+ "ccaron" => 556_f32,+ "aring" => 556_f32,+ "Ncommaaccent" => 722_f32,+ "lacute" => 278_f32,+ "agrave" => 556_f32,+ "Tcommaaccent" => 611_f32,+ "Cacute" => 722_f32,+ "atilde" => 556_f32,+ "Edotaccent" => 667_f32,+ "scaron" => 556_f32,+ "scedilla" => 556_f32,+ "iacute" => 278_f32,+ "lozenge" => 494_f32,+ "Rcaron" => 722_f32,+ "Gcommaaccent" => 778_f32,+ "ucircumflex" => 611_f32,+ "acircumflex" => 556_f32,+ "Amacron" => 722_f32,+ "rcaron" => 389_f32,+ "ccedilla" => 556_f32,+ "Zdotaccent" => 611_f32,+ "Thorn" => 667_f32,+ "Omacron" => 778_f32,+ "Racute" => 722_f32,+ "Sacute" => 667_f32,+ "dcaron" => 743_f32,+ "Umacron" => 722_f32,+ "uring" => 611_f32,+ "threesuperior" => 333_f32,+ "Ograve" => 778_f32,+ "Agrave" => 722_f32,+ "Abreve" => 722_f32,+ "multiply" => 584_f32,+ "uacute" => 611_f32,+ "Tcaron" => 611_f32,+ "partialdiff" => 494_f32,+ "ydieresis" => 556_f32,+ "Nacute" => 722_f32,+ "icircumflex" => 278_f32,+ "Ecircumflex" => 667_f32,+ "adieresis" => 556_f32,+ "edieresis" => 556_f32,+ "cacute" => 556_f32,+ "nacute" => 611_f32,+ "umacron" => 611_f32,+ "Ncaron" => 722_f32,+ "Iacute" => 278_f32,+ "plusminus" => 584_f32,+ "brokenbar" => 280_f32,+ "registered" => 737_f32,+ "Gbreve" => 778_f32,+ "Idotaccent" => 278_f32,+ "summation" => 600_f32,+ "Egrave" => 667_f32,+ "racute" => 389_f32,+ "omacron" => 611_f32,+ "Zacute" => 611_f32,+ "Zcaron" => 611_f32,+ "greaterequal" => 549_f32,+ "Eth" => 722_f32,+ "Ccedilla" => 722_f32,+ "lcommaaccent" => 278_f32,+ "tcaron" => 389_f32,+ "eogonek" => 556_f32,+ "Uogonek" => 722_f32,+ "Aacute" => 722_f32,+ "Adieresis" => 722_f32,+ "egrave" => 556_f32,+ "zacute" => 500_f32,+ "iogonek" => 278_f32,+ "Oacute" => 778_f32,+ "oacute" => 611_f32,+ "amacron" => 556_f32,+ "sacute" => 556_f32,+ "idieresis" => 278_f32,+ "Ocircumflex" => 778_f32,+ "Ugrave" => 722_f32,+ "Delta" => 612_f32,+ "thorn" => 611_f32,+ "twosuperior" => 333_f32,+ "Odieresis" => 778_f32,+ "mu" => 611_f32,+ "igrave" => 278_f32,+ "ohungarumlaut" => 611_f32,+ "Eogonek" => 667_f32,+ "dcroat" => 611_f32,+ "threequarters" => 834_f32,+ "Scedilla" => 667_f32,+ "lcaron" => 400_f32,+ "Kcommaaccent" => 722_f32,+ "Lacute" => 611_f32,+ "trademark" => 1000_f32,+ "edotaccent" => 556_f32,+ "Igrave" => 278_f32,+ "Imacron" => 278_f32,+ "Lcaron" => 611_f32,+ "onehalf" => 834_f32,+ "lessequal" => 549_f32,+ "ocircumflex" => 611_f32,+ "ntilde" => 611_f32,+ "Uhungarumlaut" => 722_f32,+ "Eacute" => 667_f32,+ "emacron" => 556_f32,+ "gbreve" => 611_f32,+ "onequarter" => 834_f32,+ "Scaron" => 667_f32,+ "Scommaaccent" => 667_f32,+ "Ohungarumlaut" => 778_f32,+ "degree" => 400_f32,+ "ograve" => 611_f32,+ "Ccaron" => 722_f32,+ "ugrave" => 611_f32,+ "radical" => 549_f32,+ "Dcaron" => 722_f32,+ "rcommaaccent" => 389_f32,+ "Ntilde" => 722_f32,+ "otilde" => 611_f32,+ "Rcommaaccent" => 722_f32,+ "Lcommaaccent" => 611_f32,+ "Atilde" => 722_f32,+ "Aogonek" => 722_f32,+ "Aring" => 722_f32,+ "Otilde" => 778_f32,+ "zdotaccent" => 500_f32,+ "Ecaron" => 667_f32,+ "Iogonek" => 278_f32,+ "kcommaaccent" => 556_f32,+ "minus" => 584_f32,+ "Icircumflex" => 278_f32,+ "ncaron" => 611_f32,+ "tcommaaccent" => 333_f32,+ "logicalnot" => 584_f32,+ "odieresis" => 611_f32,+ "udieresis" => 611_f32,+ "notequal" => 549_f32,+ "gcommaaccent" => 611_f32,+ "eth" => 611_f32,+ "zcaron" => 500_f32,+ "ncommaaccent" => 611_f32,+ "onesuperior" => 333_f32,+ "imacron" => 278_f32,+ "Euro" => 556_f32,+};++pub(crate) static HELVETICA_OBLIQUE: phf::Map<&'static str, f32> = phf_map! {+ "space" => 278_f32,+ "exclam" => 278_f32,+ "quotedbl" => 355_f32,+ "numbersign" => 556_f32,+ "dollar" => 556_f32,+ "percent" => 889_f32,+ "ampersand" => 667_f32,+ "quoteright" => 222_f32,+ "parenleft" => 333_f32,+ "parenright" => 333_f32,+ "asterisk" => 389_f32,+ "plus" => 584_f32,+ "comma" => 278_f32,+ "hyphen" => 333_f32,+ "period" => 278_f32,+ "slash" => 278_f32,+ "zero" => 556_f32,+ "one" => 556_f32,+ "two" => 556_f32,+ "three" => 556_f32,+ "four" => 556_f32,+ "five" => 556_f32,+ "six" => 556_f32,+ "seven" => 556_f32,+ "eight" => 556_f32,+ "nine" => 556_f32,+ "colon" => 278_f32,+ "semicolon" => 278_f32,+ "less" => 584_f32,+ "equal" => 584_f32,+ "greater" => 584_f32,+ "question" => 556_f32,+ "at" => 1015_f32,+ "A" => 667_f32,+ "B" => 667_f32,+ "C" => 722_f32,+ "D" => 722_f32,+ "E" => 667_f32,+ "F" => 611_f32,+ "G" => 778_f32,+ "H" => 722_f32,+ "I" => 278_f32,+ "J" => 500_f32,+ "K" => 667_f32,+ "L" => 556_f32,+ "M" => 833_f32,+ "N" => 722_f32,+ "O" => 778_f32,+ "P" => 667_f32,+ "Q" => 778_f32,+ "R" => 722_f32,+ "S" => 667_f32,+ "T" => 611_f32,+ "U" => 722_f32,+ "V" => 667_f32,+ "W" => 944_f32,+ "X" => 667_f32,+ "Y" => 667_f32,+ "Z" => 611_f32,+ "bracketleft" => 278_f32,+ "backslash" => 278_f32,+ "bracketright" => 278_f32,+ "asciicircum" => 469_f32,+ "underscore" => 556_f32,+ "quoteleft" => 222_f32,+ "a" => 556_f32,+ "b" => 556_f32,+ "c" => 500_f32,+ "d" => 556_f32,+ "e" => 556_f32,+ "f" => 278_f32,+ "g" => 556_f32,+ "h" => 556_f32,+ "i" => 222_f32,+ "j" => 222_f32,+ "k" => 500_f32,+ "l" => 222_f32,+ "m" => 833_f32,+ "n" => 556_f32,+ "o" => 556_f32,+ "p" => 556_f32,+ "q" => 556_f32,+ "r" => 333_f32,+ "s" => 500_f32,+ "t" => 278_f32,+ "u" => 556_f32,+ "v" => 500_f32,+ "w" => 722_f32,+ "x" => 500_f32,+ "y" => 500_f32,+ "z" => 500_f32,+ "braceleft" => 334_f32,+ "bar" => 260_f32,+ "braceright" => 334_f32,+ "asciitilde" => 584_f32,+ "exclamdown" => 333_f32,+ "cent" => 556_f32,+ "sterling" => 556_f32,+ "fraction" => 167_f32,+ "yen" => 556_f32,+ "florin" => 556_f32,+ "section" => 556_f32,+ "currency" => 556_f32,+ "quotesingle" => 191_f32,+ "quotedblleft" => 333_f32,+ "guillemotleft" => 556_f32,+ "guilsinglleft" => 333_f32,+ "guilsinglright" => 333_f32,+ "fi" => 500_f32,+ "fl" => 500_f32,+ "endash" => 556_f32,+ "dagger" => 556_f32,+ "daggerdbl" => 556_f32,+ "periodcentered" => 278_f32,+ "paragraph" => 537_f32,+ "bullet" => 350_f32,+ "quotesinglbase" => 222_f32,+ "quotedblbase" => 333_f32,+ "quotedblright" => 333_f32,+ "guillemotright" => 556_f32,+ "ellipsis" => 1000_f32,+ "perthousand" => 1000_f32,+ "questiondown" => 611_f32,+ "grave" => 333_f32,+ "acute" => 333_f32,+ "circumflex" => 333_f32,+ "tilde" => 333_f32,+ "macron" => 333_f32,+ "breve" => 333_f32,+ "dotaccent" => 333_f32,+ "dieresis" => 333_f32,+ "ring" => 333_f32,+ "cedilla" => 333_f32,+ "hungarumlaut" => 333_f32,+ "ogonek" => 333_f32,+ "caron" => 333_f32,+ "emdash" => 1000_f32,+ "AE" => 1000_f32,+ "ordfeminine" => 370_f32,+ "Lslash" => 556_f32,+ "Oslash" => 778_f32,+ "OE" => 1000_f32,+ "ordmasculine" => 365_f32,+ "ae" => 889_f32,+ "dotlessi" => 278_f32,+ "lslash" => 222_f32,+ "oslash" => 611_f32,+ "oe" => 944_f32,+ "germandbls" => 611_f32,+ "Idieresis" => 278_f32,+ "eacute" => 556_f32,+ "abreve" => 556_f32,+ "uhungarumlaut" => 556_f32,+ "ecaron" => 556_f32,+ "Ydieresis" => 667_f32,+ "divide" => 584_f32,+ "Yacute" => 667_f32,+ "Acircumflex" => 667_f32,+ "aacute" => 556_f32,+ "Ucircumflex" => 722_f32,+ "yacute" => 500_f32,+ "scommaaccent" => 500_f32,+ "ecircumflex" => 556_f32,+ "Uring" => 722_f32,+ "Udieresis" => 722_f32,+ "aogonek" => 556_f32,+ "Uacute" => 722_f32,+ "uogonek" => 556_f32,+ "Edieresis" => 667_f32,+ "Dcroat" => 722_f32,+ "commaaccent" => 250_f32,+ "copyright" => 737_f32,+ "Emacron" => 667_f32,+ "ccaron" => 500_f32,+ "aring" => 556_f32,+ "Ncommaaccent" => 722_f32,+ "lacute" => 222_f32,+ "agrave" => 556_f32,+ "Tcommaaccent" => 611_f32,+ "Cacute" => 722_f32,+ "atilde" => 556_f32,+ "Edotaccent" => 667_f32,+ "scaron" => 500_f32,+ "scedilla" => 500_f32,+ "iacute" => 278_f32,+ "lozenge" => 471_f32,+ "Rcaron" => 722_f32,+ "Gcommaaccent" => 778_f32,+ "ucircumflex" => 556_f32,+ "acircumflex" => 556_f32,+ "Amacron" => 667_f32,+ "rcaron" => 333_f32,+ "ccedilla" => 500_f32,+ "Zdotaccent" => 611_f32,+ "Thorn" => 667_f32,+ "Omacron" => 778_f32,+ "Racute" => 722_f32,+ "Sacute" => 667_f32,+ "dcaron" => 643_f32,+ "Umacron" => 722_f32,+ "uring" => 556_f32,+ "threesuperior" => 333_f32,+ "Ograve" => 778_f32,+ "Agrave" => 667_f32,+ "Abreve" => 667_f32,+ "multiply" => 584_f32,+ "uacute" => 556_f32,+ "Tcaron" => 611_f32,+ "partialdiff" => 476_f32,+ "ydieresis" => 500_f32,+ "Nacute" => 722_f32,+ "icircumflex" => 278_f32,+ "Ecircumflex" => 667_f32,+ "adieresis" => 556_f32,+ "edieresis" => 556_f32,+ "cacute" => 500_f32,+ "nacute" => 556_f32,+ "umacron" => 556_f32,+ "Ncaron" => 722_f32,+ "Iacute" => 278_f32,+ "plusminus" => 584_f32,+ "brokenbar" => 260_f32,+ "registered" => 737_f32,+ "Gbreve" => 778_f32,+ "Idotaccent" => 278_f32,+ "summation" => 600_f32,+ "Egrave" => 667_f32,+ "racute" => 333_f32,+ "omacron" => 556_f32,+ "Zacute" => 611_f32,+ "Zcaron" => 611_f32,+ "greaterequal" => 549_f32,+ "Eth" => 722_f32,+ "Ccedilla" => 722_f32,+ "lcommaaccent" => 222_f32,+ "tcaron" => 317_f32,+ "eogonek" => 556_f32,+ "Uogonek" => 722_f32,+ "Aacute" => 667_f32,+ "Adieresis" => 667_f32,+ "egrave" => 556_f32,+ "zacute" => 500_f32,+ "iogonek" => 222_f32,+ "Oacute" => 778_f32,+ "oacute" => 556_f32,+ "amacron" => 556_f32,+ "sacute" => 500_f32,+ "idieresis" => 278_f32,+ "Ocircumflex" => 778_f32,+ "Ugrave" => 722_f32,+ "Delta" => 612_f32,+ "thorn" => 556_f32,+ "twosuperior" => 333_f32,+ "Odieresis" => 778_f32,+ "mu" => 556_f32,+ "igrave" => 278_f32,+ "ohungarumlaut" => 556_f32,+ "Eogonek" => 667_f32,+ "dcroat" => 556_f32,+ "threequarters" => 834_f32,+ "Scedilla" => 667_f32,+ "lcaron" => 299_f32,+ "Kcommaaccent" => 667_f32,+ "Lacute" => 556_f32,+ "trademark" => 1000_f32,+ "edotaccent" => 556_f32,+ "Igrave" => 278_f32,+ "Imacron" => 278_f32,+ "Lcaron" => 556_f32,+ "onehalf" => 834_f32,+ "lessequal" => 549_f32,+ "ocircumflex" => 556_f32,+ "ntilde" => 556_f32,+ "Uhungarumlaut" => 722_f32,+ "Eacute" => 667_f32,+ "emacron" => 556_f32,+ "gbreve" => 556_f32,+ "onequarter" => 834_f32,+ "Scaron" => 667_f32,+ "Scommaaccent" => 667_f32,+ "Ohungarumlaut" => 778_f32,+ "degree" => 400_f32,+ "ograve" => 556_f32,+ "Ccaron" => 722_f32,+ "ugrave" => 556_f32,+ "radical" => 453_f32,+ "Dcaron" => 722_f32,+ "rcommaaccent" => 333_f32,+ "Ntilde" => 722_f32,+ "otilde" => 556_f32,+ "Rcommaaccent" => 722_f32,+ "Lcommaaccent" => 556_f32,+ "Atilde" => 667_f32,+ "Aogonek" => 667_f32,+ "Aring" => 667_f32,+ "Otilde" => 778_f32,+ "zdotaccent" => 500_f32,+ "Ecaron" => 667_f32,+ "Iogonek" => 278_f32,+ "kcommaaccent" => 500_f32,+ "minus" => 584_f32,+ "Icircumflex" => 278_f32,+ "ncaron" => 556_f32,+ "tcommaaccent" => 278_f32,+ "logicalnot" => 584_f32,+ "odieresis" => 556_f32,+ "udieresis" => 556_f32,+ "notequal" => 549_f32,+ "gcommaaccent" => 556_f32,+ "eth" => 556_f32,+ "zcaron" => 500_f32,+ "ncommaaccent" => 556_f32,+ "onesuperior" => 333_f32,+ "imacron" => 278_f32,+ "Euro" => 556_f32,+};++pub(crate) static SYMBOL: phf::Map<&'static str, f32> = phf_map! {+ "space" => 250_f32,+ "exclam" => 333_f32,+ "universal" => 713_f32,+ "numbersign" => 500_f32,+ "existential" => 549_f32,+ "percent" => 833_f32,+ "ampersand" => 778_f32,+ "suchthat" => 439_f32,+ "parenleft" => 333_f32,+ "parenright" => 333_f32,+ "asteriskmath" => 500_f32,+ "plus" => 549_f32,+ "comma" => 250_f32,+ "minus" => 549_f32,+ "period" => 250_f32,+ "slash" => 278_f32,+ "zero" => 500_f32,+ "one" => 500_f32,+ "two" => 500_f32,+ "three" => 500_f32,+ "four" => 500_f32,+ "five" => 500_f32,+ "six" => 500_f32,+ "seven" => 500_f32,+ "eight" => 500_f32,+ "nine" => 500_f32,+ "colon" => 278_f32,+ "semicolon" => 278_f32,+ "less" => 549_f32,+ "equal" => 549_f32,+ "greater" => 549_f32,+ "question" => 444_f32,+ "congruent" => 549_f32,+ "Alpha" => 722_f32,+ "Beta" => 667_f32,+ "Chi" => 722_f32,+ "Delta" => 612_f32,+ "Epsilon" => 611_f32,+ "Phi" => 763_f32,+ "Gamma" => 603_f32,+ "Eta" => 722_f32,+ "Iota" => 333_f32,+ "theta1" => 631_f32,+ "Kappa" => 722_f32,+ "Lambda" => 686_f32,+ "Mu" => 889_f32,+ "Nu" => 722_f32,+ "Omicron" => 722_f32,+ "Pi" => 768_f32,+ "Theta" => 741_f32,+ "Rho" => 556_f32,+ "Sigma" => 592_f32,+ "Tau" => 611_f32,+ "Upsilon" => 690_f32,+ "sigma1" => 439_f32,+ "Omega" => 768_f32,+ "Xi" => 645_f32,+ "Psi" => 795_f32,+ "Zeta" => 611_f32,+ "bracketleft" => 333_f32,+ "therefore" => 863_f32,+ "bracketright" => 333_f32,+ "perpendicular" => 658_f32,+ "underscore" => 500_f32,+ "radicalex" => 500_f32,+ "alpha" => 631_f32,+ "beta" => 549_f32,+ "chi" => 549_f32,+ "delta" => 494_f32,+ "epsilon" => 439_f32,+ "phi" => 521_f32,+ "gamma" => 411_f32,+ "eta" => 603_f32,+ "iota" => 329_f32,+ "phi1" => 603_f32,+ "kappa" => 549_f32,+ "lambda" => 549_f32,+ "mu" => 576_f32,+ "nu" => 521_f32,+ "omicron" => 549_f32,+ "pi" => 549_f32,+ "theta" => 521_f32,+ "rho" => 549_f32,+ "sigma" => 603_f32,+ "tau" => 439_f32,+ "upsilon" => 576_f32,+ "omega1" => 713_f32,+ "omega" => 686_f32,+ "xi" => 493_f32,+ "psi" => 686_f32,+ "zeta" => 494_f32,+ "braceleft" => 480_f32,+ "bar" => 200_f32,+ "braceright" => 480_f32,+ "similar" => 549_f32,+ "Euro" => 750_f32,+ "Upsilon1" => 620_f32,+ "minute" => 247_f32,+ "lessequal" => 549_f32,+ "fraction" => 167_f32,+ "infinity" => 713_f32,+ "florin" => 500_f32,+ "club" => 753_f32,+ "diamond" => 753_f32,+ "heart" => 753_f32,+ "spade" => 753_f32,+ "arrowboth" => 1042_f32,+ "arrowleft" => 987_f32,+ "arrowup" => 603_f32,+ "arrowright" => 987_f32,+ "arrowdown" => 603_f32,+ "degree" => 400_f32,+ "plusminus" => 549_f32,+ "second" => 411_f32,+ "greaterequal" => 549_f32,+ "multiply" => 549_f32,+ "proportional" => 713_f32,+ "partialdiff" => 494_f32,+ "bullet" => 460_f32,+ "divide" => 549_f32,+ "notequal" => 549_f32,+ "equivalence" => 549_f32,+ "approxequal" => 549_f32,+ "ellipsis" => 1000_f32,+ "arrowvertex" => 603_f32,+ "arrowhorizex" => 1000_f32,+ "carriagereturn" => 658_f32,+ "aleph" => 823_f32,+ "Ifraktur" => 686_f32,+ "Rfraktur" => 795_f32,+ "weierstrass" => 987_f32,+ "circlemultiply" => 768_f32,+ "circleplus" => 768_f32,+ "emptyset" => 823_f32,+ "intersection" => 768_f32,+ "union" => 768_f32,+ "propersuperset" => 713_f32,+ "reflexsuperset" => 713_f32,+ "notsubset" => 713_f32,+ "propersubset" => 713_f32,+ "reflexsubset" => 713_f32,+ "element" => 713_f32,+ "notelement" => 713_f32,+ "angle" => 768_f32,+ "gradient" => 713_f32,+ "registerserif" => 790_f32,+ "copyrightserif" => 790_f32,+ "trademarkserif" => 890_f32,+ "product" => 823_f32,+ "radical" => 549_f32,+ "dotmath" => 250_f32,+ "logicalnot" => 713_f32,+ "logicaland" => 603_f32,+ "logicalor" => 603_f32,+ "arrowdblboth" => 1042_f32,+ "arrowdblleft" => 987_f32,+ "arrowdblup" => 603_f32,+ "arrowdblright" => 987_f32,+ "arrowdbldown" => 603_f32,+ "lozenge" => 494_f32,+ "angleleft" => 329_f32,+ "registersans" => 790_f32,+ "copyrightsans" => 790_f32,+ "trademarksans" => 786_f32,+ "summation" => 713_f32,+ "parenlefttp" => 384_f32,+ "parenleftex" => 384_f32,+ "parenleftbt" => 384_f32,+ "bracketlefttp" => 384_f32,+ "bracketleftex" => 384_f32,+ "bracketleftbt" => 384_f32,+ "bracelefttp" => 494_f32,+ "braceleftmid" => 494_f32,+ "braceleftbt" => 494_f32,+ "braceex" => 494_f32,+ "angleright" => 329_f32,+ "integral" => 274_f32,+ "integraltp" => 686_f32,+ "integralex" => 686_f32,+ "integralbt" => 686_f32,+ "parenrighttp" => 384_f32,+ "parenrightex" => 384_f32,+ "parenrightbt" => 384_f32,+ "bracketrighttp" => 384_f32,+ "bracketrightex" => 384_f32,+ "bracketrightbt" => 384_f32,+ "bracerighttp" => 494_f32,+ "bracerightmid" => 494_f32,+ "bracerightbt" => 494_f32,+ "apple" => 790_f32,+};++pub(crate) static TIMES_BOLD: phf::Map<&'static str, f32> = phf_map! {+ "space" => 250_f32,+ "exclam" => 333_f32,+ "quotedbl" => 555_f32,+ "numbersign" => 500_f32,+ "dollar" => 500_f32,+ "percent" => 1000_f32,+ "ampersand" => 833_f32,+ "quoteright" => 333_f32,+ "parenleft" => 333_f32,+ "parenright" => 333_f32,+ "asterisk" => 500_f32,+ "plus" => 570_f32,+ "comma" => 250_f32,+ "hyphen" => 333_f32,+ "period" => 250_f32,+ "slash" => 278_f32,+ "zero" => 500_f32,+ "one" => 500_f32,+ "two" => 500_f32,+ "three" => 500_f32,+ "four" => 500_f32,+ "five" => 500_f32,+ "six" => 500_f32,+ "seven" => 500_f32,+ "eight" => 500_f32,+ "nine" => 500_f32,+ "colon" => 333_f32,+ "semicolon" => 333_f32,+ "less" => 570_f32,+ "equal" => 570_f32,+ "greater" => 570_f32,+ "question" => 500_f32,+ "at" => 930_f32,+ "A" => 722_f32,+ "B" => 667_f32,+ "C" => 722_f32,+ "D" => 722_f32,+ "E" => 667_f32,+ "F" => 611_f32,+ "G" => 778_f32,+ "H" => 778_f32,+ "I" => 389_f32,+ "J" => 500_f32,+ "K" => 778_f32,+ "L" => 667_f32,+ "M" => 944_f32,+ "N" => 722_f32,+ "O" => 778_f32,+ "P" => 611_f32,+ "Q" => 778_f32,+ "R" => 722_f32,+ "S" => 556_f32,+ "T" => 667_f32,+ "U" => 722_f32,+ "V" => 722_f32,+ "W" => 1000_f32,+ "X" => 722_f32,+ "Y" => 722_f32,+ "Z" => 667_f32,+ "bracketleft" => 333_f32,+ "backslash" => 278_f32,+ "bracketright" => 333_f32,+ "asciicircum" => 581_f32,+ "underscore" => 500_f32,+ "quoteleft" => 333_f32,+ "a" => 500_f32,+ "b" => 556_f32,+ "c" => 444_f32,+ "d" => 556_f32,+ "e" => 444_f32,+ "f" => 333_f32,+ "g" => 500_f32,+ "h" => 556_f32,+ "i" => 278_f32,+ "j" => 333_f32,+ "k" => 556_f32,+ "l" => 278_f32,+ "m" => 833_f32,+ "n" => 556_f32,+ "o" => 500_f32,+ "p" => 556_f32,+ "q" => 556_f32,+ "r" => 444_f32,+ "s" => 389_f32,+ "t" => 333_f32,+ "u" => 556_f32,+ "v" => 500_f32,+ "w" => 722_f32,+ "x" => 500_f32,+ "y" => 500_f32,+ "z" => 444_f32,+ "braceleft" => 394_f32,+ "bar" => 220_f32,+ "braceright" => 394_f32,+ "asciitilde" => 520_f32,+ "exclamdown" => 333_f32,+ "cent" => 500_f32,+ "sterling" => 500_f32,+ "fraction" => 167_f32,+ "yen" => 500_f32,+ "florin" => 500_f32,+ "section" => 500_f32,+ "currency" => 500_f32,+ "quotesingle" => 278_f32,+ "quotedblleft" => 500_f32,+ "guillemotleft" => 500_f32,+ "guilsinglleft" => 333_f32,+ "guilsinglright" => 333_f32,+ "fi" => 556_f32,+ "fl" => 556_f32,+ "endash" => 500_f32,+ "dagger" => 500_f32,+ "daggerdbl" => 500_f32,+ "periodcentered" => 250_f32,+ "paragraph" => 540_f32,+ "bullet" => 350_f32,+ "quotesinglbase" => 333_f32,+ "quotedblbase" => 500_f32,+ "quotedblright" => 500_f32,+ "guillemotright" => 500_f32,+ "ellipsis" => 1000_f32,+ "perthousand" => 1000_f32,+ "questiondown" => 500_f32,+ "grave" => 333_f32,+ "acute" => 333_f32,+ "circumflex" => 333_f32,+ "tilde" => 333_f32,+ "macron" => 333_f32,+ "breve" => 333_f32,+ "dotaccent" => 333_f32,+ "dieresis" => 333_f32,+ "ring" => 333_f32,+ "cedilla" => 333_f32,+ "hungarumlaut" => 333_f32,+ "ogonek" => 333_f32,+ "caron" => 333_f32,+ "emdash" => 1000_f32,+ "AE" => 1000_f32,+ "ordfeminine" => 300_f32,+ "Lslash" => 667_f32,+ "Oslash" => 778_f32,+ "OE" => 1000_f32,+ "ordmasculine" => 330_f32,+ "ae" => 722_f32,+ "dotlessi" => 278_f32,+ "lslash" => 278_f32,+ "oslash" => 500_f32,+ "oe" => 722_f32,+ "germandbls" => 556_f32,+ "Idieresis" => 389_f32,+ "eacute" => 444_f32,+ "abreve" => 500_f32,+ "uhungarumlaut" => 556_f32,+ "ecaron" => 444_f32,+ "Ydieresis" => 722_f32,+ "divide" => 570_f32,+ "Yacute" => 722_f32,+ "Acircumflex" => 722_f32,+ "aacute" => 500_f32,+ "Ucircumflex" => 722_f32,+ "yacute" => 500_f32,+ "scommaaccent" => 389_f32,+ "ecircumflex" => 444_f32,+ "Uring" => 722_f32,+ "Udieresis" => 722_f32,+ "aogonek" => 500_f32,+ "Uacute" => 722_f32,+ "uogonek" => 556_f32,+ "Edieresis" => 667_f32,+ "Dcroat" => 722_f32,+ "commaaccent" => 250_f32,+ "copyright" => 747_f32,+ "Emacron" => 667_f32,+ "ccaron" => 444_f32,+ "aring" => 500_f32,+ "Ncommaaccent" => 722_f32,+ "lacute" => 278_f32,+ "agrave" => 500_f32,+ "Tcommaaccent" => 667_f32,+ "Cacute" => 722_f32,+ "atilde" => 500_f32,+ "Edotaccent" => 667_f32,+ "scaron" => 389_f32,+ "scedilla" => 389_f32,+ "iacute" => 278_f32,+ "lozenge" => 494_f32,+ "Rcaron" => 722_f32,+ "Gcommaaccent" => 778_f32,+ "ucircumflex" => 556_f32,+ "acircumflex" => 500_f32,+ "Amacron" => 722_f32,+ "rcaron" => 444_f32,+ "ccedilla" => 444_f32,+ "Zdotaccent" => 667_f32,+ "Thorn" => 611_f32,+ "Omacron" => 778_f32,+ "Racute" => 722_f32,+ "Sacute" => 556_f32,+ "dcaron" => 672_f32,+ "Umacron" => 722_f32,+ "uring" => 556_f32,+ "threesuperior" => 300_f32,+ "Ograve" => 778_f32,+ "Agrave" => 722_f32,+ "Abreve" => 722_f32,+ "multiply" => 570_f32,+ "uacute" => 556_f32,+ "Tcaron" => 667_f32,+ "partialdiff" => 494_f32,+ "ydieresis" => 500_f32,+ "Nacute" => 722_f32,+ "icircumflex" => 278_f32,+ "Ecircumflex" => 667_f32,+ "adieresis" => 500_f32,+ "edieresis" => 444_f32,+ "cacute" => 444_f32,+ "nacute" => 556_f32,+ "umacron" => 556_f32,+ "Ncaron" => 722_f32,+ "Iacute" => 389_f32,+ "plusminus" => 570_f32,+ "brokenbar" => 220_f32,+ "registered" => 747_f32,+ "Gbreve" => 778_f32,+ "Idotaccent" => 389_f32,+ "summation" => 600_f32,+ "Egrave" => 667_f32,+ "racute" => 444_f32,+ "omacron" => 500_f32,+ "Zacute" => 667_f32,+ "Zcaron" => 667_f32,+ "greaterequal" => 549_f32,+ "Eth" => 722_f32,+ "Ccedilla" => 722_f32,+ "lcommaaccent" => 278_f32,+ "tcaron" => 416_f32,+ "eogonek" => 444_f32,+ "Uogonek" => 722_f32,+ "Aacute" => 722_f32,+ "Adieresis" => 722_f32,+ "egrave" => 444_f32,+ "zacute" => 444_f32,+ "iogonek" => 278_f32,+ "Oacute" => 778_f32,+ "oacute" => 500_f32,+ "amacron" => 500_f32,+ "sacute" => 389_f32,+ "idieresis" => 278_f32,+ "Ocircumflex" => 778_f32,+ "Ugrave" => 722_f32,+ "Delta" => 612_f32,+ "thorn" => 556_f32,+ "twosuperior" => 300_f32,+ "Odieresis" => 778_f32,+ "mu" => 556_f32,+ "igrave" => 278_f32,+ "ohungarumlaut" => 500_f32,+ "Eogonek" => 667_f32,+ "dcroat" => 556_f32,+ "threequarters" => 750_f32,+ "Scedilla" => 556_f32,+ "lcaron" => 394_f32,+ "Kcommaaccent" => 778_f32,+ "Lacute" => 667_f32,+ "trademark" => 1000_f32,+ "edotaccent" => 444_f32,+ "Igrave" => 389_f32,+ "Imacron" => 389_f32,+ "Lcaron" => 667_f32,+ "onehalf" => 750_f32,+ "lessequal" => 549_f32,+ "ocircumflex" => 500_f32,+ "ntilde" => 556_f32,+ "Uhungarumlaut" => 722_f32,+ "Eacute" => 667_f32,+ "emacron" => 444_f32,+ "gbreve" => 500_f32,+ "onequarter" => 750_f32,+ "Scaron" => 556_f32,+ "Scommaaccent" => 556_f32,+ "Ohungarumlaut" => 778_f32,+ "degree" => 400_f32,+ "ograve" => 500_f32,+ "Ccaron" => 722_f32,+ "ugrave" => 556_f32,+ "radical" => 549_f32,+ "Dcaron" => 722_f32,+ "rcommaaccent" => 444_f32,+ "Ntilde" => 722_f32,+ "otilde" => 500_f32,+ "Rcommaaccent" => 722_f32,+ "Lcommaaccent" => 667_f32,+ "Atilde" => 722_f32,+ "Aogonek" => 722_f32,+ "Aring" => 722_f32,+ "Otilde" => 778_f32,+ "zdotaccent" => 444_f32,+ "Ecaron" => 667_f32,+ "Iogonek" => 389_f32,+ "kcommaaccent" => 556_f32,+ "minus" => 570_f32,+ "Icircumflex" => 389_f32,+ "ncaron" => 556_f32,+ "tcommaaccent" => 333_f32,+ "logicalnot" => 570_f32,+ "odieresis" => 500_f32,+ "udieresis" => 556_f32,+ "notequal" => 549_f32,+ "gcommaaccent" => 500_f32,+ "eth" => 500_f32,+ "zcaron" => 444_f32,+ "ncommaaccent" => 556_f32,+ "onesuperior" => 300_f32,+ "imacron" => 278_f32,+ "Euro" => 500_f32,+};++pub(crate) static TIMES_BOLD_ITALIC: phf::Map<&'static str, f32> = phf_map! {+ "space" => 250_f32,+ "exclam" => 389_f32,+ "quotedbl" => 555_f32,+ "numbersign" => 500_f32,+ "dollar" => 500_f32,+ "percent" => 833_f32,+ "ampersand" => 778_f32,+ "quoteright" => 333_f32,+ "parenleft" => 333_f32,+ "parenright" => 333_f32,+ "asterisk" => 500_f32,+ "plus" => 570_f32,+ "comma" => 250_f32,+ "hyphen" => 333_f32,+ "period" => 250_f32,+ "slash" => 278_f32,+ "zero" => 500_f32,+ "one" => 500_f32,+ "two" => 500_f32,+ "three" => 500_f32,+ "four" => 500_f32,+ "five" => 500_f32,+ "six" => 500_f32,+ "seven" => 500_f32,+ "eight" => 500_f32,+ "nine" => 500_f32,+ "colon" => 333_f32,+ "semicolon" => 333_f32,+ "less" => 570_f32,+ "equal" => 570_f32,+ "greater" => 570_f32,+ "question" => 500_f32,+ "at" => 832_f32,+ "A" => 667_f32,+ "B" => 667_f32,+ "C" => 667_f32,+ "D" => 722_f32,+ "E" => 667_f32,+ "F" => 667_f32,+ "G" => 722_f32,+ "H" => 778_f32,+ "I" => 389_f32,+ "J" => 500_f32,+ "K" => 667_f32,+ "L" => 611_f32,+ "M" => 889_f32,+ "N" => 722_f32,+ "O" => 722_f32,+ "P" => 611_f32,+ "Q" => 722_f32,+ "R" => 667_f32,+ "S" => 556_f32,+ "T" => 611_f32,+ "U" => 722_f32,+ "V" => 667_f32,+ "W" => 889_f32,+ "X" => 667_f32,+ "Y" => 611_f32,+ "Z" => 611_f32,+ "bracketleft" => 333_f32,+ "backslash" => 278_f32,+ "bracketright" => 333_f32,+ "asciicircum" => 570_f32,+ "underscore" => 500_f32,+ "quoteleft" => 333_f32,+ "a" => 500_f32,+ "b" => 500_f32,+ "c" => 444_f32,+ "d" => 500_f32,+ "e" => 444_f32,+ "f" => 333_f32,+ "g" => 500_f32,+ "h" => 556_f32,+ "i" => 278_f32,+ "j" => 278_f32,+ "k" => 500_f32,+ "l" => 278_f32,+ "m" => 778_f32,+ "n" => 556_f32,+ "o" => 500_f32,+ "p" => 500_f32,+ "q" => 500_f32,+ "r" => 389_f32,+ "s" => 389_f32,+ "t" => 278_f32,+ "u" => 556_f32,+ "v" => 444_f32,+ "w" => 667_f32,+ "x" => 500_f32,+ "y" => 444_f32,+ "z" => 389_f32,+ "braceleft" => 348_f32,+ "bar" => 220_f32,+ "braceright" => 348_f32,+ "asciitilde" => 570_f32,+ "exclamdown" => 389_f32,+ "cent" => 500_f32,+ "sterling" => 500_f32,+ "fraction" => 167_f32,+ "yen" => 500_f32,+ "florin" => 500_f32,+ "section" => 500_f32,+ "currency" => 500_f32,+ "quotesingle" => 278_f32,+ "quotedblleft" => 500_f32,+ "guillemotleft" => 500_f32,+ "guilsinglleft" => 333_f32,+ "guilsinglright" => 333_f32,+ "fi" => 556_f32,+ "fl" => 556_f32,+ "endash" => 500_f32,+ "dagger" => 500_f32,+ "daggerdbl" => 500_f32,+ "periodcentered" => 250_f32,+ "paragraph" => 500_f32,+ "bullet" => 350_f32,+ "quotesinglbase" => 333_f32,+ "quotedblbase" => 500_f32,+ "quotedblright" => 500_f32,+ "guillemotright" => 500_f32,+ "ellipsis" => 1000_f32,+ "perthousand" => 1000_f32,+ "questiondown" => 500_f32,+ "grave" => 333_f32,+ "acute" => 333_f32,+ "circumflex" => 333_f32,+ "tilde" => 333_f32,+ "macron" => 333_f32,+ "breve" => 333_f32,+ "dotaccent" => 333_f32,+ "dieresis" => 333_f32,+ "ring" => 333_f32,+ "cedilla" => 333_f32,+ "hungarumlaut" => 333_f32,+ "ogonek" => 333_f32,+ "caron" => 333_f32,+ "emdash" => 1000_f32,+ "AE" => 944_f32,+ "ordfeminine" => 266_f32,+ "Lslash" => 611_f32,+ "Oslash" => 722_f32,+ "OE" => 944_f32,+ "ordmasculine" => 300_f32,+ "ae" => 722_f32,+ "dotlessi" => 278_f32,+ "lslash" => 278_f32,+ "oslash" => 500_f32,+ "oe" => 722_f32,+ "germandbls" => 500_f32,+ "Idieresis" => 389_f32,+ "eacute" => 444_f32,+ "abreve" => 500_f32,+ "uhungarumlaut" => 556_f32,+ "ecaron" => 444_f32,+ "Ydieresis" => 611_f32,+ "divide" => 570_f32,+ "Yacute" => 611_f32,+ "Acircumflex" => 667_f32,+ "aacute" => 500_f32,+ "Ucircumflex" => 722_f32,+ "yacute" => 444_f32,+ "scommaaccent" => 389_f32,+ "ecircumflex" => 444_f32,+ "Uring" => 722_f32,+ "Udieresis" => 722_f32,+ "aogonek" => 500_f32,+ "Uacute" => 722_f32,+ "uogonek" => 556_f32,+ "Edieresis" => 667_f32,+ "Dcroat" => 722_f32,+ "commaaccent" => 250_f32,+ "copyright" => 747_f32,+ "Emacron" => 667_f32,+ "ccaron" => 444_f32,+ "aring" => 500_f32,+ "Ncommaaccent" => 722_f32,+ "lacute" => 278_f32,+ "agrave" => 500_f32,+ "Tcommaaccent" => 611_f32,+ "Cacute" => 667_f32,+ "atilde" => 500_f32,+ "Edotaccent" => 667_f32,+ "scaron" => 389_f32,+ "scedilla" => 389_f32,+ "iacute" => 278_f32,+ "lozenge" => 494_f32,+ "Rcaron" => 667_f32,+ "Gcommaaccent" => 722_f32,+ "ucircumflex" => 556_f32,+ "acircumflex" => 500_f32,+ "Amacron" => 667_f32,+ "rcaron" => 389_f32,+ "ccedilla" => 444_f32,+ "Zdotaccent" => 611_f32,+ "Thorn" => 611_f32,+ "Omacron" => 722_f32,+ "Racute" => 667_f32,+ "Sacute" => 556_f32,+ "dcaron" => 608_f32,+ "Umacron" => 722_f32,+ "uring" => 556_f32,+ "threesuperior" => 300_f32,+ "Ograve" => 722_f32,+ "Agrave" => 667_f32,+ "Abreve" => 667_f32,+ "multiply" => 570_f32,+ "uacute" => 556_f32,+ "Tcaron" => 611_f32,+ "partialdiff" => 494_f32,+ "ydieresis" => 444_f32,+ "Nacute" => 722_f32,+ "icircumflex" => 278_f32,+ "Ecircumflex" => 667_f32,+ "adieresis" => 500_f32,+ "edieresis" => 444_f32,+ "cacute" => 444_f32,+ "nacute" => 556_f32,+ "umacron" => 556_f32,+ "Ncaron" => 722_f32,+ "Iacute" => 389_f32,+ "plusminus" => 570_f32,+ "brokenbar" => 220_f32,+ "registered" => 747_f32,+ "Gbreve" => 722_f32,+ "Idotaccent" => 389_f32,+ "summation" => 600_f32,+ "Egrave" => 667_f32,+ "racute" => 389_f32,+ "omacron" => 500_f32,+ "Zacute" => 611_f32,+ "Zcaron" => 611_f32,+ "greaterequal" => 549_f32,+ "Eth" => 722_f32,+ "Ccedilla" => 667_f32,+ "lcommaaccent" => 278_f32,+ "tcaron" => 366_f32,+ "eogonek" => 444_f32,+ "Uogonek" => 722_f32,+ "Aacute" => 667_f32,+ "Adieresis" => 667_f32,+ "egrave" => 444_f32,+ "zacute" => 389_f32,+ "iogonek" => 278_f32,+ "Oacute" => 722_f32,+ "oacute" => 500_f32,+ "amacron" => 500_f32,+ "sacute" => 389_f32,+ "idieresis" => 278_f32,+ "Ocircumflex" => 722_f32,+ "Ugrave" => 722_f32,+ "Delta" => 612_f32,+ "thorn" => 500_f32,+ "twosuperior" => 300_f32,+ "Odieresis" => 722_f32,+ "mu" => 576_f32,+ "igrave" => 278_f32,+ "ohungarumlaut" => 500_f32,+ "Eogonek" => 667_f32,+ "dcroat" => 500_f32,+ "threequarters" => 750_f32,+ "Scedilla" => 556_f32,+ "lcaron" => 382_f32,+ "Kcommaaccent" => 667_f32,+ "Lacute" => 611_f32,+ "trademark" => 1000_f32,+ "edotaccent" => 444_f32,+ "Igrave" => 389_f32,+ "Imacron" => 389_f32,+ "Lcaron" => 611_f32,+ "onehalf" => 750_f32,+ "lessequal" => 549_f32,+ "ocircumflex" => 500_f32,+ "ntilde" => 556_f32,+ "Uhungarumlaut" => 722_f32,+ "Eacute" => 667_f32,+ "emacron" => 444_f32,+ "gbreve" => 500_f32,+ "onequarter" => 750_f32,+ "Scaron" => 556_f32,+ "Scommaaccent" => 556_f32,+ "Ohungarumlaut" => 722_f32,+ "degree" => 400_f32,+ "ograve" => 500_f32,+ "Ccaron" => 667_f32,+ "ugrave" => 556_f32,+ "radical" => 549_f32,+ "Dcaron" => 722_f32,+ "rcommaaccent" => 389_f32,+ "Ntilde" => 722_f32,+ "otilde" => 500_f32,+ "Rcommaaccent" => 667_f32,+ "Lcommaaccent" => 611_f32,+ "Atilde" => 667_f32,+ "Aogonek" => 667_f32,+ "Aring" => 667_f32,+ "Otilde" => 722_f32,+ "zdotaccent" => 389_f32,+ "Ecaron" => 667_f32,+ "Iogonek" => 389_f32,+ "kcommaaccent" => 500_f32,+ "minus" => 606_f32,+ "Icircumflex" => 389_f32,+ "ncaron" => 556_f32,+ "tcommaaccent" => 278_f32,+ "logicalnot" => 606_f32,+ "odieresis" => 500_f32,+ "udieresis" => 556_f32,+ "notequal" => 549_f32,+ "gcommaaccent" => 500_f32,+ "eth" => 500_f32,+ "zcaron" => 389_f32,+ "ncommaaccent" => 556_f32,+ "onesuperior" => 300_f32,+ "imacron" => 278_f32,+ "Euro" => 500_f32,+};++pub(crate) static TIMES_ITALIC: phf::Map<&'static str, f32> = phf_map! {+ "space" => 250_f32,+ "exclam" => 333_f32,+ "quotedbl" => 420_f32,+ "numbersign" => 500_f32,+ "dollar" => 500_f32,+ "percent" => 833_f32,+ "ampersand" => 778_f32,+ "quoteright" => 333_f32,+ "parenleft" => 333_f32,+ "parenright" => 333_f32,+ "asterisk" => 500_f32,+ "plus" => 675_f32,+ "comma" => 250_f32,+ "hyphen" => 333_f32,+ "period" => 250_f32,+ "slash" => 278_f32,+ "zero" => 500_f32,+ "one" => 500_f32,+ "two" => 500_f32,+ "three" => 500_f32,+ "four" => 500_f32,+ "five" => 500_f32,+ "six" => 500_f32,+ "seven" => 500_f32,+ "eight" => 500_f32,+ "nine" => 500_f32,+ "colon" => 333_f32,+ "semicolon" => 333_f32,+ "less" => 675_f32,+ "equal" => 675_f32,+ "greater" => 675_f32,+ "question" => 500_f32,+ "at" => 920_f32,+ "A" => 611_f32,+ "B" => 611_f32,+ "C" => 667_f32,+ "D" => 722_f32,+ "E" => 611_f32,+ "F" => 611_f32,+ "G" => 722_f32,+ "H" => 722_f32,+ "I" => 333_f32,+ "J" => 444_f32,+ "K" => 667_f32,+ "L" => 556_f32,+ "M" => 833_f32,+ "N" => 667_f32,+ "O" => 722_f32,+ "P" => 611_f32,+ "Q" => 722_f32,+ "R" => 611_f32,+ "S" => 500_f32,+ "T" => 556_f32,+ "U" => 722_f32,+ "V" => 611_f32,+ "W" => 833_f32,+ "X" => 611_f32,+ "Y" => 556_f32,+ "Z" => 556_f32,+ "bracketleft" => 389_f32,+ "backslash" => 278_f32,+ "bracketright" => 389_f32,+ "asciicircum" => 422_f32,+ "underscore" => 500_f32,+ "quoteleft" => 333_f32,+ "a" => 500_f32,+ "b" => 500_f32,+ "c" => 444_f32,+ "d" => 500_f32,+ "e" => 444_f32,+ "f" => 278_f32,+ "g" => 500_f32,+ "h" => 500_f32,+ "i" => 278_f32,+ "j" => 278_f32,+ "k" => 444_f32,+ "l" => 278_f32,+ "m" => 722_f32,+ "n" => 500_f32,+ "o" => 500_f32,+ "p" => 500_f32,+ "q" => 500_f32,+ "r" => 389_f32,+ "s" => 389_f32,+ "t" => 278_f32,+ "u" => 500_f32,+ "v" => 444_f32,+ "w" => 667_f32,+ "x" => 444_f32,+ "y" => 444_f32,+ "z" => 389_f32,+ "braceleft" => 400_f32,+ "bar" => 275_f32,+ "braceright" => 400_f32,+ "asciitilde" => 541_f32,+ "exclamdown" => 389_f32,+ "cent" => 500_f32,+ "sterling" => 500_f32,+ "fraction" => 167_f32,+ "yen" => 500_f32,+ "florin" => 500_f32,+ "section" => 500_f32,+ "currency" => 500_f32,+ "quotesingle" => 214_f32,+ "quotedblleft" => 556_f32,+ "guillemotleft" => 500_f32,+ "guilsinglleft" => 333_f32,+ "guilsinglright" => 333_f32,+ "fi" => 500_f32,+ "fl" => 500_f32,+ "endash" => 500_f32,+ "dagger" => 500_f32,+ "daggerdbl" => 500_f32,+ "periodcentered" => 250_f32,+ "paragraph" => 523_f32,+ "bullet" => 350_f32,+ "quotesinglbase" => 333_f32,+ "quotedblbase" => 556_f32,+ "quotedblright" => 556_f32,+ "guillemotright" => 500_f32,+ "ellipsis" => 889_f32,+ "perthousand" => 1000_f32,+ "questiondown" => 500_f32,+ "grave" => 333_f32,+ "acute" => 333_f32,+ "circumflex" => 333_f32,+ "tilde" => 333_f32,+ "macron" => 333_f32,+ "breve" => 333_f32,+ "dotaccent" => 333_f32,+ "dieresis" => 333_f32,+ "ring" => 333_f32,+ "cedilla" => 333_f32,+ "hungarumlaut" => 333_f32,+ "ogonek" => 333_f32,+ "caron" => 333_f32,+ "emdash" => 889_f32,+ "AE" => 889_f32,+ "ordfeminine" => 276_f32,+ "Lslash" => 556_f32,+ "Oslash" => 722_f32,+ "OE" => 944_f32,+ "ordmasculine" => 310_f32,+ "ae" => 667_f32,+ "dotlessi" => 278_f32,+ "lslash" => 278_f32,+ "oslash" => 500_f32,+ "oe" => 667_f32,+ "germandbls" => 500_f32,+ "Idieresis" => 333_f32,+ "eacute" => 444_f32,+ "abreve" => 500_f32,+ "uhungarumlaut" => 500_f32,+ "ecaron" => 444_f32,+ "Ydieresis" => 556_f32,+ "divide" => 675_f32,+ "Yacute" => 556_f32,+ "Acircumflex" => 611_f32,+ "aacute" => 500_f32,+ "Ucircumflex" => 722_f32,+ "yacute" => 444_f32,+ "scommaaccent" => 389_f32,+ "ecircumflex" => 444_f32,+ "Uring" => 722_f32,+ "Udieresis" => 722_f32,+ "aogonek" => 500_f32,+ "Uacute" => 722_f32,+ "uogonek" => 500_f32,+ "Edieresis" => 611_f32,+ "Dcroat" => 722_f32,+ "commaaccent" => 250_f32,+ "copyright" => 760_f32,+ "Emacron" => 611_f32,+ "ccaron" => 444_f32,+ "aring" => 500_f32,+ "Ncommaaccent" => 667_f32,+ "lacute" => 278_f32,+ "agrave" => 500_f32,+ "Tcommaaccent" => 556_f32,+ "Cacute" => 667_f32,+ "atilde" => 500_f32,+ "Edotaccent" => 611_f32,+ "scaron" => 389_f32,+ "scedilla" => 389_f32,+ "iacute" => 278_f32,+ "lozenge" => 471_f32,+ "Rcaron" => 611_f32,+ "Gcommaaccent" => 722_f32,+ "ucircumflex" => 500_f32,+ "acircumflex" => 500_f32,+ "Amacron" => 611_f32,+ "rcaron" => 389_f32,+ "ccedilla" => 444_f32,+ "Zdotaccent" => 556_f32,+ "Thorn" => 611_f32,+ "Omacron" => 722_f32,+ "Racute" => 611_f32,+ "Sacute" => 500_f32,+ "dcaron" => 544_f32,+ "Umacron" => 722_f32,+ "uring" => 500_f32,+ "threesuperior" => 300_f32,+ "Ograve" => 722_f32,+ "Agrave" => 611_f32,+ "Abreve" => 611_f32,+ "multiply" => 675_f32,+ "uacute" => 500_f32,+ "Tcaron" => 556_f32,+ "partialdiff" => 476_f32,+ "ydieresis" => 444_f32,+ "Nacute" => 667_f32,+ "icircumflex" => 278_f32,+ "Ecircumflex" => 611_f32,+ "adieresis" => 500_f32,+ "edieresis" => 444_f32,+ "cacute" => 444_f32,+ "nacute" => 500_f32,+ "umacron" => 500_f32,+ "Ncaron" => 667_f32,+ "Iacute" => 333_f32,+ "plusminus" => 675_f32,+ "brokenbar" => 275_f32,+ "registered" => 760_f32,+ "Gbreve" => 722_f32,+ "Idotaccent" => 333_f32,+ "summation" => 600_f32,+ "Egrave" => 611_f32,+ "racute" => 389_f32,+ "omacron" => 500_f32,+ "Zacute" => 556_f32,+ "Zcaron" => 556_f32,+ "greaterequal" => 549_f32,+ "Eth" => 722_f32,+ "Ccedilla" => 667_f32,+ "lcommaaccent" => 278_f32,+ "tcaron" => 300_f32,+ "eogonek" => 444_f32,+ "Uogonek" => 722_f32,+ "Aacute" => 611_f32,+ "Adieresis" => 611_f32,+ "egrave" => 444_f32,+ "zacute" => 389_f32,+ "iogonek" => 278_f32,+ "Oacute" => 722_f32,+ "oacute" => 500_f32,+ "amacron" => 500_f32,+ "sacute" => 389_f32,+ "idieresis" => 278_f32,+ "Ocircumflex" => 722_f32,+ "Ugrave" => 722_f32,+ "Delta" => 612_f32,+ "thorn" => 500_f32,+ "twosuperior" => 300_f32,+ "Odieresis" => 722_f32,+ "mu" => 500_f32,+ "igrave" => 278_f32,+ "ohungarumlaut" => 500_f32,+ "Eogonek" => 611_f32,+ "dcroat" => 500_f32,+ "threequarters" => 750_f32,+ "Scedilla" => 500_f32,+ "lcaron" => 300_f32,+ "Kcommaaccent" => 667_f32,+ "Lacute" => 556_f32,+ "trademark" => 980_f32,+ "edotaccent" => 444_f32,+ "Igrave" => 333_f32,+ "Imacron" => 333_f32,+ "Lcaron" => 611_f32,+ "onehalf" => 750_f32,+ "lessequal" => 549_f32,+ "ocircumflex" => 500_f32,+ "ntilde" => 500_f32,+ "Uhungarumlaut" => 722_f32,+ "Eacute" => 611_f32,+ "emacron" => 444_f32,+ "gbreve" => 500_f32,+ "onequarter" => 750_f32,+ "Scaron" => 500_f32,+ "Scommaaccent" => 500_f32,+ "Ohungarumlaut" => 722_f32,+ "degree" => 400_f32,+ "ograve" => 500_f32,+ "Ccaron" => 667_f32,+ "ugrave" => 500_f32,+ "radical" => 453_f32,+ "Dcaron" => 722_f32,+ "rcommaaccent" => 389_f32,+ "Ntilde" => 667_f32,+ "otilde" => 500_f32,+ "Rcommaaccent" => 611_f32,+ "Lcommaaccent" => 556_f32,+ "Atilde" => 611_f32,+ "Aogonek" => 611_f32,+ "Aring" => 611_f32,+ "Otilde" => 722_f32,+ "zdotaccent" => 389_f32,+ "Ecaron" => 611_f32,+ "Iogonek" => 333_f32,+ "kcommaaccent" => 444_f32,+ "minus" => 675_f32,+ "Icircumflex" => 333_f32,+ "ncaron" => 500_f32,+ "tcommaaccent" => 278_f32,+ "logicalnot" => 675_f32,+ "odieresis" => 500_f32,+ "udieresis" => 500_f32,+ "notequal" => 549_f32,+ "gcommaaccent" => 500_f32,+ "eth" => 500_f32,+ "zcaron" => 389_f32,+ "ncommaaccent" => 500_f32,+ "onesuperior" => 300_f32,+ "imacron" => 278_f32,+ "Euro" => 500_f32,+};++pub(crate) static TIMES_ROMAN: phf::Map<&'static str, f32> = phf_map! {+ "space" => 250_f32,+ "exclam" => 333_f32,+ "quotedbl" => 408_f32,+ "numbersign" => 500_f32,+ "dollar" => 500_f32,+ "percent" => 833_f32,+ "ampersand" => 778_f32,+ "quoteright" => 333_f32,+ "parenleft" => 333_f32,+ "parenright" => 333_f32,+ "asterisk" => 500_f32,+ "plus" => 564_f32,+ "comma" => 250_f32,+ "hyphen" => 333_f32,+ "period" => 250_f32,+ "slash" => 278_f32,+ "zero" => 500_f32,+ "one" => 500_f32,+ "two" => 500_f32,+ "three" => 500_f32,+ "four" => 500_f32,+ "five" => 500_f32,+ "six" => 500_f32,+ "seven" => 500_f32,+ "eight" => 500_f32,+ "nine" => 500_f32,+ "colon" => 278_f32,+ "semicolon" => 278_f32,+ "less" => 564_f32,+ "equal" => 564_f32,+ "greater" => 564_f32,+ "question" => 444_f32,+ "at" => 921_f32,+ "A" => 722_f32,+ "B" => 667_f32,+ "C" => 667_f32,+ "D" => 722_f32,+ "E" => 611_f32,+ "F" => 556_f32,+ "G" => 722_f32,+ "H" => 722_f32,+ "I" => 333_f32,+ "J" => 389_f32,+ "K" => 722_f32,+ "L" => 611_f32,+ "M" => 889_f32,+ "N" => 722_f32,+ "O" => 722_f32,+ "P" => 556_f32,+ "Q" => 722_f32,+ "R" => 667_f32,+ "S" => 556_f32,+ "T" => 611_f32,+ "U" => 722_f32,+ "V" => 722_f32,+ "W" => 944_f32,+ "X" => 722_f32,+ "Y" => 722_f32,+ "Z" => 611_f32,+ "bracketleft" => 333_f32,+ "backslash" => 278_f32,+ "bracketright" => 333_f32,+ "asciicircum" => 469_f32,+ "underscore" => 500_f32,+ "quoteleft" => 333_f32,+ "a" => 444_f32,+ "b" => 500_f32,+ "c" => 444_f32,+ "d" => 500_f32,+ "e" => 444_f32,+ "f" => 333_f32,+ "g" => 500_f32,+ "h" => 500_f32,+ "i" => 278_f32,+ "j" => 278_f32,+ "k" => 500_f32,+ "l" => 278_f32,+ "m" => 778_f32,+ "n" => 500_f32,+ "o" => 500_f32,+ "p" => 500_f32,+ "q" => 500_f32,+ "r" => 333_f32,+ "s" => 389_f32,+ "t" => 278_f32,+ "u" => 500_f32,+ "v" => 500_f32,+ "w" => 722_f32,+ "x" => 500_f32,+ "y" => 500_f32,+ "z" => 444_f32,+ "braceleft" => 480_f32,+ "bar" => 200_f32,+ "braceright" => 480_f32,+ "asciitilde" => 541_f32,+ "exclamdown" => 333_f32,+ "cent" => 500_f32,+ "sterling" => 500_f32,+ "fraction" => 167_f32,+ "yen" => 500_f32,+ "florin" => 500_f32,+ "section" => 500_f32,+ "currency" => 500_f32,+ "quotesingle" => 180_f32,+ "quotedblleft" => 444_f32,+ "guillemotleft" => 500_f32,+ "guilsinglleft" => 333_f32,+ "guilsinglright" => 333_f32,+ "fi" => 556_f32,+ "fl" => 556_f32,+ "endash" => 500_f32,+ "dagger" => 500_f32,+ "daggerdbl" => 500_f32,+ "periodcentered" => 250_f32,+ "paragraph" => 453_f32,+ "bullet" => 350_f32,+ "quotesinglbase" => 333_f32,+ "quotedblbase" => 444_f32,+ "quotedblright" => 444_f32,+ "guillemotright" => 500_f32,+ "ellipsis" => 1000_f32,+ "perthousand" => 1000_f32,+ "questiondown" => 444_f32,+ "grave" => 333_f32,+ "acute" => 333_f32,+ "circumflex" => 333_f32,+ "tilde" => 333_f32,+ "macron" => 333_f32,+ "breve" => 333_f32,+ "dotaccent" => 333_f32,+ "dieresis" => 333_f32,+ "ring" => 333_f32,+ "cedilla" => 333_f32,+ "hungarumlaut" => 333_f32,+ "ogonek" => 333_f32,+ "caron" => 333_f32,+ "emdash" => 1000_f32,+ "AE" => 889_f32,+ "ordfeminine" => 276_f32,+ "Lslash" => 611_f32,+ "Oslash" => 722_f32,+ "OE" => 889_f32,+ "ordmasculine" => 310_f32,+ "ae" => 667_f32,+ "dotlessi" => 278_f32,+ "lslash" => 278_f32,+ "oslash" => 500_f32,+ "oe" => 722_f32,+ "germandbls" => 500_f32,+ "Idieresis" => 333_f32,+ "eacute" => 444_f32,+ "abreve" => 444_f32,+ "uhungarumlaut" => 500_f32,+ "ecaron" => 444_f32,+ "Ydieresis" => 722_f32,+ "divide" => 564_f32,+ "Yacute" => 722_f32,+ "Acircumflex" => 722_f32,+ "aacute" => 444_f32,+ "Ucircumflex" => 722_f32,+ "yacute" => 500_f32,+ "scommaaccent" => 389_f32,+ "ecircumflex" => 444_f32,+ "Uring" => 722_f32,+ "Udieresis" => 722_f32,+ "aogonek" => 444_f32,+ "Uacute" => 722_f32,+ "uogonek" => 500_f32,+ "Edieresis" => 611_f32,+ "Dcroat" => 722_f32,+ "commaaccent" => 250_f32,+ "copyright" => 760_f32,+ "Emacron" => 611_f32,+ "ccaron" => 444_f32,+ "aring" => 444_f32,+ "Ncommaaccent" => 722_f32,+ "lacute" => 278_f32,+ "agrave" => 444_f32,+ "Tcommaaccent" => 611_f32,+ "Cacute" => 667_f32,+ "atilde" => 444_f32,+ "Edotaccent" => 611_f32,+ "scaron" => 389_f32,+ "scedilla" => 389_f32,+ "iacute" => 278_f32,+ "lozenge" => 471_f32,+ "Rcaron" => 667_f32,+ "Gcommaaccent" => 722_f32,+ "ucircumflex" => 500_f32,+ "acircumflex" => 444_f32,+ "Amacron" => 722_f32,+ "rcaron" => 333_f32,+ "ccedilla" => 444_f32,+ "Zdotaccent" => 611_f32,+ "Thorn" => 556_f32,+ "Omacron" => 722_f32,+ "Racute" => 667_f32,+ "Sacute" => 556_f32,+ "dcaron" => 588_f32,+ "Umacron" => 722_f32,+ "uring" => 500_f32,+ "threesuperior" => 300_f32,+ "Ograve" => 722_f32,+ "Agrave" => 722_f32,+ "Abreve" => 722_f32,+ "multiply" => 564_f32,+ "uacute" => 500_f32,+ "Tcaron" => 611_f32,+ "partialdiff" => 476_f32,+ "ydieresis" => 500_f32,+ "Nacute" => 722_f32,+ "icircumflex" => 278_f32,+ "Ecircumflex" => 611_f32,+ "adieresis" => 444_f32,+ "edieresis" => 444_f32,+ "cacute" => 444_f32,+ "nacute" => 500_f32,+ "umacron" => 500_f32,+ "Ncaron" => 722_f32,+ "Iacute" => 333_f32,+ "plusminus" => 564_f32,+ "brokenbar" => 200_f32,+ "registered" => 760_f32,+ "Gbreve" => 722_f32,+ "Idotaccent" => 333_f32,+ "summation" => 600_f32,+ "Egrave" => 611_f32,+ "racute" => 333_f32,+ "omacron" => 500_f32,+ "Zacute" => 611_f32,+ "Zcaron" => 611_f32,+ "greaterequal" => 549_f32,+ "Eth" => 722_f32,+ "Ccedilla" => 667_f32,+ "lcommaaccent" => 278_f32,+ "tcaron" => 326_f32,+ "eogonek" => 444_f32,+ "Uogonek" => 722_f32,+ "Aacute" => 722_f32,+ "Adieresis" => 722_f32,+ "egrave" => 444_f32,+ "zacute" => 444_f32,+ "iogonek" => 278_f32,+ "Oacute" => 722_f32,+ "oacute" => 500_f32,+ "amacron" => 444_f32,+ "sacute" => 389_f32,+ "idieresis" => 278_f32,+ "Ocircumflex" => 722_f32,+ "Ugrave" => 722_f32,+ "Delta" => 612_f32,+ "thorn" => 500_f32,+ "twosuperior" => 300_f32,+ "Odieresis" => 722_f32,+ "mu" => 500_f32,+ "igrave" => 278_f32,+ "ohungarumlaut" => 500_f32,+ "Eogonek" => 611_f32,+ "dcroat" => 500_f32,+ "threequarters" => 750_f32,+ "Scedilla" => 556_f32,+ "lcaron" => 344_f32,+ "Kcommaaccent" => 722_f32,+ "Lacute" => 611_f32,+ "trademark" => 980_f32,+ "edotaccent" => 444_f32,+ "Igrave" => 333_f32,+ "Imacron" => 333_f32,+ "Lcaron" => 611_f32,+ "onehalf" => 750_f32,+ "lessequal" => 549_f32,+ "ocircumflex" => 500_f32,+ "ntilde" => 500_f32,+ "Uhungarumlaut" => 722_f32,+ "Eacute" => 611_f32,+ "emacron" => 444_f32,+ "gbreve" => 500_f32,+ "onequarter" => 750_f32,+ "Scaron" => 556_f32,+ "Scommaaccent" => 556_f32,+ "Ohungarumlaut" => 722_f32,+ "degree" => 400_f32,+ "ograve" => 500_f32,+ "Ccaron" => 667_f32,+ "ugrave" => 500_f32,+ "radical" => 453_f32,+ "Dcaron" => 722_f32,+ "rcommaaccent" => 333_f32,+ "Ntilde" => 722_f32,+ "otilde" => 500_f32,+ "Rcommaaccent" => 667_f32,+ "Lcommaaccent" => 611_f32,+ "Atilde" => 722_f32,+ "Aogonek" => 722_f32,+ "Aring" => 722_f32,+ "Otilde" => 722_f32,+ "zdotaccent" => 444_f32,+ "Ecaron" => 611_f32,+ "Iogonek" => 333_f32,+ "kcommaaccent" => 500_f32,+ "minus" => 564_f32,+ "Icircumflex" => 333_f32,+ "ncaron" => 500_f32,+ "tcommaaccent" => 278_f32,+ "logicalnot" => 564_f32,+ "odieresis" => 500_f32,+ "udieresis" => 500_f32,+ "notequal" => 549_f32,+ "gcommaaccent" => 500_f32,+ "eth" => 500_f32,+ "zcaron" => 444_f32,+ "ncommaaccent" => 500_f32,+ "onesuperior" => 300_f32,+ "imacron" => 278_f32,+ "Euro" => 500_f32,+};++pub(crate) static ZAPF_DING_BATS: phf::Map<&'static str, f32> = phf_map! {+ "space" => 278_f32,+ "a1" => 974_f32,+ "a2" => 961_f32,+ "a202" => 974_f32,+ "a3" => 980_f32,+ "a4" => 719_f32,+ "a5" => 789_f32,+ "a119" => 790_f32,+ "a118" => 791_f32,+ "a117" => 690_f32,+ "a11" => 960_f32,+ "a12" => 939_f32,+ "a13" => 549_f32,+ "a14" => 855_f32,+ "a15" => 911_f32,+ "a16" => 933_f32,+ "a105" => 911_f32,+ "a17" => 945_f32,+ "a18" => 974_f32,+ "a19" => 755_f32,+ "a20" => 846_f32,+ "a21" => 762_f32,+ "a22" => 761_f32,+ "a23" => 571_f32,+ "a24" => 677_f32,+ "a25" => 763_f32,+ "a26" => 760_f32,+ "a27" => 759_f32,+ "a28" => 754_f32,+ "a6" => 494_f32,+ "a7" => 552_f32,+ "a8" => 537_f32,+ "a9" => 577_f32,+ "a10" => 692_f32,+ "a29" => 786_f32,+ "a30" => 788_f32,+ "a31" => 788_f32,+ "a32" => 790_f32,+ "a33" => 793_f32,+ "a34" => 794_f32,+ "a35" => 816_f32,+ "a36" => 823_f32,+ "a37" => 789_f32,+ "a38" => 841_f32,+ "a39" => 823_f32,+ "a40" => 833_f32,+ "a41" => 816_f32,+ "a42" => 831_f32,+ "a43" => 923_f32,+ "a44" => 744_f32,+ "a45" => 723_f32,+ "a46" => 749_f32,+ "a47" => 790_f32,+ "a48" => 792_f32,+ "a49" => 695_f32,+ "a50" => 776_f32,+ "a51" => 768_f32,+ "a52" => 792_f32,+ "a53" => 759_f32,+ "a54" => 707_f32,+ "a55" => 708_f32,+ "a56" => 682_f32,+ "a57" => 701_f32,+ "a58" => 826_f32,+ "a59" => 815_f32,+ "a60" => 789_f32,+ "a61" => 789_f32,+ "a62" => 707_f32,+ "a63" => 687_f32,+ "a64" => 696_f32,+ "a65" => 689_f32,+ "a66" => 786_f32,+ "a67" => 787_f32,+ "a68" => 713_f32,+ "a69" => 791_f32,+ "a70" => 785_f32,+ "a71" => 791_f32,+ "a72" => 873_f32,+ "a73" => 761_f32,+ "a74" => 762_f32,+ "a203" => 762_f32,+ "a75" => 759_f32,+ "a204" => 759_f32,+ "a76" => 892_f32,+ "a77" => 892_f32,+ "a78" => 788_f32,+ "a79" => 784_f32,+ "a81" => 438_f32,+ "a82" => 138_f32,+ "a83" => 277_f32,+ "a84" => 415_f32,+ "a97" => 392_f32,+ "a98" => 392_f32,+ "a99" => 668_f32,+ "a100" => 668_f32,+ "a89" => 390_f32,+ "a90" => 390_f32,+ "a93" => 317_f32,+ "a94" => 317_f32,+ "a91" => 276_f32,+ "a92" => 276_f32,+ "a205" => 509_f32,+ "a85" => 509_f32,+ "a206" => 410_f32,+ "a86" => 410_f32,+ "a87" => 234_f32,+ "a88" => 234_f32,+ "a95" => 334_f32,+ "a96" => 334_f32,+ "a101" => 732_f32,+ "a102" => 544_f32,+ "a103" => 544_f32,+ "a104" => 910_f32,+ "a106" => 667_f32,+ "a107" => 760_f32,+ "a108" => 760_f32,+ "a112" => 776_f32,+ "a111" => 595_f32,+ "a110" => 694_f32,+ "a109" => 626_f32,+ "a120" => 788_f32,+ "a121" => 788_f32,+ "a122" => 788_f32,+ "a123" => 788_f32,+ "a124" => 788_f32,+ "a125" => 788_f32,+ "a126" => 788_f32,+ "a127" => 788_f32,+ "a128" => 788_f32,+ "a129" => 788_f32,+ "a130" => 788_f32,+ "a131" => 788_f32,+ "a132" => 788_f32,+ "a133" => 788_f32,+ "a134" => 788_f32,+ "a135" => 788_f32,+ "a136" => 788_f32,+ "a137" => 788_f32,+ "a138" => 788_f32,+ "a139" => 788_f32,+ "a140" => 788_f32,+ "a141" => 788_f32,+ "a142" => 788_f32,+ "a143" => 788_f32,+ "a144" => 788_f32,+ "a145" => 788_f32,+ "a146" => 788_f32,+ "a147" => 788_f32,+ "a148" => 788_f32,+ "a149" => 788_f32,+ "a150" => 788_f32,+ "a151" => 788_f32,+ "a152" => 788_f32,+ "a153" => 788_f32,+ "a154" => 788_f32,+ "a155" => 788_f32,+ "a156" => 788_f32,+ "a157" => 788_f32,+ "a158" => 788_f32,+ "a159" => 788_f32,+ "a160" => 894_f32,+ "a161" => 838_f32,+ "a163" => 1016_f32,+ "a164" => 458_f32,+ "a196" => 748_f32,+ "a165" => 924_f32,+ "a192" => 748_f32,+ "a166" => 918_f32,+ "a167" => 927_f32,+ "a168" => 928_f32,+ "a169" => 928_f32,+ "a170" => 834_f32,+ "a171" => 873_f32,+ "a172" => 828_f32,+ "a173" => 924_f32,+ "a162" => 924_f32,+ "a174" => 917_f32,+ "a175" => 930_f32,+ "a176" => 931_f32,+ "a177" => 463_f32,+ "a178" => 883_f32,+ "a179" => 836_f32,+ "a193" => 836_f32,+ "a180" => 867_f32,+ "a199" => 867_f32,+ "a181" => 696_f32,+ "a200" => 696_f32,+ "a182" => 874_f32,+ "a201" => 874_f32,+ "a183" => 760_f32,+ "a184" => 946_f32,+ "a197" => 771_f32,+ "a185" => 865_f32,+ "a194" => 771_f32,+ "a198" => 888_f32,+ "a186" => 967_f32,+ "a195" => 888_f32,+ "a187" => 831_f32,+ "a188" => 873_f32,+ "a189" => 927_f32,+ "a190" => 970_f32,+ "a191" => 918_f32,+};diff --git a/vendor/hayro-interpret/src/font/generated/mod.rs b/vendor/hayro-interpret/src/font/generated/mod.rsnew file mode 100644index 000000000..4edf16a7c--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/mod.rs@@ -0,0 +1,9 @@+pub(crate) mod glyph_names;+pub(crate) mod mac_expert;+pub(crate) mod mac_os_roman;+pub(crate) mod mac_roman;+pub(crate) mod metrics;+pub(crate) mod standard;+pub(crate) mod symbol;+pub(crate) mod win_ansi;+pub(crate) mod zapf_dings;diff --git a/vendor/hayro-interpret/src/font/generated/standard.rs b/vendor/hayro-interpret/src/font/generated/standard.rsnew file mode 100644index 000000000..a3972c8e5--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/standard.rs@@ -0,0 +1,157 @@+use phf::phf_map;++pub(crate) fn get(code: u8) -> Option<&'static str> {+ STANDARD.get(&code).copied()+}++static STANDARD: phf::Map<u8, &'static str> = phf_map! {+ 32_u8 => "space",+ 33_u8 => "exclam",+ 34_u8 => "quotedbl",+ 35_u8 => "numbersign",+ 36_u8 => "dollar",+ 37_u8 => "percent",+ 38_u8 => "ampersand",+ 39_u8 => "quoteright",+ 40_u8 => "parenleft",+ 41_u8 => "parenright",+ 42_u8 => "asterisk",+ 43_u8 => "plus",+ 44_u8 => "comma",+ 45_u8 => "hyphen",+ 46_u8 => "period",+ 47_u8 => "slash",+ 48_u8 => "zero",+ 49_u8 => "one",+ 50_u8 => "two",+ 51_u8 => "three",+ 52_u8 => "four",+ 53_u8 => "five",+ 54_u8 => "six",+ 55_u8 => "seven",+ 56_u8 => "eight",+ 57_u8 => "nine",+ 58_u8 => "colon",+ 59_u8 => "semicolon",+ 60_u8 => "less",+ 61_u8 => "equal",+ 62_u8 => "greater",+ 63_u8 => "question",+ 64_u8 => "at",+ 65_u8 => "A",+ 66_u8 => "B",+ 67_u8 => "C",+ 68_u8 => "D",+ 69_u8 => "E",+ 70_u8 => "F",+ 71_u8 => "G",+ 72_u8 => "H",+ 73_u8 => "I",+ 74_u8 => "J",+ 75_u8 => "K",+ 76_u8 => "L",+ 77_u8 => "M",+ 78_u8 => "N",+ 79_u8 => "O",+ 80_u8 => "P",+ 81_u8 => "Q",+ 82_u8 => "R",+ 83_u8 => "S",+ 84_u8 => "T",+ 85_u8 => "U",+ 86_u8 => "V",+ 87_u8 => "W",+ 88_u8 => "X",+ 89_u8 => "Y",+ 90_u8 => "Z",+ 91_u8 => "bracketleft",+ 92_u8 => "backslash",+ 93_u8 => "bracketright",+ 94_u8 => "asciicircum",+ 95_u8 => "underscore",+ 96_u8 => "quoteleft",+ 97_u8 => "a",+ 98_u8 => "b",+ 99_u8 => "c",+ 100_u8 => "d",+ 101_u8 => "e",+ 102_u8 => "f",+ 103_u8 => "g",+ 104_u8 => "h",+ 105_u8 => "i",+ 106_u8 => "j",+ 107_u8 => "k",+ 108_u8 => "l",+ 109_u8 => "m",+ 110_u8 => "n",+ 111_u8 => "o",+ 112_u8 => "p",+ 113_u8 => "q",+ 114_u8 => "r",+ 115_u8 => "s",+ 116_u8 => "t",+ 117_u8 => "u",+ 118_u8 => "v",+ 119_u8 => "w",+ 120_u8 => "x",+ 121_u8 => "y",+ 122_u8 => "z",+ 123_u8 => "braceleft",+ 124_u8 => "bar",+ 125_u8 => "braceright",+ 126_u8 => "asciitilde",+ 161_u8 => "exclamdown",+ 162_u8 => "cent",+ 163_u8 => "sterling",+ 164_u8 => "fraction",+ 165_u8 => "yen",+ 166_u8 => "florin",+ 167_u8 => "section",+ 168_u8 => "currency",+ 169_u8 => "quotesingle",+ 170_u8 => "quotedblleft",+ 171_u8 => "guillemotleft",+ 172_u8 => "guilsinglleft",+ 173_u8 => "guilsinglright",+ 174_u8 => "fi",+ 175_u8 => "fl",+ 177_u8 => "endash",+ 178_u8 => "dagger",+ 179_u8 => "daggerdbl",+ 180_u8 => "periodcentered",+ 182_u8 => "paragraph",+ 183_u8 => "bullet",+ 184_u8 => "quotesinglbase",+ 185_u8 => "quotedblbase",+ 186_u8 => "quotedblright",+ 187_u8 => "guillemotright",+ 188_u8 => "ellipsis",+ 189_u8 => "perthousand",+ 191_u8 => "questiondown",+ 193_u8 => "grave",+ 194_u8 => "acute",+ 195_u8 => "circumflex",+ 196_u8 => "tilde",+ 197_u8 => "macron",+ 198_u8 => "breve",+ 199_u8 => "dotaccent",+ 200_u8 => "dieresis",+ 202_u8 => "ring",+ 203_u8 => "cedilla",+ 205_u8 => "hungarumlaut",+ 206_u8 => "ogonek",+ 207_u8 => "caron",+ 208_u8 => "emdash",+ 225_u8 => "AE",+ 227_u8 => "ordfeminine",+ 232_u8 => "Lslash",+ 233_u8 => "Oslash",+ 234_u8 => "OE",+ 235_u8 => "ordmasculine",+ 241_u8 => "ae",+ 245_u8 => "dotlessi",+ 248_u8 => "lslash",+ 249_u8 => "oslash",+ 250_u8 => "oe",+ 251_u8 => "germandbls",+};diff --git a/vendor/hayro-interpret/src/font/generated/symbol.rs b/vendor/hayro-interpret/src/font/generated/symbol.rsnew file mode 100644index 000000000..ba68a2787--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/symbol.rs@@ -0,0 +1,197 @@+use phf::phf_map;++pub(crate) fn get(code: u8) -> Option<&'static str> {+ SYMBOL.get(&code).copied()+}++static SYMBOL: phf::Map<u8, &'static str> = phf_map! {+ 32_u8 => "space",+ 33_u8 => "exclam",+ 34_u8 => "universal",+ 35_u8 => "numbersign",+ 36_u8 => "existential",+ 37_u8 => "percent",+ 38_u8 => "ampersand",+ 39_u8 => "suchthat",+ 40_u8 => "parenleft",+ 41_u8 => "parenright",+ 42_u8 => "asteriskmath",+ 43_u8 => "plus",+ 44_u8 => "comma",+ 45_u8 => "minus",+ 46_u8 => "period",+ 47_u8 => "slash",+ 48_u8 => "zero",+ 49_u8 => "one",+ 50_u8 => "two",+ 51_u8 => "three",+ 52_u8 => "four",+ 53_u8 => "five",+ 54_u8 => "six",+ 55_u8 => "seven",+ 56_u8 => "eight",+ 57_u8 => "nine",+ 58_u8 => "colon",+ 59_u8 => "semicolon",+ 60_u8 => "less",+ 61_u8 => "equal",+ 62_u8 => "greater",+ 63_u8 => "question",+ 64_u8 => "congruent",+ 65_u8 => "Alpha",+ 66_u8 => "Beta",+ 67_u8 => "Chi",+ 68_u8 => "Delta",+ 69_u8 => "Epsilon",+ 70_u8 => "Phi",+ 71_u8 => "Gamma",+ 72_u8 => "Eta",+ 73_u8 => "Iota",+ 74_u8 => "theta1",+ 75_u8 => "Kappa",+ 76_u8 => "Lambda",+ 77_u8 => "Mu",+ 78_u8 => "Nu",+ 79_u8 => "Omicron",+ 80_u8 => "Pi",+ 81_u8 => "Theta",+ 82_u8 => "Rho",+ 83_u8 => "Sigma",+ 84_u8 => "Tau",+ 85_u8 => "Upsilon",+ 86_u8 => "sigma1",+ 87_u8 => "Omega",+ 88_u8 => "Xi",+ 89_u8 => "Psi",+ 90_u8 => "Zeta",+ 91_u8 => "bracketleft",+ 92_u8 => "therefore",+ 93_u8 => "bracketright",+ 94_u8 => "perpendicular",+ 95_u8 => "underscore",+ 96_u8 => "radicalex",+ 97_u8 => "alpha",+ 98_u8 => "beta",+ 99_u8 => "chi",+ 100_u8 => "delta",+ 101_u8 => "epsilon",+ 102_u8 => "phi",+ 103_u8 => "gamma",+ 104_u8 => "eta",+ 105_u8 => "iota",+ 106_u8 => "phi1",+ 107_u8 => "kappa",+ 108_u8 => "lambda",+ 109_u8 => "mu",+ 110_u8 => "nu",+ 111_u8 => "omicron",+ 112_u8 => "pi",+ 113_u8 => "theta",+ 114_u8 => "rho",+ 115_u8 => "sigma",+ 116_u8 => "tau",+ 117_u8 => "upsilon",+ 118_u8 => "omega1",+ 119_u8 => "omega",+ 120_u8 => "xi",+ 121_u8 => "psi",+ 122_u8 => "zeta",+ 123_u8 => "braceleft",+ 124_u8 => "bar",+ 125_u8 => "braceright",+ 126_u8 => "similar",+ 160_u8 => "Euro",+ 161_u8 => "Upsilon1",+ 162_u8 => "minute",+ 163_u8 => "lessequal",+ 164_u8 => "fraction",+ 165_u8 => "infinity",+ 166_u8 => "florin",+ 167_u8 => "club",+ 168_u8 => "diamond",+ 169_u8 => "heart",+ 170_u8 => "spade",+ 171_u8 => "arrowboth",+ 172_u8 => "arrowleft",+ 173_u8 => "arrowup",+ 174_u8 => "arrowright",+ 175_u8 => "arrowdown",+ 176_u8 => "degree",+ 177_u8 => "plusminus",+ 178_u8 => "second",+ 179_u8 => "greaterequal",+ 180_u8 => "multiply",+ 181_u8 => "proportional",+ 182_u8 => "partialdiff",+ 183_u8 => "bullet",+ 184_u8 => "divide",+ 185_u8 => "notequal",+ 186_u8 => "equivalence",+ 187_u8 => "approxequal",+ 188_u8 => "ellipsis",+ 189_u8 => "arrowvertex",+ 190_u8 => "arrowhorizex",+ 191_u8 => "carriagereturn",+ 192_u8 => "aleph",+ 193_u8 => "Ifraktur",+ 194_u8 => "Rfraktur",+ 195_u8 => "weierstrass",+ 196_u8 => "circlemultiply",+ 197_u8 => "circleplus",+ 198_u8 => "emptyset",+ 199_u8 => "intersection",+ 200_u8 => "union",+ 201_u8 => "propersuperset",+ 202_u8 => "reflexsuperset",+ 203_u8 => "notsubset",+ 204_u8 => "propersubset",+ 205_u8 => "reflexsubset",+ 206_u8 => "element",+ 207_u8 => "notelement",+ 208_u8 => "angle",+ 209_u8 => "gradient",+ 210_u8 => "registerserif",+ 211_u8 => "copyrightserif",+ 212_u8 => "trademarkserif",+ 213_u8 => "product",+ 214_u8 => "radical",+ 215_u8 => "dotmath",+ 216_u8 => "logicalnot",+ 217_u8 => "logicaland",+ 218_u8 => "logicalor",+ 219_u8 => "arrowdblboth",+ 220_u8 => "arrowdblleft",+ 221_u8 => "arrowdblup",+ 222_u8 => "arrowdblright",+ 223_u8 => "arrowdbldown",+ 224_u8 => "lozenge",+ 225_u8 => "angleleft",+ 226_u8 => "registersans",+ 227_u8 => "copyrightsans",+ 228_u8 => "trademarksans",+ 229_u8 => "summation",+ 230_u8 => "parenlefttp",+ 231_u8 => "parenleftex",+ 232_u8 => "parenleftbt",+ 233_u8 => "bracketlefttp",+ 234_u8 => "bracketleftex",+ 235_u8 => "bracketleftbt",+ 236_u8 => "bracelefttp",+ 237_u8 => "braceleftmid",+ 238_u8 => "braceleftbt",+ 239_u8 => "braceex",+ 241_u8 => "angleright",+ 242_u8 => "integral",+ 243_u8 => "integraltp",+ 244_u8 => "integralex",+ 245_u8 => "integralbt",+ 246_u8 => "parenrighttp",+ 247_u8 => "parenrightex",+ 248_u8 => "parenrightbt",+ 249_u8 => "bracketrighttp",+ 250_u8 => "bracketrightex",+ 251_u8 => "bracketrightbt",+ 252_u8 => "bracerighttp",+ 253_u8 => "bracerightmid",+ 254_u8 => "bracerightbt",+};diff --git a/vendor/hayro-interpret/src/font/generated/win_ansi.rs b/vendor/hayro-interpret/src/font/generated/win_ansi.rsnew file mode 100644index 000000000..6db56ba9d--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/win_ansi.rs@@ -0,0 +1,230 @@+// See <https://github.com/apache/pdfbox/blob/4438b8fdc67a3a9ebfb194595d0e81f88b708a37/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/encoding/WinAnsiEncoding.java>+use phf::phf_map;++pub(crate) fn get(code: u8) -> Option<&'static str> {+ WIN_ANSI+ .get(&code)+ .or(if code > 40 { Some(&"bullet") } else { None })+ .copied()+}++static WIN_ANSI: phf::Map<u8, &'static str> = phf_map! {+ 65_u8 => "A",+ 198_u8 => "AE",+ 193_u8 => "Aacute",+ 194_u8 => "Acircumflex",+ 196_u8 => "Adieresis",+ 192_u8 => "Agrave",+ 197_u8 => "Aring",+ 195_u8 => "Atilde",+ 66_u8 => "B",+ 67_u8 => "C",+ 199_u8 => "Ccedilla",+ 68_u8 => "D",+ 69_u8 => "E",+ 201_u8 => "Eacute",+ 202_u8 => "Ecircumflex",+ 203_u8 => "Edieresis",+ 200_u8 => "Egrave",+ 208_u8 => "Eth",+ 128_u8 => "Euro",+ 70_u8 => "F",+ 71_u8 => "G",+ 72_u8 => "H",+ 73_u8 => "I",+ 205_u8 => "Iacute",+ 206_u8 => "Icircumflex",+ 207_u8 => "Idieresis",+ 204_u8 => "Igrave",+ 74_u8 => "J",+ 75_u8 => "K",+ 76_u8 => "L",+ 77_u8 => "M",+ 78_u8 => "N",+ 209_u8 => "Ntilde",+ 79_u8 => "O",+ 140_u8 => "OE",+ 211_u8 => "Oacute",+ 212_u8 => "Ocircumflex",+ 214_u8 => "Odieresis",+ 210_u8 => "Ograve",+ 216_u8 => "Oslash",+ 213_u8 => "Otilde",+ 80_u8 => "P",+ 81_u8 => "Q",+ 82_u8 => "R",+ 83_u8 => "S",+ 138_u8 => "Scaron",+ 84_u8 => "T",+ 222_u8 => "Thorn",+ 85_u8 => "U",+ 218_u8 => "Uacute",+ 219_u8 => "Ucircumflex",+ 220_u8 => "Udieresis",+ 217_u8 => "Ugrave",+ 86_u8 => "V",+ 87_u8 => "W",+ 88_u8 => "X",+ 89_u8 => "Y",+ 221_u8 => "Yacute",+ 159_u8 => "Ydieresis",+ 90_u8 => "Z",+ 142_u8 => "Zcaron",+ 97_u8 => "a",+ 225_u8 => "aacute",+ 226_u8 => "acircumflex",+ 180_u8 => "acute",+ 228_u8 => "adieresis",+ 230_u8 => "ae",+ 224_u8 => "agrave",+ 38_u8 => "ampersand",+ 229_u8 => "aring",+ 94_u8 => "asciicircum",+ 126_u8 => "asciitilde",+ 42_u8 => "asterisk",+ 64_u8 => "at",+ 227_u8 => "atilde",+ 98_u8 => "b",+ 92_u8 => "backslash",+ 124_u8 => "bar",+ 123_u8 => "braceleft",+ 125_u8 => "braceright",+ 91_u8 => "bracketleft",+ 93_u8 => "bracketright",+ 166_u8 => "brokenbar",+ 149_u8 => "bullet",+ 99_u8 => "c",+ 231_u8 => "ccedilla",+ 184_u8 => "cedilla",+ 162_u8 => "cent",+ 136_u8 => "circumflex",+ 58_u8 => "colon",+ 44_u8 => "comma",+ 169_u8 => "copyright",+ 164_u8 => "currency",+ 100_u8 => "d",+ 134_u8 => "dagger",+ 135_u8 => "daggerdbl",+ 176_u8 => "degree",+ 168_u8 => "dieresis",+ 247_u8 => "divide",+ 36_u8 => "dollar",+ 101_u8 => "e",+ 233_u8 => "eacute",+ 234_u8 => "ecircumflex",+ 235_u8 => "edieresis",+ 232_u8 => "egrave",+ 56_u8 => "eight",+ 133_u8 => "ellipsis",+ 151_u8 => "emdash",+ 150_u8 => "endash",+ 61_u8 => "equal",+ 240_u8 => "eth",+ 33_u8 => "exclam",+ 161_u8 => "exclamdown",+ 102_u8 => "f",+ 53_u8 => "five",+ 131_u8 => "florin",+ 52_u8 => "four",+ 103_u8 => "g",+ 223_u8 => "germandbls",+ 96_u8 => "grave",+ 62_u8 => "greater",+ 171_u8 => "guillemotleft",+ 187_u8 => "guillemotright",+ 139_u8 => "guilsinglleft",+ 155_u8 => "guilsinglright",+ 104_u8 => "h",+ 45_u8 => "hyphen",+ 105_u8 => "i",+ 237_u8 => "iacute",+ 238_u8 => "icircumflex",+ 239_u8 => "idieresis",+ 236_u8 => "igrave",+ 106_u8 => "j",+ 107_u8 => "k",+ 108_u8 => "l",+ 60_u8 => "less",+ 172_u8 => "logicalnot",+ 109_u8 => "m",+ 175_u8 => "macron",+ 181_u8 => "mu",+ 215_u8 => "multiply",+ 110_u8 => "n",+ 57_u8 => "nine",+ 241_u8 => "ntilde",+ 35_u8 => "numbersign",+ 111_u8 => "o",+ 243_u8 => "oacute",+ 244_u8 => "ocircumflex",+ 246_u8 => "odieresis",+ 156_u8 => "oe",+ 242_u8 => "ograve",+ 49_u8 => "one",+ 189_u8 => "onehalf",+ 188_u8 => "onequarter",+ 185_u8 => "onesuperior",+ 170_u8 => "ordfeminine",+ 186_u8 => "ordmasculine",+ 248_u8 => "oslash",+ 245_u8 => "otilde",+ 112_u8 => "p",+ 182_u8 => "paragraph",+ 40_u8 => "parenleft",+ 41_u8 => "parenright",+ 37_u8 => "percent",+ 46_u8 => "period",+ 183_u8 => "periodcentered",+ 137_u8 => "perthousand",+ 43_u8 => "plus",+ 177_u8 => "plusminus",+ 113_u8 => "q",+ 63_u8 => "question",+ 191_u8 => "questiondown",+ 34_u8 => "quotedbl",+ 132_u8 => "quotedblbase",+ 147_u8 => "quotedblleft",+ 148_u8 => "quotedblright",+ 145_u8 => "quoteleft",+ 146_u8 => "quoteright",+ 130_u8 => "quotesinglbase",+ 39_u8 => "quotesingle",+ 114_u8 => "r",+ 174_u8 => "registered",+ 115_u8 => "s",+ 154_u8 => "scaron",+ 167_u8 => "section",+ 59_u8 => "semicolon",+ 55_u8 => "seven",+ 54_u8 => "six",+ 47_u8 => "slash",+ 32_u8 => "space",+ 163_u8 => "sterling",+ 116_u8 => "t",+ 254_u8 => "thorn",+ 51_u8 => "three",+ 190_u8 => "threequarters",+ 179_u8 => "threesuperior",+ 152_u8 => "tilde",+ 153_u8 => "trademark",+ 50_u8 => "two",+ 178_u8 => "twosuperior",+ 117_u8 => "u",+ 250_u8 => "uacute",+ 251_u8 => "ucircumflex",+ 252_u8 => "udieresis",+ 249_u8 => "ugrave",+ 95_u8 => "underscore",+ 118_u8 => "v",+ 119_u8 => "w",+ 120_u8 => "x",+ 121_u8 => "y",+ 253_u8 => "yacute",+ 255_u8 => "ydieresis",+ 165_u8 => "yen",+ 122_u8 => "z",+ 158_u8 => "zcaron",+ 48_u8 => "zero",+ 160_u8 => "nbspace",+ 173_u8 => "sfthyphen",+};diff --git a/vendor/hayro-interpret/src/font/generated/zapf_dings.rs b/vendor/hayro-interpret/src/font/generated/zapf_dings.rsnew file mode 100644index 000000000..19834cfdb--- /dev/null+++ b/vendor/hayro-interpret/src/font/generated/zapf_dings.rs@@ -0,0 +1,210 @@+use phf::phf_map;++pub(crate) fn get(code: u8) -> Option<&'static str> {+ ZAPF_DING_BATS.get(&code).copied()+}++static ZAPF_DING_BATS: phf::Map<u8, &'static str> = phf_map! {+ 32_u8 => "space",+ 33_u8 => "a1",+ 34_u8 => "a2",+ 35_u8 => "a202",+ 36_u8 => "a3",+ 37_u8 => "a4",+ 38_u8 => "a5",+ 39_u8 => "a119",+ 40_u8 => "a118",+ 41_u8 => "a117",+ 42_u8 => "a11",+ 43_u8 => "a12",+ 44_u8 => "a13",+ 45_u8 => "a14",+ 46_u8 => "a15",+ 47_u8 => "a16",+ 48_u8 => "a105",+ 49_u8 => "a17",+ 50_u8 => "a18",+ 51_u8 => "a19",+ 52_u8 => "a20",+ 53_u8 => "a21",+ 54_u8 => "a22",+ 55_u8 => "a23",+ 56_u8 => "a24",+ 57_u8 => "a25",+ 58_u8 => "a26",+ 59_u8 => "a27",+ 60_u8 => "a28",+ 61_u8 => "a6",+ 62_u8 => "a7",+ 63_u8 => "a8",+ 64_u8 => "a9",+ 65_u8 => "a10",+ 66_u8 => "a29",+ 67_u8 => "a30",+ 68_u8 => "a31",+ 69_u8 => "a32",+ 70_u8 => "a33",+ 71_u8 => "a34",+ 72_u8 => "a35",+ 73_u8 => "a36",+ 74_u8 => "a37",+ 75_u8 => "a38",+ 76_u8 => "a39",+ 77_u8 => "a40",+ 78_u8 => "a41",+ 79_u8 => "a42",+ 80_u8 => "a43",+ 81_u8 => "a44",+ 82_u8 => "a45",+ 83_u8 => "a46",+ 84_u8 => "a47",+ 85_u8 => "a48",+ 86_u8 => "a49",+ 87_u8 => "a50",+ 88_u8 => "a51",+ 89_u8 => "a52",+ 90_u8 => "a53",+ 91_u8 => "a54",+ 92_u8 => "a55",+ 93_u8 => "a56",+ 94_u8 => "a57",+ 95_u8 => "a58",+ 96_u8 => "a59",+ 97_u8 => "a60",+ 98_u8 => "a61",+ 99_u8 => "a62",+ 100_u8 => "a63",+ 101_u8 => "a64",+ 102_u8 => "a65",+ 103_u8 => "a66",+ 104_u8 => "a67",+ 105_u8 => "a68",+ 106_u8 => "a69",+ 107_u8 => "a70",+ 108_u8 => "a71",+ 109_u8 => "a72",+ 110_u8 => "a73",+ 111_u8 => "a74",+ 112_u8 => "a203",+ 113_u8 => "a75",+ 114_u8 => "a204",+ 115_u8 => "a76",+ 116_u8 => "a77",+ 117_u8 => "a78",+ 118_u8 => "a79",+ 119_u8 => "a81",+ 120_u8 => "a82",+ 121_u8 => "a83",+ 122_u8 => "a84",+ 123_u8 => "a97",+ 124_u8 => "a98",+ 125_u8 => "a99",+ 126_u8 => "a100",+ 128_u8 => "a89",+ 129_u8 => "a90",+ 130_u8 => "a93",+ 131_u8 => "a94",+ 132_u8 => "a91",+ 133_u8 => "a92",+ 134_u8 => "a205",+ 135_u8 => "a85",+ 136_u8 => "a206",+ 137_u8 => "a86",+ 138_u8 => "a87",+ 139_u8 => "a88",+ 140_u8 => "a95",+ 141_u8 => "a96",+ 161_u8 => "a101",+ 162_u8 => "a102",+ 163_u8 => "a103",+ 164_u8 => "a104",+ 165_u8 => "a106",+ 166_u8 => "a107",+ 167_u8 => "a108",+ 168_u8 => "a112",+ 169_u8 => "a111",+ 170_u8 => "a110",+ 171_u8 => "a109",+ 172_u8 => "a120",+ 173_u8 => "a121",+ 174_u8 => "a122",+ 175_u8 => "a123",+ 176_u8 => "a124",+ 177_u8 => "a125",+ 178_u8 => "a126",+ 179_u8 => "a127",+ 180_u8 => "a128",+ 181_u8 => "a129",+ 182_u8 => "a130",+ 183_u8 => "a131",+ 184_u8 => "a132",+ 185_u8 => "a133",+ 186_u8 => "a134",+ 187_u8 => "a135",+ 188_u8 => "a136",+ 189_u8 => "a137",+ 190_u8 => "a138",+ 191_u8 => "a139",+ 192_u8 => "a140",+ 193_u8 => "a141",+ 194_u8 => "a142",+ 195_u8 => "a143",+ 196_u8 => "a144",+ 197_u8 => "a145",+ 198_u8 => "a146",+ 199_u8 => "a147",+ 200_u8 => "a148",+ 201_u8 => "a149",+ 202_u8 => "a150",+ 203_u8 => "a151",+ 204_u8 => "a152",+ 205_u8 => "a153",+ 206_u8 => "a154",+ 207_u8 => "a155",+ 208_u8 => "a156",+ 209_u8 => "a157",+ 210_u8 => "a158",+ 211_u8 => "a159",+ 212_u8 => "a160",+ 213_u8 => "a161",+ 214_u8 => "a163",+ 215_u8 => "a164",+ 216_u8 => "a196",+ 217_u8 => "a165",+ 218_u8 => "a192",+ 219_u8 => "a166",+ 220_u8 => "a167",+ 221_u8 => "a168",+ 222_u8 => "a169",+ 223_u8 => "a170",+ 224_u8 => "a171",+ 225_u8 => "a172",+ 226_u8 => "a173",+ 227_u8 => "a162",+ 228_u8 => "a174",+ 229_u8 => "a175",+ 230_u8 => "a176",+ 231_u8 => "a177",+ 232_u8 => "a178",+ 233_u8 => "a179",+ 234_u8 => "a193",+ 235_u8 => "a180",+ 236_u8 => "a199",+ 237_u8 => "a181",+ 238_u8 => "a200",+ 239_u8 => "a182",+ 241_u8 => "a201",+ 242_u8 => "a183",+ 243_u8 => "a184",+ 244_u8 => "a197",+ 245_u8 => "a185",+ 246_u8 => "a194",+ 247_u8 => "a198",+ 248_u8 => "a186",+ 249_u8 => "a195",+ 250_u8 => "a187",+ 251_u8 => "a188",+ 252_u8 => "a189",+ 253_u8 => "a190",+ 254_u8 => "a191",+};diff --git a/vendor/hayro-interpret/src/font/glyph_simulator.rs b/vendor/hayro-interpret/src/font/glyph_simulator.rsnew file mode 100644index 000000000..903a66324--- /dev/null+++ b/vendor/hayro-interpret/src/font/glyph_simulator.rs@@ -0,0 +1,53 @@+use skrifa::GlyphId;+use std::cell::{Cell, RefCell};+use std::collections::HashMap;++#[derive(Debug)]+pub(crate) struct GlyphSimulator {+ // We simulate that Type1 glyphs have glyph IDs so we can handle them transparently+ // to OpenType fonts.+ glyph_to_string: RefCell<HashMap<GlyphId, String>>,+ string_to_glyph: RefCell<HashMap<String, GlyphId>>,+ glyph_counter: Cell<u32>,+}++impl GlyphSimulator {+ pub(crate) fn new() -> Self {+ let mut glyph_to_string = HashMap::new();+ glyph_to_string.insert(GlyphId::NOTDEF, "notdef".to_string());++ let mut string_to_glyph = HashMap::new();+ string_to_glyph.insert("notdef".to_string(), GlyphId::NOTDEF);++ Self {+ glyph_to_string: RefCell::new(glyph_to_string),+ string_to_glyph: RefCell::new(string_to_glyph),+ glyph_counter: Cell::new(1),+ }+ }++ pub(crate) fn string_to_glyph(&self, string: &str) -> GlyphId {+ if let Some(g) = self.string_to_glyph.borrow().get(string) {+ *g+ } else {+ let gid = GlyphId::new(self.glyph_counter.get());+ self.string_to_glyph+ .borrow_mut()+ .insert(string.to_string(), gid);+ self.glyph_to_string+ .borrow_mut()+ .insert(gid, string.to_string());++ self.glyph_counter.set(self.glyph_counter.get() + 1);++ gid+ }+ }++ pub(crate) fn glyph_to_string(&self, glyph: GlyphId) -> Option<String> {+ self.glyph_to_string+ .borrow()+ .get(&glyph)+ .map(|s| s.to_string())+ }+}diff --git a/vendor/hayro-interpret/src/font/mod.rs b/vendor/hayro-interpret/src/font/mod.rsnew file mode 100644index 000000000..43c4cffe4--- /dev/null+++ b/vendor/hayro-interpret/src/font/mod.rs@@ -0,0 +1,683 @@+//! Interacting with the different kinds of PDF fonts.++use crate::context::Context;+use crate::context::InterpreterCache;+use crate::device::Device;+use crate::font::cid::Type0Font;+use crate::font::generated::{+ glyph_names, mac_expert, mac_os_roman, mac_roman, standard, win_ansi,+};+use crate::font::true_type::TrueTypeFont;+use crate::font::type1::Type1Font;+use crate::font::type3::Type3;+use crate::interpret::state::State;+use crate::{CMapResolverFn, CacheKey, FontResolverFn, InterpreterSettings, Paint};+use bitflags::bitflags;+use hayro_syntax::object::Name;+use hayro_syntax::object::dict::keys::SUBTYPE;+use hayro_syntax::object::dict::keys::*;+use hayro_syntax::object::{Dict, Stream};+use hayro_syntax::page::Resources;+use hayro_syntax::xref::XRef;+use kurbo::{Affine, BezPath, Vec2};+use outline::OutlineFont;+use skrifa::GlyphId;+use std::borrow::Cow;+use std::fmt::Debug;+use std::ops::Deref;+use std::rc::Rc;+use std::sync::Arc;++mod blob;+mod cid;+mod generated;+mod glyph_simulator;+pub(crate) mod outline;+mod standard_font;+mod true_type;+mod type1;+pub(crate) mod type3;++pub(crate) const UNITS_PER_EM: f32 = 1000.0;++pub(crate) fn stretch_glyph(path: BezPath, expected_width: f32, actual_width: f32) -> BezPath {+ if actual_width != 0.0 && actual_width != expected_width {+ let stretch_factor = expected_width / actual_width;+ Affine::scale_non_uniform(stretch_factor as f64, 1.0) * path+ } else {+ path+ }+}++/// A container for the bytes of a PDF file.+pub type FontData = Arc<dyn AsRef<[u8]> + Send + Sync>;++/// Strip the 6-character subset prefix from a PostScript font name.+///+/// PDF subset fonts use names like "ABCDEF+TimesNewRoman". This function+/// returns `TimesNewRoman` from such a name, or the original name if no+/// valid prefix is found.+pub(crate) fn strip_subset_prefix(name: &str) -> &str {+ match name.split_once('+') {+ Some((prefix, rest)) if prefix.len() == 6 => rest,+ _ => name,+ }+}++use crate::util::hash128;+use hayro_cmap::{BfString, CMap, CMapName, CharacterCollection};+pub use outline::OutlineFontData;+pub use standard_font::StandardFont;++/// A glyph that can be drawn.+pub enum Glyph<'a> {+ /// A glyph defined by an outline.+ Outline(OutlineGlyph),+ /// A type3 glyph, defined by PDF drawing instructions.+ Type3(Box<Type3Glyph<'a>>),+}++impl Glyph<'_> {+ /// Returns the Unicode code point for this glyph, if available.+ ///+ /// This method attempts to determine the Unicode character that this glyph+ /// represents. The exact fallback chain depends on the font type:+ ///+ /// **For Outline Fonts (Type1, TrueType, CFF):**+ /// 1. `ToUnicode` cmap+ /// 2. Glyph name → Unicode (via Adobe Glyph List)+ /// 3. Unicode naming conventions (e.g., "uni0041", "u0041")+ ///+ /// **For CID Fonts (Type0):**+ /// 1. `ToUnicode` cmap+ ///+ ///+ /// **For Type3 Fonts:**+ /// 1. `ToUnicode` cmap+ ///+ /// Returns `None` if the Unicode value could not be determined.+ ///+ /// Please note that this method is still somewhat experimental and might+ /// not work reliably in all cases.+ pub fn as_unicode(&self) -> Option<BfString> {+ match self {+ Glyph::Outline(g) => g.as_unicode(),+ Glyph::Type3(g) => g.as_unicode(),+ }+ }+}++/// An identifier that uniquely identifies a glyph, for caching purposes.+#[derive(Clone, Debug)]+pub struct GlyphIdentifier {+ id: GlyphId,+ font: OutlineFont,+}++impl CacheKey for GlyphIdentifier {+ fn cache_key(&self) -> u128 {+ hash128(&(self.id, self.font.cache_key()))+ }+}++/// A glyph defined by an outline.+#[derive(Clone, Debug)]+pub struct OutlineGlyph {+ pub(crate) id: GlyphId,+ pub(crate) font: OutlineFont,+ pub(crate) char_code: u32,+}++impl OutlineGlyph {+ /// Return the outline of the glyph, assuming an upem value of 1000.+ pub fn outline(&self) -> BezPath {+ self.font.outline_glyph(self.id, self.char_code)+ }++ /// Return the identifier of the glyph. You can use this to calculate the cache key+ /// for the glyph.+ ///+ /// Note that the `glyph_transform` attribute is not considered in the cache key of+ /// the identifier, only the glyph ID and the font.+ pub fn identifier(&self) -> GlyphIdentifier {+ GlyphIdentifier {+ id: self.id,+ font: self.font.clone(),+ }+ }++ /// Returns the Unicode code point for this glyph, if available.+ ///+ /// See [`Glyph::as_unicode`] for details on the fallback chain used.+ pub fn as_unicode(&self) -> Option<BfString> {+ self.font.char_code_to_unicode(self.char_code)+ }++ /// Get raw font bytes and metadata for downstream use.+ ///+ /// Returns `None` for Type1 fonts.+ pub fn font_data(&self) -> Option<OutlineFontData> {+ self.font.font_data()+ }++ /// Get the glyph ID within the font.+ pub fn glyph_id(&self) -> GlyphId {+ self.id+ }++ /// Get the advance width for this glyph.+ ///+ /// The advance width is how far to move horizontally after drawing+ /// this glyph before drawing the next one.+ pub fn advance_width(&self) -> Option<f32> {+ self.font.glyph_advance_width(self.char_code)+ }++ /// Get the cache key for this glyph's font.+ ///+ /// This identifies the font uniquely, even when `font_data()` returns `None`+ /// (e.g., for Type1 fonts). Useful for grouping glyphs by font.+ pub fn font_cache_key(&self) -> u128 {+ self.font.cache_key()+ }+}++/// A type3 glyph.+#[derive(Clone)]+pub struct Type3Glyph<'a> {+ pub(crate) font: Rc<Type3<'a>>,+ pub(crate) glyph_id: GlyphId,+ pub(crate) state: State<'a>,+ pub(crate) parent_resources: Resources<'a>,+ pub(crate) cache: InterpreterCache<'a>,+ pub(crate) xref: &'a XRef,+ pub(crate) settings: InterpreterSettings,+ pub(crate) nesting_depth: u32,+ pub(crate) char_code: u32,+}++/// A glyph defined by PDF drawing instructions.+impl<'a> Type3Glyph<'a> {+ /// Draw the type3 glyph to the given device.+ pub fn interpret(+ &self,+ device: &mut impl Device<'a>,+ transform: Affine,+ glyph_transform: Affine,+ paint: &Paint<'a>,+ ) {+ self.font+ .render_glyph(self, transform, glyph_transform, paint, device);+ }++ /// Returns the Unicode code point for this glyph, if available.+ ///+ /// Note: Type3 fonts can only provide Unicode via `ToUnicode` cmap.+ pub fn as_unicode(&self) -> Option<BfString> {+ self.font.char_code_to_unicode(self.char_code)+ }++ /// PrintCraft patch: the advance width in glyph space (1000 units per em), from `/Widths`.+ pub fn advance_width(&self) -> Option<f32> {+ u8::try_from(self.char_code).ok().map(|c| self.font.glyph_width(c))+ }+}++impl CacheKey for Type3Glyph<'_> {+ fn cache_key(&self) -> u128 {+ hash128(&(self.font.cache_key(), self.glyph_id))+ }+}++#[derive(Clone, Debug)]+pub(crate) struct Font<'a>(u128, FontType<'a>);++impl<'a> Font<'a> {+ pub(crate) fn new(+ dict: &Dict<'a>,+ font_resolver: &FontResolverFn,+ cmap_resolver: &CMapResolverFn,+ ) -> Option<Self> {+ let f_type = match dict.get::<Name<'_>>(SUBTYPE)?.deref() {+ TYPE1 | MM_TYPE1 => {+ FontType::Type1(Rc::new(Type1Font::new(dict, font_resolver, cmap_resolver)?))+ }+ // PDFBOX-5463: PDF viewers seem to accept OpenType as well.+ TRUE_TYPE | OPEN_TYPE => FontType::TrueType(Rc::new(TrueTypeFont::new(+ dict,+ font_resolver,+ cmap_resolver,+ )?)),+ TYPE0 => FontType::Type0(Rc::new(Type0Font::new(dict, font_resolver, cmap_resolver)?)),+ TYPE3 => FontType::Type3(Rc::new(Type3::new(dict, cmap_resolver)?)),+ f => {+ warn!(+ "unimplemented font type {:?}",+ std::str::from_utf8(f).unwrap_or("unknown type")+ );++ return None;+ }+ };++ let cache_key = dict.cache_key();++ Some(Self(cache_key, f_type))+ }++ pub(crate) fn new_standard(+ standard_font: StandardFont,+ font_resolver: &FontResolverFn,+ ) -> Option<Self> {+ let font = Type1Font::new_standard(standard_font, font_resolver)?;++ Some(Self(0, FontType::Type1(Rc::new(font))))+ }++ pub(crate) fn map_code(&self, code: u32) -> GlyphId {+ match &self.1 {+ FontType::Type1(f) => {+ debug_assert!(code <= u8::MAX as u32);++ f.map_code(code as u8)+ }+ FontType::TrueType(t) => {+ debug_assert!(code <= u8::MAX as u32);++ t.map_code(code as u8)+ }+ FontType::Type0(t) => t.map_code(code),+ FontType::Type3(t) => {+ debug_assert!(code <= u8::MAX as u32);++ t.map_code(code as u8)+ }+ }+ }++ pub(crate) fn get_glyph(+ &self,+ glyph: GlyphId,+ char_code: u32,+ ctx: &mut Context<'a>,+ resources: &Resources<'a>,+ origin_displacement: Vec2,+ ) -> (Glyph<'a>, Affine) {+ let glyph_transform = ctx.get().text_state.full_transform()+ * Affine::scale(1.0 / UNITS_PER_EM as f64)+ * Affine::translate(origin_displacement);++ let glyph = match &self.1 {+ FontType::Type1(t) => {+ let font = OutlineFont::Type1(t.clone());+ Glyph::Outline(OutlineGlyph {+ id: glyph,+ font,+ char_code,+ })+ }+ FontType::TrueType(t) => {+ let font = OutlineFont::TrueType(t.clone());+ Glyph::Outline(OutlineGlyph {+ id: glyph,+ font,+ char_code,+ })+ }+ FontType::Type0(t) => {+ let font = OutlineFont::Type0(t.clone());+ Glyph::Outline(OutlineGlyph {+ id: glyph,+ font,+ char_code,+ })+ }+ FontType::Type3(t) => {+ let nesting_depth = ctx.nesting_depth() + 1;+ let shape_glyph = Type3Glyph {+ font: t.clone(),+ glyph_id: glyph,+ state: ctx.get().clone(),+ parent_resources: resources.clone(),+ cache: ctx.interpreter_cache.clone(),+ xref: ctx.xref,+ settings: ctx.settings.clone(),+ nesting_depth,+ char_code,+ };++ Glyph::Type3(Box::new(shape_glyph))+ }+ };++ (glyph, glyph_transform)+ }++ pub(crate) fn code_advance(&self, code: u32) -> Vec2 {+ match &self.1 {+ FontType::Type1(t) => {+ debug_assert!(code <= u8::MAX as u32);++ Vec2::new(t.glyph_width(code as u8).unwrap_or(0.0) as f64, 0.0)+ }+ FontType::TrueType(t) => {+ debug_assert!(code <= u8::MAX as u32);++ Vec2::new(t.glyph_width(code as u8) as f64, 0.0)+ }+ FontType::Type0(t) => t.code_advance(code),+ FontType::Type3(t) => {+ debug_assert!(code <= u8::MAX as u32);++ Vec2::new(t.glyph_width(code as u8) as f64, 0.0)+ }+ }+ }++ pub(crate) fn origin_displacement(&self, code: u32) -> Vec2 {+ match &self.1 {+ FontType::Type1(_) => Vec2::default(),+ FontType::TrueType(_) => Vec2::default(),+ FontType::Type0(t) => t.origin_displacement(code),+ FontType::Type3(_) => Vec2::default(),+ }+ }++ pub(crate) fn read_code(&self, bytes: &[u8], offset: usize) -> (u32, usize) {+ match &self.1 {+ FontType::Type1(_) => (bytes[offset] as u32, 1),+ FontType::TrueType(_) => (bytes[offset] as u32, 1),+ FontType::Type0(t) => t.read_code(bytes, offset),+ FontType::Type3(_) => (bytes[offset] as u32, 1),+ }+ }++ pub(crate) fn is_horizontal(&self) -> bool {+ match &self.1 {+ FontType::Type1(_) => true,+ FontType::TrueType(_) => true,+ FontType::Type0(t) => t.is_horizontal(),+ FontType::Type3(_) => true,+ }+ }+}++impl CacheKey for Font<'_> {+ fn cache_key(&self) -> u128 {+ self.0+ }+}++#[derive(Clone, Debug)]+enum FontType<'a> {+ Type1(Rc<Type1Font>),+ TrueType(Rc<TrueTypeFont>),+ Type0(Rc<Type0Font>),+ Type3(Rc<Type3<'a>>),+}++#[derive(Debug)]+enum Encoding {+ Standard,+ MacRoman,+ WinAnsi,+ MacExpert,+ BuiltIn,+}++impl Encoding {+ fn map_code(&self, code: u8) -> Option<&'static str> {+ if code == 0 {+ return Some(".notdef");+ }+ match self {+ Self::Standard => standard::get(code),+ Self::MacRoman => mac_roman::get(code).or_else(|| mac_os_roman::get(code)),+ Self::WinAnsi => win_ansi::get(code),+ Self::MacExpert => mac_expert::get(code),+ Self::BuiltIn => None,+ }+ }+}++/// The font stretch.+#[derive(Debug, Copy, Clone)]+pub enum FontStretch {+ /// Normal.+ Normal,+ /// Ultra condensed.+ UltraCondensed,+ /// Extra condensed.+ ExtraCondensed,+ /// Condensed.+ Condensed,+ /// Semi condensed.+ SemiCondensed,+ /// Semi expanded.+ SemiExpanded,+ /// Expanded.+ Expanded,+ /// Extra expanded.+ ExtraExpanded,+ /// Ultra expanded.+ UltraExpanded,+}++impl FontStretch {+ fn from_string(s: &str) -> Self {+ match s {+ "UltraCondensed" => Self::UltraCondensed,+ "ExtraCondensed" => Self::ExtraCondensed,+ "Condensed" => Self::Condensed,+ "SemiCondensed" => Self::SemiCondensed,+ "SemiExpanded" => Self::SemiExpanded,+ "Expanded" => Self::Expanded,+ "ExtraExpanded" => Self::ExtraExpanded,+ "UltraExpanded" => Self::UltraExpanded,+ _ => Self::Normal,+ }+ }+}++bitflags! {+ /// Bitflags describing various characteristics of fonts.+ #[derive(Debug)]+ pub(crate) struct FontFlags: u32 {+ const FIXED_PITCH = 1 << 0;+ const SERIF = 1 << 1;+ const SYMBOLIC = 1 << 2;+ const SCRIPT = 1 << 3;+ const NON_SYMBOLIC = 1 << 5;+ const ITALIC = 1 << 6;+ const ALL_CAP = 1 << 16;+ const SMALL_CAP = 1 << 17;+ const FORCE_BOLD = 1 << 18;+ }+}++/// A query for a font.+pub enum FontQuery {+ /// A query for one of the 14 PDF standard fonts.+ Standard(StandardFont),+ /// A query for a font that is not embedded in the PDF file.+ ///+ /// Note that this type of query is currently not supported,+ /// but will be implemented in the future.+ Fallback(FallbackFontQuery),+}++/// A query for a font with specific properties.+#[derive(Debug, Clone)]+pub struct FallbackFontQuery {+ /// The postscript name of the font.+ pub post_script_name: Option<String>,+ /// The name of the font.+ pub font_name: Option<String>,+ /// The family of the font.+ pub font_family: Option<String>,+ /// The stretch of the font.+ pub font_stretch: FontStretch,+ /// The weight of the font.+ pub font_weight: u32,+ /// Whether the font is monospaced.+ pub is_fixed_pitch: bool,+ /// Whether the font is serif.+ pub is_serif: bool,+ /// Whether the font is italic.+ pub is_italic: bool,+ /// Whether the font is bold.+ pub is_bold: bool,+ /// Whether the font is small cap.+ pub is_small_cap: bool,+ /// The character collection (registry/ordering) if this is a CID font.+ pub character_collection: Option<CharacterCollection>,+}++impl FallbackFontQuery {+ pub(crate) fn new(dict: &Dict<'_>) -> Self {+ let post_script_name = dict+ .get::<Name<'_>>(BASE_FONT)+ .map(|n| strip_subset_prefix(n.as_str()).to_string());++ let mut data = Self {+ post_script_name,+ ..Default::default()+ };++ if let Some(descriptor) = dict.get::<Dict<'_>>(FONT_DESC) {+ data.font_name = dict+ .get::<Name<'_>>(FONT_NAME)+ .map(|n| strip_subset_prefix(n.as_str()).to_string());+ data.font_family = descriptor+ .get::<Name<'_>>(FONT_FAMILY)+ .map(|n| n.as_str().to_string());+ data.font_stretch = descriptor+ .get::<Name<'_>>(FONT_STRETCH)+ .map(|n| FontStretch::from_string(n.as_str()))+ .unwrap_or(FontStretch::Normal);+ data.font_weight = descriptor.get::<u32>(FONT_WEIGHT).unwrap_or(400);++ if let Some(flags) = descriptor+ .get::<u32>(FLAGS)+ .map(FontFlags::from_bits_truncate)+ {+ data.is_serif = flags.contains(FontFlags::SERIF);+ data.is_italic = flags.contains(FontFlags::ITALIC);+ data.is_small_cap = flags.contains(FontFlags::SMALL_CAP);+ }+ }++ data.is_italic |= data+ .post_script_name+ .as_ref()+ .is_some_and(|s| s.contains("Italic"));++ data.is_bold |= data+ .post_script_name+ .as_ref()+ .is_some_and(|s| s.contains("Bold"));++ data+ }++ /// Do a best-effort fallback to the 14 standard fonts based on the query.+ pub fn pick_standard_font(&self) -> StandardFont {+ if self.is_fixed_pitch {+ match (self.is_bold, self.is_italic) {+ (true, true) => StandardFont::CourierBoldOblique,+ (true, false) => StandardFont::CourierBold,+ (false, true) => StandardFont::CourierOblique,+ (false, false) => StandardFont::Courier,+ }+ } else if !self.is_serif {+ match (self.is_bold, self.is_italic) {+ (true, true) => StandardFont::HelveticaBoldOblique,+ (true, false) => StandardFont::HelveticaBold,+ (false, true) => StandardFont::HelveticaOblique,+ (false, false) => StandardFont::Helvetica,+ }+ } else {+ match (self.is_bold, self.is_italic) {+ (true, true) => StandardFont::TimesBoldItalic,+ (true, false) => StandardFont::TimesBold,+ (false, true) => StandardFont::TimesItalic,+ (false, false) => StandardFont::TimesRoman,+ }+ }+ }+}++impl Default for FallbackFontQuery {+ fn default() -> Self {+ Self {+ post_script_name: None,+ font_name: None,+ font_family: None,+ font_stretch: FontStretch::Normal,+ font_weight: 400,+ is_fixed_pitch: false,+ is_serif: false,+ is_italic: false,+ is_bold: false,+ is_small_cap: false,+ character_collection: None,+ }+ }+}++/// Convert a glyph name to a Unicode character, if possible.+/// An incomplete implementation of the Adobe Glyph List Specification+/// <https://github.com/adobe-type-tools/agl-specification>+pub(crate) fn glyph_name_to_unicode(name: &str) -> Option<char> {+ if let Some(unicode_str) = glyph_names::get(name) {+ return unicode_str.chars().next();+ }++ unicode_from_name(name).or_else(|| {+ warn!("failed to map glyph name {} to unicode", name);++ None+ })+}++pub(crate) fn unicode_from_name(name: &str) -> Option<char> {+ let convert = |input: &str| u32::from_str_radix(input, 16).ok().and_then(char::from_u32);++ name.starts_with("uni")+ .then(|| name.get(3..).and_then(convert))+ .or_else(|| {+ name.starts_with("u")+ .then(|| name.get(1..).and_then(convert))+ })+ .flatten()+}++pub(crate) fn read_to_unicode(dict: &Dict<'_>, cmap_resolver: &CMapResolverFn) -> Option<CMap> {+ dict.get::<Stream<'_>>(TO_UNICODE)+ .and_then(|s| s.decoded().ok())+ // See PDFJS-11915, where `Identity-H` is used for `ToUnicode`. I don't+ // believe it's valid, but at least mupdf seems to be able to deal with it.+ .or_else(|| {+ dict.get::<Name<'_>>(TO_UNICODE)+ .and_then(|name| (cmap_resolver)(CMapName::from_bytes(name.as_ref())))+ .map(|d| Cow::Owned(d.to_vec()))+ })+ .and_then(|data| {+ let cmap_resolver = cmap_resolver.clone();+ CMap::parse(&data, move |name| (cmap_resolver)(name))+ })+}++// When mapping to glyphs, some fonts might only have a glyph for the "normalized"+// name.+pub(crate) fn normalized_glyph_name(mut name: &str) -> &str {+ if name == "nbspace" {+ name = "space";+ }++ if name == "sfthyphen" {+ name = "hyphen";+ }++ name+}diff --git a/vendor/hayro-interpret/src/font/outline.rs b/vendor/hayro-interpret/src/font/outline.rsnew file mode 100644index 000000000..558d886ca--- /dev/null+++ b/vendor/hayro-interpret/src/font/outline.rs@@ -0,0 +1,146 @@+use crate::CacheKey;+use crate::font::cid::Type0Font;+use crate::font::true_type::TrueTypeFont;+use crate::font::type1::Type1Font;+use hayro_cmap::BfString;+use kurbo::BezPath;+use skrifa::GlyphId;+use skrifa::outline::OutlinePen;+use std::rc::Rc;++/// Font data and metadata for downstream use.+#[derive(Clone)]+pub struct OutlineFontData {+ /// Raw font bytes (TrueType/OpenType/CFF data).+ pub data: crate::font::FontData,+ /// Cache key for font deduplication.+ pub cache_key: u128,+ /// PostScript name (e.g., "TimesNewRomanPS-BoldMT").+ pub postscript_name: Option<String>,+ /// Font weight (100-900, 400=normal, 700=bold).+ pub weight: Option<u32>,+ /// Whether the font is italic/oblique.+ pub is_italic: bool,+ /// Whether the font is serif (vs sans-serif).+ pub is_serif: bool,+ /// Whether the font is monospace.+ pub is_monospace: bool,+}++pub(crate) struct OutlinePath(BezPath);++impl OutlinePath {+ pub(crate) fn new() -> Self {+ Self(BezPath::new())+ }++ pub(crate) fn take(self) -> BezPath {+ self.0+ }+}++impl OutlinePen for OutlinePath {+ #[inline]+ fn move_to(&mut self, x: f32, y: f32) {+ self.0.move_to((x, y));+ }++ #[inline]+ fn line_to(&mut self, x: f32, y: f32) {+ if !self.0.elements().is_empty() {+ self.0.line_to((x, y));+ }+ }++ #[inline]+ fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {+ if !self.0.elements().is_empty() {+ self.0.quad_to((cx, cy), (x, y));+ }+ }++ #[inline]+ fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {+ if !self.0.elements().is_empty() {+ self.0.curve_to((cx0, cy0), (cx1, cy1), (x, y));+ }+ }++ #[inline]+ fn close(&mut self) {+ if !self.0.elements().is_empty() {+ self.0.close_path();+ }+ }+}++#[derive(Debug, Clone)]+pub(crate) enum OutlineFont {+ Type1(Rc<Type1Font>),+ TrueType(Rc<TrueTypeFont>),+ Type0(Rc<Type0Font>),+}++impl CacheKey for OutlineFont {+ fn cache_key(&self) -> u128 {+ match self {+ Self::Type1(f) => f.cache_key(),+ Self::TrueType(t) => t.cache_key(),+ Self::Type0(t0) => t0.cache_key(),+ }+ }+}++impl OutlineFont {+ pub(crate) fn outline_glyph(&self, glyph: GlyphId, code: u32) -> BezPath {+ match self {+ Self::Type1(t) => t.outline_glyph(glyph),+ Self::TrueType(t) => t.outline_glyph(glyph),+ Self::Type0(t) => t.outline_glyph(glyph, code),+ }+ }++ pub(crate) fn char_code_to_unicode(&self, char_code: u32) -> Option<BfString> {+ match self {+ Self::Type1(t) => t.char_code_to_unicode(char_code),+ Self::TrueType(t) => t.char_code_to_unicode(char_code),+ Self::Type0(t) => t.char_code_to_unicode(char_code),+ }+ }++ /// Get the advance width for a glyph by character code.+ pub(crate) fn glyph_advance_width(&self, char_code: u32) -> Option<f32> {+ match self {+ Self::Type1(t) => t.glyph_width(char_code as u8),+ Self::TrueType(t) => Some(t.glyph_width(char_code as u8)),+ Self::Type0(t) => Some(t.code_advance(char_code).x as f32),+ }+ }++ /// Get raw font bytes and metadata.+ ///+ /// Returns None for Type1 fonts and non-embedded TrueType fonts.+ pub(crate) fn font_data(&self) -> Option<OutlineFontData> {+ match self {+ Self::Type1(_) => None,+ Self::TrueType(t) => Some(OutlineFontData {+ data: t.font_data()?,+ cache_key: t.cache_key(),+ postscript_name: t.postscript_name().map(|s| s.to_string()),+ weight: t.weight(),+ is_italic: t.is_italic(),+ is_serif: t.is_serif(),+ is_monospace: t.is_monospace(),+ }),+ Self::Type0(t) => Some(OutlineFontData {+ data: t.font_data()?,+ cache_key: t.cache_key(),+ postscript_name: t.postscript_name().map(|s| s.to_string()),+ weight: t.weight(),+ is_italic: t.is_italic(),+ is_serif: t.is_serif(),+ is_monospace: t.is_monospace(),+ }),+ }+ }+}diff --git a/vendor/hayro-interpret/src/font/standard_font.rs b/vendor/hayro-interpret/src/font/standard_font.rsnew file mode 100644index 000000000..c198e542a--- /dev/null+++ b/vendor/hayro-interpret/src/font/standard_font.rs@@ -0,0 +1,497 @@+use crate::FontResolverFn;+use crate::font::blob::{CffFontBlob, OpenTypeFontBlob};+use crate::font::generated::{glyph_names, metrics, standard, symbol, zapf_dings};+use crate::font::true_type::{Width, read_encoding, read_widths};+use crate::font::{+ Encoding, FontData, FontQuery, glyph_name_to_unicode, normalized_glyph_name, stretch_glyph,+ strip_subset_prefix,+};+use hayro_syntax::object::Dict;+use hayro_syntax::object::Name;+use hayro_syntax::object::dict::keys::{BASE_FONT, FONT_DESC, FONT_WEIGHT, ITALIC_ANGLE};+use kurbo::BezPath;+use skrifa::GlyphId;+use skrifa::raw::TableProvider;+use std::cell::RefCell;+use std::collections::HashMap;++/// The 14 standard fonts of PDF.+#[derive(Copy, Clone, Debug)]+pub enum StandardFont {+ /// Helvetica.+ Helvetica,+ /// Helvetica Bold.+ HelveticaBold,+ /// Helvetica Oblique.+ HelveticaOblique,+ /// Helvetica Bold Oblique.+ HelveticaBoldOblique,+ /// Courier.+ Courier,+ /// Courier Bold.+ CourierBold,+ /// Courier Oblique.+ CourierOblique,+ /// Courier Bold Oblique.+ CourierBoldOblique,+ /// Times Roman.+ TimesRoman,+ /// Times Bold.+ TimesBold,+ /// Times Italic.+ TimesItalic,+ /// Times Bold Italic.+ TimesBoldItalic,+ /// Zapf Dingbats - a decorative symbol font.+ ZapfDingBats,+ /// Symbol - a mathematical symbol font.+ Symbol,+}++impl StandardFont {+ pub(crate) fn code_to_name(&self, code: u8) -> Option<&'static str> {+ match self {+ Self::Symbol => symbol::get(code),+ // Note that this font does not return postscript character names,+ // but instead has a custom encoding.+ Self::ZapfDingBats => zapf_dings::get(code),+ _ => standard::get(code),+ }+ }++ pub(crate) fn get_width(&self, mut name: &str) -> Option<f32> {+ // <https://github.com/apache/pdfbox/blob/129aafe26548c1ff935af9c55cb40a996186c35f/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDSimpleFont.java#L340>+ if name == ".notdef" {+ return Some(250.0);+ }++ name = normalized_glyph_name(name);++ match self {+ Self::Helvetica => metrics::HELVETICA.get(name).copied(),+ Self::HelveticaBold => metrics::HELVETICA_BOLD.get(name).copied(),+ Self::HelveticaOblique => metrics::HELVETICA_OBLIQUE.get(name).copied(),+ Self::HelveticaBoldOblique => metrics::HELVETICA_BOLD_OBLIQUE.get(name).copied(),+ Self::Courier => metrics::COURIER.get(name).copied(),+ Self::CourierBold => metrics::COURIER_BOLD.get(name).copied(),+ Self::CourierOblique => metrics::COURIER_OBLIQUE.get(name).copied(),+ Self::CourierBoldOblique => metrics::COURIER_BOLD_OBLIQUE.get(name).copied(),+ Self::TimesRoman => metrics::TIMES_ROMAN.get(name).copied(),+ Self::TimesBold => metrics::TIMES_BOLD.get(name).copied(),+ Self::TimesItalic => metrics::TIMES_ITALIC.get(name).copied(),+ Self::TimesBoldItalic => metrics::TIMES_BOLD_ITALIC.get(name).copied(),+ Self::ZapfDingBats => metrics::ZAPF_DING_BATS.get(name).copied(),+ Self::Symbol => metrics::SYMBOL.get(name).copied(),+ }+ }++ pub(crate) fn as_str(&self) -> &'static str {+ match self {+ Self::Helvetica => "Helvetica",+ Self::HelveticaBold => "Helvetica Bold",+ Self::HelveticaOblique => "Helvetica Oblique",+ Self::HelveticaBoldOblique => "Helvetica Bold Oblique",+ Self::Courier => "Courier",+ Self::CourierBold => "Courier Bold",+ Self::CourierOblique => "Courier Oblique",+ Self::CourierBoldOblique => "Courier Bold Oblique",+ Self::TimesRoman => "Times Roman",+ Self::TimesBold => "Times Bold",+ Self::TimesItalic => "Times Italic",+ Self::TimesBoldItalic => "Times Bold Italic",+ Self::ZapfDingBats => "Zapf Dingbats",+ Self::Symbol => "Symbol",+ }+ }++ /// Return the postscrit name of the font.+ pub fn postscript_name(&self) -> &'static str {+ match self {+ Self::Helvetica => "Helvetica",+ Self::HelveticaBold => "Helvetica-Bold",+ Self::HelveticaOblique => "Helvetica-Oblique",+ Self::HelveticaBoldOblique => "Helvetica-BoldOblique",+ Self::Courier => "Courier",+ Self::CourierBold => "Courier-Bold",+ Self::CourierOblique => "Courier-Oblique",+ Self::CourierBoldOblique => "Courier-BoldOblique",+ Self::TimesRoman => "Times-Roman",+ Self::TimesBold => "Times-Bold",+ Self::TimesItalic => "Times-Italic",+ Self::TimesBoldItalic => "Times-BoldItalic",+ Self::ZapfDingBats => "ZapfDingbats",+ Self::Symbol => "Symbol",+ }+ }++ pub(crate) fn is_bold(&self) -> bool {+ matches!(+ self,+ Self::HelveticaBold+ | Self::HelveticaBoldOblique+ | Self::CourierBold+ | Self::CourierBoldOblique+ | Self::TimesBold+ | Self::TimesBoldItalic+ )+ }++ pub(crate) fn is_italic(&self) -> bool {+ matches!(+ self,+ Self::HelveticaOblique+ | Self::HelveticaBoldOblique+ | Self::CourierOblique+ | Self::CourierBoldOblique+ | Self::TimesItalic+ | Self::TimesBoldItalic+ )+ }++ pub(crate) fn is_serif(&self) -> bool {+ matches!(+ self,+ Self::TimesRoman | Self::TimesBold | Self::TimesItalic | Self::TimesBoldItalic+ )+ }++ pub(crate) fn is_monospace(&self) -> bool {+ matches!(+ self,+ Self::Courier | Self::CourierBold | Self::CourierOblique | Self::CourierBoldOblique+ )+ }++ /// Return suitable font data for the given standard font.+ ///+ /// Currently, this will return the corresponding Foxit font, which is a set of permissibly+ /// licensed fonts that is also very light-weight.+ ///+ /// You can use the result of this method in your implementation of [`FontResolverFn`].+ ///+ /// [`FontResolverFn`]: crate::FontResolverFn+ #[cfg(feature = "embed-fonts")]+ pub fn get_font_data(&self) -> (FontData, u32) {+ use std::sync::Arc;++ let data = match self {+ Self::Helvetica => &include_bytes!("../../assets/FoxitSans.pfb")[..],+ Self::HelveticaBold => &include_bytes!("../../assets/FoxitSansBold.pfb")[..],+ Self::HelveticaOblique => &include_bytes!("../../assets/FoxitSansItalic.pfb")[..],+ Self::HelveticaBoldOblique => {+ &include_bytes!("../../assets/FoxitSansBoldItalic.pfb")[..]+ }+ Self::Courier => &include_bytes!("../../assets/FoxitFixed.pfb")[..],+ Self::CourierBold => &include_bytes!("../../assets/FoxitFixedBold.pfb")[..],+ Self::CourierOblique => &include_bytes!("../../assets/FoxitFixedItalic.pfb")[..],+ Self::CourierBoldOblique => {+ &include_bytes!("../../assets/FoxitFixedBoldItalic.pfb")[..]+ }+ Self::TimesRoman => &include_bytes!("../../assets/FoxitSerif.pfb")[..],+ Self::TimesBold => &include_bytes!("../../assets/FoxitSerifBold.pfb")[..],+ Self::TimesItalic => &include_bytes!("../../assets/FoxitSerifItalic.pfb")[..],+ Self::TimesBoldItalic => &include_bytes!("../../assets/FoxitSerifBoldItalic.pfb")[..],+ Self::ZapfDingBats => &include_bytes!("../../assets/FoxitDingbats.pfb")[..],+ Self::Symbol => {+ include_bytes!("../../assets/FoxitSymbol.pfb")+ }+ };++ (Arc::new(data), 0)+ }+}++enum StandardFontFamily {+ Helvetica,+ Courier,+ Times,+}++pub(crate) fn select_standard_font(+ dict: &Dict<'_>,+ descriptor: &Dict<'_>,+) -> Option<(StandardFont, bool)> {+ let base_font = dict.get::<Name<'_>>(BASE_FONT)?;+ let name = strip_subset_prefix(base_font.as_str());++ // First try whether it matches literally.+ match name {+ "Helvetica" => return Some((StandardFont::Helvetica, true)),+ "Helvetica-Bold" => return Some((StandardFont::HelveticaBold, true)),+ "Helvetica-Oblique" => return Some((StandardFont::HelveticaOblique, true)),+ "Helvetica-BoldOblique" => return Some((StandardFont::HelveticaBoldOblique, true)),+ "Courier" => return Some((StandardFont::Courier, true)),+ "Courier-Bold" => return Some((StandardFont::CourierBold, true)),+ "Courier-Oblique" => return Some((StandardFont::CourierOblique, true)),+ "Courier-BoldOblique" => return Some((StandardFont::CourierBoldOblique, true)),+ "Times-Roman" => return Some((StandardFont::TimesRoman, true)),+ "Times-Bold" => return Some((StandardFont::TimesBold, true)),+ "Times-Italic" => return Some((StandardFont::TimesItalic, true)),+ "Times-BoldItalic" => return Some((StandardFont::TimesBoldItalic, true)),+ "Symbol" => return Some((StandardFont::Symbol, true)),+ "ZapfDingbats" => return Some((StandardFont::ZapfDingBats, true)),+ _ => {}+ }++ // Now, we bruteforce, trying to determine a suitable font based on the+ // keywords that appear in the name.+ let lower = name.to_ascii_lowercase();++ let is_bold = descriptor.get::<u32>(FONT_WEIGHT).is_some_and(|w| w >= 700)+ || lower.contains("bold")+ || lower.contains("demi");+ let is_italic = descriptor+ .get::<f32>(ITALIC_ANGLE)+ .is_some_and(|a| a != 0.0)+ || lower.contains("italic")+ || lower.contains("oblique");++ let (family, exact) = if lower.contains("helvetica") {+ (Some(StandardFontFamily::Helvetica), true)+ } else if lower.contains("arial") || lower.contains("sans") {+ (Some(StandardFontFamily::Helvetica), false)+ } else if lower.contains("courier") {+ (Some(StandardFontFamily::Courier), true)+ } else if lower.contains("mono") {+ (Some(StandardFontFamily::Courier), false)+ } else if lower.contains("times") {+ (Some(StandardFontFamily::Times), true)+ } else if lower.contains("serif") {+ (Some(StandardFontFamily::Times), false)+ } else if lower.contains("zapfdingbats") || lower.contains("dingbats") {+ return Some((StandardFont::ZapfDingBats, false));+ } else {+ (None, false)+ };++ let font = match (family?, is_bold, is_italic) {+ (StandardFontFamily::Helvetica, false, false) => StandardFont::Helvetica,+ (StandardFontFamily::Helvetica, true, false) => StandardFont::HelveticaBold,+ (StandardFontFamily::Helvetica, false, true) => StandardFont::HelveticaOblique,+ (StandardFontFamily::Helvetica, true, true) => StandardFont::HelveticaBoldOblique,+ (StandardFontFamily::Courier, false, false) => StandardFont::Courier,+ (StandardFontFamily::Courier, true, false) => StandardFont::CourierBold,+ (StandardFontFamily::Courier, false, true) => StandardFont::CourierOblique,+ (StandardFontFamily::Courier, true, true) => StandardFont::CourierBoldOblique,+ (StandardFontFamily::Times, false, false) => StandardFont::TimesRoman,+ (StandardFontFamily::Times, true, false) => StandardFont::TimesBold,+ (StandardFontFamily::Times, false, true) => StandardFont::TimesItalic,+ (StandardFontFamily::Times, true, true) => StandardFont::TimesBoldItalic,+ };++ Some((font, exact))+}++#[derive(Debug)]+pub(crate) enum StandardFontBlob {+ Cff(CffFontBlob),+ Otf(OpenTypeFontBlob, HashMap<String, GlyphId>),+}++impl StandardFontBlob {+ pub(crate) fn from_data(data: FontData, index: u32) -> Option<Self> {+ if let Some(blob) = CffFontBlob::new(data.clone()) {+ Some(Self::new_cff(blob))+ } else {+ OpenTypeFontBlob::new(data, index).map(Self::new_otf)+ }+ }++ pub(crate) fn new_cff(blob: CffFontBlob) -> Self {+ Self::Cff(blob)+ }++ pub(crate) fn new_otf(blob: OpenTypeFontBlob) -> Self {+ let glyph_names = blob.glyph_names();+ Self::Otf(blob, glyph_names)+ }+}++impl StandardFontBlob {+ pub(crate) fn name_to_glyph(&self, name: &str) -> Option<GlyphId> {+ match self {+ Self::Cff(blob) => blob.glyph_index_by_name(name),+ Self::Otf(_, glyph_names) => glyph_names.get(name).copied(),+ }+ }++ pub(crate) fn unicode_to_glyph(&self, code: u32) -> Option<GlyphId> {+ match self {+ Self::Cff(_) => None,+ Self::Otf(blob, _) => blob+ .font_ref()+ .cmap()+ .ok()+ .and_then(|c| c.map_codepoint(code)),+ }+ }++ pub(crate) fn advance_width(&self, glyph: GlyphId) -> Option<f32> {+ match self {+ Self::Cff(_) => None,+ Self::Otf(blob, _) => blob.glyph_metrics().advance_width(glyph),+ }+ }++ pub(crate) fn outline_glyph(&self, glyph: GlyphId) -> BezPath {+ // Standard fonts have empty outlines for these, but in Liberation Sans+ // they are a .notdef rectangle.+ if glyph == GlyphId::NOTDEF {+ return BezPath::new();+ }++ match self {+ Self::Cff(blob) => blob.outline_glyph(glyph),+ Self::Otf(blob, _) => blob.outline_glyph(glyph),+ }+ }+}++#[derive(Debug)]+pub(crate) struct StandardKind {+ base_font: StandardFont,+ base_font_blob: StandardFontBlob,+ encoding: Encoding,+ widths: Vec<Width>,+ missing_width: f32,+ fallback: bool,+ glyph_to_code: RefCell<HashMap<GlyphId, u8>>,+ encodings: HashMap<u8, String>,+}++impl StandardKind {+ pub(crate) fn new(dict: &Dict<'_>, resolver: &FontResolverFn) -> Option<Self> {+ let descriptor = dict.get::<Dict<'_>>(FONT_DESC).unwrap_or_default();+ let (font, exact) = select_standard_font(dict, &descriptor)?;+ Self::new_with_standard(dict, font, !exact, resolver)+ }++ pub(crate) fn new_with_standard(+ dict: &Dict<'_>,+ base_font: StandardFont,+ fallback: bool,+ resolver: &FontResolverFn,+ ) -> Option<Self> {+ let descriptor = dict.get::<Dict<'_>>(FONT_DESC).unwrap_or_default();+ let (widths, missing_width) = read_widths(dict, &descriptor)?;++ let (mut encoding, encoding_map) = read_encoding(dict);++ // See PDFJS-16464: Ignore encodings for non-embedded Type1 symbol fonts.+ if matches!(base_font, StandardFont::Symbol | StandardFont::ZapfDingBats) {+ encoding = Encoding::BuiltIn;+ }++ let (blob, index) = resolver(&FontQuery::Standard(base_font))?;+ let base_font_blob = StandardFontBlob::from_data(blob, index)?;++ Some(Self {+ base_font,+ base_font_blob,+ widths,+ missing_width,+ encodings: encoding_map,+ glyph_to_code: RefCell::new(HashMap::new()),+ fallback,+ encoding,+ })+ }++ fn code_to_ps_name(&self, code: u8) -> Option<&str> {+ let bf = self.base_font;++ self.encodings+ .get(&code)+ .map(String::as_str)+ .or_else(|| match self.encoding {+ Encoding::BuiltIn => bf.code_to_name(code),+ _ => self.encoding.map_code(code),+ })+ }++ pub(crate) fn map_code(&self, code: u8) -> GlyphId {+ let result = self+ .code_to_ps_name(code)+ .and_then(|c| {+ self.base_font_blob.name_to_glyph(c).or_else(|| {+ // If the font doesn't have a POST table, try to map via unicode instead.+ glyph_names::get(c).and_then(|c| {+ self.base_font_blob+ .unicode_to_glyph(c.chars().nth(0).unwrap() as u32)+ })+ })+ })+ .unwrap_or(GlyphId::NOTDEF);+ self.glyph_to_code.borrow_mut().insert(result, code);++ result+ }++ pub(crate) fn outline_glyph(&self, glyph: GlyphId) -> BezPath {+ let path = self.base_font_blob.outline_glyph(glyph);++ // If the font is not embedded, we might need to stretch it so that+ // it matches the metrics of the actual underlying font blob.++ if let Some(code) = self.glyph_to_code.borrow().get(&glyph).copied()+ && let Some(actual_width) = self.base_font_blob.advance_width(glyph).or_else(|| {+ self.code_to_ps_name(code)+ .and_then(|name| self.base_font.get_width(name))+ })+ {+ // From my experiments: Most PDF viewers, if they detect a font is a+ // standard font, they completely ignore the widths array, even if+ // different widths are indicated there. So only if it's an unknown+ // font do we check the widths array. Otherwise, we always use the+ // base font metrics.+ let should_width = if self.fallback {+ if let Some(Width::Value(w)) = self.widths.get(code as usize).copied() {+ w+ } else {+ return path;+ }+ } else if let Some(w) = self+ .code_to_ps_name(code)+ .and_then(|name| self.base_font.get_width(name))+ {+ w+ } else {+ return path;+ };++ return stretch_glyph(path, should_width, actual_width);+ }++ path+ }++ pub(crate) fn glyph_width(&self, code: u8) -> Option<f32> {+ match self.widths.get(code as usize).copied() {+ Some(Width::Value(w)) => Some(w),+ Some(Width::Missing) => Some(self.missing_width),+ None => self+ .code_to_ps_name(code)+ .and_then(|c| self.base_font.get_width(c)),+ }+ }++ pub(crate) fn char_code_to_unicode(&self, code: u8) -> Option<char> {+ self.code_to_ps_name(code).and_then(glyph_name_to_unicode)+ }++ pub(crate) fn is_italic(&self) -> bool {+ self.base_font.is_italic()+ }++ pub(crate) fn is_bold(&self) -> bool {+ self.base_font.is_bold()+ }++ pub(crate) fn is_serif(&self) -> bool {+ self.base_font.is_serif()+ }++ pub(crate) fn is_monospace(&self) -> bool {+ self.base_font.is_monospace()+ }+}diff --git a/vendor/hayro-interpret/src/font/true_type.rs b/vendor/hayro-interpret/src/font/true_type.rsnew file mode 100644index 000000000..c95bc229a--- /dev/null+++ b/vendor/hayro-interpret/src/font/true_type.rs@@ -0,0 +1,486 @@+use crate::font::blob::{CffFontBlob, OpenTypeFontBlob};+use crate::font::generated::{glyph_names, mac_os_roman, mac_roman, standard};+use crate::font::standard_font::StandardKind;+use crate::font::{+ Encoding, FallbackFontQuery, FontFlags, glyph_name_to_unicode, read_to_unicode,+ strip_subset_prefix, unicode_from_name,+};+use crate::util::OptionLog;+use crate::{CMapResolverFn, CacheKey, FontResolverFn};+use hayro_cmap::{BfString, CMap};+use hayro_syntax::object::Array;+use hayro_syntax::object::Dict;+use hayro_syntax::object::Name;+use hayro_syntax::object::Object;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::*;+use kurbo::BezPath;+use skrifa::attribute::Style;+use skrifa::raw::TableProvider;+use skrifa::raw::tables::cmap::PlatformId;+use skrifa::{GlyphId, MetadataProvider};+use std::cell::RefCell;+use std::collections::HashMap;+use std::ops::Deref;+use std::sync::Arc;++#[derive(Debug)]+pub(crate) struct TrueTypeFont {+ cache_key: u128,+ kind: Kind,+ to_unicode: Option<CMap>,+}++#[derive(Debug)]+enum Kind {+ Embedded(EmbeddedKind),+ Standard(StandardKind),+}++impl TrueTypeFont {+ pub(crate) fn new(+ dict: &Dict<'_>,+ font_resolver: &FontResolverFn,+ cmap_resolver: &CMapResolverFn,+ ) -> Option<Self> {+ let cache_key = dict.cache_key();+ let to_unicode = read_to_unicode(dict, cmap_resolver);++ if let Some(embedded) = EmbeddedKind::new(dict) {+ return Some(Self {+ cache_key,+ kind: Kind::Embedded(embedded),+ to_unicode,+ });+ }++ let fallback = || {+ let fallback_query = FallbackFontQuery::new(dict);+ let standard_font = fallback_query.pick_standard_font();++ warn!(+ "unable to load TrueType font {}, falling back to {}",+ fallback_query+ .post_script_name+ .unwrap_or("(no name)".to_string()),+ standard_font.as_str()+ );++ Some(Self {+ cache_key,+ kind: Kind::Standard(StandardKind::new_with_standard(+ dict,+ standard_font,+ true,+ font_resolver,+ )?),+ to_unicode: to_unicode.clone(),+ })+ };++ if let Some(standard) = StandardKind::new(dict, font_resolver) {+ Some(Self {+ cache_key,+ kind: Kind::Standard(standard),+ to_unicode,+ })+ } else {+ fallback()+ }+ }++ pub(crate) fn outline_glyph(&self, glyph: GlyphId) -> BezPath {+ match &self.kind {+ Kind::Embedded(e) => e.outline_glyph(glyph),+ Kind::Standard(s) => s.outline_glyph(glyph),+ }+ }++ pub(crate) fn font_data(&self) -> Option<crate::font::FontData> {+ match &self.kind {+ Kind::Embedded(e) => Some(e.base_font.font_data()),+ Kind::Standard(_) => None,+ }+ }++ pub(crate) fn postscript_name(&self) -> Option<&str> {+ match &self.kind {+ Kind::Embedded(e) => e.postscript_name.as_deref(),+ Kind::Standard(_) => None,+ }+ }++ pub(crate) fn weight(&self) -> Option<u32> {+ match &self.kind {+ Kind::Embedded(e) => {+ let weight = e.base_font.font_ref().attributes().weight.value().round() as u32;+ if weight > 0 { Some(weight) } else { None }+ }+ Kind::Standard(s) => Some(if s.is_bold() { 700 } else { 400 }),+ }+ }++ pub(crate) fn is_italic(&self) -> bool {+ match &self.kind {+ Kind::Embedded(e) => {+ // Check PDF font flags first+ if let Some(flags) = &e.font_flags+ && flags.contains(FontFlags::ITALIC)+ {+ return true;+ }+ // Check skrifa font attributes+ e.base_font.font_ref().attributes().style != Style::Normal+ }+ Kind::Standard(s) => s.is_italic(),+ }+ }++ pub(crate) fn is_serif(&self) -> bool {+ match &self.kind {+ Kind::Embedded(e) => e+ .font_flags+ .as_ref()+ .is_some_and(|f| f.contains(FontFlags::SERIF)),+ Kind::Standard(s) => s.is_serif(),+ }+ }++ pub(crate) fn is_monospace(&self) -> bool {+ match &self.kind {+ Kind::Embedded(e) => {+ // Check PDF font flags first+ if let Some(flags) = &e.font_flags+ && flags.contains(FontFlags::FIXED_PITCH)+ {+ return true;+ }+ // Check skrifa font metrics+ e.base_font+ .font_ref()+ .metrics(+ skrifa::instance::Size::unscaled(),+ skrifa::instance::LocationRef::default(),+ )+ .is_monospace+ }+ Kind::Standard(s) => s.is_monospace(),+ }+ }++ pub(crate) fn map_code(&self, code: u8) -> GlyphId {+ match &self.kind {+ Kind::Embedded(e) => e.map_code(code),+ Kind::Standard(s) => s.map_code(code),+ }+ }++ pub(crate) fn glyph_width(&self, code: u8) -> f32 {+ match &self.kind {+ Kind::Embedded(e) => e.glyph_width(code),+ Kind::Standard(s) => s.glyph_width(code).unwrap_or(0.0),+ }+ }++ pub(crate) fn char_code_to_unicode(&self, code: u32) -> Option<BfString> {+ if let Some(to_unicode) = &self.to_unicode+ && let Some(c) = to_unicode.lookup_bf_string(code)+ {+ return Some(c);+ }++ match &self.kind {+ Kind::Embedded(e) => e+ .code_to_name(code as u8)+ .and_then(glyph_name_to_unicode)+ .map(BfString::Char),+ Kind::Standard(s) => s.char_code_to_unicode(code as u8).map(BfString::Char),+ }++ // TODO: The test PDFs below fail (but mutool can render them correctly).+ // There is likely some other strategy that requires processing the font tables+ // hayro-tests/pdfs/custom/font_truetype_7.pdf+ // hayro-tests/pdfs/custom/font_truetype_6.pdf+ }+}++#[derive(Debug)]+struct EmbeddedKind {+ base_font: OpenTypeFontBlob,+ widths: Vec<Width>,+ missing_width: f32,+ font_flags: Option<FontFlags>,+ glyph_names: HashMap<String, GlyphId>,+ encoding: Encoding,+ // Only used for PDFs that mistakenly embed a+ // CFF font.+ cff_blob: Option<CffFontBlob>,+ differences: HashMap<u8, String>,+ cached_mappings: RefCell<HashMap<u8, GlyphId>>,+ /// PostScript name from the PDF.+ postscript_name: Option<String>,+}++impl EmbeddedKind {+ fn new(dict: &Dict<'_>) -> Option<Self> {+ let descriptor = dict.get::<Dict<'_>>(FONT_DESC).unwrap_or_default();++ let font_flags = descriptor.get::<u32>(FLAGS).and_then(FontFlags::from_bits);++ let (widths, missing_width) = read_widths(dict, &descriptor)?;+ let (encoding, differences) = read_encoding(dict);+ let base_font = descriptor+ .get::<Stream<'_>>(FONT_FILE2)+ .and_then(|s| s.decoded().ok())+ .and_then(|d| OpenTypeFontBlob::new(Arc::new(d.to_vec()), 0))?;++ let glyph_names = base_font.glyph_names();++ let cff_font_blob = base_font+ .font_ref()+ .cff()+ .ok()+ .and_then(|cff| CffFontBlob::new(Arc::new(cff.offset_data().as_ref().to_vec())));++ let postscript_name = dict+ .get::<Name<'_>>(BASE_FONT)+ .map(|n| strip_subset_prefix(n.as_str()).to_string());++ Some(Self {+ base_font,+ differences,+ cff_blob: cff_font_blob,+ widths,+ missing_width,+ glyph_names,+ font_flags,+ encoding,+ cached_mappings: RefCell::new(HashMap::new()),+ postscript_name,+ })+ }++ fn is_non_symbolic(&self) -> bool {+ self.font_flags+ .as_ref()+ .map(|f| f.contains(FontFlags::NON_SYMBOLIC))+ .unwrap_or(false)+ }++ fn code_to_name(&self, code: u8) -> Option<&str> {+ self.differences+ .get(&code)+ .map(|s| s.as_str())+ .or_else(|| self.encoding.map_code(code))+ // See PDFJS-6410 - PDF has no base encoding, so let's fallback to+ // standard here.+ .or_else(|| standard::get(code))+ }++ fn outline_glyph(&self, glyph: GlyphId) -> BezPath {+ self.base_font.outline_glyph(glyph)+ }++ fn map_code(&self, code: u8) -> GlyphId {+ if let Some(glyph) = self.cached_mappings.borrow().get(&code) {+ return *glyph;+ }++ if let Some(blob) = self.cff_blob.as_ref() {+ return self+ .code_to_name(code)+ .and_then(|name| blob.glyph_index_by_name(name))+ .unwrap_or(GlyphId::NOTDEF);+ }++ let mut glyph = None;++ if self.is_non_symbolic() {+ let Some(lookup) = self.code_to_name(code) else {+ return GlyphId::NOTDEF;+ };++ if let Ok(cmap) = self.base_font.font_ref().cmap() {+ for record in cmap.encoding_records() {+ if record.platform_id() == PlatformId::Windows+ && record.encoding_id() == 1+ && let Ok(subtable) = record.subtable(cmap.offset_data())+ {+ glyph = glyph.or_else(|| {+ glyph_names::get(lookup)+ .map(|n| n.to_string())+ .or_else(|| unicode_from_name(lookup).map(|n| n.to_string()))+ .and_then(|n| n.chars().next())+ .and_then(|c| subtable.map_codepoint(c))+ .filter(|g| *g != GlyphId::NOTDEF)+ });+ }+ }++ for record in cmap.encoding_records() {+ if record.platform_id() == PlatformId::Macintosh+ && record.encoding_id() == 0+ && let Ok(subtable) = record.subtable(cmap.offset_data())+ {+ glyph = glyph.or_else(|| {+ mac_os_roman::get_inverse(lookup)+ .or_else(|| mac_roman::get_inverse(lookup))+ .and_then(|c| subtable.map_codepoint(c))+ .filter(|g| *g != GlyphId::NOTDEF)+ });+ }+ }+ }++ if glyph.is_none() {+ if let Some(gid) = self.glyph_names.get(lookup) {+ glyph = Some(*gid);+ } else if let Some(gid) = glyph_num_string(lookup) {+ glyph = Some(GlyphId::new(gid));+ }+ }+ } else if let Ok(cmap) = self.base_font.font_ref().cmap() {+ for record in cmap.encoding_records() {+ if record.platform_id() == PlatformId::Windows+ && matches!(record.encoding_id(), 0 | 1)+ {+ if let Ok(subtable) = record.subtable(cmap.offset_data()) {+ for offset in [0x0000_u32, 0xF000, 0xF100, 0xF200] {+ glyph = glyph+ .or_else(|| subtable.map_codepoint(code as u32 + offset))+ .filter(|g| *g != GlyphId::NOTDEF);+ }+ }+ } else if matches!(+ record.platform_id(),+ PlatformId::Macintosh | PlatformId::Unicode+ ) && record.encoding_id() == 0+ && let Ok(subtable) = record.subtable(cmap.offset_data())+ {+ glyph = glyph+ .or_else(|| subtable.map_codepoint(code))+ .filter(|g| *g != GlyphId::NOTDEF);+ }+ }+ }++ let glyph = glyph.unwrap_or(GlyphId::NOTDEF);+ self.cached_mappings.borrow_mut().insert(code, glyph);++ glyph+ }++ fn glyph_width(&self, code: u8) -> f32 {+ match self.widths.get(code as usize).copied() {+ Some(Width::Value(w)) => w,+ Some(Width::Missing) => self.missing_width,+ _ => self+ .base_font+ .glyph_metrics()+ .advance_width(self.map_code(code))+ .warn_none(&format!("failed to find advance width for code {code}"))+ .unwrap_or(0.0),+ }+ }+}++#[derive(Debug, Clone, Copy)]+pub(crate) enum Width {+ Value(f32),+ Missing,+}++pub(crate) fn read_widths(dict: &Dict<'_>, descriptor: &Dict<'_>) -> Option<(Vec<Width>, f32)> {+ let mut widths = Vec::new();++ let first_char = dict.get::<usize>(FIRST_CHAR);+ let last_char = dict.get::<usize>(LAST_CHAR);+ let widths_arr = dict.get::<Array<'_>>(WIDTHS);+ let missing_width = descriptor.get::<f32>(MISSING_WIDTH).unwrap_or(0.0);++ if let (Some(fc), Some(lc), Some(w)) = (first_char, last_char, widths_arr) {+ let iter = w.iter::<f32>().take(lc.checked_sub(fc)?.checked_add(1)?);++ for _ in 0..fc {+ widths.push(Width::Missing);+ }++ for w in iter {+ widths.push(Width::Value(w));+ }++ while widths.len() <= (u8::MAX as usize) + 1 {+ widths.push(Width::Missing);+ }+ }++ Some((widths, missing_width))+}++fn glyph_num_string(s: &str) -> Option<u32> {+ if !s.starts_with('g') || s.len() < 2 {+ return None;+ }++ s[1..].parse::<u32>().ok()+}++impl CacheKey for TrueTypeFont {+ fn cache_key(&self) -> u128 {+ self.cache_key+ }+}++pub(crate) fn read_encoding(dict: &Dict<'_>) -> (Encoding, HashMap<u8, String>) {+ fn get_encoding_base(dict: &Dict<'_>, name: Name<'_>) -> Encoding {+ match dict.get::<Name<'_>>(name.as_ref()) {+ Some(n) => match n.deref() {+ WIN_ANSI_ENCODING => Encoding::WinAnsi,+ MAC_ROMAN_ENCODING => Encoding::MacRoman,+ MAC_EXPERT_ENCODING => Encoding::MacExpert,+ STANDARD_ENCODING => Encoding::Standard,+ _ => {+ warn!("Unknown font encoding {}", name.as_str());++ Encoding::BuiltIn+ }+ },+ None => Encoding::BuiltIn,+ }+ }++ let mut map = HashMap::new();++ if let Some(encoding_dict) = dict.get::<Dict<'_>>(ENCODING) {+ if let Some(differences) = encoding_dict.get::<Array<'_>>(DIFFERENCES) {+ let entries = differences.iter::<Object<'_>>();++ let mut code = 0_i64;++ for obj in entries {+ match obj {+ Object::Number(num) => {+ code = num.as_i64();+ }+ Object::Name(name) => {+ if let Ok(code) = code.try_into() {+ map.insert(code, name.as_str().to_string());+ }+ code += 1;+ }+ _ => {}+ }+ }+ }++ (+ get_encoding_base(&encoding_dict, Name::new_unescaped(BASE_ENCODING)),+ map,+ )+ } else {+ (+ get_encoding_base(dict, Name::new_unescaped(ENCODING)),+ HashMap::new(),+ )+ }+}diff --git a/vendor/hayro-interpret/src/font/type1.rs b/vendor/hayro-interpret/src/font/type1.rsnew file mode 100644index 000000000..32b5e3ddd--- /dev/null+++ b/vendor/hayro-interpret/src/font/type1.rs@@ -0,0 +1,341 @@+use crate::font::blob::{CffFontBlob, Type1FontBlob};+use crate::font::standard_font::{StandardFont, StandardKind, select_standard_font};+use crate::font::true_type::{Width, read_encoding, read_widths};+use crate::font::{+ Encoding, FallbackFontQuery, glyph_name_to_unicode, normalized_glyph_name, read_to_unicode,+};+use crate::{CMapResolverFn, CacheKey, FontResolverFn};+use hayro_cmap::{BfString, CMap};+use hayro_syntax::object::Dict;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::{FONT_DESC, FONT_FILE, FONT_FILE3};+use kurbo::BezPath;+use skrifa::GlyphId;+use std::collections::HashMap;+use std::sync::Arc;++#[derive(Debug)]+pub(crate) struct Type1Font(u128, Kind, Option<CMap>);++impl Type1Font {+ pub(crate) fn new(+ dict: &Dict<'_>,+ resolver: &FontResolverFn,+ cmap_resolver: &CMapResolverFn,+ ) -> Option<Self> {+ let cache_key = dict.cache_key();++ let to_unicode = read_to_unicode(dict, cmap_resolver);++ let fallback = || {+ // TODO: Actually use fallback fonts+ let fallback_query = FallbackFontQuery::new(dict);+ let standard_font = fallback_query.pick_standard_font();++ warn!(+ "unable to load font {}, falling back to {}",+ fallback_query+ .post_script_name+ .unwrap_or("(no name)".to_string()),+ standard_font.as_str()+ );++ Some(Self(+ cache_key,+ Kind::Standard(StandardKind::new_with_standard(+ dict,+ standard_font,+ true,+ resolver,+ )?),+ to_unicode.clone(),+ ))+ };++ let inner = if is_cff(dict) {+ if let Some(cff) = CffKind::new(dict) {+ Self(cache_key, Kind::Cff(cff), to_unicode)+ } else {+ return fallback();+ }+ } else if is_type1(dict) {+ if let Some(f) = Type1Kind::new(dict) {+ Self(cache_key, Kind::Type1(f), to_unicode)+ } else {+ return fallback();+ }+ } else if let Some(standard) = StandardKind::new(dict, resolver) {+ Self(cache_key, Kind::Standard(standard), to_unicode)+ } else {+ return fallback();+ };++ Some(inner)+ }++ pub(crate) fn new_standard(font: StandardFont, resolver: &FontResolverFn) -> Option<Self> {+ let dict = Dict::default();+ let standard = StandardKind::new_with_standard(&dict, font, true, resolver)?;++ Some(Self(0, Kind::Standard(standard), None))+ }++ pub(crate) fn map_code(&self, code: u8) -> GlyphId {+ match &self.1 {+ Kind::Standard(s) => s.map_code(code),+ Kind::Type1(s) => s.map_code(code),+ Kind::Cff(c) => c.map_code(code),+ }+ }++ pub(crate) fn outline_glyph(&self, glyph: GlyphId) -> BezPath {+ match &self.1 {+ Kind::Standard(s) => s.outline_glyph(glyph),+ Kind::Cff(c) => c.outline_glyph(glyph),+ Kind::Type1(t) => t.outline_glyph(glyph),+ }+ }++ pub(crate) fn glyph_width(&self, code: u8) -> Option<f32> {+ match &self.1 {+ Kind::Standard(s) => s.glyph_width(code),+ Kind::Cff(c) => c.glyph_width(code),+ Kind::Type1(t) => t.glyph_width(code),+ }+ }++ pub(crate) fn char_code_to_unicode(&self, char_code: u32) -> Option<BfString> {+ if let Some(to_unicode) = &self.2+ && let Some(c) = to_unicode.lookup_bf_string(char_code)+ {+ // Skip null character mappings and fall back to glyph name+ // lookup. Some PDFs have incorrect ToUnicode mappings that map+ // to U+0000.+ if c != BfString::Char('\0') {+ return Some(c);+ }+ }++ let code = char_code as u8;+ match &self.1 {+ Kind::Standard(s) => s.char_code_to_unicode(code).map(BfString::Char),+ Kind::Cff(c) => c.char_code_to_unicode(code).map(BfString::Char),+ Kind::Type1(t) => t.char_code_to_unicode(code).map(BfString::Char),+ }+ }+}++impl CacheKey for Type1Font {+ fn cache_key(&self) -> u128 {+ self.0+ }+}++#[derive(Debug)]+enum Kind {+ Standard(StandardKind),+ Cff(CffKind),+ Type1(Type1Kind),+}++fn is_cff(dict: &Dict<'_>) -> bool {+ dict.get::<Dict<'_>>(FONT_DESC)+ .map(|dict| dict.contains_key(FONT_FILE3))+ .unwrap_or(false)+}++fn is_type1(dict: &Dict<'_>) -> bool {+ dict.get::<Dict<'_>>(FONT_DESC)+ .map(|dict| dict.contains_key(FONT_FILE))+ .unwrap_or(false)+}++#[derive(Debug)]+struct Type1Kind {+ font: Type1FontBlob,+ encoding: Encoding,+ widths: Vec<Width>,+ missing_width: f32,+ encodings: HashMap<u8, String>,+ name_to_gid: HashMap<String, GlyphId>,+ standard_font: Option<StandardFont>,+}++impl Type1Kind {+ fn new(dict: &Dict<'_>) -> Option<Self> {+ let descriptor = dict.get::<Dict<'_>>(FONT_DESC)?;+ let data = descriptor.get::<Stream<'_>>(FONT_FILE)?;+ let font = Type1FontBlob::new(Arc::new(data.decoded().ok()?.to_vec()))?;++ let (encoding, encodings) = read_encoding(dict);+ let (widths, missing_width) = read_widths(dict, &descriptor)?;+ let standard_font = select_standard_font(dict, &descriptor).map(|(f, _)| f);++ let name_to_gid: HashMap<String, GlyphId> = font+ .table()+ .glyph_names()+ .map(|(gid, name)| (name.to_string(), gid))+ .collect();++ Some(Self {+ font,+ encoding,+ widths,+ missing_width,+ encodings,+ name_to_gid,+ standard_font,+ })+ }++ fn name_to_glyph(&self, name: &str) -> Option<GlyphId> {+ self.name_to_gid.get(name).copied()+ }++ fn map_code(&self, code: u8) -> GlyphId {+ if let Some(entry) = self.encodings.get(&code) {+ self.name_to_glyph(entry)+ } else {+ match self.encoding {+ Encoding::BuiltIn => self.font.table().encoding().and_then(|e| e.map(code)),+ _ => self+ .encoding+ .map_code(code)+ .and_then(|name| self.name_to_glyph(name)),+ }+ }+ .unwrap_or(GlyphId::NOTDEF)+ }++ fn outline_glyph(&self, glyph: GlyphId) -> BezPath {+ self.font.outline_glyph(glyph)+ }++ fn code_to_ps_name(&self, code: u8) -> Option<&str> {+ self.encodings+ .get(&code)+ .map(String::as_str)+ .or_else(|| match self.encoding {+ Encoding::BuiltIn => self+ .font+ .table()+ .encoding()+ .and_then(|e| e.glyph_name(code)),+ _ => self.encoding.map_code(code),+ })+ }++ fn glyph_width(&self, code: u8) -> Option<f32> {+ match self.widths.get(code as usize).copied() {+ Some(Width::Value(w)) => Some(w),+ Some(Width::Missing) => Some(self.missing_width),+ _ => {+ // If font looks like a standard font, get the width from there.+ let sf = self.standard_font?;+ self.code_to_ps_name(code)+ .and_then(|name| sf.get_width(name))+ }+ }+ }++ fn char_code_to_unicode(&self, code: u8) -> Option<char> {+ self.code_to_ps_name(code).and_then(glyph_name_to_unicode)+ }+}++#[derive(Debug)]+struct CffKind {+ font: CffFontBlob,+ encoding: Encoding,+ widths: Vec<Width>,+ missing_width: f32,+ encodings: HashMap<u8, String>,+ name_to_gid: HashMap<String, GlyphId>,+ gid_to_name: Vec<Option<String>>,+ standard_font: Option<StandardFont>,+}++impl CffKind {+ fn new(dict: &Dict<'_>) -> Option<Self> {+ let descriptor = dict.get::<Dict<'_>>(FONT_DESC)?;+ let data = descriptor.get::<Stream<'_>>(FONT_FILE3)?;+ let font = CffFontBlob::new(Arc::new(data.decoded().ok()?.to_vec()))?;++ let (encoding, encodings) = read_encoding(dict);+ let (widths, missing_width) = read_widths(dict, &descriptor)?;+ let standard_font = select_standard_font(dict, &descriptor).map(|(f, _)| f);+ let mut gid_to_name = vec![None; font.num_glyphs() as usize];+ let name_to_gid: HashMap<String, GlyphId> = font+ .glyph_names()+ .into_iter()+ .inspect(|(gid, name)| gid_to_name[gid.to_u32() as usize] = Some(name.clone()))+ .map(|(gid, name)| (name, gid))+ .collect();++ Some(Self {+ font,+ encoding,+ widths,+ missing_width,+ encodings,+ name_to_gid,+ gid_to_name,+ standard_font,+ })+ }++ fn map_code(&self, code: u8) -> GlyphId {+ let get_glyph = |entry: &str| {+ self.name_to_gid+ .get(entry)+ .copied()+ .or_else(|| self.name_to_gid.get(normalized_glyph_name(entry)).copied())+ };++ if let Some(entry) = self.encodings.get(&code) {+ get_glyph(entry)+ } else {+ match self.encoding {+ Encoding::BuiltIn => self.font.glyph_index(code),+ _ => self.encoding.map_code(code).and_then(get_glyph),+ }+ }+ .unwrap_or(GlyphId::NOTDEF)+ }++ fn outline_glyph(&self, glyph: GlyphId) -> BezPath {+ self.font.outline_glyph(glyph)+ }++ fn code_to_ps_name(&self, code: u8) -> Option<&str> {+ if let Some(entry) = self.encodings.get(&code) {+ Some(entry.as_str())+ } else {+ match self.encoding {+ Encoding::BuiltIn => self+ .font+ .glyph_index(code)+ .and_then(|gid| self.gid_to_name.get(gid.to_u32() as usize))+ .and_then(|name| name.as_deref()),+ _ => self.encoding.map_code(code),+ }+ }+ }++ fn glyph_width(&self, code: u8) -> Option<f32> {+ match self.widths.get(code as usize).copied() {+ Some(Width::Value(w)) => Some(w),+ Some(Width::Missing) => Some(self.missing_width),+ _ => {+ // If font looks like a standard font, get the width from there.+ let sf = self.standard_font?;+ self.code_to_ps_name(code)+ .and_then(|name| sf.get_width(name))+ }+ }+ }++ fn char_code_to_unicode(&self, code: u8) -> Option<char> {+ self.code_to_ps_name(code).and_then(glyph_name_to_unicode)+ }+}diff --git a/vendor/hayro-interpret/src/font/type3.rs b/vendor/hayro-interpret/src/font/type3.rsnew file mode 100644index 000000000..877f551ad--- /dev/null+++ b/vendor/hayro-interpret/src/font/type3.rs@@ -0,0 +1,260 @@+use crate::CMapResolverFn;+use crate::context::Context;+use crate::device::Device;+use crate::font::glyph_simulator::GlyphSimulator;+use crate::font::true_type::{Width, read_encoding, read_widths};+use crate::font::{Encoding, Glyph, Type3Glyph, UNITS_PER_EM, read_to_unicode};+use crate::interpret::state::TextState;+use crate::soft_mask::SoftMask;+use crate::util::RectExt;+use crate::{BlendMode, interpret};+use crate::{CacheKey, ClipPath, GlyphDrawMode, PathDrawMode};+use crate::{Image, Paint};+use hayro_cmap::{BfString, CMap};+use hayro_syntax::content::TypedIter;+use hayro_syntax::content::ops::TypedInstruction;+use hayro_syntax::object::Dict;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::{CHAR_PROCS, FONT_BBOX, FONT_MATRIX, RESOURCES};+use hayro_syntax::page::Resources;+use kurbo::{Affine, BezPath, Rect};+use skrifa::GlyphId;+use std::collections::HashMap;++#[derive(Debug)]+pub(crate) struct Type3<'a> {+ widths: Vec<Width>,+ missing_width: f32,+ encoding: Encoding,+ encodings: HashMap<u8, String>,+ dict: Dict<'a>,+ char_procs: HashMap<String, Stream<'a>>,+ glyph_simulator: GlyphSimulator,+ font_bbox: Rect,+ matrix: Affine,+ to_unicode: Option<CMap>,+}++impl<'a> Type3<'a> {+ pub(crate) fn new(dict: &Dict<'a>, cmap_resolver: &CMapResolverFn) -> Option<Self> {+ let (encoding, encodings) = read_encoding(dict);+ let (widths, missing_width) = read_widths(dict, dict)?;+ let font_bbox = dict+ .get::<hayro_syntax::object::Rect>(FONT_BBOX)+ .unwrap_or(hayro_syntax::object::Rect::ZERO)+ .to_kurbo();++ let matrix = Affine::new(+ dict.get::<[f64; 6]>(FONT_MATRIX)+ .unwrap_or([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]),+ );++ let char_procs = {+ let mut procs = HashMap::new();+ let dict = dict.get::<Dict<'_>>(CHAR_PROCS).unwrap_or_default();++ for name in dict.keys() {+ if let Some(prog) = dict.get::<Stream<'_>>(name.as_ref()) {+ procs.insert(name.as_str().to_string(), prog);+ }+ }++ procs+ };++ let to_unicode = read_to_unicode(dict, cmap_resolver);++ Some(Self {+ glyph_simulator: GlyphSimulator::new(),+ encoding,+ font_bbox,+ char_procs,+ widths,+ missing_width,+ encodings,+ matrix,+ dict: dict.clone(),+ to_unicode,+ })+ }++ pub(crate) fn map_code(&self, code: u8) -> GlyphId {+ self.encodings+ .get(&code)+ .map(|s| s.as_str())+ .or_else(|| self.encoding.map_code(code))+ .map(|g| self.glyph_simulator.string_to_glyph(g))+ .unwrap_or(GlyphId::NOTDEF)+ }++ pub(crate) fn glyph_width(&self, code: u8) -> f32 {+ let w = match self.widths.get(code as usize).copied() {+ Some(Width::Value(w)) => w,+ _ => self.missing_width,+ };+ (w * self.matrix.as_coeffs()[0] as f32) * UNITS_PER_EM+ }++ pub(crate) fn char_code_to_unicode(&self, char_code: u32) -> Option<BfString> {+ // PrintCraft patch: upstream only consulted ToUnicode. Many Type3 fonts (e.g. TeX/dvips+ // bitmap fonts) have none; fall back to the /Encoding glyph names, then to printable+ // ASCII codes, as other viewers do for text extraction.+ self.to_unicode+ .as_ref()+ .and_then(|t| t.lookup_bf_string(char_code))+ .or_else(|| {+ let code = u8::try_from(char_code).ok()?;+ let name = self+ .encodings+ .get(&code)+ .map(|s| s.as_str())+ .or_else(|| self.encoding.map_code(code));+ name.and_then(crate::font::glyph_name_to_unicode)+ .or_else(|| (0x20..0x7f).contains(&code).then_some(code as char))+ .map(BfString::Char)+ })+ }++ pub(crate) fn render_glyph(+ &self,+ glyph: &Type3Glyph<'a>,+ transform: Affine,+ glyph_transform: Affine,+ paint: &Paint<'a>,+ device: &mut impl Device<'a>,+ ) -> Option<()> {+ let mut state = glyph.state.clone();+ let root_transform =+ transform * glyph_transform * self.matrix * Affine::scale(UNITS_PER_EM as f64);+ state.ctm = root_transform;++ // Not sure if this is mentioned anywhere, but I do think we need to reset the text state+ // (though the graphics state itself should be preserved).+ state.text_state = TextState::default();++ let name = self.glyph_simulator.glyph_to_string(glyph.glyph_id)?;+ let program = self.char_procs.get(&name)?;+ let decoded = program.decoded().ok()?;+ let iter = TypedIter::new(decoded.as_ref());++ let is_shape_glyph = {+ let mut iter = iter.clone();+ let mut is_shape_glyph = true;++ while let Some(op) = iter.next() {+ match op {+ TypedInstruction::ShapeGlyph(_) => {+ break;+ }+ TypedInstruction::ColorGlyph(_) => {+ is_shape_glyph = false;+ break;+ }+ _ => {}+ }+ }++ is_shape_glyph+ };++ let mut context = Context::new_with(+ state.ctm,+ self.font_bbox,+ &glyph.cache,+ glyph.xref,+ glyph.settings.clone(),+ state,+ glyph.nesting_depth,+ );++ let mut resources = Resources::from_parent(+ self.dict.get(RESOURCES).unwrap_or_default(),+ glyph.parent_resources.clone(),+ );++ // Technically not valid, but also support by Adobe Acrobat. See PDFBOX-5294.+ if let Some(procs_resources) = program.dict().get::<Dict<'_>>(RESOURCES) {+ resources = Resources::from_parent(procs_resources, resources);+ }++ if is_shape_glyph {+ let mut device = Type3ShapeGlyphDevice::new(device, paint.clone());+ interpret(iter, &resources, &mut context, &mut device);+ } else {+ interpret(iter, &resources, &mut context, device);+ }++ Some(())+ }+}++impl CacheKey for Type3<'_> {+ fn cache_key(&self) -> u128 {+ self.dict.cache_key()+ }+}++struct Type3ShapeGlyphDevice<'a, 'b, T: Device<'a>> {+ inner: &'b mut T,+ paint: Paint<'a>,+}++impl<'a, 'b, T: Device<'a>> Type3ShapeGlyphDevice<'a, 'b, T> {+ pub(crate) fn new(device: &'b mut T, paint: Paint<'a>) -> Self {+ Self {+ inner: device,+ paint,+ }+ }+}++// Only filling, stroking of paths and stencil masks are allowed.+impl<'a, T: Device<'a>> Device<'a> for Type3ShapeGlyphDevice<'a, '_, T> {+ fn set_soft_mask(&mut self, m: Option<SoftMask<'a>>) {+ self.inner.set_soft_mask(m);+ }++ fn draw_path(+ &mut self,+ path: &BezPath,+ transform: Affine,+ _: &Paint<'_>,+ draw_mode: &PathDrawMode,+ ) {+ self.inner+ .draw_path(path, transform, &self.paint, draw_mode);+ }++ fn push_clip_path(&mut self, clip_path: &ClipPath) {+ self.inner.push_clip_path(clip_path);+ }++ fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}++ fn draw_glyph(+ &mut self,+ g: &Glyph<'a>,+ transform: Affine,+ glyph_transform: Affine,+ p: &Paint<'a>,+ draw_mode: &GlyphDrawMode,+ ) {+ self.inner+ .draw_glyph(g, transform, glyph_transform, p, draw_mode);+ }++ fn pop_clip_path(&mut self) {+ self.inner.pop_clip_path();+ }++ fn pop_transparency_group(&mut self) {}++ fn draw_image(&mut self, image: Image<'a, '_>, transform: Affine) {+ if let Image::Stencil(mut s) = image {+ s.paint = self.paint.clone();+ self.inner.draw_image(Image::Stencil(s), transform);+ }+ }++ fn set_blend_mode(&mut self, _: BlendMode) {}+}diff --git a/vendor/hayro-interpret/src/function/mod.rs b/vendor/hayro-interpret/src/function/mod.rsnew file mode 100644index 000000000..89d251742--- /dev/null+++ b/vendor/hayro-interpret/src/function/mod.rs@@ -0,0 +1,105 @@+//! PDF functions.+//!+//! PDF has the concept of functions, representing objects that take a certain number of values+//! as input, do some processing on them and then return some output.++mod type0;+mod type2;+mod type3;+mod type4;++use crate::function::type0::Type0;+use crate::function::type2::Type2;+use crate::function::type3::Type3;+use crate::function::type4::Type4;+use hayro_syntax::object::Dict;+use hayro_syntax::object::dict::keys::{DOMAIN, FUNCTION_TYPE, RANGE};+use hayro_syntax::object::{Object, dict_or_stream};+use smallvec::SmallVec;+use std::sync::Arc;++/// The input/output type of functions.+pub(crate) type Values = SmallVec<[f32; 4]>;+type TupleVec = SmallVec<[(f32, f32); 4]>;++#[derive(Debug)]+enum FunctionType {+ Type0(Type0),+ Type2(Type2),+ Type3(Type3),+ Type4(Type4),+}++/// A PDF function.+#[derive(Debug, Clone)]+pub struct Function(Arc<FunctionType>);++impl Function {+ /// Create a new function.+ pub fn new(obj: &Object<'_>) -> Option<Self> {+ let (dict, stream) = dict_or_stream(obj)?;++ let function_type = match dict.get::<u8>(FUNCTION_TYPE)? {+ 0 => FunctionType::Type0(Type0::new(stream?)?),+ 2 => FunctionType::Type2(Type2::new(dict)?),+ 3 => FunctionType::Type3(Type3::new(dict)?),+ 4 => FunctionType::Type4(Type4::new(stream?)?),+ _ => return None,+ };++ Some(Self(Arc::new(function_type)))+ }++ /// Evaluate the function with the given input.+ pub fn eval(&self, input: Values) -> Option<Values> {+ match self.0.as_ref() {+ FunctionType::Type0(t0) => t0.eval(input),+ FunctionType::Type2(t2) => Some(t2.eval(*input.first()?)),+ FunctionType::Type3(t3) => t3.eval(*input.first()?),+ FunctionType::Type4(t4) => Some(t4.eval(input)?),+ }+ }+}++#[derive(Debug, Clone)]+struct Clamper {+ domain: TupleVec,+ range: Option<TupleVec>,+}++impl Clamper {+ fn new(dict: &Dict<'_>) -> Option<Self> {+ let domain = dict.get::<TupleVec>(DOMAIN)?;+ let range = dict.get::<TupleVec>(RANGE);++ Some(Self { domain, range })+ }++ fn clamp_input(&self, input: &mut [f32]) {+ if input.len() != self.domain.len() {+ warn!("the domain of the function didn't match the input arguments");+ }++ for ((min, max), val) in self.domain.iter().zip(input.iter_mut()) {+ *val = val.min(*max).max(*min);+ }+ }++ fn clamp_output(&self, output: &mut [f32]) {+ if let Some(range) = &self.range {+ if range.len() != output.len() {+ warn!("the range of the function didn't match the output arguments");+ }++ for ((min, max), val) in range.iter().zip(output.iter_mut()) {+ *val = val.min(*max).max(*min);+ }+ }+ }+}++/// Linearly interpolate the value `x`, assuming that it lies within the range `x_min` and `x_max`,+/// to the range `y_min` and `y_max`.+pub(crate) fn interpolate(x: f32, x_min: f32, x_max: f32, y_min: f32, y_max: f32) -> f32 {+ y_min + (x - x_min) * (y_max - y_min) / (x_max - x_min)+}diff --git a/vendor/hayro-interpret/src/function/type0.rs b/vendor/hayro-interpret/src/function/type0.rsnew file mode 100644index 000000000..8b44ba6e0--- /dev/null+++ b/vendor/hayro-interpret/src/function/type0.rs@@ -0,0 +1,302 @@+use crate::function::{Clamper, TupleVec, Values, interpolate};+use hayro_syntax::bit_reader::BitReader;+use hayro_syntax::object::Array;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::{BITS_PER_SAMPLE, DECODE, ENCODE, SIZE};+use smallvec::{SmallVec, ToSmallVec, smallvec};+use std::collections::HashMap;++/// A type 0 function (sampled function).+#[derive(Debug)]+pub(crate) struct Type0 {+ sizes: IntVec,+ table: HashMap<Key, IntVec>,+ clamper: Clamper,+ range: TupleVec,+ bits_per_sample: u8,+ encode: TupleVec,+ decode: TupleVec,+}++impl Type0 {+ /// Create a new type 0 function.+ pub(crate) fn new(stream: &Stream<'_>) -> Option<Self> {+ let dict = stream.dict();+ let bits_per_sample = dict.get::<u8>(BITS_PER_SAMPLE)?;++ if !matches!(bits_per_sample, 1 | 2 | 4 | 8 | 16 | 24 | 32) {+ error!("invalid bits per sample: {bits_per_sample}");++ return None;+ }++ let clamper = Clamper::new(dict)?;+ let range = clamper.range.clone()?;++ if range.is_empty() {+ warn!("encountered Type0 function with invalid range length 0.");++ return None;+ }++ let sizes = dict+ .get::<Array<'_>>(SIZE)?+ .iter::<u32>()+ .collect::<IntVec>();++ let encode = dict+ .get::<TupleVec>(ENCODE)+ .unwrap_or(sizes.iter().map(|s| (0.0, (*s - 1) as f32)).collect());++ let decode = dict.get::<TupleVec>(DECODE).unwrap_or(range.clone());++ let mut data = {+ let decoded = stream.decoded().ok()?;+ let mut buf = vec![];+ let mut reader = BitReader::new(&decoded);++ while let Some(data) = reader.read(bits_per_sample) {+ buf.push(data);+ }++ buf+ };++ let num_expected_entries = sizes.iter().fold(1, |i1, i2| i1 * *i2 as usize) * range.len();++ if data.len() != num_expected_entries {+ warn!("Type0 function didn't have the expected number of sample entries.");+ data.truncate(num_expected_entries);+ }++ let table = build_table(&data, &sizes, range.len())?;++ Some(Self {+ sizes,+ clamper,+ range,+ bits_per_sample,+ table,+ encode,+ decode,+ })+ }++ /// Evaluate a type 0 function with the given input.+ pub(crate) fn eval(&self, mut input: Values) -> Option<Values> {+ if input.len() != self.sizes.len() {+ warn!("wrong number of arguments for sampled function");++ return None;+ }++ self.clamper.clamp_input(&mut input);++ let mut key = input;++ for (((x, domain), encode), size) in key+ .iter_mut()+ .zip(self.clamper.domain.iter())+ .zip(self.encode.iter())+ .zip(self.sizes.iter())+ {+ *x = interpolate(*x, domain.0, domain.1, encode.0, encode.1);+ *x = x.max(0.0).min(*size as f32 - 1.0);+ }++ let in_prev = key.iter().map(|v| v.floor() as u32).collect::<IntVec>();+ let in_next = key.iter().map(|v| v.ceil() as u32).collect::<IntVec>();++ let interpolator = Interpolator::new(+ key.clone().to_smallvec(),+ in_prev,+ in_next,+ self.sizes.clone(),+ self.range.len(),+ );++ let interpolated = interpolator.interpolate(&self.table)?;++ let mut out = interpolated+ .iter()+ .zip(self.decode.iter())+ .map(|(x, decode)| {+ interpolate(+ *x,+ 0.0,+ (2_u32.pow(self.bits_per_sample as u32) - 1) as f32,+ decode.0,+ decode.1,+ )+ })+ .collect::<SmallVec<_>>();++ self.clamper.clamp_output(&mut out);++ Some(out)+ }+}++type FloatVec = SmallVec<[f32; 4]>;+type IntVec = SmallVec<[u32; 4]>;++// See <https://github.com/apache/pdfbox/blob/bb778d4784f354c36ce032e91a0cee2169a4c598/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/function/PDFunctionType0.java#L252>+struct Interpolator {+ input: FloatVec,+ sizes: IntVec,+ in_prev: IntVec,+ in_next: IntVec,+ out_len: usize,+}++impl Interpolator {+ fn new(+ input: FloatVec,+ in_prev: IntVec,+ in_next: IntVec,+ sizes: IntVec,+ out_len: usize,+ ) -> Self {+ Self {+ input,+ in_prev,+ in_next,+ sizes,+ out_len,+ }+ }++ fn interpolate(&self, table: &HashMap<Key, IntVec>) -> Option<FloatVec> {+ self.interpolate_inner(smallvec![0; self.input.len()], 0, table)+ }++ fn interpolate_inner(+ &self,+ mut coord: IntVec,+ step: usize,+ table: &HashMap<Key, IntVec>,+ ) -> Option<FloatVec> {+ if step == self.input.len() - 1 {+ if self.in_prev[step] == self.in_next[step] {+ coord[step] = self.in_prev[step];++ Some(+ table+ .get(&Key::from_raw(&self.sizes, &coord))?+ .clone()+ .iter()+ .map(|n| *n as f32)+ .collect(),+ )+ } else {+ coord[step] = self.in_prev[step];+ let val1 = table.get(&Key::from_raw(&self.sizes, &coord))?;+ coord[step] = self.in_next[step];+ let val2 = table.get(&Key::from_raw(&self.sizes, &coord))?;+ let mut out = smallvec![0.0; self.out_len];++ for i in 0..self.out_len {+ out[i] = interpolate(+ self.input[step],+ self.in_prev[step] as f32,+ self.in_next[step] as f32,+ val1[i] as f32,+ val2[i] as f32,+ );+ }++ Some(out)+ }+ } else if self.in_prev[step] == self.in_next[step] {+ coord[step] = self.in_prev[step];+ self.interpolate_inner(coord, step + 1, table)+ } else {+ coord[step] = self.in_prev[step];+ let val1 = self.interpolate_inner(coord.clone(), step + 1, table)?;+ coord[step] = self.in_next[step];+ let val2 = self.interpolate_inner(coord, step + 1, table)?;++ let mut out = smallvec![0.0; self.out_len];++ for i in 0..self.out_len {+ out[i] = interpolate(+ self.input[step],+ self.in_prev[step] as f32,+ self.in_next[step] as f32,+ val1[i],+ val2[i],+ );+ }++ Some(out)+ }+ }+}++fn build_table(data: &[u32], sizes: &[u32], n: usize) -> Option<HashMap<Key, IntVec>> {+ let mut key = Key::new(sizes);+ let mut table = HashMap::new();++ let mut first = true;++ for b in data.chunks_exact(n) {+ if !first {+ key.increment();+ }++ table.insert(key.clone(), b.to_smallvec());++ first = false;+ }++ Some(table)+}++/// A sampled function consists of a (possibly) multi-dimensional table that we can index+/// into. We do this by representing the entries as a flat list of vectors, where each+/// element in the vector represents the value of the key in that specific dimension.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+struct Key {+ sizes: SmallVec<[u32; 4]>,+ parts: SmallVec<[u32; 4]>,+}++impl Key {+ fn new(sizes: &[u32]) -> Self {+ let parts = smallvec![0; sizes.len()];++ Self {+ sizes: sizes.to_smallvec(),+ parts,+ }+ }++ fn from_raw(sizes: &[u32], parts: &[u32]) -> Self {+ Self {+ sizes: sizes.to_smallvec(),+ parts: parts.to_smallvec(),+ }+ }++ fn increment(&mut self) -> Option<()> {+ self.increment_index(0)+ }++ fn increment_index(&mut self, index: usize) -> Option<()> {+ let size = *self.sizes.get(index).or_else(|| {+ error!("overflowed key in sampled function");++ None+ })?;+ let val = self.parts.get_mut(index)?;++ if *val >= (size - 1) {+ *val = 0;+ self.increment_index(index + 1)?;+ } else {+ *val += 1;+ }++ Some(())+ }+}diff --git a/vendor/hayro-interpret/src/function/type2.rs b/vendor/hayro-interpret/src/function/type2.rsnew file mode 100644index 000000000..3e12fdaf5--- /dev/null+++ b/vendor/hayro-interpret/src/function/type2.rs@@ -0,0 +1,148 @@+use crate::function::{Clamper, Values};+use hayro_syntax::object::Dict;+use hayro_syntax::object::Number;+use hayro_syntax::object::dict::keys::{C0, C1, N};+use smallvec::{SmallVec, smallvec};++/// A type 2 function (exponential function).+#[derive(Debug)]+pub(crate) struct Type2 {+ c0: Values,+ c1: Values,+ clamper: Clamper,+ n: f32,+}++impl Type2 {+ /// Create a new type 2 function.+ pub(crate) fn new(dict: &Dict<'_>) -> Option<Self> {+ let c0 = dict.get::<Values>(C0).unwrap_or(smallvec![0.0]);+ let c1 = dict.get::<Values>(C1).unwrap_or(smallvec![1.0]);+ let clamper = Clamper::new(dict)?;+ let n = dict.get::<Number>(N)?.as_f64() as f32;++ Some(Self { c0, c1, clamper, n })+ }++ /// Evaluate the function with the given input.+ pub(crate) fn eval(&self, input: f32) -> Values {+ let mut input = [input];+ self.clamper.clamp_input(&mut input);++ let mut out = self+ .c0+ .iter()+ .zip(self.c1.iter())+ .map(|(c0, c1)| *c0 + input[0].powf(self.n) * (*c1 - *c0))+ .collect::<SmallVec<_>>();++ self.clamper.clamp_output(&mut out);++ out+ }+}++#[cfg(test)]+mod tests {+ use crate::function::Function;++ use hayro_syntax::object::Object;+ use hayro_syntax::object::{Dict, FromBytes};+ use smallvec::smallvec;++ #[test]+ fn simple() {+ let func = Function::new(&Object::Dict(+ Dict::from_bytes(+ b"<<+ /FunctionType 2+ /Domain [ 0 1 ]+ /C0 [ 0 20 ]+ /C1 [ 30 -50 ]+ /N 1+ >>",+ )+ .unwrap(),+ ))+ .unwrap();++ assert_eq!(func.eval(smallvec![0.0]).unwrap().as_ref(), &[0.0, 20.0]);+ assert_eq!(func.eval(smallvec![0.5]).unwrap().as_ref(), &[15.0, -15.0]);+ assert_eq!(func.eval(smallvec![1.0]).unwrap().as_ref(), &[30.0, -50.0]);+ }++ #[test]+ fn with_exponent() {+ let func = Function::new(&Object::Dict(+ Dict::from_bytes(+ b"<<+ /FunctionType 2+ /Domain [ 0 1 ]+ /C0 [ 0 ]+ /C1 [ 30 ]+ /N 2+ >>",+ )+ .unwrap(),+ ))+ .unwrap();++ assert_eq!(func.eval(smallvec![0.5]), Some(smallvec![7.5]));+ }++ #[test]+ fn clamp_domain() {+ let func = Function::new(&Object::Dict(+ Dict::from_bytes(+ b"<<+ /FunctionType 2+ /Domain [ 0.2 0.8 ]+ /C0 [ 0 ]+ /C1 [ 30 ]+ /N 2+ >>",+ )+ .unwrap(),+ ))+ .unwrap();++ assert_eq!(+ func.eval(smallvec![0.0]).as_ref(),+ func.eval(smallvec![0.2]).as_ref(),+ );+ assert_eq!(+ func.eval(smallvec![-10.]).as_ref(),+ func.eval(smallvec![0.2]).as_ref(),+ );+ assert_eq!(+ func.eval(smallvec![0.8]).as_ref(),+ func.eval(smallvec![0.8]).as_ref(),+ );+ assert_eq!(+ func.eval(smallvec![1.2]).as_ref(),+ func.eval(smallvec![1.0]).as_ref(),+ );+ }++ #[test]+ fn clamp_range() {+ let func = Function::new(&Object::Dict(+ Dict::from_bytes(+ b"<<+ /FunctionType 2+ /Domain [ 0.0 1.0 ]+ /Range [10.0 20.0]+ /C0 [ 0 ]+ /C1 [ 30 ]+ /N 1+ >>",+ )+ .unwrap(),+ ))+ .unwrap();++ assert_eq!(func.eval(smallvec![0.0]), Some(smallvec![10.0]));+ assert_eq!(func.eval(smallvec![0.5]), Some(smallvec![15.0]));+ assert_eq!(func.eval(smallvec![1.0]), Some(smallvec![20.0]));+ }+}diff --git a/vendor/hayro-interpret/src/function/type3.rs b/vendor/hayro-interpret/src/function/type3.rsnew file mode 100644index 000000000..f66fead17--- /dev/null+++ b/vendor/hayro-interpret/src/function/type3.rs@@ -0,0 +1,135 @@+use crate::function::{Clamper, Function, TupleVec, Values, interpolate};+use hayro_syntax::object::Array;+use hayro_syntax::object::Dict;+use hayro_syntax::object::Object;+use hayro_syntax::object::dict::keys::{BOUNDS, ENCODE, FUNCTIONS};+use smallvec::smallvec;++/// A type 3 function (stitching function).+#[derive(Debug)]+pub(crate) struct Type3 {+ functions: Vec<Function>,+ bounds: Vec<f32>,+ encode: TupleVec,+ clamper: Clamper,+}++impl Type3 {+ /// Create a new type 3 function.+ pub(crate) fn new(dict: &Dict<'_>) -> Option<Self> {+ let clamper = Clamper::new(dict)?;++ let functions = dict+ .get::<Array<'_>>(FUNCTIONS)+ .and_then(|d| d.iter::<Object<'_>>().map(|o| Function::new(&o)).collect())?;+ let domain = *clamper.domain.first()?;+ let mut bounds = vec![domain.0 - 0.0001];+ if let Some(a) = dict.get::<Array<'_>>(BOUNDS) {+ bounds.extend(a.iter::<f32>());+ }+ // Add a small delta so that the interval is considered to be closed on the right.+ bounds.push(domain.1 + 0.0001);++ let encode = dict.get::<TupleVec>(ENCODE)?;++ Some(Self {+ functions,+ clamper,+ bounds,+ encode,+ })+ }++ /// Evaluate the function with the given input.+ pub(crate) fn eval(&self, input: f32) -> Option<Values> {+ let mut input = [input];+ self.clamper.clamp_input(&mut input);++ let index = find_interval(&self.bounds, input[0])?;++ let bounds_i = *self.bounds.get(index + 1)?;+ let bounds_i_minus_1 = *self.bounds.get(index)?;++ // - 1 because we inserted a dummy bound in the constructor.+ let encoding = self.encode.get(index)?;+ let function = self.functions.get(index)?;+ let encoded = interpolate(input[0], bounds_i_minus_1, bounds_i, encoding.0, encoding.1);++ let mut evaluated = function.eval(smallvec![encoded])?;++ self.clamper.clamp_output(&mut evaluated);++ Some(evaluated)+ }+}++fn find_interval(bounds: &[f32], x: f32) -> Option<usize> {+ if x < *bounds.first()? || x >= *bounds.last()? {+ return None;+ }++ match bounds.binary_search_by(|val| {+ if *val <= x {+ std::cmp::Ordering::Less+ } else {+ std::cmp::Ordering::Greater+ }+ }) {+ Ok(i) => Some(i - 1),+ Err(i) => Some(i - 1),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use hayro_syntax::object::FromBytes;++ #[test]+ fn simple() {+ let data = b"<<+ /FunctionType 3+ /Domain [-7 7]+ /Functions [+ << /FunctionType 2+ /Domain [0 1]+ /C0 [0.5 0.5 0.5]+ /C1 [0.5 0.5 0.5]+ /N 1+ >>+ << /FunctionType 2+ /Domain [0 1]+ /C0 [0.7 0.7 0.7]+ /C1 [0.7 0.7 0.7]+ /N 1+ >>+ ]+ /Bounds [0]+ /Encode [0 1 0 1]+>>";++ let dict = Object::from_bytes(data).unwrap();+ let function = Function::new(&dict).unwrap();++ assert_eq!(+ function.eval(smallvec![-7.0]).unwrap().as_slice(),+ &[0.5, 0.5, 0.5]+ );+ assert_eq!(+ function.eval(smallvec![-3.0]).unwrap().as_slice(),+ &[0.5, 0.5, 0.5]+ );+ assert_eq!(+ function.eval(smallvec![-0.5]).unwrap().as_slice(),+ &[0.5, 0.5, 0.5]+ );+ assert_eq!(+ function.eval(smallvec![0.0]).unwrap().as_slice(),+ &[0.7, 0.7, 0.7]+ );+ assert_eq!(+ function.eval(smallvec![7.0]).unwrap().as_slice(),+ &[0.7, 0.7, 0.7]+ );+ }+}diff --git a/vendor/hayro-interpret/src/function/type4.rs b/vendor/hayro-interpret/src/function/type4.rsnew file mode 100644index 000000000..ffa6a3742--- /dev/null+++ b/vendor/hayro-interpret/src/function/type4.rs@@ -0,0 +1,910 @@+use crate::function::{Clamper, Values};+use hayro_syntax::content;+use hayro_syntax::object::Number;+use hayro_syntax::object::Stream;+use hayro_syntax::reader::Reader;+use hayro_syntax::reader::{ReaderContext, ReaderExt};+use smallvec::SmallVec;+use std::array;+use std::ops::Rem;++/// A type 4 function (postscript function).+#[derive(Debug)]+pub(crate) struct Type4 {+ program: Vec<PostScriptOp>,+ clamper: Clamper,+}++impl Type4 {+ /// Create a new type 4 function.+ pub(crate) fn new(stream: &Stream<'_>) -> Option<Self> {+ let dict = stream.dict().clone();+ let clamper = Clamper::new(&dict)?;++ Some(Self {+ clamper,+ program: parse_procedure(&stream.decoded().ok()?)?,+ })+ }++ /// Evaluate the function with the given input.+ pub(crate) fn eval(&self, mut input: Values) -> Option<Values> {+ self.clamper.clamp_input(&mut input);++ let mut arg_stack = InterpreterStack::new();++ for input in input {+ arg_stack.push(Argument::Float(input));+ }++ eval_inner(&self.program, &mut arg_stack)?;++ let mut out: SmallVec<_> = arg_stack.items().iter().map(|i| i.as_f32()).collect();++ self.clamper.clamp_output(&mut out);++ Some(out)+ }+}++#[derive(Clone, Copy)]+enum Argument {+ Float(f32),+ Bool(bool),+}++impl Default for Argument {+ fn default() -> Self {+ Self::Float(0.0)+ }+}++impl Argument {+ fn as_bool(&self) -> bool {+ match self {+ Self::Float(f) => *f != 0.0,+ Self::Bool(b) => *b,+ }+ }++ fn as_f32(&self) -> f32 {+ match self {+ Self::Float(f) => *f,+ Self::Bool(b) => {+ if *b {+ 1.0+ } else {+ 0.0+ }+ }+ }+ }+}++struct ArgumentsStack<T: Default, const C: usize> {+ stack: [T; C],+ len: usize,+}++impl<T: Default, const C: usize> ArgumentsStack<T, C> {+ fn new() -> Self {+ Self {+ stack: array::from_fn(|_| T::default()),+ len: 0,+ }+ }++ #[inline]+ fn len(&self) -> usize {+ self.len+ }++ #[inline]+ fn is_empty(&self) -> bool {+ self.len == 0+ }++ #[inline]+ fn push(&mut self, n: T) -> Option<()> {+ if self.len == C {+ error!("overflowed post script argument stack");++ None+ } else {+ self.stack[self.len] = n;+ self.len += 1;++ Some(())+ }+ }++ #[inline]+ fn at(&self, index: usize) -> Option<&T> {+ if index >= self.len {+ None+ } else {+ Some(&self.stack[index])+ }+ }++ #[inline]+ fn last(&self) -> Option<&T> {+ if self.is_empty() {+ None+ } else {+ Some(&self.stack[self.len - 1])+ }+ }++ #[inline]+ fn pop(&mut self) -> Option<T> {+ if self.is_empty() {+ error!("underflowed post script argument stack");++ None+ } else {+ self.len -= 1;+ Some(std::mem::take(&mut self.stack[self.len]))+ }+ }++ #[inline]+ fn items(&self) -> &[T] {+ &self.stack[..self.len]+ }++ #[inline]+ fn items_mut(&mut self) -> &mut [T] {+ &mut self.stack[..self.len]+ }+}++type InterpreterStack = ArgumentsStack<Argument, 64>;+type ParseStack = ArgumentsStack<Vec<PostScriptOp>, 2>;++fn eval_inner(procedure: &[PostScriptOp], arg_stack: &mut InterpreterStack) -> Option<()> {+ macro_rules! zero {+ ($eval:expr) => {+ arg_stack.push($eval);+ };+ }++ macro_rules! one_f {+ ($eval:expr) => {+ let n1 = arg_stack.pop()?;+ arg_stack.push(Argument::Float($eval(n1.as_f32())));+ };+ }++ macro_rules! two_f {+ ($eval:expr) => {+ let n2 = arg_stack.pop()?;+ let n1 = arg_stack.pop()?;+ arg_stack.push(Argument::Float($eval(n1.as_f32(), n2.as_f32())));+ };+ }++ macro_rules! four {+ ($eval_f:expr, $eval_b:expr) => {+ let n2 = arg_stack.pop()?;+ let n1 = arg_stack.pop()?;++ let res = match (n1, n2) {+ (Argument::Float(f1), Argument::Float(f2)) => Argument::Float($eval_f(f1, f2)),+ (Argument::Float(_), Argument::Bool(f2)) => {+ Argument::Bool($eval_b(n1.as_bool(), f2))+ }+ (Argument::Bool(f1), Argument::Float(_)) => {+ Argument::Bool($eval_b(f1, n2.as_bool()))+ }+ (Argument::Bool(f1), Argument::Bool(f2)) => Argument::Bool($eval_b(f1, f2)),+ };++ arg_stack.push(res);+ };+ }++ fn bf(cond: bool) -> f32 {+ (cond as i32) as f32+ }++ for op in procedure {+ match op {+ PostScriptOp::Number(n) => arg_stack.push(Argument::Float(n.as_f64() as f32))?,+ PostScriptOp::Abs => {+ one_f!(|n: f32| n.abs());+ }+ PostScriptOp::Add => {+ two_f!(|n1: f32, n2: f32| n1 + n2);+ }+ PostScriptOp::Atan => {+ two_f!(|n1: f32, n2: f32| {+ let mut res = n1.atan2(n2).to_degrees() % 360.0;+ if res < 0.0 {+ res += 360.0;+ }++ res+ });+ }+ PostScriptOp::Ceiling => {+ one_f!(|n: f32| n.ceil());+ }+ PostScriptOp::Cos => {+ one_f!(|n: f32| n.to_radians().cos());+ }+ PostScriptOp::Cvi => {+ one_f!(|n: f32| n.trunc());+ }+ PostScriptOp::Cvr => {+ one_f!(|n: f32| n);+ }+ PostScriptOp::Div => {+ two_f!(|n1: f32, n2: f32| n1 / n2);+ }+ PostScriptOp::Exp => {+ two_f!(|n1: f32, n2: f32| n1.powf(n2));+ }+ PostScriptOp::Floor => {+ one_f!(|n: f32| n.floor());+ }+ PostScriptOp::Idiv => {+ two_f!(|n1: f32, n2: f32| {+ let n1 = n1 as i32;+ let n2 = n2 as i32;++ (n1 / n2) as f32+ });+ }+ PostScriptOp::Ln => {+ one_f!(|n: f32| n.ln());+ }+ PostScriptOp::Log => {+ one_f!(|n: f32| n.log10());+ }+ PostScriptOp::Mod => {+ two_f!(|n1: f32, n2: f32| n1.rem(n2));+ }+ PostScriptOp::Mul => {+ two_f!(|n1: f32, n2: f32| n1 * n2);+ }+ PostScriptOp::Neg => {+ one_f!(|n: f32| -n);+ }+ PostScriptOp::Round => {+ one_f!(|n: f32| n.round());+ }+ PostScriptOp::Sin => {+ one_f!(|n: f32| n.to_radians().sin());+ }+ PostScriptOp::Sqrt => {+ one_f!(|n: f32| n.sqrt());+ }+ PostScriptOp::Sub => {+ two_f!(|n1: f32, n2: f32| n1 - n2);+ }+ PostScriptOp::Truncate => {+ one_f!(|n: f32| n.trunc());+ }+ PostScriptOp::And => {+ two_f!(|n1: f32, n2: f32| (n1 as i32 & n2 as i32) as f32);+ }+ PostScriptOp::Bitshift => {+ two_f!(|n1: f32, n2: f32| {+ let num = n1 as u32;+ let shift = n2 as i32;++ if shift >= 0 {+ (num << shift) as f32+ } else {+ (num >> -shift) as f32+ }+ });+ }+ PostScriptOp::Eq => {+ two_f!(|n1: f32, n2: f32| bf(n1 == n2));+ }+ PostScriptOp::False => {+ zero!(Argument::Bool(false));+ }+ PostScriptOp::Ge => {+ two_f!(|n1: f32, n2: f32| bf(n1 >= n2));+ }+ PostScriptOp::Gt => {+ two_f!(|n1: f32, n2: f32| bf(n1 > n2));+ }+ PostScriptOp::Le => {+ two_f!(|n1: f32, n2: f32| bf(n1 <= n2));+ }+ PostScriptOp::Lt => {+ two_f!(|n1: f32, n2: f32| bf(n1 < n2));+ }+ PostScriptOp::Ne => {+ two_f!(|n1: f32, n2: f32| bf(n1 != n2));+ }+ PostScriptOp::Not => {+ let arg = arg_stack.pop()?;++ let res = match arg {+ Argument::Float(f) => Argument::Float(!(f as i32) as f32),+ Argument::Bool(b) => Argument::Bool(!b),+ };++ arg_stack.push(res);+ }+ PostScriptOp::Or => {+ four!(+ |n1: f32, n2: f32| ((n1 as i32) | (n2 as i32)) as f32,+ |b1: bool, b2: bool| b1 || b2+ );+ }+ PostScriptOp::True => {+ zero!(Argument::Bool(true));+ }+ PostScriptOp::Xor => {+ four!(+ |n1: f32, n2: f32| ((n1 as i32) ^ (n2 as i32)) as f32,+ |b1: bool, b2: bool| b1 ^ b2+ );+ }+ PostScriptOp::If(p) => {+ let cond = arg_stack.pop()?.as_bool();++ if cond {+ eval_inner(p, arg_stack)?;+ }+ }+ PostScriptOp::IfElse(p1, p2) => {+ let cond = arg_stack.pop()?.as_bool();++ if cond {+ eval_inner(p1, arg_stack)?;+ } else {+ eval_inner(p2, arg_stack)?;+ }+ }+ PostScriptOp::Copy => {+ let n = arg_stack.pop()?.as_f32() as u32 as usize;+ let start = arg_stack.len().checked_sub(n)?;+ for i in start..arg_stack.len() {+ arg_stack.push(*arg_stack.at(i)?);+ }+ }+ PostScriptOp::Dup => {+ arg_stack.push(*arg_stack.last()?);+ }+ PostScriptOp::Exch => {+ let n2 = arg_stack.pop()?;+ let n1 = arg_stack.pop()?;++ arg_stack.push(n2);+ arg_stack.push(n1);+ }+ PostScriptOp::Index => {+ let n = arg_stack.pop()?.as_f32() as u32 as usize;+ let n = arg_stack.len().checked_sub(n + 1)?;++ arg_stack.push(*arg_stack.at(n)?);+ }+ PostScriptOp::Pop => {+ arg_stack.pop()?;+ }+ PostScriptOp::Roll => {+ let j = arg_stack.pop()?.as_f32() as i32;+ let n = arg_stack.pop()?.as_f32() as u32 as usize;+ let trimmed_n = arg_stack.len().checked_sub(n)?;++ let target = &mut arg_stack.items_mut()[trimmed_n..];++ if target.is_empty() {+ continue;+ }++ if j >= 0 {+ let shift = j as usize % target.len();+ target.rotate_right(shift);+ } else {+ let shift = (-j) as usize % target.len();+ target.rotate_left(shift);+ }+ }+ }+ }++ Some(())+}++fn parse_procedure(data: &[u8]) -> Option<Vec<PostScriptOp>> {+ let mut r = Reader::new(data);+ parse_procedure_inner(&mut r)+}++fn parse_procedure_inner(r: &mut Reader<'_>) -> Option<Vec<PostScriptOp>> {+ let mut stack = ParseStack::new();++ let mut ops = vec![];+ r.skip_white_spaces_and_comments();+ r.forward_tag(b"{")?;++ loop {+ r.skip_white_spaces_and_comments();++ if r.peek_byte()? == b'}' {+ r.forward_tag(b"}")?;++ break;+ } else if r.peek_byte()? == b'{' {+ stack.push(parse_procedure_inner(r)?);+ } else {+ let op = PostScriptOp::from_reader(r, &mut stack)?;+ ops.push(op);+ }+ }++ Some(ops)+}++#[derive(Debug, Clone, PartialEq)]+pub(super) enum PostScriptOp {+ Number(Number),+ Abs,+ Add,+ Atan,+ Ceiling,+ Cos,+ Cvi,+ Cvr,+ Div,+ Exp,+ Floor,+ Idiv,+ Ln,+ Log,+ Mod,+ Mul,+ Neg,+ Round,+ Sin,+ Sqrt,+ Sub,+ Truncate,+ And,+ Bitshift,+ Eq,+ False,+ Ge,+ Gt,+ Le,+ Lt,+ Ne,+ Not,+ Or,+ True,+ Xor,+ If(Vec<Self>),+ IfElse(Vec<Self>, Vec<Self>),+ Copy,+ Dup,+ Exch,+ Index,+ Pop,+ Roll,+}++impl PostScriptOp {+ fn from_reader(r: &mut Reader<'_>, stack: &mut ParseStack) -> Option<Self> {+ let op = if let Some(n) = r.read::<Number>(&ReaderContext::dummy()) {+ // TODO: Support radix numbers+ Self::Number(n)+ } else {+ let op = r.read::<content::Operator<'_>>(&ReaderContext::dummy())?;+ match op.as_ref() {+ b"abs" => Self::Abs,+ b"add" => Self::Add,+ b"atan" => Self::Atan,+ b"ceiling" => Self::Ceiling,+ b"cos" => Self::Cos,+ b"cvi" => Self::Cvi,+ b"cvr" => Self::Cvr,+ b"div" => Self::Div,+ b"exp" => Self::Exp,+ b"floor" => Self::Floor,+ b"idiv" => Self::Idiv,+ b"ln" => Self::Ln,+ b"log" => Self::Log,+ b"mod" => Self::Mod,+ b"mul" => Self::Mul,+ b"neg" => Self::Neg,+ b"round" => Self::Round,+ b"sin" => Self::Sin,+ b"sqrt" => Self::Sqrt,+ b"sub" => Self::Sub,+ b"truncate" => Self::Truncate,+ b"and" => Self::And,+ b"bitshift" => Self::Bitshift,+ b"eq" => Self::Eq,+ b"false" => Self::False,+ b"ge" => Self::Ge,+ b"gt" => Self::Gt,+ b"le" => Self::Le,+ b"lt" => Self::Lt,+ b"ne" => Self::Ne,+ b"not" => Self::Not,+ b"or" => Self::Or,+ b"true" => Self::True,+ b"xor" => Self::Xor,+ b"if" => Self::If(stack.pop()?),+ b"ifelse" => {+ let s = stack.pop()?;+ let f = stack.pop()?;+ Self::IfElse(f, s)+ }+ b"copy" => Self::Copy,+ b"dup" => Self::Dup,+ b"exch" => Self::Exch,+ b"index" => Self::Index,+ b"pop" => Self::Pop,+ b"roll" => Self::Roll,+ _ => {+ error!("encountered unknown postscript operator {op:?}");++ return None;+ }+ }+ };++ Some(op)+ }+}++#[cfg(test)]+mod tests {+ use crate::function::type4::{PostScriptOp, Type4, parse_procedure};+ use crate::function::{Clamper, Function, FunctionType, TupleVec, Values};+ use std::f32::consts::LN_10;+ use std::sync::Arc;++ use hayro_syntax::object::Number;+ use smallvec::smallvec;++ #[test]+ fn lex_1() {+ let program = b"{ copy dup 2.0 exch roll }";+ let parsed = parse_procedure(program).unwrap();++ assert_eq!(+ parsed,+ vec![+ PostScriptOp::Copy,+ PostScriptOp::Dup,+ PostScriptOp::Number(Number::from_f32(2.0)),+ PostScriptOp::Exch,+ PostScriptOp::Roll,+ ]+ );+ }++ #[test]+ fn lex_3() {+ let program = b" { {dup exch} if {0} {1} ifelse }";+ let parsed = parse_procedure(program).unwrap();++ assert_eq!(+ parsed,+ vec![+ PostScriptOp::If(vec![PostScriptOp::Dup, PostScriptOp::Exch]),+ PostScriptOp::IfElse(+ vec![PostScriptOp::Number(Number::from_i32(0))],+ vec![PostScriptOp::Number(Number::from_i32(1))]+ )+ ]+ );+ }++ fn op_impl(prog: &str, out: &[f32]) {+ let procedure = format!("{{{prog}}}");+ let procedure = parse_procedure(procedure.as_bytes()).unwrap();++ let type4 = Type4 {+ program: procedure,+ clamper: Clamper {+ domain: TupleVec::default(),+ range: None,+ },+ };++ let res = type4.eval(Values::new()).unwrap();++ assert_eq!(res.as_slice(), out);+ }++ #[test]+ fn op_abs() {+ op_impl("4.5 abs", &[4.5]);+ op_impl("-3 abs", &[3.0]);+ op_impl("0 abs", &[0.0]);+ }++ #[test]+ fn op_atan() {+ op_impl("0 1 atan", &[0.0]);+ op_impl("1 0 atan", &[90.0]);+ op_impl("-100 0 atan", &[270.0]);+ op_impl("4 4 atan", &[45.0]);+ }++ #[test]+ fn op_ceiling() {+ op_impl("3.2 ceiling", &[4.0]);+ op_impl("-4.8 ceiling", &[-4.0]);+ op_impl("99 ceiling", &[99.0]);+ }++ #[test]+ fn op_cos() {+ op_impl("0 cos", &[1.0]);+ // Should be zero, but floating point impreciseness.+ op_impl("90 cos", &[-4.371139e-8]);+ }++ #[test]+ fn op_cvi() {+ op_impl("-47.8 cvi", &[-47.0]);+ op_impl("520.9 cvi", &[520.0]);+ }++ #[test]+ fn op_cvr() {+ op_impl("-47.8 cvr", &[-47.8]);+ op_impl("520 cvr", &[520.0]);+ }++ #[test]+ fn op_div() {+ op_impl("3 2 div", &[1.5]);+ op_impl("4 2 div", &[2.0]);+ }++ #[test]+ fn op_exp() {+ op_impl("9 0.5 exp", &[3.0]);+ op_impl("-9 -1 exp", &[-0.11111111]);+ }++ #[test]+ fn op_floor() {+ op_impl("3.2 floor", &[3.0]);+ op_impl("-4.8 floor", &[-5.0]);+ op_impl("99 floor", &[99.0]);+ }++ #[test]+ fn op_idiv() {+ op_impl("3 2 idiv", &[1.0]);+ op_impl("4 2 idiv", &[2.0]);+ op_impl("-5 2 idiv", &[-2.0]);+ }++ #[test]+ fn op_ln() {+ op_impl("10 ln", &[LN_10]);+ op_impl("100 ln", &[4.6051702]);+ }++ #[test]+ fn op_log() {+ op_impl("10 log", &[1.0]);+ op_impl("100 log", &[2.0]);+ }++ #[test]+ fn op_mod() {+ op_impl("5 3 mod", &[2.0]);+ op_impl("5 2 mod", &[1.0]);+ op_impl("-5 3 mod", &[-2.0]);+ }++ #[test]+ fn op_mul() {+ op_impl("5 3 mul", &[15.0]);+ op_impl("-2 6 mul", &[-12.0]);+ }++ #[test]+ fn op_neg() {+ op_impl("4.5 neg", &[-4.5]);+ op_impl("-3 neg", &[3.0]);+ }++ #[test]+ fn op_round() {+ op_impl("3.2 round", &[3.0]);+ op_impl("6.5 round", &[7.0]);+ op_impl("-4.8 round", &[-5.0]);+ // TODO: This rounding doesn't match the PS spec.+ // op_impl("-6.5 round", &[-6.0]);+ op_impl("99 round", &[99.0]);+ }++ #[test]+ fn op_sin() {+ op_impl("0.0 sin", &[0.0]);+ op_impl("90.0 sin", &[1.0]);+ }++ #[test]+ fn op_sqrt() {+ op_impl("100 sqrt", &[10.0]);+ }++ #[test]+ fn op_sub() {+ op_impl("3 4 sub", &[-1.0]);+ op_impl("6 0 sub", &[6.0]);+ }++ #[test]+ fn op_truncate() {+ op_impl("3.2 truncate", &[3.0]);+ op_impl("-4.8 truncate", &[-4.0]);+ op_impl("99 truncate", &[99.0]);+ }++ #[test]+ fn op_and() {+ op_impl("true true and", &[1.0]);+ op_impl("true false and", &[0.0]);+ op_impl("false true and", &[0.0]);+ op_impl("false false and", &[0.0]);+ op_impl("99 1 and", &[1.0]);+ op_impl("52 7 and", &[4.0]);+ }++ #[test]+ fn op_bitshift() {+ op_impl("7 3 bitshift", &[56.0]);+ op_impl("142 -3 bitshift", &[17.0]);+ }++ #[test]+ fn op_eq() {+ op_impl("4.0 4 eq", &[1.0]);+ op_impl("-2.0 -3 eq", &[0.0]);+ }++ #[test]+ fn op_false() {+ op_impl("false", &[0.0]);+ }++ #[test]+ fn op_ge() {+ op_impl("4.2 4 ge", &[1.0]);+ op_impl("4.2 4.2 ge", &[1.0]);+ op_impl("4.2 6 ge", &[0.0]);+ }++ #[test]+ fn op_gt() {+ op_impl("4.2 4 gt", &[1.0]);+ op_impl("4.2 4.2 gt", &[0.0]);+ op_impl("4.2 6 gt", &[0.0]);+ }++ #[test]+ fn op_le() {+ op_impl("4.2 4 le", &[0.0]);+ op_impl("4.2 4.2 le", &[1.0]);+ op_impl("4.2 6 le", &[1.0]);+ }++ #[test]+ fn op_lt() {+ op_impl("4.2 4 lt", &[0.0]);+ op_impl("4.2 4.2 lt", &[0.0]);+ op_impl("4.2 6 lt", &[1.0]);+ }++ #[test]+ fn op_ne() {+ op_impl("3.0 3 ne", &[0.0]);+ op_impl("3.0 3.0 ne", &[0.0]);+ op_impl("3.0 3.1 ne", &[1.0]);+ }++ #[test]+ fn op_not() {+ op_impl("true not", &[0.0]);+ op_impl("false not", &[1.0]);+ op_impl("52 not", &[-53.0]);+ }++ #[test]+ fn op_or() {+ op_impl("true true or", &[1.0]);+ op_impl("true false or", &[1.0]);+ op_impl("false true or", &[1.0]);+ op_impl("false false or", &[0.0]);+ op_impl("17 5 or", &[21.0]);+ }++ #[test]+ fn op_xor() {+ op_impl("true true xor", &[0.0]);+ op_impl("true false xor", &[1.0]);+ op_impl("false true xor", &[1.0]);+ op_impl("false false xor", &[0.0]);+ op_impl("7 3 xor", &[4.0]);+ op_impl("12 3 xor", &[15.0]);+ }++ #[test]+ fn op_if() {+ op_impl("true { 1.0 } if", &[1.0]);+ op_impl("false { 1.0 } if", &[]);+ }++ #[test]+ fn op_ifelse() {+ op_impl("true { 1.0 } { 2.0 } ifelse", &[1.0]);+ op_impl("false { 1.0 } { 2.0 } ifelse", &[2.0]);+ }++ #[test]+ fn op_copy() {+ op_impl("1 2 3 2 copy", &[1.0, 2.0, 3.0, 2.0, 3.0]);+ op_impl("1 2 3 0 copy", &[1.0, 2.0, 3.0]);+ }++ #[test]+ fn op_dup() {+ op_impl("1 2 3 dup", &[1.0, 2.0, 3.0, 3.0]);+ }++ #[test]+ fn op_exch() {+ op_impl("1 2 3 exch", &[1.0, 3.0, 2.0]);+ }++ #[test]+ fn op_index() {+ op_impl("1 2 3 4 0 index", &[1.0, 2.0, 3.0, 4.0, 4.0]);+ op_impl("1 2 3 4 3 index", &[1.0, 2.0, 3.0, 4.0, 1.0]);+ }++ #[test]+ fn op_pop() {+ op_impl("1 2 3 pop", &[1.0, 2.0]);+ }++ #[test]+ fn op_roll() {+ op_impl("1 2 3 3 -1 roll", &[2.0, 3.0, 1.0]);+ op_impl("1 2 3 3 1 roll", &[3.0, 1.0, 2.0]);+ op_impl("1 2 3 3 0 roll", &[1.0, 2.0, 3.0]);+ op_impl("1 2 3 3 5 roll", &[2.0, 3.0, 1.0]);+ op_impl("0 2 roll", &[]);+ op_impl(+ "1 2 3 4 5 6 7 5 2 roll",+ &[1.0, 2.0, 6.0, 7.0, 3.0, 4.0, 5.0],+ );+ }++ #[test]+ fn domain() {+ let procedure = parse_procedure(b"{ }").unwrap();++ let type4 = Function(Arc::new(FunctionType::Type4(Type4 {+ program: procedure,+ clamper: Clamper {+ domain: smallvec![(-5.0, 5.0), (-5.0, 5.0), (-5.0, 5.0)],+ range: None,+ },+ })));++ let input = smallvec![-10.0, -2.0, 6.0];+ let res = type4.eval(input).unwrap();++ assert_eq!(res.as_slice(), &[-5.0, -2.0, 5.0]);+ }+}diff --git a/vendor/hayro-interpret/src/interpret/mod.rs b/vendor/hayro-interpret/src/interpret/mod.rsnew file mode 100644index 000000000..0cb5c03ae--- /dev/null+++ b/vendor/hayro-interpret/src/interpret/mod.rs@@ -0,0 +1,755 @@+use crate::FillRule;+use crate::color::ColorSpace;+use crate::context::Context;+use crate::convert::{convert_line_cap, convert_line_join};+use crate::device::Device;+use crate::font::{Font, FontData, FontQuery, StandardFont};+use crate::interpret::path::{+ close_path, fill_path, fill_path_impl, fill_stroke_path, stroke_path,+};+use crate::interpret::state::{TextStateFont, handle_gs};+use crate::interpret::text::TextRenderingMode;+use crate::pattern::{Pattern, ShadingPattern};+use crate::shading::Shading;+use crate::util::{OptionLog, RectExt};+use crate::x_object::{+ FormXObject, ImageXObject, XObject, draw_form_xobject, draw_image_xobject, draw_xobject,+};+use hayro_syntax::content::TypedIter;+use hayro_syntax::content::ops::TypedInstruction;+use hayro_syntax::object::dict::keys::{ANNOTS, AP, AS, F, MCID, N, OC, RECT};+use hayro_syntax::object::{Array, Dict, Object, Rect, Stream, dict_or_stream};+use hayro_syntax::page::{Page, Resources};+use kurbo::{Affine, Point, Shape};+use smallvec::smallvec;+use std::sync::Arc;++pub(crate) mod path;+pub(crate) mod state;+pub(crate) mod text;++pub use state::ActiveTransferFunction;++/// A callback function for resolving font queries.+///+/// The first argument is the raw data, the second argument is the index in case the font+/// is a TTC, otherwise it should be 0.+pub type FontResolverFn = Arc<dyn Fn(&FontQuery) -> Option<(FontData, u32)> + Send + Sync>;+/// A callback function for resolving cmap names to their files.+pub type CMapResolverFn =+ Arc<dyn Fn(hayro_cmap::CMapName<'_>) -> Option<&'static [u8]> + Send + Sync>;+/// A callback function for resolving warnings during interpretation.+pub type WarningSinkFn = Arc<dyn Fn(InterpreterWarning) + Send + Sync>;++#[derive(Clone)]+/// Settings that should be applied during the interpretation process.+pub struct InterpreterSettings {+ /// Nearly every PDF contains text. In most cases, PDF files embed the fonts they use, and+ /// hayro can therefore read the font files and do all the processing needed. However, there+ /// are two problems:+ /// - Fonts don't _have_ to be embedded, it's possible that the PDF file only defines the basic+ /// metadata of the font, like its name, but relies on the PDF processor to find that font+ /// in its environment.+ /// - The PDF specification requires a list of 14 fonts that should always be available to a+ /// PDF processor. These include:+ /// - Times New Roman (Normal, Bold, Italic, `BoldItalic`)+ /// - Courier (Normal, Bold, Italic, `BoldItalic`)+ /// - Helvetica (Normal, Bold, Italic, `BoldItalic`)+ /// - `ZapfDingBats`+ /// - Symbol+ ///+ /// Because of this, if any of the above situations occurs, this callback will be called, which+ /// expects the data of an appropriate font to be returned, if available. If no such font is+ /// provided, the text will most likely fail to render.+ ///+ /// For the font data, there are two different formats that are accepted:+ /// - Any valid TTF/OTF font.+ /// - A valid CFF font program.+ ///+ /// The following recommendations are given for the implementation of this callback function.+ ///+ /// For the standard fonts, in case the original fonts are available on the system, you should+ /// just return those. Otherwise, for Helvetica, Courier and Times New Roman, the best alternative+ /// are the corresponding fonts of the [Liberation font family](https://github.com/liberationfonts/liberation-fonts).+ /// If you prefer smaller fonts, you can use the [Foxit CFF fonts](https://github.com/LaurenzV/hayro/tree/master/assets/standard_fonts),+ /// which are much smaller but are missing glyphs for certain scripts.+ ///+ /// For the `Symbol` and `ZapfDingBats` fonts, you should also prefer the system fonts, and if+ /// not available to you, you can, similarly to above, use the corresponding fonts from Foxit.+ ///+ /// If you don't want having to deal with this, you can just enable the `embed-fonts` feature+ /// and use the default implementation of the callback.+ pub font_resolver: FontResolverFn,+ /// A callback for resolving cmaps that aren't embedded.+ ///+ /// When the PDF requires using a cmap that is not directly embedded in the PDF,+ /// this callback will be called to attempt fetching the data of the file.+ ///+ /// When the `embed-cmaps` feature is enabled, this uses `load_embedded`+ /// method from `hayro-cmap` by default, which embeds the cmap files for+ /// all 61 predefined cmaps+ /// that the PDF specification requires to be readily available on a system.+ /// Otherwise, you can implement your custom logic for lazily fetching the+ /// data. If you are fine not supporting such PDFs, you can simply pass a closure+ /// that always returns `None`.+ pub cmap_resolver: CMapResolverFn,+ /// In certain cases, `hayro` will emit a warning in case an issue was encountered while interpreting+ /// the PDF file. Providing a callback allows you to catch those warnings and handle them, if desired.+ pub warning_sink: WarningSinkFn,+ /// Whether annotations should be rendered as well.+ ///+ /// Note that this feature is currently not fully implemented yet, so some+ /// annotations might be missing.+ pub render_annotations: bool,+ /// PrintCraft patch: viewer overrides for optional content groups (object number, generation,+ /// visible), applied on top of the document's default configuration (Layers panel toggles).+ pub ocg_overrides: Arc<Vec<(i32, i32, bool)>>,+}++impl Default for InterpreterSettings {+ fn default() -> Self {+ Self {+ #[cfg(not(feature = "embed-fonts"))]+ font_resolver: Arc::new(|_| None),+ #[cfg(feature = "embed-fonts")]+ font_resolver: Arc::new(|query| match query {+ FontQuery::Standard(s) => Some(s.get_font_data()),+ FontQuery::Fallback(f) => Some(f.pick_standard_font().get_font_data()),+ }),+ #[cfg(feature = "embed-cmaps")]+ cmap_resolver: Arc::new(hayro_cmap::load_embedded),+ #[cfg(not(feature = "embed-cmaps"))]+ cmap_resolver: Arc::new(|_| None),+ warning_sink: Arc::new(|_| {}),+ render_annotations: true,+ ocg_overrides: Arc::new(Vec::new()),+ }+ }+}++#[derive(Copy, Clone, Debug)]+/// Warnings that can occur while interpreting a PDF file.+pub enum InterpreterWarning {+ /// An unsupported font kind was encountered.+ ///+ /// Currently, only CID fonts with non-identity encoding are unsupported.+ UnsupportedFont,+ /// An image failed to decode.+ ImageDecodeFailure,+}++/// interpret the contents of the page and render them into the device.+pub fn interpret_page<'a>(+ page: &Page<'a>,+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+) {+ let resources = page.resources();+ interpret(page.typed_operations(), resources, context, device);++ if context.settings.render_annotations+ && let Some(annot_arr) = page.raw().get::<Array<'_>>(ANNOTS)+ {+ for annot in annot_arr.iter::<Dict<'_>>() {+ let flags = annot.get::<u32>(F).unwrap_or(0);++ // Annotation should be hidden (Hidden = bit 2, NoView = bit 6).+ // PrintCraft patch: NoView was not honoured upstream.+ if flags & (2 | 32) != 0 {+ continue;+ }++ // PrintCraft patch: `/N` may be a stream or a dictionary of appearance states selected+ // by `/AS` (checkboxes, radio buttons, …). Upstream only handled the stream form.+ let normal = annot.get::<Dict<'_>>(AP).and_then(|ap| {+ ap.get::<Stream<'_>>(N).or_else(|| {+ let states = ap.get::<Dict<'_>>(N)?;+ let state = annot.get::<hayro_syntax::object::Name<'_>>(AS)?;+ states.get::<Stream<'_>>(state.as_ref())+ })+ });+ if let Some(apx) = normal.and_then(|o| FormXObject::new(&o)) {+ let Some(rect) = annot.get::<Rect>(RECT) else {+ continue;+ };++ let annot_rect = rect.to_kurbo();+ // 12.5.5. Appearance streams+ // "The algorithm outlined in this subclause shall be used+ // to map from the coordinate system of the appearance XObject."++ // 1) The appearance’s bounding box (specified by its BBox entry)+ // shall be transformed, using Matrix, to produce a+ // quadrilateral with arbitrary orientation. The transformed+ // appearance box is the smallest upright rectangle that+ // encompasses this quadrilateral.+ let transformed_rect = (apx.matrix+ * kurbo::Rect::new(+ apx.bbox[0] as f64,+ apx.bbox[1] as f64,+ apx.bbox[2] as f64,+ apx.bbox[3] as f64,+ )+ .to_path(0.1))+ .bounding_box();++ // 2) A matrix A shall be computed that scales and translates+ // the transformed appearance box to align with the edges+ // of the annotation’s rectangle (specified by the Rect entry).+ // A maps the lower-left corner (the corner with the smallest+ // x and y coordinates) and the upper-right corner (the+ // corner with the greatest x and y coordinates) of the+ // transformed appearance box to the corresponding corners+ // of the annotation’s rectangle.+ let affine = Affine::new([+ annot_rect.width() / transformed_rect.width(),+ 0.0,+ 0.0,+ annot_rect.height() / transformed_rect.height(),+ annot_rect.x0 - transformed_rect.x0,+ annot_rect.y0 - transformed_rect.y0,+ ]);++ // 3) Matrix shall be concatenated with A to form a matrix+ // AA that maps from the appearance’s coordinate system to+ // the annotation’s rectangle in default user space.+ context.save_state();+ context.pre_concat_affine(affine);+ context.push_root_transform();++ draw_form_xobject(resources, &apx, context, device);+ context.pop_root_transform();+ context.restore_state(device);+ }+ }+ }+}++/// Interpret the instructions from `ops` and render them into the device.+pub fn interpret<'a>(+ mut ops: TypedIter<'_>,+ resources: &Resources<'a>,+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+) {+ let num_states = context.num_states();++ context.save_state();++ while let Some(op) = ops.next() {+ match op {+ TypedInstruction::SaveState(_) => context.save_state(),+ TypedInstruction::StrokeColorDeviceRgb(s) => {+ context.get_mut().graphics_state.stroke_cs = ColorSpace::device_rgb();+ context.get_mut().graphics_state.stroke_color =+ smallvec![s.0.as_f32(), s.1.as_f32(), s.2.as_f32()];+ context.get_mut().graphics_state.stroke_pattern = None;+ }+ TypedInstruction::StrokeColorDeviceGray(s) => {+ context.get_mut().graphics_state.stroke_cs = ColorSpace::device_gray();+ context.get_mut().graphics_state.stroke_color = smallvec![s.0.as_f32()];+ context.get_mut().graphics_state.stroke_pattern = None;+ }+ TypedInstruction::StrokeColorCmyk(s) => {+ context.get_mut().graphics_state.stroke_cs = ColorSpace::device_cmyk();+ context.get_mut().graphics_state.stroke_color =+ smallvec![s.0.as_f32(), s.1.as_f32(), s.2.as_f32(), s.3.as_f32()];+ context.get_mut().graphics_state.stroke_pattern = None;+ }+ TypedInstruction::LineWidth(w) => {+ context.get_mut().graphics_state.stroke_props.line_width = w.0.as_f32();+ }+ TypedInstruction::LineCap(c) => {+ context.get_mut().graphics_state.stroke_props.line_cap = convert_line_cap(c);+ }+ TypedInstruction::LineJoin(j) => {+ context.get_mut().graphics_state.stroke_props.line_join = convert_line_join(j);+ }+ TypedInstruction::MiterLimit(l) => {+ context.get_mut().graphics_state.stroke_props.miter_limit = l.0.as_f32();+ }+ TypedInstruction::Transform(t) => {+ context.pre_concat_transform(t);+ }+ TypedInstruction::RectPath(r) => {+ let rect = kurbo::Rect::new(+ r.0.as_f64(),+ r.1.as_f64(),+ r.0.as_f64() + r.2.as_f64(),+ r.1.as_f64() + r.3.as_f64(),+ )+ .to_path(0.1);+ context.path_mut().extend(rect);+ }+ TypedInstruction::MoveTo(m) => {+ let p = Point::new(m.0.as_f64(), m.1.as_f64());+ *(context.last_point_mut()) = p;+ *(context.sub_path_start_mut()) = p;+ context.path_mut().move_to(p);+ }+ TypedInstruction::FillPathEvenOdd(_) => {+ fill_path(context, device, FillRule::EvenOdd);+ }+ TypedInstruction::FillPathNonZero(_) => {+ fill_path(context, device, FillRule::NonZero);+ }+ TypedInstruction::FillPathNonZeroCompatibility(_) => {+ fill_path(context, device, FillRule::NonZero);+ }+ TypedInstruction::FillAndStrokeEvenOdd(_) => {+ fill_stroke_path(context, device, FillRule::EvenOdd);+ }+ TypedInstruction::FillAndStrokeNonZero(_) => {+ fill_stroke_path(context, device, FillRule::NonZero);+ }+ TypedInstruction::CloseAndStrokePath(_) => {+ close_path(context);+ stroke_path(context, device);+ }+ TypedInstruction::CloseFillAndStrokeEvenOdd(_) => {+ close_path(context);+ fill_stroke_path(context, device, FillRule::EvenOdd);+ }+ TypedInstruction::CloseFillAndStrokeNonZero(_) => {+ close_path(context);+ fill_stroke_path(context, device, FillRule::NonZero);+ }+ TypedInstruction::NonStrokeColorDeviceGray(s) => {+ context.get_mut().graphics_state.none_stroke_cs = ColorSpace::device_gray();+ context.get_mut().graphics_state.non_stroke_color = smallvec![s.0.as_f32()];+ context.get_mut().graphics_state.non_stroke_pattern = None;+ }+ TypedInstruction::NonStrokeColorDeviceRgb(s) => {+ context.get_mut().graphics_state.none_stroke_cs = ColorSpace::device_rgb();+ context.get_mut().graphics_state.non_stroke_color =+ smallvec![s.0.as_f32(), s.1.as_f32(), s.2.as_f32()];+ context.get_mut().graphics_state.non_stroke_pattern = None;+ }+ TypedInstruction::NonStrokeColorCmyk(s) => {+ context.get_mut().graphics_state.none_stroke_cs = ColorSpace::device_cmyk();+ context.get_mut().graphics_state.non_stroke_color =+ smallvec![s.0.as_f32(), s.1.as_f32(), s.2.as_f32(), s.3.as_f32()];+ context.get_mut().graphics_state.non_stroke_pattern = None;+ }+ TypedInstruction::LineTo(m) => {+ if !context.path().elements().is_empty() {+ let last_point = *context.last_point();+ let mut p = Point::new(m.0.as_f64(), m.1.as_f64());+ *(context.last_point_mut()) = p;+ if last_point == p {+ // Add a small delta so that zero width lines can still have a round stroke.+ p.x += 0.0001;+ }++ context.path_mut().line_to(p);+ }+ }+ TypedInstruction::CubicTo(c) => {+ if !context.path().elements().is_empty() {+ let p1 = Point::new(c.0.as_f64(), c.1.as_f64());+ let p2 = Point::new(c.2.as_f64(), c.3.as_f64());+ let p3 = Point::new(c.4.as_f64(), c.5.as_f64());++ *(context.last_point_mut()) = p3;++ context.path_mut().curve_to(p1, p2, p3);+ }+ }+ TypedInstruction::CubicStartTo(c) => {+ if !context.path().elements().is_empty() {+ let p1 = *context.last_point();+ let p2 = Point::new(c.0.as_f64(), c.1.as_f64());+ let p3 = Point::new(c.2.as_f64(), c.3.as_f64());++ *(context.last_point_mut()) = p3;++ context.path_mut().curve_to(p1, p2, p3);+ }+ }+ TypedInstruction::CubicEndTo(c) => {+ if !context.path().elements().is_empty() {+ let p2 = Point::new(c.0.as_f64(), c.1.as_f64());+ let p3 = Point::new(c.2.as_f64(), c.3.as_f64());++ *(context.last_point_mut()) = p3;++ context.path_mut().curve_to(p2, p3, p3);+ }+ }+ TypedInstruction::ClosePath(_) => {+ close_path(context);+ }+ TypedInstruction::SetGraphicsState(gs) => {+ if let Some(gs) = resources+ .get_ext_g_state(gs.0)+ .warn_none(&format!("failed to get extgstate {}", gs.0.as_str()))+ {+ handle_gs(&gs, context, resources);+ }+ }+ TypedInstruction::StrokePath(_) => {+ stroke_path(context, device);+ }+ TypedInstruction::EndPath(_) => {+ if let Some(clip) = *context.clip()+ && !context.path().elements().is_empty()+ {+ let clip_path = context.get().ctm * context.path().clone();+ context.push_clip_path(clip_path, clip, device);++ *(context.clip_mut()) = None;+ }++ context.path_mut().truncate(0);+ }+ TypedInstruction::NonStrokeColor(c) => {+ let gs = &mut context.get_mut().graphics_state;+ gs.non_stroke_color = c.0.into_iter().map(|n| n.as_f32()).collect();+ gs.non_stroke_pattern = None;+ }+ TypedInstruction::StrokeColor(c) => {+ let gs = &mut context.get_mut().graphics_state;+ gs.stroke_color = c.0.into_iter().map(|n| n.as_f32()).collect();+ gs.stroke_pattern = None;+ }+ TypedInstruction::ClipNonZero(_) => {+ *(context.clip_mut()) = Some(FillRule::NonZero);+ }+ TypedInstruction::ClipEvenOdd(_) => {+ *(context.clip_mut()) = Some(FillRule::EvenOdd);+ }+ TypedInstruction::RestoreState(_) => context.restore_state(device),+ TypedInstruction::FlatnessTolerance(_) => {+ // Ignore for now.+ }+ TypedInstruction::ColorSpaceStroke(c) => {+ let cs = if let Some(named) = ColorSpace::new_from_name(c.0) {+ named+ } else {+ context+ .get_color_space(resources, c.0)+ .unwrap_or(ColorSpace::device_gray())+ };++ if !cs.is_pattern() {+ context.get_mut().graphics_state.stroke_pattern = None;+ }+ context.get_mut().graphics_state.stroke_color = cs.initial_color();+ context.get_mut().graphics_state.stroke_cs = cs;+ }+ TypedInstruction::ColorSpaceNonStroke(c) => {+ let cs = if let Some(named) = ColorSpace::new_from_name(c.0) {+ named+ } else {+ context+ .get_color_space(resources, c.0)+ .unwrap_or(ColorSpace::device_gray())+ };++ if !cs.is_pattern() {+ context.get_mut().graphics_state.non_stroke_pattern = None;+ }+ context.get_mut().graphics_state.non_stroke_color = cs.initial_color();+ context.get_mut().graphics_state.none_stroke_cs = cs;+ }+ TypedInstruction::DashPattern(p) => {+ context.get_mut().graphics_state.stroke_props.dash_offset = p.1.as_f32();+ // kurbo apparently cannot properly deal with offsets that are exactly 0.+ context.get_mut().graphics_state.stroke_props.dash_array =+ p.0.iter::<f32>()+ .map(|n| if n == 0.0 { 0.01 } else { n })+ .collect();+ }+ TypedInstruction::RenderingIntent(_) => {+ // Ignore for now.+ }+ TypedInstruction::NonStrokeColorNamed(n) => {+ context.get_mut().graphics_state.non_stroke_color =+ n.0.into_iter().map(|n| n.as_f32()).collect();+ context.get_mut().graphics_state.non_stroke_pattern = n.1.and_then(|name| {+ resources+ .get_pattern(name)+ .and_then(|d| Pattern::new(d, context, resources))+ });+ }+ TypedInstruction::StrokeColorNamed(n) => {+ context.get_mut().graphics_state.stroke_color =+ n.0.into_iter().map(|n| n.as_f32()).collect();+ context.get_mut().graphics_state.stroke_pattern = n.1.and_then(|name| {+ resources+ .get_pattern(name)+ .and_then(|d| Pattern::new(d, context, resources))+ });+ }+ TypedInstruction::BeginMarkedContentWithProperties(bdc) => {+ // Properties can be either:+ // 1. A Name that references an entry in the Resources/Properties dictionary+ // 2. An inline dictionary with an OC key++ let mcid = dict_or_stream(bdc.1).and_then(|(props, _)| props.get::<i32>(MCID));++ let oc = bdc+ .1+ .clone()+ .into_name()+ .and_then(|name| {+ let r = resources.properties.get_ref(name.as_ref())?;+ let d = resources+ .properties+ .get::<Dict<'_>>(name)+ .unwrap_or_default();+ Some((d, r))+ })+ .or_else(|| {+ let (props, _) = dict_or_stream(bdc.1)?;+ let r = props.get_ref(OC)?;+ let d = props.get::<Dict<'_>>(OC).unwrap_or_default();+ Some((d, r))+ });++ if let Some((dict, oc_ref)) = oc {+ context.ocg_state.begin_ocg(&dict, oc_ref.into());+ } else {+ context.ocg_state.begin_marked_content();+ }++ device.begin_marked_content(bdc.0, mcid);+ }+ TypedInstruction::MarkedContentPointWithProperties(_) => {}+ TypedInstruction::EndMarkedContent(_) => {+ context.ocg_state.end_marked_content();+ device.end_marked_content();+ }+ TypedInstruction::MarkedContentPoint(_) => {}+ TypedInstruction::BeginMarkedContent(bmc) => {+ context.ocg_state.begin_marked_content();+ device.begin_marked_content(bmc.0, None);+ }+ TypedInstruction::BeginText(_) => {+ context.get_mut().text_state.text_matrix = Affine::IDENTITY;+ context.get_mut().text_state.text_line_matrix = Affine::IDENTITY;+ }+ TypedInstruction::SetTextMatrix(m) => {+ let m = Affine::new([+ m.0.as_f64(),+ m.1.as_f64(),+ m.2.as_f64(),+ m.3.as_f64(),+ m.4.as_f64(),+ m.5.as_f64(),+ ]);+ context.get_mut().text_state.text_line_matrix = m;+ context.get_mut().text_state.text_matrix = m;+ }+ TypedInstruction::EndText(_) => {+ let has_outline = context+ .get()+ .text_state+ .clip_paths+ .segments()+ .next()+ .is_some();++ if has_outline {+ let clip_path = context.get().ctm * context.get().text_state.clip_paths.clone();++ context.push_clip_path(clip_path, FillRule::NonZero, device);+ }++ context.get_mut().text_state.clip_paths.truncate(0);+ }+ TypedInstruction::TextFont(t) => {+ let name = t.0;++ // In case we are unable to resolve the font, two scenarios:+ // 1) If the font doesn't exist in the first place in the resource dictionary,+ // assume Helvetica (this seems to be what other PDF viewers do).+ // 2) In case it's `None` because we were unable to resolve the font+ // (for whatever reason), leave it as `None`. Better showing no+ // text at all than garbage text.+ let font = if let Some(font_dict) = resources.get_font(name) {+ context.resolve_font(&font_dict)+ } else {+ Font::new_standard(StandardFont::Helvetica, &context.settings.font_resolver)+ .map(TextStateFont::Fallback)+ };++ context.get_mut().text_state.font_size = t.1.as_f32();+ context.get_mut().text_state.font = font;+ }+ TypedInstruction::ShowText(s) => {+ if context.get().text_state.font.is_none() {+ // Even if no explicit font was set, we try to assume Helvetica. Acrobat+ // seems to do the same.+ context.get_mut().text_state.font = Font::new_standard(+ StandardFont::Helvetica,+ &context.settings.font_resolver,+ )+ .map(TextStateFont::Fallback);+ }++ text::show_text_string(context, device, resources, s.0);+ }+ TypedInstruction::ShowTexts(s) => {+ if context.get().text_state.font.is_none() {+ // Even if no explicit font was set, we try to assume Helvetica. Acrobat+ // seems to do the same.+ context.get_mut().text_state.font = Font::new_standard(+ StandardFont::Helvetica,+ &context.settings.font_resolver,+ )+ .map(TextStateFont::Fallback);+ }++ for obj in s.0.iter::<Object<'_>>() {+ match obj {+ Object::Number(num) => {+ context.get_mut().text_state.apply_adjustment(num.as_f32());+ }+ Object::String(text) => {+ text::show_text_string(context, device, resources, &text);+ }+ _ => {}+ }+ }+ }+ TypedInstruction::HorizontalScaling(h) => {+ context.get_mut().text_state.horizontal_scaling = h.0.as_f32();+ }+ TypedInstruction::TextLeading(tl) => {+ context.get_mut().text_state.leading = tl.0.as_f32();+ }+ TypedInstruction::CharacterSpacing(c) => {+ context.get_mut().text_state.char_space = c.0.as_f32();+ }+ TypedInstruction::WordSpacing(w) => {+ context.get_mut().text_state.word_space = w.0.as_f32();+ }+ TypedInstruction::NextLine(n) => {+ let (tx, ty) = (n.0.as_f64(), n.1.as_f64());+ text::next_line(context, tx, ty);+ }+ TypedInstruction::NextLineUsingLeading(_) => {+ text::next_line(context, 0.0, -context.get().text_state.leading as f64);+ }+ TypedInstruction::NextLineAndShowText(n) => {+ text::next_line(context, 0.0, -context.get().text_state.leading as f64);+ text::show_text_string(context, device, resources, n.0);+ }+ TypedInstruction::TextRenderingMode(r) => {+ let mode = match r.0.as_i64() {+ 0 => TextRenderingMode::Fill,+ 1 => TextRenderingMode::Stroke,+ 2 => TextRenderingMode::FillStroke,+ 3 => TextRenderingMode::Invisible,+ 4 => TextRenderingMode::FillAndClip,+ 5 => TextRenderingMode::StrokeAndClip,+ 6 => TextRenderingMode::FillAndStrokeAndClip,+ 7 => TextRenderingMode::Clip,+ _ => {+ warn!("unknown text rendering mode {}", r.0.as_i64());++ TextRenderingMode::Fill+ }+ };++ context.get_mut().text_state.render_mode = mode;+ }+ TypedInstruction::NextLineAndSetLeading(n) => {+ let (tx, ty) = (n.0.as_f64(), n.1.as_f64());+ context.get_mut().text_state.leading = -ty as f32;+ text::next_line(context, tx, ty);+ }+ TypedInstruction::ShapeGlyph(_) => {}+ TypedInstruction::XObject(x) => {+ let cache = context.interpreter_cache.object_cache.clone();+ let transfer_function = context.get().graphics_state.transfer_function.clone();+ if let Some(x_object) = resources.get_x_object(x.0).and_then(|s| {+ XObject::new(+ &s,+ &context.settings.warning_sink,+ &cache,+ transfer_function.clone(),+ )+ }) {+ draw_xobject(&x_object, resources, context, device);+ }+ }+ TypedInstruction::InlineImage(i) => {+ let warning_sink = context.settings.warning_sink.clone();+ let transfer_function = context.get().graphics_state.transfer_function.clone();+ let cache = context.interpreter_cache.object_cache.clone();+ if let Some(x_object) = ImageXObject::new(+ i.0,+ |name| context.get_color_space(resources, name),+ &warning_sink,+ &cache,+ false,+ transfer_function,+ ) {+ draw_image_xobject(&x_object, context, device);+ }+ }+ TypedInstruction::TextRise(t) => {+ context.get_mut().text_state.rise = t.0.as_f32();+ }+ TypedInstruction::Shading(s) => {+ if !context.ocg_state.is_visible() {+ continue;+ }++ let transfer_function = context.get().graphics_state.transfer_function.clone();++ if let Some(sp) = resources+ .get_shading(s.0)+ .and_then(|o| {+ let (dict, stream) = dict_or_stream(&o)?;+ Shading::new(dict, stream, &context.interpreter_cache.object_cache)+ })+ .map(|s| {+ Pattern::Shading(ShadingPattern {+ shading: Arc::new(s),+ matrix: Affine::IDENTITY,+ opacity: context.get().graphics_state.non_stroke_alpha,+ transfer_function: transfer_function.clone(),+ })+ })+ {+ context.save_state();+ context.push_root_transform();+ let st = context.get_mut();+ st.graphics_state.non_stroke_pattern = Some(sp);+ st.graphics_state.none_stroke_cs = ColorSpace::pattern();++ device.set_soft_mask(st.graphics_state.soft_mask.clone());+ device.set_blend_mode(st.graphics_state.blend_mode);++ let bbox = context.bbox().to_path(0.1);+ let inverted_bbox = context.get().ctm.inverse() * bbox;+ fill_path_impl(context, device, FillRule::NonZero, Some(&inverted_bbox));++ context.pop_root_transform();+ context.restore_state(device);+ } else {+ warn!("failed to process shading");+ }+ }+ TypedInstruction::BeginCompatibility(_) => {}+ TypedInstruction::EndCompatibility(_) => {}+ TypedInstruction::ColorGlyph(_) => {}+ TypedInstruction::ShowTextWithParameters(t) => {+ context.get_mut().text_state.word_space = t.0.as_f32();+ context.get_mut().text_state.char_space = t.1.as_f32();+ text::next_line(context, 0.0, -context.get().text_state.leading as f64);+ text::show_text_string(context, device, resources, t.2);+ }+ _ => {+ warn!("failed to read an operator");+ }+ }+ }++ while context.num_states() > num_states {+ context.restore_state(device);+ }+}diff --git a/vendor/hayro-interpret/src/interpret/path.rs b/vendor/hayro-interpret/src/interpret/path.rsnew file mode 100644index 000000000..e1e7d96a5--- /dev/null+++ b/vendor/hayro-interpret/src/interpret/path.rs@@ -0,0 +1,163 @@+use crate::color::{Color, ColorSpace};+use crate::context::{Context, path_as_rect};+use crate::device::Device;+use crate::util::{BezPathExt, Float32Ext};+use crate::{FillRule, Paint, PathDrawMode, StrokeProps};+use kurbo::{BezPath, Cap, Join, PathEl};+use smallvec::smallvec;++pub(crate) fn fill_path<'a>(+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+ fill_rule: FillRule,+) {+ fill_path_impl(context, device, fill_rule, None);++ context.path_mut().truncate(0);+}++pub(crate) fn stroke_path<'a>(context: &mut Context<'a>, device: &mut impl Device<'a>) {+ stroke_path_impl(context, device, None);++ context.path_mut().truncate(0);+}++pub(crate) fn fill_stroke_path<'a>(+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+ fill_rule: FillRule,+) {+ fill_path_impl(context, device, fill_rule, None);+ stroke_path_impl(context, device, None);++ context.path_mut().truncate(0);+}++pub(crate) fn close_path(context: &mut Context<'_>) {+ // This is necessary to prevent artifacts (see for example issue 157),+ // but it does cause some weird lines (maybe conflation artifacts) in+ // pdftc_900k_0907.+ if context.path().elements().last() != Some(&PathEl::ClosePath) && !context.path().is_empty() {+ context.path_mut().close_path();++ *(context.last_point_mut()) = *context.sub_path_start();+ }+}++pub(crate) fn fill_path_impl<'a>(+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+ fill_rule: FillRule,+ path: Option<&BezPath>,+) {+ if !context.ocg_state.is_visible() {+ return;+ }++ let base_transform = context.get().ctm;++ let paint = get_paint(context, false);+ device.set_soft_mask(context.get().graphics_state.soft_mask.clone());+ device.set_blend_mode(context.get().graphics_state.blend_mode);++ let mut draw = |path: &BezPath| {+ // pdf.js issue 4260: Replace zero-sized paths with a small stroke instead.+ let bbox = path.fast_bounding_box();++ match (+ (bbox.width() as f32).is_nearly_zero(),+ (bbox.height() as f32).is_nearly_zero(),+ ) {+ (false, false) => {+ let draw_mode = PathDrawMode::Fill(fill_rule);+ if let Some(rect) = path_as_rect(path) {+ device.draw_rect(&rect, base_transform, &paint, &draw_mode);+ } else {+ device.draw_path(path, base_transform, &paint, &draw_mode);+ }+ }+ _ => {+ let mut path = BezPath::new();+ path.move_to((bbox.x0, bbox.y0));+ path.line_to((bbox.x1, bbox.y1));++ let stroke_props = StrokeProps {+ // TODO: Make dependent on transform?+ line_width: 0.001,+ line_join: Join::Bevel,+ line_cap: Cap::Butt,+ ..Default::default()+ };++ device.draw_path(+ &path,+ base_transform,+ &paint,+ &PathDrawMode::Stroke(stroke_props),+ );+ }+ };+ };++ match path {+ None => draw(context.path()),+ Some(path) => draw(path),+ };+}++pub(crate) fn stroke_path_impl<'a>(+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+ path: Option<&BezPath>,+) {+ if !context.ocg_state.is_visible() {+ return;+ }++ let base_transform = context.get().ctm;++ let stroke_props = context.stroke_props();+ device.set_soft_mask(context.get().graphics_state.soft_mask.clone());+ device.set_blend_mode(context.get().graphics_state.blend_mode);+ let paint = get_paint(context, true);++ let path = path.unwrap_or(context.path());+ let draw_mode = PathDrawMode::Stroke(stroke_props);++ if let Some(rect) = path_as_rect(path) {+ device.draw_rect(&rect, base_transform, &paint, &draw_mode);+ } else {+ device.draw_path(path, base_transform, &paint, &draw_mode);+ }+}++pub(crate) fn get_paint<'a>(context: &Context<'a>, is_stroke: bool) -> Paint<'a> {+ let data = if is_stroke {+ context.get().stroke_data()+ } else {+ context.get().non_stroke_data()+ };++ if data.color_space.is_pattern() || data.pattern.is_some() {+ if let Some(mut pattern) = data.pattern {+ if let Some(tf) = &data.transfer_function {+ pattern.set_transfer_function(tf.clone());+ }++ pattern.pre_concat_transform(context.root_transform());++ Paint::Pattern(Box::new(pattern))+ } else {+ // Pattern was likely invalid, use transparent paint.+ Paint::Color(Color::new(ColorSpace::device_gray(), smallvec![0.0], 0.0))+ }+ } else {+ let color = Color::new(data.color_space, data.color, data.alpha);++ if let Some(tf) = &data.transfer_function {+ Paint::Color(Color::from_rgba(tf.apply(&color.to_rgba())))+ } else {+ Paint::Color(color)+ }+ }+}diff --git a/vendor/hayro-interpret/src/interpret/state.rs b/vendor/hayro-interpret/src/interpret/state.rsnew file mode 100644index 000000000..95b773fb5--- /dev/null+++ b/vendor/hayro-interpret/src/interpret/state.rs@@ -0,0 +1,440 @@+use crate::StrokeProps;+use crate::color::{AlphaColor, ColorComponents, ColorSpace};+use crate::context::Context;+use crate::convert::{convert_line_cap, convert_line_join};+use crate::font::{Font, UNITS_PER_EM};+use crate::function::Function;+use crate::interpret::text::TextRenderingMode;+use crate::pattern::Pattern;+use crate::soft_mask::SoftMask;+use crate::types::BlendMode;+use crate::util::OptionLog;+use hayro_syntax::content::ops::{LineCap, LineJoin};+use hayro_syntax::object::dict::keys::{FONT, SMASK, TR, TR2};+use hayro_syntax::object::{Array, Dict, Name, Number, Object};+use hayro_syntax::page::Resources;+use kurbo::{Affine, BezPath, Vec2};+use smallvec::smallvec;+use std::ops::Deref;++/// A transfer function.+#[derive(Clone, Debug)]+pub enum ActiveTransferFunction {+ /// A single transfer function applied to all components.+ Single(Function),+ /// Four transfer functions, one for each component.+ Four([Function; 4]),+}++impl ActiveTransferFunction {+ /// Apply the transfer function to the RGB channels of an RGBA color.+ /// The alpha channel is left unchanged.+ pub fn apply(&self, color: &AlphaColor) -> AlphaColor {+ let mut rgba = color.components();++ match self {+ Self::Single(f) => {+ for c in &mut rgba[..3] {+ if let Some(out) = f.eval(smallvec![*c]) {+ *c = out[0];+ }+ }+ }+ Self::Four(functions) => {+ for (i, f) in functions[..3].iter().enumerate() {+ if let Some(out) = f.eval(smallvec![rgba[i]]) {+ rgba[i] = out[0];+ }+ }+ }+ }++ AlphaColor::new(rgba)+ }+}++#[derive(Clone, Debug)]+pub(crate) enum ClipType {+ Dummy,+ Real,+}++#[derive(Clone, Debug)]+pub(crate) struct State<'a> {+ // Note that the text state and ctm are theoretically part of the graphics state,+ // but we keep them separate for simplicity.+ pub(crate) graphics_state: GraphicsState<'a>,+ pub(crate) text_state: TextState<'a>,+ pub(crate) ctm: Affine,+ // Strictly speaking not part of the graphics state, but we keep it there for+ // consistency.+ pub(crate) clips: Vec<ClipType>,+}++impl Default for State<'_> {+ fn default() -> Self {+ State {+ ctm: Affine::IDENTITY,+ clips: vec![],+ text_state: TextState::default(),+ graphics_state: GraphicsState::default(),+ }+ }+}++impl<'a> State<'a> {+ pub(crate) fn new(initial_transform: Affine) -> Self {+ Self {+ ctm: initial_transform,+ ..Self::default()+ }+ }++ pub(crate) fn stroke_data(&self) -> PaintData<'a> {+ PaintData {+ alpha: self.graphics_state.stroke_alpha,+ color: self.graphics_state.stroke_color.clone(),+ color_space: self.graphics_state.stroke_cs.clone(),+ pattern: self.graphics_state.stroke_pattern.clone(),+ transfer_function: self.graphics_state.transfer_function.clone(),+ }+ }++ pub(crate) fn non_stroke_data(&self) -> PaintData<'a> {+ PaintData {+ alpha: self.graphics_state.non_stroke_alpha,+ color: self.graphics_state.non_stroke_color.clone(),+ color_space: self.graphics_state.none_stroke_cs.clone(),+ pattern: self.graphics_state.non_stroke_pattern.clone(),+ transfer_function: self.graphics_state.transfer_function.clone(),+ }+ }+}++#[derive(Clone, Debug)]+pub(crate) enum TextStateFont<'a> {+ /// The font in the text state was explicitly set and resolves to a valid+ /// font.+ Font(Font<'a>),+ /// The font was not set or an invalid font was set.+ Fallback(Font<'a>),+}++impl<'a> Deref for TextStateFont<'a> {+ type Target = Font<'a>;++ fn deref(&self) -> &Self::Target {+ match self {+ TextStateFont::Font(f) => f,+ TextStateFont::Fallback(f) => f,+ }+ }+}++#[derive(Clone, Debug)]+pub(crate) struct TextState<'a> {+ pub(crate) char_space: f32,+ pub(crate) word_space: f32,+ // Note that this stores 1/100 of the actual scaling.+ pub(crate) horizontal_scaling: f32,+ pub(crate) leading: f32,+ pub(crate) font: Option<TextStateFont<'a>>,+ pub(crate) font_size: f32,+ pub(crate) rise: f32,+ pub(crate) render_mode: TextRenderingMode,++ pub(crate) text_matrix: Affine,+ pub(crate) text_line_matrix: Affine,++ // When setting the text rendering mode to `clip`, the glyphs should instead be collected+ // as paths and then applied as 1 single clip path. This field stores those clip paths.+ pub(crate) clip_paths: BezPath,+}++impl<'a> TextState<'a> {+ fn temp_transform(&self) -> Affine {+ Affine::new([+ self.font_size as f64 * self.horizontal_scaling() as f64,+ 0.0,+ 0.0,+ self.font_size as f64,+ 0.0,+ self.rise as f64,+ ])+ }++ fn horizontal_scaling(&self) -> f32 {+ self.horizontal_scaling / 100.0+ }++ fn font_horizontal(&self) -> bool {+ self.font+ .as_ref()+ .map(|f| f.is_horizontal())+ .unwrap_or(false)+ }++ pub(crate) fn apply_adjustment(&mut self, adjustment: f32) {+ let horizontal = self.font_horizontal();++ let horizontal_scaling = if horizontal {+ self.horizontal_scaling()+ } else {+ 1.0+ };++ let scaled_adjustment = -adjustment / UNITS_PER_EM * self.font_size * horizontal_scaling;+ let (tx, ty) = if horizontal {+ (scaled_adjustment, 0.0)+ } else {+ (0.0, scaled_adjustment)+ };++ self.text_matrix *= Affine::new([1.0, 0.0, 0.0, 1.0, tx as f64, ty as f64]);+ }++ pub(crate) fn apply_code_advance(&mut self, char_code: u32, code_len: usize) {+ let glyph_advance = self+ .font+ .as_ref()+ .map(|f| f.code_advance(char_code))+ .unwrap_or(Vec2::ZERO);+ let horizontal = self.font_horizontal();++ let word_space = if char_code == 32 && code_len == 1 {+ self.word_space+ } else {+ 0.0+ };++ let base_advance =+ |advance: f32| advance / UNITS_PER_EM * self.font_size + self.char_space + word_space;++ let tx = if horizontal {+ base_advance(glyph_advance.x as f32) * self.horizontal_scaling()+ } else {+ 0.0+ };++ let ty = if !horizontal {+ base_advance(glyph_advance.y as f32)+ } else {+ 0.0+ };++ self.text_matrix *= Affine::new([1.0, 0.0, 0.0, 1.0, tx as f64, ty as f64]);+ }++ pub(crate) fn full_transform(&self) -> Affine {+ self.text_matrix * self.temp_transform()+ }+}++impl Default for TextState<'_> {+ fn default() -> Self {+ Self {+ char_space: 0.0,+ word_space: 0.0,+ horizontal_scaling: 100.0,+ leading: 0.0,+ font: None,+ // Not in the specification, but we just define it so we don't need to use an option.+ font_size: 1.0,+ render_mode: TextRenderingMode::default(),+ text_matrix: Affine::IDENTITY,+ text_line_matrix: Affine::IDENTITY,+ rise: 0.0,+ clip_paths: BezPath::default(),+ }+ }+}++#[derive(Clone, Debug)]+pub(crate) struct GraphicsState<'a> {+ // Stroke parameters.+ pub(crate) stroke_props: StrokeProps,++ // Stroke paint parameters.+ pub(crate) stroke_color: ColorComponents,+ pub(crate) stroke_pattern: Option<Pattern<'a>>,+ pub(crate) stroke_cs: ColorSpace,+ pub(crate) stroke_alpha: f32,++ // Non-stroke paint parameters.+ pub(crate) non_stroke_color: ColorComponents,+ pub(crate) non_stroke_pattern: Option<Pattern<'a>>,+ pub(crate) none_stroke_cs: ColorSpace,+ pub(crate) non_stroke_alpha: f32,++ pub(crate) soft_mask: Option<SoftMask<'a>>,+ pub(crate) transfer_function: Option<ActiveTransferFunction>,+ pub(crate) blend_mode: BlendMode,+}++impl Default for GraphicsState<'_> {+ fn default() -> Self {+ GraphicsState {+ stroke_props: StrokeProps::default(),+ non_stroke_alpha: 1.0,+ stroke_cs: ColorSpace::device_gray(),+ stroke_color: smallvec![0.0,],+ none_stroke_cs: ColorSpace::device_gray(),+ non_stroke_color: smallvec![0.0],+ stroke_alpha: 1.0,+ stroke_pattern: None,+ non_stroke_pattern: None,+ soft_mask: None,+ transfer_function: None,+ blend_mode: BlendMode::default(),+ }+ }+}++pub(crate) struct PaintData<'a> {+ pub(crate) alpha: f32,+ pub(crate) color: ColorComponents,+ pub(crate) color_space: ColorSpace,+ pub(crate) pattern: Option<Pattern<'a>>,+ pub(crate) transfer_function: Option<ActiveTransferFunction>,+}++pub(crate) fn handle_gs<'a>(+ dict: &Dict<'a>,+ context: &mut Context<'a>,+ parent_resources: &Resources<'a>,+) {+ for key in dict.keys() {+ handle_gs_single(dict, key.clone(), context, parent_resources).warn_none(&format!(+ "invalid value in graphics state for {}",+ key.as_str()+ ));+ }+}++pub(crate) fn handle_gs_single<'a>(+ dict: &Dict<'a>,+ key: Name<'_>,+ context: &mut Context<'a>,+ parent_resources: &Resources<'a>,+) -> Option<()> {+ // TODO Can we use constants here somehow?+ match key.as_str() {+ "LW" => context.get_mut().graphics_state.stroke_props.line_width = dict.get::<f32>(key)?,+ "LC" => {+ context.get_mut().graphics_state.stroke_props.line_cap =+ convert_line_cap(LineCap(dict.get::<Number>(key)?));+ }+ "LJ" => {+ context.get_mut().graphics_state.stroke_props.line_join =+ convert_line_join(LineJoin(dict.get::<Number>(key)?));+ }+ "ML" => context.get_mut().graphics_state.stroke_props.miter_limit = dict.get::<f32>(key)?,+ "CA" => context.get_mut().graphics_state.stroke_alpha = dict.get::<f32>(key)?,+ "ca" => context.get_mut().graphics_state.non_stroke_alpha = dict.get::<f32>(key)?,+ "TR" | "TR2" => {+ let function = match dict+ .get::<Object<'_>>(TR2)+ .or_else(|| dict.get::<Object<'_>>(TR))?+ {+ Object::Array(array) => {+ let mut iter = array.iter::<Object<'_>>();+ let functions = [+ Function::new(&iter.next()?)?,+ Function::new(&iter.next()?)?,+ Function::new(&iter.next()?)?,+ Function::new(&iter.next()?)?,+ ];++ Some(ActiveTransferFunction::Four(functions))+ }+ // Only `Identity` and `Default` are valid, which both just reset it.+ Object::Name(_) => None,+ o => Some(ActiveTransferFunction::Single(Function::new(&o)?)),+ };++ context.get_mut().graphics_state.transfer_function = function;+ }+ "SMask" => {+ if let Some(name) = dict.get::<Name<'_>>(SMASK) {+ if name.deref() == b"None" {+ context.get_mut().graphics_state.soft_mask = None;+ }+ } else {+ context.get_mut().graphics_state.soft_mask = dict+ .get::<Dict<'_>>(SMASK)+ .and_then(|d| SoftMask::new(&d, context, parent_resources.clone()));+ }+ }+ "BM" => {+ if let Some(name) = dict.get::<Name<'_>>(key.as_ref()) {+ if let Some(bm) = convert_blend_mode(name.as_str()) {+ context.get_mut().graphics_state.blend_mode = bm;++ return Some(());+ }+ } else if let Some(arr) = dict.get::<Array<'_>>(key) {+ for name in arr.iter::<Name<'_>>() {+ if let Some(bm) = convert_blend_mode(name.as_str()) {+ context.get_mut().graphics_state.blend_mode = bm;++ return Some(());+ }+ }+ }++ warn!("unknown blend mode, defaulting to Normal");+ context.get_mut().graphics_state.blend_mode = BlendMode::Normal;+ }+ "Font" => {+ let arr = dict.get::<Array<'_>>(FONT)?;+ let mut iter = arr.iter::<Object<'_>>();+ let font_dict = iter.next()?.into_dict()?;+ let size = iter.next()?.into_number()?.as_f32();++ let font = context.resolve_font(&font_dict);+ context.get_mut().text_state.font_size = size;+ context.get_mut().text_state.font = font;+ }+ "D" => {+ let arr = dict.get::<Array<'_>>(key)?;+ let mut iter = arr.iter::<Object<'_>>();+ let dash_array = iter.next()?.into_array()?;+ let dash_phase = iter.next()?.into_number()?.as_f32();++ context.get_mut().graphics_state.stroke_props.dash_offset = dash_phase;+ context.get_mut().graphics_state.stroke_props.dash_array = dash_array+ .iter::<f32>()+ // kurbo apparently cannot properly deal with offsets that are exactly 0.+ .map(|n| if n == 0.0 { 0.01 } else { n })+ .collect();+ }+ "Type" => {}+ _ => {}+ }++ Some(())+}++fn convert_blend_mode(name: &str) -> Option<BlendMode> {+ let bm = match name {+ "Normal" => BlendMode::Normal,+ "Multiply" => BlendMode::Multiply,+ "Screen" => BlendMode::Screen,+ "Overlay" => BlendMode::Overlay,+ "Darken" => BlendMode::Darken,+ "Lighten" => BlendMode::Lighten,+ "ColorDodge" => BlendMode::ColorDodge,+ "ColorBurn" => BlendMode::ColorBurn,+ "HardLight" => BlendMode::HardLight,+ "SoftLight" => BlendMode::SoftLight,+ "Difference" => BlendMode::Difference,+ "Exclusion" => BlendMode::Exclusion,+ "Hue" => BlendMode::Hue,+ "Saturation" => BlendMode::Saturation,+ "Color" => BlendMode::Color,+ "Luminosity" => BlendMode::Luminosity,+ _ => return None,+ };++ Some(bm)+}diff --git a/vendor/hayro-interpret/src/interpret/text.rs b/vendor/hayro-interpret/src/interpret/text.rsnew file mode 100644index 000000000..a631ba902--- /dev/null+++ b/vendor/hayro-interpret/src/interpret/text.rs@@ -0,0 +1,188 @@+use crate::GlyphDrawMode;+use crate::context::Context;+use crate::device::Device;+use crate::font::Glyph;+use crate::interpret::path::get_paint;+use crate::interpret::state::TextStateFont;+use hayro_syntax::object;+use hayro_syntax::page::Resources;+use kurbo::Affine;++pub(crate) fn show_text_string<'a>(+ ctx: &mut Context<'a>,+ device: &mut impl Device<'a>,+ resources: &Resources<'a>,+ text: &object::String<'_>,+) {+ let Some(font) = ctx.get().text_state.font.clone() else {+ warn!("tried to show text without active font");++ return;+ };++ let bytes = text.as_bytes();++ // In case we have a fallback font (which occurs if either no font was set at all+ // in the content stream, or an invalid one), we only want to show the glyphs+ // using Helvetica if the bytes are actually valid ASCII.+ let show_glyphs = matches!(font, TextStateFont::Font(_))+ || (matches!(font, TextStateFont::Fallback(_)) && bytes.is_ascii());++ let mut cur_idx = 0;++ while cur_idx < bytes.len() {+ let (code, adv) = font.read_code(bytes, cur_idx);+ cur_idx += adv;++ if show_glyphs {+ let (glyph, glyph_transform) = font.get_glyph(+ font.map_code(code),+ code,+ ctx,+ resources,+ font.origin_displacement(code),+ );+ show_glyph(ctx, device, &glyph, glyph_transform);+ }++ ctx.get_mut().text_state.apply_code_advance(code, adv);+ }+}++pub(crate) fn next_line(ctx: &mut Context<'_>, tx: f64, ty: f64) {+ let new_matrix = ctx.get_mut().text_state.text_line_matrix * Affine::translate((tx, ty));+ ctx.get_mut().text_state.text_line_matrix = new_matrix;+ ctx.get_mut().text_state.text_matrix = new_matrix;+}++pub(crate) fn show_glyph<'a>(+ ctx: &mut Context<'a>,+ device: &mut impl Device<'a>,+ glyph: &Glyph<'a>,+ glyph_transform: Affine,+) {+ if !ctx.ocg_state.is_visible() {+ return;+ }++ device.set_soft_mask(ctx.get().graphics_state.soft_mask.clone());+ device.set_blend_mode(ctx.get().graphics_state.blend_mode);+ let stroke_props = ctx.stroke_props();++ match ctx.get().text_state.render_mode {+ TextRenderingMode::Fill => {+ device.draw_glyph(+ glyph,+ ctx.get().ctm,+ glyph_transform,+ &get_paint(ctx, false),+ &GlyphDrawMode::Fill,+ );+ }+ TextRenderingMode::Stroke => {+ device.draw_glyph(+ glyph,+ ctx.get().ctm,+ glyph_transform,+ &get_paint(ctx, true),+ &GlyphDrawMode::Stroke(stroke_props),+ );+ }+ TextRenderingMode::FillStroke => {+ device.draw_glyph(+ glyph,+ ctx.get().ctm,+ glyph_transform,+ &get_paint(ctx, false),+ &GlyphDrawMode::Fill,+ );+ device.draw_glyph(+ glyph,+ ctx.get().ctm,+ glyph_transform,+ &get_paint(ctx, true),+ &GlyphDrawMode::Stroke(stroke_props),+ );+ }+ TextRenderingMode::Invisible => {+ // Still call draw_glyph for invisible text, so that it can+ // for example be used for text extraction.+ device.draw_glyph(+ glyph,+ ctx.get().ctm,+ glyph_transform,+ &get_paint(ctx, false),+ &GlyphDrawMode::Invisible,+ );+ }+ TextRenderingMode::Clip => {+ clip_glyph(ctx, glyph, glyph_transform);+ }+ TextRenderingMode::FillAndClip => {+ clip_glyph(ctx, glyph, glyph_transform);+ device.draw_glyph(+ glyph,+ ctx.get().ctm,+ glyph_transform,+ &get_paint(ctx, false),+ &GlyphDrawMode::Fill,+ );+ }+ TextRenderingMode::StrokeAndClip => {+ clip_glyph(ctx, glyph, glyph_transform);+ device.draw_glyph(+ glyph,+ ctx.get().ctm,+ glyph_transform,+ &get_paint(ctx, true),+ &GlyphDrawMode::Stroke(stroke_props),+ );+ }+ TextRenderingMode::FillAndStrokeAndClip => {+ clip_glyph(ctx, glyph, glyph_transform);+ device.draw_glyph(+ glyph,+ ctx.get().ctm,+ glyph_transform,+ &get_paint(ctx, false),+ &GlyphDrawMode::Fill,+ );+ device.draw_glyph(+ glyph,+ ctx.get().ctm,+ glyph_transform,+ &get_paint(ctx, true),+ &GlyphDrawMode::Stroke(stroke_props),+ );+ }+ }+}++pub(crate) fn clip_glyph(context: &mut Context<'_>, glyph: &Glyph<'_>, transform: Affine) {+ match glyph {+ Glyph::Outline(o) => {+ let outline = transform * o.outline();+ let has_outline = outline.segments().next().is_some();++ if has_outline {+ context.get_mut().text_state.clip_paths.extend(outline);+ }+ }+ Glyph::Type3(_) => {+ warn!("text rendering mode clip not implemented for shape glyphs");+ }+ }+}++#[derive(Debug, Clone, Copy, Default)]+pub(crate) enum TextRenderingMode {+ #[default]+ Fill,+ Stroke,+ FillStroke,+ Invisible,+ FillAndClip,+ StrokeAndClip,+ FillAndStrokeAndClip,+ Clip,+}diff --git a/vendor/hayro-interpret/src/lib.rs b/vendor/hayro-interpret/src/lib.rsnew file mode 100644index 000000000..b8ee48b8b--- /dev/null+++ b/vendor/hayro-interpret/src/lib.rs@@ -0,0 +1,61 @@+/*!+A crate for interpreting PDF files.++This crate provides an abstraction to interpret the content of a PDF file and render them+into an abstract [`Device`], which clients can implement as needed. This allows you, for+example, to render PDF files to bitmaps (which is what the `hayro` crate does), or other formats+such as SVG.++It should be noted that this crate is still very much in development. Therefore it currently+lacks pretty much any documentation on how to use it. It's current API also only really makes it+useful for rendering to PNG or SVG, though this will be improved upon in the future.++# Examples+See the `examples` folder on the GitHub repository. Apart from that, you can also consult+the implementation of `hayro` and `hayro-svg` to get an idea on how to use this crate.++# Safety+This crate forbids unsafe code via a crate-level attribute.++# Cargo features+This crate has one optional feature:+- `embed-fonts`: PDF processors are required to support 14 predefined fonts that do not need to be+ embedded into a PDF file. If you enable this feature, hayro will embed a (permissively-licensed)+ substitute for each font, so that you don't have to implement your custom font loading logic. This+ will add around ~240KB to your binary.+*/++#![forbid(unsafe_code)]+#![deny(missing_docs)]++#[macro_use]+mod log;++mod cache;+mod context;+mod convert;+mod device;+mod function;+mod interpret;+mod ocg;+mod soft_mask;+mod types;+mod x_object;++pub mod color;+pub mod encode;+pub mod font;+pub mod pattern;+pub mod shading;+pub mod util;++pub use cache::CacheKey;+pub use context::*;+pub use device::*;+pub use function::Function;+pub use hayro_cmap;+pub use hayro_syntax;+pub use interpret::*;+pub use soft_mask::*;+pub use types::*;+pub use util::{RectExt, TransformExt};diff --git a/vendor/hayro-interpret/src/log.rs b/vendor/hayro-interpret/src/log.rsnew file mode 100644index 000000000..fee9828c0--- /dev/null+++ b/vendor/hayro-interpret/src/log.rs@@ -0,0 +1,27 @@+//! Logging macros that optionally forward to the `log` crate.++macro_rules! error {+ ($fmt:literal $(, $($arg:expr),* $(,)?)?) => {{+ #[cfg(feature = "logging")]+ {+ ::log::error!($fmt $(, $($arg),*)?);+ }+ #[cfg(not(feature = "logging"))]+ {+ $($(let _ = &$arg;)*)?+ }+ }};+}++macro_rules! warn {+ ($fmt:literal $(, $($arg:expr),* $(,)?)?) => {{+ #[cfg(feature = "logging")]+ {+ ::log::warn!($fmt $(, $($arg),*)?);+ }+ #[cfg(not(feature = "logging"))]+ {+ $($(let _ = &$arg;)*)?+ }+ }};+}diff --git a/vendor/hayro-interpret/src/ocg.rs b/vendor/hayro-interpret/src/ocg.rsnew file mode 100644index 000000000..1d12b1f06--- /dev/null+++ b/vendor/hayro-interpret/src/ocg.rs@@ -0,0 +1,179 @@+use hayro_syntax::object::dict::keys::{BASE_STATE, D, OCGS, OCMD, OCPROPERTIES, OFF, ON, P, TYPE};+use hayro_syntax::object::{Array, Dict, Name, ObjectIdentifier};+use std::collections::HashSet;++pub(crate) struct OcgState {+ inactive_ocgs: HashSet<ObjectIdentifier>,+ visibility_stack: Vec<bool>,+}++impl OcgState {+ fn dummy() -> Self {+ Self {+ inactive_ocgs: HashSet::default(),+ visibility_stack: vec![],+ }+ }++ pub(crate) fn from_catalog(catalog: &Dict<'_>) -> Self {+ let Some(oc_properties) = catalog.get::<Dict<'_>>(OCPROPERTIES) else {+ return Self::dummy();+ };++ let Some(config) = oc_properties.get::<Dict<'_>>(D) else {+ return Self::dummy();+ };++ let mut inactive = HashSet::new();++ let base_state = config+ .get::<Name<'_>>(BASE_STATE)+ .and_then(|b| BaseState::from_name(b.as_ref()));++ if base_state.unwrap_or(BaseState::On) == BaseState::Off+ && let Some(ocgs) = oc_properties.get::<Array<'_>>(OCGS)+ {+ for item in ocgs.raw_iter() {+ if let Some(ref_) = item.as_obj_ref() {+ let id: ObjectIdentifier = ref_.into();+ inactive.insert(id);+ }+ }+ }++ let mut read_ocg_array = |key, insert_active: bool| {+ if let Some(arr) = config.get::<Array<'_>>(key) {+ for item in arr.raw_iter() {+ if let Some(ref_) = item.as_obj_ref() {+ let id: ObjectIdentifier = ref_.into();+ if insert_active {+ inactive.remove(&id);+ } else {+ inactive.insert(id);+ }+ }+ }+ }+ };++ read_ocg_array(ON, true);+ read_ocg_array(OFF, false);++ Self {+ inactive_ocgs: inactive,+ visibility_stack: Vec::new(),+ }+ }++ pub(crate) fn begin_single_oc(&mut self, ocg_id: ObjectIdentifier) {+ let is_active = !self.inactive_ocgs.contains(&ocg_id);+ let visible = self.is_visible() && is_active;+ self.visibility_stack.push(visible);+ }++ pub(crate) fn begin_ocmd(&mut self, ocmd: &Dict<'_>) {+ let policy = ocmd+ .get::<Name<'_>>(P)+ .and_then(|n| OcmdPolicy::from_name(n.as_ref()))+ .unwrap_or(OcmdPolicy::AnyOn);++ let mut ocg_ids: Vec<ObjectIdentifier> = Vec::new();++ if let Some(arr) = ocmd.get::<Array<'_>>(OCGS) {+ for item in arr.raw_iter() {+ if let Some(ref_) = item.as_obj_ref() {+ ocg_ids.push(ref_.into());+ }+ }+ } else if let Some(ref_) = ocmd.get_ref(OCGS) {+ ocg_ids.push(ref_.into());+ }++ let is_active = if ocg_ids.is_empty() {+ true+ } else {+ match policy {+ OcmdPolicy::AllOn => ocg_ids.iter().all(|id| !self.inactive_ocgs.contains(id)),+ OcmdPolicy::AnyOn => ocg_ids.iter().any(|id| !self.inactive_ocgs.contains(id)),+ OcmdPolicy::AnyOff => ocg_ids.iter().any(|id| self.inactive_ocgs.contains(id)),+ OcmdPolicy::AllOff => ocg_ids.iter().all(|id| self.inactive_ocgs.contains(id)),+ }+ };++ let visible = self.is_visible() && is_active;+ self.visibility_stack.push(visible);+ }++ pub(crate) fn begin_ocg(&mut self, props: &Dict<'_>, ref_id: ObjectIdentifier) {+ match props.get::<Name<'_>>(TYPE).as_deref() {+ Some(OCMD) => self.begin_ocmd(props),+ _ => self.begin_single_oc(ref_id),+ }+ }++ pub(crate) fn begin_marked_content(&mut self) {+ let visible = self.is_visible();+ self.visibility_stack.push(visible);+ }++ pub(crate) fn end_marked_content(&mut self) {+ self.visibility_stack.pop();+ }++ /// PrintCraft patch: override one group's state (viewer layer toggles).+ pub(crate) fn set_active(&mut self, id: ObjectIdentifier, active: bool) {+ if active {+ self.inactive_ocgs.remove(&id);+ } else {+ self.inactive_ocgs.insert(id);+ }+ }++ pub(crate) fn is_visible(&self) -> bool {+ self.visibility_stack.last().copied().unwrap_or(true)+ }+}++impl Default for OcgState {+ fn default() -> Self {+ Self::dummy()+ }+}++#[derive(Debug, PartialEq, Eq, Copy, Clone)]+enum BaseState {+ On,+ Off,+ Unchanged,+}++impl BaseState {+ fn from_name(name: &[u8]) -> Option<Self> {+ match name {+ b"ON" => Some(Self::On),+ b"OFF" => Some(Self::Off),+ b"Unchanged" => Some(Self::Unchanged),+ _ => None,+ }+ }+}++#[derive(Debug, PartialEq, Eq, Copy, Clone)]+enum OcmdPolicy {+ AllOn,+ AnyOn,+ AnyOff,+ AllOff,+}++impl OcmdPolicy {+ fn from_name(name: &[u8]) -> Option<Self> {+ match name {+ b"AllOn" => Some(Self::AllOn),+ b"AnyOn" => Some(Self::AnyOn),+ b"AnyOff" => Some(Self::AnyOff),+ b"AllOff" => Some(Self::AllOff),+ _ => None,+ }+ }+}diff --git a/vendor/hayro-interpret/src/pattern.rs b/vendor/hayro-interpret/src/pattern.rsnew file mode 100644index 000000000..dfb9d93f4--- /dev/null+++ b/vendor/hayro-interpret/src/pattern.rs@@ -0,0 +1,343 @@+//! PDF patterns.++use crate::cache::Cache;+use crate::color::{Color, ColorSpace};+use crate::context::{Context, InterpreterCache};+use crate::device::Device;+use crate::font::Glyph;+use crate::interpret::state::{ActiveTransferFunction, State};+use crate::shading::Shading;+use crate::soft_mask::SoftMask;+use crate::util::{Float32Ext, RectExt, hash128};+use crate::{BlendMode, CacheKey, ClipPath, GlyphDrawMode, Image, PathDrawMode};+use crate::{FillRule, InterpreterSettings, Paint, interpret};+use hayro_syntax::content::TypedIter;+use hayro_syntax::object::Dict;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::{+ BBOX, EXT_G_STATE, MATRIX, PAINT_TYPE, RESOURCES, SHADING, X_STEP, Y_STEP,+};+use hayro_syntax::object::{Object, dict_or_stream};+use hayro_syntax::page::Resources;+use hayro_syntax::xref::XRef;+use kurbo::{Affine, BezPath, Rect, Shape};+use std::fmt::{Debug, Formatter};+use std::sync::Arc;++/// A PDF pattern.+#[derive(Debug, Clone)]+pub enum Pattern<'a> {+ /// A shading pattern.+ Shading(ShadingPattern),+ /// A tiling pattern.+ Tiling(Box<TilingPattern<'a>>),+}++impl<'a> Pattern<'a> {+ pub(crate) fn new(+ object: Object<'a>,+ ctx: &Context<'a>,+ resources: &Resources<'a>,+ ) -> Option<Self> {+ match object {+ Object::Dict(dict) => Some(Self::Shading(ShadingPattern::new(+ &dict,+ &ctx.interpreter_cache.object_cache,+ ctx.get().graphics_state.non_stroke_alpha,+ )?)),+ Object::Stream(stream) => Some(Self::Tiling(Box::new(TilingPattern::new(+ stream, ctx, resources,+ )?))),+ _ => None,+ }+ }++ pub(crate) fn pre_concat_transform(&mut self, transform: Affine) {+ match self {+ Self::Shading(p) => {+ p.matrix = transform * p.matrix;+ let transformed_clip_path = p.shading.clip_path.clone().map(|r| p.matrix * r);+ Arc::make_mut(&mut p.shading).clip_path = transformed_clip_path;+ }+ Self::Tiling(p) => p.matrix = transform * p.matrix,+ }+ }++ pub(crate) fn set_transfer_function(&mut self, tf: ActiveTransferFunction) {+ if let Self::Shading(p) = self {+ p.transfer_function = Some(tf);+ }+ }+}++impl CacheKey for Pattern<'_> {+ fn cache_key(&self) -> u128 {+ match self {+ Self::Shading(p) => p.cache_key(),+ Self::Tiling(p) => p.cache_key(),+ }+ }+}++/// A shading pattern.+#[derive(Clone, Debug)]+pub struct ShadingPattern {+ /// The underlying shading of the pattern.+ pub shading: Arc<Shading>,+ /// A transformation matrix to apply prior to rendering.+ pub matrix: Affine,+ /// An additional opacity to apply to the shading pattern.+ pub opacity: f32,+ /// An optional transfer function to apply to the shading's output colors.+ pub transfer_function: Option<ActiveTransferFunction>,+}++impl ShadingPattern {+ pub(crate) fn new(dict: &Dict<'_>, cache: &Cache, opacity: f32) -> Option<Self> {+ let shading = dict.get::<Object<'_>>(SHADING).and_then(|o| {+ let (dict, stream) = dict_or_stream(&o)?;++ Shading::new(dict, stream, cache)+ })?;+ let matrix = dict+ .get::<[f64; 6]>(MATRIX)+ .map(Affine::new)+ .unwrap_or_default();++ if dict.contains_key(EXT_G_STATE) {+ warn!("shading patterns with ext_g_state are not supported yet");+ }++ Some(Self {+ shading: Arc::new(shading),+ opacity,+ matrix,+ transfer_function: None,+ })+ }+}++impl CacheKey for ShadingPattern {+ fn cache_key(&self) -> u128 {+ hash128(&(self.shading.cache_key(), self.matrix.cache_key()))+ }+}++/// A tiling pattern.+#[derive(Clone)]+pub struct TilingPattern<'a> {+ cache_key: u128,+ ctx_bbox: Rect,+ /// The bbox of the tiling pattern.+ pub bbox: Rect,+ /// The step in the x direction.+ pub x_step: f32,+ /// The step in the y direction.+ pub y_step: f32,+ /// A transformation to apply prior to rendering.+ pub matrix: Affine,+ stream: Stream<'a>,+ is_color: bool,+ pub(crate) stroke_paint: Color,+ pub(crate) non_stroking_paint: Color,+ pub(crate) parent_resources: Resources<'a>,+ pub(crate) cache: InterpreterCache<'a>,+ pub(crate) settings: InterpreterSettings,+ pub(crate) xref: &'a XRef,+ nesting_depth: u32,+}++impl Debug for TilingPattern<'_> {+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {+ f.write_str("TilingPattern")+ }+}++impl<'a> TilingPattern<'a> {+ pub(crate) fn new(+ stream: Stream<'a>,+ ctx: &Context<'a>,+ resources: &Resources<'a>,+ ) -> Option<Self> {+ let cache_key = stream.cache_key();+ let dict = stream.dict();++ let bbox = dict.get::<hayro_syntax::object::Rect>(BBOX)?.to_kurbo();+ let x_step = dict.get::<f32>(X_STEP)?;+ let y_step = dict.get::<f32>(Y_STEP)?;++ if x_step.is_nearly_zero() || y_step.is_nearly_zero() || bbox.is_zero_area() {+ return None;+ }++ let is_color = dict.get::<u8>(PAINT_TYPE)? == 1;+ let matrix = dict+ .get::<[f64; 6]>(MATRIX)+ .map(Affine::new)+ .unwrap_or_default();++ let state = ctx.get().clone();+ let ctx_bbox = ctx.bbox();++ let fill_cs = state+ .graphics_state+ .none_stroke_cs+ .pattern_cs()+ .unwrap_or(ColorSpace::device_gray());+ let stroke_cs = state+ .graphics_state+ .stroke_cs+ .pattern_cs()+ .unwrap_or(ColorSpace::device_gray());++ let non_stroking_paint = Color::new(+ fill_cs,+ state.graphics_state.non_stroke_color.clone(),+ state.graphics_state.non_stroke_alpha,+ );+ let stroke_paint = Color::new(+ stroke_cs,+ state.graphics_state.stroke_color.clone(),+ state.graphics_state.stroke_alpha,+ );+ let nesting_depth = ctx.nesting_depth() + 1;++ Some(Self {+ cache_key,+ bbox,+ x_step,+ y_step,+ matrix,+ ctx_bbox,+ is_color,+ stream,+ stroke_paint,+ non_stroking_paint,+ settings: ctx.settings.clone(),+ parent_resources: resources.clone(),+ cache: ctx.interpreter_cache.clone(),+ xref: ctx.xref,+ nesting_depth,+ })+ }++ /// Interpret the contents of the pattern into the given device.+ pub fn interpret(+ &self,+ device: &mut impl Device<'a>,+ initial_transform: Affine,+ is_stroke: bool,+ ) -> Option<()> {+ let state = State::new(initial_transform);++ let mut context = Context::new_with(+ state.ctm,+ // TODO: bbox?+ (initial_transform * self.ctx_bbox.to_path(0.1)).bounding_box(),+ &self.cache,+ self.xref,+ self.settings.clone(),+ state,+ self.nesting_depth,+ );++ let decoded = self.stream.decoded().ok()?;+ let resources = Resources::from_parent(+ self.stream.dict().get(RESOURCES).unwrap_or_default(),+ self.parent_resources.clone(),+ );+ let iter = TypedIter::new(decoded.as_ref());++ let clip_path = ClipPath {+ path: initial_transform * self.bbox.to_path(0.1),+ fill: FillRule::NonZero,+ };+ device.push_clip_path(&clip_path);++ if self.is_color {+ interpret(iter, &resources, &mut context, device);+ } else {+ let paint = if !is_stroke {+ Paint::Color(self.non_stroking_paint.clone())+ } else {+ Paint::Color(self.stroke_paint.clone())+ };++ let mut device = StencilPatternDevice::new(device, paint.clone());+ interpret(iter, &resources, &mut context, &mut device);+ }++ device.pop_clip_path();++ Some(())+ }+}++impl CacheKey for TilingPattern<'_> {+ fn cache_key(&self) -> u128 {+ self.cache_key+ }+}++struct StencilPatternDevice<'a, 'b, T: Device<'a>> {+ inner: &'b mut T,+ paint: Paint<'a>,+}++impl<'a, 'b, T: Device<'a>> StencilPatternDevice<'a, 'b, T> {+ pub(crate) fn new(device: &'b mut T, paint: Paint<'a>) -> Self {+ Self {+ inner: device,+ paint,+ }+ }+}++// Only filling, stroking of paths and stencil masks are allowed.+impl<'a, T: Device<'a>> Device<'a> for StencilPatternDevice<'a, '_, T> {+ fn draw_path(+ &mut self,+ path: &BezPath,+ transform: Affine,+ _: &Paint<'_>,+ draw_mode: &PathDrawMode,+ ) {+ self.inner+ .draw_path(path, transform, &self.paint, draw_mode);+ }++ fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}++ fn push_clip_path(&mut self, clip_path: &ClipPath) {+ self.inner.push_clip_path(clip_path);+ }++ fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}++ fn draw_glyph(+ &mut self,+ g: &Glyph<'a>,+ transform: Affine,+ glyph_transform: Affine,+ p: &Paint<'a>,+ draw_mode: &GlyphDrawMode,+ ) {+ self.inner+ .draw_glyph(g, transform, glyph_transform, p, draw_mode);+ }++ fn draw_image(&mut self, image: Image<'a, '_>, transform: Affine) {+ if let Image::Stencil(mut s) = image {+ s.paint = self.paint.clone();+ self.inner.draw_image(Image::Stencil(s), transform);+ }+ }++ fn pop_clip_path(&mut self) {+ self.inner.pop_clip_path();+ }++ fn pop_transparency_group(&mut self) {}++ fn set_blend_mode(&mut self, _: BlendMode) {}+}diff --git a/vendor/hayro-interpret/src/shading.rs b/vendor/hayro-interpret/src/shading.rsnew file mode 100644index 000000000..1e29c5e94--- /dev/null+++ b/vendor/hayro-interpret/src/shading.rs@@ -0,0 +1,1032 @@+//! PDF shadings.++#![allow(clippy::needless_range_loop)]++use crate::CacheKey;+use crate::cache::Cache;+use crate::color::{ColorComponents, ColorSpace};+use crate::function::{Function, Values, interpolate};+use crate::util::{Float32Ext, PointExt, RectExt};+use hayro_syntax::bit_reader::BitReader;+use hayro_syntax::object::Array;+use hayro_syntax::object::Dict;+use hayro_syntax::object::Object;+use hayro_syntax::object::Rect;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::{+ BACKGROUND, BBOX, BITS_PER_COMPONENT, BITS_PER_COORDINATE, BITS_PER_FLAG, COLORSPACE, COORDS,+ DECODE, DOMAIN, EXTEND, FUNCTION, MATRIX, SHADING_TYPE, VERTICES_PER_ROW,+};+use kurbo::{Affine, BezPath, CubicBez, ParamCurve, Point, Shape};+use smallvec::{SmallVec, smallvec};+use std::sync::Arc;++/// The function supplied to a shading.+#[derive(Debug, Clone)]+pub enum ShadingFunction {+ /// A single function, which should be used to evaluate all components of the shading.+ Single(Function),+ /// Multiple functions, one for each color component.+ Multiple(SmallVec<[Function; 4]>),+}++impl ShadingFunction {+ /// Evaluate the shading function.+ pub fn eval(&self, input: &Values) -> Option<Values> {+ match self {+ Self::Single(s) => s.eval(input.clone()),+ Self::Multiple(m) => {+ // 1-in, 1-out function for each color component.++ let mut out = smallvec![];++ for func in m {+ out.push(*func.eval(input.clone())?.first()?);+ }++ Some(out)+ }+ }+ }+}++/// A type of shading.+#[derive(Debug)]+pub enum ShadingType {+ /// A function-based shading.+ FunctionBased {+ /// The domain of the function.+ domain: [f32; 4],+ /// A transform to apply to the shading.+ matrix: Affine,+ /// The function that should be used to evaluate the shading.+ function: ShadingFunction,+ },+ /// A radial-axial shading.+ RadialAxial {+ /// The coordinates of the shading.+ ///+ /// For axial shadings, only the first 4 entries are relevant, representing the x/y coordinates+ /// of the first point and the coordinates for the second point.+ ///+ /// For radial shadings, the coordinates contain the x/y coordinates as well as the radius+ /// for both circles.+ coords: [f32; 6],+ /// The domain of the shading.+ domain: [f32; 2],+ /// The function forming the basis of the shading.+ function: ShadingFunction,+ /// The extends in the left/right direction of the shading.+ extend: [bool; 2],+ /// Whether the shading is axial or radial.+ axial: bool,+ },+ /// A triangle-mesh shading.+ TriangleMesh {+ /// The triangles making up the shading.+ triangles: Vec<Triangle>,+ /// An optional function used for calculating the sampled color values.+ function: Option<ShadingFunction>,+ },+ /// A coons-patch-mesh shading.+ CoonsPatchMesh {+ /// The patches that make up the shading.+ patches: Vec<CoonsPatch>,+ /// An optional function used for calculating the sampled color values.+ function: Option<ShadingFunction>,+ },+ /// A tensor-product-patch-mesh shading.+ TensorProductPatchMesh {+ /// The patches that make up the shading.+ patches: Vec<TensorProductPatch>,+ /// An optional function used for calculating the sampled color values.+ function: Option<ShadingFunction>,+ },+ /// A dummy shading that should just be drawn transparent.+ Dummy,+}++/// A PDF shading.+#[derive(Clone, Debug)]+pub struct Shading {+ cache_key: u128,+ /// The type of shading.+ pub shading_type: Arc<ShadingType>,+ /// The color space of the shading.+ pub color_space: ColorSpace,+ /// A clip path that should be applied to the shading.+ pub clip_path: Option<BezPath>,+ /// The background color of the shading.+ pub background: Option<SmallVec<[f32; 4]>>,+}++impl Shading {+ pub(crate) fn new(dict: &Dict<'_>, stream: Option<&Stream<'_>>, cache: &Cache) -> Option<Self> {+ let cache_key = dict.cache_key();++ let shading_num = dict.get::<u8>(SHADING_TYPE)?;++ let color_space = ColorSpace::new(dict.get(COLORSPACE)?, cache)?;++ let shading_type = match shading_num {+ 1 => {+ let domain = dict.get::<[f32; 4]>(DOMAIN).unwrap_or([0.0, 1.0, 0.0, 1.0]);+ let matrix = dict+ .get::<[f64; 6]>(MATRIX)+ .map(Affine::new)+ .unwrap_or_default();+ let function = read_function(dict, &color_space)?;++ ShadingType::FunctionBased {+ domain,+ matrix,+ function,+ }+ }+ 2 | 3 => {+ let domain = dict.get::<[f32; 2]>(DOMAIN).unwrap_or([0.0, 1.0]);+ let function = read_function(dict, &color_space)?;+ let extend = dict.get::<[bool; 2]>(EXTEND).unwrap_or([false, false]);+ let (coords, invalid) = if shading_num == 2 {+ let read = dict.get::<[f32; 4]>(COORDS)?;+ let invalid = (read[0] - read[2]).is_nearly_zero()+ && (read[1] - read[3]).is_nearly_zero();+ ([read[0], read[1], read[2], read[3], 0.0, 0.0], invalid)+ } else {+ let read = dict.get::<[f32; 6]>(COORDS)?;+ let invalid = (read[0] - read[3]).is_nearly_zero()+ && (read[1] - read[4]).is_nearly_zero()+ && (read[2] - read[5]).is_nearly_zero();+ (read, invalid)+ };++ let axial = shading_num == 2;++ if invalid {+ ShadingType::Dummy+ } else {+ ShadingType::RadialAxial {+ domain,+ function,+ extend,+ coords,+ axial,+ }+ }+ }+ 4 => {+ let stream = stream?;+ let stream_data = stream.decoded().ok()?;+ let bp_coord = dict.get::<u8>(BITS_PER_COORDINATE)?;+ let bp_comp = dict.get::<u8>(BITS_PER_COMPONENT)?;+ let bpf = dict.get::<u8>(BITS_PER_FLAG)?;+ let function = read_function(dict, &color_space);+ let decode = dict+ .get::<Array<'_>>(DECODE)?+ .iter::<f32>()+ .collect::<Vec<_>>();++ let triangles = read_free_form_triangles(+ stream_data.as_ref(),+ bpf,+ bp_coord,+ bp_comp,+ function.is_some(),+ &decode,+ )?;++ ShadingType::TriangleMesh {+ triangles,+ function,+ }+ }+ 5 => {+ let stream = stream?;+ let stream_data = stream.decoded().ok()?;+ let bp_coord = dict.get::<u8>(BITS_PER_COORDINATE)?;+ let bp_comp = dict.get::<u8>(BITS_PER_COMPONENT)?;+ let function = read_function(dict, &color_space);+ let decode = dict+ .get::<Array<'_>>(DECODE)?+ .iter::<f32>()+ .collect::<Vec<_>>();+ let vertices_per_row = dict.get::<u32>(VERTICES_PER_ROW)?;++ let triangles = read_lattice_triangles(+ stream_data.as_ref(),+ bp_coord,+ bp_comp,+ function.is_some(),+ vertices_per_row,+ &decode,+ )?;++ ShadingType::TriangleMesh {+ triangles,+ function,+ }+ }+ 6 => {+ let stream = stream?;+ let stream_data = stream.decoded().ok()?;+ let bp_coord = dict.get::<u8>(BITS_PER_COORDINATE)?;+ let bp_comp = dict.get::<u8>(BITS_PER_COMPONENT)?;+ let bpf = dict.get::<u8>(BITS_PER_FLAG)?;+ let function = read_function(dict, &color_space);+ let decode = dict+ .get::<Array<'_>>(DECODE)?+ .iter::<f32>()+ .collect::<Vec<_>>();++ let patches = read_coons_patch_mesh(+ stream_data.as_ref(),+ bpf,+ bp_coord,+ bp_comp,+ function.is_some(),+ &decode,+ )?;++ ShadingType::CoonsPatchMesh { patches, function }+ }+ 7 => {+ let stream = stream?;+ let stream_data = stream.decoded().ok()?;+ let bp_coord = dict.get::<u8>(BITS_PER_COORDINATE)?;+ let bp_comp = dict.get::<u8>(BITS_PER_COMPONENT)?;+ let bpf = dict.get::<u8>(BITS_PER_FLAG)?;+ let function = read_function(dict, &color_space);+ let decode = dict+ .get::<Array<'_>>(DECODE)?+ .iter::<f32>()+ .collect::<Vec<_>>();++ let patches = read_tensor_product_patch_mesh(+ stream_data.as_ref(),+ bpf,+ bp_coord,+ bp_comp,+ function.is_some(),+ &decode,+ )?;++ ShadingType::TensorProductPatchMesh { patches, function }+ }+ _ => return None,+ };++ let bbox = dict.get::<Rect>(BBOX).map(|r| r.to_kurbo());+ let background = dict+ .get::<Array<'_>>(BACKGROUND)+ .map(|a| a.iter::<f32>().collect::<SmallVec<_>>());++ Some(Self {+ cache_key,+ shading_type: Arc::new(shading_type),+ color_space,+ clip_path: bbox.map(|r| r.to_path(0.1)),+ background,+ })+ }+}++impl CacheKey for Shading {+ fn cache_key(&self) -> u128 {+ self.cache_key+ }+}++/// A triangle made up of three vertices.+#[derive(Clone, Debug)]+pub struct Triangle {+ /// The first vertex.+ pub p0: TriangleVertex,+ /// The second vertex.+ pub p1: TriangleVertex,+ /// The third vertex.+ pub p2: TriangleVertex,+ kurbo_tri: kurbo::Triangle,+ d00: f64,+ d01: f64,+ d11: f64,+}++impl Triangle {+ /// Create a new triangle.+ pub fn new(p0: TriangleVertex, p1: TriangleVertex, p2: TriangleVertex) -> Self {+ let v0 = p1.point - p0.point;+ let v1 = p2.point - p0.point;++ let d00 = v0.dot(v0);+ let d01 = v0.dot(v1);+ let d11 = v1.dot(v1);++ let kurbo_tri = kurbo::Triangle::new(p0.point, p1.point, p2.point);++ Self {+ p0,+ p1,+ kurbo_tri,+ p2,+ d00,+ d01,+ d11,+ }+ }++ /// Get the interpolated colors of the point from the triangle.+ ///+ /// Returns `None` if the point is not inside of the triangle.+ pub fn interpolate(&self, pos: Point) -> ColorComponents {+ let (u, v, w) = self.barycentric_coords(pos);++ let mut result = smallvec![];++ for i in 0..self.p0.colors.len() {+ let c0 = self.p0.colors[i];+ let c1 = self.p1.colors[i];+ let c2 = self.p2.colors[i];+ result.push(u * c0 + v * c1 + w * c2);+ }++ result+ }++ /// Return whether the point is contained within the triangle.+ pub fn contains_point(&self, pos: Point) -> bool {+ self.kurbo_tri.winding(pos) != 0+ }++ /// Return the bounding box of the triangle.+ pub fn bounding_box(&self) -> kurbo::Rect {+ self.kurbo_tri.bounding_box()+ }++ fn barycentric_coords(&self, p: Point) -> (f32, f32, f32) {+ let (a, b, c) = (self.p0.point, self.p1.point, self.p2.point);+ let v0 = b - a;+ let v1 = c - a;+ let v2 = p - a;++ let d00 = self.d00;+ let d01 = self.d01;+ let d11 = self.d11;+ let d20 = v2.dot(v0);+ let d21 = v2.dot(v1);++ let denom = d00 * d11 - d01 * d01;+ let v = (d11 * d20 - d01 * d21) / denom;+ let w = (d00 * d21 - d01 * d20) / denom;+ let u = (1.0 - v - w) as f32;++ (u, v as f32, w as f32)+ }+}++/// A triangle vertex.+#[derive(Clone, Debug)]+pub struct TriangleVertex {+ flag: u32,+ /// The position of the vertex.+ pub point: Point,+ /// The color component of the vertex.+ pub colors: ColorComponents,+}++/// A coons patch.+#[derive(Clone, Debug)]+pub struct CoonsPatch {+ /// The control points of the coons patch.+ pub control_points: [Point; 12],+ /// The colors at each corner of the coons patch.+ pub colors: [ColorComponents; 4],+}++/// A tensor-product patch.+#[derive(Clone, Debug)]+pub struct TensorProductPatch {+ /// The control points of the tensor-product patch (4x4 grid = 16 points).+ pub control_points: [Point; 16],+ /// The colors at each corner of the tensor-product patch.+ pub colors: [ColorComponents; 4],+}++impl CoonsPatch {+ /// Map the point to the coordinates of the coons patch.+ pub fn map_coordinate(&self, p: Point) -> Point {+ let (u, v) = (p.x, p.y);++ let cp = &self.control_points;++ let c1 = CubicBez::new(cp[0], cp[11], cp[10], cp[9]);+ let c2 = CubicBez::new(cp[3], cp[4], cp[5], cp[6]);+ let d1 = CubicBez::new(cp[0], cp[1], cp[2], cp[3]);+ let d2 = CubicBez::new(cp[9], cp[8], cp[7], cp[6]);++ let sc = (1.0 - v) * c1.eval(u).to_vec2() + v * c2.eval(u).to_vec2();+ let sd = (1.0 - u) * d1.eval(v).to_vec2() + u * d2.eval(v).to_vec2();+ let sb = (1.0 - v) * ((1.0 - u) * c1.eval(0.0).to_vec2() + u * c1.eval(1.0).to_vec2())+ + v * ((1.0 - u) * c2.eval(0.0).to_vec2() + u * c2.eval(1.0).to_vec2());++ (sc + sd - sb).to_point()+ }++ /// Approximate the patch by triangles.+ pub fn to_triangles(&self, buffer: &mut Vec<Triangle>) {+ generate_patch_triangles(|p| self.map_coordinate(p), |p| self.interpolate(p), buffer);+ }++ /// Get the interpolated colors of the point from the patch.+ pub fn interpolate(&self, pos: Point) -> ColorComponents {+ let (u, v) = (pos.x, pos.y);+ let (c0, c1, c2, c3) = {+ (+ &self.colors[0],+ &self.colors[1],+ &self.colors[2],+ &self.colors[3],+ )+ };++ let mut result = SmallVec::new();+ for i in 0..c0.len() {+ let val = (1.0 - u) * (1.0 - v) * c0[i] as f64+ + u * (1.0 - v) * c3[i] as f64+ + u * v * c2[i] as f64+ + (1.0 - u) * v * c1[i] as f64;+ result.push(val as f32);+ }++ result+ }+}++impl TensorProductPatch {+ /// Evaluate Bernstein polynomial `B_i(t)` for tensor-product patches.+ fn bernstein(i: usize, t: f64) -> f64 {+ match i {+ 0 => (1.0 - t).powi(3),+ 1 => 3.0 * t * (1.0 - t).powi(2),+ 2 => 3.0 * t.powi(2) * (1.0 - t),+ 3 => t.powi(3),+ _ => 0.0,+ }+ }++ /// Map the point to the coordinates of the tensor product patch.+ pub fn map_coordinate(&self, p: Point) -> Point {+ let (u, v) = (p.x, p.y);++ let mut x = 0.0;+ let mut y = 0.0;++ fn idx(i: usize, j: usize) -> usize {+ match (i, j) {+ (0, 0) => 0,+ (0, 1) => 1,+ (0, 2) => 2,+ (0, 3) => 3,+ (1, 0) => 11,+ (1, 1) => 12,+ (1, 2) => 13,+ (1, 3) => 4,+ (2, 0) => 10,+ (2, 1) => 15,+ (2, 2) => 14,+ (2, 3) => 5,+ (3, 0) => 9,+ (3, 1) => 8,+ (3, 2) => 7,+ (3, 3) => 6,+ _ => panic!("Invalid index"),+ }+ }++ for i in 0..4 {+ for j in 0..4 {+ let control_point_idx = idx(i, j);+ let basis = Self::bernstein(i, u) * Self::bernstein(j, v);++ x += self.control_points[control_point_idx].x * basis;+ y += self.control_points[control_point_idx].y * basis;+ }+ }++ Point::new(x, y)+ }++ /// Approximate the tensor product patch mesh by triangles.+ pub fn to_triangles(&self, buffer: &mut Vec<Triangle>) {+ generate_patch_triangles(|p| self.map_coordinate(p), |p| self.interpolate(p), buffer);+ }++ /// Get the interpolated colors of the point from the patch.+ pub fn interpolate(&self, pos: Point) -> ColorComponents {+ let (u, v) = (pos.x, pos.y);+ let (c0, c1, c2, c3) = {+ (+ &self.colors[0],+ &self.colors[1],+ &self.colors[2],+ &self.colors[3],+ )+ };++ let mut result = SmallVec::new();+ for i in 0..c0.len() {+ let val = (1.0 - u) * (1.0 - v) * c0[i] as f64+ + u * (1.0 - v) * c3[i] as f64+ + u * v * c2[i] as f64+ + (1.0 - u) * v * c1[i] as f64;+ result.push(val as f32);+ }++ result+ }+}++fn read_free_form_triangles(+ data: &[u8],+ bpf: u8,+ bp_cord: u8,+ bp_comp: u8,+ has_function: bool,+ decode: &[f32],+) -> Option<Vec<Triangle>> {+ let mut triangles = vec![];++ let ([x_min, x_max, y_min, y_max], decode) = split_decode(decode)?;+ let mut reader = BitReader::new(data);+ let helpers = InterpolationHelpers::new(bp_cord, bp_comp, x_min, x_max, y_min, y_max);++ let read_single = |reader: &mut BitReader<'_>| -> Option<TriangleVertex> {+ helpers.read_triangle_vertex(reader, bpf, has_function, decode)+ };++ let mut a = None;+ let mut b = None;+ let mut c = None;++ loop {+ let Some(first) = read_single(&mut reader) else {+ break;+ };++ if first.flag == 0 {+ let second = read_single(&mut reader)?;+ let third = read_single(&mut reader)?;++ a = Some(first.clone());+ b = Some(second.clone());+ c = Some(third.clone());+ } else if first.flag == 1 {+ a = Some(b.clone()?);+ b = Some(c.clone()?);+ c = Some(first);+ } else if first.flag == 2 {+ b = Some(c.clone()?);+ c = Some(first);+ }++ let (p0, p1, p2) = (a.clone()?, b.clone()?, c.clone()?);++ if p0.point.nearly_same(p1.point) || p1.point.nearly_same(p2.point) {+ continue;+ }++ triangles.push(Triangle::new(a.clone()?, b.clone()?, c.clone()?));+ }++ Some(triangles)+}++/// Common interpolation functions used across different shading types.+struct InterpolationHelpers {+ bp_coord: u8,+ bp_comp: u8,+ coord_max: f32,+ comp_max: f32,+ x_min: f32,+ x_max: f32,+ y_min: f32,+ y_max: f32,+}++impl InterpolationHelpers {+ fn new(bp_coord: u8, bp_comp: u8, x_min: f32, x_max: f32, y_min: f32, y_max: f32) -> Self {+ let coord_max = 2.0_f32.powi(bp_coord as i32) - 1.0;+ let comp_max = 2.0_f32.powi(bp_comp as i32) - 1.0;+ Self {+ bp_coord,+ bp_comp,+ coord_max,+ comp_max,+ x_min,+ x_max,+ y_min,+ y_max,+ }+ }++ fn interpolate_coord(&self, n: u32, d_min: f32, d_max: f32) -> f32 {+ interpolate(n as f32, 0.0, self.coord_max, d_min, d_max)+ }++ fn interpolate_comp(&self, n: u32, d_min: f32, d_max: f32) -> f32 {+ interpolate(n as f32, 0.0, self.comp_max, d_min, d_max)+ }++ fn read_point(&self, reader: &mut BitReader<'_>) -> Option<Point> {+ let x = self.interpolate_coord(reader.read(self.bp_coord)?, self.x_min, self.x_max);+ let y = self.interpolate_coord(reader.read(self.bp_coord)?, self.y_min, self.y_max);+ Some(Point::new(x as f64, y as f64))+ }++ fn read_colors(+ &self,+ reader: &mut BitReader<'_>,+ has_function: bool,+ decode: &[f32],+ ) -> Option<ColorComponents> {+ let mut colors = smallvec![];+ if has_function {+ colors.push(self.interpolate_comp(+ reader.read(self.bp_comp)?,+ *decode.first()?,+ *decode.get(1)?,+ ));+ } else {+ let num_components = decode.len() / 2;+ for (_, decode) in (0..num_components).zip(decode.chunks_exact(2)) {+ colors.push(self.interpolate_comp(+ reader.read(self.bp_comp)?,+ decode[0],+ decode[1],+ ));+ }+ }+ Some(colors)+ }++ fn read_triangle_vertex(+ &self,+ reader: &mut BitReader<'_>,+ bpf: u8,+ has_function: bool,+ decode: &[f32],+ ) -> Option<TriangleVertex> {+ let flag = reader.read(bpf)?;+ let point = self.read_point(reader)?;+ let colors = self.read_colors(reader, has_function, decode)?;+ reader.align();++ Some(TriangleVertex {+ flag,+ point,+ colors,+ })+ }+}++/// Split decode array into coordinate bounds and component decode values.+fn split_decode(decode: &[f32]) -> Option<([f32; 4], &[f32])> {+ decode.split_first_chunk::<4>().map(|(a, b)| (*a, b))+}++/// Generate triangles from a grid of points using a mapping function.+fn generate_patch_triangles<F, I>(map_coordinate: F, interpolate: I, buffer: &mut Vec<Triangle>)+where+ F: Fn(Point) -> Point,+ I: Fn(Point) -> ColorComponents,+{+ const GRID_SIZE: usize = 20;+ let mut grid = vec![vec![Point::ZERO; GRID_SIZE]; GRID_SIZE];++ // Create grid by mapping unit square coordinates.+ for i in 0..GRID_SIZE {+ for j in 0..GRID_SIZE {+ let u = i as f64 / (GRID_SIZE - 1) as f64; // 0.0 to 1.0 (left to right).+ let v = j as f64 / (GRID_SIZE - 1) as f64; // 0.0 to 1.0 (top to bottom).++ // Map unit square coordinate to patch coordinate.+ let unit_point = Point::new(u, v);+ grid[i][j] = map_coordinate(unit_point);+ }+ }++ for i in 0..(GRID_SIZE - 1) {+ for j in 0..(GRID_SIZE - 1) {+ let p00 = grid[i][j];+ let p10 = grid[i + 1][j];+ let p01 = grid[i][j + 1];+ let p11 = grid[i + 1][j + 1];++ // Calculate unit square coordinates for color interpolation.+ let u0 = i as f64 / (GRID_SIZE - 1) as f64;+ let u1 = (i + 1) as f64 / (GRID_SIZE - 1) as f64;+ let v0 = j as f64 / (GRID_SIZE - 1) as f64;+ let v1 = (j + 1) as f64 / (GRID_SIZE - 1) as f64;++ // Create triangle vertices with interpolated colors.+ let v00 = TriangleVertex {+ flag: 0,+ point: p00,+ colors: interpolate(Point::new(u0, v0)),+ };+ let v10 = TriangleVertex {+ flag: 0,+ point: p10,+ colors: interpolate(Point::new(u1, v0)),+ };+ let v01 = TriangleVertex {+ flag: 0,+ point: p01,+ colors: interpolate(Point::new(u0, v1)),+ };+ let v11 = TriangleVertex {+ flag: 0,+ point: p11,+ colors: interpolate(Point::new(u1, v1)),+ };++ let inflate_point = |p: Point, mid: Point| -> Point {+ const INFLATION_FACTOR: f64 = 1.025;+ mid + (p - mid) * INFLATION_FACTOR+ };++ // Converting to triangles is lossy and can lead to gaps. To make this a bit better,+ // we slightly inflate the triangles.+ let inflate = |mut triangle: Triangle| {+ let mid = triangle.kurbo_tri.centroid();+ triangle.p0.point = inflate_point(triangle.p0.point, mid);+ triangle.p1.point = inflate_point(triangle.p1.point, mid);+ triangle.p2.point = inflate_point(triangle.p2.point, mid);++ triangle+ };++ buffer.push(inflate(Triangle::new(+ v00.clone(),+ v10.clone(),+ v01.clone(),+ )));+ buffer.push(inflate(Triangle::new(+ v10.clone(),+ v11.clone(),+ v01.clone(),+ )));+ }+ }+}++fn read_lattice_triangles(+ data: &[u8],+ bp_cord: u8,+ bp_comp: u8,+ has_function: bool,+ vertices_per_row: u32,+ decode: &[f32],+) -> Option<Vec<Triangle>> {+ let mut lattices = vec![];++ let ([x_min, x_max, y_min, y_max], decode) = split_decode(decode)?;+ let mut reader = BitReader::new(data);+ let helpers = InterpolationHelpers::new(bp_cord, bp_comp, x_min, x_max, y_min, y_max);++ let read_single = |reader: &mut BitReader<'_>| -> Option<TriangleVertex> {+ let point = helpers.read_point(reader)?;+ let colors = helpers.read_colors(reader, has_function, decode)?;+ reader.align();++ Some(TriangleVertex {+ flag: 0,+ point,+ colors,+ })+ };++ 'outer: loop {+ let mut single_row = vec![];++ for _ in 0..vertices_per_row {+ let Some(next) = read_single(&mut reader) else {+ break 'outer;+ };++ single_row.push(next);+ }++ lattices.push(single_row);+ }++ let mut triangles = vec![];++ for i in 0..lattices.len().saturating_sub(1) {+ for j in 0..(vertices_per_row as usize).saturating_sub(1) {+ triangles.push(Triangle::new(+ lattices[i][j].clone(),+ lattices[i + 1][j].clone(),+ lattices[i][j + 1].clone(),+ ));++ triangles.push(Triangle::new(+ lattices[i + 1][j + 1].clone(),+ lattices[i + 1][j].clone(),+ lattices[i][j + 1].clone(),+ ));+ }+ }++ Some(triangles)+}++fn read_coons_patch_mesh(+ data: &[u8],+ bpf: u8,+ bp_coord: u8,+ bp_comp: u8,+ has_function: bool,+ decode: &[f32],+) -> Option<Vec<CoonsPatch>> {+ read_patch_mesh(+ data,+ bpf,+ bp_coord,+ bp_comp,+ has_function,+ decode,+ 12,+ |control_points, colors| {+ let mut coons_points = [Point::ZERO; 12];+ coons_points.copy_from_slice(&control_points[0..12]);+ CoonsPatch {+ control_points: coons_points,+ colors,+ }+ },+ )+}++/// Generic patch mesh reading function that works for both Coons and Tensor Product patches.+#[allow(clippy::too_many_arguments)]+fn read_patch_mesh<P, F>(+ data: &[u8],+ bpf: u8,+ bp_coord: u8,+ bp_comp: u8,+ has_function: bool,+ decode: &[f32],+ control_points_count: usize,+ create_patch: F,+) -> Option<Vec<P>>+where+ F: Fn([Point; 16], [ColorComponents; 4]) -> P,+{+ let ([x_min, x_max, y_min, y_max], decode) = split_decode(decode)?;+ let mut reader = BitReader::new(data);+ let helpers = InterpolationHelpers::new(bp_coord, bp_comp, x_min, x_max, y_min, y_max);++ let read_colors = |reader: &mut BitReader<'_>| -> Option<ColorComponents> {+ helpers.read_colors(reader, has_function, decode)+ };++ let mut prev_patch_points: Option<Vec<Point>> = None;+ let mut prev_patch_colors: Option<[ColorComponents; 4]> = None;+ let mut patches = vec![];++ while let Some(flag) = reader.read(bpf) {+ let mut control_points = vec![Point::ZERO; 16]; // Always allocate 16, use subset as needed.+ let mut colors = [smallvec![], smallvec![], smallvec![], smallvec![]];++ match flag {+ 0 => {+ for i in 0..control_points_count {+ control_points[i] = helpers.read_point(&mut reader)?;+ }++ for i in 0..4 {+ colors[i] = read_colors(&mut reader)?;+ }++ prev_patch_points = Some(control_points.clone());+ prev_patch_colors = Some(colors.clone());+ }+ 1..=3 => {+ let prev_points = prev_patch_points.as_ref()?;+ let prev_colors = prev_patch_colors.as_ref()?;++ copy_patch_control_points(flag, prev_points, &mut control_points);++ match flag {+ 1 => {+ colors[0] = prev_colors[1].clone();+ colors[1] = prev_colors[2].clone();+ }+ 2 => {+ colors[0] = prev_colors[2].clone();+ colors[1] = prev_colors[3].clone();+ }+ 3 => {+ colors[0] = prev_colors[3].clone();+ colors[1] = prev_colors[0].clone();+ }+ _ => unreachable!(),+ }++ for i in 4..control_points_count {+ control_points[i] = helpers.read_point(&mut reader)?;+ }++ colors[2] = read_colors(&mut reader)?;+ colors[3] = read_colors(&mut reader)?;++ prev_patch_points = Some(control_points.clone());+ prev_patch_colors = Some(colors.clone());+ }+ _ => break,+ }++ let mut fixed_points = [Point::ZERO; 16];+ for i in 0..16 {+ if i < control_points.len() {+ fixed_points[i] = control_points[i];+ }+ }++ patches.push(create_patch(fixed_points, colors));+ }+ Some(patches)+}++fn copy_patch_control_points(+ flag: u32,+ prev_control_points: &[Point],+ control_points: &mut [Point],+) {+ match flag {+ 1 => {+ control_points[0] = prev_control_points[3];+ control_points[1] = prev_control_points[4];+ control_points[2] = prev_control_points[5];+ control_points[3] = prev_control_points[6];+ }+ 2 => {+ control_points[0] = prev_control_points[6];+ control_points[1] = prev_control_points[7];+ control_points[2] = prev_control_points[8];+ control_points[3] = prev_control_points[9];+ }+ 3 => {+ control_points[0] = prev_control_points[9];+ control_points[1] = prev_control_points[10];+ control_points[2] = prev_control_points[11];+ control_points[3] = prev_control_points[0];+ }+ _ => {}+ }+}++fn read_tensor_product_patch_mesh(+ data: &[u8],+ bpf: u8,+ bp_coord: u8,+ bp_comp: u8,+ has_function: bool,+ decode: &[f32],+) -> Option<Vec<TensorProductPatch>> {+ read_patch_mesh(+ data,+ bpf,+ bp_coord,+ bp_comp,+ has_function,+ decode,+ 16,+ |control_points, colors| TensorProductPatch {+ control_points,+ colors,+ },+ )+}++fn read_function(dict: &Dict<'_>, color_space: &ColorSpace) -> Option<ShadingFunction> {+ if let Some(arr) = dict.get::<Array<'_>>(FUNCTION) {+ let arr: Option<SmallVec<_>> = arr+ .iter::<Object<'_>>()+ .map(|o| Function::new(&o))+ .collect();+ let arr = arr?;++ if arr.len() != color_space.num_components() as usize {+ warn!("function array of shading has wrong size");++ return None;+ }++ Some(ShadingFunction::Multiple(arr))+ } else if let Some(obj) = dict.get::<Object<'_>>(FUNCTION) {+ Some(ShadingFunction::Single(Function::new(&obj)?))+ } else {+ None+ }+}diff --git a/vendor/hayro-interpret/src/soft_mask.rs b/vendor/hayro-interpret/src/soft_mask.rsnew file mode 100644index 000000000..45937ceb7--- /dev/null+++ b/vendor/hayro-interpret/src/soft_mask.rs@@ -0,0 +1,190 @@+use crate::color::{Color, ColorComponents, ColorSpace};+use crate::context::{Context, InterpreterCache};+use crate::device::Device;+use crate::function::Function;+use crate::interpret::state::State;+use crate::util::hash128;+use crate::x_object::{FormXObject, draw_form_xobject};+use crate::{CacheKey, InterpreterSettings};+use hayro_syntax::object::Name;+use hayro_syntax::object::ObjectIdentifier;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::*;+use hayro_syntax::object::{Dict, Object};+use hayro_syntax::page::Resources;+use hayro_syntax::xref::XRef;+use kurbo::Affine;+use smallvec::smallvec;+use std::fmt::Debug;+use std::hash::{Hash, Hasher};+use std::ops::Deref;+use std::rc::Rc;++/// Type type of mask.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum MaskType {+ /// A luminosity mask.+ Luminosity,+ /// An alpha mask.+ Alpha,+}++/// A transfer function to apply to the opacity values of a mask.+pub struct TransferFunction(Function);++impl TransferFunction {+ /// Apply the transfer function to the given value.+ ///+ /// The input value needs to be between 0 and 1 and the return value is+ /// guaranteed to be between 0 and 1.+ #[inline]+ pub fn apply(&self, val: f32) -> f32 {+ self.0+ .eval(smallvec![val])+ .and_then(|v| v.first().copied())+ .unwrap_or(0.0)+ .clamp(0.0, 1.0)+ }+}++struct Repr<'a> {+ obj_id: ObjectIdentifier,+ group: FormXObject<'a>,+ mask_type: MaskType,+ parent_resources: Resources<'a>,+ root_transform: Affine,+ bbox: kurbo::Rect,+ interpreter_cache: InterpreterCache<'a>,+ transfer_function: Option<TransferFunction>,+ settings: InterpreterSettings,+ background: Color,+ xref: &'a XRef,+ nesting_depth: u32,+}++impl Hash for Repr<'_> {+ fn hash<H: Hasher>(&self, state: &mut H) {+ self.obj_id.hash(state);+ self.root_transform.cache_key().hash(state);+ }+}++/// A soft mask.+#[derive(Clone, Hash)]+pub struct SoftMask<'a>(Rc<Repr<'a>>);++impl Debug for SoftMask<'_> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "SoftMask({:?})", self.0.obj_id)+ }+}++impl PartialEq for SoftMask<'_> {+ fn eq(&self, other: &Self) -> bool {+ self.0.obj_id == other.0.obj_id+ }+}++impl Eq for SoftMask<'_> {}++impl CacheKey for SoftMask<'_> {+ fn cache_key(&self) -> u128 {+ hash128(self)+ }+}++impl<'a> SoftMask<'a> {+ pub(crate) fn new(+ dict: &Dict<'a>,+ context: &Context<'a>,+ parent_resources: Resources<'a>,+ ) -> Option<Self> {+ // TODO: With this setup, if there is a luminosity mask and alpha mask pointing to the+ // same xobject, the ID will be the same.+ let obj_id = dict.get_ref(G)?.into();+ let group_stream = dict.get::<Stream<'_>>(G)?;+ let group = FormXObject::new(&group_stream)?;+ // PrintCraft patch: the group's /CS is optional (ISO 32000-2 §11.6.5.2; Chrome/Skia omit+ // it). Upstream returned None here, silently dropping the whole soft mask. Fall back to+ // DeviceRGB, the blending space our renderer composites in.+ let cs = group+ .dict+ .get::<Dict<'_>>(GROUP)+ .and_then(|g| g.get::<Object<'_>>(CS))+ .and_then(|o| ColorSpace::new(o, &context.interpreter_cache.object_cache))+ .unwrap_or_else(ColorSpace::device_rgb);+ let transfer_function = dict+ .get::<Object<'_>>(TR)+ .and_then(|o| Function::new(&o))+ .map(TransferFunction);+ let (mask_type, background) = match dict.get::<Name<'_>>(S)?.deref() {+ LUMINOSITY => {+ let color = dict+ .get::<ColorComponents>(BC)+ .map(|c| Color::new(cs, c, 1.0))+ .unwrap_or(Color::new(ColorSpace::device_gray(), smallvec![0.0], 1.0));++ (MaskType::Luminosity, color)+ }+ ALPHA => (+ MaskType::Alpha,+ // Background color attribute should only be used with luminosity masks.+ Color::new(ColorSpace::device_gray(), smallvec![0.0], 1.0),+ ),+ _ => return None,+ };+ let nesting_depth = context.nesting_depth() + 1;++ Some(Self(Rc::new(Repr {+ obj_id,+ group,+ mask_type,+ root_transform: context.get().ctm,+ transfer_function,+ bbox: context.bbox(),+ interpreter_cache: context.interpreter_cache.clone(),+ settings: context.settings.clone(),+ xref: context.xref,+ background,+ parent_resources,+ nesting_depth,+ })))+ }++ /// Interpret the contents of the mask into the given device.+ pub fn interpret(&self, device: &mut impl Device<'a>) {+ let state = State::new(self.0.root_transform);+ let mut ctx = Context::new_with(+ self.0.root_transform,+ self.0.bbox,+ &self.0.interpreter_cache,+ self.0.xref,+ self.0.settings.clone(),+ state,+ self.0.nesting_depth,+ );+ draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device);+ }++ /// Return the object identifier of the mask.+ ///+ /// This can be used as a unique identifier for caching purposes.+ pub fn id(&self) -> ObjectIdentifier {+ self.0.obj_id+ }++ /// Return the underlying mask type.+ pub fn mask_type(&self) -> MaskType {+ self.0.mask_type+ }++ /// The background color against which the mask should be composited.+ pub fn background_color(&self) -> Color {+ self.0.background.clone()+ }++ /// Return the transfer function that should be used for the mask.+ pub fn transfer_function(&self) -> Option<&TransferFunction> {+ self.0.transfer_function.as_ref()+ }+}diff --git a/vendor/hayro-interpret/src/types.rs b/vendor/hayro-interpret/src/types.rsnew file mode 100644index 000000000..64d2b849b--- /dev/null+++ b/vendor/hayro-interpret/src/types.rs@@ -0,0 +1,366 @@+use crate::CacheKey;+use crate::color::Color;+use crate::pattern::Pattern;+use crate::util::hash128;+use crate::x_object::ImageXObject;+use hayro_syntax::object::Stream;+use kurbo::{BezPath, Cap, Join};+use smallvec::{SmallVec, smallvec};++/// A clip path.+#[derive(Debug, Clone)]+pub struct ClipPath {+ /// The clipping path.+ pub path: BezPath,+ /// The fill rule.+ pub fill: FillRule,+}++impl CacheKey for ClipPath {+ fn cache_key(&self) -> u128 {+ hash128(&(&self.path.to_svg(), &self.fill))+ }+}++/// A stencil image.+pub struct StencilImage<'a, 'b> {+ pub(crate) paint: Paint<'a>,+ pub(crate) image_xobject: ImageXObject<'b>,+}++impl<'a, 'b> StencilImage<'a, 'b> {+ /// Perform some operation with the stencil data of the image.+ ///+ /// The second argument allows you to give the image decoder a hint for+ /// what resolution of the image you want to have. Note that this does not+ /// mean that the resulting image will have that dimension. Instead, it allows+ /// the image decoder to extract a lower-resolution version of the image in+ /// certain cases.+ pub fn with_stencil(+ &self,+ func: impl FnOnce(LumaData, &Paint<'a>),+ target_dimension: Option<(u32, u32)>,+ ) {+ if let Some(decoded) = self.image_xobject.decoded_mask(target_dimension) {+ func(decoded.luma, &self.paint);+ }+ }++ // These are hidden since clients are supposed to call get the+ // width/height from `LumaData` instead.+ #[doc(hidden)]+ pub fn width(&self) -> u32 {+ self.image_xobject.width()+ }++ #[doc(hidden)]+ pub fn height(&self) -> u32 {+ self.image_xobject.height()+ }+}++impl CacheKey for StencilImage<'_, '_> {+ fn cache_key(&self) -> u128 {+ self.image_xobject.cache_key()+ }+}++/// A raster image.+pub struct RasterImage<'a>(pub(crate) ImageXObject<'a>);++impl RasterImage<'_> {+ /// Perform some operation with the RGB and alpha channel of the image.+ ///+ /// The second argument allows you to give the image decoder a hint for+ /// what resolution of the image you want to have. Note that this does not+ /// mean that the resulting image will have that dimension. Instead, it allows+ /// the image decoder to extract a lower-resolution version of the image in+ /// certain cases.+ pub fn with_rgba(+ &self,+ func: impl FnOnce(ImageData, Option<LumaData>),+ target_dimension: Option<(u32, u32)>,+ ) {+ if let Some(decoded) = self.0.decoded_raster(target_dimension) {+ func(decoded.image, decoded.alpha);+ }+ }++ /// Return the underlying stream object.+ ///+ /// This allows you to get access to the raw encoded image data, without doing any decoding.+ pub fn stream(&self) -> &Stream<'_> {+ self.0.stream()+ }++ // These are hidden since clients are supposed to call get the+ // width/height from `LumaData` instead.+ #[doc(hidden)]+ pub fn width(&self) -> u32 {+ self.0.width()+ }++ #[doc(hidden)]+ pub fn height(&self) -> u32 {+ self.0.height()+ }+}++impl CacheKey for RasterImage<'_> {+ fn cache_key(&self) -> u128 {+ self.0.cache_key()+ }+}++/// A type of image.+pub enum Image<'a, 'b> {+ /// A stencil image.+ Stencil(StencilImage<'a, 'b>),+ /// A normal raster image.+ Raster(RasterImage<'b>),+}++impl Image<'_, '_> {+ // These are hidden since clients are supposed to call get the+ // width/height from `LumaData/RgbData` instead.+ #[doc(hidden)]+ pub fn width(&self) -> u32 {+ match self {+ Image::Stencil(s) => s.width(),+ Image::Raster(r) => r.width(),+ }+ }++ // These are hidden since clients are supposed to call get the+ // width/height from `LumaData/RgbData` instead.+ #[doc(hidden)]+ pub fn height(&self) -> u32 {+ match self {+ Image::Stencil(s) => s.height(),+ Image::Raster(r) => r.height(),+ }+ }+}++impl CacheKey for Image<'_, '_> {+ fn cache_key(&self) -> u128 {+ match self {+ Image::Stencil(i) => i.cache_key(),+ Image::Raster(i) => i.cache_key(),+ }+ }+}++/// A structure holding 3-channel RGB data.+#[derive(Clone)]+pub struct RgbData {+ /// The actual data. It is guaranteed to have the length width * height * 3.+ pub data: Vec<u8>,+ /// The width.+ pub width: u32,+ /// The height.+ pub height: u32,+ /// Whether the image should be interpolated.+ pub interpolate: bool,+ /// Additional scaling factors to apply to the image.+ ///+ /// In most cases, those factors will just be 1.0, and you can+ /// ignore them. There are two situations in which they will not be equal+ /// to 1:+ /// 1) The PDF provided wrong metadata about the width/height of the image,+ /// which needs to be corrected+ /// 2) A lower resolution of the image was requested, in which case it needs+ /// to be scaled up so that it still covers the same area.+ ///+ /// The first number indicates the x scaling factor, the second number the+ /// y scaling factor.+ pub scale_factors: (f32, f32),+}++/// A structure holding 1-channel luma data.+#[derive(Clone)]+pub struct LumaData {+ /// The actual data. It is guaranteed to have the length width * height.+ pub data: Vec<u8>,+ /// The width.+ pub width: u32,+ /// The height.+ pub height: u32,+ /// Whether the image should be interpolated.+ pub interpolate: bool,+ /// Additional scaling factors to apply to the image.+ ///+ /// In most cases, those factors will just be 1.0, and you can+ /// ignore them. There are two situations in which they will not be equal+ /// to 1:+ /// 1) The PDF provided wrong metadata about the width/height of the image,+ /// which needs to be corrected+ /// 2) A lower resolution of the image was requested, in which case it needs+ /// to be scaled up so that it still covers the same area.+ ///+ /// The first number indicates the x scaling factor, the second number the+ /// y scaling factor.+ pub scale_factors: (f32, f32),+}++/// The color data of a raster image, either 3-channel RGB or 1-channel luma.+#[derive(Clone)]+pub enum ImageData {+ /// 3-channel RGB data.+ Rgb(RgbData),+ /// 1-channel grayscale data.+ Luma(LumaData),+}++impl ImageData {+ /// The width of the image.+ pub fn width(&self) -> u32 {+ match self {+ Self::Rgb(d) => d.width,+ Self::Luma(d) => d.width,+ }+ }++ /// The height of the image.+ pub fn height(&self) -> u32 {+ match self {+ Self::Rgb(d) => d.height,+ Self::Luma(d) => d.height,+ }+ }++ /// Whether the image should be interpolated.+ pub fn interpolate(&self) -> bool {+ match self {+ Self::Rgb(d) => d.interpolate,+ Self::Luma(d) => d.interpolate,+ }+ }++ /// The scaling factors of the image.+ pub fn scale_factors(&self) -> (f32, f32) {+ match self {+ Self::Rgb(d) => d.scale_factors,+ Self::Luma(d) => d.scale_factors,+ }+ }+}++/// A type of paint.+#[derive(Clone, Debug)]+pub enum Paint<'a> {+ /// A solid RGBA color.+ Color(Color),+ /// A PDF pattern.+ Pattern(Box<Pattern<'a>>),+}++impl CacheKey for Paint<'_> {+ fn cache_key(&self) -> u128 {+ match self {+ Paint::Color(c) => {+ // TODO: We should actually cache the color with color space etc., not just the+ // RGBA8 version.+ hash128(&c.to_rgba().to_rgba8())+ }+ Paint::Pattern(p) => p.cache_key(),+ }+ }+}++/// The draw mode that should be used for a path.+#[derive(Clone, Debug)]+pub enum PathDrawMode {+ /// Draw using a fill.+ Fill(FillRule),+ /// Draw using a stroke.+ Stroke(StrokeProps),+}++/// The draw mode that should be used for a glyph.+#[derive(Clone, Debug)]+pub enum GlyphDrawMode {+ /// Draw using a fill.+ Fill,+ /// Draw using a stroke.+ Stroke(StrokeProps),+ /// Invisible text (for text extraction but not visual rendering).+ Invisible,+}++/// Stroke properties.+#[derive(Clone, Debug)]+pub struct StrokeProps {+ /// The line width.+ pub line_width: f32,+ /// The line cap.+ pub line_cap: Cap,+ /// The line join.+ pub line_join: Join,+ /// The miter limit.+ pub miter_limit: f32,+ /// The dash array.+ pub dash_array: SmallVec<[f32; 4]>,+ /// The dash offset.+ pub dash_offset: f32,+}++impl Default for StrokeProps {+ fn default() -> Self {+ Self {+ line_width: 1.0,+ line_cap: Cap::Butt,+ line_join: Join::Miter,+ miter_limit: 10.0,+ dash_array: smallvec![],+ dash_offset: 0.0,+ }+ }+}++/// A fill rule.+#[derive(Clone, Debug, Copy, Hash, PartialEq, Eq)]+pub enum FillRule {+ /// Non-zero filling.+ NonZero,+ /// Even-odd filling.+ EvenOdd,+}++/// A blend mode.+#[derive(Clone, Debug, Copy, Hash, PartialEq, Eq, Default)]+pub enum BlendMode {+ /// Normal blend mode (default).+ #[default]+ Normal,+ /// Multiply blend mode.+ Multiply,+ /// Screen blend mode.+ Screen,+ /// Overlay blend mode.+ Overlay,+ /// Darken blend mode.+ Darken,+ /// Lighten blend mode.+ Lighten,+ /// `ColorDodge` blend mode.+ ColorDodge,+ /// `ColorBurn` blend mode.+ ColorBurn,+ /// `HardLight` blend mode.+ HardLight,+ /// `SoftLight` blend mode.+ SoftLight,+ /// Difference blend mode.+ Difference,+ /// Exclusion blend mode.+ Exclusion,+ /// Hue blend mode.+ Hue,+ /// Saturation blend mode.+ Saturation,+ /// Color blend mode.+ Color,+ /// Luminosity blend mode.+ Luminosity,+}diff --git a/vendor/hayro-interpret/src/util.rs b/vendor/hayro-interpret/src/util.rsnew file mode 100644index 000000000..d39b450b8--- /dev/null+++ b/vendor/hayro-interpret/src/util.rs@@ -0,0 +1,183 @@+//! A number of utility methods.++use kurbo::{BezPath, PathEl, Rect};+use siphasher::sip128::{Hasher128, SipHasher13};+use std::hash::Hash;+use std::ops::Sub;++pub(crate) trait OptionLog {+ fn warn_none(self, f: &str) -> Self;+}++impl<T> OptionLog for Option<T> {+ #[inline]+ fn warn_none(self, _f: &str) -> Self {+ self.or_else(|| {+ warn!("{_f}");++ None+ })+ }+}++const SCALAR_NEARLY_ZERO: f32 = 1.0 / (1 << 8) as f32;++/// A number of useful methods for f32 numbers.+pub trait Float32Ext: Sized + Sub<f32, Output = f32> + Copy + PartialOrd<f32> {+ /// Whether the number is approximately 0.+ fn is_nearly_zero(&self) -> bool {+ self.is_nearly_zero_within_tolerance(SCALAR_NEARLY_ZERO)+ }++ /// Whether the number is nearly equal to another number.+ fn is_nearly_equal(&self, other: f32) -> bool {+ (*self - other).is_nearly_zero()+ }++ /// Whether the number is nearly equal to another number.+ fn is_nearly_less_or_equal(&self, other: f32) -> bool {+ (*self - other).is_nearly_zero() || *self < other+ }++ /// Whether the number is nearly equal to another number.+ fn is_nearly_greater_or_equal(&self, other: f32) -> bool {+ (*self - other).is_nearly_zero() || *self > other+ }++ /// Whether the number is approximately 0, with a given tolerance.+ fn is_nearly_zero_within_tolerance(&self, tolerance: f32) -> bool;+}++impl Float32Ext for f32 {+ fn is_nearly_zero_within_tolerance(&self, tolerance: f32) -> bool {+ debug_assert!(tolerance >= 0.0, "tolerance must be non-negative");++ self.abs() <= tolerance+ }+}++/// A number of useful methods for f64 numbers.+pub trait Float64Ext: Sized + Sub<f64, Output = f64> + Copy + PartialOrd<f64> {+ /// Whether the number is approximately 0.+ fn is_nearly_zero(&self) -> bool {+ self.is_nearly_zero_within_tolerance(SCALAR_NEARLY_ZERO as f64)+ }++ /// Whether the number is nearly equal to another number.+ fn is_nearly_equal(&self, other: f64) -> bool {+ (*self - other).is_nearly_zero()+ }++ /// Whether the number is nearly equal to another number.+ fn is_nearly_less_or_equal(&self, other: f64) -> bool {+ (*self - other).is_nearly_zero() || *self < other+ }++ /// Whether the number is nearly equal to another number.+ fn is_nearly_greater_or_equal(&self, other: f64) -> bool {+ (*self - other).is_nearly_zero() || *self > other+ }++ /// Whether the number is approximately 0, with a given tolerance.+ fn is_nearly_zero_within_tolerance(&self, tolerance: f64) -> bool;+}++impl Float64Ext for f64 {+ fn is_nearly_zero_within_tolerance(&self, tolerance: f64) -> bool {+ debug_assert!(tolerance >= 0.0, "tolerance must be non-negative");++ self.abs() <= tolerance+ }+}++pub(crate) trait PointExt: Sized {+ fn x(&self) -> f32;+ fn y(&self) -> f32;++ fn nearly_same(&self, other: Self) -> bool {+ self.x().is_nearly_equal(other.x()) && self.y().is_nearly_equal(other.y())+ }+}++impl PointExt for kurbo::Point {+ fn x(&self) -> f32 {+ self.x as f32+ }++ fn y(&self) -> f32 {+ self.y as f32+ }+}++/// Calculate a 128-bit siphash of a value.+pub(crate) fn hash128<T: Hash + ?Sized>(value: &T) -> u128 {+ let mut state = SipHasher13::new();+ value.hash(&mut state);+ state.finish128().as_u128()+}++pub(crate) trait BezPathExt {+ fn fast_bounding_box(&self) -> Rect;+}++impl BezPathExt for BezPath {+ fn fast_bounding_box(&self) -> Rect {+ let mut min_x = f64::INFINITY;+ let mut min_y = f64::INFINITY;+ let mut max_x = f64::NEG_INFINITY;+ let mut max_y = f64::NEG_INFINITY;++ let mut include = |x: f64, y: f64| {+ min_x = min_x.min(x);+ min_y = min_y.min(y);+ max_x = max_x.max(x);+ max_y = max_y.max(y);+ };++ for el in self.elements() {+ match *el {+ PathEl::MoveTo(p) | PathEl::LineTo(p) => include(p.x, p.y),+ PathEl::QuadTo(p1, p2) => {+ include(p1.x, p1.y);+ include(p2.x, p2.y);+ }+ PathEl::CurveTo(p1, p2, p3) => {+ include(p1.x, p1.y);+ include(p2.x, p2.y);+ include(p3.x, p3.y);+ }+ PathEl::ClosePath => {}+ }+ }++ if min_x > max_x {+ Rect::ZERO+ } else {+ Rect::new(min_x, min_y, max_x, max_y)+ }+ }+}++/// Extension methods for converting a [`hayro_syntax::transform::Transform`] to a [`kurbo::Affine`].+pub trait TransformExt {+ /// Convert to a `kurbo::Affine`.+ fn to_kurbo(&self) -> kurbo::Affine;+}++impl TransformExt for hayro_syntax::transform::Transform {+ fn to_kurbo(&self) -> kurbo::Affine {+ kurbo::Affine::new(self.as_coeffs())+ }+}++/// Extension methods for rectangles.+pub trait RectExt {+ /// Convert the rectangle to a `kurbo` rectangle.+ fn to_kurbo(&self) -> Rect;+}++impl RectExt for hayro_syntax::object::Rect {+ fn to_kurbo(&self) -> Rect {+ Rect::new(self.x0, self.y0, self.x1, self.y1)+ }+}diff --git a/vendor/hayro-interpret/src/x_object.rs b/vendor/hayro-interpret/src/x_object.rsnew file mode 100644index 000000000..058f786eb--- /dev/null+++ b/vendor/hayro-interpret/src/x_object.rs@@ -0,0 +1,970 @@+use crate::cache::Cache;+use crate::color::{ColorComponents, ColorSpace, ToRgb};+use crate::context::Context;+use crate::device::Device;+use crate::function::{Function, interpolate};+use crate::interpret::path::get_paint;+use crate::interpret::state::ActiveTransferFunction;+use crate::{BlendMode, CacheKey, ClipPath, Image, RasterImage, StencilImage};+use crate::{FillRule, InterpreterWarning, WarningSinkFn, interpret};+use crate::{ImageData, LumaData, RgbData};+use hayro_syntax::bit_reader::BitReader;+use hayro_syntax::content::TypedIter;+use hayro_syntax::object::Array;+use hayro_syntax::object::Dict;+use hayro_syntax::object::Name;+use hayro_syntax::object::Object;+use hayro_syntax::object::Stream;+use hayro_syntax::object::dict::keys::*;+use hayro_syntax::object::stream::{FilterResult, ImageColorSpace, ImageDecodeParams};+use hayro_syntax::page::Resources;+use kurbo::{Affine, Rect, Shape};+use smallvec::{SmallVec, smallvec};+use std::borrow::Cow;+use std::iter;+use std::ops::Deref;++pub(crate) enum XObject<'a> {+ FormXObject(FormXObject<'a>),+ ImageXObject(ImageXObject<'a>),+}++impl<'a> XObject<'a> {+ pub(crate) fn new(+ stream: &Stream<'a>,+ warning_sink: &WarningSinkFn,+ cache: &Cache,+ transfer_function: Option<ActiveTransferFunction>,+ ) -> Option<Self> {+ let dict = stream.dict();+ match dict.get::<Name<'_>>(SUBTYPE)?.deref() {+ IMAGE => Some(Self::ImageXObject(ImageXObject::new(+ stream,+ |_| None,+ warning_sink,+ cache,+ false,+ transfer_function,+ )?)),+ FORM => Some(Self::FormXObject(FormXObject::new(stream)?)),+ _ => None,+ }+ }+}++pub(crate) struct FormXObject<'a> {+ pub(crate) decoded: Cow<'a, [u8]>,+ pub(crate) matrix: Affine,+ pub(crate) bbox: [f32; 4],+ is_transparency_group: bool,+ pub(crate) dict: Dict<'a>,+ resources: Dict<'a>,+}++impl<'a> FormXObject<'a> {+ pub(crate) fn new(stream: &Stream<'a>) -> Option<Self> {+ let dict = stream.dict();++ let decoded = stream.decoded().ok()?;+ let resources = dict.get::<Dict<'_>>(RESOURCES).unwrap_or_default();++ let matrix = Affine::new(+ dict.get::<[f64; 6]>(MATRIX)+ .unwrap_or([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]),+ );+ let bbox = dict.get::<[f32; 4]>(BBOX)?;+ let is_transparency_group = dict.get::<Dict<'_>>(GROUP).is_some();++ Some(Self {+ decoded,+ matrix,+ is_transparency_group,+ bbox,+ dict: dict.clone(),+ resources,+ })+ }+}++pub(crate) fn draw_xobject<'a>(+ x_object: &XObject<'a>,+ resources: &Resources<'a>,+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+) {+ match x_object {+ XObject::FormXObject(f) => draw_form_xobject(resources, f, context, device),+ XObject::ImageXObject(i) => {+ draw_image_xobject(i, context, device);+ }+ }+}++pub(crate) fn draw_form_xobject<'a, 'b>(+ resources: &Resources<'a>,+ x_object: &'b FormXObject<'a>,+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+) {+ if !context.ocg_state.is_visible() {+ return;+ }++ if !context.begin_nested_interpretation() {+ return;+ }++ let has_oc = xobject_oc(&x_object.dict, context);+ if !context.ocg_state.is_visible() {+ if has_oc {+ context.ocg_state.end_marked_content();+ }+ context.end_nested_interpretation();+ return;+ }++ let iter = TypedIter::new(x_object.decoded.as_ref());++ context.path_mut().truncate(0);+ context.save_state();+ context.pre_concat_affine(x_object.matrix);+ context.push_root_transform();++ if x_object.is_transparency_group {+ device.push_transparency_group(+ context.get().graphics_state.non_stroke_alpha,+ std::mem::take(&mut context.get_mut().graphics_state.soft_mask),+ std::mem::take(&mut context.get_mut().graphics_state.blend_mode),+ );++ context.get_mut().graphics_state.non_stroke_alpha = 1.0;+ context.get_mut().graphics_state.stroke_alpha = 1.0;+ }++ device.set_soft_mask(context.get().graphics_state.soft_mask.clone());+ device.set_blend_mode(context.get().graphics_state.blend_mode);++ device.push_clip_path(&ClipPath {+ path: context.get().ctm+ * Rect::new(+ x_object.bbox[0] as f64,+ x_object.bbox[1] as f64,+ x_object.bbox[2] as f64,+ x_object.bbox[3] as f64,+ )+ .to_path(0.1),+ fill: FillRule::NonZero,+ });++ interpret(+ iter,+ &Resources::from_parent(x_object.resources.clone(), resources.clone()),+ context,+ device,+ );++ device.pop_clip_path();++ if x_object.is_transparency_group {+ device.pop_transparency_group();+ }++ context.pop_root_transform();+ context.restore_state(device);++ if has_oc {+ context.ocg_state.end_marked_content();+ }++ context.end_nested_interpretation();+}++pub(crate) fn draw_image_xobject<'a, 'b>(+ x_object: &ImageXObject<'b>,+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+) {+ if !context.ocg_state.is_visible() {+ return;+ }++ let has_oc = xobject_oc(x_object.stream.dict(), context);+ if !context.ocg_state.is_visible() {+ if has_oc {+ context.ocg_state.end_marked_content();+ }+ return;+ }++ let width = x_object.width as f64;+ let height = x_object.height as f64;++ context.save_state();+ context.pre_concat_affine(Affine::new([+ 1.0 / width,+ 0.0,+ 0.0,+ -1.0 / height,+ 0.0,+ 1.0,+ ]));+ let transform = context.get().ctm;++ let has_alpha = x_object.has_mask();++ let mut soft_mask = std::mem::take(&mut context.get_mut().graphics_state.soft_mask);+ let blend_mode = std::mem::take(&mut context.get_mut().graphics_state.blend_mode);++ // If image has smask, the soft mask from the graphics state should be discarde.+ if has_alpha {+ soft_mask = None;+ }++ device.push_transparency_group(+ context.get().graphics_state.non_stroke_alpha,+ std::mem::take(&mut soft_mask),+ blend_mode,+ );++ device.set_soft_mask(None);+ device.set_blend_mode(BlendMode::default());++ let image = if x_object.is_mask {+ Image::Stencil(StencilImage {+ paint: get_paint(context, false),+ image_xobject: x_object.clone(),+ })+ } else {+ Image::Raster(RasterImage(x_object.clone()))+ };++ device.draw_image(image, transform);+ device.pop_transparency_group();++ context.restore_state(device);++ if has_oc {+ context.ocg_state.end_marked_content();+ }+}++fn xobject_oc(dict: &Dict<'_>, context: &mut Context<'_>) -> bool {+ let Some(oc_dict) = dict.get::<Dict<'_>>(OC) else {+ return false;+ };++ if let Some(oc_ref) = dict.get_ref(OC) {+ context.ocg_state.begin_ocg(&oc_dict, oc_ref.into());+ } else {+ context.ocg_state.begin_ocmd(&oc_dict);+ }++ true+}++#[derive(Clone)]+pub(crate) struct ImageXObject<'a> {+ width: u32,+ height: u32,+ color_space: Option<ColorSpace>,+ cache: Cache,+ interpolate: bool,+ is_mask: bool,+ is_stencil_mask: bool,+ stream: Stream<'a>,+ transfer_function: Option<ActiveTransferFunction>,+ warning_sink: WarningSinkFn,+}++impl<'a> ImageXObject<'a> {+ pub(crate) fn new(+ stream: &Stream<'a>,+ resolve_cs: impl FnOnce(&Name<'_>) -> Option<ColorSpace>,+ warning_sink: &WarningSinkFn,+ cache: &Cache,+ mut is_mask: bool,+ transfer_function: Option<ActiveTransferFunction>,+ ) -> Option<Self> {+ let dict = stream.dict();++ let is_stencil_mask = dict+ .get::<bool>(IM)+ .or_else(|| dict.get::<bool>(IMAGE_MASK))+ .unwrap_or(false);+ is_mask |= is_stencil_mask;++ let image_cs = if is_mask {+ // Masks are always single-channel.+ Some(ColorSpace::device_gray())+ } else {+ let cs_obj = dict+ .get::<Object<'_>>(CS)+ .or_else(|| dict.get::<Object<'_>>(COLORSPACE));++ cs_obj+ .clone()+ .and_then(|c| ColorSpace::new(c, cache))+ // Inline images can also refer to color spaces by name.+ .or_else(|| {+ cs_obj+ .and_then(|c| c.into_name())+ .and_then(|n| resolve_cs(&n))+ })+ };++ let interpolate = dict+ .get::<bool>(I)+ .or_else(|| dict.get::<bool>(INTERPOLATE))+ .unwrap_or(false);++ let width = dict.get::<u32>(W).or_else(|| dict.get::<u32>(WIDTH))?;+ let height = dict.get::<u32>(H).or_else(|| dict.get::<u32>(HEIGHT))?;++ if width == 0 || height == 0 {+ return None;+ }++ Some(Self {+ width,+ cache: cache.clone(),+ height,+ color_space: image_cs,+ warning_sink: warning_sink.clone(),+ transfer_function,+ interpolate,+ stream: stream.clone(),+ is_mask,+ is_stencil_mask,+ })+ }++ pub(crate) fn decoded_mask(&self, target_dimension: Option<(u32, u32)>) -> Option<DecodedMask> {+ if !self.is_mask {+ return None;+ }++ decode_mask(self, target_dimension)+ }++ pub(crate) fn decoded_raster(+ &self,+ target_dimension: Option<(u32, u32)>,+ ) -> Option<DecodedRaster> {+ if self.is_mask {+ return None;+ }++ decode_raster(self, target_dimension)+ }++ pub(crate) fn width(&self) -> u32 {+ self.width+ }++ pub(crate) fn height(&self) -> u32 {+ self.height+ }++ pub(crate) fn stream(&self) -> &Stream<'a> {+ &self.stream+ }++ fn has_mask(&self) -> bool {+ let dict = self.stream.dict();++ dict.contains_key(SMASK_IN_DATA) || dict.contains_key(SMASK) || dict.contains_key(MASK)+ }+}++pub(crate) struct DecodedMask {+ pub(crate) luma: LumaData,+}++pub(crate) struct DecodedRaster {+ pub(crate) image: ImageData,+ pub(crate) alpha: Option<LumaData>,+}++struct DecodeContext<'a> {+ decoded: FilterResult<'a>,+ width: u32,+ height: u32,+ scale_factors: (f32, f32),+ color_space: ColorSpace,+ bits_per_component: u8,+ decode_arr: SmallVec<[(f32, f32); 4]>,+}++fn decode_context<'a>(+ obj: &ImageXObject<'a>,+ target_dimension: Option<(u32, u32)>,+) -> Option<DecodeContext<'a>> {+ let dict = obj.stream.dict();+ let dict_bpc = dict+ .get::<u8>(BPC)+ .or_else(|| dict.get::<u8>(BITS_PER_COMPONENT));+ let color_space = obj.color_space.clone();+ let is_indexed = obj.color_space.as_ref().is_some_and(|cs| cs.is_indexed());++ let decode_params = ImageDecodeParams {+ is_indexed,+ bpc: dict_bpc,+ num_components: color_space.as_ref().map(|c| c.num_components()),+ target_dimension,+ width: obj.width,+ height: obj.height,+ };++ let decoded = obj+ .stream+ .decoded_image(&decode_params)+ .map_err(|_| (obj.warning_sink)(InterpreterWarning::ImageDecodeFailure))+ .ok()?;++ let (mut scale_x, mut scale_y) = (1.0, 1.0);++ let (width, height) = decoded+ .image_data+ .as_ref()+ .map(|d| {+ scale_x = obj.width as f32 / d.width as f32;+ scale_y = obj.height as f32 / d.height as f32;++ (d.width, d.height)+ })+ .unwrap_or((obj.width, obj.height));++ let color_space = color_space+ .or_else(|| {+ decoded+ .image_data+ .as_ref()+ .map(|i| i.color_space)+ .and_then(|c| {+ c.and_then(|c| match c {+ ImageColorSpace::Gray => Some(ColorSpace::device_gray()),+ ImageColorSpace::Rgb => Some(ColorSpace::device_rgb()),+ ImageColorSpace::Cmyk => Some(ColorSpace::device_cmyk()),+ ImageColorSpace::Unknown(_) => None,+ })+ })+ })+ .unwrap_or(ColorSpace::device_gray());++ let fallback_bpc = if obj.is_stencil_mask { 1 } else { 8 };++ let bits_per_component = decoded+ .image_data+ .as_ref()+ .map(|i| i.bits_per_component)+ .or(dict_bpc)+ .unwrap_or(fallback_bpc);++ let decode_arr = dict+ .get::<Array<'_>>(D)+ .or_else(|| dict.get::<Array<'_>>(DECODE))+ .map(|a| a.iter::<(f32, f32)>().collect::<SmallVec<_>>())+ .unwrap_or(color_space.default_decode_arr(bits_per_component as f32));++ Some(DecodeContext {+ decoded,+ width,+ height,+ scale_factors: (scale_x, scale_y),+ color_space,+ bits_per_component,+ decode_arr,+ })+}++fn decode_mask(+ obj: &ImageXObject<'_>,+ target_dimension: Option<(u32, u32)>,+) -> Option<DecodedMask> {+ let ctx = decode_context(obj, target_dimension)?;+ let mut height = ctx.height;++ let data = decode_mask_bytes(+ ctx.decoded.data,+ ctx.width,+ &mut height,+ &ctx.color_space,+ ctx.bits_per_component,+ &ctx.decode_arr,+ // Note: The semantics between "normal" soft masks (i.e. masks defined in+ // the graphics state or via `Mask`/`SMask` are inverted compared to+ // stencil masks (defined via `ImageMask`). The former match the semantics+ // of normal alpha images, where 0 stands for invisible and MAX stands for+ // fully opaque. For stencil masks, it's the other way around: 1 means the+ // paint is visible, while 0 means it's invisible.+ obj.is_stencil_mask,+ )?;++ Some(DecodedMask {+ luma: LumaData {+ data,+ width: ctx.width,+ height,+ interpolate: obj.interpolate,+ scale_factors: ctx.scale_factors,+ },+ })+}++fn decode_raster(+ obj: &ImageXObject<'_>,+ target_dimension: Option<(u32, u32)>,+) -> Option<DecodedRaster> {+ let mut ctx = decode_context(obj, target_dimension)?;+ let mut height = ctx.height;++ let is_default_decode = ctx.decode_arr+ == ctx+ .color_space+ .default_decode_arr(ctx.bits_per_component as f32);+ let is_inverted_default_decode = ctx.decode_arr+ == ctx+ .color_space+ .inverted_default_decode_arr(ctx.bits_per_component as f32);++ let image_data = if ctx.bits_per_component == 8+ && ctx.color_space.supports_u8()+ && obj.transfer_function.is_none()+ && (is_default_decode || is_inverted_default_decode)+ {+ // This is actually the most common case, where the PDF is embedded+ // in such a way where we don't need to decode. In this case,+ // we can prevent the round-trip from f32 back to u8 and just return+ // the raw decoded data, which will already be in+ // RGB8/gray-scale with values between 0 and 255.+ fix_image_length(+ ctx.decoded.data.to_mut(),+ ctx.width,+ &mut height,+ 0,+ &ctx.color_space,+ )?;++ if is_inverted_default_decode {+ for b in ctx.decoded.data.to_mut() {+ *b = 255 - *b;+ }+ }++ if ctx.color_space.is_device_gray() {+ Some(ImageData::Luma(LumaData {+ data: core::mem::take(&mut ctx.decoded.data).into_owned(),+ width: ctx.width,+ height,+ interpolate: obj.interpolate,+ scale_factors: ctx.scale_factors,+ }))+ } else {+ let mut output_buf = vec![0; ctx.width as usize * height as usize * 3];+ ctx.color_space+ .convert_u8(&ctx.decoded.data, &mut output_buf)?;++ Some(ImageData::Rgb(RgbData {+ data: output_buf,+ width: ctx.width,+ height,+ interpolate: obj.interpolate,+ scale_factors: ctx.scale_factors,+ }))+ }+ } else {+ let components = get_components(+ &ctx.decoded.data,+ ctx.width,+ height,+ &ctx.color_space,+ ctx.bits_per_component,+ )?;++ let mut f32_data = apply_decode_array(+ &components,+ &ctx.color_space,+ ctx.bits_per_component,+ &ctx.decode_arr,+ )?;++ fix_image_length(&mut f32_data, ctx.width, &mut height, 0.0, &ctx.color_space)?;++ let mut rgb_data = get_rgb_data(+ &f32_data,+ ctx.width,+ height,+ ctx.scale_factors,+ &ctx.color_space,+ obj.interpolate,+ );++ if let Some(transfer_function) = &obj.transfer_function+ && let Some(rgb_data) = &mut rgb_data+ {+ let apply_single = |data: u8, function: &Function| {+ function+ .eval(smallvec![data as f32 / 255.0])+ .and_then(|v| v.first().copied())+ .map(|v| (v * 255.0 + 0.5) as u8)+ .unwrap_or(data)+ };++ match transfer_function {+ ActiveTransferFunction::Single(s) => {+ for data in &mut rgb_data.data {+ *data = apply_single(*data, s);+ }+ }+ ActiveTransferFunction::Four(f) => {+ for data in rgb_data.data.chunks_exact_mut(3) {+ data[0] = apply_single(data[0], &f[0]);+ data[1] = apply_single(data[1], &f[1]);+ data[2] = apply_single(data[2], &f[2]);+ }+ }+ }+ }++ rgb_data.map(ImageData::Rgb)+ };++ let mut image = image_data?;++ let alpha = if let Some((alpha, matte_rgb)) =+ resolve_matte(obj, &ctx.color_space, target_dimension)+ && alpha.width == ctx.width+ && alpha.height == height+ {+ unpremultiply(&mut image, &alpha.data, &matte_rgb);++ Some(alpha)+ } else {+ // Use flatten here, so in case the alpha channel is invalid we can still+ // return the main image (see PDFJS-19611).+ resolve_alpha(+ obj,+ &mut ctx.decoded,+ Some(&image),+ &ctx.color_space,+ ctx.bits_per_component,+ ctx.width,+ &mut height,+ ctx.scale_factors,+ target_dimension,+ )+ .flatten()+ };++ Some(DecodedRaster { image, alpha })+}++fn decode_mask_bytes(+ mut decoded_data: Cow<'_, [u8]>,+ width: u32,+ height: &mut u32,+ color_space: &ColorSpace,+ bits_per_component: u8,+ decode_arr: &[(f32, f32)],+ invert: bool,+) -> Option<Vec<u8>> {+ let default_decode = color_space.default_decode_arr(bits_per_component as f32);+ let inverted_default = color_space.inverted_default_decode_arr(bits_per_component as f32);+ let fast_path = bits_per_component == 8+ && (decode_arr == default_decode.as_slice() || decode_arr == inverted_default.as_slice());++ let mut data = if fast_path {+ let should_invert = invert ^ (decode_arr == inverted_default.as_slice());+ if should_invert {+ for b in decoded_data.to_mut() {+ *b = 255 - *b;+ }+ }++ decoded_data.into_owned()+ } else {+ let components = get_components(+ &decoded_data,+ width,+ *height,+ color_space,+ bits_per_component,+ )?;++ let f32_data =+ apply_decode_array(&components, color_space, bits_per_component, decode_arr)?;++ if invert {+ f32_data+ .iter()+ .map(|alpha| ((1.0 - *alpha) * 255.0 + 0.5) as u8)+ .collect()+ } else {+ f32_data+ .iter()+ .map(|alpha| (*alpha * 255.0 + 0.5) as u8)+ .collect()+ }+ };++ fix_image_length(&mut data, width, height, 0, color_space)?;++ Some(data)+}++fn resolve_alpha(+ obj: &ImageXObject<'_>,+ decoded: &mut FilterResult<'_>,+ image_data: Option<&ImageData>,+ color_space: &ColorSpace,+ bits_per_component: u8,+ width: u32,+ height: &mut u32,+ scale_factors: (f32, f32),+ target_dimension: Option<(u32, u32)>,+) -> Option<Option<LumaData>> {+ let dict = obj.stream.dict();++ let alpha = if let Some(1) = dict.get::<u8>(SMASK_IN_DATA) {+ let smask_data = decoded.image_data.as_mut().and_then(|i| i.alpha.take());++ if let Some(mut data) = smask_data {+ fix_image_length(&mut data, width, height, 0, &ColorSpace::device_gray())?;++ Some(LumaData {+ data,+ width,+ height: *height,+ interpolate: obj.interpolate,+ scale_factors,+ })+ } else {+ None+ }+ // Note: `SMASK` field takes precedence over `MASK`, so order matters here.+ } else if let Some(s_mask) = dict+ .get::<Stream<'_>>(SMASK)+ .or_else(|| dict.get::<Stream<'_>>(MASK))+ {+ let obj = ImageXObject::new(&s_mask, |_| None, &obj.warning_sink, &obj.cache, true, None)?;++ decode_mask(&obj, target_dimension).map(|decoded| decoded.luma)+ } else if let Some(color_key_mask) = dict.get::<SmallVec<[u16; 4]>>(MASK) {+ let mut mask_data = vec![];++ // TODO: Make this less ugly.+ let raw_data = match image_data {+ Some(ImageData::Luma(d)) => &d.data,+ _ => decoded.data.as_ref(),+ };++ let components = get_components(raw_data, width, *height, color_space, bits_per_component)?;++ for pixel in components.chunks_exact(color_space.num_components() as usize) {+ let mut mask_val = 0;++ for (component, min_max) in pixel.iter().zip(color_key_mask.chunks_exact(2)) {+ if *component > min_max[1] || *component < min_max[0] {+ mask_val = 255;+ }+ }++ mask_data.push(mask_val);+ }++ fix_image_length(&mut mask_data, width, height, 0, &ColorSpace::device_gray())?;++ Some(LumaData {+ data: mask_data,+ width,+ height: *height,+ interpolate: obj.interpolate,+ scale_factors,+ })+ } else {+ None+ };++ Some(alpha)+}++fn resolve_matte(+ obj: &ImageXObject<'_>,+ color_space: &ColorSpace,+ target_dimension: Option<(u32, u32)>,+) -> Option<(LumaData, [u8; 3])> {+ let dict = obj.stream.dict();+ let s_mask = dict.get::<Stream<'_>>(SMASK)?;+ let matte = s_mask.dict().get::<ColorComponents>(MATTE)?;++ if matte.len() != color_space.num_components() as usize {+ return None;+ }++ // In theory, matte needs to be applied in the image's original color space,+ // but we always do it in RGB for now.+ let mut matte_rgb = [0_u8; 3];+ color_space.convert_f32(&matte, &mut matte_rgb, false);++ let mask_obj = ImageXObject::new(&s_mask, |_| None, &obj.warning_sink, &obj.cache, true, None)?;+ let alpha = decode_mask(&mask_obj, target_dimension)?.luma;++ Some((alpha, matte_rgb))+}++fn unpremultiply(image: &mut ImageData, alpha: &[u8], matte_rgb: &[u8]) {+ match image {+ ImageData::Rgb(rgb) => {+ for (pixel, &a) in rgb.data.chunks_exact_mut(3).zip(alpha.iter()) {+ if a == 0 {+ continue;+ }+ let inv_alpha = 255.0 / a as f32;+ for (c, &m) in pixel.iter_mut().zip(matte_rgb.iter()) {+ let m = m as f32;+ *c = (m + (*c as f32 - m) * inv_alpha) as u8;+ }+ }+ }+ ImageData::Luma(luma) => {+ let m = matte_rgb[0] as f32;+ for (c, &a) in luma.data.iter_mut().zip(alpha.iter()) {+ if a == 0 {+ continue;+ }+ let inv_alpha = 255.0 / a as f32;+ *c = (m + (*c as f32 - m) * inv_alpha) as u8;+ }+ }+ }+}++fn get_rgb_data(+ decoded: &[f32],+ width: u32,+ height: u32,+ scale_factors: (f32, f32),+ cs: &ColorSpace,+ interpolate: bool,+) -> Option<RgbData> {+ // To prevent a panic when calling the `chunks` method.+ if cs.num_components() == 0 {+ return None;+ }++ let mut output = vec![0; width as usize * height as usize * 3];+ cs.convert_f32(decoded, &mut output, false);++ Some(RgbData {+ data: output,+ width,+ height,+ interpolate,+ scale_factors,+ })+}++impl CacheKey for ImageXObject<'_> {+ fn cache_key(&self) -> u128 {+ self.stream.cache_key()+ }+}++#[must_use]+fn fix_image_length<T: Copy>(+ image: &mut Vec<T>,+ width: u32,+ height: &mut u32,+ filler: T,+ cs: &ColorSpace,+) -> Option<()> {+ let row_len = width as usize * cs.num_components() as usize;++ if (row_len * *height as usize) <= image.len() {+ // Too much data (or just the right amount), truncate it.+ image.truncate(row_len * *height as usize);+ } else {+ // Too little data, adapt the height and pad.+ *height = image.len().div_ceil(row_len) as u32;++ if !image.len().is_multiple_of(row_len) {+ image.extend(iter::repeat_n(filler, row_len - (image.len() % row_len)));+ }+ }++ if width == 0 || *height == 0 {+ None+ } else {+ Some(())+ }+}++fn get_components(+ data: &[u8],+ width: u32,+ height: u32,+ color_space: &ColorSpace,+ bits_per_component: u8,+) -> Option<Vec<u16>> {+ let result = match bits_per_component {+ 1..8 | 9..16 => {+ let mut buf = vec![];+ let bpc = bits_per_component;+ let mut reader = BitReader::new(data);++ for _ in 0..height {+ for _ in 0..width {+ for _ in 0..color_space.num_components() {+ // See `stream_ccit_not_enough_data`, some images seemingly don't have+ // enough data, so we just pad with zeroes in this case.+ let next = reader.read(bpc).unwrap_or(0) as u16;++ buf.push(next);+ }+ }++ reader.align();+ }++ buf+ }+ 8 => data.iter().map(|v| *v as u16).collect(),+ 16 => data+ .chunks(2)+ .map(|v| u16::from_be_bytes([v[0], v[1]]))+ .collect(),+ _ => {+ warn!("unsupported bits per component: {bits_per_component}");+ return None;+ }+ };++ Some(result)+}++fn apply_decode_array(+ components: &[u16],+ color_space: &ColorSpace,+ bits_per_component: u8,+ decode: &[(f32, f32)],+) -> Option<Vec<f32>> {+ let interpolate = |n: f32, d_min: f32, d_max: f32| {+ interpolate(+ n,+ 0.0,+ 2.0_f32.powi(bits_per_component as i32) - 1.0,+ d_min,+ d_max,+ )+ };++ let mut decoded_arr = vec![];++ for pixel in components.chunks(color_space.num_components() as usize) {+ for (component, (d_min, d_max)) in pixel.iter().zip(decode) {+ decoded_arr.push(interpolate(*component as f32, *d_min, *d_max));+ }+ }++ Some(decoded_arr)+}diff --git a/vendor/hayro/.cargo-ok b/vendor/hayro/.cargo-oknew file mode 100644index 000000000..5f8b79583--- /dev/null+++ b/vendor/hayro/.cargo-ok@@ -0,0 +1 @@+{"v":1}\ No newline at end of filediff --git a/vendor/hayro/.cargo_vcs_info.json b/vendor/hayro/.cargo_vcs_info.jsonnew file mode 100644index 000000000..4ea4f2df7--- /dev/null+++ b/vendor/hayro/.cargo_vcs_info.json@@ -0,0 +1,6 @@+{+ "git": {+ "sha1": "1e5b8eb7bfe03afe431ed0bc1d704c9432323ef6"+ },+ "path_in_vcs": "hayro"+}\ No newline at end of filediff --git a/vendor/hayro/Cargo.lock b/vendor/hayro/Cargo.locknew file mode 100644index 000000000..de7668d7e--- /dev/null+++ b/vendor/hayro/Cargo.lock@@ -0,0 +1,665 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[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 = "arrayvec"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"++[[package]]+name = "autocfg"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"++[[package]]+name = "bitflags"+version = "2.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"++[[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 = "bytemuck"+version = "1.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "color"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf"+dependencies = [+ "bytemuck",+]++[[package]]+name = "crc32fast"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"+dependencies = [+ "cfg-if",+]++[[package]]+name = "euclid"+version = "0.22.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"+dependencies = [+ "num-traits",+]++[[package]]+name = "fastrand"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "fearless_simd"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76258897e51fd156ee03b6246ea53f3e0eb395d0b327e9961c4fc4c8b2fa151a"++[[package]]+name = "flate2"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"+dependencies = [+ "crc32fast",+ "miniz_oxide",+]++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "font-types"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"+dependencies = [+ "bytemuck",+]++[[package]]+name = "glifo"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae9d48c6d81526ad2f9d5d6e5fddf5f6949ffbc46fcac0db0d061a6e65097019"+dependencies = [+ "bytemuck",+ "foldhash",+ "hashbrown",+ "log",+ "peniko",+ "png",+ "skrifa",+ "smallvec",+ "vello_common",+]++[[package]]+name = "guillotiere"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab"+dependencies = [+ "euclid",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+dependencies = [+ "foldhash",+]++[[package]]+name = "hayro"+version = "0.7.1"+dependencies = [+ "bytemuck",+ "hayro-interpret",+ "image",+ "kurbo",+ "log",+ "pic-scale",+ "vello_cpu",+]++[[package]]+name = "hayro-ccitt"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+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",+]++[[package]]+name = "hayro-interpret"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2613d0406898995042d0794c4245b2f2fba1246490c8ac593769bba6551129d"+dependencies = [+ "bitflags",+ "hayro-cmap",+ "hayro-syntax",+ "kurbo",+ "log",+ "moxcms",+ "phf",+ "rustc-hash",+ "siphasher",+ "skrifa",+ "smallvec",+ "yoke",+]++[[package]]+name = "hayro-jbig2"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d"+dependencies = [+ "fearless_simd",+ "hayro-ccitt",+]++[[package]]+name = "hayro-jpeg2000"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"+dependencies = [+ "fearless_simd",+ "log",+]++[[package]]+name = "hayro-postscript"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"++[[package]]+name = "hayro-syntax"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0edeafd70aa2db743de8ede8637d07ec87db05efe69cde371d03f1b185fcef27"+dependencies = [+ "flate2",+ "hayro-ccitt",+ "hayro-jbig2",+ "hayro-jpeg2000",+ "log",+ "memchr",+ "rustc-hash",+ "smallvec",+ "zune-jpeg",+]++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "moxcms",+ "num-traits",+ "png",+]++[[package]]+name = "kurbo"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"+dependencies = [+ "arrayvec",+ "euclid",+ "polycool",+ "smallvec",+]++[[package]]+name = "linebender_resource_handle"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"++[[package]]+name = "log"+version = "0.4.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"++[[package]]+name = "memchr"+version = "2.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "peniko"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6"+dependencies = [+ "bytemuck",+ "color",+ "kurbo",+ "linebender_resource_handle",+ "smallvec",+]++[[package]]+name = "phf"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"+dependencies = [+ "phf_macros",+ "phf_shared",+]++[[package]]+name = "phf_generator"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"+dependencies = [+ "fastrand",+ "phf_shared",+]++[[package]]+name = "phf_macros"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"+dependencies = [+ "phf_generator",+ "phf_shared",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "phf_shared"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"+dependencies = [+ "siphasher",+]++[[package]]+name = "pic-scale"+version = "0.7.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b05a62c3762cb26cb62665b915fea652def8a9f609b0b289b7f782a7394307b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide",+]++[[package]]+name = "polycool"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"+dependencies = [+ "arrayvec",+]++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "pxfm"+version = "0.1.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5a041e753da8b807c9255f28de81879c78c876392ff2469cde94799b2896b9d"++[[package]]+name = "quote"+version = "1.0.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "read-fonts"+version = "0.39.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"+dependencies = [+ "bytemuck",+ "font-types",+]++[[package]]+name = "rustc-hash"+version = "2.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"++[[package]]+name = "simd-adler32"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"++[[package]]+name = "siphasher"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e"++[[package]]+name = "skrifa"+version = "0.42.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"+dependencies = [+ "bytemuck",+ "read-fonts",+]++[[package]]+name = "smallvec"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "syn"+version = "2.0.117"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "vello_common"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee"+dependencies = [+ "bytemuck",+ "fearless_simd",+ "guillotiere",+ "hashbrown",+ "log",+ "peniko",+ "png",+ "smallvec",+ "thiserror",+]++[[package]]+name = "vello_cpu"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0"+dependencies = [+ "bytemuck",+ "glifo",+ "hashbrown",+ "png",+ "vello_common",+]++[[package]]+name = "yoke"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerofrom"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zune-core"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]diff --git a/vendor/hayro/Cargo.toml b/vendor/hayro/Cargo.tomlnew file mode 100644index 000000000..cb05624d4--- /dev/null+++ b/vendor/hayro/Cargo.toml@@ -0,0 +1,118 @@+# 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"+rust-version = "1.92"+name = "hayro"+version = "0.7.1"+authors = ["Laurenz Stampfl <[email protected]>"]+build = false+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "A rasterizer for PDF files."+readme = "README.md"+license = "Apache-2.0 OR MIT"+repository = "https://github.com/LaurenzV/hayro"+resolver = "2"++[features]+default = [+ "embed-fonts",+ "embed-cmaps",+]+embed-cmaps = ["hayro-interpret/embed-cmaps"]+embed-fonts = ["hayro-interpret/embed-fonts"]+logging = ["hayro-interpret/logging"]++[lib]+name = "hayro"+path = "src/lib.rs"++[[example]]+name = "render"+path = "examples/render.rs"++[dependencies.bytemuck]+version = "1"+features = ["bytemuck_derive"]++[dependencies.hayro-interpret]+version = "0.7.0"+default-features = false++[dependencies.image]+version = "0.25"+features = ["png"]+default-features = false++[dependencies.kurbo]+version = "0.13.0"++[dependencies.pic-scale]+version = "0.7.9"+features = [+ "neon",+ "rdm",+ "sse",+ "avx",+]+default-features = false++[dependencies.vello_cpu]+version = "0.0.8"+features = [+ "std",+ "png",+ "u8_pipeline",+]+default-features = false++[dev-dependencies.log]+version = "0.4"++[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/Cargo.toml.orig b/vendor/hayro/Cargo.toml.orignew file mode 100644index 000000000..1e60e6c00--- /dev/null+++ b/vendor/hayro/Cargo.toml.orig@@ -0,0 +1,31 @@+[package]+name = "hayro"+version = "0.7.1"+description = "A rasterizer for PDF files."+edition = { workspace = true }+rust-version = { workspace = true }+authors = { workspace = true }+repository = { workspace = true }+license = { workspace = true }+readme = "README.md"++[dependencies]+hayro-interpret = { workspace = true }+kurbo = { workspace = true }+image = { workspace = true, features = ["png"] }+bytemuck = { workspace = true, features = ["bytemuck_derive"] }+vello_cpu = { workspace = true }+pic-scale = { workspace = true }++[dev-dependencies]+log = { workspace = true }++[features]+default = ["embed-fonts", "embed-cmaps"]+embed-fonts = ["hayro-interpret/embed-fonts"]+# Embed the 61 predefined cmaps into the binary. Adds about ~250KB of brotli-encoded data.+embed-cmaps = ["hayro-interpret/embed-cmaps"]+logging = ["hayro-interpret/logging"]++[lints]+workspace = truediff --git a/vendor/hayro/LICENSE-APACHE b/vendor/hayro/LICENSE-APACHEnew file mode 100644index 000000000..4947287f7--- /dev/null+++ b/vendor/hayro/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 filediff --git a/vendor/hayro/LICENSE-MIT b/vendor/hayro/LICENSE-MITnew file mode 100644index 000000000..ae3742de4--- /dev/null+++ b/vendor/hayro/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 filediff --git a/vendor/hayro/README.md b/vendor/hayro/README.mdnew file mode 100644index 000000000..e09af3594--- /dev/null+++ b/vendor/hayro/README.md@@ -0,0 +1,46 @@+# hayro++[](https://crates.io/crates/hayro)+[](https://docs.rs/hayro)++<!-- cargo-rdme start -->++A crate for rendering PDF files.++This crate allows you to render pages of a PDF file into bitmaps. It is supposed to be relatively+lightweight, since we do not have any dependencies on the GPU. All the rendering happens on the CPU.++The ultimate goal of this crate is to be a *feature-complete* and *performant* PDF rasterizer.+With that said, we are currently still very far away from reaching that goal: So far, no effort+has been put into performance optimizations, as we are still working on implementing missing features.+However, this crate is currently the most comprehensive and feature-complete+implementation of a PDF rasterizer in pure Rust. This claim is supported by the fact that we currently+include over 1000 PDF files in our regression test suite. The majority of those have been scraped+from the `pdf.js` and `PDFBOX` test suites and therefore represent a very large and diverse sample+of PDF files.++As mentioned, there are still some serious limitations, including lack of support for+encrypted/password-protected PDF files, blending and isolation, knockout groups as well as a range+of smaller features such as color key masking. But you should be able to render the vast majority+of PDF files without too many issues.++### Safety+This crate forbids unsafe code via a crate-level attribute.++### Examples+For usage examples, see the [example](https://github.com/LaurenzV/hayro/tree/master/hayro/examples) in+the GitHub repository.++### Cargo features+This crate has one optional feature:+- `embed-fonts`: See the description of [`hayro-interpret`](https://docs.rs/hayro-interpret/latest/hayro_interpret/#cargo-features) for more information.++<!-- cargo-rdme end -->++## License+Licensed under either of++- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)+- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)++at your option.diff --git a/vendor/hayro/examples/render.rs b/vendor/hayro/examples/render.rsnew file mode 100644index 000000000..1e6ae24f0--- /dev/null+++ b/vendor/hayro/examples/render.rs@@ -0,0 +1,149 @@+//! This example shows you how you can render a PDF file to PNG.++use hayro::hayro_interpret::InterpreterSettings;+use hayro::hayro_interpret::font::{FontData, FontQuery, StandardFont};+use hayro::hayro_interpret::hayro_cmap::CidFamily;+use hayro::hayro_syntax::Pdf;+use hayro::{RenderCache, RenderSettings, render};+use std::path::Path;+use std::sync::Arc;+use vello_cpu::color::palette::css::WHITE;++fn load_asset(name: &str) -> Option<(FontData, u32)> {+ let base = Path::new(env!("CARGO_MANIFEST_DIR")).join("../hayro-tests/assets");+ let path = base.join(name);+ let data = std::fs::read(&path).ok()?;+ Some((Arc::new(data), 0))+}++fn main() {+ if let Ok(()) = log::set_logger(&LOGGER) {+ log::set_max_level(log::LevelFilter::Trace);+ }++ let file = std::fs::read(std::env::args().nth(1).unwrap()).unwrap();+ let output_dir = std::env::args().nth(2).unwrap_or_else(|| ".".to_string());+ let scale = std::env::args()+ .nth(3)+ .and_then(|s| s.parse::<f32>().ok())+ .unwrap_or(1.0);++ // Create output directory if it doesn't exist+ std::fs::create_dir_all(&output_dir).unwrap();++ let pdf = Pdf::new(file).unwrap();++ let interpreter_settings = InterpreterSettings {+ font_resolver: Arc::new(move |query| match query {+ FontQuery::Standard(s) => {+ let name = pick_standard_font(s);+ load_asset(name).or_else(|| Some(s.get_font_data()))+ }+ FontQuery::Fallback(f) => {+ if let Some(cc) = &f.character_collection {+ let name = match cc.family {+ CidFamily::AdobeGB1 | CidFamily::AdobeCNS1 => {+ if f.is_bold {+ "NotoSansCJKsc-Bold.otf"+ } else {+ "NotoSansCJKsc-Regular.otf"+ }+ }+ CidFamily::AdobeJapan1 => {+ if f.is_bold {+ "NotoSansCJKjp-Bold.otf"+ } else {+ "NotoSansCJKjp-Regular.otf"+ }+ }+ CidFamily::AdobeKorea1 => {+ if f.is_bold {+ "NotoSansCJKkr-Bold.otf"+ } else {+ "NotoSansCJKkr-Regular.otf"+ }+ }+ _ => {+ let name = pick_standard_font(&f.pick_standard_font());+ return load_asset(name)+ .or_else(|| Some(f.pick_standard_font().get_font_data()));+ }+ };++ if let Some(data) = load_asset(name) {+ return Some(data);+ }+ }++ let name = pick_standard_font(&f.pick_standard_font());+ load_asset(name).or_else(|| Some(f.pick_standard_font().get_font_data()))+ }+ }),+ ..Default::default()+ };++ let render_settings = RenderSettings {+ x_scale: scale,+ y_scale: scale,+ bg_color: WHITE,+ ..Default::default()+ };+ let cache = RenderCache::new();++ for (idx, page) in pdf.pages().iter().enumerate() {+ let pixmap = render(page, &cache, &interpreter_settings, &render_settings);+ let output_path = format!("{}/rendered_{idx}.png", output_dir);+ std::fs::write(output_path, pixmap.into_png().unwrap()).unwrap();+ }+}++fn pick_standard_font(font: &StandardFont) -> &'static str {+ match font {+ StandardFont::Helvetica => "LiberationSans-Regular.ttf",+ StandardFont::HelveticaBold => "LiberationSans-Bold.ttf",+ StandardFont::HelveticaOblique => "LiberationSans-Italic.ttf",+ StandardFont::HelveticaBoldOblique => "LiberationSans-BoldItalic.ttf",+ StandardFont::Courier => "LiberationMono-Regular.ttf",+ StandardFont::CourierBold => "LiberationMono-Bold.ttf",+ StandardFont::CourierOblique => "LiberationMono-Italic.ttf",+ StandardFont::CourierBoldOblique => "LiberationMono-BoldItalic.ttf",+ StandardFont::TimesRoman => "LiberationSerif-Regular.ttf",+ StandardFont::TimesBold => "LiberationSerif-Bold.ttf",+ StandardFont::TimesItalic => "LiberationSerif-Italic.ttf",+ StandardFont::TimesBoldItalic => "LiberationSerif-BoldItalic.ttf",+ StandardFont::ZapfDingBats => "FoxitDingbats.pfb",+ StandardFont::Symbol => "FoxitSymbol.pfb",+ }+}++/// A simple stderr logger.+static LOGGER: SimpleLogger = SimpleLogger;+struct SimpleLogger;+impl log::Log for SimpleLogger {+ fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {+ metadata.level() <= log::LevelFilter::Warn+ }++ fn log(&self, record: &log::Record<'_>) {+ if self.enabled(record.metadata()) {+ let target = if !record.target().is_empty() {+ record.target()+ } else {+ record.module_path().unwrap_or_default()+ };++ let line = record.line().unwrap_or(0);+ let args = record.args();++ match record.level() {+ log::Level::Error => eprintln!("Error (in {target}:{line}): {args}"),+ log::Level::Warn => eprintln!("Warning (in {target}:{line}): {args}"),+ log::Level::Info => eprintln!("Info (in {target}:{line}): {args}"),+ log::Level::Debug => eprintln!("Debug (in {target}:{line}): {args}"),+ log::Level::Trace => eprintln!("Trace (in {target}:{line}): {args}"),+ }+ }+ }++ fn flush(&self) {}+}diff --git a/vendor/hayro/src/lib.rs b/vendor/hayro/src/lib.rsnew file mode 100644index 000000000..d0637e35f--- /dev/null+++ b/vendor/hayro/src/lib.rs@@ -0,0 +1,224 @@+/*!+A crate for rendering PDF files.++This crate allows you to render pages of a PDF file into bitmaps. It is supposed to be relatively+lightweight, since we do not have any dependencies on the GPU. All the rendering happens on the CPU.++The ultimate goal of this crate is to be a *feature-complete* and *performant* PDF rasterizer.+With that said, we are currently still very far away from reaching that goal: So far, no effort+has been put into performance optimizations, as we are still working on implementing missing features.+However, this crate is currently the most comprehensive and feature-complete+implementation of a PDF rasterizer in pure Rust. This claim is supported by the fact that we currently+include over 1000 PDF files in our regression test suite. The majority of those have been scraped+from the `pdf.js` and `PDFBOX` test suites and therefore represent a very large and diverse sample+of PDF files.++As mentioned, there are still some serious limitations, including lack of support for+encrypted/password-protected PDF files, blending and isolation, knockout groups as well as a range+of smaller features such as color key masking. But you should be able to render the vast majority+of PDF files without too many issues.++## Safety+This crate forbids unsafe code via a crate-level attribute.++## Examples+For usage examples, see the [example](https://github.com/LaurenzV/hayro/tree/master/hayro/examples) in+the GitHub repository.++## Cargo features+This crate has one optional feature:+- `embed-fonts`: See the description of [`hayro-interpret`](https://docs.rs/hayro-interpret/latest/hayro_interpret/#cargo-features) for more information.+*/++#![forbid(unsafe_code)]+#![deny(missing_docs)]++use crate::renderer::Renderer;+use hayro_interpret::Device;+use hayro_interpret::FillRule;+use hayro_interpret::InterpreterCache;+use hayro_interpret::InterpreterSettings;+use hayro_interpret::hayro_syntax::Pdf;+use hayro_interpret::hayro_syntax::page::Page;+use hayro_interpret::util::{RectExt, TransformExt};+use hayro_interpret::{BlendMode, Context};+use hayro_interpret::{ClipPath, interpret_page};+use kurbo::{Affine, Rect, Shape};+use std::cell::RefCell;+use std::collections::HashMap;+use std::ops::RangeInclusive;+use std::rc::Rc;++pub use hayro_interpret;+pub use hayro_interpret::hayro_syntax;+pub use vello_cpu;++use vello_cpu::color::AlphaColor;+use vello_cpu::color::Srgb;+use vello_cpu::color::palette::css::TRANSPARENT;+use vello_cpu::color::palette::css::WHITE;+use vello_cpu::{Level, Pixmap, RenderMode};++mod renderer;++/// A cache used by the renderer.+///+/// Ideally, such a cache should be constructed once per PDF and then reused across+/// multiple render invocations on the same document.+#[derive(Clone, Default)]+pub struct RenderCache<'a> {+ pub(crate) interpreter_cache: InterpreterCache<'a>,+ pub(crate) outline_cache: Rc<RefCell<HashMap<u128, Rc<kurbo::BezPath>>>>,+}++impl<'a> RenderCache<'a> {+ /// Create a new render cache.+ pub fn new() -> Self {+ Self {+ interpreter_cache: InterpreterCache::new(),+ outline_cache: Rc::new(RefCell::new(HashMap::new())),+ }+ }+}++/// Settings to apply during rendering.+#[derive(Clone, Copy)]+pub struct RenderSettings {+ /// How much the contents should be scaled into the x direction.+ pub x_scale: f32,+ /// How much the contents should be scaled into the y direction.+ pub y_scale: f32,+ /// The width of the viewport. If this is set to `None`, the width will be chosen+ /// automatically based on the scale factor and the dimensions of the PDF.+ pub width: Option<u16>,+ /// The height of the viewport. If this is set to `None`, the height will be chosen+ /// automatically based on the scale factor and the dimensions of the PDF.+ pub height: Option<u16>,+ /// The background color. Determines the color of the base+ /// rectangle during rendering to a pixmap.+ pub bg_color: AlphaColor<Srgb>,+ /// PrintCraft patch: top-left corner of the rendered region, in device pixels of the scaled+ /// page. Together with `width`/`height` this renders one tile of a large page.+ pub x_offset: f32,+ /// See `x_offset`.+ pub y_offset: f32,+}++impl Default for RenderSettings {+ fn default() -> Self {+ Self {+ x_scale: 1.0,+ y_scale: 1.0,+ width: None,+ height: None,+ bg_color: TRANSPARENT,+ x_offset: 0.0,+ y_offset: 0.0,+ }+ }+}++/// Render the page with the given settings to a pixmap.+pub fn render<'a>(+ page: &'a Page<'a>,+ cache: &RenderCache<'a>,+ interpreter_settings: &InterpreterSettings,+ render_settings: &RenderSettings,+) -> Pixmap {+ let (x_scale, y_scale) = (render_settings.x_scale, render_settings.y_scale);+ let (width, height) = page.render_dimensions();+ let (scaled_width, scaled_height) = ((width * x_scale) as f64, (height * y_scale) as f64);+ let initial_transform = Affine::translate((-render_settings.x_offset as f64, -render_settings.y_offset as f64))+ * Affine::scale_non_uniform(x_scale as f64, y_scale as f64)+ * page.initial_transform(true).to_kurbo();++ let (pix_width, pix_height) = (+ render_settings.width.unwrap_or(scaled_width.floor() as u16),+ render_settings+ .height+ .unwrap_or(scaled_height.floor() as u16),+ );+ let mut state = Context::new(+ initial_transform,+ Rect::new(0.0, 0.0, pix_width as f64, pix_height as f64),+ &cache.interpreter_cache,+ page.xref(),+ interpreter_settings.clone(),+ );++ let vc_settings = vello_cpu::RenderSettings {+ level: Level::new(),+ num_threads: 0,+ render_mode: RenderMode::OptimizeSpeed,+ };++ let mut device = Renderer::new(pix_width, pix_height, vc_settings, cache);++ device.ctx.set_paint(render_settings.bg_color);+ device+ .ctx+ .fill_rect(&Rect::new(0.0, 0.0, pix_width as f64, pix_height as f64));+ let mut clip_path = page.intersected_crop_box().to_kurbo().to_path(0.1);+ clip_path.apply_affine(initial_transform);+ device.push_clip_path(&ClipPath {+ path: clip_path,+ fill: FillRule::NonZero,+ });++ device.push_transparency_group(1.0, None, BlendMode::Normal);+ interpret_page(page, &mut state, &mut device);++ device.pop_transparency_group();++ device.pop_clip_path();++ let mut pixmap = Pixmap::new(pix_width, pix_height);+ let mut resources = vello_cpu::Resources::default();+ device.ctx.render_to_pixmap(&mut resources, &mut pixmap);++ pixmap+}++// Just a convenience method for testing.+#[doc(hidden)]+pub fn render_pdf(+ pdf: &Pdf,+ scale: f32,+ settings: InterpreterSettings,+ range: Option<RangeInclusive<usize>>,+) -> Option<Vec<Pixmap>> {+ let cache = RenderCache::new();+ let rendered = pdf+ .pages()+ .iter()+ .enumerate()+ .flat_map(|(idx, page)| {+ if range.clone().is_some_and(|range| !range.contains(&idx)) {+ return None;+ }++ let pixmap = render(+ page,+ &cache,+ &settings,+ &RenderSettings {+ x_scale: scale,+ y_scale: scale,+ bg_color: WHITE,+ ..Default::default()+ },+ );++ Some(pixmap)+ })+ .collect();++ Some(rendered)+}++pub(crate) fn derive_settings(settings: &vello_cpu::RenderSettings) -> vello_cpu::RenderSettings {+ vello_cpu::RenderSettings {+ num_threads: 0,+ ..*settings+ }+}diff --git a/vendor/hayro/src/renderer.rs b/vendor/hayro/src/renderer.rsnew file mode 100644index 000000000..8e8824bcb--- /dev/null+++ b/vendor/hayro/src/renderer.rs@@ -0,0 +1,1141 @@+use crate::{RenderCache, derive_settings};+use hayro_interpret::encode::EncodedShadingPattern;+use hayro_interpret::font::Glyph;+use hayro_interpret::pattern::Pattern;+use hayro_interpret::{+ BlendMode, CacheKey, ClipPath, Device, FillRule, GlyphDrawMode, ImageData, LumaData, MaskType,+ Paint, PathDrawMode, RgbData, SoftMask, StrokeProps,+};+use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2};+use pic_scale::{+ ImageSize, ImageStore, ImageStoreMut, PicScaleError, Resampling, ResamplingFunction, Scaler,+};+use std::collections::HashMap;+use std::rc::Rc;+use std::sync::Arc;+use vello_cpu::color::palette::css::BLACK;+use vello_cpu::color::{AlphaColor, PremulRgba8, Srgb};+use vello_cpu::peniko::{Compose, Fill, ImageQuality, ImageSampler, Mix};+use vello_cpu::{+ Image, ImageSource, Mask, PaintType, Pixmap, RenderContext, RenderSettings, peniko,+};++pub(crate) struct Renderer {+ pub(crate) ctx: RenderContext,+ pub(crate) inside_pattern: bool,+ pub(crate) soft_mask_cache: HashMap<u128, Mask>,+ pub(crate) outline_cache: Rc<std::cell::RefCell<HashMap<u128, Rc<BezPath>>>>,+ pub(crate) cur_mask: Option<Mask>,+ pub(crate) in_type3_glyph: bool,+ pub(crate) scaler: Scaler,+ // TODO: Remove this once vello_cpu bug with non-transparent images is fixed+ image_transparency_stack: Vec<bool>,+}++#[derive(Clone, Copy)]+enum ImagePixelFormat {+ Luma,+ Rgb,+ Rgba,+}++impl Renderer {+ pub(crate) fn new(+ width: u16,+ height: u16,+ settings: RenderSettings,+ cache: &RenderCache<'_>,+ ) -> Self {+ Self {+ ctx: RenderContext::new_with(width, height, settings),+ inside_pattern: false,+ soft_mask_cache: HashMap::default(),+ outline_cache: cache.outline_cache.clone(),+ cur_mask: None,+ in_type3_glyph: false,+ scaler: Scaler::new(ResamplingFunction::CatmullRom),+ image_transparency_stack: Vec::new(),+ }+ }++ fn set_stroke_properties(&mut self, stroke_props: &StrokeProps, is_text: bool) {+ let threshold = if is_text { 0.25 } else { 1.0 };++ // Best-effort attempt to ensure a line width of at least 1.0, as required by the PDF+ // specification. If we are stroking text, we reduce the threshold as it will otherwise+ // lead to very bold-looking text at low resolutions.+ let min_factor = max_factor(self.ctx.transform());+ let mut line_width = stroke_props.line_width.max(0.01);+ let transformed_width = line_width * min_factor;++ // Only enforce line width if not inside of pattern or type 3 glyph.+ if transformed_width < threshold && !self.inside_pattern && !self.in_type3_glyph {+ line_width /= transformed_width;+ line_width *= threshold;+ }++ let stroke = kurbo::Stroke {+ width: line_width as f64,+ join: stroke_props.line_join,+ miter_limit: stroke_props.miter_limit as f64,+ start_cap: stroke_props.line_cap,+ end_cap: stroke_props.line_cap,+ dash_pattern: stroke_props.dash_array.iter().map(|n| *n as f64).collect(),+ dash_offset: stroke_props.dash_offset as f64,+ };++ self.ctx.set_stroke(stroke);+ }++ fn draw_image_with_alpha_mask(&mut self, image_data: ImageData, alpha_data: LumaData) {+ let mask = {+ let transform = *self.ctx.transform()+ * Affine::scale_non_uniform(+ image_data.width() as f64 / alpha_data.width as f64,+ image_data.height() as f64 / alpha_data.height as f64,+ );+ let mut renderer = Self {+ ctx: RenderContext::new_with(+ self.ctx.width(),+ self.ctx.height(),+ derive_settings(self.ctx.render_settings()),+ ),+ inside_pattern: false,+ soft_mask_cache: HashMap::default(),+ outline_cache: self.outline_cache.clone(),+ cur_mask: None,+ in_type3_glyph: false,+ scaler: self.scaler,+ image_transparency_stack: Vec::new(),+ };+ let mut mask_pix = Pixmap::new(self.ctx.width(), self.ctx.height());+ let rgb_data = ImageData::Rgb(RgbData {+ data: vec![0; alpha_data.width as usize * alpha_data.height as usize * 3],+ width: alpha_data.width,+ height: alpha_data.height,+ interpolate: alpha_data.interpolate,+ scale_factors: alpha_data.scale_factors,+ });+ renderer.ctx.set_transform(transform);+ // Note that there is a circle between `draw_image` and `draw_image_with_alpha_mask`,+ // but `draw_image_with_alpha_mask` is only called if the dimensions or interpolate+ // values between alpha_data and rgb_data don't match, which they do here.+ renderer.draw_image(rgb_data, Some(alpha_data));+ renderer.ctx.flush();+ let mut resources = vello_cpu::Resources::default();+ renderer.ctx.render_to_pixmap(&mut resources, &mut mask_pix);+ Mask::new_alpha(&mask_pix)+ };++ self.ctx.push_mask_layer(mask);+ self.image_transparency_stack.push(true);+ self.draw_image(image_data, None);+ self.image_transparency_stack.pop();+ self.ctx.pop_layer();+ }++ fn resize_image_data(+ &self,+ data: Vec<u8>,+ src_width: u32,+ src_height: u32,+ new_width: u32,+ new_height: u32,+ pixel_format: ImagePixelFormat,+ ) -> Vec<u8> {+ match pixel_format {+ ImagePixelFormat::Luma => self.resize_image_data_impl::<1>(+ data,+ src_width,+ src_height,+ new_width,+ new_height,+ |scaler, source_size, target_size| {+ scaler.plan_planar_resampling(source_size, target_size)+ },+ ),+ ImagePixelFormat::Rgb => self.resize_image_data_impl::<3>(+ data,+ src_width,+ src_height,+ new_width,+ new_height,+ |scaler, source_size, target_size| {+ scaler.plan_rgb_resampling(source_size, target_size)+ },+ ),+ ImagePixelFormat::Rgba => self.resize_image_data_impl::<4>(+ data,+ src_width,+ src_height,+ new_width,+ new_height,+ |scaler, source_size, target_size| {+ scaler.plan_rgba_resampling(source_size, target_size, true)+ },+ ),+ }+ }++ fn resize_image_data_impl<const N: usize>(+ &self,+ data: Vec<u8>,+ src_width: u32,+ src_height: u32,+ new_width: u32,+ new_height: u32,+ plan: impl FnOnce(+ &Scaler,+ ImageSize,+ ImageSize,+ ) -> Result<Arc<Resampling<u8, N>>, PicScaleError>,+ ) -> Vec<u8> {+ let source_size = ImageSize::new(src_width as usize, src_height as usize);+ let target_size = ImageSize::new(new_width as usize, new_height as usize);+ let src = ImageStore::<u8, N>::from_slice(&data, src_width as usize, src_height as usize)+ .unwrap();+ let mut out = vec![0; new_width as usize * new_height as usize * N];+ let mut dst =+ ImageStoreMut::<u8, N>::from_slice(&mut out, new_width as usize, new_height as usize)+ .unwrap();+ let plan = plan(&self.scaler, source_size, target_size).unwrap();+ plan.resample(&src, &mut dst).unwrap();+ out+ }++ fn draw_image(&mut self, image_data: ImageData, alpha_data: Option<LumaData>) {+ let cur_transform = *self.ctx.transform();+ let mut additional_transform = Affine::IDENTITY;++ let (x_scale, y_scale) = {+ let (x, y) = x_y_advances(&cur_transform);+ (x.length() as f32, y.length() as f32)+ };+ let mut img_width = image_data.width();+ let mut img_height = image_data.height();+ let interpolate = image_data.interpolate();++ if let Some(a) = &alpha_data+ && (a.width != img_width || a.height != img_height || a.interpolate != interpolate)+ {+ return self.draw_image_with_alpha_mask(image_data, alpha_data.unwrap());+ }++ let mut quality = if interpolate {+ ImageQuality::Medium+ } else {+ ImageQuality::Low+ };++ let has_alpha = alpha_data.is_some();+ let mut may_have_transparency = has_alpha || self.force_images_may_have_transparency();+ let needs_resize = x_scale < 1.0 || y_scale < 1.0;+ let (new_width, new_height) = if needs_resize {+ let w = (img_width as f32 * x_scale)+ .ceil()+ .max(1.0)+ .min((u16::MAX / 2) as f32) as u32;+ let h = (img_height as f32 * y_scale)+ .ceil()+ .max(1.0)+ .min((u16::MAX / 2) as f32) as u32;+ if self.in_type3_glyph {+ quality = ImageQuality::High;+ }+ (w, h)+ } else {+ (img_width, img_height)+ };++ // For luma images without alpha, we can resize as single-channel and+ // expand to RGBA afterwards, which is ~4x faster.+ let mut rgba_data = if matches!(&image_data, ImageData::Luma(_)) && !has_alpha {+ // We cannot lift this up due to borrowing issues.+ let ImageData::Luma(luma) = image_data else {+ unreachable!()+ };++ let luma_data = if !needs_resize {+ luma.data+ } else {+ let resized = self.resize_image_data(+ luma.data,+ img_width,+ img_height,+ new_width,+ new_height,+ ImagePixelFormat::Luma,+ );+ additional_transform = Affine::scale_non_uniform(+ img_width as f64 / new_width as f64,+ img_height as f64 / new_height as f64,+ );+ img_width = new_width;+ img_height = new_height;+ resized+ };++ luma_data+ .iter()+ .flat_map(|g| [*g, *g, *g, 255])+ .collect::<Vec<_>>()+ } else if matches!(&image_data, ImageData::Rgb(_)) && !has_alpha && needs_resize {+ let ImageData::Rgb(rgb) = image_data else {+ unreachable!()+ };++ let resized = self.resize_image_data(+ rgb.data,+ img_width,+ img_height,+ new_width,+ new_height,+ ImagePixelFormat::Rgb,+ );+ additional_transform = Affine::scale_non_uniform(+ img_width as f64 / new_width as f64,+ img_height as f64 / new_height as f64,+ );+ img_width = new_width;+ img_height = new_height;++ let mut out = Vec::with_capacity((img_width * img_height) as usize * 4);+ for px in resized.chunks_exact(3) {+ out.extend_from_slice(&[px[0], px[1], px[2], 255]);+ }+ out+ } else {+ let (rgb_data, alpha_data) = match image_data {+ ImageData::Rgb(rgb) => (rgb.data, alpha_data.map(|a| a.data)),+ ImageData::Luma(luma) => {+ let rgb = luma+ .data+ .iter()+ .flat_map(|g| [*g, *g, *g])+ .collect::<Vec<_>>();+ (rgb, alpha_data.map(|a| a.data))+ }+ };++ let rgba_data = match alpha_data {+ None => rgb_data+ .chunks_exact(3)+ .flat_map(|rgb| [rgb[0], rgb[1], rgb[2], 255])+ .collect::<Vec<_>>(),+ Some(alpha) => rgb_data+ .chunks_exact(3)+ .zip(alpha)+ .flat_map(|(rgb, a)| [rgb[0], rgb[1], rgb[2], a])+ .collect::<Vec<_>>(),+ };++ if !needs_resize {+ rgba_data+ } else {+ let resized = self.resize_image_data(+ rgba_data,+ img_width,+ img_height,+ new_width,+ new_height,+ ImagePixelFormat::Rgba,+ );+ additional_transform = Affine::scale_non_uniform(+ img_width as f64 / new_width as f64,+ img_height as f64 / new_height as f64,+ );+ img_width = new_width;+ img_height = new_height;+ resized+ }+ };++ if has_alpha {+ let (chunks, _) = rgba_data.as_chunks_mut::<4>();+ for chunk in chunks {+ *chunk = AlphaColor::from_rgba8(chunk[0], chunk[1], chunk[2], chunk[3])+ .premultiply()+ .to_rgba8()+ .to_u8_array();+ }+ }++ // The problem is that by default, when applying a bilinear or bicubic scaling, we will+ // sample pixels using an extend (pad/reflect/repeat). For glyphs, this is undesirable+ // as the glyphs will look very bold. Therefore, for glyphs it is more desirable to sample+ // a transparent pixel when reaching the border. Thus, we wrap glyphs in a transparent frame+ // of pixel width 2.+ if self.in_type3_glyph {+ let mut padded_image = vec![];+ padded_image.extend(vec![0; (4 * img_width as usize + 16) * 2]);++ for row in rgba_data.chunks_exact(img_width as usize * 4) {+ padded_image.extend([0; 8]);+ padded_image.extend(row);+ padded_image.extend([0; 8]);+ }++ padded_image.extend(vec![0; (4 * img_width as usize + 16) * 2]);+ img_width += 4;+ img_height += 4;+ additional_transform *= Affine::translate((-2.0, -2.0));+ may_have_transparency = true;++ rgba_data = padded_image;+ }++ let pixmap = Pixmap::from_parts_with_opacity(+ bytemuck::cast_vec(rgba_data),+ img_width as u16,+ img_height as u16,+ may_have_transparency,+ );++ self.draw_pixmap(+ Arc::new(pixmap),+ quality,+ cur_transform * additional_transform,+ );+ }++ fn push_clip_path_inner(&mut self, clip_path: &BezPath, fill: FillRule) {+ let old_transform = *self.ctx.transform();++ self.ctx.set_fill_rule(convert_fill_rule(fill));+ self.ctx.set_transform(Affine::IDENTITY);+ self.ctx.push_clip_path(clip_path);++ self.ctx.set_transform(old_transform);+ }++ fn draw_pixmap(&mut self, pixmap: Arc<Pixmap>, quality: ImageQuality, transform: Affine) {+ let (width, height) = (pixmap.width(), pixmap.height());+ let image = Image {+ image: ImageSource::Pixmap(pixmap),+ sampler: ImageSampler {+ x_extend: peniko::Extend::Pad,+ y_extend: peniko::Extend::Pad,+ quality,+ alpha: 1.0,+ },+ };++ self.ctx.set_transform(transform);+ self.ctx.set_paint(image);+ self.ctx+ .fill_rect(&Rect::new(0.0, 0.0, width as f64, height as f64));+ }++ #[must_use]+ fn set_paint(&mut self, paint: &Paint<'_>, path: &BezPath, is_stroke: bool) -> Option<BezPath> {+ let mut paint_transform = Affine::IDENTITY;+ let mut clip_path = None;++ let paint: PaintType = match paint.clone() {+ Paint::Color(c) => {+ let c = c.to_rgba().to_rgba8();+ AlphaColor::from_rgba8(c[0], c[1], c[2], c[3]).into()+ }+ Paint::Pattern(p) => {+ let path_transform = self.ctx.transform();++ match *p {+ Pattern::Shading(s) => {+ clip_path = s.shading.clip_path.clone();+ let mut bbox = (*path_transform * path.clone()).bounding_box();++ if is_stroke {+ // Try to account for stroke in bbox.+ let (a1, a2) = x_y_advances(path_transform);+ let factor = a1.length().max(a2.length()) * self.ctx.stroke().width;+ bbox = bbox.inflate(factor, factor);+ }++ bbox = bbox.intersect(Rect::new(+ 0.0,+ 0.0,+ self.ctx.width() as f64,+ self.ctx.height() as f64,+ ));++ let encoded = s.encode();+ let (image, width, height, transform, may_have_transparency) =+ render_shading_texture(bbox, &encoded);+ let may_have_transparency =+ may_have_transparency || self.force_images_may_have_transparency();+ paint_transform = path_transform.inverse() * transform;++ let pixmap = Pixmap::from_parts_with_opacity(+ image,+ width as u16,+ height as u16,+ may_have_transparency,+ );++ let image = Image {+ image: ImageSource::Pixmap(Arc::new(pixmap)),+ sampler: ImageSampler {+ x_extend: peniko::Extend::Repeat,+ y_extend: peniko::Extend::Repeat,+ quality: ImageQuality::Medium,+ alpha: 1.0,+ },+ };++ PaintType::Image(image)+ }+ Pattern::Tiling(t) => {+ const MAX_PIXMAP_SIZE: f32 = 3000.0;+ // TODO: Raise this limit and perform downsampling if reached+ // (see pdftc_100k_0138.pdf).+ const MIN_PIXMAP_SIZE: f32 = 1.0;++ let bbox = t.bbox;+ let max_x_scale = MAX_PIXMAP_SIZE / bbox.width() as f32;+ let min_x_scale = MIN_PIXMAP_SIZE / bbox.width() as f32;+ let max_y_scale = MAX_PIXMAP_SIZE / bbox.height() as f32;+ let min_y_scale = MIN_PIXMAP_SIZE / bbox.height() as f32;++ let (mut xs, mut ys) = {+ let (x, y) = x_y_advances(&(t.matrix));+ (x.length() as f32, y.length() as f32)+ };+ xs = xs.max(min_x_scale).min(max_x_scale);+ ys = ys.max(min_y_scale).min(max_y_scale);++ let x_step = xs * t.x_step;+ let y_step = ys * t.y_step;++ let scaled_width = bbox.width() as f32 * xs;+ let scaled_height = bbox.height() as f32 * ys;+ let pix_width = x_step.abs().round() as u16;+ let pix_height = y_step.abs().round() as u16;++ let mut renderer = Self {+ ctx: RenderContext::new_with(+ pix_width,+ pix_height,+ derive_settings(self.ctx.render_settings()),+ ),+ cur_mask: None,+ inside_pattern: true,+ soft_mask_cache: HashMap::default(),+ outline_cache: self.outline_cache.clone(),+ in_type3_glyph: false,+ scaler: self.scaler,+ image_transparency_stack: Vec::new(),+ };+ let mut initial_transform = Affine::scale_non_uniform(xs as f64, ys as f64)+ * Affine::translate((-bbox.x0, -bbox.y0));+ t.interpret(&mut renderer, initial_transform, is_stroke);+ let mut pix = Pixmap::new(pix_width, pix_height);+ renderer.ctx.flush();+ let mut resources = vello_cpu::Resources::default();+ renderer.ctx.render_to_pixmap(&mut resources, &mut pix);++ // TODO: Fix these+ if x_step < 0.0 {+ initial_transform *=+ Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width as f64, 0.0]);+ }++ if y_step < 0.0 {+ initial_transform *=+ Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height as f64]);+ }++ paint_transform =+ path_transform.inverse() * t.matrix * initial_transform.inverse();++ let image = Image {+ image: ImageSource::Pixmap(Arc::new(pix)),+ sampler: ImageSampler {+ x_extend: peniko::Extend::Repeat,+ y_extend: peniko::Extend::Repeat,+ quality: ImageQuality::Medium,+ alpha: 1.0,+ },+ };++ PaintType::Image(image)+ }+ }+ }+ };++ self.ctx.set_paint_transform(paint_transform);+ self.ctx.set_paint(paint);++ clip_path+ }++ fn stroke_path(+ &mut self,+ path: &BezPath,+ transform: Affine,+ paint: &Paint<'_>,+ stroke_props: &StrokeProps,+ is_text: bool,+ ) {+ self.ctx.set_transform(transform);+ self.set_stroke_properties(stroke_props, is_text);++ let clip_path = self.set_paint(paint, path, true);+ if let Some(clip_path) = clip_path.as_ref() {+ self.push_clip_path_inner(clip_path, FillRule::NonZero);+ }+ self.ctx.stroke_path(path);+ if clip_path.is_some() {+ self.ctx.pop_clip_path();+ }+ }++ fn fill_path(+ &mut self,+ path: &BezPath,+ transform: Affine,+ paint: &Paint<'_>,+ fill_rule: FillRule,+ ) {+ self.ctx.set_fill_rule(convert_fill_rule(fill_rule));+ self.ctx.set_transform(transform);++ let clip_path = self.set_paint(paint, path, false);+ if let Some(clip_path) = clip_path.as_ref() {+ self.push_clip_path_inner(clip_path, fill_rule);+ }++ self.ctx.fill_path(path);++ if clip_path.is_some() {+ self.ctx.pop_clip_path();+ }+ }++ fn fill_glyph<'a>(+ &mut self,+ glyph: &Glyph<'a>,+ transform: Affine,+ glyph_transform: Affine,+ paint: &Paint<'a>,+ ) {+ match glyph {+ Glyph::Outline(o) => {+ let base_outline = self.cached_outline(o);++ self.fill_path(+ base_outline.as_ref(),+ transform * glyph_transform,+ paint,+ FillRule::NonZero,+ );+ }+ Glyph::Type3(s) => {+ self.in_type3_glyph = true;+ s.interpret(self, transform, glyph_transform, paint);+ self.in_type3_glyph = false;+ }+ }+ }++ fn stroke_glyph<'a>(+ &mut self,+ glyph: &Glyph<'a>,+ transform: Affine,+ glyph_transform: Affine,+ paint: &Paint<'a>,+ stroke_props: &StrokeProps,+ ) {+ match glyph {+ Glyph::Outline(o) => {+ let base_outline = self.cached_outline(o);++ self.stroke_path(+ &(glyph_transform * base_outline.as_ref().clone()),+ transform,+ paint,+ stroke_props,+ true,+ );+ }+ Glyph::Type3(s) => {+ s.interpret(self, transform, glyph_transform, paint);+ }+ }+ }++ fn cached_outline(&self, glyph: &hayro_interpret::font::OutlineGlyph) -> Rc<BezPath> {+ let id = glyph.identifier().cache_key();++ if let Some(path) = self.outline_cache.borrow().get(&id) {+ return path.clone();+ }++ let path = Rc::new(glyph.outline());+ self.outline_cache.borrow_mut().insert(id, path.clone());+ path+ }++ fn force_images_may_have_transparency(&self) -> bool {+ self.cur_mask.is_some()+ || self+ .image_transparency_stack+ .last()+ .copied()+ .unwrap_or(false)+ || self.ctx.blend_mode() != peniko::BlendMode::default()+ }+}++impl<'a> Device<'a> for Renderer {+ fn draw_image(&mut self, image: hayro_interpret::Image<'a, '_>, mut transform: Affine) {+ self.ctx.set_paint_transform(Affine::IDENTITY);+ self.ctx.set_aliasing_threshold(Some(1));++ let target_width = (transform * Point::new(image.width() as f64, 0.0))+ .to_vec2()+ .length()+ .ceil() as u32;+ let target_height = (transform * Point::new(0.0, image.height() as f64))+ .to_vec2()+ .length()+ .ceil() as u32;++ match image {+ hayro_interpret::Image::Stencil(s) => {+ s.with_stencil(+ |stencil, paint| {+ transform *= Affine::scale_non_uniform(+ stencil.scale_factors.0 as f64,+ stencil.scale_factors.1 as f64,+ );++ match paint {+ Paint::Color(c) => {+ let color = c.to_rgba().to_rgba8();+ let (rgb_bytes, alpha) = (+ stencil+ .data+ .iter()+ .flat_map(|_| [color[0], color[1], color[2]])+ .collect::<Vec<u8>>(),+ color[3],+ );++ let blend_mode = self.ctx.blend_mode();+ let push_layer =+ alpha != 255 || blend_mode != peniko::BlendMode::default();+ self.ctx.set_transform(transform);+ if push_layer {+ self.ctx.push_layer(+ None,+ Some(blend_mode),+ Some(alpha as f32 / 255.0),+ None,+ None,+ );+ }+ let old_rule = *self.ctx.fill_rule();+ self.ctx.set_fill_rule(Fill::NonZero);++ let rgb_data = ImageData::Rgb(RgbData {+ data: rgb_bytes,+ width: stencil.width,+ height: stencil.height,+ interpolate: stencil.interpolate,+ scale_factors: stencil.scale_factors,+ });+ self.draw_image(rgb_data, Some(stencil));++ if push_layer {+ self.ctx.pop_layer();+ }++ self.ctx.set_fill_rule(old_rule);+ }+ Paint::Pattern(_) => {+ let (width, height) = (self.ctx.width(), self.ctx.height());+ let stencil_rect = Rect::new(+ 0.0,+ 0.0,+ stencil.width as f64,+ stencil.height as f64,+ );+ let mask_pix = {+ let rgb_bytes = ImageData::Rgb(RgbData {+ data: vec![+ 255;+ stencil.width as usize+ * stencil.height as usize+ * 3+ ],+ width: stencil.width,+ height: stencil.height,+ interpolate: stencil.interpolate,+ scale_factors: stencil.scale_factors,+ });+ let mut sub_renderer = Self {+ ctx: RenderContext::new_with(+ width,+ height,+ derive_settings(self.ctx.render_settings()),+ ),+ inside_pattern: false,+ soft_mask_cache: HashMap::default(),+ outline_cache: self.outline_cache.clone(),+ cur_mask: None,+ in_type3_glyph: false,+ scaler: self.scaler,+ image_transparency_stack: Vec::new(),+ };+ let mut sub_pix = Pixmap::new(width, height);+ sub_renderer.ctx.set_transform(transform);+ sub_renderer.draw_image(rgb_bytes, Some(stencil));+ sub_renderer.ctx.flush();+ let mut resources = vello_cpu::Resources::default();+ sub_renderer+ .ctx+ .render_to_pixmap(&mut resources, &mut sub_pix);+ sub_pix+ };++ self.ctx.push_layer(+ None,+ Some(self.ctx.blend_mode()),+ None,+ Some(Mask::new_luminance(&mask_pix)),+ None,+ );+ self.ctx.set_transform(transform);++ let clip_path =+ self.set_paint(paint, &stencil_rect.to_path(0.1), true);+ if let Some(clip_path) = clip_path.as_ref() {+ self.push_clip_path_inner(clip_path, FillRule::NonZero);+ }+ self.ctx.fill_rect(&stencil_rect);+ if clip_path.is_some() {+ self.ctx.pop_clip_path();+ }++ self.ctx.pop_layer();+ }+ };+ },+ Some((target_width, target_height)),+ );+ }+ hayro_interpret::Image::Raster(r) => {+ r.with_rgba(+ |image, alpha| {+ let (sx, sy) = image.scale_factors();+ transform *= Affine::scale_non_uniform(sx as f64, sy as f64);+ self.ctx.set_transform(transform);+ self.draw_image(image, alpha);+ },+ Some((target_width, target_height)),+ );+ }+ }++ self.ctx.set_aliasing_threshold(None);+ }++ fn push_clip_path(&mut self, clip_path: &ClipPath) {+ self.push_clip_path_inner(&clip_path.path, clip_path.fill);+ }++ fn push_transparency_group(+ &mut self,+ opacity: f32,+ mask: Option<SoftMask<'_>>,+ blend_mode: BlendMode,+ ) {+ let settings = *self.ctx.render_settings();+ let force_images_may_have_transparency = mask.is_some()+ || blend_mode != BlendMode::Normal+ || self+ .image_transparency_stack+ .last()+ .copied()+ .unwrap_or(false);+ self.ctx.push_layer(+ None,+ Some(convert_blend_mode(blend_mode)),+ Some(opacity),+ // TODO: Deduplicate+ mask.map(|m| {+ let width = self.ctx.width();+ let height = self.ctx.height();++ self.soft_mask_cache+ .entry(m.cache_key())+ .or_insert_with(|| draw_soft_mask(&m, settings, width, height))+ .clone()+ }),+ None,+ );+ self.image_transparency_stack+ .push(force_images_may_have_transparency);+ }++ fn pop_clip_path(&mut self) {+ self.ctx.pop_clip_path();+ }++ fn pop_transparency_group(&mut self) {+ self.image_transparency_stack.pop();+ self.ctx.pop_layer();+ }++ fn set_soft_mask(&mut self, mask: Option<SoftMask<'_>>) {+ let settings = *self.ctx.render_settings();+ self.cur_mask = mask.map(|m| {+ let width = self.ctx.width();+ let height = self.ctx.height();++ self.soft_mask_cache+ .entry(m.cache_key())+ .or_insert_with(|| draw_soft_mask(&m, settings, width, height))+ .clone()+ });+ if let Some(mask) = self.cur_mask.clone() {+ self.ctx.set_mask(mask);+ } else {+ self.ctx.reset_mask();+ }+ }++ fn draw_path(+ &mut self,+ path: &BezPath,+ transform: Affine,+ paint: &Paint<'_>,+ draw_mode: &PathDrawMode,+ ) {+ match draw_mode {+ PathDrawMode::Fill(f) => {+ Self::fill_path(self, path, transform, paint, *f);+ }+ PathDrawMode::Stroke(s) => {+ Self::stroke_path(self, path, transform, paint, s, false);+ }+ }+ }++ fn draw_rect(+ &mut self,+ rect: &Rect,+ transform: Affine,+ paint: &Paint<'_>,+ draw_mode: &PathDrawMode,+ ) {+ let path = rect.to_path(0.1);+ match draw_mode {+ PathDrawMode::Fill(fill_rule) => {+ self.ctx.set_fill_rule(convert_fill_rule(*fill_rule));+ self.ctx.set_transform(transform);++ let clip_path = self.set_paint(paint, &path, false);+ if let Some(clip_path) = clip_path.as_ref() {+ self.push_clip_path_inner(clip_path, *fill_rule);+ }++ self.ctx.fill_rect(rect);++ if clip_path.is_some() {+ self.ctx.pop_clip_path();+ }+ }+ PathDrawMode::Stroke(s) => {+ Self::stroke_path(self, &path, transform, paint, s, false);+ }+ }+ }++ fn draw_glyph(+ &mut self,+ glyph: &Glyph<'a>,+ transform: Affine,+ glyph_transform: Affine,+ paint: &Paint<'a>,+ draw_mode: &GlyphDrawMode,+ ) {+ match draw_mode {+ GlyphDrawMode::Fill => {+ Self::fill_glyph(self, glyph, transform, glyph_transform, paint);+ }+ GlyphDrawMode::Stroke(s) => {+ Self::stroke_glyph(self, glyph, transform, glyph_transform, paint, s);+ }+ GlyphDrawMode::Invisible => {+ // Don't render invisible text for visual output+ }+ }+ }++ fn set_blend_mode(&mut self, blend_mode: BlendMode) {+ self.ctx.set_blend_mode(convert_blend_mode(blend_mode));+ }+}++// TODO: Deduplicate with hayro-svg?+fn render_shading_texture(+ path_bbox: Rect,+ shading_pattern: &EncodedShadingPattern,+) -> (Vec<PremulRgba8>, u32, u32, Affine, bool) {+ let base_width = (path_bbox.width() as f32).max(1.0);+ let base_height = (path_bbox.height() as f32).max(1.0);++ let width = (base_width).ceil() as u32;+ let height = (base_height).ceil() as u32;++ let (x_advance, y_advance) = x_y_advances(&shading_pattern.base_transform);++ let mut buf = vec![PremulRgba8::from_u32(0); width as usize * height as usize];+ let mut start_point = shading_pattern.base_transform+ * Affine::translate((0.5, 0.5))+ * Point::new(path_bbox.x0, path_bbox.y0);+ let mut may_have_transparency = false;++ for row in buf.chunks_exact_mut(width as usize) {+ let mut point = start_point;++ for pixel in row {+ let sample = shading_pattern.sample(point);+ *pixel = AlphaColor::<Srgb>::new(sample).premultiply().to_rgba8();+ may_have_transparency |= pixel.a != 255;++ point += x_advance;+ }++ start_point += y_advance;+ }++ (+ buf,+ width,+ height,+ Affine::translate((path_bbox.x0, path_bbox.y0)),+ may_have_transparency,+ )+}++fn draw_soft_mask(mask: &SoftMask<'_>, settings: RenderSettings, width: u16, height: u16) -> Mask {+ let mut renderer = Renderer {+ ctx: RenderContext::new_with(width, height, derive_settings(&settings)),+ inside_pattern: false,+ cur_mask: None,+ soft_mask_cache: HashMap::default(),+ outline_cache: Rc::new(std::cell::RefCell::new(HashMap::new())),+ in_type3_glyph: false,+ scaler: Scaler::new(ResamplingFunction::CatmullRom),+ image_transparency_stack: Vec::new(),+ };++ let bg_color = mask.background_color().to_rgba();+ let apply_bg = bg_color.to_rgba8() != BLACK.to_rgba8().to_u8_array();++ if apply_bg {+ renderer+ .ctx+ .set_paint(AlphaColor::<Srgb>::new(bg_color.components()));+ renderer+ .ctx+ .fill_rect(&Rect::new(0.0, 0.0, width as f64, height as f64));+ renderer.ctx.push_layer(None, None, None, None, None);+ }++ mask.interpret(&mut renderer);++ if apply_bg {+ renderer.ctx.pop_layer();+ }++ let mut pix = Pixmap::new(width, height);+ renderer.ctx.flush();+ let mut resources = vello_cpu::Resources::default();+ renderer.ctx.render_to_pixmap(&mut resources, &mut pix);++ let mut rendered_mask = match mask.mask_type() {+ MaskType::Luminosity => Mask::new_luminance(&pix),+ MaskType::Alpha => Mask::new_alpha(&pix),+ };++ if let Some(transfer_function) = mask.transfer_function() {+ let mut map = Vec::new();++ for y in 0..rendered_mask.height() {+ for x in 0..rendered_mask.width() {+ map.push(+ (transfer_function.apply(rendered_mask.sample(x, y) as f32 / 255.0) * 255.0+ + 0.5) as u8,+ );+ }+ }++ rendered_mask = Mask::from_parts(map, rendered_mask.width(), rendered_mask.height());+ }++ rendered_mask+}++pub(crate) fn max_factor(transform: &Affine) -> f32 {+ let scale_skew_transform = {+ let c = transform.as_coeffs();+ Affine::new([c[0], c[1], c[2], c[3], 0.0, 0.0])+ };++ let x_advance = scale_skew_transform * Point::new(1.0, 0.0);+ let y_advance = scale_skew_transform * Point::new(0.0, 1.0);++ x_advance+ .to_vec2()+ .length()+ .max(y_advance.to_vec2().length()) as f32+}++pub(crate) fn x_y_advances(transform: &Affine) -> (Vec2, Vec2) {+ let scale_skew_transform = {+ let c = transform.as_coeffs();+ Affine::new([c[0], c[1], c[2], c[3], 0.0, 0.0])+ };++ let x_advance = scale_skew_transform * Point::new(1.0, 0.0);+ let y_advance = scale_skew_transform * Point::new(0.0, 1.0);++ (+ Vec2::new(x_advance.x, x_advance.y),+ Vec2::new(y_advance.x, y_advance.y),+ )+}++fn convert_fill_rule(fill_rule: FillRule) -> Fill {+ match fill_rule {+ FillRule::NonZero => Fill::NonZero,+ FillRule::EvenOdd => Fill::EvenOdd,+ }+}++fn convert_blend_mode(blend_mode: BlendMode) -> peniko::BlendMode {+ let mix = match blend_mode {+ BlendMode::Normal => Mix::Normal,+ BlendMode::Multiply => Mix::Multiply,+ BlendMode::Screen => Mix::Screen,+ BlendMode::Overlay => Mix::Overlay,+ BlendMode::Darken => Mix::Darken,+ BlendMode::Lighten => Mix::Lighten,+ BlendMode::ColorDodge => Mix::ColorDodge,+ BlendMode::ColorBurn => Mix::ColorBurn,+ BlendMode::HardLight => Mix::HardLight,+ BlendMode::SoftLight => Mix::SoftLight,+ BlendMode::Difference => Mix::Difference,+ BlendMode::Exclusion => Mix::Exclusion,+ BlendMode::Hue => Mix::Hue,+ BlendMode::Saturation => Mix::Saturation,+ BlendMode::Color => Mix::Color,+ BlendMode::Luminosity => Mix::Luminosity,+ };++ peniko::BlendMode::new(mix, Compose::SrcOver)+}diff --git a/xtask/Cargo.toml b/xtask/Cargo.tomlindex 21464bc3c..59e0318a4 100644--- a/xtask/Cargo.toml+++ b/xtask/Cargo.toml@@ -9,3 +9,4 @@ license = "MIT OR Apache-2.0"anyhow = "1"lopdf = "0.45"png = "0.18"+serde_json = "1"diff --git a/xtask/baselines/pdfjs.json b/xtask/baselines/pdfjs.jsonnew file mode 100644index 000000000..a441ad872--- /dev/null+++ b/xtask/baselines/pdfjs.json@@ -0,0 +1,22 @@+{+ "Brotli-Prototype-FileA.pdf": "open-error",+ "REDHAT-1531897-0.pdf": "open-error",+ "auth-event-ef-open.pdf": "open-error",+ "bug1020226.pdf": "open-error",+ "bug1782186.pdf": "open-error",+ "bug1978317.pdf": "timeout",+ "encrypted-attachment.pdf": "open-error",+ "issue15590.pdf": "open-error",+ "issue15893_reduced.pdf": "open-error",+ "issue16263.pdf": "timeout",+ "issue21579.pdf": "open-error",+ "issue3371.pdf": "open-error",+ "issue6010_1.pdf": "open-error",+ "issue6010_2.pdf": "open-error",+ "issue9105_other.pdf": "open-error",+ "poppler-742-0-fuzzed.pdf": "open-error",+ "poppler-937-0-fuzzed.pdf": "open-error",+ "pr6531_1.pdf": "open-error",+ "print_protection.pdf": "open-error",+ "saslprep-r6.pdf": "open-error"+}diff --git a/xtask/src/demo_pdf/annots.rs b/xtask/src/demo_pdf/annots.rsindex 8da9a8fec..3b9595078 100644--- a/xtask/src/demo_pdf/annots.rs+++ b/xtask/src/demo_pdf/annots.rs@@ -223,11 +223,7 @@ impl Annotator {fn note_icon(&self, doc: &mut Document, r: Rect, fill: Rgb) -> ObjectId {let (w, h) = (r.w(), r.h());let mut c = Content::new();- c.fill_color(fill)- .stroke_color(colors::INK)- .line_width(0.8)- .rounded_rect(0.5, 0.5, w - 1.0, h - 1.0, 3.0)- .fill_stroke();+ c.fill_color(fill).stroke_color(colors::INK).line_width(0.8).rounded_rect(0.5, 0.5, w - 1.0, h - 1.0, 3.0).fill_stroke();c.line_width(1.0).round_caps();for i in 1..=3 {let y = h - 0.5 - (h - 1.0) * i as f32 / 4.2;@@ -240,14 +236,7 @@ impl Annotator {fn sticky_note(&mut self, doc: &mut Document, page: ObjectId, self_id: ObjectId, r: Rect) -> (Dictionary, Vec<ObjectId>) {let r = Rect::xywh(r.x0, r.y1 - 20.0, 20.0, 20.0);- let mut dict = self.base(- "Text",- r,- colors::GOLD,- AUTHOR,- "Sticky notes hold threaded discussions. This one has two replies.",- page,- );+ let mut dict = self.base("Text", r, colors::GOLD, AUTHOR, "Sticky notes hold threaded discussions. This one has two replies.", page);dict.set("F", 28); // Print | NoZoom | NoRotatedict.set("Name", "Comment");dict.set("Open", false);@@ -319,22 +308,16 @@ impl Annotator {dict.set("DS", Object::string_literal("font: Helvetica,sans-serif 9.0pt; text-align:left; color:#16213B"));dict.set("RC",- text(&format!(- "<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xhtml\" \- xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\" xfa:APIVersion=\"Acroform:2.7.0.0\" \- xfa:spec=\"2.0.2\"><p><b>FreeText:</b> typed straight onto the page, with a /DA and \- <span style=\"color:#E4572E\">rich text</span>.</p></body>"- )),+ text(+ "<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xhtml\"><p><b>FreeText:</b> \+ typed straight onto the page, with a /DA and <span style=\"color:#E4572E\">rich text</span>.</p></body>",+ ),);dict.set("Q", 0);dict.set("BS", dictionary! { "W" => 1, "S" => "S" });let (w, h) = (r.w(), r.h());let mut c = Content::new();- c.fill_color(colors::FIELD)- .stroke_color(colors::BLUE)- .line_width(1.0)- .rect(0.5, 0.5, w - 1.0, h - 1.0)- .fill_stroke();+ c.fill_color(colors::FIELD).stroke_color(colors::BLUE).line_width(1.0).rect(0.5, 0.5, w - 1.0, h - 1.0).fill_stroke();c.save().rect(2.0, 2.0, w - 4.0, h - 4.0).clip();c.fill_color(colors::INK);c.text(Font::HelvBold, 9.0, 6.0, h - 15.0, "FreeText:");@@ -363,12 +346,7 @@ impl Annotator {let mut c = Content::new();c.stroke_color(colors::INK).line_width(1.5).round_caps();c.move_to(lx0, ly0).line_to(bx, by).stroke();- c.fill_color(colors::ACCENT)- .move_to(lx1, ly1)- .line_to(bx - uy * aw, by + ux * aw)- .line_to(bx + uy * aw, by - ux * aw)- .close()- .fill_stroke();+ c.fill_color(colors::ACCENT).move_to(lx1, ly1).line_to(bx - uy * aw, by + ux * aw).line_to(bx + uy * aw, by - ux * aw).close().fill_stroke();c.ellipse(lx0, ly0, 3.0, 3.0).fill_stroke();self.set_ap(doc, &mut dict, r, c, Dictionary::new());dict@@ -440,11 +418,7 @@ impl Annotator {let len = (dx * dx + dy * dy).sqrt();let (ux, uy) = (dx / len, dy / len);let (bx, by) = (b.0 - ux * 9.0, b.1 - uy * 9.0);- c.round_caps()- .move_to(bx - uy * 5.0, by + ux * 5.0)- .line_to(b.0, b.1)- .line_to(bx + uy * 5.0, by - ux * 5.0)- .stroke();+ c.round_caps().move_to(bx - uy * 5.0, by + ux * 5.0).line_to(b.0, b.1).line_to(bx + uy * 5.0, by - ux * 5.0).stroke();}self.set_ap(doc, &mut dict, r, c, Dictionary::new());dict@@ -452,12 +426,13 @@ impl Annotator {fn ink(&mut self, doc: &mut Document, page: ObjectId, r: Rect) -> Dictionary {let (w, h) = (r.w(), r.h());- // A looping "signature-like" scribble and a short underline swoosh.- let scribble: Vec<(f32, f32)> = (0..=120)+ // A looping, cursive "signature" (a prolate trochoid) and an underline swoosh.+ let loops = 6.0 * std::f32::consts::TAU;+ let scribble: Vec<(f32, f32)> = (0..=360).map(|i| {- let t = i as f32 / 120.0;- let x = 6.0 + t * (w * 0.78) + 7.0 * (t * 38.0).sin();- let y = h * 0.6 + (h * 0.26) * (t * 19.0).sin() * (1.0 - 0.5 * t);+ let t = i as f32 / 360.0;+ let x = 10.0 + t * (w * 0.8) - 7.0 * (loops * t).sin();+ let y = h * 0.62 + h * 0.24 * (loops * t).cos() * (1.0 - 0.35 * t);(x, y)}).collect();@@ -468,10 +443,8 @@ impl Annotator {}).collect();let mut dict = self.base("Ink", r, colors::ACCENT, AUTHOR, "Freehand ink: two strokes.", page);- let ink_list: Vec<Object> = [&scribble, &swoosh]- .iter()- .map(|pts| floats(&pts.iter().flat_map(|&(x, y)| [r.x0 + x, r.y0 + y]).collect::<Vec<_>>()))- .collect();+ let ink_list: Vec<Object> =+ [&scribble, &swoosh].iter().map(|pts| floats(&pts.iter().flat_map(|&(x, y)| [r.x0 + x, r.y0 + y]).collect::<Vec<_>>())).collect();dict.set("InkList", ink_list);dict.set("BS", dictionary! { "W" => 1.8, "S" => "S" });let mut c = Content::new();diff --git a/xtask/src/demo_pdf/chrome.rs b/xtask/src/demo_pdf/chrome.rsindex 5c4e3ad6c..89cdd671b 100644--- a/xtask/src/demo_pdf/chrome.rs+++ b/xtask/src/demo_pdf/chrome.rs@@ -4,7 +4,9 @@ use std::env;use std::ffi::OsString;use std::fs;use std::path::{Path, PathBuf};-use std::process::Command;+use std::process::{Command, Stdio};+use std::thread;+use std::time::{Duration, Instant};use anyhow::{Context, Result, bail};@@ -36,9 +38,7 @@ pub fn find(explicit: Option<&Path>) -> Result<PathBuf> {.map(PathBuf::from).collect();if let Some(home) = env::var_os("HOME") {- candidates.push(- Path::new(&home).join("Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),- );+ candidates.push(Path::new(&home).join("Applications/Google Chrome.app/Contents/MacOS/Google Chrome"));}for var in ["ProgramFiles", "ProgramFiles(x86)", "LocalAppData"] {if let Some(base) = env::var_os(var) {@@ -51,16 +51,8 @@ pub fn find(explicit: Option<&Path>) -> Result<PathBuf> {return Ok(found);}- let names = [- "google-chrome",- "google-chrome-stable",- "chromium",- "chromium-browser",- "chrome",- "chrome.exe",- "msedge",- ];- let path = env::var_os("PATH").unwrap_or_else(OsString::new);+ let names = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome", "chrome.exe", "msedge"];+ let path = env::var_os("PATH").unwrap_or_default();for dir in env::split_paths(&path) {for name in names {let candidate = dir.join(name);@@ -77,37 +69,54 @@ pub fn find(explicit: Option<&Path>) -> Result<PathBuf> {/// Print `html` to `pdf` with headless Chrome. Chrome emits a tagged PDF and,/// with `--generate-pdf-document-outline`, bookmarks built from the headings.-pub fn print_to_pdf(chrome: &Path, html: &Path, pdf: &Path, profile_dir: &Path) -> Result<()> {+///+/// Some Chrome builds finish writing the PDF but linger afterwards, so rather+/// than only waiting for exit we poll for a complete file and then stop Chrome.+pub fn print_to_pdf(chrome: &Path, html: &Path, pdf: &Path, log: &Path) -> Result<()> {if pdf.exists() {fs::remove_file(pdf).with_context(|| format!("removing stale {}", pdf.display()))?;}let mut print_arg = OsString::from("--print-to-pdf=");print_arg.push(pdf);- let mut profile_arg = OsString::from("--user-data-dir=");- profile_arg.push(profile_dir);+ let log_file = fs::File::create(log).with_context(|| format!("creating {}", log.display()))?;- let output = Command::new(chrome)+ let mut child = Command::new(chrome).arg("--headless=new").arg("--disable-gpu")- .arg("--no-first-run")- .arg("--no-default-browser-check")- .arg("--allow-file-access-from-files").arg("--no-pdf-header-footer").arg("--generate-pdf-document-outline")- .arg(profile_arg).arg(print_arg).arg(super::file_url(html))- .output()+ .stdout(Stdio::null())+ .stderr(log_file)+ .spawn().with_context(|| format!("running {}", chrome.display()))?;- let ok = output.status.success() && fs::metadata(pdf).map(|m| m.len() > 0).unwrap_or(false);- if !ok {- bail!(- "Chrome did not produce {} (status {}):\n{}",- pdf.display(),- output.status,- String::from_utf8_lossy(&output.stderr)- );+ let started = Instant::now();+ let mut last_len = None;+ loop {+ if let Some(status) = child.try_wait()? {+ if is_complete(pdf) {+ return Ok(());+ }+ bail!("Chrome exited with {status} without writing {}; see {}", pdf.display(), log.display());+ }+ let len = fs::metadata(pdf).map(|m| m.len()).ok();+ if len.is_some() && len == last_len && is_complete(pdf) {+ let _ = child.kill();+ let _ = child.wait();+ return Ok(());+ }+ last_len = len;+ if started.elapsed() > Duration::from_secs(120) {+ let _ = child.kill();+ bail!("Chrome timed out printing {}; see {}", html.display(), log.display());+ }+ thread::sleep(Duration::from_millis(500));}- Ok(())+}++/// A PDF is complete once its trailer's `%%EOF` marker has been written.+fn is_complete(pdf: &Path) -> bool {+ fs::read(pdf).map(|bytes| bytes.len() > 1024 && bytes[bytes.len() - 1024..].windows(5).any(|w| w == b"%%EOF")).unwrap_or(false)}diff --git a/xtask/src/demo_pdf/form.rs b/xtask/src/demo_pdf/form.rsindex 431bf2ad2..e1f34d91c 100644--- a/xtask/src/demo_pdf/form.rs+++ b/xtask/src/demo_pdf/form.rs@@ -59,13 +59,7 @@ pub fn build(doc: &mut Document, annotator: &mut Annotator, inputs: FormInputs<'});label(&mut c, COL2, row2 + 24.0, "Amount (AFNumber_Format, right-aligned)");b.text_field("amount", "Amount in US dollars", Rect::new(COL2, row2, RIGHT, row2 + 20.0), "1234.5", Some("$1,234.50"), 2, |d| {- d.set(- "AA",- js_actions(- "AFNumber_Format(2, 0, 0, 0, \"$\", true);",- "AFNumber_Keystroke(2, 0, 0, 0, \"$\", true);",- ),- );+ d.set("AA", js_actions("AFNumber_Format(2, 0, 0, 0, \"$\", true);", "AFNumber_Keystroke(2, 0, 0, 0, \"$\", true);"));});label(&mut c, LEFT, 510.0, "Comments (multiline)");@@ -77,11 +71,8 @@ pub fn build(doc: &mut Document, annotator: &mut Annotator, inputs: FormInputs<'// --- Preferences -----------------------------------------------------------section(&mut c, 418.0, "Preferences");- let checks = [- ("subscribe", "Subscribe to release notes", true),- ("license", "I have read the licence", true),- ("stickers", "Send me stickers", false),- ];+ let checks =+ [("subscribe", "Subscribe to release notes", true), ("license", "I have read the licence", true), ("stickers", "Send me stickers", false)];for (i, (field, caption, on)) in checks.into_iter().enumerate() {let y = 382.0 - i as f32 * 20.0;b.checkbox(field, caption, Rect::xywh(LEFT, y, 12.0, 12.0), on);@@ -112,13 +103,7 @@ pub fn build(doc: &mut Document, annotator: &mut Annotator, inputs: FormInputs<'Rect::new(LEFT, 184.0, 250.0, 206.0),"app.alert(\"Hello from the PrintCraft showcase! This alert is a JavaScript action on a push button.\", 3);",);- c.fill_color(colors::INK_3).text(- Font::Helv,- 7.0,- LEFT,- 172.0,- "JavaScript: shows app.alert(...) in viewers that run document scripts.",- );+ c.fill_color(colors::INK_3).text(Font::Helv, 7.0, LEFT, 172.0, "JavaScript: shows app.alert(...) in viewers that run document scripts.");label(&mut c, COL2, 212.0, "Signature (unsigned /Sig field)");b.signature("signature", "Approver signature", Rect::new(COL2, 150.0, RIGHT, 206.0));@@ -144,7 +129,12 @@ pub fn build(doc: &mut Document, annotator: &mut Annotator, inputs: FormInputs<'// --- Page object -------------------------------------------------------------let mut annots = b.widgets.clone();let fields = b.fields.clone();- annots.push(annotator.link(b.doc, page, Rect::new(COL2 - 1.0, link_y - 5.0, COL2 + back_w + 1.0, link_y + 9.0), LinkTarget::Page(inputs.contents_page)));+ annots.push(annotator.link(+ b.doc,+ page,+ Rect::new(COL2 - 1.0, link_y - 5.0, COL2 + back_w + 1.0, link_y + 9.0),+ LinkTarget::Page(inputs.contents_page),+ ));annots.push(annotator.link(b.doc, page, Rect::new(COL2 - 1.0, link_y - 21.0, COL2 + visit_w + 1.0, link_y - 7.0), LinkTarget::Uri(visit)));annots.push(annotator.simple_note(b.doc,@@ -184,7 +174,7 @@ fn draw_page_chrome(c: &mut Content, folio: &str) {c.fill_color(colors::ACCENT).tracked_text(Font::HelvBold, 7.5, LEFT, 722.0, 1.8, "CHAPTER TEN");c.fill_color(colors::INK).text(Font::Times, 34.0, LEFT, 686.0, "Interactive");- let w = Font::Times.width("Interactive ", 34.0);+ let w = Font::Times.width("Interactive", 34.0) + 12.0;c.fill_color(colors::ACCENT).text(Font::TimesItalic, 34.0, LEFT + w, 686.0, "Form");c.fill_color(colors::INK_2);c.text(Font::TimesItalic, 13.0, LEFT, 660.0, "This page was not printed by Chrome: the xtask writes its content stream and");diff --git a/xtask/src/demo_pdf/mod.rs b/xtask/src/demo_pdf/mod.rsindex 9f5f81834..60905f545 100644--- a/xtask/src/demo_pdf/mod.rs+++ b/xtask/src/demo_pdf/mod.rs@@ -58,7 +58,7 @@ pub fn run(args: &[String]) -> Result<()> {let chrome = chrome::find(chrome_override.as_deref())?;println!("demo-pdf: printing with {}", chrome.display());let raw = build.join("chrome.pdf");- chrome::print_to_pdf(&chrome, &html_path, &raw, &build.join("chrome-profile"))?;+ chrome::print_to_pdf(&chrome, &html_path, &raw, &build.join("chrome.log"))?;println!("demo-pdf: post-processing");let mut doc = lopdf::Document::load(&raw).with_context(|| format!("loading {}", raw.display()))?;diff --git a/xtask/src/demo_pdf/pdf.rs b/xtask/src/demo_pdf/pdf.rsindex c30852ac4..9f4b9cc58 100644--- a/xtask/src/demo_pdf/pdf.rs+++ b/xtask/src/demo_pdf/pdf.rs@@ -10,11 +10,7 @@ pub struct Rgb(pub f32, pub f32, pub f32);impl Rgb {pub const fn hex(v: u32) -> Self {- Rgb(- ((v >> 16) & 0xff) as f32 / 255.0,- ((v >> 8) & 0xff) as f32 / 255.0,- (v & 0xff) as f32 / 255.0,- )+ Rgb(((v >> 16) & 0xff) as f32 / 255.0, ((v >> 8) & 0xff) as f32 / 255.0, (v & 0xff) as f32 / 255.0)}pub fn array(self) -> Object {@@ -74,10 +70,7 @@ pub struct Stamp {impl Stamp {pub fn now() -> Self {- let secs = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_secs() as i64)- .unwrap_or(0);+ let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);Self::from_unix(secs)}@@ -95,11 +88,7 @@ impl Stamp {let d = doy - (153 * mp + 2) / 5 + 1;let m = if mp < 10 { mp + 3 } else { mp - 9 };let y = yoe + era * 400 + i64::from(m <= 2);- Stamp {- unix: secs,- pdf: format!("D:{y:04}{m:02}{d:02}{h:02}{mi:02}{s:02}Z"),- iso: format!("{y:04}-{m:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z"),- }+ Stamp { unix: secs, pdf: format!("D:{y:04}{m:02}{d:02}{h:02}{mi:02}{s:02}Z"), iso: format!("{y:04}-{m:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z") }}/// The same moment shifted by `minutes` (used to order threaded replies).@@ -120,14 +109,7 @@ pub enum Font {}impl Font {- pub const ALL: [Font; 6] = [- Font::Helv,- Font::HelvBold,- Font::Times,- Font::TimesItalic,- Font::Courier,- Font::ZapfDingbats,- ];+ pub const ALL: [Font; 6] = [Font::Helv, Font::HelvBold, Font::Times, Font::TimesItalic, Font::Courier, Font::ZapfDingbats];/// Resource name, following the conventional AcroForm names.pub fn res(self) -> &'static str {@@ -338,30 +320,13 @@ impl Content {/// One line of text with its baseline starting at (x, y).pub fn text(&mut self, font: Font, size: f32, x: f32, y: f32, s: &str) -> &mut Self {- let _ = writeln!(- self.0,- "BT /{} {} Tf {} {} Td {} Tj ET",- font.res(),- num(size),- num(x),- num(y),- pdf_string(s)- );+ let _ = writeln!(self.0, "BT /{} {} Tf {} {} Td {} Tj ET", font.res(), num(size), num(x), num(y), pdf_string(s));self}/// Text with letter-spacing (`Tc`), for tracked capitals.pub fn tracked_text(&mut self, font: Font, size: f32, x: f32, y: f32, tracking: f32, s: &str) -> &mut Self {- let _ = writeln!(- self.0,- "BT /{} {} Tf {} Tc {} {} Td {} Tj ET",- font.res(),- num(size),- num(tracking),- num(x),- num(y),- pdf_string(s)- );+ let _ = writeln!(self.0, "BT /{} {} Tf {} Tc {} {} Td {} Tj 0 Tc ET", font.res(), num(size), num(tracking), num(x), num(y), pdf_string(s));self}}diff --git a/xtask/src/demo_pdf/postprocess.rs b/xtask/src/demo_pdf/postprocess.rsindex 46f72deb4..ed1fb488e 100644--- a/xtask/src/demo_pdf/postprocess.rs+++ b/xtask/src/demo_pdf/postprocess.rs@@ -60,8 +60,7 @@ pub fn enhance(doc: &mut Document, now: Stamp) -> Result<Summary> {}seen.push(uri.clone());let kind_str = uri[MARKER_PREFIX.len()..].split('/').next().unwrap_or_default();- let kind = Kind::from_marker(kind_str)- .with_context(|| format!("unknown annotation marker {uri} on page {}", index + 1))?;+ let kind = Kind::from_marker(kind_str).with_context(|| format!("unknown annotation marker {uri} on page {}", index + 1))?;let struct_parent = doc.get_dictionary(id)?.get(b"StructParent").ok().cloned();let built = annotator.build(doc, page, id, kind, r);let mut dict = built.dict;@@ -112,13 +111,7 @@ pub fn enhance(doc: &mut Document, now: Stamp) -> Result<Summary> {let form_page = form::build(doc,&mut annotator,- FormInputs {- fonts: &fonts,- pages_root,- contents_page: pages[PAGE_CONTENTS],- print_only_ocg: ocg_notes,- folio: "10",- },+ FormInputs { fonts: &fonts, pages_root, contents_page: pages[PAGE_CONTENTS], print_only_ocg: ocg_notes, folio: "10" },);{let root = doc.get_dictionary_mut(pages_root)?;@@ -261,13 +254,7 @@ fn add_resource(doc: &mut Document, page: ObjectId, category: &str, key: &str, vfn add_watermark(doc: &mut Document, page: ObjectId, ocg: ObjectId, fonts: &Fonts) -> Result<()> {add_resource(doc, page, "Properties", "PCDraft", Object::Reference(ocg))?;add_resource(doc, page, "Font", "PCDraftFont", Object::Reference(fonts.id(Font::HelvBold)))?;- add_resource(- doc,- page,- "ExtGState",- "PCDraftGS",- dictionary! { "Type" => "ExtGState", "ca" => 0.09, "CA" => 0.09 }.into(),- )?;+ add_resource(doc, page, "ExtGState", "PCDraftGS", dictionary! { "Type" => "ExtGState", "ca" => 0.09, "CA" => 0.09 }.into())?;let size = 150.0f32;let word = "DRAFT";@@ -281,10 +268,7 @@ fn add_watermark(doc: &mut Document, page: ObjectId, ocg: ObjectId, fonts: &Fontc.raw("Q").save();c.raw("/OC /PCDraft BDC /Artifact << /Type /Pagination /Subtype /Watermark >> BDC");c.gs("PCDraftGS").fill_color(colors::ACCENT);- c.raw(&format!(- "BT /PCDraftFont {size} Tf {cos:.4} {sin:.4} {:.4} {cos:.4} {x:.2} {y:.2} Tm (DRAFT) Tj ET",- -sin- ));+ c.raw(&format!("BT /PCDraftFont {size} Tf {cos:.4} {sin:.4} {:.4} {cos:.4} {x:.2} {y:.2} Tm (DRAFT) Tj ET", -sin));c.raw("EMC EMC").restore();let open = doc.add_object(Stream::new(Dictionary::new(), b"q\n".to_vec()));@@ -304,12 +288,10 @@ fn add_watermark(doc: &mut Document, page: ObjectId, ocg: ObjectId, fonts: &FontOk(())}-/// Keep Chrome's heading-based outline and add the form page; if Chrome did not-/// produce one, build a flat outline of the chapters.+/// Keep Chrome's heading-based outline (tidying its titles) and add the form+/// page next to the other chapters; if Chrome produced none, build one.fn extend_outline(doc: &mut Document, pages: &[ObjectId], form_page: ObjectId) -> Result<String> {- let dest = |page: ObjectId| -> Object {- vec![Object::Reference(page), name("XYZ"), 0.into(), 792.into(), Object::Null].into()- };+ let dest = |page: ObjectId, top: i64| -> Object { vec![Object::Reference(page), name("XYZ"), 0.into(), top.into(), Object::Null].into() };let existing = doc.catalog()?.get(b"Outlines")@@ -317,45 +299,112 @@ fn extend_outline(doc: &mut Document, pages: &[ObjectId], form_page: ObjectId) -.ok().filter(|id| doc.get_dictionary(*id).map(|d| d.has(b"First")).unwrap_or(false));- let (root, description) = match existing {- Some(root) => (root, "Chrome headings + form page"),+ let (chapter_parent, description) = match existing {+ Some(root) => {+ let mut items = Vec::new();+ collect_outline(doc, root, &mut items);+ let mut parent = root;+ for id in items {+ let dict = doc.get_dictionary_mut(id)?;+ let title = decode_text(dict.get(b"Title").and_then(Object::as_str).unwrap_or_default());+ if title == "Review & Markup" {+ parent = dict.get(b"Parent").and_then(Object::as_reference).unwrap_or(root);+ }+ let tidy = tidy_title(&title);+ if tidy != title {+ dict.set("Title", text(&tidy));+ }+ }+ (parent, "Chrome headings (tidied) + form page")+ }None => {let root = doc.add_object(dictionary! { "Type" => "Outlines", "Count" => 0 });let chapters = [- ("Cover", 0),- ("Contents", 1),- ("Foreword", 2),- ("1 Setting Text", 3),- ("2 OpenType Features", 4),- ("3 Expressive Type", 5),- ("4 Scripts of the World", 6),- ("5 Mathematics", 7),- ("6 Vector Graphics", 8),- ("7 Data & Tables", 9),- ("8 Code & Images", 10),- ("9 Review & Markup", 11),+ "Cover",+ "Contents",+ "Foreword",+ "Setting Text",+ "OpenType Features",+ "Expressive Type",+ "Scripts of the World",+ "Mathematics",+ "Vector Graphics",+ "Data & Tables",+ "Code & Images",+ "Review & Markup",];- for (title, index) in chapters {- append_outline_item(doc, root, title, dest(pages[index]), None)?;+ for (index, title) in chapters.into_iter().enumerate() {+ append_outline_item(doc, root, title, dest(pages[index], 792), None)?;}doc.catalog_mut()?.set("Outlines", root);(root, "built by xtask (Chrome emitted none)")}};- let form_item = append_outline_item(doc, root, "10 Interactive Form", dest(form_page), Some(colors::ACCENT.array()))?;+ let form_item = append_outline_item(doc, chapter_parent, "Interactive Form", dest(form_page, 792), Some(colors::ACCENT.array()))?;for (title, top) in [("Contact", 620), ("Preferences", 426), ("Actions & signature", 240)] {- let d: Object = vec![Object::Reference(form_page), name("XYZ"), 0.into(), top.into(), Object::Null].into();- append_outline_item(doc, form_item, title, d, None)?;+ append_outline_item(doc, form_item, title, dest(form_page, top), None)?;}- // Leave the form entry collapsed: a negative /Count means closed.- let kids = doc.get_dictionary(form_item)?.get(b"Count")?.as_i64()?;- doc.get_dictionary_mut(form_item)?.set("Count", -kids.abs());+ let root = doc.catalog()?.get(b"Outlines")?.as_reference()?;let total = count_outline(doc, root);Ok(format!("{description}, {total} entries"))}-/// Append a child item to outline node `parent`, updating First/Last/Count.+/// Every outline item below `node`, depth first.+fn collect_outline(doc: &Document, node: ObjectId, out: &mut Vec<ObjectId>) {+ let next = |id: ObjectId, key: &[u8]| doc.get_dictionary(id).ok().and_then(|d| d.get(key).and_then(Object::as_reference).ok());+ let mut cur = next(node, b"First");+ while let Some(id) = cur {+ out.push(id);+ collect_outline(doc, id, out);+ cur = next(id, b"Next");+ }+}++/// Decode a PDF text string (UTF-16BE with BOM, else treated as Latin-1).+fn decode_text(bytes: &[u8]) -> String {+ if let Some(rest) = bytes.strip_prefix(&[0xfe, 0xff]) {+ let units: Vec<u16> = rest.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();+ String::from_utf16_lossy(&units)+ } else {+ bytes.iter().map(|&b| b as char).collect()+ }+}++/// Chrome copies CSS `text-transform: uppercase` into bookmark titles; turn+/// all-caps headings back into sentence case (keeping acronyms).+fn tidy_title(title: &str) -> String {+ const ACRONYMS: &[&str] = &["PDF"];+ // Chrome drops the <br> between the two lines of the cover title.+ if title == "PrintCraftShowcase" {+ return TITLE.to_string();+ }+ let title = title.split_whitespace().collect::<Vec<_>>().join(" ");+ if title.chars().any(char::is_lowercase) || !title.chars().any(char::is_uppercase) {+ return title;+ }+ title+ .split(' ')+ .enumerate()+ .map(|(i, word)| {+ let bare = word.trim_matches(|c: char| !c.is_alphanumeric());+ if ACRONYMS.contains(&bare) {+ return word.to_string();+ }+ let lower = word.to_lowercase();+ if i == 0 {+ let mut chars = lower.chars();+ chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()+ } else {+ lower+ }+ })+ .collect::<Vec<_>>()+ .join(" ")+}++/// Append a child item to outline node `parent`, updating First/Last and the+/// /Count of every open ancestor.fn append_outline_item(doc: &mut Document, parent: ObjectId, title: &str, dest: Object, color: Option<Object>) -> Result<ObjectId> {let last = doc.get_dictionary(parent)?.get(b"Last").and_then(Object::as_reference).ok();let mut item = dictionary! { "Title" => text(title), "Parent" => parent, "Dest" => dest };@@ -375,9 +424,20 @@ fn append_outline_item(doc: &mut Document, parent: ObjectId, title: &str, dest:p.set("First", id);}p.set("Last", id);- let count = p.get(b"Count").and_then(Object::as_i64).unwrap_or(0);- // Open nodes (and the root) count visible descendants positively.- p.set("Count", if count < 0 { count - 1 } else { count + 1 });++ // Open nodes count visible descendants (positive); a closed node's negative+ // count grows in magnitude and hides the change from its ancestors.+ let mut node = Some(parent);+ while let Some(n) = node {+ let d = doc.get_dictionary_mut(n)?;+ let count = d.get(b"Count").and_then(Object::as_i64).unwrap_or(0);+ if count < 0 {+ d.set("Count", count - 1);+ break;+ }+ d.set("Count", count + 1);+ node = d.get(b"Parent").and_then(Object::as_reference).ok();+ }Ok(id)}@@ -403,10 +463,7 @@ fn add_embedded_file_name(doc: &mut Document, file_name: &str, spec: ObjectId) -catalog.get_mut(b"Names")?.as_dict_mut()?}};- names.set(- "EmbeddedFiles",- dictionary! { "Names" => vec![Object::string_literal(file_name), Object::Reference(spec)] },- );+ names.set("EmbeddedFiles", dictionary! { "Names" => vec![Object::string_literal(file_name), Object::Reference(spec)] });Ok(())}@@ -446,14 +503,7 @@ fn xmp(producer: &str, now: &Stamp) -> String {for b in now.iso.bytes().chain(TITLE.bytes()) {h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);}- let uuid = format!(- "{:08x}-{:04x}-4{:03x}-8{:03x}-{:012x}",- h >> 32,- (h >> 16) & 0xffff,- h & 0xfff,- (h >> 20) & 0xfff,- h & 0xffff_ffff_ffff- );+ let uuid = format!("{:08x}-{:04x}-4{:03x}-8{:03x}-{:012x}", h >> 32, (h >> 16) & 0xffff, h & 0xfff, (h >> 20) & 0xfff, h & 0xffff_ffff_ffff);let keywords: String = KEYWORDS.iter().map(|k| format!("<rdf:li>{}</rdf:li>", xml_escape(k))).collect();format!("<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n\diff --git a/xtask/src/gates.rs b/xtask/src/gates.rsnew file mode 100644index 000000000..33222abde--- /dev/null+++ b/xtask/src/gates.rs@@ -0,0 +1,269 @@+//! Quality gates: layering, wasm, the CI bundle, corpora and the robustness sweep.++use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::process::Command;++use anyhow::{Context, anyhow, bail};++use crate::layers;++pub fn root() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR")).parent().expect("xtask has a parent dir").to_path_buf()+}++fn cargo() -> Command {+ let mut c = Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()));+ c.current_dir(root());+ c+}++fn run(mut cmd: Command, what: &str) -> anyhow::Result<()> {+ eprintln!("$ {what}");+ let status = cmd.status().with_context(|| format!("{what}: failed to spawn"))?;+ if !status.success() {+ bail!("{what}: exited with {status}");+ }+ Ok(())+}++fn metadata() -> anyhow::Result<serde_json::Value> {+ let out = cargo().args(["metadata", "--format-version", "1", "--no-deps"]).output().context("cargo metadata")?;+ if !out.status.success() {+ bail!("cargo metadata failed:\n{}", String::from_utf8_lossy(&out.stderr));+ }+ Ok(serde_json::from_slice(&out.stdout)?)+}++pub fn layers(_: &[String]) -> anyhow::Result<()> {+ let crates = layers::from_metadata(&metadata()?).map_err(|e| anyhow!(e))?;+ println!("Dependency layering (plan/architecture.md §3)\n");+ println!("{:<24} {:<14} workspace deps", "crate", "layer");+ for c in &crates {+ let ws: Vec<String> = c+ .deps+ .iter()+ .filter(|d| d.workspace)+ .map(|d| format!("{}{}", layers::short_name(&d.name), if d.kind == layers::DepKind::Dev { " (dev)" } else { "" }))+ .collect();+ println!("{:<24} {:<14} {}", c.name, layers::describe(layers::classify(&c.name)), ws.join(", "));+ }+ let violations = layers::check(&crates);+ println!();+ if violations.is_empty() {+ println!("OK: {} crates, no layering violations.", crates.len());+ return Ok(());+ }+ for v in &violations {+ println!(" - {v}");+ }+ bail!("{} layering violation(s)", violations.len())+}++pub fn wasm(_: &[String]) -> anyhow::Result<()> {+ let crates = layers::from_metadata(&metadata()?).map_err(|e| anyhow!(e))?;+ let set: Vec<String> = crates+ .into_iter()+ .filter(|c| matches!(layers::classify(&c.name), Some(layers::Class::Layer(_) | layers::Class::Standalone(_))))+ .map(|c| c.name)+ .collect();+ let mut failed = Vec::new();+ for pkg in &set {+ let mut c = cargo();+ c.args(["check", "--target", "wasm32-unknown-unknown", "-p", pkg]);+ if run(c, &format!("cargo check --target wasm32-unknown-unknown -p {pkg}")).is_err() {+ failed.push(pkg.clone());+ }+ }+ if failed.is_empty() {+ println!("wasm32: {} crates ok", set.len());+ Ok(())+ } else {+ bail!("wasm32 check failed for: {}", failed.join(", "))+ }+}++pub fn ci(_: &[String]) -> anyhow::Result<()> {+ type Step = (&'static str, Box<dyn Fn() -> anyhow::Result<()>>);+ let steps: Vec<Step> = vec![+ ("fmt", Box::new(|| run_args(&["fmt", "--all", "--", "--check"]))),+ ("clippy", Box::new(|| run_args(&["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"]))),+ ("test", Box::new(|| run_args(&["test", "--workspace"]))),+ ("layers", Box::new(|| layers(&[]))),+ ("wasm", Box::new(|| wasm(&[]))),+ ];+ for (i, (name, f)) in steps.iter().enumerate() {+ eprintln!("\n=== ci: {name} ===");+ if let Err(e) = f() {+ println!("\nCI: {} passed, FAILED at `{name}`: {e:#}", i);+ bail!("ci failed at `{name}`");+ }+ }+ println!("\nCI: all {} steps passed", steps.len());+ Ok(())+}++fn run_args(args: &[&str]) -> anyhow::Result<()> {+ let mut c = cargo();+ c.args(args);+ run(c, &format!("cargo {}", args.join(" ")))+}++pub fn corpus(_: &[String]) -> anyhow::Result<()> {+ let dir = root().join("corpus");+ std::fs::create_dir_all(&dir)?;+ let pdfjs = dir.join("pdfjs");+ if pdfjs.join("test/pdfs").is_dir() {+ println!("corpus/pdfjs already present");+ } else {+ let mut c = Command::new("git");+ c.current_dir(&dir).args(["clone", "-q", "--depth", "1", "--filter=blob:none", "--sparse", "https://github.com/mozilla/pdf.js.git", "pdfjs"]);+ run(c, "git clone --sparse mozilla/pdf.js")?;+ let mut c = Command::new("git");+ c.current_dir(&pdfjs).args(["sparse-checkout", "set", "test/pdfs"]);+ run(c, "git sparse-checkout set test/pdfs")?;+ }+ println!(+ "Corpora (git-ignored, never committed; tests skip when absent):\n corpus/pdfjs/test/pdfs pdf.js test files committed in-repo (Apache-2.0 repository; individual files keep their own terms)"+ );+ Ok(())+}++/// `cargo xtask check [--update-baseline]`: run `printcraft-cli check` over the corpus and compare+/// with `xtask/baselines/<corpus>.json` (the list of files known not to open/render cleanly).+/// Fails on any crash, and on any file that regressed from `ok`.+pub fn check(args: &[String]) -> anyhow::Result<()> {+ let update = args.iter().any(|a| a == "--update-baseline");+ let corpus = root().join("corpus/pdfjs/test/pdfs");+ if !corpus.is_dir() {+ bail!("corpus missing: run `cargo xtask corpus` first");+ }+ run_args(&["build", "--release", "-p", "printcraft-cli"])?;+ let report = root().join("target/check-pdfjs.json");+ let mut c = Command::new(root().join("target/release/printcraft-cli"));+ c.args(["check"]).arg(&corpus).args(["--timeout", "20", "--dpi", "36", "--json"]).arg(&report);+ run(c, "printcraft-cli check corpus/pdfjs")?;+ let results: Vec<serde_json::Value> = serde_json::from_str(&std::fs::read_to_string(&report)?)?;+ let name =+ |v: &serde_json::Value| Path::new(v["file"].as_str().unwrap_or("")).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ let status = |v: &serde_json::Value| v["status"].as_str().unwrap_or("?").split(':').next().unwrap_or("?").to_string();+ let current: BTreeMap<String, String> = results.iter().filter(|v| status(v) != "ok").map(|v| (name(v), status(v))).collect();+ let crashes: Vec<&String> = current.iter().filter(|(_, s)| s.as_str() == "crash").map(|(f, _)| f).collect();+ let baseline_path = root().join("xtask/baselines/pdfjs.json");+ if update {+ std::fs::create_dir_all(baseline_path.parent().expect("has parent"))?;+ std::fs::write(&baseline_path, serde_json::to_string_pretty(¤t)? + "\n")?;+ println!("baseline updated: {} known non-ok files", current.len());+ }+ let baseline: BTreeMap<String, String> =+ std::fs::read_to_string(&baseline_path).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();+ let regressions: Vec<String> = current.iter().filter(|(f, _)| !baseline.contains_key(*f)).map(|(f, s)| format!("{f} ({s})")).collect();+ let fixed: Vec<&String> = baseline.keys().filter(|f| !current.contains_key(*f)).collect();+ println!(+ "\n{} files: {} ok, {} known issues, {} regressions, {} newly fixed, {} crashes",+ results.len(),+ results.len() - current.len(),+ current.len() - regressions.len(),+ regressions.len(),+ fixed.len(),+ crashes.len()+ );+ if !fixed.is_empty() {+ println!("newly fixed (run with --update-baseline): {fixed:?}");+ }+ if !crashes.is_empty() {+ bail!("crashes: {crashes:?}");+ }+ if !regressions.is_empty() {+ bail!("regressions: {regressions:?}");+ }+ Ok(())+}++/// `cargo xtask text-oracle [--limit N]`: compare `printcraft-cli text` with poppler's `pdftotext`+/// (external oracle process, never linked) over the corpus. Reports word-level F1 per file and the+/// median. Plan target (M2): median ≥ 0.97.+pub fn text_oracle(args: &[String]) -> anyhow::Result<()> {+ let limit: usize = args.iter().position(|a| a == "--limit").and_then(|i| args.get(i + 1)).and_then(|v| v.parse().ok()).unwrap_or(usize::MAX);+ if Command::new("pdftotext").arg("-v").output().is_err() {+ bail!("pdftotext (poppler) not found; install it to run the text oracle (brew install poppler / apt install poppler-utils)");+ }+ run_args(&["build", "--release", "-p", "printcraft-cli"])?;+ let corpus = root().join("corpus/pdfjs/test/pdfs");+ let mut files: Vec<PathBuf> =+ std::fs::read_dir(&corpus)?.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "pdf")).collect();+ files.sort();+ let cli = root().join("target/release/printcraft-cli");+ let mut scores = Vec::new();+ let mut worst: Vec<(f64, String)> = Vec::new();+ for f in files.iter().take(limit) {+ let ours = run_capture(Command::new(&cli).arg("text").arg(f), 20);+ let theirs = run_capture(Command::new("pdftotext").arg("-q").arg(f).arg("-"), 20);+ let (Some(ours), Some(theirs)) = (ours, theirs) else { continue };+ let (a, b) = (words(&ours), words(&theirs));+ if b.len() < 20 {+ continue; // image-only or near-empty per the oracle+ }+ let score = f1(&a, &b);+ scores.push(score);+ worst.push((score, f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()));+ }+ if scores.is_empty() {+ bail!("no comparable files");+ }+ scores.sort_by(f64::total_cmp);+ worst.sort_by(|a, b| a.0.total_cmp(&b.0));+ let median = scores[scores.len() / 2];+ let mean = scores.iter().sum::<f64>() / scores.len() as f64;+ println!("text oracle: {} files with text; median F1 {:.3}, mean {:.3}, p10 {:.3}", scores.len(), median, mean, scores[scores.len() / 10]);+ println!("lowest:");+ for (s, n) in worst.iter().take(12) {+ println!(" {s:.3} {n}");+ }+ Ok(())+}++fn run_capture(cmd: &mut Command, timeout_s: u64) -> Option<String> {+ let mut child = cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null()).spawn().ok()?;+ let start = std::time::Instant::now();+ let mut out = String::new();+ let mut stdout = child.stdout.take()?;+ let reader = std::thread::spawn(move || {+ use std::io::Read;+ let mut s = String::new();+ let _ = stdout.read_to_string(&mut s);+ s+ });+ loop {+ match child.try_wait() {+ Ok(Some(_)) => break,+ Ok(None) if start.elapsed().as_secs() > timeout_s => {+ let _ = child.kill();+ let _ = child.wait();+ return None;+ }+ Ok(None) => std::thread::sleep(std::time::Duration::from_millis(10)),+ Err(_) => return None,+ }+ }+ out.push_str(&reader.join().ok()?);+ Some(out)+}++fn words(s: &str) -> BTreeMap<String, usize> {+ let mut m = BTreeMap::new();+ for w in s.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()) {+ *m.entry(w.to_lowercase()).or_insert(0) += 1;+ }+ m+}++fn f1(a: &BTreeMap<String, usize>, b: &BTreeMap<String, usize>) -> f64 {+ let common: usize = a.iter().map(|(w, n)| (*n).min(*b.get(w).unwrap_or(&0))).sum();+ let (na, nb): (usize, usize) = (a.values().sum(), b.values().sum());+ if na == 0 || nb == 0 {+ return 0.0;+ }+ let (p, r) = (common as f64 / na as f64, common as f64 / nb as f64);+ if p + r == 0.0 { 0.0 } else { 2.0 * p * r / (p + r) }+}diff --git a/xtask/src/layers.rs b/xtask/src/layers.rsnew file mode 100644index 000000000..c5780d74b--- /dev/null+++ b/xtask/src/layers.rs@@ -0,0 +1,336 @@+//! Dependency layering rules (plan/architecture.md §3), enforced by `cargo xtask layers`.+//!+//! The rule engine works on a small, metadata-independent model so it can be unit-tested;+//! `from_metadata` builds that model from `cargo metadata`. (Structure shared with PhotoCraft.)++use serde_json::Value;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Class {+ /// Regular layered crate.+ Layer(u8),+ /// Layer 0/1 core that may depend only on the workspace crates listed in `STANDALONE_DEPS`.+ Standalone(u8),+ /// Test tooling: dev-dependency only for other crates.+ Testkit,+ /// Binaries, build tooling: exempt.+ Exempt,+}++impl Class {+ fn layer(self) -> Option<u8> {+ match self {+ Class::Layer(l) | Class::Standalone(l) => Some(l),+ Class::Testkit => Some(7),+ Class::Exempt => None,+ }+ }+}++/// Every workspace crate (package name without the `printcraft-` prefix) and its layer.+pub const TABLE: &[(&str, Class)] = &[+ // L0 foundation (standalone, publishable)+ ("geom", Class::Standalone(0)),+ ("filters", Class::Standalone(0)),+ ("crypt", Class::Standalone(0)),+ ("arlington", Class::Standalone(0)),+ // L1 object layer+ ("cos", Class::Standalone(1)),+ // L2 core model+ ("content", Class::Layer(2)),+ ("model", Class::Layer(2)),+ ("color", Class::Layer(2)),+ ("fonts", Class::Layer(2)),+ ("ops", Class::Layer(2)),+ // L3 core services+ ("render", Class::Layer(3)),+ ("text", Class::Layer(3)),+ ("annot", Class::Layer(3)),+ ("forms", Class::Layer(3)),+ ("js", Class::Layer(3)),+ ("xfa", Class::Layer(3)),+ ("ml", Class::Layer(3)),+ // L4 features+ ("edit", Class::Layer(4)),+ ("organize", Class::Layer(4)),+ ("security", Class::Layer(4)),+ ("redact", Class::Layer(4)),+ ("sign", Class::Layer(4)),+ ("ocr", Class::Layer(4)),+ ("create", Class::Layer(4)),+ ("export", Class::Layer(4)),+ ("optimize", Class::Layer(4)),+ ("preflight", Class::Layer(4)),+ ("prepress", Class::Layer(4)),+ ("a11y", Class::Layer(4)),+ ("compare", Class::Layer(4)),+ ("measure", Class::Layer(4)),+ ("search", Class::Layer(4)),+ ("print", Class::Layer(4)),+ ("media", Class::Layer(4)),+ ("ai", Class::Layer(4)),+ // L5 interaction+ ("viewport", Class::Layer(5)),+ ("tools", Class::Layer(5)),+ // L6 façade+ ("engine", Class::Layer(6)),+ // L7 platform + frontends+ ("platform", Class::Layer(7)),+ ("ui-common", Class::Layer(7)),+ ("ui-egui", Class::Layer(7)),+ ("automation", Class::Layer(7)),+ // test support+ ("testkit", Class::Testkit),+ ("oracle", Class::Testkit),+ // L8 apps + tooling+ ("printcraft", Class::Exempt),+ ("cli", Class::Exempt),+ ("web", Class::Exempt),+ ("xtask", Class::Exempt),+];++/// Workspace crates a standalone crate may use (architecture §3 rule 3: `cos → filters, crypt, geom`).+pub const STANDALONE_DEPS: &[(&str, &[&str])] = &[("cos", &["filters", "crypt", "geom"])];++/// Allowed same-layer edges (architecture §3 rule 1). `forms → js` is deliberately absent.+pub const SIDEWAYS: &[(&str, &str)] = &[+ ("redact", "edit"),+ ("a11y", "preflight"),+ ("prepress", "preflight"),+ ("export", "ocr"),+ ("sign", "security"),+ ("ui-egui", "ui-common"),+ ("ui-egui", "platform"),+ ("automation", "platform"),+];++/// External crates that constitute a UI toolkit / windowing dependency (prefix match with `*`).+pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "egui_extras", "egui_dock", "egui_tiles", "rfd", "wgpu*"];+pub const UI_MIN_LAYER: u8 = 7;++pub fn short_name(pkg: &str) -> &str {+ pkg.strip_prefix("printcraft-").unwrap_or(pkg)+}++pub fn classify(pkg: &str) -> Option<Class> {+ let s = short_name(pkg);+ TABLE.iter().find(|(n, _)| *n == s).map(|(_, c)| *c)+}++fn is_ui_crate(name: &str) -> bool {+ UI_CRATES.iter().any(|p| match p.strip_suffix('*') {+ Some(prefix) => name.starts_with(prefix),+ None => name == *p,+ })+}++fn sideways_allowed(from: &str, to: &str) -> bool {+ SIDEWAYS.contains(&(short_name(from), short_name(to)))+}++fn standalone_allowed(from: &str, to: &str) -> bool {+ STANDALONE_DEPS.iter().any(|(f, ok)| *f == short_name(from) && ok.contains(&short_name(to)))+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DepKind {+ Normal,+ Dev,+ Build,+}++#[derive(Debug, Clone)]+pub struct Dep {+ pub name: String,+ pub kind: DepKind,+ pub workspace: bool,+}++#[derive(Debug, Clone)]+pub struct Crate {+ pub name: String,+ pub deps: Vec<Dep>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Violation {+ Unregistered { krate: String },+ Upward { krate: String, dep: String, from: u8, to: u8, kind: DepKind },+ StandaloneHasWorkspaceDep { krate: String, dep: String },+ TestkitAsNormalDep { krate: String, dep: String },+ UiBelowL7 { krate: String, dep: String, layer: u8 },+}++impl std::fmt::Display for Violation {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Violation::Unregistered { krate } => {+ write!(f, "{krate}: unknown workspace crate; register it in xtask/src/layers.rs TABLE (plan/architecture.md §3)")+ }+ Violation::Upward { krate, dep, from, to, kind } => {+ write!(f, "{krate} (L{from}) -> {dep} (L{to}) [{kind:?}]: may only depend on lower layers (or an allowed sideways edge)")+ }+ Violation::StandaloneHasWorkspaceDep { krate, dep } => write!(f, "{krate}: standalone crate must not depend on workspace crate {dep}"),+ Violation::TestkitAsNormalDep { krate, dep } => write!(f, "{krate}: {dep} may only be a dev-dependency"),+ Violation::UiBelowL7 { krate, dep, layer } => {+ write!(f, "{krate} (L{layer}) depends on UI crate `{dep}`; UI toolkits are only allowed in L7+")+ }+ }+ }+}++pub fn check(crates: &[Crate]) -> Vec<Violation> {+ let mut out = Vec::new();+ for c in crates {+ let Some(class) = classify(&c.name) else {+ out.push(Violation::Unregistered { krate: c.name.clone() });+ continue;+ };+ if class == Class::Exempt {+ continue;+ }+ let layer = class.layer().unwrap_or(0);+ for d in &c.deps {+ if d.name == c.name {+ continue;+ }+ if d.workspace {+ if matches!(class, Class::Standalone(_)) && !standalone_allowed(&c.name, &d.name) {+ out.push(Violation::StandaloneHasWorkspaceDep { krate: c.name.clone(), dep: d.name.clone() });+ continue;+ }+ match classify(&d.name) {+ None => {}+ Some(Class::Testkit) => {+ if d.kind != DepKind::Dev && class != Class::Testkit {+ out.push(Violation::TestkitAsNormalDep { krate: c.name.clone(), dep: d.name.clone() });+ }+ }+ Some(dc) => {+ let to = dc.layer().unwrap_or(u8::MAX);+ let ok = to < layer || (to == layer && sideways_allowed(&c.name, &d.name));+ if !ok {+ out.push(Violation::Upward { krate: c.name.clone(), dep: d.name.clone(), from: layer, to: to.min(8), kind: d.kind });+ }+ }+ }+ } else if layer < UI_MIN_LAYER && is_ui_crate(&d.name) && !(class == Class::Testkit || d.kind == DepKind::Dev && d.name == "egui_kittest")+ {+ out.push(Violation::UiBelowL7 { krate: c.name.clone(), dep: d.name.clone(), layer });+ }+ }+ }+ out.sort_by_key(|v| v.to_string());+ out.dedup();+ out+}++pub fn from_metadata(meta: &Value) -> Result<Vec<Crate>, String> {+ let pkgs = meta["packages"].as_array().ok_or("metadata: no packages array")?;+ let members: Vec<&str> = pkgs.iter().filter_map(|p| p["name"].as_str()).collect();+ let mut out = Vec::new();+ for p in pkgs {+ let name = p["name"].as_str().ok_or("package without name")?.to_owned();+ let mut deps = Vec::new();+ for d in p["dependencies"].as_array().into_iter().flatten() {+ let dname = d["name"].as_str().unwrap_or_default().to_owned();+ let kind = match d["kind"].as_str() {+ Some("dev") => DepKind::Dev,+ Some("build") => DepKind::Build,+ _ => DepKind::Normal,+ };+ let workspace = members.contains(&dname.as_str());+ deps.push(Dep { name: dname, kind, workspace });+ }+ out.push(Crate { name, deps });+ }+ out.sort_by(|a, b| a.name.cmp(&b.name));+ Ok(out)+}++pub fn describe(class: Option<Class>) -> String {+ match class {+ Some(Class::Layer(l)) => format!("L{l}"),+ Some(Class::Standalone(l)) => format!("L{l} standalone"),+ Some(Class::Testkit) => "test support".into(),+ Some(Class::Exempt) => "exempt".into(),+ None => "UNREGISTERED".into(),+ }+}++#[cfg(test)]+mod tests {+ use super::DepKind::*;+ use super::*;++ fn c(name: &str, deps: &[(&str, DepKind, bool)]) -> Crate {+ Crate { name: name.into(), deps: deps.iter().map(|(n, k, w)| Dep { name: (*n).into(), kind: *k, workspace: *w }).collect() }+ }++ #[test]+ fn current_graph_shape_passes() {+ let g = [+ c("printcraft-geom", &[]),+ c("printcraft-render", &[("hayro", Normal, false), ("lopdf", Normal, false)]),+ c("printcraft-engine", &[("printcraft-render", Normal, true)]),+ c("printcraft-ui-egui", &[("printcraft-engine", Normal, true), ("egui", Normal, false), ("egui_kittest", Dev, false)]),+ c("printcraft", &[("printcraft-ui-egui", Normal, true)]),+ ];+ assert!(check(&g).is_empty(), "{:?}", check(&g));+ }++ #[test]+ fn upward_and_sideways_edges_flagged() {+ let v = check(&[c("printcraft-model", &[("printcraft-engine", Normal, true)])]);+ assert!(matches!(v[..], [Violation::Upward { from: 2, to: 6, .. }]));+ // forms -> js must go through the ActionRunner trait, never directly.+ let v = check(&[c("printcraft-forms", &[("printcraft-js", Normal, true)])]);+ assert!(matches!(v[..], [Violation::Upward { from: 3, to: 3, .. }]));+ }++ #[test]+ fn listed_sideways_edges_allowed() {+ assert!(check(&[c("printcraft-redact", &[("printcraft-edit", Normal, true)])]).is_empty());+ assert!(!check(&[c("printcraft-edit", &[("printcraft-redact", Normal, true)])]).is_empty());+ }++ #[test]+ fn cos_may_use_only_its_listed_foundation() {+ assert!(check(&[c("printcraft-cos", &[("printcraft-filters", Normal, true), ("printcraft-crypt", Normal, true)])]).is_empty());+ let v = check(&[c("printcraft-cos", &[("printcraft-arlington", Normal, true)])]);+ assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]));+ let v = check(&[c("printcraft-filters", &[("printcraft-geom", Normal, true)])]);+ assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]));+ }++ #[test]+ fn ui_crates_below_l7_flagged() {+ for dep in ["egui", "eframe", "winit", "rfd", "wgpu", "wgpu-core", "egui_dock"] {+ let v = check(&[c("printcraft-engine", &[(dep, Normal, false)])]);+ assert!(matches!(v[..], [Violation::UiBelowL7 { layer: 6, .. }]), "{dep}");+ }+ assert!(check(&[c("printcraft-platform", &[("winit", Normal, false)])]).is_empty());+ }++ #[test]+ fn test_support_only_as_dev_dependency() {+ let v = check(&[c("printcraft-cos", &[("printcraft-testkit", Normal, true)])]);+ assert!(!v.is_empty());+ assert!(check(&[c("printcraft-render", &[("printcraft-oracle", Dev, true)])]).is_empty());+ let v = check(&[c("printcraft-render", &[("printcraft-oracle", Normal, true)])]);+ assert!(matches!(v[..], [Violation::TestkitAsNormalDep { .. }]));+ }++ #[test]+ fn unregistered_crate_is_error() {+ let v = check(&[c("printcraft-mystery", &[])]);+ assert!(matches!(&v[..], [Violation::Unregistered { krate }] if krate == "printcraft-mystery"));+ }++ #[test]+ fn apps_exempt() {+ for app in ["printcraft", "printcraft-cli", "printcraft-web", "xtask"] {+ assert!(check(&[c(app, &[("egui", Normal, false), ("printcraft-ui-egui", Normal, true)])]).is_empty());+ }+ }+}diff --git a/xtask/src/main.rs b/xtask/src/main.rsindex 1ab7b4349..3edfedcae 100644--- a/xtask/src/main.rs+++ b/xtask/src/main.rs@@ -3,15 +3,21 @@use std::process::ExitCode;mod demo_pdf;+mod gates;+mod layers;type Command = fn(&[String]) -> anyhow::Result<()>;/// Every subcommand: name, one-line summary, entry point.-const COMMANDS: &[(&str, &str, Command)] = &[(- "demo-pdf",- "Build dist/demo/printcraft-showcase.pdf (needs Google Chrome or Chromium)",- demo_pdf::run,-)];+const COMMANDS: &[(&str, &str, Command)] = &[+ ("layers", "Enforce the crate dependency layering (plan/architecture.md §3)", gates::layers),+ ("wasm", "cargo check --target wasm32-unknown-unknown for every crate below L8", gates::wasm),+ ("ci", "fmt --check, clippy -D warnings, test, layers, wasm (stops at first failure)", gates::ci),+ ("corpus", "Fetch test corpora into corpus/ (git-ignored): pdf.js test PDFs", gates::corpus),+ ("check", "Robustness sweep over corpus/ with printcraft-cli; fails on crashes or regressions vs xtask/baselines", gates::check),+ ("text-oracle", "Compare text extraction with pdftotext over corpus/ (word F1; target median ≥ 0.97)", gates::text_oracle),+ ("demo-pdf", "Build dist/demo/printcraft-showcase.pdf (needs Google Chrome or Chromium)", demo_pdf::run),+];fn main() -> ExitCode {let args: Vec<String> = std::env::args().skip(1).collect();