diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cbda7377c7..d13972d7d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,6 +46,10 @@ jobs: # A missing oracle fails the job instead of printing a skip notice that reads as a pass. linux-env: PDFCRAFT_ORACLES_REQUIRED=1 windows-env: PDFCRAFT_REQUIRE_WINRES=1 + # Windows completed its 54m33s gate, then cache save hit the default 60m job cap + # (run 44364342368). Leave bounded room for setup and post-job cleanup. + # This changes no test watchdog or selection; craft-common-actions#60. + timeout-minutes: 90 # Preserve the packaging regression check removed from git-sources in #7042. command: | pwsh -NoProfile -File packaging/windows/test-font-notices.ps1 diff --git a/Cargo.lock b/Cargo.lock index ce3a8273ac..d44f44f5bb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1190,6 +1190,11 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-cfb" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" + [[package]] name = "craft-cms" version = "0.1.0" @@ -1211,7 +1216,7 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f29e82f1a7a009e68312bd2e84adab72be23344d#f29e82f1a7a009e68312bd2e84adab72be23344d" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" [[package]] name = "craft-csv" @@ -1226,12 +1231,64 @@ name = "craft-docpath" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +[[package]] +name = "craft-docx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "base64 0.23.1", + "chrono", + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "craft-math 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "craft-offcrypto", + "craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "log", + "quick-xml 0.41.0", + "thiserror 2.0.21", + "unicode-bidi", + "zeroize", +] + +[[package]] +name = "craft-drawingml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "kurbo 0.13.1", + "log", + "serde", +] + +[[package]] +name = "craft-drawingml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "kurbo 0.13.1", + "log", + "serde", +] + +[[package]] +name = "craft-flow" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "image", + "log", +] + [[package]] name = "craft-flow" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33#fbb3f47f7ae712192586984af11ca8f6c0f64d33" dependencies = [ - "craft-wordmodel", + "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)", "image", "log", ] @@ -1314,9 +1371,18 @@ name = "craft-markdown" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33#fbb3f47f7ae712192586984af11ca8f6c0f64d33" dependencies = [ - "craft-flow", + "craft-flow 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)", "craft-html", - "craft-wordmodel", + "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)", +] + +[[package]] +name = "craft-math" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "serde", ] [[package]] @@ -1341,23 +1407,62 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-metafile" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "encoding_rs", + "image", + "kurbo 0.13.1", + "thiserror 2.0.21", +] + [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f29e82f1a7a009e68312bd2e84adab72be23344d#f29e82f1a7a009e68312bd2e84adab72be23344d" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" dependencies = [ "chrono", "craft-codepage", "encoding_rs", ] +[[package]] +name = "craft-offcrypto" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "aes", + "base64 0.23.1", + "craft-cfb", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "getrandom 0.3.4", + "hmac", + "sha1 0.11.0", + "sha2 0.11.1", + "thiserror 2.0.21", + "zeroize", +] + [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", - "craft-zip", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "log", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-opc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", "log", "thiserror 2.0.21", ] @@ -1413,6 +1518,21 @@ dependencies = [ "zeroize", ] +[[package]] +name = "craft-pptx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "kurbo 0.13.1", + "log", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-prc" version = "0.1.0" @@ -1450,10 +1570,14 @@ dependencies = [ [[package]] name = "craft-rtf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f29e82f1a7a009e68312bd2e84adab72be23344d#f29e82f1a7a009e68312bd2e84adab72be23344d" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" dependencies = [ "craft-codepage", + "craft-flow 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "craft-metafile", + "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", "encoding_rs", + "image", ] [[package]] @@ -1552,13 +1676,27 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "craft-wordmodel" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "base64 0.23.1", + "craft-math 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", + "log", + "serde", + "serde_json", + "thiserror 2.0.21", + "unicode-segmentation", +] + [[package]] name = "craft-wordmodel" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33#fbb3f47f7ae712192586984af11ca8f6c0f64d33" dependencies = [ "base64 0.23.1", - "craft-math", + "craft-math 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)", "log", "serde", "serde_json", @@ -1583,6 +1721,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -1593,6 +1741,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -1622,6 +1780,26 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -2759,9 +2937,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] @@ -3096,6 +3276,7 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33" [[package]] name = "hayro-syntax" @@ -3730,6 +3911,7 @@ dependencies = [ "arrayvec", "euclid", "polycool", + "serde", "smallvec", ] @@ -4698,8 +4880,10 @@ version = "0.21.1" dependencies = [ "base64 0.23.1", "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", + "craft-docx", "craft-image-codecs", "craft-prc", + "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", "flate2", "pdfcraft-cos", "pdfcraft-engine", @@ -4856,12 +5040,14 @@ dependencies = [ name = "pdfcraft-export" version = "0.21.1" dependencies = [ + "craft-docx", "craft-markdown", "craft-mime", - "craft-opc", + "craft-pptx", "craft-rtf", + "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", - "craft-zip", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "flate2", ] diff --git a/Cargo.toml b/Cargo.toml index 9f4d5155e4..9becf77a2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,19 +36,20 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e2dc681a3", features = ["egui"] } craft-pdf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "8e03cd016d42032b867fef6bad86bc69bf2c1920", features = ["cos", "crypt", "filters"] } -# The writer the RTF export maps onto (storytold/craft-libs#793), at storytold/craft-libs#1467: -# its font and colour lookups take constant time, as PdfCraft's own writer did. -craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "f29e82f1a7a009e68312bd2e84adab72be23344d" } +# The writers the Word and RTF exports map onto (storytold/craft-libs#793). craft-rtf, craft-wordmodel and +# craft-docx move together: craft_rtf::doc::export takes its own revision's Document. +craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" } # Shared Base64 encoder; use the existing RTF revision to reuse its codepage dependency. -craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "f29e82f1a7a009e68312bd2e84adab72be23344d" } +craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" } craft-csv = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } -craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } -craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } -craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } +craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" } +craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" } +craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "010702ee9b030844c852939095b1da0d0656a890" } +craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "010702ee9b030844c852939095b1da0d0656a890" } craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } # internal pdfcraft-geom = { path = "crates/geom", version = "0.21.0" } @@ -166,7 +167,7 @@ hayro-interpret = { path = "vendor/hayro-interpret" } hayro = { path = "vendor/hayro" } hayro-syntax = { path = "vendor/hayro-syntax" } hayro-cmap = { path = "vendor/hayro-cmap" } -hayro-postscript = { path = "vendor/hayro-postscript" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" } hayro-jbig2 = { path = "vendor/hayro-jbig2" } lopdf = { path = "vendor/lopdf" } vello_common = { path = "vendor/vello_common" } diff --git a/apps/pdfcraft/tests/it/vendor_graph.rs b/apps/pdfcraft/tests/it/vendor_graph.rs index aa870c92cc..c64833dcb1 100644 --- a/apps/pdfcraft/tests/it/vendor_graph.rs +++ b/apps/pdfcraft/tests/it/vendor_graph.rs @@ -72,7 +72,6 @@ fn renderer_and_security_vendors_remain() { "vendor/hayro-syntax", "vendor/hayro-cmap", "vendor/hayro-jbig2", - "vendor/hayro-postscript", "vendor/lopdf", "vendor/vello_common", ] { diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index eec9b172d9..9e9efaee9b 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -31,6 +31,9 @@ mcp = ["dep:base64"] # Synthetic printer profiles for the app-managed print colour tests. craft-cms = { workspace = true } craft-image-codecs = { workspace = true } +# Word exports read back as Word reads them. +craft-docx = { workspace = true } +craft-wordmodel = { workspace = true } pdfcraft-fonts = { workspace = true } flate2.workspace = true pdfcraft-model = { workspace = true } diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index c2bda33e06..01c32fcf0a 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -10190,29 +10190,37 @@ BT /F1 11 Tf 20 20 Td (Total due: 150.00) Tj ET"; let mut a = auto(&dir); let doc = ok(&mut a, "doc_open", json!({ "path": "invoice.pdf" }))["doc"].as_u64().unwrap(); ok(&mut a, "doc_export_office", json!({ "doc": doc, "path": "invoice.docx" })); - // Inspect the actual package emitted by the tool, not an intermediate page model. - let zip = std::fs::read(dir.join("invoice.docx")).unwrap(); - let mut at = 0; - let mut xml = String::new(); - while zip[at..].starts_with(b"PK\x03\x04") { - let size = u32::from_le_bytes(zip[at + 18..at + 22].try_into().unwrap()) as usize; - let len = u16::from_le_bytes(zip[at + 26..at + 28].try_into().unwrap()) as usize; - let data = at + 30 + len; - if &zip[at + 30..data] == b"word/document.xml" { - std::io::Read::read_to_string(&mut flate2::read::DeflateDecoder::new(&zip[data..data + size]), &mut xml).unwrap(); - break; - } - at = data + size; - } - assert!(xml.contains("rotation:315.000"), "diagonal text survives extraction: {xml}"); - assert!(xml.contains("z-index:-2"), "the large watermark stays behind the invoice"); - assert!(!xml.contains("") && !xml.contains("")); - assert!(!xml.contains("w:val=\"single\"")); - assert_eq!(xml.matches(">DRAFT").count(), 1); - assert_eq!(xml.matches(">Total due: 150.00").count(), 1); - assert_eq!(xml.matches("").count(), 1); - assert!(!xml.contains("w:type=\"page\"")); - assert!(xml.contains("margin-left:20.000pt"), "invoice fields retain their left edge"); + // Inspect the actual package emitted by the tool, read back as Word reads it. + use craft_wordmodel::InlineObject; + use craft_wordmodel::para::Wrap; + let word = craft_docx::read(&std::fs::read(dir.join("invoice.docx")).unwrap()).unwrap(); + assert!(word.body.iter().all(|b| matches!(&**b, craft_wordmodel::Block::Para(_))), "no table"); + let objects: Vec<&InlineObject> = + word.body.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p) } else { None }).flat_map(|p| &p.objects).collect(); + let text_of = |o: &InlineObject| match o { + InlineObject::Shape { story: Some(id), .. } => word.parts.get(id).map(|p| { + p.blocks.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p.plain_text()) } else { None }).collect::() + }), + _ => None, + }; + let boxes: Vec<(String, &craft_wordmodel::para::Float)> = objects + .iter() + .filter_map(|o| match o { + InlineObject::Shape { float, .. } => text_of(o).map(|t| (t, float)), + _ => None, + }) + .collect(); + let draft: Vec<_> = boxes.iter().filter(|(t, _)| t == "DRAFT").collect(); + assert_eq!(draft.len(), 1, "{boxes:?}"); + assert!((draft[0].1.rot - 315.0).abs() < 0.01, "diagonal text survives extraction: {}", draft[0].1.rot); + assert_eq!(draft[0].1.wrap, Wrap::BehindText, "the large watermark stays behind the invoice"); + assert!(boxes.iter().filter(|(t, _)| t != "DRAFT").all(|(_, f)| f.z > draft[0].1.z)); + assert!(!objects.iter().any(|o| matches!(o, InlineObject::Image { float, .. } if float.wrap == Wrap::Inline))); + assert_eq!(boxes.iter().filter(|(t, _)| t == "Total due: 150.00").count(), 1); + assert_eq!(word.sections().len(), 1); + assert!(!word.body.iter().any(|b| matches!(&**b, craft_wordmodel::Block::Para(p) if p.text.contains(craft_wordmodel::para::PAGE_BREAK)))); + let description = boxes.iter().find(|(t, _)| t == "Description").expect("the Description field"); + assert_eq!(description.1.x, 20.0, "invoice fields retain their left edge"); let rendered = a.call("page_render", &json!({ "doc": doc, "page": 1, "dpi": 72 })).unwrap(); assert!(rendered.iter().any(|c| matches!(c, Content::Png { .. }))); } diff --git a/crates/engine/src/compare.rs b/crates/engine/src/compare.rs index a476e1538b..d9dd0eae57 100644 --- a/crates/engine/src/compare.rs +++ b/crates/engine/src/compare.rs @@ -329,9 +329,8 @@ impl crate::Document { /// [`Self::export_office`], and the pages whose text it had to leave out /// ([`OfficeExport::truncated_pages`]). pub fn export_office_checked(&self, format: OfficeFormat) -> OfficeExport { - // RTF and Markdown leave pictures out. - let (pages, truncated_pages) = - self.export_pages_checked(!matches!(format, OfficeFormat::Rtf | OfficeFormat::Markdown), MAX_EXPORT_IMAGE_BYTES); + // Markdown leaves pictures out. + let (pages, truncated_pages) = self.export_pages_checked(!matches!(format, OfficeFormat::Markdown), MAX_EXPORT_IMAGE_BYTES); let title = self.info.title.clone().unwrap_or_else(|| self.name.trim_end_matches(".pdf").to_string()); // Word and HTML name the document's language (`/Lang`), so spelling is checked in it. let language = self.initial_view().language; @@ -340,7 +339,7 @@ impl crate::Document { OfficeFormat::Pptx => pdfcraft_export::pptx(&pages, &title), OfficeFormat::Html => pdfcraft_export::html_with_language(&pages, &title, language.as_deref()).into_bytes(), OfficeFormat::HtmlSimple => pdfcraft_export::html_simple_with_language(&pages, &title, language.as_deref()).into_bytes(), - OfficeFormat::Rtf => pdfcraft_export::rtf(&pages).into_bytes(), + OfficeFormat::Rtf => pdfcraft_export::rtf_with_title(&pages, &title).into_bytes(), OfficeFormat::Markdown => pdfcraft_export::markdown(&pages).into_bytes(), }; OfficeExport { bytes, truncated_pages } diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml index 7da25ce59b..c23ef4ec71 100644 --- a/crates/export/Cargo.toml +++ b/crates/export/Cargo.toml @@ -13,8 +13,10 @@ workspace = true [dependencies] craft-markdown.workspace = true craft-mime.workspace = true -craft-opc.workspace = true -craft-rtf.workspace = true +craft-rtf = { workspace = true, features = ["doc"] } +craft-wordmodel.workspace = true +craft-docx.workspace = true +craft-pptx.workspace = true craft-xml.workspace = true craft-zip.workspace = true diff --git a/crates/export/src/as_docx.rs b/crates/export/src/as_docx.rs index 24b1c5eb98..bfb0ba4bc4 100644 --- a/crates/export/src/as_docx.rs +++ b/crates/export/src/as_docx.rs @@ -1,7 +1,10 @@ -use super::as_html::language_tag; -use super::layout::{Image, Item, Page, Table, body_size, items, reading_order}; -use craft_opc::{PackageOut, RT_BASE, RelOut, RelsOut}; -use craft_xml::{Writer, esc}; +//! Word (.docx) through craft-docx (storytold/craft-libs#793): the pages are mapped onto a +//! `craft_wordmodel::Document` ([`super::as_word`]); pages that can't flow keep their layout as +//! positioned text boxes and pictures. + +use super::as_word::{Meta, word_doc}; +use super::layout::{Image, Page}; +use craft_xml::Writer; pub(crate) fn core_properties_xml(title: &str) -> Vec { let mut w = Writer::document(); @@ -37,112 +40,6 @@ pub(crate) fn hex(c: [f64; 3]) -> Option { (r | g | b != 0).then(|| format!("{r:02X}{g:02X}{b:02X}")) } -/// A formatted text run (shared by paragraphs and table cells). -fn run_xml(text: &str, size: f64, bold: bool, italic: bool, color: [f64; 3]) -> String { - let mut rpr = String::new(); - if bold { - rpr.push_str(""); - } - if italic { - rpr.push_str(""); - } - if let Some(h) = hex(color) { - rpr.push_str(&format!("")); - } - let half_points = if size.is_finite() { (size * 2.0).round().clamp(2.0, 3276.0) as i64 } else { 24 }; - rpr.push_str(&format!("")); - format!("{rpr}{}", esc(text)) -} - -/// One Word table: when the page's rules draw its grid, single inside borders and single outer -/// borders on the edges they rule; explicit absent borders otherwise (alignment alone cannot -/// prove PDF rules), a grid sized from the detected column -/// edges, `gridSpan` for spanning cells, empty cells for holes. -pub(crate) fn docx_table(t: &Table) -> String { - let mut edges = t.cols.clone(); - edges.push(t.rect[2]); - let widths: Vec = edges.windows(2).map(|w| ((w[1] - w[0]).max(20.0) * 20.0).round().clamp(60.0, 31680.0) as i64).collect(); - let mut s = String::from(""); - let [top, left, bottom, right] = t.ruled.unwrap_or_default(); - let inside = t.ruled.is_some(); - for (edge, drawn) in [("top", top), ("left", left), ("bottom", bottom), ("right", right), ("insideH", inside), ("insideV", inside)] { - if drawn { - s.push_str(&format!("")); - } else { - s.push_str(&format!("")); - } - } - s.push_str(""); - for w in &widths { - s.push_str(&format!("")); - } - s.push_str(""); - for row in &t.rows { - s.push_str(""); - let mut column = 0usize; - for c in row { - let span = if c.span > 1 { format!("", c.span) } else { String::new() }; - let w: i64 = widths.iter().skip(column).take(c.span).sum(); - s.push_str(&format!( - "{span}{}", - run_xml(&c.text, c.size, c.bold, c.italic, c.color) - )); - column = column.saturating_add(c.span); - } - // Pad the grid so every row covers all columns (Word rejects short rows). - for _ in column..t.cols.len() { - s.push_str(""); - } - s.push_str(""); - } - s.push_str(""); - s -} - -/// Pages with rotated text, or text that actually overlaps an image or an oversized -/// (watermark-like) text block, cannot be put in paragraph flow without changing their layout. -/// Keep those pages as editable, absolutely positioned text boxes. Every other page, including -/// one with a logo or a big title that sits clear of the text, flows as paragraphs and tables. -fn positioned(page: &Page) -> bool { - if page.blocks.iter().any(|b| b.rotation.abs() > 0.1) { - return true; - } - let body = body_size(std::slice::from_ref(page)).max(1.0); - let overlays = page - .images - .iter() - .map(|im| (im.rect, None)) - .chain(page.blocks.iter().enumerate().filter(|(_, b)| b.size >= 2.0 * body).map(|(i, b)| (b.rect, Some(i)))); - // Bound the pairwise test on hostile pages (many overlays times many blocks): past the - // budget, keep the default flowing layout. - let mut budget: usize = 1_000_000; - for (r, own) in overlays { - for (i, b) in page.blocks.iter().enumerate() { - if budget == 0 { - return false; - } - budget -= 1; - if Some(i) != own && overlaps(r, b.rect) { - return true; - } - } - } - false -} - -/// Whether two [x0, y0, x1, y1] boxes share more than a hairline (0.5 pt each way); boxes that -/// only touch, or hostile non-finite coordinates, do not count. -fn overlaps(a: [f64; 4], b: [f64; 4]) -> bool { - let w = a[2].min(b[2]) - a[0].max(b[0]); - let h = a[3].min(b[3]) - a[1].max(b[1]); - w.is_finite() && h.is_finite() && w > 0.5 && h > 0.5 -} - -/// Bound every value written into a shape's style, including hostile PDF coordinates. -fn layout_number(n: f64) -> f64 { - if n.is_finite() { n.clamp(-1584.0, 1584.0) } else { 0.0 } -} - /// Most images a Word export embeds, and most image bytes (the zip writer has 32-bit sizes and /// a 16-bit entry count; a hostile PDF must not be able to overflow them). pub(crate) const MAX_MEDIA: usize = 1000; @@ -156,135 +53,12 @@ pub(crate) fn room_for(media: &[(String, &Image)], im: &Image) -> bool { && media.iter().map(|(_, m)| m.bytes.len()).fold(im.bytes.len(), usize::saturating_add) <= MAX_MEDIA_BYTES } -/// Points as EMU (12700 per point); non-finite values are 0. -fn emu(pt: f64) -> i64 { - if pt.is_finite() { (pt * 12700.0).round() as i64 } else { 0 } -} +/// The body text's font. A reader without Arial draws it in a sans-serif: the font table says +/// it is one (Word and LibreOffice substitute their own sans, LibreOffice Liberation Sans). +const FONT: &str = "Arial"; -/// The `a:graphic` of one picture (DrawingML), rotated by `rotation` degrees when given. -fn picture_xml(n: usize, name: &str, (cx, cy): (i64, i64), rotation: Option) -> String { - let rot = rotation.map_or(String::new(), |r| format!(" rot=\"{}\"", (r * 60000.0).round() as i64)); - format!( - "\ -\ -\ -\ -\ -" - ) -} - -fn positioned_page<'a>(page: &'a Page, media: &mut Vec<(String, &'a Image)>, shape_id: &mut usize) -> String { - // One 1 pt paragraph anchors the whole page. Shapes never reserve body space, so even a - // page-sized watermark cannot push the invoice footer onto another page. - let mut s = String::from(""); - let body = body_size(std::slice::from_ref(page)).max(1.0); - // Rotated pages are positioned shapes, so paragraph flow never orders them. Emit the - // text boxes in reading order; the file's block order is not the reading order. - let blocks = reading_order(page, page.blocks.iter().map(|b| (b.rect, b.size, b)).collect()); - for b in blocks { - *shape_id = shape_id.saturating_add(1); - let rotation = layout_number(-b.rotation).rem_euclid(360.0); - let (sin, cos) = rotation.to_radians().sin_cos(); - let (bw, bh) = (layout_number(b.rect[2] - b.rect[0]).max(1.0), layout_number(b.rect[3] - b.rect[1]).max(1.0)); - let h = if b.rotation.abs() > 0.1 { layout_number(b.size).max(1.0) } else { bh }; - // Recover the unrotated width from the axis-aligned box. Use the larger axis so - // quarter turns and 45-degree watermarks do not divide by (nearly) zero. - let w = if b.rotation.abs() <= 0.1 { - bw - } else if cos.abs() >= sin.abs() { - (bw - h * sin.abs()) / cos.abs() - } else { - (bh - h * cos.abs()) / sin.abs() - }; - let w = layout_number(w).max(1.0); - let (x, y) = (layout_number(b.rect[0] + (bw - w) / 2.0), layout_number(page.height - b.rect[3] + (bh - h) / 2.0)); - let z = if b.size >= 2.0 * body { -2 } else { 1 }; - let style = format!( - "position:absolute;margin-left:{x:.3}pt;margin-top:{y:.3}pt;width:{w:.3}pt;height:{h:.3}pt;rotation:{rotation:.3};z-index:{z};mso-position-horizontal-relative:page;mso-position-vertical-relative:page" - ); - s.push_str(&format!( - "{}", - shape_id, run_xml(&b.text, b.size, b.bold, b.italic, b.color) - )); - } - for im in &page.images { - if !room_for(media, im) { - continue; - } - *shape_id = shape_id.saturating_add(1); - let n = media.len().saturating_add(1); - let (w, h) = (layout_number(im.size[0]).max(1.0), layout_number(im.size[1]).max(1.0)); - let (x, y) = (layout_number((im.rect[0] + im.rect[2] - w) / 2.0), layout_number(page.height - (im.rect[1] + im.rect[3] + h) / 2.0)); - let rotation = layout_number(-im.rotation).rem_euclid(360.0); - let name = format!("image{n}.{}", im.ext); - let pic = picture_xml(n, &name, (emu(w), emu(h)), Some(rotation)); - // A DrawingML anchor, the way Word itself stores a picture placed behind text: a VML - // rectangle with an image does not show the picture. - s.push_str(&format!( - "\ -{}{}\ -", - n.saturating_add(1), - emu(x), - emu(y), - emu(w), - emu(h), - )); - s.push_str(&pic); - s.push_str(""); - media.push((name, im)); - } - s.push_str(""); - s -} - -fn word_page_size(page: &Page) -> (i64, i64) { - let twips = |pt: f64| if pt.is_finite() { (pt * 20.0).round().clamp(144.0, 31680.0) as i64 } else { 12240 }; - (twips(page.width), twips(page.height)) -} - -fn section(page: &Page) -> String { - let (pw, ph) = word_page_size(page); - let (mx, my) = ((pw / 8).min(1440), (ph / 8).min(1440)); - format!( - "", - my / 2, - my / 2 - ) -} - -/// The page colour of a Word document: Word has one background for the whole document, so it -/// is written only when every page has the same, non-white background (#2992). -fn word_background(pages: &[Page]) -> Option { - let first = rgb8(pages.first()?.background?); - let same = pages.iter().all(|p| p.background.map(rgb8) == Some(first)); - (same && first != [255, 255, 255]).then(|| format!("{:02X}{:02X}{:02X}", first[0], first[1], first[2])) -} - -/// The `w:lang` that makes `tag` the language of a Word document's text. Word keeps one language -/// per script: Chinese, Japanese and Korean are its East Asian text, Arabic, Hebrew, Persian and -/// Urdu its right-to-left text, and any other language its Latin, Greek and Cyrillic text. A -/// script the tag names (`pa-Arab`, `zh-Latn`) decides over its language. -fn word_lang(tag: &str) -> String { - let mut subtags = tag.split('-'); - let primary = subtags.next().unwrap_or_default().to_ascii_lowercase(); - // The script comes straight after the language and any three-letter extended languages; a - // singleton before it starts an extension or private use, which names no script. - let script = subtags - .find(|s| s.len() != 3 || !s.bytes().all(|b| b.is_ascii_alphabetic())) - .filter(|s| s.len() == 4 && s.bytes().all(|b| b.is_ascii_alphabetic())) - .map(str::to_ascii_lowercase); - let attribute = match (script.as_deref(), primary.as_str()) { - (Some("arab" | "hebr" | "syrc" | "thaa"), _) => "w:bidi", - (Some("hans" | "hant" | "hani" | "jpan" | "kore" | "hang" | "hira" | "kana"), _) => "w:eastAsia", - (Some("latn" | "cyrl" | "grek"), _) => "w:val", - (_, "zh" | "ja" | "ko") => "w:eastAsia", - (_, "ar" | "he" | "fa" | "ur") => "w:bidi", - _ => "w:val", - }; - format!("", esc(tag)) -} +/// The application `docProps/app.xml` names. +const APPLICATION: &str = "PdfCraft"; /// A Word document (.docx, Office Open XML). Ordinary pages flow as paragraphs and tables; /// pages with rotated text, or text that overlaps artwork, use floating shapes to retain their layout. @@ -296,121 +70,8 @@ pub fn docx(pages: &[Page], title: &str) -> Vec { /// it): the default language of its text, so Word checks the spelling in that language rather /// than in its own. A language that is not a well formed tag is left out. pub fn docx_with_language(pages: &[Page], title: &str, language: Option<&str>) -> Vec { - let mut body = String::new(); - let mut media: Vec<(String, &Image)> = Vec::new(); - // Word needs a paragraph between adjacent tables and after the last one in the body. - let mut after_table = false; - let mut shape_id = 0usize; - for (page_index, page) in pages.iter().enumerate() { - let (pw, _) = word_page_size(page); - let text_w = (pw - 2 * (pw / 8).min(1440)) as f64 / 20.0; - if positioned(page) { - body.push_str(&positioned_page(page, &mut media, &mut shape_id)); - after_table = false; - } else { - for it in items(std::slice::from_ref(page)) { - match &it { - Item::Para(runs, lvl) => { - let style = match lvl { - 1 => "", - 2 => "", - _ => "", - }; - body.push_str(""); - body.push_str(style); - for r in runs { - body.push_str(&run_xml(&r.text, r.block.size, r.block.bold, r.block.italic, r.block.color)); - } - body.push_str(""); - } - Item::Table(t) => { - if after_table { - body.push_str(""); - } - body.push_str(&docx_table(t)); - } - Item::Img(im) => { - if room_for(&media, im) { - let n = media.len() + 1; - let name = format!("image{n}.{}", im.ext); - // Size on the page, at most the text width. - let (w, h) = ((im.rect[2] - im.rect[0]).max(1.0), (im.rect[3] - im.rect[1]).max(1.0)); - let k = (text_w / w).min(1.0); - let (cx, cy) = (emu(w * k), emu(h * k)); - body.push_str(&format!("")); - body.push_str(&picture_xml(n, &name, (cx, cy), None)); - body.push_str(""); - media.push((name, im)); - } - } - Item::PageBreak => body.push_str(""), - } - after_table = matches!(it, Item::Table(_)); - } - } - // Section breaks carry this source page's size and create exactly one next page. - // The last section must be a direct child of the body (OOXML 17.6.17). - if page_index + 1 < pages.len() { - body.push_str(&format!( - "{}", - section(page) - )); - } else { - if after_table || page.blocks.is_empty() && page.images.is_empty() { - body.push_str(""); - } - body.push_str(§ion(page)); - } - after_table = false; - } - // Word shows a document background only when its settings say so (`settings.xml` below). - let page_colour = word_background(pages); - let background = page_colour.as_deref().map(|c| format!("")).unwrap_or_default(); - let doc = format!( - "\n\ -{background}{body}\ -" - ); - let mut pkg = PackageOut::default(); - let mut root_rels = RelsOut::default(); - root_rels.add("officeDocument", "word/document.xml", false); - root_rels.add("metadata/core-properties", "docProps/core.xml", false); - pkg.rels("", &root_rels); - - let mut doc_rels = RelsOut::default(); - doc_rels.items.push(RelOut { id: "rIdStyles".into(), ty: format!("{RT_BASE}styles"), target: "styles.xml".into(), external: false }); - for (i, (name, im)) in media.iter().enumerate() { - doc_rels.items.push(RelOut { - id: format!("rIdImg{}", i + 1), - ty: format!("{RT_BASE}image"), - target: format!("media/{name}"), - external: false, - }); - pkg.binary(&format!("word/media/{name}"), image_mime(im.ext), im.bytes.to_vec()); - } - if page_colour.is_some() { - doc_rels.items.push(RelOut { id: "rIdSettings".into(), ty: format!("{RT_BASE}settings"), target: "settings.xml".into(), external: false }); - } - pkg.rels("word/document.xml", &doc_rels); - let defaults = language_tag(language) - .map(|tag| format!("{}", word_lang(tag))) - .unwrap_or_default(); - let styles = format!( - "\n{defaults}\ -\ -\ -\ -" - ); - pkg.xml_part("docProps/core.xml", "application/vnd.openxmlformats-package.core-properties+xml", core_properties_xml(title)); - pkg.xml_part("word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", doc.into_bytes()); - pkg.xml_part("word/styles.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", styles.into_bytes()); - if page_colour.is_some() { - let mut settings = Writer::document(); - settings.open("w:settings", &[("xmlns:w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]); - settings.empty("w:displayBackgroundShape", &[]); - pkg.xml_part("word/settings.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", settings.into_bytes()); - } - pkg.finish().unwrap_or_default() + craft_docx::set_application_name(APPLICATION); + // Writing a document built here fails only on a hostile size the mapping already bounds; an + // empty result is what the export returned for a package it couldn't finish. + craft_docx::write(&word_doc(pages, &Meta { title, language, font: FONT })).unwrap_or_default() } diff --git a/crates/export/src/as_rtf.rs b/crates/export/src/as_rtf.rs index feea5306ee..b5ae44d137 100644 --- a/crates/export/src/as_rtf.rs +++ b/crates/export/src/as_rtf.rs @@ -1,90 +1,23 @@ -//! Rich Text Format through craft-rtf's writer: this module maps the pages onto its small model -//! (storytold/craft-libs#793). +//! Rich Text Format through craft-rtf's full writer (storytold/craft-libs#793): the pages are +//! mapped onto a `craft_wordmodel::Document` ([`super::as_word`]), every page flowing. -use super::as_docx::rgb8; -use super::as_html::allowed; -use super::layout::{Item, Page, Table, items}; -use craft_rtf::{Block, Cell, CharFmt, Document, PAGE_BREAK, Para, Run}; +use super::as_word::{Meta, flow_doc}; +use super::layout::Page; -/// The text as RTF may hold it: the characters Word refuses are left out. -fn clean(s: &str) -> String { - s.chars().filter(|c| allowed(*c)).collect() -} +/// The body text's font, as PdfCraft's RTF has always named it (a reader without Helvetica draws +/// it in its sans-serif, which the font table's `\fswiss` asks for). +const FONT: &str = "Helvetica"; -/// A run's formatting: its size in half points, bold, italic and colour (none for black, which -/// is the default). -fn char_fmt(size: f64, bold: bool, italic: bool, color: [f64; 3]) -> CharFmt { - let color = Some(rgb8(color)).filter(|c| *c != [0, 0, 0]); - // A size that is not finite or below zero becomes 0, as the cast saturates. - CharFmt { bold, italic, half_points: Some((size * 2.0).round() as u32), color, ..CharFmt::default() } -} +/// The application the RTF names as its writer (`{\*\generator}`). +pub(crate) const GENERATOR: &str = "PdfCraft"; -/// A table's rows. Each cell ends at the right edge of the last grid column it spans, in twips. -fn table(t: &Table) -> craft_rtf::Table { - let mut edges = t.cols.clone(); - edges.push(t.rect[2]); - let cellx: Vec = edges.iter().skip(1).map(|e| (e * 20.0).round() as i32).collect(); - let rows = t - .rows - .iter() - .map(|row| { - let mut column = 0; - row.iter() - .map(|c| { - column += c.span.max(1); - let right = cellx.get(column.min(cellx.len()).saturating_sub(1)).copied().unwrap_or(0); - let run = Run { text: clean(&c.text), fmt: char_fmt(c.size, c.bold, c.italic, c.color) }; - Cell { right, paras: vec![Para { runs: vec![run], ..Para::default() }] } - }) - .collect() - }) - .collect(); - craft_rtf::Table { rows } -} - -/// Keep a break outside tables, including when no text follows it on its page. -fn standalone_page_break(blocks: &mut Vec) { - let run = Run { text: PAGE_BREAK.to_string(), fmt: CharFmt::default() }; - blocks.push(Block::Para(Para { runs: vec![run], ..Para::default() })); -} - -/// Rich Text Format: paragraphs with their sizes, bold, italic and colours, real table rows, page -/// breaks between pages (images are left out). +/// Rich Text Format: paragraphs with their sizes, bold, italic and colours, headings, tables, +/// pictures, and each page in a section of its own size. pub fn rtf(pages: &[Page]) -> String { - let mut blocks = Vec::new(); - // A page break waits for what follows it: RTF's `\page` is a character in a paragraph, so it - // starts the next one, or stands alone before a table. - let mut page_break = false; - for it in items(pages) { - match it { - Item::Para(runs, _) => { - let mut runs: Vec = runs - .iter() - .map(|r| Run { text: clean(&r.text), fmt: char_fmt(r.block.size, r.block.bold, r.block.italic, r.block.color) }) - .collect(); - let Some(first) = runs.first_mut() else { continue }; - if std::mem::take(&mut page_break) { - first.text.insert(0, PAGE_BREAK); - } - blocks.push(Block::Para(Para { runs, ..Para::default() })); - } - Item::Table(t) => { - if std::mem::take(&mut page_break) { - standalone_page_break(&mut blocks); - } - blocks.push(Block::Table(table(&t))); - } - Item::Img(_) => {} - Item::PageBreak => { - if page_break { - standalone_page_break(&mut blocks); - } - page_break = true; - } - } - } - if page_break { - standalone_page_break(&mut blocks); - } - craft_rtf::write(&Document { blocks, pictures_left_out: 0 }, "Helvetica") + rtf_with_title(pages, "") +} + +/// [`rtf`] with the document's title (`\info\title`). +pub fn rtf_with_title(pages: &[Page], title: &str) -> String { + craft_rtf::doc::export_with_generator(&flow_doc(pages, &Meta { title, language: None, font: FONT }), GENERATOR) } diff --git a/crates/export/src/as_word.rs b/crates/export/src/as_word.rs new file mode 100644 index 0000000000..03a9ceaca1 --- /dev/null +++ b/crates/export/src/as_word.rs @@ -0,0 +1,443 @@ +//! The pages as a `craft_wordmodel::Document`, the model craft-libs' word-processing writers take +//! (storytold/craft-libs#793): paragraphs with their runs and heading levels, tables, pictures, +//! and a section per page with that page's size. RTF writes it with craft-rtf's full writer, every +//! page flowing ([`flow_doc`]); Word writes it with craft-docx, pages that can't flow kept as +//! positioned text boxes and pictures ([`word_doc`]). + +use super::as_docx::{rgb8, room_for}; +use super::as_html::{allowed, language_tag}; +use super::layout::{Image, Item, Page, Table, body_size, items, reading_order}; +use craft_wordmodel::para::{Anchor, Float, ShapeKind, Wrap}; +use craft_wordmodel::props::{Border, BorderStyle, Borders, CellProps, LineSpacing, TableProps}; +use craft_wordmodel::{Block, CharProps, Document, InlineObject, ParaProps, Paragraph, PartKind, Rgb, SectionProps, Style, StyleSheet, TextColor}; + +/// A run's formatting: its size, bold, italic and colour (none for black, the default). +fn chr(size: f64, bold: bool, italic: bool, color: [f64; 3]) -> CharProps { + let [r, g, b] = rgb8(color); + // Half points, as Word and RTF store sizes; one that is not finite gets the 12 pt default. + let half_points = if size.is_finite() { (size * 2.0).round().clamp(2.0, 3276.0) } else { 24.0 }; + CharProps { + size: Some(half_points as f32 / 2.0), + bold: bold.then_some(true), + italic: italic.then_some(true), + color: (r | g | b != 0).then_some(TextColor::Rgb(Rgb(r, g, b))), + ..CharProps::default() + } +} + +/// Appends `text` to `p` as a run (`Paragraph::push_text` drops U+FFFC, the model's object mark, +/// which in the PDF's text is a character, not an object), keeping only the characters Word and +/// RTF readers accept. +fn push_text(p: &mut Paragraph, text: &str, props: CharProps) { + // A hard line ending in the text (LF, CR or CRLF) is a line break, the model's `\n`, which the + // writers keep inside its paragraph or cell (storytold/pdfcraft#4723). + let text = text.replace("\r\n", "\n").replace('\r', "\n"); + let text: String = text.chars().filter(|c| allowed(*c)).collect(); + p.push_text(&text, &props); +} + +/// A table: its grid from the column edges, ruled where the PDF draws rules, one paragraph per +/// cell. +pub(crate) fn table(t: &Table) -> craft_wordmodel::Table { + let mut edges = t.cols.clone(); + edges.push(t.rect[2]); + // Whole twips, at least 3 pt wide (Word's narrowest column), as `as_docx` writes them. + let widths: Vec = edges.windows(2).map(|w| (((w[1] - w[0]).max(20.0) * 20.0).round().clamp(60.0, 31680.0) / 20.0) as f32).collect(); + let [top, left, bottom, right] = t.ruled.unwrap_or_default(); + let inside = t.ruled.is_some(); + let rule = |drawn: bool| Some(if drawn { Border { style: BorderStyle::Single, width: 0.5, color: None, space: 0.0 } } else { Border::default() }); + let props = TableProps { + borders: Some(Borders { + top: rule(top), + left: rule(left), + bottom: rule(bottom), + right: rule(right), + between: rule(inside), + inside_v: rule(inside), + }), + ..TableProps::default() + }; + let rows = t + .rows + .iter() + .map(|row| { + let mut cells = Vec::new(); + let mut column = 0usize; + for c in row { + let span = c.span.max(1); + let w: f32 = widths.iter().skip(column).take(span).sum(); + let mut p = Paragraph::new(); + push_text(&mut p, &c.text, chr(c.size, c.bold, c.italic, c.color)); + cells.push(craft_wordmodel::Cell { + props: CellProps { width: Some(w), span: span as u32, ..CellProps::default() }, + blocks: vec![craft_wordmodel::para_block(p)], + ..Default::default() + }); + column = column.saturating_add(span); + } + // A short row is padded to the grid, as Word expects every row to fill it. + for w in widths.iter().skip(column) { + cells.push(craft_wordmodel::Cell { + props: CellProps { width: Some(*w), ..CellProps::default() }, + blocks: vec![craft_wordmodel::para_block(Paragraph::new())], + ..Default::default() + }); + } + craft_wordmodel::Row { cells, ..Default::default() } + }) + .collect(); + craft_wordmodel::Table { props, grid: widths, rows, ..Default::default() } +} + +/// A page's section: its size, with margins of an eighth of each side, at most an inch. +fn section(page: &Page) -> SectionProps { + let twips = |pt: f64| if pt.is_finite() { (pt * 20.0).round().clamp(144.0, 31680.0) as i64 } else { 12240 }; + let (w, h) = (twips(page.width), twips(page.height)); + let (mx, my) = ((w / 8).min(1440), (h / 8).min(1440)); + let pt = |t: i64| t as f32 / 20.0; + SectionProps { + page_w: pt(w), + page_h: pt(h), + landscape: false, + margin_top: pt(my), + margin_bottom: pt(my), + margin_left: pt(mx), + margin_right: pt(mx), + header: pt(my / 2), + footer: pt(my / 2), + ..SectionProps::default() + } +} + +/// The document default formatting for text in `tag`. Word keeps one language per script: +/// Chinese, Japanese and Korean are its East Asian text, Arabic, Hebrew, Persian and Urdu its +/// right-to-left text, and any other language its Latin, Greek and Cyrillic text. A script the +/// tag names (`pa-Arab`, `zh-Latn`) decides over its language. +fn language(tag: &str) -> CharProps { + let mut subtags = tag.split('-'); + let primary = subtags.next().unwrap_or_default().to_ascii_lowercase(); + // The script comes straight after the language and any three-letter extended languages; a + // singleton before it starts an extension or private use, which names no script. + let script = subtags + .find(|s| s.len() != 3 || !s.bytes().all(|b| b.is_ascii_alphabetic())) + .filter(|s| s.len() == 4 && s.bytes().all(|b| b.is_ascii_alphabetic())) + .map(str::to_ascii_lowercase); + let tag = Some(tag.to_string()); + match (script.as_deref(), primary.as_str()) { + (Some("arab" | "hebr" | "syrc" | "thaa"), _) => CharProps { lang_bidi: tag, ..CharProps::default() }, + (Some("hans" | "hant" | "hani" | "jpan" | "kore" | "hang" | "hira" | "kana"), _) => CharProps { lang_ea: tag, ..CharProps::default() }, + (Some("latn" | "cyrl" | "grek"), _) => CharProps { lang: tag, ..CharProps::default() }, + (_, "zh" | "ja" | "ko") => CharProps { lang_ea: tag, ..CharProps::default() }, + (_, "ar" | "he" | "fa" | "ur") => CharProps { lang_bidi: tag, ..CharProps::default() }, + _ => CharProps { lang: tag, ..CharProps::default() }, + } +} + +/// The styles: the body text in `font`, in the document's language, and two heading levels. +fn styles(font: &str, lang: Option<&str>) -> StyleSheet { + let mut s = StyleSheet { styles: Vec::new(), ..StyleSheet::default() }; + s.default_chr = CharProps { font: Some(font.to_string()), ..language_tag(lang).map(language).unwrap_or_default() }; + // As `as_docx` set them: lines at 1.16 and 6 pt after each paragraph. + s.default_para = ParaProps { line_spacing: Some(LineSpacing::Multiple(1.16)), ..ParaProps::default() }; + s.default_para_present = true; + let normal = ParaProps { space_after: Some(6.0), ..ParaProps::default() }; + s.styles.push(Style { id: "Normal".into(), name: "Normal".into(), default: true, builtin: true, para: normal, ..Style::default() }); + for (lvl, before) in [(1u8, 12.0f32), (2, 10.0)] { + s.styles.push(Style { + id: format!("Heading{lvl}"), + name: format!("heading {lvl}"), + based_on: Some("Normal".into()), + next: Some("Normal".into()), + para: ParaProps { keep_next: Some(true), space_before: Some(before), outline_level: Some(lvl - 1), ..ParaProps::default() }, + chr: CharProps { bold: Some(true), ..CharProps::default() }, + builtin: true, + ..Style::default() + }); + } + s +} + +/// What the document holds besides its pages. +pub(crate) struct Meta<'a> { + pub title: &'a str, + /// The PDF's `/Lang`. + pub language: Option<&'a str>, + /// The body text's font. + pub font: &'a str, +} + +/// The document being built: the model, its body, and the pictures it has embedded so far (for +/// the export's limits on their count and size, [`room_for`]). +struct Builder<'a> { + doc: Document, + body: Vec, + media: Vec<(String, &'a Image)>, +} + +impl<'a> Builder<'a> { + fn new(pages: &[Page], meta: &Meta) -> Self { + let mut doc = Document::new(); + doc.styles = std::sync::Arc::new(styles(meta.font, meta.language)); + doc.core.title = meta.title.to_string(); + // A background every page shares is the document's page colour (#2992): Word has one for + // the whole document. + let shared = pages.first().and_then(|p| p.background).map(rgb8); + if let Some(c) = shared.filter(|c| *c != [255; 3] && pages.iter().all(|p| p.background.map(rgb8) == Some(*c))) { + doc.settings.page_color = Some(Rgb(c[0], c[1], c[2])); + } + Builder { doc, body: Vec::new(), media: Vec::new() } + } + + /// The media key for `im`, or `None` past the limits. + fn add_media(&mut self, im: &'a Image) -> Option { + if !room_for(&self.media, im) { + return None; + } + let key = self.doc.add_media(im.bytes.to_vec(), im.ext); + self.media.push((key.clone(), im)); + Some(key) + } + + /// One flowing item: a paragraph, a table, or a picture scaled to fit between the margins of + /// `sec`. + fn flow(&mut self, it: Item<'a>, sec: &SectionProps) { + match it { + Item::Para(runs, lvl) => { + let mut p = Paragraph::new(); + if matches!(lvl, 1 | 2) { + p.props.style = Some(format!("Heading{lvl}")); + } + for r in &runs { + push_text(&mut p, &r.text, chr(r.block.size, r.block.bold, r.block.italic, r.block.color)); + } + self.body.push(Block::Para(p)); + } + Item::Table(t) => { + // Tables that touch become one table: a paragraph keeps them apart. + if matches!(self.body.last(), Some(Block::Table(_))) { + self.body.push(Block::Para(Paragraph::new())); + } + self.body.push(Block::Table(table(&t))); + } + Item::Img(im) => { + let Some(media) = self.add_media(im) else { return }; + let text_w = f64::from((sec.page_w - sec.margin_left - sec.margin_right).max(1.0)); + let (w, h) = ((im.rect[2] - im.rect[0]).max(1.0), (im.rect[3] - im.rect[1]).max(1.0)); + let k = (text_w / w).min(1.0); + let pic = InlineObject::Image { + media, + w: (w * k) as f32, + h: (h * k) as f32, + alt: String::new(), + float: Float::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }; + let mut p = Paragraph::new(); + p.push_object(pic, &CharProps::default()); + self.body.push(Block::Para(p)); + } + Item::PageBreak => {} + } + } + + /// End a page: its section ends here, and the next page's starts on a new page. + fn end_page(&mut self, sec: SectionProps) { + let mut p = Paragraph::new(); + p.props = exact_1pt(); + p.section = Some(Box::new(sec)); + self.body.push(Block::Para(p)); + } + + fn finish(mut self, last: SectionProps) -> Document { + self.doc.last_section = last; + self.doc.body = self.body.into_iter().map(std::sync::Arc::new).collect(); + self.doc.ensure_nonempty(); + self.doc + } +} + +/// A paragraph that takes no room: no space around it and a 1 pt line. +fn exact_1pt() -> ParaProps { + ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(1.0)), ..ParaProps::default() } +} + +/// The pages as one flowing document: each page a section of its own size (so a page always +/// starts a new one, blank pages included), its paragraphs, tables and pictures in reading order. +/// Headings are told from the whole document's body size. +pub(crate) fn flow_doc(pages: &[Page], meta: &Meta) -> Document { + let mut b = Builder::new(pages, meta); + let mut page = 0usize; + let mut sec = pages.first().map(section).unwrap_or_default(); + for it in items(pages) { + if matches!(it, Item::PageBreak) { + b.end_page(sec); + page += 1; + sec = pages.get(page).map(section).unwrap_or_default(); + } else { + b.flow(it, &sec); + } + } + b.finish(sec) +} + +/// Pages with rotated text, or text that actually overlaps an image or an oversized +/// (watermark-like) text block, cannot be put in paragraph flow without changing their layout. +/// Keep those pages as editable, absolutely positioned text boxes. Every other page, including +/// one with a logo or a big title that sits clear of the text, flows as paragraphs and tables. +pub(crate) fn positioned(page: &Page) -> bool { + if page.blocks.iter().any(|b| b.rotation.abs() > 0.1) { + return true; + } + let body = body_size(std::slice::from_ref(page)).max(1.0); + let overlays = page + .images + .iter() + .map(|im| (im.rect, None)) + .chain(page.blocks.iter().enumerate().filter(|(_, b)| b.size >= 2.0 * body).map(|(i, b)| (b.rect, Some(i)))); + // Bound the pairwise test on hostile pages (many overlays times many blocks): past the + // budget, keep the default flowing layout. + let mut budget: usize = 1_000_000; + for (r, own) in overlays { + for (i, b) in page.blocks.iter().enumerate() { + if budget == 0 { + return false; + } + budget -= 1; + if Some(i) != own && overlaps(r, b.rect) { + return true; + } + } + } + false +} + +/// Whether two [x0, y0, x1, y1] boxes share more than a hairline (0.5 pt each way); boxes that +/// only touch, or hostile non-finite coordinates, do not count. +fn overlaps(a: [f64; 4], b: [f64; 4]) -> bool { + let w = a[2].min(b[2]) - a[0].max(b[0]); + let h = a[3].min(b[3]) - a[1].max(b[1]); + w.is_finite() && h.is_finite() && w > 0.5 && h > 0.5 +} + +/// Bound every value written into a shape's position and size, including hostile PDF coordinates. +fn layout_number(n: f64) -> f64 { + if n.is_finite() { n.clamp(-1584.0, 1584.0) } else { 0.0 } +} + +/// The stacking order (`Float::z`, higher on top) of watermark-sized text, which is behind +/// everything, of the page's pictures, over it, and of its other text, over both. +const Z_WATERMARK: u32 = 1; +const Z_PICTURE: u32 = 1 << 20; +const Z_TEXT: u32 = 1 << 21; + +/// A page that can't flow: one 1 pt paragraph anchors its text boxes and pictures, placed on the +/// page. Shapes never reserve body space, so even a page-sized watermark cannot push the text +/// after it onto another page. +fn positioned_page<'a>(b: &mut Builder<'a>, page: &'a Page) { + let mut anchor = Paragraph::new(); + anchor.props = exact_1pt(); + let body = body_size(std::slice::from_ref(page)).max(1.0); + // The text boxes in reading order, which a screen reader follows; the file's block order isn't + // the reading order. + let blocks = reading_order(page, page.blocks.iter().map(|bl| (bl.rect, bl.size, bl)).collect()); + for (i, bl) in blocks.into_iter().enumerate() { + let rotation = layout_number(-bl.rotation).rem_euclid(360.0); + let (sin, cos) = rotation.to_radians().sin_cos(); + let (bw, bh) = (layout_number(bl.rect[2] - bl.rect[0]).max(1.0), layout_number(bl.rect[3] - bl.rect[1]).max(1.0)); + let h = if bl.rotation.abs() > 0.1 { layout_number(bl.size).max(1.0) } else { bh }; + // Recover the unrotated width from the axis-aligned box. Use the larger axis so quarter + // turns and 45-degree watermarks do not divide by (nearly) zero. + let w = if bl.rotation.abs() <= 0.1 { + bw + } else if cos.abs() >= sin.abs() { + (bw - h * sin.abs()) / cos.abs() + } else { + (bh - h * cos.abs()) / sin.abs() + }; + let w = layout_number(w).max(1.0); + let (x, y) = (layout_number(bl.rect[0] + (bw - w) / 2.0), layout_number(page.height - bl.rect[3] + (bh - h) / 2.0)); + let mut p = Paragraph::new(); + p.props = ParaProps { space_before: Some(0.0), space_after: Some(0.0), ..ParaProps::default() }; + push_text(&mut p, &bl.text, chr(bl.size, bl.bold, bl.italic, bl.color)); + let story = b.doc.add_part(PartKind::TextBox, vec![craft_wordmodel::para_block(p)]); + if let Some(part) = b.doc.parts.get_mut(&story) { + // No inset, and the box grows to fit its text. + part.body.inset = Some([0; 4]); + part.body.auto_fit = true; + } + // Each layer keeps to its range, however many blocks a hostile page has. + let order = u32::try_from(i).unwrap_or(u32::MAX).min(Z_PICTURE - Z_WATERMARK - 1); + let watermark = bl.size >= 2.0 * body; + let float = Float { + wrap: if watermark { Wrap::BehindText } else { Wrap::InFrontOfText }, + h_rel: Anchor::Page, + v_rel: Anchor::Page, + x: x as f32, + y: y as f32, + rot: rotation as f32, + z: if watermark { Z_WATERMARK } else { Z_TEXT }.saturating_add(order), + ..Float::default() + }; + let shape = InlineObject::Shape { + kind: ShapeKind::TextBox, + w: w as f32, + h: h as f32, + fill: None, + stroke: None, + stroke_width: 0.0, + float, + story: Some(story), + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + anchor.push_object(shape, &CharProps::default()); + } + for (n, im) in page.images.iter().enumerate() { + let Some(media) = b.add_media(im) else { continue }; + let (w, h) = (layout_number(im.size[0]).max(1.0), layout_number(im.size[1]).max(1.0)); + let (x, y) = (layout_number((im.rect[0] + im.rect[2] - w) / 2.0), layout_number(page.height - (im.rect[1] + im.rect[3] + h) / 2.0)); + let rotation = layout_number(-im.rotation).rem_euclid(360.0); + let order = u32::try_from(n).unwrap_or(0).min(Z_TEXT - Z_PICTURE - 1); + let float = Float { + wrap: Wrap::BehindText, + h_rel: Anchor::Page, + v_rel: Anchor::Page, + x: x as f32, + y: y as f32, + rot: rotation as f32, + z: Z_PICTURE + order, + ..Float::default() + }; + let pic = + InlineObject::Image { media, w: w as f32, h: h as f32, alt: String::new(), float, crop: [0.0; 4], fx: Default::default(), ole: None }; + anchor.push_object(pic, &CharProps::default()); + } + b.body.push(Block::Para(anchor)); +} + +/// The pages as a Word document: a page that can't flow ([`positioned`]) keeps its layout as +/// positioned text boxes and pictures, and the others flow as paragraphs, tables and pictures. +/// Each page is a section of its own size, and its headings are told from its own body size. +pub(crate) fn word_doc(pages: &[Page], meta: &Meta) -> Document { + let mut b = Builder::new(pages, meta); + let mut last = SectionProps::default(); + for (i, page) in pages.iter().enumerate() { + let sec = section(page); + if positioned(page) { + positioned_page(&mut b, page); + } else { + for it in items(std::slice::from_ref(page)) { + b.flow(it, &sec); + } + } + if i + 1 < pages.len() { + b.end_page(sec); + } else { + last = sec; + } + } + b.finish(last) +} diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 5f50122f90..93d93fc2a5 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -20,13 +20,14 @@ mod as_docx; mod as_html; mod as_markdown; mod as_rtf; +mod as_word; mod clip; mod flow; mod layout; -pub(crate) use as_docx::hex; #[cfg(test)] -use as_docx::{MAX_MEDIA, docx_table}; +use as_docx::MAX_MEDIA; +pub(crate) use as_docx::hex; pub use as_docx::{docx, docx_with_language}; pub(crate) use as_html::esc; #[cfg(test)] @@ -35,7 +36,7 @@ pub use as_html::{html, html_simple, html_simple_with_language, html_with_langua pub use as_markdown::markdown; #[cfg(test)] use as_markdown::{emphasis, paragraph}; -pub use as_rtf::rtf; +pub use as_rtf::{rtf, rtf_with_title}; pub use clip::{ClipBuilder, ClipSpan, ClipStyle, ClipText, MAX_CLIP_HTML_BYTES, MAX_CLIP_SPANS, MAX_CLIP_TEXT_BYTES, clip_html, font_family}; #[cfg(test)] use flow::list_item; diff --git a/crates/export/src/pptx.rs b/crates/export/src/pptx.rs index 59d9f858d9..be66397190 100644 --- a/crates/export/src/pptx.rs +++ b/crates/export/src/pptx.rs @@ -2,11 +2,16 @@ //! largest text as slide title, remaining paragraphs as body text, images and tables between them. use std::collections::HashMap; +use std::sync::Arc; -use crate::as_docx::{core_properties_xml, image_mime, room_for}; +use crate::as_docx::{image_mime, room_for}; use crate::{Image, Page, Run, Table, hex}; -use craft_opc::{PackageOut, RT_BASE, RelOut, RelsOut}; -use craft_xml::{DECL_STANDALONE, esc}; +use craft_pptx::table::{Cell, Table as DmlTable}; +use craft_pptx::text::{Paragraph, Run as DmlRun, RunKind, RunProps, TextBody}; +use craft_pptx::{ + ColorBase, ColorRef, Fill, Geom, Line, MediaId, MediaItem, Plain, Presentation, Rgba, Shape, ShapeId, ShapeKind, Size, Slide, SlideId, Xfrm, + style::PictureFill, +}; /// Items on a slide in reading order. enum SlideBodyItem<'a> { @@ -16,102 +21,105 @@ enum SlideBodyItem<'a> { Img(&'a Image), } -/// Convert points to EMU (English Metric Units: 1 pt = 12700 EMU). -/// -/// Clamps to PowerPoint's allowed slide dimensions: 1 inch (914,400 EMU = 72 pt) -/// to 56 inches (51,206,400 EMU = 4032 pt). -fn emu(pt: f64, default_pt: f64) -> i64 { - if pt.is_finite() && pt > 0.0 { (pt * 12700.0).round().clamp(914400.0, 51206400.0) as i64 } else { (default_pt * 12700.0).round() as i64 } +/// Clamp slide dimensions in points to PowerPoint's allowed range: 1 inch (72 pt) to 56 inches (4032 pt). +fn slide_pt(pt: f64, default_pt: f64) -> f64 { + if pt.is_finite() && pt > 0.0 { pt.clamp(72.0, 4032.0) } else { default_pt } } -/// The largest height one item may take on a slide (about 1,100 inches). Text sizes and image -/// rectangles come from the PDF, so a hostile size (say 1e300 pt) must not push the running -/// vertical position past what an `i64` (or a DrawingML coordinate) holds. -const MAX_ITEM_EMU: i64 = 1_000_000_000; +/// The largest height one item may take on a slide (about 1,100 inches in points). +const MAX_ITEM_PT: f64 = 78_740.0; -/// Points to EMU for a height or gap, clamped to `0..=MAX_ITEM_EMU` (NaN reads as 0). -fn height_emu(pt: f64) -> i64 { - let v = pt * 12700.0; - // Clamped to 0..=MAX_ITEM_EMU before the cast, so it cannot truncate or wrap. - if v.is_finite() { - v.round().clamp(0.0, MAX_ITEM_EMU as f64) as i64 - } else if v > 0.0 { - MAX_ITEM_EMU +/// Points for a height or gap, clamped to `0..=MAX_ITEM_PT` (NaN reads as 0). +fn height_pt(pt: f64) -> f64 { + if pt.is_finite() { + pt.clamp(0.0, MAX_ITEM_PT) + } else if pt > 0.0 { + MAX_ITEM_PT } else { - 0 + 0.0 } } -/// A formatted DrawingML text run (``). -fn run_drawingml(text: &str, size: f64, bold: bool, italic: bool, color: [f64; 3]) -> String { - let mut rpr = String::new(); - let sz = if size.is_finite() { (size * 100.0).round().clamp(100.0, 400000.0) as i64 } else { 1200 }; - rpr.push_str(&format!(" sz=\"{sz}\"")); - if bold { - rpr.push_str(" b=\"1\""); +/// Parse a 6-digit hex color string into `Rgba`. +fn rgba_from_hex(h: &str) -> Option { + if h.len() != 6 { + return None; } - if italic { - rpr.push_str(" i=\"1\""); - } - let fill = if let Some(h) = hex(color) { format!("") } else { String::new() }; - format!("{fill}{}", esc(text)) + let r = u8::from_str_radix(&h[0..2], 16).ok()?; + let g = u8::from_str_radix(&h[2..4], 16).ok()?; + let b = u8::from_str_radix(&h[4..6], 16).ok()?; + Some(Rgba::rgb(r, g, b)) } -/// Generates a DrawingML table inside a `` with explicit cell borders. -fn pptx_table(shape_id: usize, t: &Table, x: i64, y: i64, content_w: i64) -> (String, i64) { +/// A formatted DrawingML text run. +fn dml_run(text: &str, size: f64, bold: bool, italic: bool, color: [f64; 3]) -> DmlRun { + let sz = if size.is_finite() { size.clamp(1.0, 4000.0) } else { 12.0 }; + let fill = + hex(color).and_then(|h| rgba_from_hex(&h)).map(|c| Fill::Solid { color: ColorRef { base: ColorBase::Rgb { rgb: c }, mods: Vec::new() } }); + DmlRun { + text: text.to_string(), + props: RunProps { + size: Some(sz), + bold: if bold { Some(true) } else { None }, + italic: if italic { Some(true) } else { None }, + fill, + ..Default::default() + }, + kind: RunKind::Text, + } +} + +/// Generates a DrawingML table shape with explicit cell borders. +fn pptx_table(shape_id: u32, t: &Table, x: f64, y: f64, content_w: f64) -> (Shape, f64) { let mut edges = t.cols.clone(); edges.push(t.rect[2]); let widths_pt: Vec = edges.windows(2).map(|w| (w[1] - w[0]).max(20.0)).collect(); let total_pt: f64 = widths_pt.iter().sum(); - let scale = if total_pt > 0.0 { (content_w as f64 / (total_pt * 12700.0)).min(1.0) } else { 1.0 }; - let widths: Vec = widths_pt.iter().map(|w| (w * scale * 12700.0).round().max(127000.0) as i64).collect(); - let table_w: i64 = widths.iter().fold(0i64, |sum, w| sum.saturating_add(*w)); - let row_h: i64 = height_emu(24.0); - let table_h: i64 = i64::try_from(t.rows.len()).unwrap_or(i64::MAX).saturating_mul(row_h).min(MAX_ITEM_EMU); + let scale = if total_pt > 0.0 { (content_w / total_pt).min(1.0) } else { 1.0 }; + let widths: Vec = widths_pt.iter().map(|w| (w * scale).max(10.0)).collect(); + let table_w: f64 = widths.iter().sum(); + let row_h: f64 = 24.0; + let table_h: f64 = (t.rows.len() as f64 * row_h).min(MAX_ITEM_PT); - let mut grid_cols = String::new(); - for w in &widths { - grid_cols.push_str(&format!("")); - } + let border = Some(Line { + width: Some(1.0), + fill: Some(Fill::Solid { color: ColorRef { base: ColorBase::Rgb { rgb: Rgba::rgb(0x99, 0x99, 0x99) }, mods: Vec::new() } }), + ..Default::default() + }); + let borders = [border.clone(), border.clone(), border.clone(), border]; - const TC_PR: &str = "\ -\ -\ -\ -\ -"; - - let mut rows_xml = String::new(); + let mut rows = Vec::with_capacity(t.rows.len()); for row in &t.rows { - rows_xml.push_str(&format!("")); + let mut cells = Vec::new(); for c in row { let span = c.span.max(1); - let run = run_drawingml(&c.text, c.size, c.bold, c.italic, c.color); - if span > 1 { - rows_xml.push_str(&format!("{run}{TC_PR}")); - for _ in 1..span { - rows_xml.push_str(&format!("{TC_PR}")); - } - } else { - rows_xml.push_str(&format!("{run}{TC_PR}")); + let run = dml_run(&c.text, c.size, c.bold, c.italic, c.color); + cells.push(Cell { + text: TextBody { paragraphs: vec![Paragraph { runs: vec![run], ..Default::default() }], ..Default::default() }, + grid_span: span as u32, + row_span: 1, + borders: borders.clone(), + ..Default::default() + }); + for _ in 1..span { + cells.push(Cell { h_merge: true, borders: borders.clone(), ..Default::default() }); } } let used: usize = row.iter().map(|c| c.span).sum(); for _ in used..t.cols.len() { - rows_xml.push_str(&format!("{TC_PR}")); + cells.push(Cell { borders: borders.clone(), ..Default::default() }); } - rows_xml.push_str(""); + rows.push(craft_pptx::table::Row { height: row_h, cells }); } - let frame = format!( - "\ -\ -\ -\ -{grid_cols}{rows_xml}\ -" - ); - (frame, table_h) + let shape = Shape { + id: ShapeId(shape_id), + name: format!("Table {shape_id}"), + xfrm: Some(Xfrm { x, y, w: table_w, h: table_h, ..Default::default() }), + kind: ShapeKind::Table(DmlTable { cols: widths, rows, ..Default::default() }), + ..Default::default() + }; + (shape, table_h) } /// A PowerPoint presentation (.pptx, Office Open XML PresentationML): each page becomes a slide, @@ -123,18 +131,18 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec { let dummy = [Page::default()]; let pages = if pages.is_empty() { &dummy[..] } else { pages }; - let (sw, sh) = pages.first().map_or((9144000, 6858000), |p| (emu(p.width, 720.0), emu(p.height, 540.0))); - let mx = (sw / 16).clamp(360000, 914400); - let my = (sh / 16).clamp(360000, 914400); - let content_w = sw - 2 * mx; + let (sw, sh) = pages.first().map_or((720.0, 540.0), |p| (slide_pt(p.width, 720.0), slide_pt(p.height, 540.0))); + let mx = (sw / 16.0).clamp(360000.0 / 12700.0, 72.0); + let my = (sh / 16.0).clamp(360000.0 / 12700.0, 72.0); + let content_w = sw - 2.0 * mx; let mut global_media: Vec<(String, &Image)> = Vec::new(); // Shared picture bytes remain alive throughout export; only admitted media enter this map. let mut media_of: HashMap<*const u8, usize> = HashMap::new(); - let mut slides: Vec<(String, RelsOut)> = Vec::new(); // (slide_xml, slide_rels) + let mut slides: Vec> = Vec::new(); let body = crate::layout::body_size(pages); - for p in pages { + for (slide_idx, p) in pages.iter().enumerate() { let (tables, consumed) = crate::tables(&p.blocks, &p.rules); let title_idx = p .blocks @@ -161,52 +169,60 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec { let items = crate::reading_order(p, parts); let mut current_y = my; - let mut shapes = String::new(); - let mut shape_id = 2usize; - let mut slide_media_rels: Vec<(String, usize)> = Vec::new(); + let mut shapes: Vec = Vec::new(); + let mut shape_id = 2u32; if let Some(title_block) = title_idx.and_then(|ti| p.blocks.get(ti)) { - let title_h = height_emu((title_block.size * 1.5).max(36.0)); - let title_run = run_drawingml(&title_block.text, title_block.size, title_block.bold, title_block.italic, title_block.color); - shapes.push_str(&format!( - "\ -\ -{title_run}" - )); + let title_h = height_pt((title_block.size * 1.5).max(36.0)); + let title_run = dml_run(&title_block.text, title_block.size, title_block.bold, title_block.italic, title_block.color); + shapes.push(Shape { + id: ShapeId(shape_id), + name: format!("Title {shape_id}"), + xfrm: Some(Xfrm { x: mx, y: current_y, w: content_w, h: title_h, ..Default::default() }), + kind: ShapeKind::Shape, + geom: Geom::Preset { name: "rect".into(), adj: Vec::new() }, + fill: Some(Fill::None), + text_box: true, + text: Some(TextBody { paragraphs: vec![Paragraph { runs: vec![title_run], ..Default::default() }], ..Default::default() }), + ..Default::default() + }); shape_id += 1; - current_y = current_y.saturating_add(title_h).saturating_add(height_emu(18.0)); + current_y = (current_y + title_h + 18.0).min(MAX_ITEM_PT); } let mut i = 0; while let Some(item) = items.get(i) { match item { SlideBodyItem::Para(_) => { - let mut paras_xml = String::new(); + let mut paragraphs = Vec::new(); let mut est_h_pt = 0.0; while let Some(SlideBodyItem::Para(runs)) = items.get(i) { - paras_xml.push_str(""); - for r in runs { - paras_xml.push_str(&run_drawingml(&r.text, r.block.size, r.block.bold, r.block.italic, r.block.color)); - } - paras_xml.push_str(""); + let dml_runs = runs.iter().map(|r| dml_run(&r.text, r.block.size, r.block.bold, r.block.italic, r.block.color)).collect(); + paragraphs.push(Paragraph { runs: dml_runs, ..Default::default() }); let len = runs.iter().map(|r| r.text.len()).fold(0usize, usize::saturating_add); let size = runs.iter().map(|r| r.block.size).fold(10.0, f64::max); let lines = (len as f64 / 60.0).ceil().max(1.0); est_h_pt += (size * 1.3) * lines + 6.0; i += 1; } - let box_h = height_emu(est_h_pt); - shapes.push_str(&format!( - "\ -\ -{paras_xml}" - )); + let box_h = height_pt(est_h_pt); + shapes.push(Shape { + id: ShapeId(shape_id), + name: format!("TextBox {shape_id}"), + xfrm: Some(Xfrm { x: mx, y: current_y, w: content_w, h: box_h, ..Default::default() }), + kind: ShapeKind::Shape, + geom: Geom::Preset { name: "rect".into(), adj: Vec::new() }, + fill: Some(Fill::None), + text_box: true, + text: Some(TextBody { paragraphs, ..Default::default() }), + ..Default::default() + }); shape_id += 1; - current_y = current_y.saturating_add(box_h).saturating_add(height_emu(12.0)); + current_y = (current_y + box_h + 12.0).min(MAX_ITEM_PT); } SlideBodyItem::Img(im) => { let global_img_idx = match media_of.get(&im.bytes.as_ptr()) { - Some(&i) => i, + Some(&idx) => idx, None if room_for(&global_media, im) => { let n = global_media.len() + 1; global_media.push((format!("image{n}.{}", im.ext), *im)); @@ -218,173 +234,55 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec { continue; } }; - let r_id = format!("rIdImg{}", slide_media_rels.len() + 1); - slide_media_rels.push((r_id.clone(), global_img_idx)); let (w, h) = ((im.rect[2] - im.rect[0]).max(1.0), (im.rect[3] - im.rect[1]).max(1.0)); - let max_w = content_w as f64 / 12700.0; - let k = (max_w / w).min(1.0); - let cx = height_emu(w * k).min(content_w); - let cy = height_emu(h * k); - let x = mx + (content_w - cx) / 2; + let k = (content_w / w).min(1.0); + let cx = height_pt(w * k).min(content_w); + let cy = height_pt(h * k); + let x = mx + (content_w - cx) / 2.0; let y = current_y; - shapes.push_str(&format!( - "\ -\ -" - )); + shapes.push(Shape { + id: ShapeId(shape_id), + name: format!("Picture {shape_id}"), + xfrm: Some(Xfrm { x, y, w: cx, h: cy, ..Default::default() }), + kind: ShapeKind::Picture { fill: PictureFill { media: MediaId(global_img_idx as u32), ..Default::default() } }, + geom: Geom::Preset { name: "rect".into(), adj: Vec::new() }, + ..Default::default() + }); shape_id += 1; - current_y = current_y.saturating_add(cy).saturating_add(height_emu(12.0)); + current_y = (current_y + cy + 12.0).min(MAX_ITEM_PT); i += 1; } SlideBodyItem::Table(t) => { - let (table_xml, table_h) = pptx_table(shape_id, t, mx, current_y, content_w); - shapes.push_str(&table_xml); + let (table_shape, table_h) = pptx_table(shape_id, t, mx, current_y, content_w); + shapes.push(table_shape); shape_id += 1; - current_y = current_y.saturating_add(table_h).saturating_add(height_emu(12.0)); + current_y = (current_y + table_h + 12.0).min(MAX_ITEM_PT); i += 1; } } } - let slide_xml = format!( - "\n\ -\ -\ -\ -{shapes}" - ); - - let mut slide_rels = RelsOut::default(); - slide_rels.items.push(RelOut { - id: "rIdLayout".into(), - ty: format!("{RT_BASE}slideLayout"), - target: "../slideLayouts/slideLayout1.xml".into(), - external: false, - }); - for (r_id, global_idx) in &slide_media_rels { - if let Some((name, _)) = global_media.get(*global_idx - 1) { - slide_rels.items.push(RelOut { - id: r_id.clone(), - ty: format!("{RT_BASE}image"), - target: format!("../media/{name}"), - external: false, - }); - } - } - - slides.push((slide_xml, slide_rels)); + slides.push(Arc::new(Slide { id: SlideId(256 + slide_idx as u32), shapes, ..Default::default() })); } - let mut pkg = PackageOut::default(); - let mut root_rels = RelsOut::default(); - root_rels.add("officeDocument", "ppt/presentation.xml", false); - root_rels.add("metadata/core-properties", "docProps/core.xml", false); - pkg.rels("", &root_rels); + let media: Vec = global_media + .into_iter() + .enumerate() + .map(|(idx, (name, im))| MediaItem { + id: MediaId((idx + 1) as u32), + name, + content_type: image_mime(im.ext).to_string(), + data: Arc::new(im.bytes.to_vec()), + link: None, + }) + .collect(); - let mut sld_id_lst = String::new(); - let mut pres_rels = RelsOut::default(); - pres_rels.items.push(RelOut { - id: "rIdMaster1".into(), - ty: format!("{RT_BASE}slideMaster"), - target: "slideMasters/slideMaster1.xml".into(), - external: false, - }); - for i in 1..=slides.len() { - let sld_id = 255 + i; - sld_id_lst.push_str(&format!("")); - pres_rels.items.push(RelOut { - id: format!("rIdSld{i}"), - ty: format!("{RT_BASE}slide"), - target: format!("slides/slide{i}.xml"), - external: false, - }); - } - pkg.rels("ppt/presentation.xml", &pres_rels); + let mut pres = Presentation { slide_size: Size::new(sw, sh), slides, media, ..Default::default() }; + pres.props.title = title.to_string(); - let pres = format!( - "{DECL_STANDALONE}\ -\ -{sld_id_lst}" - ); - - let slide_master = format!( - "{DECL_STANDALONE}\ -\ -\ -\ -" - ); - - let mut slide_master_rels = RelsOut::default(); - slide_master_rels.items.push(RelOut { - id: "rIdLayout1".into(), - ty: format!("{RT_BASE}slideLayout"), - target: "../slideLayouts/slideLayout1.xml".into(), - external: false, - }); - slide_master_rels.items.push(RelOut { - id: "rIdTheme1".into(), - ty: format!("{RT_BASE}theme"), - target: "../theme/theme1.xml".into(), - external: false, - }); - pkg.rels("ppt/slideMasters/slideMaster1.xml", &slide_master_rels); - - let slide_layout = format!( - "{DECL_STANDALONE}\ -\ -" - ); - - let mut slide_layout_rels = RelsOut::default(); - slide_layout_rels.add("slideMaster", "../slideMasters/slideMaster1.xml", false); - pkg.rels("ppt/slideLayouts/slideLayout1.xml", &slide_layout_rels); - - let theme = format!( - "{DECL_STANDALONE}\ -\ -\ -\ -\ -\ -\ -\ -\ -\ -\ -\ -" - ); - - pkg.xml_part("docProps/core.xml", "application/vnd.openxmlformats-package.core-properties+xml", core_properties_xml(title)); - pkg.xml_part("ppt/presentation.xml", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml", pres.into_bytes()); - pkg.xml_part( - "ppt/slideMasters/slideMaster1.xml", - "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml", - slide_master.into_bytes(), - ); - pkg.xml_part( - "ppt/slideLayouts/slideLayout1.xml", - "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml", - slide_layout.into_bytes(), - ); - pkg.xml_part("ppt/theme/theme1.xml", "application/vnd.openxmlformats-officedocument.theme+xml", theme.into_bytes()); - for (i, (s_xml, s_rels)) in slides.iter().enumerate() { - let num = i + 1; - let path = format!("ppt/slides/slide{num}.xml"); - pkg.xml_part(&path, "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", s_xml.as_bytes().to_vec()); - pkg.rels(&path, s_rels); - } - for (name, im) in &global_media { - pkg.binary(&format!("ppt/media/{name}"), image_mime(im.ext), im.bytes.to_vec()); - } - pkg.finish().unwrap_or_default() + craft_pptx::export(&pres, &Plain).unwrap_or_default() } #[cfg(test)] diff --git a/crates/export/src/tests.rs b/crates/export/src/tests.rs index 3bae8571d3..d2defc87ff 100644 --- a/crates/export/src/tests.rs +++ b/crates/export/src/tests.rs @@ -120,10 +120,14 @@ fn docx_is_a_word_package() { #[test] fn word_does_not_invent_borders_for_aligned_invoice_fields() { - let xml = part(&docx(&[table_page()], "Invoice"), "word/document.xml"); - assert!(xml.contains("")); - assert!(!xml.contains("w:val=\"single\""), "text alignment is not evidence of a border: {xml}"); - assert!(xml.contains("")); + let tables = docx_tables(&docx(&[table_page()], "Invoice")); + assert_eq!(tables.len(), 1); + let single = |b: &Option| b.is_some_and(|b| b.style == craft_wordmodel::props::BorderStyle::Single); + let cells = tables[0].rows.iter().flat_map(|r| &r.cells).filter_map(|c| c.props.borders); + let table = tables[0].props.borders.into_iter(); + for b in table.chain(cells) { + assert!(![b.top, b.left, b.bottom, b.right, b.between, b.inside_v].iter().any(single), "text alignment is not evidence of a border: {b:?}"); + } } #[test] @@ -141,28 +145,71 @@ fn word_table_cell_widths_follow_the_columns_they_span() { ], ruled: None, }; - let xml = docx_table(&table); - assert!(xml.contains(""), "{xml}"); - let widths: Vec> = - xml.split("").skip(1).map(|row| row.split("> = t.rows.iter().map(|r| r.cells.iter().map(|c| c.props.width.unwrap_or(0.0)).collect()).collect(); + // A short row is padded to the grid with cells as wide as the columns they fill. + assert_eq!(widths, vec![vec![50.0, 100.0, 150.0], vec![50.0, 250.0], vec![150.0, 150.0], vec![300.0], vec![50.0, 100.0, 150.0]]); +} + +/// The tables a Word document holds, read back through craft-docx. +fn docx_tables(d: &[u8]) -> Vec { + craft_docx::read(d) + .unwrap() + .body + .iter() + .filter_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t.clone()) } else { None }) + .collect() +} + +/// The paragraphs of a document's body (not inside tables). +fn body_paragraphs(doc: &craft_wordmodel::Document) -> Vec<&craft_wordmodel::Paragraph> { + doc.body.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p) } else { None }).collect() +} + +/// The objects in the body's paragraphs, in order. +fn body_objects(doc: &craft_wordmodel::Document) -> Vec<&craft_wordmodel::InlineObject> { + body_paragraphs(doc).into_iter().flat_map(|p| &p.objects).collect() +} + +/// A shape's text, from the story it holds. +fn shape_text(doc: &craft_wordmodel::Document, o: &craft_wordmodel::InlineObject) -> String { + let craft_wordmodel::InlineObject::Shape { story: Some(id), .. } = o else { return String::new() }; + doc.parts + .get(id) + .map(|part| part.blocks.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p.plain_text()) } else { None }).collect()) + .unwrap_or_default() +} + +/// A floating object's placement. +fn float_of(o: &craft_wordmodel::InlineObject) -> Option<&craft_wordmodel::para::Float> { + match o { + craft_wordmodel::InlineObject::Shape { float, .. } | craft_wordmodel::InlineObject::Image { float, .. } => Some(float), + _ => None, + } } #[test] fn word_keeps_a_page_with_a_clear_image_and_big_title_in_flow() { // page() has a picture between paragraphs and a 24 pt title over 11 pt body text, but // nothing overlaps: it must stay flowing paragraphs with the image inline. - let xml = part(&docx(&[page()], "Report"), "word/document.xml"); - assert!(!xml.contains("position:absolute"), "nothing overlaps, so nothing floats: {xml}"); - assert!(xml.contains(""), "the picture stays inline: {xml}"); - assert!(xml.contains(""), "the title stays a heading: {xml}"); - let (title, body) = (xml.find(">Annual Report"), xml.find(">Body text after the picture")); - assert!(title.is_some() && body.is_some() && title < body, "reading order kept: {xml}"); + let doc = craft_docx::read(&docx(&[page()], "Report")).unwrap(); + let objects = body_objects(&doc); + assert!(objects.iter().all(|o| !matches!(o, craft_wordmodel::InlineObject::Shape { .. })), "nothing overlaps, so nothing floats: {objects:?}"); + assert!( + objects.iter().any(|o| matches!(o, craft_wordmodel::InlineObject::Image { float, .. } if float.wrap == craft_wordmodel::para::Wrap::Inline)), + "the picture stays inline: {objects:?}" + ); + let paras = body_paragraphs(&doc); + let title = paras.iter().position(|p| p.plain_text() == "Annual Report"); + let body = paras.iter().position(|p| p.plain_text().starts_with("Body text after the picture")); + assert_eq!(title.and_then(|i| paras[i].props.style.as_deref()), Some("Heading1"), "the title stays a heading"); + assert!(title.is_some() && body.is_some() && title < body, "reading order kept"); // The same page with the picture moved over the body text floats. let mut over = page(); over.images[0].rect = [72.0, 380.0, 272.0, 530.0]; - let xml = part(&docx(&[over], "Report"), "word/document.xml"); - assert!(xml.contains("position:absolute"), "an image over text floats: {xml}"); + let doc = craft_docx::read(&docx(&[over], "Report")).unwrap(); + assert!(body_objects(&doc).iter().any(|o| matches!(o, craft_wordmodel::InlineObject::Shape { .. })), "an image over text floats the page"); } #[test] @@ -179,18 +226,23 @@ fn word_overlap_does_not_consume_invoice_body_space() { space_around: [false; 2], }); p.images = page().images; - let xml = part(&docx(&[p], "Invoice"), "word/document.xml"); - assert!(xml.contains("position:absolute"), "overlapping text must float: {xml}"); - assert!(!xml.contains(""), "images must not displace invoice text"); - assert!(!xml.contains(""), "the source text boxes must keep their positions"); - assert_eq!(xml.matches(">DRAFT").count(), 1); - assert_eq!(xml.matches("w:type=\"page\"").count(), 0); - assert!(xml.contains("margin-left:72.000pt;margin-top:160.000pt"), "Meter field keeps its source position: {xml}"); - let watermark = xml.split(">DRAFT").next().unwrap().rsplit(""), "{xml}"); + let d = docx(&[p], "Invoice"); + let doc = craft_docx::read(&d).unwrap(); + use craft_wordmodel::para::{Anchor, Wrap}; + assert!(doc.body.iter().all(|b| !matches!(&**b, craft_wordmodel::Block::Table(_))), "the source text boxes keep their positions"); + let objects = body_objects(&doc); + let shape = |text: &str| objects.iter().copied().find(|o| shape_text(&doc, o) == text); + let draft = shape("DRAFT").and_then(float_of).expect("the watermark is a text box"); + assert_eq!(objects.iter().filter(|o| shape_text(&doc, o) == "DRAFT").count(), 1); + let meter = shape("Meter").and_then(float_of).expect("Meter is a text box"); + assert_eq!((meter.h_rel, meter.v_rel), (Anchor::Page, Anchor::Page)); + assert_eq!((meter.x, meter.y), (72.0, 160.0), "the Meter field keeps its source position"); + assert_eq!(meter.wrap, Wrap::InFrontOfText); + assert!(!body_paragraphs(&doc).iter().any(|p| p.text.contains(craft_wordmodel::para::PAGE_BREAK)), "no page breaks"); + // The watermark is behind everything, and the picture, behind the text too, is drawn over it. + let picture = objects.iter().copied().find(|o| matches!(o, craft_wordmodel::InlineObject::Image { .. })).and_then(float_of).expect("the picture"); + assert_eq!((draft.wrap, picture.wrap), (Wrap::BehindText, Wrap::BehindText), "images must not displace invoice text"); + assert!(draft.z < picture.z && picture.z < meter.z, "{} < {} < {}", draft.z, picture.z, meter.z); } #[test] @@ -200,12 +252,18 @@ fn word_rotated_pages_keep_separate_page_sizes_and_unique_shapes() { let mut second = p.clone(); second.width = 400.0; second.height = 500.0; - let xml = part(&docx(&[p, second], "Two invoices"), "word/document.xml"); - assert!(xml.contains("rotation:315.000"), "PDF y-up becomes Word y-down"); - assert_eq!(xml.matches("").count(), 2); - assert!(xml.contains("")); - assert_eq!(xml.matches("id=\"Text1\"").count(), 1); - assert_eq!(xml.matches(">Meter").count(), 2); + let d = docx(&[p, second], "Two invoices"); + let doc = craft_docx::read(&d).unwrap(); + let meters: Vec<_> = body_objects(&doc).into_iter().filter(|o| shape_text(&doc, o) == "Meter").collect(); + assert_eq!(meters.len(), 2); + assert!(meters.iter().all(|o| float_of(o).is_some_and(|f| (f.rot - 315.0).abs() < 0.01)), "PDF y-up becomes Word y-down"); + let sizes: Vec<(f32, f32)> = doc.sections().iter().map(|(_, s)| (s.page_w, s.page_h)).collect(); + assert_eq!(sizes, [(612.0, 792.0), (400.0, 500.0)]); + // Every drawing has an id of its own. + let xml = part(&d, "word/document.xml"); + let ids: Vec<&str> = xml.split(" = ids.iter().copied().collect(); + assert!(!ids.is_empty() && unique.len() == ids.len(), "{ids:?}"); } /// #2992: pages that share a background colour get it as the Word document's page colour @@ -214,11 +272,10 @@ fn word_rotated_pages_keep_separate_page_sizes_and_unique_shapes() { fn docx_keeps_a_shared_page_background() { let teal = Page { background: Some([0.0, 0.5, 0.5]), ..page() }; let zip = docx(&[teal.clone(), teal.clone()], "Teal"); - let xml = part(&zip, "word/document.xml"); - assert!(xml.contains(""), "{xml}"); + assert_eq!(craft_docx::read(&zip).unwrap().settings.page_color, Some(craft_wordmodel::Rgb(0, 128, 128))); + // Word shows the colour only when the settings say so. + assert!(part(&zip, "word/document.xml").contains("")); - assert!(part(&zip, "[Content_Types].xml").contains("/word/settings.xml")); - assert!(part(&zip, "word/_rels/document.xml.rels").contains("Target=\"settings.xml\"")); let other = Page { background: Some([1.0, 0.0, 0.0]), ..page() }; for (pages, why) in [ (vec![teal.clone(), other], "different colours"), @@ -227,8 +284,8 @@ fn docx_keeps_a_shared_page_background() { (vec![page()], "none"), ] { let zip = docx(&pages, "Plain"); + assert_eq!(craft_docx::read(&zip).unwrap().settings.page_color, None, "{why}"); assert!(!part(&zip, "word/document.xml").contains(" String { #[test] fn word_and_html_take_the_documents_language() { let pages = [page()]; - let styles = |lang| part(&docx_with_language(&pages, "Report", lang), "word/styles.xml"); - let defaults = |lang: &str| format!("{lang}"); - assert!(styles(Some("bg-BG")).contains(&defaults("")), "{}", styles(Some("bg-BG"))); - assert!(styles(Some(" en-GB ")).contains(""), "the tag is trimmed"); - assert!(styles(Some("zh-Hant-TW")).contains(&defaults("")), "East Asian text"); - assert!(styles(Some("ja")).contains(""), "East Asian text"); - assert!(styles(Some("ar-EG")).contains(&defaults("")), "right-to-left text"); - assert!(styles(Some("HE")).contains(""), "right-to-left text"); + // The document default languages Word reads back: (Latin, East Asian, right-to-left). + let langs = |lang| { + let c = craft_docx::read(&docx_with_language(&pages, "Report", lang)).unwrap().styles.default_chr.clone(); + (c.lang, c.lang_ea, c.lang_bidi) + }; + let latin = |t: &str| (Some(t.to_string()), None, None); + let east_asian = |t: &str| (None, Some(t.to_string()), None); + let bidi = |t: &str| (None, None, Some(t.to_string())); + assert_eq!(langs(Some("bg-BG")), latin("bg-BG")); + assert_eq!(langs(Some(" en-GB ")), latin("en-GB"), "the tag is trimmed"); + assert_eq!(langs(Some("zh-Hant-TW")), east_asian("zh-Hant-TW"), "East Asian text"); + assert_eq!(langs(Some("ja")), east_asian("ja"), "East Asian text"); + assert_eq!(langs(Some("ar-EG")), bidi("ar-EG"), "right-to-left text"); + assert_eq!(langs(Some("HE")), bidi("HE"), "right-to-left text"); // A script subtag decides over the language; private use names no script. - assert!(styles(Some("pa-Arab-PK")).contains(""), "Punjabi in Arabic script"); - assert!(styles(Some("sr-Latn")).contains(""), "Serbian in Latin script"); - assert!(styles(Some("zh-Latn")).contains(""), "Chinese in Latin script"); - assert!(styles(Some("en-x-arab")).contains(""), "private use"); - assert!(styles(Some("az-Latn-x-arab")).contains(""), "private use"); + assert_eq!(langs(Some("pa-Arab-PK")), bidi("pa-Arab-PK"), "Punjabi in Arabic script"); + assert_eq!(langs(Some("sr-Latn")), latin("sr-Latn"), "Serbian in Latin script"); + assert_eq!(langs(Some("zh-Latn")), latin("zh-Latn"), "Chinese in Latin script"); + assert_eq!(langs(Some("en-x-arab")), latin("en-x-arab"), "private use"); + assert_eq!(langs(Some("az-Latn-x-arab")), latin("az-Latn-x-arab"), "private use"); assert!(html_with_language(&pages, "Report", Some("bg-BG")).starts_with("\n\n")); // A tag longer than 35 characters is still a tag. let long = "en-US-u-ca-gregory-nu-latn-co-phonebk"; - assert!(styles(Some(long)).contains(&format!("")), "{long}"); + assert_eq!(langs(Some(long)), latin(long), "{long}"); assert!(html_with_language(&pages, "Report", Some(long)).contains(&format!("")), "{long}"); let too_long = format!("en{}", "-abcdefgh".repeat(29)); // Private use takes one-character subtags. @@ -296,7 +359,7 @@ fn word_and_html_take_the_documents_language() { Some("1a-BG"), Some("\u{431}\u{433}-BG"), ] { - assert!(docx_with_language(&pages, "Report", lang) == docx(&pages, "Report"), "{lang:?}"); + assert_eq!(langs(lang), (None, None, None), "{lang:?}"); assert_eq!(html_with_language(&pages, "Report", lang), html(&pages, "Report"), "{lang:?}"); assert_eq!(html_simple_with_language(&pages, "Report", lang), html_simple(&pages, "Report"), "{lang:?}"); } @@ -320,16 +383,19 @@ fn word_opens_text_with_control_characters_and_long_pages() { rotation: 0.0, space_around: [false; 2], }); - let xml = part(&docx(&[p.clone()], "Receipt\u{1}"), "word/document.xml"); - assert!(xml.contains(">Total 4.50\tGBP"), "{xml}"); + let d = docx(&[p.clone()], "Receipt\u{1}"); + let xml = part(&d, "word/document.xml"); assert!(!xml.chars().any(|c| !allowed(c))); - assert!(xml.contains(""), "clamped to 22 in: {xml}"); - assert!(xml.contains(""), "a non-finite size falls back to 12 pt"); + let doc = craft_docx::read(&d).unwrap(); + let total = body_paragraphs(&doc).into_iter().find(|p| p.plain_text().starts_with("Total")).expect("the receipt line"); + assert_eq!(total.plain_text(), "Total 4.50\tGBP"); + assert_eq!(total.runs.first().and_then(|r| r.props.size), Some(12.0), "a non-finite size falls back to 12 pt"); + assert_eq!(doc.last_section.page_h, 1584.0, "clamped to 22 in"); assert!(rtf(&[p]).contains("Total 4.50\\tab GBP")); // A narrow page keeps room for text: margins shrink. let narrow = Page { width: 100.0, height: 200.0, ..page() }; - let xml = part(&docx(&[narrow], "Narrow"), "word/document.xml"); - assert!(xml.contains(" = rtf_paras(&r).into_iter().flatten().collect(); assert!(runs.contains(&("Annual Report".into(), true, false, Some(48))), "{runs:?}"); assert!(runs.contains(&("Café {x}".into(), false, true, Some(20))), "{runs:?}"); } -/// A page break starts the next page's first paragraph, and stands in a paragraph of its own -/// before a table, rather than in the table's first cell. -#[test] -fn rtf_page_breaks_stay_out_of_tables() { - let r = rtf(&[page(), table_page(), page()]); - let back = craft_rtf::read(r.as_bytes()).unwrap(); - let first_cell = back.blocks.iter().find_map(|b| match b { - craft_rtf::Block::Table(t) => t.rows.first().and_then(|row| row.first()).map(|c| c.paras.iter().map(|p| p.text()).collect::()), - craft_rtf::Block::Para(_) => None, - }); - assert_eq!(first_cell.as_deref(), Some("Meter"), "{r}"); - let texts: Vec = back.blocks.iter().map(|b| if let craft_rtf::Block::Para(p) = b { p.text() } else { "".into() }).collect(); - let table = texts.iter().position(|t| t == "
"); - assert_eq!(table.and_then(|i| i.checked_sub(1)).and_then(|i| texts.get(i)).map(String::as_str), Some("\u{000C}"), "{texts:?}"); - assert_eq!(texts.iter().filter(|t| t.starts_with('\u{000C}')).count(), 2, "one break before each later page: {texts:?}"); +/// The RTF read back into the word model: each section's page size (points) and the text of its +/// blocks, tables as ``. +fn rtf_sections(r: &str) -> Vec<([f32; 2], Vec)> { + let doc = craft_rtf::doc::import(r.as_bytes()).unwrap(); + let mut out: Vec<([f32; 2], Vec)> = Vec::new(); + let mut texts = Vec::new(); + for b in &doc.body { + match &**b { + craft_wordmodel::Block::Para(p) => { + if !p.plain_text().is_empty() || !p.objects.is_empty() { + texts.push(if p.objects.is_empty() { p.plain_text() } else { "".into() }); + } + if let Some(s) = &p.section { + out.push(([s.page_w, s.page_h], std::mem::take(&mut texts))); + } + } + craft_wordmodel::Block::Table(t) => { + let first = t + .rows + .first() + .and_then(|r| r.cells.first()) + .map(|c| { + c.blocks + .iter() + .filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p.plain_text()) } else { None }) + .collect::() + }) + .unwrap_or_default(); + texts.push(format!("", first.trim())); + } + } + } + out.push(([doc.last_section.page_w, doc.last_section.page_h], texts)); + out } -/// Empty and image-only pages still occupy a page when pictures are omitted from RTF. +/// Each page is a section of its own, so it starts a new page, and a table on a page is in that +/// page's section rather than after a break character in its first cell. #[test] -fn rtf_preserves_breaks_for_pages_without_text() { +fn rtf_pages_are_sections_and_tables_stay_on_theirs() { + let r = rtf(&[page(), table_page(), page()]); + let sections = rtf_sections(&r); + assert_eq!(sections.len(), 3, "{sections:?}"); + assert!(sections[1].1.first().is_some_and(|t| t == ""), "{sections:?}"); + assert!(!r.contains("\\page"), "sections break the pages: {r}"); +} + +/// Empty and image-only pages still occupy a page; each keeps its own size. +#[test] +fn rtf_keeps_pages_without_text() { let mut blank = page(); blank.blocks.clear(); blank.images.clear(); blank.rules.clear(); let mut image_only = page(); image_only.blocks.clear(); + let mut small = blank.clone(); + small.width = 400.0; + small.height = 500.0; for pages in [ vec![blank.clone(), blank.clone(), page()], vec![page(), blank.clone(), blank.clone()], vec![page(), blank.clone(), blank.clone(), table_page()], - vec![blank.clone(), blank.clone(), blank], + vec![blank.clone(), blank.clone(), blank.clone()], vec![page(), image_only.clone(), image_only.clone(), page()], vec![page(), image_only], + vec![page(), small, blank], ] { let r = rtf(&pages); - let breaks = rtf_paras(&r).iter().flatten().map(|run| run.0.matches(craft_rtf::PAGE_BREAK).count()).sum::(); - assert_eq!(breaks, pages.len() - 1, "{r}"); + let sizes: Vec<[f32; 2]> = rtf_sections(&r).iter().map(|s| s.0).collect(); + let want: Vec<[f32; 2]> = pages.iter().map(|p| [p.width as f32, p.height as f32]).collect(); + assert_eq!(sizes, want, "{r}"); } } @@ -493,16 +594,19 @@ fn grid_text_becomes_a_real_table_in_every_format() { assert!(d.windows(b"word/document.xml".len()).any(|w| w == b"word/document.xml")); let (tables, _) = tables(&p.blocks, &p.rules); assert_eq!(tables.len(), 1); - let table_xml = docx_table(&tables[0]); - assert!(table_xml.contains("")); - assert!(table_xml.contains(""), "{table_xml}"); - assert_eq!(table_xml.matches("").count(), 4); + let read = docx_tables(&d); + assert_eq!(read.len(), 1, "{read:?}"); + assert_eq!(read[0].grid.len(), 3, "a three-column grid"); + assert_eq!(read[0].rows.len(), 4); + assert!(read[0].rows.iter().any(|r| r.cells.first().is_some_and(|c| c.props.span == 2)), "Totals spans two columns: {:?}", read[0]); let r = rtf(std::slice::from_ref(&p)); assert!(r.contains("\\trowd"), "{r}"); assert_eq!(r.matches("\\row").count(), 4); - // Each cell ends at its last column's right edge; "Totals" spans two columns, so it ends at - // the second of the three. + // Each cell ends at its last column's right edge, measured from the left margin (`\cellx`): + // the columns start at x = 72, 232 and 392 and the table ends at 496, so 160, 160 and 104 pt + // wide. "Totals" spans two columns, so it ends at the second edge, and its row is padded to + // the grid with an empty cell. let back = craft_rtf::read(r.as_bytes()).unwrap(); let rows: Vec> = back .blocks @@ -511,8 +615,8 @@ fn grid_text_becomes_a_real_table_in_every_format() { .flat_map(|t| &t.rows) .map(|row| row.iter().map(|c| (c.right, c.paras.iter().map(|p| p.text()).collect())).collect()) .collect(); - assert_eq!(rows.first().map(|r| r.iter().map(|c| c.0).collect::>()), Some(vec![4640, 7840, 9920]), "{rows:?}"); - assert!(rows.contains(&vec![(7840, "Totals".to_string())]), "{rows:?}"); + assert_eq!(rows.first().map(|r| r.iter().map(|c| c.0).collect::>()), Some(vec![3200, 6400, 8480]), "{rows:?}"); + assert!(rows.contains(&vec![(6400, "Totals".to_string()), (8480, String::new())]), "{rows:?}"); let pt = pptx(std::slice::from_ref(&p), "Bill"); assert!(pt.starts_with(b"PK")); @@ -736,17 +840,14 @@ fn word_pictures_resolve_to_media_in_the_package() { p.blocks[0].rect = [72.0, 700.0, 300.0, 760.0]; } let zip = docx(&[p], "T"); - let xml = part(&zip, "word/document.xml"); - assert_eq!(xml.contains(" = body_objects(&doc).into_iter().filter(|o| matches!(o, craft_wordmodel::InlineObject::Image { .. })).collect(); + assert_eq!(pictures.len(), 1); + let craft_wordmodel::InlineObject::Image { media, float, .. } = pictures[0] else { panic!("not a picture") }; + assert_eq!(float.wrap != craft_wordmodel::para::Wrap::Inline, placed); + // The picture resolves to the JPEG's bytes in the package, which has a type for it. + assert_eq!(doc.media.get(media).map(|b| b.to_vec()), Some(vec![0xFF, 0xD8, 0xFF, 0xD9]), "{:?}", doc.media.keys().collect::>()); + assert!(part(&zip, "[Content_Types].xml").contains("image/jpeg")); } } @@ -757,8 +858,11 @@ fn word_export_bounds_the_number_of_pictures_and_skips_empty_ones() { p.images = vec![Image { bytes: [].as_slice().into(), ..one.clone() }]; p.images.extend(std::iter::repeat_n(one, MAX_MEDIA + 10)); let zip = docx(&[p], "T"); - let rels = part(&zip, "word/_rels/document.xml.rels"); - assert_eq!(rels.matches("relationships/image\"").count(), MAX_MEDIA); + let doc = craft_docx::read(&zip).unwrap(); + let placed = body_objects(&doc).into_iter().filter(|o| matches!(o, craft_wordmodel::InlineObject::Image { .. })).count(); + assert_eq!(placed, MAX_MEDIA, "at most MAX_MEDIA pictures, and none for the empty one"); + // One picture drawn many times is one file in the package. + assert_eq!(doc.media.len(), 1); } /// The flowing paragraphs of a Word document (table cells left out), each as its runs' text @@ -1134,12 +1238,11 @@ fn a_ruled_table_gets_outer_borders_only_where_the_page_draws_them() { let (found, _) = tables(&blocks, &inside); assert_eq!(found.len(), 1); assert_eq!(found[0].ruled, Some([false; 4])); - let xml = docx_table(&found[0]); - for edge in ["insideH", "insideV"] { - assert!(xml.contains(&format!("")), "{xml}"); + let borders = crate::as_word::table(&found[0]).props.borders.unwrap(); + let single = |b: Option| b.is_some_and(|b| b.style == craft_wordmodel::props::BorderStyle::Single); + assert!(single(borders.between) && single(borders.inside_v), "{borders:?}"); + for edge in [borders.top, borders.left, borders.bottom, borders.right] { + assert!(!single(edge), "{borders:?}"); } let mut ruled_top = inside.clone(); @@ -1454,3 +1557,162 @@ fn html_bounds_the_pictures_it_embeds() { assert_eq!(h.matches(" Some(p.props.style.clone()), + _ => None, + }); + let style = heading.flatten().and_then(|id| doc.styles.styles.iter().find(|s| s.id == id).map(|s| s.para.outline_level)); + assert_eq!(style, Some(Some(0)), "Annual Report is a level 1 heading: {r}"); +} + +/// The document's title goes into the RTF's information group, and PdfCraft is named as the +/// application that wrote it. +#[test] +fn rtf_names_the_title_and_pdfcraft() { + let r = crate::rtf_with_title(&[page()], "Annual Report"); + assert_eq!(craft_rtf::doc::import(r.as_bytes()).unwrap().core.title, "Annual Report", "{r}"); + assert!(r.contains(r"{\*\generator PdfCraft;}") && !r.contains("WordCraft"), "{r}"); +} + +/// Two tables one under the other stay two tables: in RTF, rows that follow each other are one +/// table, so a paragraph keeps them apart. +#[test] +fn rtf_keeps_tables_that_touch_apart() { + // Two grids on one page with nothing between them. + let mut one = table_page(); + one.blocks.retain(|b| !b.text.starts_with("Notes")); + let mut lower = one.blocks.clone(); + for b in &mut lower { + b.rect[1] -= 300.0; + b.rect[3] -= 300.0; + } + one.blocks.extend(lower); + let r = rtf(std::slice::from_ref(&one)); + let (found, _) = tables(&one.blocks, &one.rules); + assert_eq!(found.len(), 2, "the page has two grids"); + let read = craft_rtf::doc::import(r.as_bytes()).unwrap().body.iter().filter(|b| matches!(&***b, craft_wordmodel::Block::Table(_))).count(); + assert_eq!(read, 2, "{r}"); +} + +/// A hard line ending in the text (LF, CR or CRLF) is a line break inside its paragraph or table +/// cell, which RTF readers keep (storytold/pdfcraft#4723, by KyleKassen): they ignore a bare line +/// ending as whitespace. +#[test] +fn rtf_keeps_hard_line_breaks_in_paragraphs_and_cells() { + let mut paragraph = page(); + paragraph.blocks.truncate(1); + paragraph.blocks[0].text = "First\nSecond\r\nThird\rFourth".into(); + paragraph.blocks[0].italic = true; + paragraph.images.clear(); + let r = rtf(&[paragraph]); + let texts: Vec = rtf_sections(&r).into_iter().flat_map(|s| s.1).collect(); + assert_eq!(texts, ["First\nSecond\nThird\nFourth"], "one paragraph, four lines: {r}"); + + let mut table = table_page(); + table.blocks[0].text = "Meter\nnumber".into(); + table.blocks[4].text = "kWh\r\nunit".into(); + let r = rtf(&[table]); + let back = craft_rtf::read(r.as_bytes()).unwrap(); + let cells: Vec = back + .blocks + .iter() + .filter_map(|b| if let craft_rtf::Block::Table(t) = b { Some(t) } else { None }) + .flat_map(|t| t.rows.iter().flatten()) + .map(|c| c.paras.iter().map(|p| p.text()).collect()) + .collect(); + assert!(cells.contains(&"Meter\nnumber".to_string()) && cells.contains(&"kWh\nunit".to_string()), "{cells:?}"); +} + +/// The Word export names PdfCraft as its application, its body font (Arial) in a font table that +/// says it is a sans-serif, so a reader without it draws a like face. +#[test] +fn word_names_pdfcraft_and_its_fonts() { + let zip = docx(&[page()], "Report"); + assert!(part(&zip, "docProps/app.xml").contains("PdfCraft")); + let fonts = part(&zip, "word/fontTable.xml"); + assert!(fonts.contains(r#""#), "{fonts}"); + assert_eq!(craft_docx::read(&zip).unwrap().styles.default_chr.font.as_deref(), Some("Arial")); +} + +/// A positioned page's text boxes have a VML fallback, which Word 2007 reads (it refuses a Word +/// 2010 shape on its own). +#[test] +fn word_text_boxes_have_a_fallback_for_word_2007() { + let mut p = table_page(); + p.blocks[0].rotation = 45.0; + let xml = part(&docx(&[p], "Rotated"), "word/document.xml"); + let boxes = xml.matches("").count(); + assert!(boxes > 0, "{xml}"); + assert_eq!(xml.matches("").count(), boxes, "{xml}"); + assert!(xml.contains(" = body_paragraphs(&doc).iter().map(|p| p.plain_text()).filter(|t| !t.is_empty()).collect(); + assert_eq!(texts, ["First\nSecond\nThird\tafter a tab"]); + + let mut t = table_page(); + t.blocks[0].text = "Meter\nnumber".into(); + t.blocks[4].text = "kWh\tunit".into(); + let tables = docx_tables(&docx(&[t], "Breaks")); + let cells: Vec = tables + .iter() + .flat_map(|t| t.rows.iter().flat_map(|r| &r.cells)) + .map(|c| c.blocks.iter().filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p.plain_text()) } else { None }).collect()) + .collect(); + assert!(cells.contains(&"Meter\nnumber".to_string()) && cells.contains(&"kWh\tunit".to_string()), "{cells:?}"); +} diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rs index 1a9d9cc14b..729259faad 100644 --- a/crates/ui-egui/tests/it/editing.rs +++ b/crates/ui-egui/tests/it/editing.rs @@ -2756,10 +2756,15 @@ fn a_startup_file_after_a_protected_one_keeps_its_password_prompt() { if unlock { h.state_mut().submit_password(Some("reader".into())); support::wait_until(&mut h, "both files", |app| app.views.len() == 2); - // The other file opened while the password was being typed; the unlocked one comes - // after it and is the one in view. - assert_eq!(open_paths(h.state()), vec![other_path, locked_path]); + // The password retry has worker priority, so either file can finish first. + // Both must open exactly once; the last admitted tab is the active one. + let mut paths = open_paths(h.state()); + paths.sort(); + let mut expected = vec![other_path, locked_path]; + expected.sort(); + assert_eq!(paths, expected); assert_eq!(h.state().active_ids().map(|(i, _)| i), Some(1)); + assert!(h.state().password_prompt.is_none(), "successful unlock leaves no stale prompt"); } else { h.state_mut().submit_password(None); support::wait_until(&mut h, "the other file", |app| app.views.len() == 1); diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 1b7ef6ff3f..6fdfead89c 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -7229,8 +7229,8 @@ milestone = "M10" status = "partial" commands = ["export.docx"] tools = ["doc_export_office"] -evidence = ["crates/export/src/tests.rs::word_table_cell_widths_follow_the_columns_they_span", "crates/export/src/tests.rs::table_spans_do_not_consume_text_they_do_not_emit", "crates/edit/src/tests.rs::reading_keeps_dotted_leader_entries_whole_and_in_order", "crates/engine/src/tests.rs::exporting_office_keeps_dotted_leader_entries_as_paragraphs", "crates/export/src/tests.rs::word_does_not_invent_borders_for_aligned_invoice_fields", "crates/export/src/tests.rs::word_overlap_does_not_consume_invoice_body_space", "crates/export/src/tests.rs::word_keeps_a_page_with_a_clear_image_and_big_title_in_flow", "crates/export/src/tests.rs::word_rotated_pages_keep_separate_page_sizes_and_unique_shapes", "crates/engine/src/tests.rs::office_export_positions_follow_the_displayed_crop_rotation_and_units", "crates/automation/tests/it/automation.rs::exporting_an_invoice_to_word_keeps_the_watermark_out_of_flow", "crates/export/src/tests.rs::docx_is_a_word_package", "crates/export/src/tests.rs::text_colour_survives_every_format", "crates/engine/src/tests.rs::exporting_office_files_keeps_text_colour", "crates/export/src/tests.rs::grid_text_becomes_a_real_table_in_every_format", "crates/export/src/tests.rs::a_link_inside_a_sentence_is_not_a_table_column", "crates/export/src/tests.rs::sentences_that_run_on_into_links_are_not_a_table", "crates/export/src/tests.rs::a_superscript_beside_a_number_keeps_its_table", "crates/export/src/tests.rs::word_opens_text_with_control_characters_and_long_pages", "crates/engine/src/tests.rs::exporting_office_files_keeps_images", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf", "crates/ui-egui/tests/it/compare.rs::export_to_word_html_and_rtf", "crates/export/src/tests.rs::docx_keeps_a_shared_page_background", "crates/edit/src/tests.rs::a_page_painted_first_with_a_full_page_fill_has_that_background", "crates/engine/src/tests.rs::exporting_to_word_keeps_the_page_background", "crates/export/src/tests.rs::an_italic_word_stays_in_its_sentence", "crates/export/src/tests.rs::a_sentence_keeps_its_reading_order", "crates/export/src/tests.rs::runs_keep_the_spaces_the_source_had_between_them", "crates/export/src/tests.rs::a_paragraph_is_a_heading_only_when_its_text_is", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_an_italic_word_inside_its_sentence", "crates/export/src/tests.rs::word_and_html_take_the_documents_language", "crates/engine/src/tests.rs::office_exports_take_the_documents_language", "crates/export/src/tests.rs::a_sentence_that_wraps_after_a_style_change_is_one_paragraph", "crates/export/src/tests.rs::a_slanted_word_that_leans_into_the_next_stays_in_its_line", "crates/export/src/tests.rs::a_paragraph_breaks_where_its_line_does_not_run_on", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_a_wrapped_sentence_in_one_paragraph", "crates/export/src/tests.rs::a_bulleted_list_is_paragraphs_not_a_table", "crates/export/src/tests.rs::a_bullet_is_never_a_table_cell", "crates/export/src/tests.rs::a_long_bulleted_list_keeps_every_bullet_with_its_item", "crates/export/src/tests.rs::a_dash_in_a_table_row_stays_a_cell", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_a_bulleted_list_as_paragraphs"] -notes = "Text in slots covered by a preceding table-cell span remains in paragraph flow instead of being discarded. Flowing Word document: paragraphs, Heading 1/2 from larger text, bold/italic, text colour (fill as sRGB; gray/CMYK converted naively, colour spaces via cs/sc read as black), detected tables with spans/empty cells (borderless, except single borders along the grid lines the page draws, #5149) (cell widths sum the grid columns they occupy, including cells after spans, verified in the XML; a row whose blocks run on into each other, such as a link or superscript inside a sentence, or overlap, as a paragraph's lines do, is text and not a table row, #2806), per-page sections/sizes, the page colour (a full-page opaque fill painted first, such as Edit a PDF ▸ Background) as the document background when every page shares one non-white colour (Word has no per-page background, so differing colours are dropped; #2992; checked in the XML only, not yet opened in Word), and positioned editable text/artwork only for pages with rotated text or text overlapped by an image or watermark-sized text, other pages flowing with inline images (#773); synthetic invoice regression; dotted-leader contents entries keep the title, dots and page number together in separate paragraphs (#1757); the emitted package validates with Open XML SDK 2.20 (Office 2010 schema). Word/LibreOffice rendering of the positioned output remains unverified. Pictures on positioned pages are DrawingML anchors behind the text (a VML rectangle with an image showed no picture, #1936; not yet opened in Word); a Word file embeds at most 1000 pictures and 512 MiB of them. The earlier flowing output was checked with macOS textutil and opened in Microsoft Word (Windows). Characters XML forbids are dropped; the page size stays within Word's 22 in. A block that continues another on its line (an italic case name, a link, a superscript) is a run in its own size, bold/italic and colour inside that paragraph, keeping the source's word space between them, rather than a paragraph of its own; a lead-in in bold no longer makes its whole line a heading (#4158); a slanted run whose box leans into the next word by up to 0.3 of its size still runs on into it. A paragraph whose last line reaches the right edge of the page's text runs on into the line just below it that starts at the same left edge in the same size, so a sentence the reading blocks split at a style change stays one paragraph across its lines; headings, list items, a line that ends a sentence, an indented line and one after paragraph space keep their break (#4158). A list whose bullets are blocks of their own (a bullet in a symbol font a tab stop before the item's text, as Word writes it, U+F0B7 and U+F0A7 included) is one paragraph per item, the bullet first, and not a borderless two-column table: a bullet is never a table cell, and a dash or middle dot counts as a bullet only when nothing starts left of it on its line. The PDF's language (`/Lang`, when it is a well formed BCP 47 tag) is the default language of the text, in the attribute Word keeps for its script (East Asian, right to left or other), so Word checks the spelling in it rather than in English (checked in the XML only, not yet opened in Word). Not yet: Word list numbering (an item is a plain paragraph that starts with its bullet), a bullet drawn in the standard Symbol font without a ToUnicode map (it never reaches export, though text extraction reads it), a paragraph whose rows the reading blocks already grouped past a style change (the exporter does not see where such a block's last row ends), a wrapped line that ends in a full stop or colon, a page whose only text is short lines that end without punctuation, such as a poem (its longest line counts as full, so the lines join), a first-line indent, lines with more than half their font size of space between them (as 1.5 or double line spacing leaves), text in columns, exact font matching, vector rules other than a table grid, arbitrary paint-order/transparency, general exact layout fidelity." +evidence = ["crates/export/src/tests.rs::word_table_cell_widths_follow_the_columns_they_span", "crates/export/src/tests.rs::table_spans_do_not_consume_text_they_do_not_emit", "crates/edit/src/tests.rs::reading_keeps_dotted_leader_entries_whole_and_in_order", "crates/engine/src/tests.rs::exporting_office_keeps_dotted_leader_entries_as_paragraphs", "crates/export/src/tests.rs::word_does_not_invent_borders_for_aligned_invoice_fields", "crates/export/src/tests.rs::word_overlap_does_not_consume_invoice_body_space", "crates/export/src/tests.rs::word_keeps_a_page_with_a_clear_image_and_big_title_in_flow", "crates/export/src/tests.rs::word_rotated_pages_keep_separate_page_sizes_and_unique_shapes", "crates/engine/src/tests.rs::office_export_positions_follow_the_displayed_crop_rotation_and_units", "crates/automation/tests/it/automation.rs::exporting_an_invoice_to_word_keeps_the_watermark_out_of_flow", "crates/export/src/tests.rs::word_names_pdfcraft_and_its_fonts", "crates/export/src/tests.rs::word_text_boxes_have_a_fallback_for_word_2007", "crates/export/src/tests.rs::word_rotated_text_is_a_turned_line", "crates/export/src/tests.rs::word_keeps_line_breaks_and_tabs_inside_paragraphs_and_cells", "crates/export/src/tests.rs::docx_is_a_word_package", "crates/export/src/tests.rs::text_colour_survives_every_format", "crates/engine/src/tests.rs::exporting_office_files_keeps_text_colour", "crates/export/src/tests.rs::grid_text_becomes_a_real_table_in_every_format", "crates/export/src/tests.rs::a_link_inside_a_sentence_is_not_a_table_column", "crates/export/src/tests.rs::sentences_that_run_on_into_links_are_not_a_table", "crates/export/src/tests.rs::a_superscript_beside_a_number_keeps_its_table", "crates/export/src/tests.rs::word_opens_text_with_control_characters_and_long_pages", "crates/engine/src/tests.rs::exporting_office_files_keeps_images", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf", "crates/ui-egui/tests/it/compare.rs::export_to_word_html_and_rtf", "crates/export/src/tests.rs::docx_keeps_a_shared_page_background", "crates/edit/src/tests.rs::a_page_painted_first_with_a_full_page_fill_has_that_background", "crates/engine/src/tests.rs::exporting_to_word_keeps_the_page_background", "crates/export/src/tests.rs::an_italic_word_stays_in_its_sentence", "crates/export/src/tests.rs::a_sentence_keeps_its_reading_order", "crates/export/src/tests.rs::runs_keep_the_spaces_the_source_had_between_them", "crates/export/src/tests.rs::a_paragraph_is_a_heading_only_when_its_text_is", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_an_italic_word_inside_its_sentence", "crates/export/src/tests.rs::word_and_html_take_the_documents_language", "crates/engine/src/tests.rs::office_exports_take_the_documents_language", "crates/export/src/tests.rs::a_sentence_that_wraps_after_a_style_change_is_one_paragraph", "crates/export/src/tests.rs::a_slanted_word_that_leans_into_the_next_stays_in_its_line", "crates/export/src/tests.rs::a_paragraph_breaks_where_its_line_does_not_run_on", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_a_wrapped_sentence_in_one_paragraph", "crates/export/src/tests.rs::a_bulleted_list_is_paragraphs_not_a_table", "crates/export/src/tests.rs::a_bullet_is_never_a_table_cell", "crates/export/src/tests.rs::a_long_bulleted_list_keeps_every_bullet_with_its_item", "crates/export/src/tests.rs::a_dash_in_a_table_row_stays_a_cell", "crates/automation/tests/it/automation.rs::exporting_to_word_keeps_a_bulleted_list_as_paragraphs"] +notes = "Text in slots covered by a preceding table-cell span remains in paragraph flow instead of being discarded. Flowing Word document: paragraphs, Heading 1/2 from larger text, bold/italic, text colour (fill as sRGB; gray/CMYK converted naively, colour spaces via cs/sc read as black), detected tables with spans/empty cells (borderless, except single borders along the grid lines the page draws, #5149) (cell widths sum the grid columns they occupy, including cells after spans, verified in the XML; a row whose blocks run on into each other, such as a link or superscript inside a sentence, or overlap, as a paragraph's lines do, is text and not a table row, #2806), per-page sections/sizes, the page colour (a full-page opaque fill painted first, such as Edit a PDF ▸ Background) as the document background when every page shares one non-white colour (Word has no per-page background, so differing colours are dropped; #2992; checked in the XML only, not yet opened in Word), and positioned editable text/artwork only for pages with rotated text or text overlapped by an image or watermark-sized text, other pages flowing with inline images (#773); synthetic invoice regression; dotted-leader contents entries keep the title, dots and page number together in separate paragraphs (#1757); the emitted package validates with Open XML SDK 2.20 (Office 2010 schema). Written by craft-docx from the word model PdfCraft's RTF export also uses (storytold/craft-libs#793): every text box has a VML fallback, so Word 2007 opens positioned pages; rotated text is a turned text box, drawn as a line (the W-4 draft's margin text was a column of letters); pictures on positioned pages float behind the text, over watermark-sized text; the body font is Arial, with a font table saying it is a sans; docProps/app.xml names PdfCraft; a picture drawn many times is stored once. Seven public PDFs (IRS W-9, 1040 and W-4 drafts, arXiv 1706.03762, NIST CSF 2.0, a W3C table, the BLS Employment Situation) open in Word 16, Word 2007 and LibreOffice with the same words as before; flowing pages run a little longer in Arial than in the Times New Roman Word fell back to. A Word file embeds at most 1000 pictures and 512 MiB of them. The earlier flowing output was checked with macOS textutil and opened in Microsoft Word (Windows). Characters XML forbids are dropped; the page size stays within Word's 22 in. A block that continues another on its line (an italic case name, a link, a superscript) is a run in its own size, bold/italic and colour inside that paragraph, keeping the source's word space between them, rather than a paragraph of its own; a lead-in in bold no longer makes its whole line a heading (#4158); a slanted run whose box leans into the next word by up to 0.3 of its size still runs on into it. A paragraph whose last line reaches the right edge of the page's text runs on into the line just below it that starts at the same left edge in the same size, so a sentence the reading blocks split at a style change stays one paragraph across its lines; headings, list items, a line that ends a sentence, an indented line and one after paragraph space keep their break (#4158). A list whose bullets are blocks of their own (a bullet in a symbol font a tab stop before the item's text, as Word writes it, U+F0B7 and U+F0A7 included) is one paragraph per item, the bullet first, and not a borderless two-column table: a bullet is never a table cell, and a dash or middle dot counts as a bullet only when nothing starts left of it on its line. The PDF's language (`/Lang`, when it is a well formed BCP 47 tag) is the default language of the text, in the attribute Word keeps for its script (East Asian, right to left or other), so Word checks the spelling in it rather than in English (checked in the XML only, not yet opened in Word). Not yet: Word list numbering (an item is a plain paragraph that starts with its bullet), a bullet drawn in the standard Symbol font without a ToUnicode map (it never reaches export, though text extraction reads it), a paragraph whose rows the reading blocks already grouped past a style change (the exporter does not see where such a block's last row ends), a wrapped line that ends in a full stop or colon, a page whose only text is short lines that end without punctuation, such as a poem (its longest line counts as full, so the lines join), a first-line indent, lines with more than half their font size of space between them (as 1.5 or double line spacing leaves), text in columns, exact font matching, vector rules other than a table grid, arbitrary paint-order/transparency, general exact layout fidelity." [[feature]] id = "create.export-rtf" @@ -7241,8 +7241,8 @@ milestone = "M10" status = "shipped" commands = ["export.rtf"] tools = ["doc_export_office"] -evidence = ["crates/export/src/tests.rs::table_spans_do_not_consume_text_they_do_not_emit", "crates/export/src/tests.rs::rtf_escapes_and_sizes", "crates/export/src/tests.rs::text_colour_survives_every_format", "crates/export/src/tests.rs::word_opens_text_with_control_characters_and_long_pages", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf", "crates/ui-egui/tests/it/compare.rs::export_to_word_html_and_rtf", "crates/export/src/tests.rs::a_sentence_that_wraps_after_a_style_change_is_one_paragraph", "crates/export/src/tests.rs::a_bulleted_list_is_paragraphs_not_a_table"] -notes = "Text in slots covered by a preceding table-cell span remains in paragraph flow instead of being discarded. Paragraphs with sizes, bold, italic, text colour (colortbl), Unicode; a block that continues another on its line is a formatted group inside that paragraph (#4158), and a paragraph that wraps onto the next line after a style change runs on there, with the same rules and limits as Word export; a list whose bullets are blocks of their own is a paragraph per item, not a table, as in Word export; page breaks. Images are left out." +evidence = ["crates/export/src/tests.rs::table_spans_do_not_consume_text_they_do_not_emit", "crates/export/src/tests.rs::rtf_escapes_and_sizes", "crates/export/src/tests.rs::text_colour_survives_every_format", "crates/export/src/tests.rs::word_opens_text_with_control_characters_and_long_pages", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf", "crates/ui-egui/tests/it/compare.rs::export_to_word_html_and_rtf", "crates/export/src/tests.rs::a_sentence_that_wraps_after_a_style_change_is_one_paragraph", "crates/export/src/tests.rs::a_bulleted_list_is_paragraphs_not_a_table", "crates/export/src/tests.rs::rtf_keeps_pictures", "crates/export/src/tests.rs::rtf_keeps_pages_without_text", "crates/export/src/tests.rs::rtf_headings_have_heading_styles", "crates/export/src/tests.rs::rtf_keeps_hard_line_breaks_in_paragraphs_and_cells"] +notes = "Text in slots covered by a preceding table-cell span remains in paragraph flow instead of being discarded. Paragraphs with sizes, bold, italic, text colour (colortbl), Unicode; a block that continues another on its line is a formatted group inside that paragraph (#4158), and a paragraph that wraps onto the next line after a style change runs on there, with the same rules and limits as Word export; a list whose bullets are blocks of their own is a paragraph per item, not a table, as in Word export; written by craft-rtf's full writer from the word model: each page a section of its own size (blank pages kept), pictures inline, Heading 1 and 2 styles, tables that touch kept apart, hard line breaks kept inside their paragraph or cell, and the title. Not kept: the PDF's language (the writer names English), and positioned pages flow." [[feature]] diff --git a/vendor/hayro-postscript/Cargo.lock b/vendor/hayro-postscript/Cargo.lock deleted file mode 100644 index b95d341526..0000000000 --- a/vendor/hayro-postscript/Cargo.lock +++ /dev/null @@ -1,7 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "hayro-postscript" -version = "0.1.0" diff --git a/vendor/hayro-postscript/Cargo.toml b/vendor/hayro-postscript/Cargo.toml deleted file mode 100644 index b1d53c3f3f..0000000000 --- a/vendor/hayro-postscript/Cargo.toml +++ /dev/null @@ -1,70 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2024" -name = "hayro-postscript" -version = "0.1.0" -authors = ["Laurenz Stampfl "] -build = false -autolib = false -autobins = false -autoexamples = false -autotests = false -autobenches = false -description = "A lightweight PostScript scanner." -readme = "README.md" -license = "Apache-2.0 OR MIT" -repository = "https://github.com/LaurenzV/hayro" -resolver = "2" - -[lib] -name = "hayro_postscript" -path = "src/lib.rs" - -[[example]] -name = "tokenize" -path = "examples/tokenize.rs" - -[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-postscript/Cargo.toml.orig b/vendor/hayro-postscript/Cargo.toml.orig deleted file mode 100644 index 6ba1eed22f..0000000000 --- a/vendor/hayro-postscript/Cargo.toml.orig +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "hayro-postscript" -version = "0.1.0" -description = "A lightweight PostScript scanner." -authors = { workspace = true } -edition = { workspace = true } -repository = { workspace = true } -license = { workspace = true } - -[lints] -workspace = true diff --git a/vendor/hayro-postscript/LICENSE-APACHE b/vendor/hayro-postscript/LICENSE-APACHE deleted file mode 100644 index 4947287f7b..0000000000 --- a/vendor/hayro-postscript/LICENSE-APACHE +++ /dev/null @@ -1,177 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/vendor/hayro-postscript/LICENSE-MIT b/vendor/hayro-postscript/LICENSE-MIT deleted file mode 100644 index ae3742de4e..0000000000 --- a/vendor/hayro-postscript/LICENSE-MIT +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) The Hayro Authors - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/hayro-postscript/README.md b/vendor/hayro-postscript/README.md deleted file mode 100644 index 3c2282716b..0000000000 --- a/vendor/hayro-postscript/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# hayro-postscript - -[![Crates.io](https://img.shields.io/crates/v/hayro-postscript.svg)](https://crates.io/crates/hayro-postscript) -[![Documentation](https://docs.rs/hayro-postscript/badge.svg)](https://docs.rs/hayro-postscript) - - - -A lightweight PostScript scanner. - -This crate provides a scanner for tokenizing PostScript programs into typed objects. -It currently only implements a very small subset of the PostScript language, -with the main goal of being enough to parse CMAP files, but the scope _might_ -be expanded upon in the future. - -The supported types include integers and real numbers, name objects, strings and arrays. -Unsupported is anything else, including dictionaries, procedures, etc. An error -will be returned in case any of these is encountered. - -### Safety -This crate forbids unsafe code via a crate-level attribute. - - - -## License -Licensed under either of - -- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) -- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) - -at your option. diff --git a/vendor/hayro-postscript/examples/tokenize.rs b/vendor/hayro-postscript/examples/tokenize.rs deleted file mode 100644 index c8cd84d038..0000000000 --- a/vendor/hayro-postscript/examples/tokenize.rs +++ /dev/null @@ -1,74 +0,0 @@ -//! A small example that shows how to tokenize a PostScript program. - -#![allow(missing_docs)] - -use hayro_postscript::{Number, Object, Scanner}; -use std::env; -use std::fs; -use std::process; - -fn main() { - let path = match env::args().nth(1) { - Some(p) => p, - None => { - eprintln!("Usage: tokenize "); - process::exit(1); - } - }; - - let data = match fs::read(&path) { - Ok(d) => d, - Err(e) => { - eprintln!("Error reading {path}: {e}"); - process::exit(1); - } - }; - - let mut scanner = Scanner::new(&data); - - while !scanner.at_end() { - match scanner.parse_object() { - Ok(object) => { - print_object(&object); - println!(); - } - Err(e) => eprintln!("Error: {e}"), - } - } -} - -fn print_object(object: &Object<'_>) { - match object { - Object::Number(Number::Integer(n)) => print!("Integer({n})"), - Object::Number(Number::Real(n)) => print!("Real({n})"), - Object::Name(name) => { - let kind = if name.is_literal() { - "literal" - } else { - "executable" - }; - let text = name.as_str().unwrap_or(""); - print!("Name({text}, {kind})"); - } - Object::String(s) => { - let decoded = s.decode().unwrap_or_else(|_| Vec::new()); - print!("String({})", String::from_utf8_lossy(&decoded)); - } - Object::Array(arr) => { - print!("["); - let mut inner = arr.objects(); - let mut first = true; - while !inner.at_end() { - if !first { - print!(" "); - } - first = false; - match inner.parse_object() { - Ok(obj) => print_object(&obj), - Err(e) => print!("Error({e})"), - } - } - print!("]"); - } - } -} diff --git a/vendor/hayro-postscript/src/array.rs b/vendor/hayro-postscript/src/array.rs deleted file mode 100644 index b96b3601a5..0000000000 --- a/vendor/hayro-postscript/src/array.rs +++ /dev/null @@ -1,127 +0,0 @@ -use crate::error::{Error, Result}; -use crate::object; -use crate::reader::Reader; -use crate::string; - -/// A PostScript array object. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Array<'a> { - data: &'a [u8], -} - -impl<'a> Array<'a> { - pub(crate) fn new(data: &'a [u8]) -> Self { - Self { data } - } - - /// Return a [`Scanner`](crate::Scanner) that iterates over the objects inside - /// this array. - pub fn objects(&self) -> crate::Scanner<'a> { - crate::Scanner::new(self.data) - } -} - -pub(crate) fn parse<'a>(r: &mut Reader<'a>) -> Result<&'a [u8]> { - r.forward_tag(b"[").ok_or(Error::SyntaxError)?; - - let start = r.offset(); - skip_array(r)?; - let end = r.offset() - 1; - - r.range(start..end).ok_or(Error::SyntaxError) -} - -fn skip_array(r: &mut Reader<'_>) -> Result<()> { - let mut depth = 1_u32; - - while depth > 0 { - match r.peek_byte().ok_or(Error::SyntaxError)? { - b'[' => { - r.forward(); - depth += 1; - } - b']' => { - r.forward(); - depth -= 1; - } - b'(' => { - let _ = string::parse_literal(r).ok_or(Error::SyntaxError)?; - } - b'<' => { - if r.peek_bytes(2) == Some(b"<~") { - let _ = string::parse_ascii85(r).ok_or(Error::SyntaxError)?; - } else if r.peek_bytes(2) == Some(b"<<") { - r.forward(); - r.forward(); - } else { - let _ = string::parse_hex(r).ok_or(Error::SyntaxError)?; - } - } - b'%' => object::skip_whitespace_and_comments(r), - _ => { - r.forward(); - } - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn parse_array(input: &[u8]) -> Result<&[u8]> { - let mut r = Reader::new(input); - parse(&mut r) - } - - #[test] - fn empty() { - assert_eq!(parse_array(b"[]").unwrap(), b""); - } - - #[test] - fn simple() { - assert_eq!(parse_array(b"[1 2 3]").unwrap(), b"1 2 3"); - } - - #[test] - fn nested() { - assert_eq!(parse_array(b"[1 [2 3] 4]").unwrap(), b"1 [2 3] 4"); - } - - #[test] - fn with_string() { - // The ']' inside the string should not close the array. - assert_eq!(parse_array(b"[1 (str]) 2]").unwrap(), b"1 (str]) 2"); - } - - #[test] - fn with_hex_string() { - assert_eq!(parse_array(b"[<48> /name]").unwrap(), b"<48> /name"); - } - - #[test] - fn with_ascii85_string() { - assert_eq!(parse_array(b"[<~87cURDZ~> 1]").unwrap(), b"<~87cURDZ~> 1"); - } - - #[test] - fn with_comment() { - assert_eq!( - parse_array(b"[1 % comment with ]\n2]").unwrap(), - b"1 % comment with ]\n2" - ); - } - - #[test] - fn unterminated() { - assert_eq!(parse_array(b"[1 2"), Err(Error::SyntaxError)); - } - - #[test] - fn not_an_array() { - assert_eq!(parse_array(b"1 2]"), Err(Error::SyntaxError)); - } -} diff --git a/vendor/hayro-postscript/src/error.rs b/vendor/hayro-postscript/src/error.rs deleted file mode 100644 index 3a2627a1a6..0000000000 --- a/vendor/hayro-postscript/src/error.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! Error types for the PostScript scanner. - -use core::fmt; - -/// A specialized [`Result`] type for PostScript scanner operations. -pub type Result = core::result::Result; - -/// An error encountered while scanning a PostScript token stream. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Error { - /// A syntax error in the input. - SyntaxError, - /// A numeric value exceeded implementation limits. - LimitCheck, - /// An unsupported PostScript type was encountered (like dictionaries or - /// procedures, which will be added in the future). - UnsupportedType, -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::SyntaxError => f.write_str("syntaxerror"), - Self::LimitCheck => f.write_str("limitcheck"), - Self::UnsupportedType => f.write_str("unsupported type"), - } - } -} - -impl core::error::Error for Error {} diff --git a/vendor/hayro-postscript/src/lib.rs b/vendor/hayro-postscript/src/lib.rs deleted file mode 100644 index e254d37b6f..0000000000 --- a/vendor/hayro-postscript/src/lib.rs +++ /dev/null @@ -1,275 +0,0 @@ -/*! -A lightweight PostScript scanner. - -This crate provides a scanner for tokenizing PostScript programs into typed objects. -It currently only implements a very small subset of the PostScript language, -with the main goal of being enough to parse CMAP files, but the scope _might_ -be expanded upon in the future. - -The supported types include integers and real numbers, name objects, strings and arrays. -Unsupported is anything else, including dictionaries, procedures, etc. An error -will be returned in case any of these is encountered. - -## Safety -This crate forbids unsafe code via a crate-level attribute. -*/ - -#![no_std] -#![forbid(unsafe_code)] -#![allow(missing_docs)] - -extern crate alloc; - -mod array; -mod error; -mod name; -mod number; -mod object; -mod reader; -mod string; - -pub use array::Array; -pub use error::{Error, Result}; -pub use name::Name; -pub use number::Number; -pub use object::Object; -pub use string::String; - -use reader::Reader; - -/// A PostScript scanner that parses [`Object`]s from a byte stream. -pub struct Scanner<'a> { - reader: Reader<'a>, -} - -impl<'a> Scanner<'a> { - /// Create a new scanner over the given bytes of a PostScript program. - pub fn new(data: &'a [u8]) -> Self { - Self { - reader: Reader::new(data), - } - } - - /// Returns `true` if there are no more objects to parse. - pub fn at_end(&mut self) -> bool { - object::at_end(&mut self.reader) - } - - /// Parse the next object. - pub fn parse_object(&mut self) -> Result> { - object::read(&mut self.reader) - } - - /// PdfCraft patch (2): parse the next object; when it can't be read, read on from where - /// the failed read stopped, or, when it read nothing, from one byte past where its token - /// starts, so a caller can read on past a token it can't parse (a stray `>` in a name, a - /// CMap name with spaces in it) instead of stopping there. Every failure moves forward, one - /// failure per unreadable token, and what a failed read went through (an unclosed string, - /// to the end of the data) is not read again, so a loop over this ends and reads the data - /// about once. A number that can't be read is skipped to the end of its token: its tail - /// (`beginbfchar` in `1beginbfchar`) is not read as a token of its own. - pub fn parse_object_or_skip(&mut self) -> Result> { - // The whitespace and comments before the token are not the token: skipped first, they - // don't count as progress, so a token after a space fails once, not twice. - object::skip_whitespace_and_comments(&mut self.reader); - let start = self.reader.offset(); - // `object::read` reads a token starting with one of these bytes as a number. - let number = matches!( - self.reader.peek_byte(), - Some(b'.' | b'+' | b'-' | b'0'..=b'9') - ); - let read = object::read(&mut self.reader); - // A number read stops at the first byte that can't be part of a number, which may be - // inside the token; the rest of the token goes with it. - if read.is_err() && number { - self.reader.forward_while(reader::is_regular); - } - if read.is_err() && self.reader.offset() <= start { - self.reader - .jump(start.saturating_add(1).min(self.reader.data.len())); - } - read - } - - /// Parse the next object as a [`Number`]. - pub fn parse_number(&mut self) -> Result { - match self.parse_object()? { - Object::Number(n) => Ok(n), - _ => Err(Error::SyntaxError), - } - } - - /// Parse the next object as a [`Name`]. - pub fn parse_name(&mut self) -> Result> { - match self.parse_object()? { - Object::Name(n) => Ok(n), - _ => Err(Error::SyntaxError), - } - } - - /// Parse the next object as a [`String`]. - pub fn parse_string(&mut self) -> Result> { - match self.parse_object()? { - Object::String(s) => Ok(s), - _ => Err(Error::SyntaxError), - } - } - - /// Parse the next object as an [`Array`]. - pub fn parse_array(&mut self) -> Result> { - match self.parse_object()? { - Object::Array(a) => Ok(a), - _ => Err(Error::SyntaxError), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cmap_snippet() { - let input = br#"/CIDInit /ProcSet findresource begin -12 dict begin -begincmap -/CMapName /Test-H def -1 begincodespacerange -<00> -endcodespacerange -2 beginbfchar -<03> <0041> -<04> <0042> -endbfchar -endcmap"#; - - let mut s = Scanner::new(input); - - assert_eq!(s.parse_name().unwrap(), Name::new(b"CIDInit", true)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"ProcSet", true)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"findresource", false)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false)); - assert_eq!(s.parse_number().unwrap(), Number::Integer(12)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"dict", false)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"begincmap", false)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"CMapName", true)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"Test-H", true)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"def", false)); - assert_eq!(s.parse_number().unwrap(), Number::Integer(1)); - assert_eq!( - s.parse_name().unwrap(), - Name::new(b"begincodespacerange", false) - ); - assert_eq!(s.parse_string().unwrap(), String::from_hex(b"00")); - assert_eq!(s.parse_string().unwrap(), String::from_hex(b"FF")); - assert_eq!( - s.parse_name().unwrap(), - Name::new(b"endcodespacerange", false) - ); - assert_eq!(s.parse_number().unwrap(), Number::Integer(2)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"beginbfchar", false)); - assert_eq!(s.parse_string().unwrap(), String::from_hex(b"03")); - assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0041")); - assert_eq!(s.parse_string().unwrap(), String::from_hex(b"04")); - assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0042")); - assert_eq!(s.parse_name().unwrap(), Name::new(b"endbfchar", false)); - assert_eq!(s.parse_name().unwrap(), Name::new(b"endcmap", false)); - assert!(s.at_end()); - } - - #[test] - fn array_round_trip() { - let input = b"[123 /abc (xyz)]"; - let mut scanner = Scanner::new(input); - let arr = scanner.parse_array().unwrap(); - assert!(scanner.at_end()); - - let mut inner = arr.objects(); - assert_eq!(inner.parse_number().unwrap(), Number::Integer(123)); - assert_eq!(inner.parse_name().unwrap(), Name::new(b"abc", true)); - assert_eq!(inner.parse_string().unwrap(), String::from_literal(b"xyz")); - assert!(inner.at_end()); - } - - #[test] - fn comments_skipped() { - let input = b"% comment\n42 % another\n/Name"; - let mut scanner = Scanner::new(input); - - assert_eq!(scanner.parse_number().unwrap(), Number::Integer(42)); - assert_eq!(scanner.parse_name().unwrap(), Name::new(b"Name", true)); - assert!(scanner.at_end()); - } - - #[test] - fn wrong_type_is_error() { - let mut scanner = Scanner::new(b"42 "); - assert!(scanner.parse_name().is_err()); - } - - /// PdfCraft patch (2) test: a token that can't be read fails once and is stepped over, - /// whether or not whitespace or a comment comes before it, and the objects after it read. - #[test] - fn parse_object_or_skip_steps_over_an_unreadable_token() { - let mut s = Scanner::new(b"/A> /B % note\n > /C"); - assert_eq!( - s.parse_object_or_skip(), - Ok(Object::Name(Name::new(b"A", true))) - ); - assert!(s.parse_object_or_skip().is_err()); - assert_eq!( - s.parse_object_or_skip(), - Ok(Object::Name(Name::new(b"B", true))) - ); - assert!(s.parse_object_or_skip().is_err()); - assert_eq!( - s.parse_object_or_skip(), - Ok(Object::Name(Name::new(b"C", true))) - ); - assert!(s.at_end()); - } - - /// PdfCraft patch (2) test: a number that can't be read fails once with the rest of its - /// token, which is not read as a name of its own; the tokens after it still read. - #[test] - fn parse_object_or_skip_skips_the_rest_of_an_unreadable_number() { - let mut s = Scanner::new(b"1beginbfchar 2.5.3x 16#zz! -x /C"); - for _ in 0..4 { - assert!(s.parse_object_or_skip().is_err()); - } - assert_eq!( - s.parse_object_or_skip(), - Ok(Object::Name(Name::new(b"C", true))) - ); - assert!(s.at_end()); - } - - /// PdfCraft patch (2) test: what a failed read went through is not read again. An unclosed - /// string reads to the end of the data, so one failure leaves nothing to read; the nested - /// `(` inside it are not each read to the end once more. - #[test] - fn parse_object_or_skip_does_not_read_a_failed_read_again() { - let mut s = Scanner::new(b"/A (((( x"); - assert_eq!( - s.parse_object_or_skip(), - Ok(Object::Name(Name::new(b"A", true))) - ); - assert!(s.parse_object_or_skip().is_err()); - assert!(s.at_end()); - } - - /// PdfCraft patch (2) test: at the end of the data a read fails and the scanner stays at - /// the end; it never steps past the data. - #[test] - fn parse_object_or_skip_stays_at_the_end() { - for input in [&b""[..], b" ", b">"] { - let mut s = Scanner::new(input); - for _ in 0..3 { - assert!(s.parse_object_or_skip().is_err()); - assert!(s.reader.offset() <= input.len()); - } - assert!(s.at_end()); - } - } -} diff --git a/vendor/hayro-postscript/src/name.rs b/vendor/hayro-postscript/src/name.rs deleted file mode 100644 index ab78e7ba67..0000000000 --- a/vendor/hayro-postscript/src/name.rs +++ /dev/null @@ -1,191 +0,0 @@ -use alloc::vec::Vec; - -use crate::error::{Error, Result}; -use crate::reader::{Reader, is_regular}; -use crate::string::ascii_hex::decode_hex_digit; - -/// A PostScript name object. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Name<'a> { - data: &'a [u8], - literal: bool, -} - -impl<'a> Name<'a> { - pub(crate) fn new(data: &'a [u8], literal: bool) -> Self { - Self { data, literal } - } - - /// Returns `true` if this is a literal name. - pub fn is_literal(&self) -> bool { - self.literal - } - - /// Returns the name as a string if it is valid UTF-8, or - /// `None` if it contains non-ASCII bytes. - pub fn as_str(&self) -> Option<&'a str> { - core::str::from_utf8(self.data).ok() - } - - /// Decode the name into `out`, replacing any previous contents. - pub fn decode_into(&self, out: &mut Vec) -> Result<()> { - out.clear(); - - // Fast path: no escape sequences. - if !self.data.contains(&b'#') { - out.extend_from_slice(self.data); - return Ok(()); - } - - // Slow path: Process escape sequences. - let mut inner = Reader::new(self.data); - - while let Some(b) = inner.read_byte() { - if b == b'#' { - let hex = inner.read_bytes(2).ok_or(Error::SyntaxError)?; - let hi = decode_hex_digit(hex[0]).ok_or(Error::SyntaxError)?; - let lo = decode_hex_digit(hex[1]).ok_or(Error::SyntaxError)?; - out.push(hi << 4 | lo); - } else { - out.push(b); - } - } - - Ok(()) - } - - /// Decode the name. - pub fn decode(&self) -> Result> { - let mut out = Vec::new(); - self.decode_into(&mut out)?; - Ok(out) - } -} - -pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { - r.forward_tag(b"/")?; - let start = r.offset(); - while r.eat(is_regular).is_some() {} - r.range(start..r.offset()) -} - -pub(crate) fn parse_executable<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { - let start = r.offset(); - r.forward_while(is_regular); - if r.offset() == start { - return None; - } - r.range(start..r.offset()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn read_literal(input: &[u8]) -> Option> { - let mut r = Reader::new(input); - parse_literal(&mut r).map(|d| Name::new(d, true)) - } - - fn read_executable(input: &[u8]) -> Option> { - let mut r = Reader::new(input); - parse_executable(&mut r).map(|d| Name::new(d, false)) - } - - #[test] - fn literal_simple() { - let n = read_literal(b"/Name1").unwrap(); - assert_eq!(n.as_str().unwrap(), "Name1"); - assert!(n.is_literal()); - } - - #[test] - fn literal_empty_name() { - let n = read_literal(b"/").unwrap(); - assert_eq!(n.as_str().unwrap(), ""); - assert!(n.is_literal()); - } - - #[test] - fn literal_with_hex_escape() { - let n = read_literal(b"/lime#20Green").unwrap(); - assert_eq!(n.as_str().unwrap(), "lime#20Green"); - assert_eq!(n.decode().unwrap(), b"lime Green"); - } - - #[test] - fn literal_multiple_hex_escapes() { - let n = read_literal(b"/paired#28#29parentheses").unwrap(); - assert_eq!(n.decode().unwrap(), b"paired()parentheses"); - } - - #[test] - fn literal_special_chars() { - let n = read_literal(b"/A;Name_With-Various***Characters?").unwrap(); - assert_eq!(n.as_str().unwrap(), "A;Name_With-Various***Characters?"); - } - - #[test] - fn literal_stops_at_delimiter() { - let mut r = Reader::new(b"/Name(rest"); - let data = parse_literal(&mut r).unwrap(); - assert_eq!(data, b"Name"); - assert_eq!(r.peek_byte(), Some(b'(')); - } - - #[test] - fn literal_stops_at_whitespace() { - let mut r = Reader::new(b"/Name rest"); - let data = parse_literal(&mut r).unwrap(); - assert_eq!(data, b"Name"); - assert_eq!(r.peek_byte(), Some(b' ')); - } - - #[test] - fn literal_not_a_name() { - assert!(read_literal(b"Name").is_none()); - } - - #[test] - fn executable_simple() { - let n = read_executable(b"beginbfchar ").unwrap(); - assert_eq!(n.as_str().unwrap(), "beginbfchar"); - assert!(!n.is_literal()); - } - - #[test] - fn executable_stops_at_delimiter() { - let mut r = Reader::new(b"def/name"); - let data = parse_executable(&mut r).unwrap(); - assert_eq!(data, b"def"); - assert_eq!(r.peek_byte(), Some(b'/')); - } - - #[test] - fn executable_at_eof() { - let n = read_executable(b"endcmap").unwrap(); - assert_eq!(n.as_str().unwrap(), "endcmap"); - } - - #[test] - fn executable_empty() { - assert!(read_executable(b"").is_none()); - } - - #[test] - fn executable_starts_at_delimiter() { - assert!(read_executable(b"(foo)").is_none()); - } - - #[test] - fn decode_no_escapes() { - let n = Name::new(b"simple", true); - assert_eq!(n.decode().unwrap(), b"simple"); - } - - #[test] - fn decode_with_escapes() { - let n = Name::new(b"lime#20Green", true); - assert_eq!(n.decode().unwrap(), b"lime Green"); - } -} diff --git a/vendor/hayro-postscript/src/number.rs b/vendor/hayro-postscript/src/number.rs deleted file mode 100644 index 5c6d3ba10f..0000000000 --- a/vendor/hayro-postscript/src/number.rs +++ /dev/null @@ -1,177 +0,0 @@ -use crate::error::{Error, Result}; -use crate::reader::{Reader, is_delimiter, is_whitespace}; - -/// A PostScript number object (integer or real). -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Number { - Integer(i32), - Real(f32), -} - -impl Number { - /// Return the value as an `i32`. Reals are truncated. - pub fn as_i32(self) -> i32 { - match self { - Self::Integer(v) => v, - Self::Real(v) => v as i32, - } - } - - /// Return the value as an `f32`. - pub fn as_f32(self) -> f32 { - match self { - Self::Integer(v) => v as f32, - Self::Real(v) => v, - } - } - - /// Return the value as an `f64`. - pub fn as_f64(self) -> f64 { - match self { - Self::Integer(v) => v as f64, - Self::Real(v) => v as f64, - } - } -} - -fn is_terminated(r: &Reader<'_>) -> bool { - match r.peek_byte() { - None => true, - Some(b) => is_whitespace(b) || is_delimiter(b), - } -} - -pub(crate) fn read(r: &mut Reader<'_>) -> Result { - let saved = r.offset(); - - // Optional sign. - let first = r.peek_byte().ok_or(Error::SyntaxError)?; - let has_sign = first == b'+' || first == b'-'; - - if has_sign { - r.forward(); - } - - // Consume leading digits. - let digit_start = r.offset(); - r.forward_while(|b| b.is_ascii_digit()); - let has_digits = r.offset() > digit_start; - - // Check if number is a radix number. - if !has_sign && has_digits && r.peek_byte() == Some(b'#') { - let base_bytes = r.range(digit_start..r.offset()).ok_or(Error::SyntaxError)?; - let base_str = core::str::from_utf8(base_bytes).map_err(|_| Error::SyntaxError)?; - let base = base_str.parse::().map_err(|_| Error::SyntaxError)?; - - if !(2..=36).contains(&base) { - return Err(Error::SyntaxError); - } - - // Skip `#`. - r.forward(); - - let num_start = r.offset(); - r.forward_while(|b| b.is_ascii_alphanumeric()); - - if r.offset() == num_start || !is_terminated(r) { - return Err(Error::SyntaxError); - } - - let num_bytes = r.range(num_start..r.offset()).ok_or(Error::SyntaxError)?; - let num_str = core::str::from_utf8(num_bytes).map_err(|_| Error::SyntaxError)?; - let value = i32::from_str_radix(num_str, base).map_err(|_| Error::SyntaxError)?; - - return Ok(Number::Integer(value)); - } - - // Check for real number indicators: `.` or `e`/`E`. - let has_dot = r.peek_byte() == Some(b'.'); - - if has_dot { - r.forward(); // skip '.' - r.forward_while(|b| b.is_ascii_digit()); - } - - // At this point we need at least some digits (before or after the dot). - if !has_digits && !has_dot { - return Err(Error::SyntaxError); - } - - let has_exponent = matches!(r.peek_byte(), Some(b'e' | b'E')); - if has_exponent { - r.forward(); - - // Optional exponent sign. - if matches!(r.peek_byte(), Some(b'+' | b'-')) { - r.forward(); - } - - r.forward_while(|b| b.is_ascii_digit()); - } - - if !is_terminated(r) { - return Err(Error::SyntaxError); - } - - let token = r.range(saved..r.offset()).ok_or(Error::SyntaxError)?; - let str = core::str::from_utf8(token).map_err(|_| Error::SyntaxError)?; - - if has_dot || has_exponent { - let value = str.parse::().map_err(|_| Error::SyntaxError)?; - - Ok(Number::Real(value)) - } else { - if !has_digits { - return Err(Error::SyntaxError); - } - - let value = str.parse::().map_err(|_| Error::SyntaxError)?; - - Ok(Number::Integer(value)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn read_num(input: &[u8]) -> Result { - let mut r = Reader::new(input); - read(&mut r) - } - - #[test] - fn signed_integers() { - assert_eq!(read_num(b"123 ").unwrap(), Number::Integer(123)); - assert_eq!(read_num(b"-98 ").unwrap(), Number::Integer(-98)); - assert_eq!(read_num(b"43445 ").unwrap(), Number::Integer(43445)); - assert_eq!(read_num(b"0 ").unwrap(), Number::Integer(0)); - assert_eq!(read_num(b"+17 ").unwrap(), Number::Integer(17)); - } - - #[test] - fn real_numbers() { - assert_eq!(read_num(b"-.002 ").unwrap(), Number::Real(-0.002)); - assert_eq!(read_num(b"34.5 ").unwrap(), Number::Real(34.5)); - assert_eq!(read_num(b"-3.62 ").unwrap(), Number::Real(-3.62)); - assert_eq!(read_num(b"123.6e10 ").unwrap(), Number::Real(123.6e10)); - assert_eq!(read_num(b"1.0E-5 ").unwrap(), Number::Real(1.0E-5)); - assert_eq!(read_num(b"1E6 ").unwrap(), Number::Real(1E6)); - assert_eq!(read_num(b"-1. ").unwrap(), Number::Real(-1.0)); - assert_eq!(read_num(b"0.0 ").unwrap(), Number::Real(0.0)); - } - - #[test] - fn radix_numbers() { - assert_eq!(read_num(b"8#1777 ").unwrap(), Number::Integer(0o1777)); - assert_eq!(read_num(b"16#FFFE ").unwrap(), Number::Integer(0xFFFE)); - assert_eq!(read_num(b"2#1000 ").unwrap(), Number::Integer(0b1000)); - } - - #[test] - fn invalid() { - assert!(read_num(b"abc").is_err()); - assert!(read_num(b"+abc").is_err()); - assert!(read_num(b"1a").is_err()); - } -} diff --git a/vendor/hayro-postscript/src/object.rs b/vendor/hayro-postscript/src/object.rs deleted file mode 100644 index 7c20075860..0000000000 --- a/vendor/hayro-postscript/src/object.rs +++ /dev/null @@ -1,226 +0,0 @@ -use crate::array::{self, Array}; -use crate::error::{Error, Result}; -use crate::name::{self, Name}; -use crate::number::{self, Number}; -use crate::reader::Reader; -use crate::string::{self, String}; - -/// A PostScript object. -#[derive(Debug, Clone, PartialEq)] -pub enum Object<'a> { - /// A number object. - Number(Number), - /// A name object. - Name(Name<'a>), - /// A string object. - String(String<'a>), - /// An array object. - Array(Array<'a>), -} - -pub(crate) fn read<'a>(r: &mut Reader<'a>) -> Result> { - // PdfCraft patch: `<<` and `>>` are skipped by looping instead of - // recursing once per delimiter, so a long run cannot overflow the stack. - loop { - skip_whitespace_and_comments(r); - - let b = r.peek_byte().ok_or(Error::SyntaxError)?; - - return match b { - b'(' => string::parse_literal(r) - .map(|s| Object::String(String::from_literal(s))) - .ok_or(Error::SyntaxError), - b'<' => { - if r.peek_bytes(2) == Some(b"<~") { - string::parse_ascii85(r) - .map(|s| Object::String(String::from_ascii85(s))) - .ok_or(Error::SyntaxError) - } else if r.peek_bytes(2) == Some(b"<<") { - // TODO: Proper dict support. For now, skip `<<` and return - // the next object so callers see the inner tokens. - r.forward(); - r.forward(); - continue; - } else { - string::parse_hex(r) - .map(|s| Object::String(String::from_hex(s))) - .ok_or(Error::SyntaxError) - } - } - b'/' => name::parse_literal(r) - .map(|s| Object::Name(Name::new(s, true))) - .ok_or(Error::SyntaxError), - b'[' => array::parse(r).map(|d| Object::Array(Array::new(d))), - b'>' => { - if r.peek_bytes(2) == Some(b">>") { - // TODO: Proper dict support. Skip `>>` closing delimiter. - r.forward(); - r.forward(); - continue; - } else { - Err(Error::SyntaxError) - } - } - b'{' => { - r.forward(); - Err(Error::UnsupportedType) - } - b'.' | b'+' | b'-' | b'0'..=b'9' => number::read(r).map(Object::Number), - _ => name::parse_executable(r) - .map(|s| Object::Name(Name::new(s, false))) - .ok_or(Error::SyntaxError), - }; - } -} - -pub(crate) fn at_end(r: &mut Reader<'_>) -> bool { - skip_whitespace_and_comments(r); - r.peek_byte().is_none() -} - -pub(crate) fn skip_whitespace_and_comments(r: &mut Reader<'_>) { - loop { - match r.peek_byte() { - Some(b) if crate::reader::is_whitespace(b) => { - r.forward(); - } - Some(b'%') => { - r.forward(); - r.forward_while(|b| !crate::reader::is_eol(b)); - } - _ => return, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn read_one(input: &[u8]) -> Result> { - let mut r = Reader::new(input); - read(&mut r) - } - - fn read_ok(input: &[u8]) -> Object<'_> { - read_one(input).unwrap() - } - - fn read_err(input: &[u8]) -> Error { - read_one(input).unwrap_err() - } - - #[test] - fn integer() { - assert_eq!(read_ok(b"42 "), Object::Number(Number::Integer(42))); - } - - #[test] - fn negative_integer() { - assert_eq!(read_ok(b"-7 "), Object::Number(Number::Integer(-7))); - } - - #[test] - fn literal_name() { - assert_eq!( - read_ok(b"/CMapName "), - Object::Name(Name::new(b"CMapName", true)) - ); - } - - #[test] - fn executable_name() { - let obj = read_ok(b"beginbfchar "); - assert_eq!(obj, Object::Name(Name::new(b"beginbfchar", false))); - } - - #[test] - fn literal_string() { - assert_eq!( - read_ok(b"(Hello)"), - Object::String(String::from_literal(b"Hello")) - ); - } - - #[test] - fn hex_string() { - assert_eq!( - read_ok(b"<48656C6C6F>"), - Object::String(String::from_hex(b"48656C6C6F")) - ); - } - - #[test] - fn ascii85_string() { - assert_eq!( - read_ok(b"<~87cURDZ~>"), - Object::String(String::from_ascii85(b"87cURDZ")) - ); - } - - #[test] - fn array_simple() { - let obj = read_ok(b"[1 2 3]"); - assert_eq!(obj, Object::Array(Array::new(b"1 2 3"))); - } - - #[test] - fn stray_close_bracket() { - assert_eq!(read_err(b"]"), Error::SyntaxError); - } - - #[test] - fn stray_gt() { - assert_eq!(read_err(b">x"), Error::SyntaxError); - } - - #[test] - fn skips_whitespace() { - assert_eq!(read_ok(b" \t\n 42 "), Object::Number(Number::Integer(42))); - } - - #[test] - fn skips_comments() { - assert_eq!( - read_ok(b"% this is a comment\n42 "), - Object::Number(Number::Integer(42)) - ); - } - - #[test] - fn eof() { - assert!(read_one(b"").is_err()); - assert!(read_one(b" ").is_err()); - assert!(read_one(b"% comment only\n").is_err()); - } - - // PdfCraft patch: `<<` and `>>` runs are skipped without recursion. - #[test] - fn long_open_dict_run_does_not_overflow() { - let input = alloc::vec![b'<'; 1_000_000]; - assert_eq!(read_err(&input), Error::SyntaxError); - } - - #[test] - fn long_close_dict_run_does_not_overflow() { - let input = b">>".repeat(500_000); - assert_eq!(read_err(&input), Error::SyntaxError); - } - - #[test] - fn dict_delimiters_are_skipped() { - let mut r = Reader::new(b"<< /A 1 >>"); - assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"A", true)))); - assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(1)))); - assert_eq!(read(&mut r), Err(Error::SyntaxError)); - } - - #[test] - fn nested_dict_delimiters_are_skipped() { - let mut r = Reader::new(b"<<<< /X >>>> 7 <<\n% c\n<< >> 8"); - assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"X", true)))); - assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(7)))); - assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(8)))); - assert!(at_end(&mut r)); - } -} diff --git a/vendor/hayro-postscript/src/reader.rs b/vendor/hayro-postscript/src/reader.rs deleted file mode 100644 index f8a4967462..0000000000 --- a/vendor/hayro-postscript/src/reader.rs +++ /dev/null @@ -1,136 +0,0 @@ -use core::ops::Range; - -#[derive(Clone, Debug)] -pub(crate) struct Reader<'a> { - pub(crate) data: &'a [u8], - pub(crate) offset: usize, -} - -impl<'a> Reader<'a> { - #[inline] - pub(crate) fn new(data: &'a [u8]) -> Self { - Self { data, offset: 0 } - } - - #[inline] - pub(crate) fn jump(&mut self, offset: usize) { - self.offset = offset; - } - - #[inline] - pub(crate) fn range(&self, range: Range) -> Option<&'a [u8]> { - self.data.get(range) - } - - #[inline] - pub(crate) fn offset(&self) -> usize { - self.offset - } - - #[inline] - pub(crate) fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> { - let v = self.peek_bytes(len)?; - self.offset += len; - Some(v) - } - - #[inline] - pub(crate) fn read_byte(&mut self) -> Option { - let v = self.peek_byte()?; - self.offset += 1; - Some(v) - } - - #[inline] - pub(crate) fn peek_bytes(&self, len: usize) -> Option<&'a [u8]> { - self.data.get(self.offset..self.offset + len) - } - - #[inline] - pub(crate) fn peek_byte(&self) -> Option { - self.data.get(self.offset).copied() - } - - #[inline] - pub(crate) fn eat(&mut self, f: impl Fn(u8) -> bool) -> Option { - let val = self.peek_byte()?; - if f(val) { - self.forward(); - Some(val) - } else { - None - } - } - - #[inline] - pub(crate) fn forward(&mut self) { - self.offset += 1; - } - - #[inline] - pub(crate) fn forward_while(&mut self, f: impl Fn(u8) -> bool) { - while let Some(b) = self.peek_byte() { - if f(b) { - self.forward(); - } else { - break; - } - } - } - - #[inline] - pub(crate) fn forward_tag(&mut self, tag: &[u8]) -> Option<()> { - self.peek_tag(tag)?; - self.offset += tag.len(); - Some(()) - } - - #[inline] - pub(crate) fn peek_tag(&self, tag: &[u8]) -> Option<()> { - let mut cloned = self.clone(); - - for b in tag.iter().copied() { - if cloned.peek_byte() == Some(b) { - cloned.forward(); - } else { - return None; - } - } - - Some(()) - } - - #[inline] - pub(crate) fn skip_eol(&mut self) { - while let Some(b) = self.peek_byte() { - if is_eol(b) { - self.forward(); - } else { - return; - } - } - } -} - -#[inline(always)] -pub(crate) fn is_whitespace(b: u8) -> bool { - matches!(b, 0x00 | 0x09 | 0x0a | 0x0c | 0x0d | 0x20) -} - -#[inline(always)] -pub(crate) fn is_delimiter(b: u8) -> bool { - matches!( - b, - b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%' - ) -} - -#[inline(always)] -pub(crate) fn is_regular(b: u8) -> bool { - !is_whitespace(b) && !is_delimiter(b) -} - -#[inline(always)] -pub(crate) fn is_eol(b: u8) -> bool { - matches!(b, 0x0a | 0x0d) -} diff --git a/vendor/hayro-postscript/src/string.rs b/vendor/hayro-postscript/src/string.rs deleted file mode 100644 index ed39d57c73..0000000000 --- a/vendor/hayro-postscript/src/string.rs +++ /dev/null @@ -1,288 +0,0 @@ -mod ascii_85; -pub(crate) mod ascii_hex; -mod literal; - -use alloc::vec::Vec; - -use crate::error::{Error, Result}; -use crate::reader::Reader; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum StringInner<'a> { - Literal(&'a [u8]), - Hex(&'a [u8]), - Ascii85(&'a [u8]), -} - -/// A PostScript string object. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct String<'a> { - inner: StringInner<'a>, -} - -impl<'a> String<'a> { - pub(crate) const fn from_literal(data: &'a [u8]) -> Self { - Self { - inner: StringInner::Literal(data), - } - } - - pub(crate) const fn from_hex(data: &'a [u8]) -> Self { - Self { - inner: StringInner::Hex(data), - } - } - - pub(crate) const fn from_ascii85(data: &'a [u8]) -> Self { - Self { - inner: StringInner::Ascii85(data), - } - } - - /// Decode the string content into `out`, replacing any previous contents. - pub fn decode_into(&self, out: &mut Vec) -> Result<()> { - out.clear(); - match self.inner { - StringInner::Literal(data) => literal::decode_into(data, out), - StringInner::Hex(data) => ascii_hex::decode_into(data, out), - StringInner::Ascii85(data) => ascii_85::decode_into(data, out), - } - .ok_or(Error::SyntaxError) - } - - /// Decode the string content. - pub fn decode(&self) -> Result> { - let mut out = Vec::new(); - self.decode_into(&mut out)?; - Ok(out) - } -} - -pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { - let start = r.offset(); - skip_literal(r)?; - let end = r.offset(); - // Exclude outer parentheses. - r.range(start + 1..end - 1) -} - -pub(crate) fn parse_hex<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { - r.forward_tag(b"<")?; - let start = r.offset(); - while let Some(b) = r.read_byte() { - if b == b'>' { - return r.range(start..r.offset() - 1); - } - } - None -} - -pub(crate) fn parse_ascii85<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { - r.forward_tag(b"<~")?; - let start = r.offset(); - loop { - let b = r.read_byte()?; - if b == b'~' { - let end = r.offset() - 1; - r.forward_tag(b">")?; - return r.range(start..end); - } - } -} - -fn skip_literal(r: &mut Reader<'_>) -> Option<()> { - r.forward_tag(b"(")?; - let mut depth = 1_u32; - - while depth > 0 { - let byte = r.read_byte()?; - match byte { - b'\\' => { - let _ = r.read_byte()?; - } - b'(' => depth += 1, - b')' => depth -= 1, - _ => {} - } - } - - Some(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn decode_literal(input: &[u8]) -> Result> { - let mut r = Reader::new(input); - let data = parse_literal(&mut r).ok_or(Error::SyntaxError)?; - String::from_literal(data).decode() - } - - #[test] - fn literal_empty() { - assert_eq!(decode_literal(b"()").unwrap(), b""); - } - - #[test] - fn literal_simple() { - assert_eq!(decode_literal(b"(Hello)").unwrap(), b"Hello"); - } - - #[test] - fn literal_nested_parens() { - assert_eq!( - decode_literal(b"(Hi (()) there)").unwrap(), - b"Hi (()) there" - ); - } - - #[test] - fn literal_escape_n() { - assert_eq!(decode_literal(b"(a\\nb)").unwrap(), b"a\nb"); - } - - #[test] - fn literal_escape_r() { - assert_eq!(decode_literal(b"(a\\rb)").unwrap(), b"a\rb"); - } - - #[test] - fn literal_escape_t() { - assert_eq!(decode_literal(b"(a\\tb)").unwrap(), b"a\tb"); - } - - #[test] - fn literal_escape_b() { - assert_eq!(decode_literal(b"(a\\bb)").unwrap(), &[b'a', 0x08, b'b']); - } - - #[test] - fn literal_escape_f() { - assert_eq!(decode_literal(b"(a\\fb)").unwrap(), &[b'a', 0x0C, b'b']); - } - - #[test] - fn literal_escape_backslash() { - assert_eq!(decode_literal(b"(a\\\\b)").unwrap(), b"a\\b"); - } - - #[test] - fn literal_escape_parens() { - assert_eq!(decode_literal(b"(Hi \\()").unwrap(), b"Hi ("); - } - - #[test] - fn literal_octal_three_digits() { - assert_eq!(decode_literal(b"(\\053)").unwrap(), b"+"); - } - - #[test] - fn literal_octal_two_digits() { - assert_eq!(decode_literal(b"(\\36)").unwrap(), b"\x1e"); - } - - #[test] - fn literal_octal_one_digit() { - assert_eq!(decode_literal(b"(\\3)").unwrap(), b"\x03"); - } - - #[test] - fn literal_line_continuation_lf() { - assert_eq!(decode_literal(b"(Hi \\\nthere)").unwrap(), b"Hi there"); - } - - #[test] - fn literal_line_continuation_cr() { - assert_eq!(decode_literal(b"(Hi \\\rthere)").unwrap(), b"Hi there"); - } - - #[test] - fn literal_line_continuation_crlf() { - assert_eq!(decode_literal(b"(Hi \\\r\nthere)").unwrap(), b"Hi there"); - } - - #[test] - fn literal_bare_eol_lf() { - assert_eq!(decode_literal(b"(a\nb)").unwrap(), b"a\nb"); - } - - #[test] - fn literal_bare_eol_cr() { - assert_eq!(decode_literal(b"(a\rb)").unwrap(), b"a\nb"); - } - - #[test] - fn literal_bare_eol_crlf() { - assert_eq!(decode_literal(b"(a\r\nb)").unwrap(), b"a\nb"); - } - - fn decode_hex(input: &[u8]) -> Result> { - let mut r = Reader::new(input); - let data = parse_hex(&mut r).ok_or(Error::SyntaxError)?; - String::from_hex(data).decode() - } - - #[test] - fn hex_simple() { - assert_eq!(decode_hex(b"<48656C6C6F>").unwrap(), b"Hello"); - } - - #[test] - fn hex_with_whitespace() { - assert_eq!(decode_hex(b"<48 65 6C 6C 6F>").unwrap(), b"Hello"); - } - - #[test] - fn hex_odd_nibble() { - assert_eq!(decode_hex(b"").unwrap(), &[0xAB, 0xC0]); - } - - #[test] - fn hex_empty() { - assert_eq!(decode_hex(b"<>").unwrap(), b""); - } - - #[test] - fn hex_lowercase() { - assert_eq!(decode_hex(b"").unwrap(), &[0xAB, 0xCD]); - } - - #[test] - fn hex_mixed_case() { - assert_eq!(decode_hex(b"").unwrap(), &[0xAB, 0x3E]); - } - - fn decode_a85(input: &[u8]) -> Result> { - let mut r = Reader::new(input); - let data = parse_ascii85(&mut r).ok_or(Error::SyntaxError)?; - String::from_ascii85(data).decode() - } - - #[test] - fn ascii85_simple() { - // "Hello" in ASCII85 is "87cURDZ" - assert_eq!(decode_a85(b"<~87cURDZ~>").unwrap(), b"Hello"); - } - - #[test] - fn ascii85_empty() { - assert_eq!(decode_a85(b"<~~>").unwrap(), b""); - } - - #[test] - fn ascii85_z_shorthand() { - assert_eq!(decode_a85(b"<~z~>").unwrap(), &[0, 0, 0, 0]); - } - - #[test] - fn ascii85_partial_group() { - let result = decode_a85(b"<~87~>").unwrap(); - assert_eq!(result.len(), 1); - } - - #[test] - fn ascii85_with_whitespace() { - assert_eq!(decode_a85(b"<~87cU RDZ~>").unwrap(), b"Hello"); - } -} diff --git a/vendor/hayro-postscript/src/string/ascii_85.rs b/vendor/hayro-postscript/src/string/ascii_85.rs deleted file mode 100644 index 93f7f50274..0000000000 --- a/vendor/hayro-postscript/src/string/ascii_85.rs +++ /dev/null @@ -1,90 +0,0 @@ -// Keep in sync with `hayro-syntax/src/filter/ascii_85.rs`. - -use crate::reader::{Reader, is_whitespace}; -use alloc::vec::Vec; - -pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { - const POW_85: [u32; 5] = [52200625, 614125, 7225, 85, 1]; - - let mut reader = Reader::new(data); - - let mut read_byte = || -> Option { - loop { - let b = reader.read_byte()?; - - // White space characters should be ignored. - if !is_whitespace(b) { - return Some(b); - } - } - }; - - let flush_group = |group: &mut Vec, decoded: &mut Vec| -> Option<()> { - let (digits, output_len): ([u32; 5], usize) = match group.len() { - 0 => return Some(()), - 1 => return None, // A single character is not valid. - 2 => ( - [group[0], group[1], b'u', b'u', b'u'].map(|b| (b - b'!') as u32), - 1, - ), - 3 => ( - [group[0], group[1], group[2], b'u', b'u'].map(|b| (b - b'!') as u32), - 2, - ), - 4 => ( - [group[0], group[1], group[2], group[3], b'u'].map(|b| (b - b'!') as u32), - 3, - ), - 5 => ( - [group[0], group[1], group[2], group[3], group[4]].map(|b| (b - b'!') as u32), - 4, - ), - _ => unreachable!(), - }; - - let value = digits[0] - .checked_mul(POW_85[0])? - .checked_add(digits[1].checked_mul(POW_85[1])?)? - .checked_add(digits[2].checked_mul(POW_85[2])?)? - .checked_add(digits[3].checked_mul(POW_85[3])?)? - .checked_add(digits[4])?; - - decoded.extend_from_slice(&value.to_be_bytes()[..output_len]); - group.clear(); - Some(()) - }; - - out.reserve(data.len() * 4 / 5); - let mut group = Vec::with_capacity(5); - - loop { - let Some(b) = read_byte() else { - // Be lenient and accept what we have (see PDFBOX-5910). - flush_group(&mut group, out)?; - - return Some(()); - }; - - match b { - b'!'..=b'u' => { - group.push(b); - - if group.len() == 5 { - flush_group(&mut group, out)?; - } - } - b'z' => { - flush_group(&mut group, out)?; - out.extend_from_slice(&[0, 0, 0, 0]); - } - b'~' => { - // Technically requires a '>', but there is a PDF where it isn't - // appended and decodes fine in other viewers. - flush_group(&mut group, out)?; - - return Some(()); - } - _ => return None, // Invalid character. - } - } -} diff --git a/vendor/hayro-postscript/src/string/ascii_hex.rs b/vendor/hayro-postscript/src/string/ascii_hex.rs deleted file mode 100644 index bdf74389f4..0000000000 --- a/vendor/hayro-postscript/src/string/ascii_hex.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Keep in sync with `hayro-syntax/src/filter/ascii_hex.rs`. - -use crate::reader::is_whitespace; -use alloc::vec::Vec; - -pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { - let has_whitespace = data.iter().any(|&b| is_whitespace(b)); - - out.reserve(data.len().div_ceil(2)); - - if !has_whitespace { - // Fast path, don't need to worry about white spaces. - let mut i = 0; - while i + 1 < data.len() { - out.push(decode_hex_digit(data[i])? << 4 | decode_hex_digit(data[i + 1])?); - i += 2; - } - if i < data.len() { - out.push(decode_hex_digit(data[i])? << 4); - } - } else { - // Slow path, need to strip white spaces. - let mut iter = data.iter().copied(); - let mut read_byte = || -> Option { - loop { - let b = iter.next()?; - if !is_whitespace(b) { - return Some(b); - } - } - }; - - loop { - match (read_byte(), read_byte()) { - (Some(hi), Some(lo)) => { - out.push(decode_hex_digit(hi)? << 4 | decode_hex_digit(lo)?); - } - (Some(hi), None) => { - out.push(decode_hex_digit(hi)? << 4); - - break; - } - (None, _) => break, - } - } - } - - Some(()) -} - -#[inline(always)] -pub(crate) fn decode_hex_digit(c: u8) -> Option { - match c { - b'0'..=b'9' => Some(c - b'0'), - b'A'..=b'F' => Some(c - b'A' + 10), - b'a'..=b'f' => Some(c - b'a' + 10), - _ => None, - } -} diff --git a/vendor/hayro-postscript/src/string/literal.rs b/vendor/hayro-postscript/src/string/literal.rs deleted file mode 100644 index 37a15934ff..0000000000 --- a/vendor/hayro-postscript/src/string/literal.rs +++ /dev/null @@ -1,85 +0,0 @@ -// Keep in sync with `hayro-syntax/src/object/string.rs` (`read_literal`). - -use alloc::vec::Vec; - -use crate::reader::Reader; - -pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { - let mut r = Reader::new(data); - - while let Some(byte) = r.read_byte() { - match byte { - b'\\' => { - let next = r.read_byte()?; - - if is_octal_digit(next) { - let second = r.read_byte(); - let third = r.read_byte(); - - let bytes = match (second, third) { - (Some(n1), Some(n2)) => match (is_octal_digit(n1), is_octal_digit(n2)) { - (true, true) => [next, n1, n2], - (true, _) => { - r.jump(r.offset() - 1); - [b'0', next, n1] - } - _ => { - r.jump(r.offset() - 2); - [b'0', b'0', next] - } - }, - (Some(n1), None) => { - if is_octal_digit(n1) { - [b'0', next, n1] - } else { - r.jump(r.offset() - 1); - [b'0', b'0', next] - } - } - _ => [b'0', b'0', next], - }; - - let str = core::str::from_utf8(&bytes).unwrap(); - - if let Ok(num) = u8::from_str_radix(str, 8) { - out.push(num); - } - } else { - match next { - b'n' => out.push(0xA), - b'r' => out.push(0xD), - b't' => out.push(0x9), - b'b' => out.push(0x8), - b'f' => out.push(0xC), - b'(' => out.push(b'('), - b')' => out.push(b')'), - b'\\' => out.push(b'\\'), - b'\n' | b'\r' => { - // "If the \ is followed immediately by a newline - // (CR, LF, or CR-LF pair), the scanner ignores - // both the initial \ and the newline; this breaks - // a string into multiple lines without including - // the newline character as part of the string." - r.skip_eol(); - } - _ => out.push(next), - } - } - } - b'(' | b')' => out.push(byte), - // "But if a newline appears without a preceding \, the result is - // equivalent to \n." - b'\n' | b'\r' => { - out.push(b'\n'); - r.skip_eol(); - } - other => out.push(other), - } - } - - Some(()) -} - -fn is_octal_digit(byte: u8) -> bool { - matches!(byte, b'0'..=b'7') -}