Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bf0bb1db5d | |||
| 0cba2be2b2 | |||
| 17db54fdbf | |||
| e46cbe3547 | |||
| 45f1d40c5b | |||
| 47576bd6e0 | |||
| 6efc835d24 | |||
| f1f0234ffb | |||
| fcc9840fdc | |||
| a400ff88a6 |
@@ -0,0 +1,19 @@
|
|||||||
|
# Pictor's core: every test, on the Windows runner (Fabrica on Mark's PC), in the background. pdfium is fetched by
|
||||||
|
# its pinned script; the optional hostile corpus too. LibreOffice, when installed, is used by the PDF-to-Word test.
|
||||||
|
name: test
|
||||||
|
on:
|
||||||
|
push: [main]
|
||||||
|
manual: true
|
||||||
|
runner: windows
|
||||||
|
env:
|
||||||
|
RUST_BACKTRACE: "1"
|
||||||
|
steps:
|
||||||
|
- id: pdfium
|
||||||
|
run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/fetch-pdfium.ps1
|
||||||
|
- id: corpus
|
||||||
|
run: powershell -NoProfile -ExecutionPolicy Bypass -File fixtures-fetch/fetch.ps1
|
||||||
|
- id: test
|
||||||
|
needs: [pdfium, corpus]
|
||||||
|
run: cargo test --workspace --release
|
||||||
|
- id: licences
|
||||||
|
run: node --test scripts/deps.test.mjs && node scripts/deps.mjs --check
|
||||||
Generated
+588
-1
@@ -43,6 +43,18 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "arrayref"
|
||||||
|
version = "0.3.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "arrayvec"
|
||||||
|
version = "0.7.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "autocfg"
|
name = "autocfg"
|
||||||
version = "1.5.1"
|
version = "1.5.1"
|
||||||
@@ -55,6 +67,12 @@ version = "0.22.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "base64"
|
||||||
|
version = "0.23.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bit-set"
|
name = "bit-set"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -143,6 +161,20 @@ name = "bytemuck"
|
|||||||
version = "1.25.2"
|
version = "1.25.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytemuck_derive"
|
||||||
|
version = "1.12.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.10",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "byteorder"
|
name = "byteorder"
|
||||||
@@ -271,6 +303,15 @@ version = "1.0.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
|
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "core_maths"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
|
||||||
|
dependencies = [
|
||||||
|
"libm",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpubits"
|
name = "cpubits"
|
||||||
version = "0.1.1"
|
version = "0.1.1"
|
||||||
@@ -310,6 +351,12 @@ dependencies = [
|
|||||||
"hybrid-array",
|
"hybrid-array",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "data-url"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "digest"
|
name = "digest"
|
||||||
version = "0.11.3"
|
version = "0.11.3"
|
||||||
@@ -321,6 +368,22 @@ dependencies = [
|
|||||||
"crypto-common",
|
"crypto-common",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "docx-rs"
|
||||||
|
version = "0.4.22"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7fdf00e8af6d0b3e92d4bbf9b76f773d8b84ea80f310324ad16cbdc2e653e02c"
|
||||||
|
dependencies = [
|
||||||
|
"base64 0.22.1",
|
||||||
|
"crc32fast",
|
||||||
|
"quick-xml",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"smallvec",
|
||||||
|
"thiserror",
|
||||||
|
"zip",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ecb"
|
name = "ecb"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
@@ -366,6 +429,15 @@ dependencies = [
|
|||||||
"windows-sys",
|
"windows-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "euclid"
|
||||||
|
version = "0.22.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
|
||||||
|
dependencies = [
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fastrand"
|
name = "fastrand"
|
||||||
version = "2.5.0"
|
version = "2.5.0"
|
||||||
@@ -404,6 +476,12 @@ dependencies = [
|
|||||||
"zlib-rs",
|
"zlib-rs",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "float-cmp"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fnv"
|
name = "fnv"
|
||||||
version = "1.0.7"
|
version = "1.0.7"
|
||||||
@@ -416,6 +494,46 @@ version = "0.2.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "font-types"
|
||||||
|
version = "0.11.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "font-types"
|
||||||
|
version = "0.12.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fontconfig-parser"
|
||||||
|
version = "0.5.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
|
||||||
|
dependencies = [
|
||||||
|
"roxmltree 0.20.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fontdb"
|
||||||
|
version = "0.24.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f"
|
||||||
|
dependencies = [
|
||||||
|
"fontconfig-parser",
|
||||||
|
"log",
|
||||||
|
"memmap2",
|
||||||
|
"slotmap",
|
||||||
|
"tinyvec",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "futures-core"
|
name = "futures-core"
|
||||||
version = "0.3.34"
|
version = "0.3.34"
|
||||||
@@ -501,6 +619,19 @@ dependencies = [
|
|||||||
"zerocopy",
|
"zerocopy",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "harfrust"
|
||||||
|
version = "0.15.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "865dcc4105d51c323d8fedbb2d75b5e9c8ecddf5613f74c82f851d0afbc97114"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"bytemuck",
|
||||||
|
"read-fonts 0.46.0",
|
||||||
|
"smallvec",
|
||||||
|
"yoke",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.17.1"
|
version = "0.17.1"
|
||||||
@@ -572,6 +703,12 @@ dependencies = [
|
|||||||
"quick-error 2.0.1",
|
"quick-error 2.0.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "imagesize"
|
||||||
|
version = "0.15.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "img-parts"
|
name = "img-parts"
|
||||||
version = "0.4.2"
|
version = "0.4.2"
|
||||||
@@ -638,6 +775,18 @@ dependencies = [
|
|||||||
"mutate_once",
|
"mutate_once",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "kurbo"
|
||||||
|
version = "0.13.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
|
||||||
|
dependencies = [
|
||||||
|
"arrayvec",
|
||||||
|
"euclid",
|
||||||
|
"polycool",
|
||||||
|
"smallvec",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
version = "0.2.191"
|
version = "0.2.191"
|
||||||
@@ -654,6 +803,12 @@ dependencies = [
|
|||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libm"
|
||||||
|
version = "0.2.16"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "linux-raw-sys"
|
name = "linux-raw-sys"
|
||||||
version = "0.12.1"
|
version = "0.12.1"
|
||||||
@@ -724,6 +879,15 @@ version = "2.8.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "memmap2"
|
||||||
|
version = "0.9.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "miniz_oxide"
|
name = "miniz_oxide"
|
||||||
version = "0.8.9"
|
version = "0.8.9"
|
||||||
@@ -791,6 +955,18 @@ version = "1.21.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pdf-writer"
|
||||||
|
version = "0.15.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"itoa",
|
||||||
|
"memchr",
|
||||||
|
"ryu",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pdfium-render"
|
name = "pdfium-render"
|
||||||
version = "0.9.5"
|
version = "0.9.5"
|
||||||
@@ -817,6 +993,36 @@ dependencies = [
|
|||||||
"web-sys",
|
"web-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pico-args"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pictor-doc"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"base64 0.22.1",
|
||||||
|
"flate2",
|
||||||
|
"fontdb",
|
||||||
|
"image",
|
||||||
|
"pdf-writer",
|
||||||
|
"pictor-pdf",
|
||||||
|
"proptest",
|
||||||
|
"rustybuzz",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
|
"subsetter",
|
||||||
|
"tempfile",
|
||||||
|
"thiserror",
|
||||||
|
"tiny-skia",
|
||||||
|
"ttf-parser",
|
||||||
|
"usvg",
|
||||||
|
"zip",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pictor-meta"
|
name = "pictor-meta"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -833,6 +1039,7 @@ dependencies = [
|
|||||||
name = "pictor-pdf"
|
name = "pictor-pdf"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"docx-rs",
|
||||||
"flate2",
|
"flate2",
|
||||||
"getrandom",
|
"getrandom",
|
||||||
"image",
|
"image",
|
||||||
@@ -841,7 +1048,9 @@ dependencies = [
|
|||||||
"pictor-meta",
|
"pictor-meta",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"tempfile",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -879,10 +1088,11 @@ dependencies = [
|
|||||||
name = "pictor-worker"
|
name = "pictor-worker"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64",
|
"base64 0.22.1",
|
||||||
"flate2",
|
"flate2",
|
||||||
"image",
|
"image",
|
||||||
"lopdf",
|
"lopdf",
|
||||||
|
"pictor-doc",
|
||||||
"pictor-meta",
|
"pictor-meta",
|
||||||
"pictor-pdf",
|
"pictor-pdf",
|
||||||
"pictor-qr",
|
"pictor-qr",
|
||||||
@@ -893,6 +1103,7 @@ dependencies = [
|
|||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
"windows",
|
"windows",
|
||||||
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -920,6 +1131,15 @@ dependencies = [
|
|||||||
"miniz_oxide 0.8.9",
|
"miniz_oxide 0.8.9",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "polycool"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"
|
||||||
|
dependencies = [
|
||||||
|
"arrayvec",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "proc-macro-crate"
|
name = "proc-macro-crate"
|
||||||
version = "3.5.0"
|
version = "3.5.0"
|
||||||
@@ -982,6 +1202,16 @@ version = "2.0.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quick-xml"
|
||||||
|
version = "0.41.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
|
||||||
|
dependencies = [
|
||||||
|
"encoding_rs",
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quote"
|
name = "quote"
|
||||||
version = "1.0.47"
|
version = "1.0.47"
|
||||||
@@ -1029,12 +1259,51 @@ version = "1.8.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"
|
checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "read-fonts"
|
||||||
|
version = "0.39.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
"font-types 0.11.3",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "read-fonts"
|
||||||
|
version = "0.46.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bdaa4fffe9ff3ca2c353fa9729792805b9b3e324695ff5a081f860612e81b330"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
"foldhash",
|
||||||
|
"font-types 0.12.7",
|
||||||
|
"once_cell",
|
||||||
|
"smallvec",
|
||||||
|
"yoke",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "regex-syntax"
|
name = "regex-syntax"
|
||||||
version = "0.8.11"
|
version = "0.8.11"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "roxmltree"
|
||||||
|
version = "0.20.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "roxmltree"
|
||||||
|
version = "0.21.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rqrr"
|
name = "rqrr"
|
||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
@@ -1046,6 +1315,12 @@ dependencies = [
|
|||||||
"lru",
|
"lru",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustc-hash"
|
||||||
|
version = "2.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustix"
|
name = "rustix"
|
||||||
version = "1.1.6"
|
version = "1.1.6"
|
||||||
@@ -1077,6 +1352,30 @@ dependencies = [
|
|||||||
"wait-timeout",
|
"wait-timeout",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustybuzz"
|
||||||
|
version = "0.20.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"bytemuck",
|
||||||
|
"core_maths",
|
||||||
|
"log",
|
||||||
|
"smallvec",
|
||||||
|
"ttf-parser",
|
||||||
|
"unicode-bidi-mirroring",
|
||||||
|
"unicode-ccc",
|
||||||
|
"unicode-properties",
|
||||||
|
"unicode-script",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ryu"
|
||||||
|
version = "1.0.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "scopeguard"
|
name = "scopeguard"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
@@ -1155,12 +1454,80 @@ version = "0.1.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
|
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "simplecss"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "siphasher"
|
||||||
|
version = "1.0.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "skrifa"
|
||||||
|
version = "0.42.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
"read-fonts 0.39.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "skrifa"
|
||||||
|
version = "0.49.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a7459fb60888ad9a5f367dd293fa2fb9df142cb451aa6bfd6cd66a7d6a9b739d"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
"once_cell",
|
||||||
|
"read-fonts 0.46.0",
|
||||||
|
"smallvec",
|
||||||
|
"yoke",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "slab"
|
name = "slab"
|
||||||
version = "0.4.12"
|
version = "0.4.12"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "slotmap"
|
||||||
|
version = "1.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
|
||||||
|
dependencies = [
|
||||||
|
"version_check",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "smallvec"
|
||||||
|
version = "1.16.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "stable_deref_trait"
|
||||||
|
version = "1.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "strict-num"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
|
||||||
|
dependencies = [
|
||||||
|
"float-cmp",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "stringprep"
|
name = "stringprep"
|
||||||
version = "0.1.5"
|
version = "0.1.5"
|
||||||
@@ -1172,6 +1539,28 @@ dependencies = [
|
|||||||
"unicode-properties",
|
"unicode-properties",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "subsetter"
|
||||||
|
version = "0.2.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
|
||||||
|
dependencies = [
|
||||||
|
"kurbo",
|
||||||
|
"rustc-hash",
|
||||||
|
"skrifa 0.42.1",
|
||||||
|
"write-fonts",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "svgtypes"
|
||||||
|
version = "0.16.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e"
|
||||||
|
dependencies = [
|
||||||
|
"kurbo",
|
||||||
|
"siphasher",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "2.0.119"
|
version = "2.0.119"
|
||||||
@@ -1194,6 +1583,17 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "synstructure"
|
||||||
|
version = "0.14.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.10",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tempfile"
|
name = "tempfile"
|
||||||
version = "3.27.0"
|
version = "3.27.0"
|
||||||
@@ -1241,6 +1641,32 @@ dependencies = [
|
|||||||
"zune-jpeg",
|
"zune-jpeg",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tiny-skia"
|
||||||
|
version = "0.12.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
|
||||||
|
dependencies = [
|
||||||
|
"arrayref",
|
||||||
|
"arrayvec",
|
||||||
|
"bytemuck",
|
||||||
|
"cfg-if",
|
||||||
|
"log",
|
||||||
|
"png",
|
||||||
|
"tiny-skia-path",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tiny-skia-path"
|
||||||
|
version = "0.12.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
|
||||||
|
dependencies = [
|
||||||
|
"arrayref",
|
||||||
|
"bytemuck",
|
||||||
|
"strict-num",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tinyvec"
|
name = "tinyvec"
|
||||||
version = "1.13.3"
|
version = "1.13.3"
|
||||||
@@ -1286,6 +1712,21 @@ dependencies = [
|
|||||||
"winnow",
|
"winnow",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ttf-parser"
|
||||||
|
version = "0.25.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
|
||||||
|
dependencies = [
|
||||||
|
"core_maths",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "typed-path"
|
||||||
|
version = "0.12.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.20.1"
|
version = "1.20.1"
|
||||||
@@ -1304,6 +1745,18 @@ version = "0.3.18"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
|
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-bidi-mirroring"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-ccc"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.27"
|
version = "1.0.27"
|
||||||
@@ -1325,6 +1778,45 @@ version = "0.1.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"
|
checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-script"
|
||||||
|
version = "0.5.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-vo"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "usvg"
|
||||||
|
version = "0.50.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bdb896f04730b97805bbc3191fc57e4bf03face0f14577dd42e783c4d8c98802"
|
||||||
|
dependencies = [
|
||||||
|
"base64 0.23.1",
|
||||||
|
"data-url",
|
||||||
|
"fontdb",
|
||||||
|
"harfrust",
|
||||||
|
"imagesize",
|
||||||
|
"kurbo",
|
||||||
|
"log",
|
||||||
|
"pico-args",
|
||||||
|
"roxmltree 0.21.2",
|
||||||
|
"simplecss",
|
||||||
|
"siphasher",
|
||||||
|
"skrifa 0.49.0",
|
||||||
|
"strict-num",
|
||||||
|
"svgtypes",
|
||||||
|
"tiny-skia-path",
|
||||||
|
"unicode-bidi",
|
||||||
|
"unicode-script",
|
||||||
|
"unicode-vo",
|
||||||
|
"xmlwriter",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "utf16string"
|
name = "utf16string"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
@@ -1343,6 +1835,12 @@ dependencies = [
|
|||||||
"piston-float",
|
"piston-float",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "version_check"
|
||||||
|
version = "0.9.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wait-timeout"
|
name = "wait-timeout"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
@@ -1557,6 +2055,48 @@ dependencies = [
|
|||||||
"memchr",
|
"memchr",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "write-fonts"
|
||||||
|
version = "0.48.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
|
||||||
|
dependencies = [
|
||||||
|
"font-types 0.11.3",
|
||||||
|
"indexmap",
|
||||||
|
"kurbo",
|
||||||
|
"log",
|
||||||
|
"read-fonts 0.39.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "xmlwriter"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "yoke"
|
||||||
|
version = "0.8.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"
|
||||||
|
dependencies = [
|
||||||
|
"stable_deref_trait",
|
||||||
|
"yoke-derive",
|
||||||
|
"zerofrom",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "yoke-derive"
|
||||||
|
version = "0.8.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.10",
|
||||||
|
"synstructure",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zerocopy"
|
name = "zerocopy"
|
||||||
version = "0.8.63"
|
version = "0.8.63"
|
||||||
@@ -1577,6 +2117,41 @@ dependencies = [
|
|||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerofrom"
|
||||||
|
version = "0.1.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
|
||||||
|
dependencies = [
|
||||||
|
"zerofrom-derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerofrom-derive"
|
||||||
|
version = "0.1.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.10",
|
||||||
|
"synstructure",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zip"
|
||||||
|
version = "8.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
|
||||||
|
dependencies = [
|
||||||
|
"crc32fast",
|
||||||
|
"flate2",
|
||||||
|
"indexmap",
|
||||||
|
"memchr",
|
||||||
|
"typed-path",
|
||||||
|
"zopfli",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zlib-rs"
|
name = "zlib-rs"
|
||||||
version = "0.6.8"
|
version = "0.6.8"
|
||||||
@@ -1589,6 +2164,18 @@ version = "1.0.23"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zopfli"
|
||||||
|
version = "0.8.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
|
||||||
|
dependencies = [
|
||||||
|
"bumpalo",
|
||||||
|
"crc32fast",
|
||||||
|
"log",
|
||||||
|
"simd-adler32",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zune-core"
|
name = "zune-core"
|
||||||
version = "0.5.3"
|
version = "0.5.3"
|
||||||
|
|||||||
+3
-1
@@ -1,6 +1,6 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
members = ["crates/raster", "crates/pdf", "crates/meta", "crates/qr", "crates/save", "crates/worker"]
|
members = ["crates/raster", "crates/pdf", "crates/meta", "crates/qr", "crates/save", "crates/doc", "crates/worker"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -16,6 +16,7 @@ pictor-pdf = { path = "crates/pdf" }
|
|||||||
pictor-meta = { path = "crates/meta" }
|
pictor-meta = { path = "crates/meta" }
|
||||||
pictor-qr = { path = "crates/qr" }
|
pictor-qr = { path = "crates/qr" }
|
||||||
pictor-save = { path = "crates/save" }
|
pictor-save = { path = "crates/save" }
|
||||||
|
pictor-doc = { path = "crates/doc" }
|
||||||
|
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
@@ -30,6 +31,7 @@ pdfium-render = { version = "0.9.5", default-features = false, features = ["thre
|
|||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
sha2 = "0.11"
|
sha2 = "0.11"
|
||||||
getrandom = "0.4"
|
getrandom = "0.4"
|
||||||
|
docx-rs = { version = "0.4.22", default-features = false }
|
||||||
flate2 = "1"
|
flate2 = "1"
|
||||||
windows = "0.62"
|
windows = "0.62"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
[package]
|
||||||
|
name = "pictor-doc"
|
||||||
|
description = "Pictor's document model: pages, layers, vector objects and bitmaps; operations with exact undo; the .pictor format; text, rendering and export"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
thiserror.workspace = true
|
||||||
|
serde = { workspace = true, features = ["rc"] }
|
||||||
|
serde_json.workspace = true
|
||||||
|
base64.workspace = true
|
||||||
|
image.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
|
tiny-skia = "0.12"
|
||||||
|
usvg = { version = "0.50", default-features = false, features = ["text", "system-fonts", "memmap-fonts"] }
|
||||||
|
fontdb = { version = "0.24", default-features = false, features = ["fs", "memmap"] }
|
||||||
|
rustybuzz = "0.20"
|
||||||
|
ttf-parser = "0.25"
|
||||||
|
pdf-writer = "0.15"
|
||||||
|
subsetter = "0.2"
|
||||||
|
flate2.workspace = true
|
||||||
|
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
proptest.workspace = true
|
||||||
|
pictor-pdf.workspace = true
|
||||||
|
tempfile.workspace = true
|
||||||
@@ -0,0 +1,697 @@
|
|||||||
|
//! Pixel tools on a bitmap layer's raster: brush, pencil, eraser, fill bucket, magic wand, rectangle and lasso
|
||||||
|
//! selections, delete and copy, adjustments, blur, sharpen, invert, clone stamp, and applying a matte (background
|
||||||
|
//! removal). Each returns the rectangle it changed, so the caller can record one exact undo patch.
|
||||||
|
use crate::model::{Document, PixelRect, Raster};
|
||||||
|
use crate::ops::Op;
|
||||||
|
|
||||||
|
/// A selection: one coverage byte per pixel of the raster it belongs to.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Mask {
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub data: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mask {
|
||||||
|
pub fn empty(width: u32, height: u32) -> Mask {
|
||||||
|
Mask { width, height, data: vec![0; width as usize * height as usize] }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rect(width: u32, height: u32, r: PixelRect) -> Mask {
|
||||||
|
let mut m = Mask::empty(width, height);
|
||||||
|
let r = r.clamp(width, height);
|
||||||
|
for y in r.y..r.y + r.h {
|
||||||
|
let row = y as usize * width as usize;
|
||||||
|
m.data[row + r.x as usize..row + (r.x + r.w) as usize].fill(255);
|
||||||
|
}
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A polygon (lasso), anti-aliased at its edge.
|
||||||
|
pub fn polygon(width: u32, height: u32, points: &[(f32, f32)]) -> Mask {
|
||||||
|
let mut m = Mask::empty(width, height);
|
||||||
|
if points.len() < 3 {
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
let mut pb = tiny_skia::PathBuilder::new();
|
||||||
|
pb.move_to(points[0].0, points[0].1);
|
||||||
|
for p in &points[1..] {
|
||||||
|
pb.line_to(p.0, p.1);
|
||||||
|
}
|
||||||
|
pb.close();
|
||||||
|
let (Some(path), Some(mut sm)) = (pb.finish(), tiny_skia::Mask::new(width, height)) else { return m };
|
||||||
|
sm.fill_path(&path, tiny_skia::FillRule::EvenOdd, true, tiny_skia::Transform::identity());
|
||||||
|
m.data.copy_from_slice(sm.data());
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, x: u32, y: u32) -> u8 {
|
||||||
|
self.data[y as usize * self.width as usize + x as usize]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.data.iter().all(|v| *v == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bbox(&self) -> PixelRect {
|
||||||
|
let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0);
|
||||||
|
for y in 0..self.height {
|
||||||
|
for x in 0..self.width {
|
||||||
|
if self.get(x, y) > 0 {
|
||||||
|
x0 = x0.min(x);
|
||||||
|
y0 = y0.min(y);
|
||||||
|
x1 = x1.max(x + 1);
|
||||||
|
y1 = y1.max(y + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if x0 == u32::MAX {
|
||||||
|
PixelRect { x: 0, y: 0, w: 0, h: 0 }
|
||||||
|
} else {
|
||||||
|
PixelRect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn invert(&mut self) {
|
||||||
|
for v in &mut self.data {
|
||||||
|
*v = 255 - *v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The selection's edge as path data (pixel edges between inside and outside), for the marching ants.
|
||||||
|
pub fn outline(&self) -> String {
|
||||||
|
use std::fmt::Write;
|
||||||
|
let inside = |x: i64, y: i64| {
|
||||||
|
x >= 0 && y >= 0 && x < self.width as i64 && y < self.height as i64 && self.get(x as u32, y as u32) >= 128
|
||||||
|
};
|
||||||
|
let mut d = String::new();
|
||||||
|
// Horizontal edges, merged along each row.
|
||||||
|
for y in 0..=self.height as i64 {
|
||||||
|
let mut start: Option<i64> = None;
|
||||||
|
for x in 0..=self.width as i64 {
|
||||||
|
let edge = x < self.width as i64 && inside(x, y) != inside(x, y - 1);
|
||||||
|
match (edge, start) {
|
||||||
|
(true, None) => start = Some(x),
|
||||||
|
(false, Some(s)) => {
|
||||||
|
let _ = write!(d, "M{s} {y}H{x}");
|
||||||
|
start = None;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for x in 0..=self.width as i64 {
|
||||||
|
let mut start: Option<i64> = None;
|
||||||
|
for y in 0..=self.height as i64 {
|
||||||
|
let edge = y < self.height as i64 && inside(x, y) != inside(x - 1, y);
|
||||||
|
match (edge, start) {
|
||||||
|
(true, None) => start = Some(y),
|
||||||
|
(false, Some(s)) => {
|
||||||
|
let _ = write!(d, "M{x} {s}V{y}");
|
||||||
|
start = None;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sel(mask: Option<&Mask>, x: u32, y: u32) -> f32 {
|
||||||
|
mask.map(|m| m.get(x, y) as f32 / 255.0).unwrap_or(1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Source-over in straight alpha: `src` (straight RGBA) with extra coverage `cov` onto `dst`.
|
||||||
|
fn blend(dst: &mut [u8], src: [u8; 4], cov: f32) {
|
||||||
|
let sa = src[3] as f32 / 255.0 * cov;
|
||||||
|
if sa <= 0.0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let da = dst[3] as f32 / 255.0;
|
||||||
|
let oa = sa + da * (1.0 - sa);
|
||||||
|
if oa <= 0.0 {
|
||||||
|
dst.copy_from_slice(&[0, 0, 0, 0]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for i in 0..3 {
|
||||||
|
let v = (src[i] as f32 * sa + dst[i] as f32 * da * (1.0 - sa)) / oa;
|
||||||
|
dst[i] = v.round().clamp(0.0, 255.0) as u8;
|
||||||
|
}
|
||||||
|
dst[3] = (oa * 255.0).round().clamp(0.0, 255.0) as u8;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct Brush {
|
||||||
|
/// Radius in pixels at full pressure.
|
||||||
|
pub radius: f32,
|
||||||
|
/// 0 = soft to the centre, 1 = a hard edge.
|
||||||
|
pub hardness: f32,
|
||||||
|
pub color: [u8; 4],
|
||||||
|
/// 0..1 for the whole stroke (a stroke never builds up over itself).
|
||||||
|
pub opacity: f32,
|
||||||
|
pub erase: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stroke coverage (0..1) over a rectangle: dabs along the points, the maximum where they overlap.
|
||||||
|
struct Coverage {
|
||||||
|
rect: PixelRect,
|
||||||
|
cov: Vec<f32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn coverage(width: u32, height: u32, points: &[(f32, f32, f32)], radius: f32, hardness: f32) -> Coverage {
|
||||||
|
let r = radius.max(0.5);
|
||||||
|
let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
|
||||||
|
for (x, y, _) in points {
|
||||||
|
x0 = x0.min(x - r - 1.0);
|
||||||
|
y0 = y0.min(y - r - 1.0);
|
||||||
|
x1 = x1.max(x + r + 1.0);
|
||||||
|
y1 = y1.max(y + r + 1.0);
|
||||||
|
}
|
||||||
|
let rect = PixelRect {
|
||||||
|
x: x0.max(0.0) as u32,
|
||||||
|
y: y0.max(0.0) as u32,
|
||||||
|
w: (x1.min(width as f32).max(0.0) - x0.max(0.0)).max(0.0).ceil() as u32,
|
||||||
|
h: (y1.min(height as f32).max(0.0) - y0.max(0.0)).max(0.0).ceil() as u32,
|
||||||
|
}
|
||||||
|
.clamp(width, height);
|
||||||
|
let mut cov = vec![0f32; rect.w as usize * rect.h as usize];
|
||||||
|
let hard = hardness.clamp(0.0, 0.99);
|
||||||
|
let mut dab = |cx: f32, cy: f32, pr: f32| {
|
||||||
|
let rr = (r * pr.clamp(0.05, 1.0)).max(0.5);
|
||||||
|
let bx0 = ((cx - rr - 1.0).floor().max(rect.x as f32)) as u32;
|
||||||
|
let by0 = ((cy - rr - 1.0).floor().max(rect.y as f32)) as u32;
|
||||||
|
let bx1 = ((cx + rr + 1.0).ceil().min((rect.x + rect.w) as f32)) as u32;
|
||||||
|
let by1 = ((cy + rr + 1.0).ceil().min((rect.y + rect.h) as f32)) as u32;
|
||||||
|
for y in by0..by1 {
|
||||||
|
for x in bx0..bx1 {
|
||||||
|
let d = (((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt()) / rr;
|
||||||
|
// A hard core, then a smooth fall to the edge; half a pixel of anti-aliasing at any size.
|
||||||
|
let edge = 1.0 - (d * rr - rr + 0.5).clamp(0.0, 1.0);
|
||||||
|
let a = if d <= hard {
|
||||||
|
edge
|
||||||
|
} else {
|
||||||
|
let t = ((d - hard) / (1.0 - hard)).clamp(0.0, 1.0);
|
||||||
|
(1.0 - t * t * (3.0 - 2.0 * t)).min(edge)
|
||||||
|
};
|
||||||
|
let i = (y - rect.y) as usize * rect.w as usize + (x - rect.x) as usize;
|
||||||
|
if a > cov[i] {
|
||||||
|
cov[i] = a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(&(x, y, p)) = points.first() {
|
||||||
|
dab(x, y, p);
|
||||||
|
}
|
||||||
|
for w in points.windows(2) {
|
||||||
|
let (ax, ay, ap) = w[0];
|
||||||
|
let (bx, by, bp) = w[1];
|
||||||
|
let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt();
|
||||||
|
let step = (r * ap.min(bp).clamp(0.05, 1.0) * 0.25).max(0.5);
|
||||||
|
let n = (len / step).ceil().max(1.0) as usize;
|
||||||
|
for i in 1..=n {
|
||||||
|
let t = i as f32 / n as f32;
|
||||||
|
dab(ax + (bx - ax) * t, ay + (by - ay) * t, ap + (bp - ap) * t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Coverage { rect, cov }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Brush or eraser along `points` (x, y, pressure 0..1).
|
||||||
|
pub fn brush(r: &mut Raster, points: &[(f32, f32, f32)], b: &Brush, mask: Option<&Mask>) -> PixelRect {
|
||||||
|
if points.is_empty() {
|
||||||
|
return PixelRect { x: 0, y: 0, w: 0, h: 0 };
|
||||||
|
}
|
||||||
|
let c = coverage(r.width, r.height, points, b.radius, b.hardness);
|
||||||
|
for y in 0..c.rect.h {
|
||||||
|
for x in 0..c.rect.w {
|
||||||
|
let (px, py) = (c.rect.x + x, c.rect.y + y);
|
||||||
|
let k = c.cov[(y * c.rect.w + x) as usize] * b.opacity.clamp(0.0, 1.0) * sel(mask, px, py);
|
||||||
|
if k <= 0.0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let i = (py as usize * r.width as usize + px as usize) * 4;
|
||||||
|
let dst = &mut r.rgba[i..i + 4];
|
||||||
|
if b.erase {
|
||||||
|
let a = dst[3] as f32 * (1.0 - k * b.color[3] as f32 / 255.0);
|
||||||
|
dst[3] = a.round() as u8;
|
||||||
|
} else {
|
||||||
|
blend(dst, b.color, k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.rect
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pencil: hard square pixels of `size` along the points, no anti-aliasing.
|
||||||
|
pub fn pencil(
|
||||||
|
r: &mut Raster,
|
||||||
|
points: &[(f32, f32)],
|
||||||
|
size: u32,
|
||||||
|
color: [u8; 4],
|
||||||
|
erase: bool,
|
||||||
|
mask: Option<&Mask>,
|
||||||
|
) -> PixelRect {
|
||||||
|
let mut dirty = PixelRect { x: 0, y: 0, w: 0, h: 0 };
|
||||||
|
let s = size.max(1) as i64;
|
||||||
|
let mut put = |x: i64, y: i64, r: &mut Raster| {
|
||||||
|
let x0 = x - (s - 1) / 2;
|
||||||
|
let y0 = y - (s - 1) / 2;
|
||||||
|
for yy in y0..y0 + s {
|
||||||
|
for xx in x0..x0 + s {
|
||||||
|
if xx < 0 || yy < 0 || xx >= r.width as i64 || yy >= r.height as i64 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let k = sel(mask, xx as u32, yy as u32);
|
||||||
|
if k <= 0.0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let i = (yy as usize * r.width as usize + xx as usize) * 4;
|
||||||
|
if erase {
|
||||||
|
r.rgba[i + 3] = (r.rgba[i + 3] as f32 * (1.0 - k)).round() as u8;
|
||||||
|
} else if k >= 1.0 {
|
||||||
|
r.rgba[i..i + 4].copy_from_slice(&color);
|
||||||
|
} else {
|
||||||
|
blend(&mut r.rgba[i..i + 4], color, k);
|
||||||
|
}
|
||||||
|
dirty = dirty.union(PixelRect { x: xx as u32, y: yy as u32, w: 1, h: 1 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let pts: Vec<(i64, i64)> = points.iter().map(|(x, y)| (x.floor() as i64, y.floor() as i64)).collect();
|
||||||
|
if let Some(&(x, y)) = pts.first() {
|
||||||
|
put(x, y, r);
|
||||||
|
}
|
||||||
|
for w in pts.windows(2) {
|
||||||
|
// Bresenham.
|
||||||
|
let (mut x0, mut y0) = w[0];
|
||||||
|
let (x1, y1) = w[1];
|
||||||
|
let (dx, dy) = ((x1 - x0).abs(), -(y1 - y0).abs());
|
||||||
|
let (sx, sy) = (if x0 < x1 { 1 } else { -1 }, if y0 < y1 { 1 } else { -1 });
|
||||||
|
let mut err = dx + dy;
|
||||||
|
loop {
|
||||||
|
put(x0, y0, r);
|
||||||
|
if x0 == x1 && y0 == y1 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let e2 = 2 * err;
|
||||||
|
if e2 >= dy {
|
||||||
|
err += dy;
|
||||||
|
x0 += sx;
|
||||||
|
}
|
||||||
|
if e2 <= dx {
|
||||||
|
err += dx;
|
||||||
|
y0 += sy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dirty
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a pixel belongs with the seed: transparent with transparent (by alpha), visible with visible by colour
|
||||||
|
/// alone, so a stroke's soft, half-transparent edge goes with the stroke.
|
||||||
|
fn close(a: &[u8], b: [u8; 4], tol: u8) -> bool {
|
||||||
|
if b[3] == 0 {
|
||||||
|
return a[3] <= tol;
|
||||||
|
}
|
||||||
|
if a[3] == 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
(0..3).all(|i| (a[i] as i16 - b[i] as i16).unsigned_abs() <= tol as u16)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The region around (x, y) whose pixels are within `tol` of its colour (4-connected).
|
||||||
|
pub fn region(r: &Raster, x: u32, y: u32, tol: u8) -> Mask {
|
||||||
|
let mut m = Mask::empty(r.width, r.height);
|
||||||
|
if x >= r.width || y >= r.height {
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
let seed = r.pixel(x, y);
|
||||||
|
let w = r.width as usize;
|
||||||
|
let mut stack = vec![(x, y)];
|
||||||
|
while let Some((sx, sy)) = stack.pop() {
|
||||||
|
// Scanline fill: walk left and right, then queue the rows above and below.
|
||||||
|
let row = sy as usize * w;
|
||||||
|
if m.data[row + sx as usize] != 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let px = |xx: u32| &r.rgba[(row + xx as usize) * 4..(row + xx as usize) * 4 + 4];
|
||||||
|
let mut l = sx;
|
||||||
|
while l > 0 && m.data[row + l as usize - 1] == 0 && close(px(l - 1), seed, tol) {
|
||||||
|
l -= 1;
|
||||||
|
}
|
||||||
|
let mut rr = sx;
|
||||||
|
while rr + 1 < r.width && m.data[row + rr as usize + 1] == 0 && close(px(rr + 1), seed, tol) {
|
||||||
|
rr += 1;
|
||||||
|
}
|
||||||
|
for xx in l..=rr {
|
||||||
|
m.data[row + xx as usize] = 255;
|
||||||
|
}
|
||||||
|
for ny in [sy.wrapping_sub(1), sy + 1] {
|
||||||
|
if ny >= r.height {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let nrow = ny as usize * w;
|
||||||
|
let mut xx = l;
|
||||||
|
while xx <= rr {
|
||||||
|
let i = nrow + xx as usize;
|
||||||
|
if m.data[i] == 0 && close(&r.rgba[i * 4..i * 4 + 4], seed, tol) {
|
||||||
|
stack.push((xx, ny));
|
||||||
|
// Skip the rest of this run; it is filled from the pushed seed.
|
||||||
|
while xx <= rr && close(&r.rgba[(nrow + xx as usize) * 4..(nrow + xx as usize) * 4 + 4], seed, tol)
|
||||||
|
{
|
||||||
|
xx += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
xx += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fill bucket: the region around (x, y) becomes `color` (inside the selection, if any).
|
||||||
|
pub fn fill(r: &mut Raster, x: u32, y: u32, tol: u8, color: [u8; 4], mask: Option<&Mask>) -> PixelRect {
|
||||||
|
let reg = region(r, x, y, tol);
|
||||||
|
let b = reg.bbox();
|
||||||
|
for yy in b.y..b.y + b.h {
|
||||||
|
for xx in b.x..b.x + b.w {
|
||||||
|
if reg.get(xx, yy) == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let k = sel(mask, xx, yy);
|
||||||
|
let i = (yy as usize * r.width as usize + xx as usize) * 4;
|
||||||
|
if k >= 1.0 {
|
||||||
|
r.rgba[i..i + 4].copy_from_slice(&color);
|
||||||
|
} else if k > 0.0 {
|
||||||
|
let old: [u8; 4] = r.rgba[i..i + 4].try_into().unwrap();
|
||||||
|
for c in 0..4 {
|
||||||
|
r.rgba[i + c] = (old[c] as f32 + (color[c] as f32 - old[c] as f32) * k).round() as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete: the selected pixels (or all) become transparent.
|
||||||
|
pub fn clear(r: &mut Raster, mask: Option<&Mask>) -> PixelRect {
|
||||||
|
let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: r.width, h: r.height });
|
||||||
|
for y in b.y..b.y + b.h {
|
||||||
|
for x in b.x..b.x + b.w {
|
||||||
|
let k = sel(mask, x, y);
|
||||||
|
let i = (y as usize * r.width as usize + x as usize) * 4 + 3;
|
||||||
|
r.rgba[i] = (r.rgba[i] as f32 * (1.0 - k)).round() as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy: the selected pixels (alpha × selection) in their bounding box, and where that box is.
|
||||||
|
pub fn copy(r: &Raster, mask: Option<&Mask>) -> (Raster, PixelRect) {
|
||||||
|
let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: r.width, h: r.height });
|
||||||
|
let mut out = r.crop(b);
|
||||||
|
if let Some(m) = mask {
|
||||||
|
for y in 0..b.h {
|
||||||
|
for x in 0..b.w {
|
||||||
|
let i = (y as usize * b.w as usize + x as usize) * 4 + 3;
|
||||||
|
out.rgba[i] = (out.rgba[i] as u32 * m.get(b.x + x, b.y + y) as u32 / 255) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(out, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
|
pub enum Adjust {
|
||||||
|
/// −100..100.
|
||||||
|
Brightness {
|
||||||
|
amount: f32,
|
||||||
|
},
|
||||||
|
/// −100..100.
|
||||||
|
Contrast {
|
||||||
|
amount: f32,
|
||||||
|
},
|
||||||
|
/// Input black and white points (0..255), gamma (0.1..10), output black and white.
|
||||||
|
Levels {
|
||||||
|
in_black: f32,
|
||||||
|
in_white: f32,
|
||||||
|
gamma: f32,
|
||||||
|
out_black: f32,
|
||||||
|
out_white: f32,
|
||||||
|
},
|
||||||
|
/// Hue in degrees, saturation and lightness −100..100.
|
||||||
|
HueSaturation {
|
||||||
|
hue: f32,
|
||||||
|
saturation: f32,
|
||||||
|
lightness: f32,
|
||||||
|
},
|
||||||
|
Invert,
|
||||||
|
/// Radius in pixels.
|
||||||
|
Blur {
|
||||||
|
radius: f32,
|
||||||
|
},
|
||||||
|
/// Amount 0..5, radius in pixels.
|
||||||
|
Sharpen {
|
||||||
|
amount: f32,
|
||||||
|
radius: f32,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rgb_to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
|
||||||
|
let max = r.max(g).max(b);
|
||||||
|
let min = r.min(g).min(b);
|
||||||
|
let l = (max + min) / 2.0;
|
||||||
|
if max == min {
|
||||||
|
return (0.0, 0.0, l);
|
||||||
|
}
|
||||||
|
let d = max - min;
|
||||||
|
let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
|
||||||
|
let h = if max == r {
|
||||||
|
(g - b) / d + if g < b { 6.0 } else { 0.0 }
|
||||||
|
} else if max == g {
|
||||||
|
(b - r) / d + 2.0
|
||||||
|
} else {
|
||||||
|
(r - g) / d + 4.0
|
||||||
|
};
|
||||||
|
(h * 60.0, s, l)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hsl_to_rgb(h: f32, s: f32, l: f32) -> (f32, f32, f32) {
|
||||||
|
if s == 0.0 {
|
||||||
|
return (l, l, l);
|
||||||
|
}
|
||||||
|
let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
|
||||||
|
let p = 2.0 * l - q;
|
||||||
|
let hue = |mut t: f32| {
|
||||||
|
t = t.rem_euclid(1.0);
|
||||||
|
if t < 1.0 / 6.0 {
|
||||||
|
p + (q - p) * 6.0 * t
|
||||||
|
} else if t < 0.5 {
|
||||||
|
q
|
||||||
|
} else if t < 2.0 / 3.0 {
|
||||||
|
p + (q - p) * (2.0 / 3.0 - t) * 6.0
|
||||||
|
} else {
|
||||||
|
p
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let h = h / 360.0;
|
||||||
|
(hue(h + 1.0 / 3.0), hue(h), hue(h - 1.0 / 3.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A box blur of premultiplied RGBA, three passes (close to a Gaussian).
|
||||||
|
fn blurred(src: &Raster, radius: f32) -> Vec<f32> {
|
||||||
|
let (w, h) = (src.width as usize, src.height as usize);
|
||||||
|
let mut buf: Vec<f32> = Vec::with_capacity(w * h * 4);
|
||||||
|
for p in src.rgba.as_chunks::<4>().0 {
|
||||||
|
let a = p[3] as f32 / 255.0;
|
||||||
|
buf.extend_from_slice(&[p[0] as f32 * a, p[1] as f32 * a, p[2] as f32 * a, p[3] as f32]);
|
||||||
|
}
|
||||||
|
let r = ((radius / 3.0f32.sqrt()).round() as usize).max(1);
|
||||||
|
let mut tmp = vec![0f32; buf.len()];
|
||||||
|
for _ in 0..3 {
|
||||||
|
for horizontal in [true, false] {
|
||||||
|
let (n, m) = if horizontal { (h, w) } else { (w, h) };
|
||||||
|
for line in 0..n {
|
||||||
|
let idx = |k: usize| if horizontal { (line * w + k) * 4 } else { (k * w + line) * 4 };
|
||||||
|
let mut acc = [0f32; 4];
|
||||||
|
let count = (2 * r + 1) as f32;
|
||||||
|
// Edge pixels repeat beyond the border.
|
||||||
|
for k in 0..(2 * r + 1) {
|
||||||
|
let kk = (k as isize - r as isize).clamp(0, m as isize - 1) as usize;
|
||||||
|
for c in 0..4 {
|
||||||
|
acc[c] += buf[idx(kk) + c];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for k in 0..m {
|
||||||
|
for c in 0..4 {
|
||||||
|
tmp[idx(k) + c] = acc[c] / count;
|
||||||
|
}
|
||||||
|
let out = (k as isize - r as isize).clamp(0, m as isize - 1) as usize;
|
||||||
|
let inn = (k as isize + r as isize + 1).clamp(0, m as isize - 1) as usize;
|
||||||
|
for c in 0..4 {
|
||||||
|
acc[c] += buf[idx(inn) + c] - buf[idx(out) + c];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::mem::swap(&mut buf, &mut tmp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buf
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the adjustment of `src` into `dst` (the same size), inside the selection; `dst` may start as a copy of
|
||||||
|
/// `src` (a live preview re-runs this from the untouched original).
|
||||||
|
pub fn adjust(src: &Raster, dst: &mut Raster, a: &Adjust, mask: Option<&Mask>) -> PixelRect {
|
||||||
|
let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: src.width, h: src.height });
|
||||||
|
let blur = match a {
|
||||||
|
Adjust::Blur { radius } | Adjust::Sharpen { radius, .. } => Some(blurred(src, radius.max(0.5))),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let lut = |f: &dyn Fn(f32) -> f32| -> [u8; 256] {
|
||||||
|
let mut t = [0u8; 256];
|
||||||
|
for (i, v) in t.iter_mut().enumerate() {
|
||||||
|
*v = f(i as f32).round().clamp(0.0, 255.0) as u8;
|
||||||
|
}
|
||||||
|
t
|
||||||
|
};
|
||||||
|
let table: Option<[u8; 256]> = match *a {
|
||||||
|
Adjust::Brightness { amount } => Some(lut(&|v| v + amount * 2.55)),
|
||||||
|
Adjust::Contrast { amount } => {
|
||||||
|
let c = amount.clamp(-100.0, 100.0) * 2.55;
|
||||||
|
let f = (259.0 * (c + 255.0)) / (255.0 * (259.0 - c));
|
||||||
|
Some(lut(&|v| f * (v - 128.0) + 128.0))
|
||||||
|
}
|
||||||
|
Adjust::Levels { in_black, in_white, gamma, out_black, out_white } => {
|
||||||
|
let span = (in_white - in_black).max(1.0);
|
||||||
|
let g = gamma.clamp(0.1, 10.0);
|
||||||
|
Some(lut(&|v| {
|
||||||
|
let t = ((v - in_black) / span).clamp(0.0, 1.0).powf(1.0 / g);
|
||||||
|
out_black + t * (out_white - out_black)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Adjust::Invert => Some(lut(&|v| 255.0 - v)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
for y in b.y..b.y + b.h {
|
||||||
|
for x in b.x..b.x + b.w {
|
||||||
|
let k = sel(mask, x, y);
|
||||||
|
let i = (y as usize * src.width as usize + x as usize) * 4;
|
||||||
|
let s: [u8; 4] = src.rgba[i..i + 4].try_into().unwrap();
|
||||||
|
let out: [u8; 4] = match (a, &table, &blur) {
|
||||||
|
(_, Some(t), _) => [t[s[0] as usize], t[s[1] as usize], t[s[2] as usize], s[3]],
|
||||||
|
(Adjust::HueSaturation { hue, saturation, lightness }, _, _) => {
|
||||||
|
let (h, sat, l) = rgb_to_hsl(s[0] as f32 / 255.0, s[1] as f32 / 255.0, s[2] as f32 / 255.0);
|
||||||
|
let sat = (sat * (1.0 + saturation / 100.0)).clamp(0.0, 1.0);
|
||||||
|
let l = if *lightness >= 0.0 {
|
||||||
|
l + (1.0 - l) * lightness / 100.0
|
||||||
|
} else {
|
||||||
|
l * (1.0 + lightness / 100.0)
|
||||||
|
};
|
||||||
|
let (r, g, bb) = hsl_to_rgb(h + hue, sat, l.clamp(0.0, 1.0));
|
||||||
|
[(r * 255.0).round() as u8, (g * 255.0).round() as u8, (bb * 255.0).round() as u8, s[3]]
|
||||||
|
}
|
||||||
|
(Adjust::Blur { .. }, _, Some(bl)) => {
|
||||||
|
let a = bl[i + 3];
|
||||||
|
if a <= 0.0 {
|
||||||
|
[0, 0, 0, 0]
|
||||||
|
} else {
|
||||||
|
let f = 255.0 / a;
|
||||||
|
[
|
||||||
|
(bl[i] * f).round().min(255.0) as u8,
|
||||||
|
(bl[i + 1] * f).round().min(255.0) as u8,
|
||||||
|
(bl[i + 2] * f).round().min(255.0) as u8,
|
||||||
|
a.round() as u8,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Adjust::Sharpen { amount, .. }, _, Some(bl)) => {
|
||||||
|
let a = (bl[i + 3] / 255.0).max(1e-3);
|
||||||
|
let mut o = [0u8; 4];
|
||||||
|
for c in 0..3 {
|
||||||
|
let blur_c = bl[i + c] / a;
|
||||||
|
o[c] = (s[c] as f32 + amount * (s[c] as f32 - blur_c)).round().clamp(0.0, 255.0) as u8;
|
||||||
|
}
|
||||||
|
o[3] = s[3];
|
||||||
|
o
|
||||||
|
}
|
||||||
|
_ => s,
|
||||||
|
};
|
||||||
|
let d = &mut dst.rgba[i..i + 4];
|
||||||
|
if k >= 1.0 {
|
||||||
|
d.copy_from_slice(&out);
|
||||||
|
} else if k > 0.0 {
|
||||||
|
for c in 0..4 {
|
||||||
|
d[c] = (s[c] as f32 + (out[c] as f32 - s[c] as f32) * k).round() as u8;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
d.copy_from_slice(&s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clone stamp: dabs that copy from `source` (the layer as it was when the stroke began) at an offset.
|
||||||
|
pub fn clone_stamp(
|
||||||
|
r: &mut Raster,
|
||||||
|
source: &Raster,
|
||||||
|
offset: (f32, f32),
|
||||||
|
points: &[(f32, f32, f32)],
|
||||||
|
b: &Brush,
|
||||||
|
mask: Option<&Mask>,
|
||||||
|
) -> PixelRect {
|
||||||
|
if points.is_empty() {
|
||||||
|
return PixelRect { x: 0, y: 0, w: 0, h: 0 };
|
||||||
|
}
|
||||||
|
let c = coverage(r.width, r.height, points, b.radius, b.hardness);
|
||||||
|
for y in 0..c.rect.h {
|
||||||
|
for x in 0..c.rect.w {
|
||||||
|
let (px, py) = (c.rect.x + x, c.rect.y + y);
|
||||||
|
let k = c.cov[(y * c.rect.w + x) as usize] * b.opacity.clamp(0.0, 1.0) * sel(mask, px, py);
|
||||||
|
if k <= 0.0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let sx = px as f32 + offset.0;
|
||||||
|
let sy = py as f32 + offset.1;
|
||||||
|
if sx < 0.0 || sy < 0.0 || sx >= source.width as f32 || sy >= source.height as f32 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let s = source.pixel(sx as u32, sy as u32);
|
||||||
|
let i = (py as usize * r.width as usize + px as usize) * 4;
|
||||||
|
blend(&mut r.rgba[i..i + 4], s, k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.rect
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Multiplies the alpha by a matte (0..255 per pixel, the raster's size): background removal as a layer action.
|
||||||
|
pub fn apply_matte(r: &mut Raster, matte: &[u8]) -> PixelRect {
|
||||||
|
for (p, m) in r.rgba.as_chunks_mut::<4>().0.iter_mut().zip(matte) {
|
||||||
|
p[3] = (p[3] as u32 * *m as u32 / 255) as u8;
|
||||||
|
}
|
||||||
|
PixelRect { x: 0, y: 0, w: r.width, h: r.height }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a pixel edit on an asset and returns the operation and its inverse (already applied), for
|
||||||
|
/// `History::record`; none when nothing changed or the asset is missing.
|
||||||
|
pub fn edit(doc: &mut Document, asset: &str, f: impl FnOnce(&mut Raster) -> PixelRect) -> Option<(Op, Op)> {
|
||||||
|
let r = doc.assets.get_mut(asset)?;
|
||||||
|
let before = r.clone();
|
||||||
|
let rect = f(r).clamp(r.width, r.height);
|
||||||
|
if rect.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let after = r.crop(rect);
|
||||||
|
let old = before.crop(rect);
|
||||||
|
if after == old {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((
|
||||||
|
Op::Patch { asset: asset.to_string(), rect, pixels: after.rgba },
|
||||||
|
Op::Patch { asset: asset.to_string(), rect, pixels: old.rgba },
|
||||||
|
))
|
||||||
|
}
|
||||||
@@ -0,0 +1,467 @@
|
|||||||
|
//! The display list: what a page looks like, as fill, stroke, image and glyph commands in page coordinates. The core's
|
||||||
|
//! tiny-skia painter (`render`), the face's canvas painter and the PDF and SVG exports all walk this one list, so the
|
||||||
|
//! screen and the export agree. Text is laid out here and enters as glyph outlines (each glyph defined once).
|
||||||
|
use crate::model::*;
|
||||||
|
use crate::path::{self, Seg};
|
||||||
|
use crate::text::{self, FontBook, FontKey};
|
||||||
|
use serde::Serialize;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub type Tf = [f32; 6];
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct DisplayList {
|
||||||
|
pub width: f32,
|
||||||
|
pub height: f32,
|
||||||
|
pub background: Option<[u8; 4]>,
|
||||||
|
/// Glyph outlines in font units (y up), referred to by index from `Text` items.
|
||||||
|
pub glyphs: Vec<GlyphDef>,
|
||||||
|
pub items: Vec<Item>,
|
||||||
|
/// Every top-level object of every visible vector layer, for selection and snapping in the face.
|
||||||
|
pub objects: Vec<ObjectInfo>,
|
||||||
|
/// Pixel sizes of the assets the list uses.
|
||||||
|
pub assets: Vec<AssetInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct GlyphDef {
|
||||||
|
pub d: Arc<str>,
|
||||||
|
pub upem: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct AssetInfo {
|
||||||
|
pub id: String,
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct ObjectInfo {
|
||||||
|
pub id: Id,
|
||||||
|
pub layer: Id,
|
||||||
|
pub kind: &'static str,
|
||||||
|
/// The object's own box (x, y, w, h) before its transform.
|
||||||
|
pub local: [f32; 4],
|
||||||
|
pub transform: Tf,
|
||||||
|
/// The four corners of the box on the page (clockwise from the box's top left).
|
||||||
|
pub corners: [[f32; 2]; 4],
|
||||||
|
/// The axis-aligned bounds on the page: x0, y0, x1, y1.
|
||||||
|
pub bounds: [f32; 4],
|
||||||
|
pub locked: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
#[serde(tag = "k", rename_all = "snake_case")]
|
||||||
|
pub enum Item {
|
||||||
|
Fill {
|
||||||
|
d: String,
|
||||||
|
t: Tf,
|
||||||
|
paint: DPaint,
|
||||||
|
even_odd: bool,
|
||||||
|
layer: Id,
|
||||||
|
obj: Option<Id>,
|
||||||
|
},
|
||||||
|
Stroke {
|
||||||
|
d: String,
|
||||||
|
t: Tf,
|
||||||
|
paint: DPaint,
|
||||||
|
width: f32,
|
||||||
|
cap: Cap,
|
||||||
|
join: Join,
|
||||||
|
dash: Vec<f32>,
|
||||||
|
layer: Id,
|
||||||
|
obj: Option<Id>,
|
||||||
|
},
|
||||||
|
/// The asset's pixels (0..width, 0..height) through `t`, clipped to `clip` (path data through `clip_t`).
|
||||||
|
Image {
|
||||||
|
asset: String,
|
||||||
|
t: Tf,
|
||||||
|
clip: Option<String>,
|
||||||
|
clip_t: Tf,
|
||||||
|
smooth: bool,
|
||||||
|
layer: Id,
|
||||||
|
obj: Option<Id>,
|
||||||
|
},
|
||||||
|
Text {
|
||||||
|
t: Tf,
|
||||||
|
color: [u8; 4],
|
||||||
|
size: f32,
|
||||||
|
glyphs: Vec<DGlyph>,
|
||||||
|
#[serde(skip)]
|
||||||
|
family: String,
|
||||||
|
#[serde(skip)]
|
||||||
|
weight: u16,
|
||||||
|
#[serde(skip)]
|
||||||
|
italic: bool,
|
||||||
|
layer: Id,
|
||||||
|
obj: Option<Id>,
|
||||||
|
},
|
||||||
|
/// Everything up to the matching `Pop` is drawn into its own layer, then composited at `opacity`.
|
||||||
|
Push {
|
||||||
|
opacity: f32,
|
||||||
|
},
|
||||||
|
Pop,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct DGlyph {
|
||||||
|
/// Index into `DisplayList::glyphs` (none for an empty glyph such as a space).
|
||||||
|
pub g: Option<u32>,
|
||||||
|
pub x: f32,
|
||||||
|
pub y: f32,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub font: FontKey,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub gid: u16,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub advance: f32,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
|
pub enum DPaint {
|
||||||
|
Solid { c: [u8; 4] },
|
||||||
|
Linear { x1: f32, y1: f32, x2: f32, y2: f32, stops: Vec<(f32, [u8; 4])> },
|
||||||
|
Radial { cx: f32, cy: f32, r: f32, stops: Vec<(f32, [u8; 4])> },
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mul(a: Tf, b: Tf) -> Tf {
|
||||||
|
// a after b: (a ∘ b)(p) = a(b(p)).
|
||||||
|
[
|
||||||
|
a[0] * b[0] + a[2] * b[1],
|
||||||
|
a[1] * b[0] + a[3] * b[1],
|
||||||
|
a[0] * b[2] + a[2] * b[3],
|
||||||
|
a[1] * b[2] + a[3] * b[3],
|
||||||
|
a[0] * b[4] + a[2] * b[5] + a[4],
|
||||||
|
a[1] * b[4] + a[3] * b[5] + a[5],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply_tf(t: Tf, x: f32, y: f32) -> [f32; 2] {
|
||||||
|
[t[0] * x + t[2] * y + t[4], t[1] * x + t[3] * y + t[5]]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn translate(x: f32, y: f32) -> Tf {
|
||||||
|
[1.0, 0.0, 0.0, 1.0, x, y]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn scale(sx: f32, sy: f32) -> Tf {
|
||||||
|
[sx, 0.0, 0.0, sy, 0.0, 0.0]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inverse of an affine transform (identity when it is singular).
|
||||||
|
pub fn invert(t: Tf) -> Tf {
|
||||||
|
let det = t[0] * t[3] - t[1] * t[2];
|
||||||
|
if det.abs() < 1e-12 {
|
||||||
|
return identity();
|
||||||
|
}
|
||||||
|
let (a, b, c, d) = (t[3] / det, -t[1] / det, -t[2] / det, t[0] / det);
|
||||||
|
[a, b, c, d, -(a * t[4] + c * t[5]), -(b * t[4] + d * t[5])]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dpaint(p: &Paint, bx: [f32; 4]) -> DPaint {
|
||||||
|
let [x, y, w, h] = bx;
|
||||||
|
let stops = |s: &[Stop]| s.iter().map(|s| (s.offset.clamp(0.0, 1.0), s.color.0)).collect();
|
||||||
|
match p {
|
||||||
|
Paint::Solid { color } => DPaint::Solid { c: color.0 },
|
||||||
|
Paint::Linear { x1, y1, x2, y2, stops: s } => {
|
||||||
|
DPaint::Linear { x1: x + x1 * w, y1: y + y1 * h, x2: x + x2 * w, y2: y + y2 * h, stops: stops(s) }
|
||||||
|
}
|
||||||
|
Paint::Radial { cx, cy, r, stops: s } => {
|
||||||
|
DPaint::Radial { cx: x + cx * w, cy: y + cy * h, r: (r * w.abs().max(h.abs())).max(0.01), stops: stops(s) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The object's own box: x, y, w, h before its transform. Text needs the layout, so it is passed in.
|
||||||
|
pub fn local_box(o: &Object, book: &FontBook) -> [f32; 4] {
|
||||||
|
match &o.shape {
|
||||||
|
Shape::Rect { w, h, .. } | Shape::Ellipse { w, h } | Shape::Image { w, h, .. } => [0.0, 0.0, *w, *h],
|
||||||
|
Shape::Line { x1, y1, x2, y2, .. } => [x1.min(*x2), y1.min(*y2), (x2 - x1).abs(), (y2 - y1).abs()],
|
||||||
|
Shape::Path { d } => {
|
||||||
|
let b = path::parse(d).ok().and_then(|s| path::bounds(&s)).unwrap_or([0.0; 4]);
|
||||||
|
[b[0], b[1], b[2] - b[0], b[3] - b[1]]
|
||||||
|
}
|
||||||
|
Shape::Text { w, text, style } => {
|
||||||
|
let l = text::layout(book, text, style, *w);
|
||||||
|
[0.0, 0.0, l.width.max(if *w > 0.0 { *w } else { 1.0 }), l.height]
|
||||||
|
}
|
||||||
|
Shape::Group { objects } => {
|
||||||
|
let mut b: Option<[f32; 4]> = None;
|
||||||
|
for c in objects {
|
||||||
|
let lb = local_box(c, book);
|
||||||
|
for (px, py) in
|
||||||
|
[(lb[0], lb[1]), (lb[0] + lb[2], lb[1]), (lb[0] + lb[2], lb[1] + lb[3]), (lb[0], lb[1] + lb[3])]
|
||||||
|
{
|
||||||
|
let [x, y] = apply_tf(c.transform, px, py);
|
||||||
|
b = Some(match b {
|
||||||
|
None => [x, y, x, y],
|
||||||
|
Some([a, c2, d, e]) => [a.min(x), c2.min(y), d.max(x), e.max(y)],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let b = b.unwrap_or([0.0; 4]);
|
||||||
|
[b[0], b[1], b[2] - b[0], b[3] - b[1]]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Builder<'a> {
|
||||||
|
book: &'a FontBook,
|
||||||
|
doc: &'a Document,
|
||||||
|
glyph_index: HashMap<(FontKey, u16), Option<u32>>,
|
||||||
|
glyphs: Vec<GlyphDef>,
|
||||||
|
items: Vec<Item>,
|
||||||
|
assets: Vec<AssetInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Builder<'_> {
|
||||||
|
fn asset(&mut self, id: &str) -> Option<(u32, u32)> {
|
||||||
|
let r = self.doc.assets.get(id)?;
|
||||||
|
if !self.assets.iter().any(|a| a.id == id) {
|
||||||
|
self.assets.push(AssetInfo { id: id.to_string(), width: r.width, height: r.height });
|
||||||
|
}
|
||||||
|
Some((r.width, r.height))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn glyph(&mut self, font: FontKey, gid: u16) -> Option<u32> {
|
||||||
|
if let Some(g) = self.glyph_index.get(&(font, gid)) {
|
||||||
|
return *g;
|
||||||
|
}
|
||||||
|
let g = self.book.outline(font, gid).filter(|d| !d.is_empty()).map(|d| {
|
||||||
|
self.glyphs.push(GlyphDef { d, upem: self.book.font(font).units_per_em });
|
||||||
|
(self.glyphs.len() - 1) as u32
|
||||||
|
});
|
||||||
|
self.glyph_index.insert((font, gid), g);
|
||||||
|
g
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object(&mut self, o: &Object, parent: Tf, layer: Id, top: Option<Id>) {
|
||||||
|
if !o.visible {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let t = mul(parent, o.transform);
|
||||||
|
let obj = top.or(Some(o.id));
|
||||||
|
let group = o.opacity < 0.999;
|
||||||
|
if group {
|
||||||
|
self.items.push(Item::Push { opacity: o.opacity.max(0.0) });
|
||||||
|
}
|
||||||
|
let bx = local_box(o, self.book);
|
||||||
|
let fill = |b: &mut Self, segs: &[Seg]| {
|
||||||
|
if let Some(p) = &o.fill {
|
||||||
|
b.items.push(Item::Fill { d: path::write(segs), t, paint: dpaint(p, bx), even_odd: false, layer, obj });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let stroke = |b: &mut Self, segs: &[Seg]| {
|
||||||
|
if let Some(s) = &o.stroke
|
||||||
|
&& s.width > 0.0
|
||||||
|
{
|
||||||
|
b.items.push(Item::Stroke {
|
||||||
|
d: path::write(segs),
|
||||||
|
t,
|
||||||
|
paint: dpaint(&s.paint, bx),
|
||||||
|
width: s.width,
|
||||||
|
cap: s.cap,
|
||||||
|
join: s.join,
|
||||||
|
dash: s.dash.clone(),
|
||||||
|
layer,
|
||||||
|
obj,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match &o.shape {
|
||||||
|
Shape::Rect { w, h, radius } => {
|
||||||
|
let segs = path::rect(*w, *h, *radius);
|
||||||
|
fill(self, &segs);
|
||||||
|
stroke(self, &segs);
|
||||||
|
}
|
||||||
|
Shape::Ellipse { w, h } => {
|
||||||
|
let segs = path::ellipse(*w, *h);
|
||||||
|
fill(self, &segs);
|
||||||
|
stroke(self, &segs);
|
||||||
|
}
|
||||||
|
Shape::Path { d } => {
|
||||||
|
if let Ok(segs) = path::parse(d) {
|
||||||
|
fill(self, &segs);
|
||||||
|
stroke(self, &segs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Shape::Line { x1, y1, x2, y2, arrow_start, arrow_end } => {
|
||||||
|
let w = o.stroke.as_ref().map(|s| s.width).unwrap_or(1.0);
|
||||||
|
let (mut a, mut b) = ((*x1, *y1), (*x2, *y2));
|
||||||
|
if *arrow_end {
|
||||||
|
b = path::shorten(*x1, *y1, *x2, *y2, w);
|
||||||
|
}
|
||||||
|
if *arrow_start {
|
||||||
|
a = path::shorten(*x2, *y2, *x1, *y1, w);
|
||||||
|
}
|
||||||
|
stroke(self, &[Seg::Move(a.0, a.1), Seg::Line(b.0, b.1)]);
|
||||||
|
if let Some(s) = &o.stroke {
|
||||||
|
for (on, (fx, fy, tx, ty)) in
|
||||||
|
[(*arrow_end, (*x1, *y1, *x2, *y2)), (*arrow_start, (*x2, *y2, *x1, *y1))]
|
||||||
|
{
|
||||||
|
if on {
|
||||||
|
let head = path::arrow_head(fx, fy, tx, ty, w);
|
||||||
|
self.items.push(Item::Fill {
|
||||||
|
d: path::write(&head),
|
||||||
|
t,
|
||||||
|
paint: dpaint(&s.paint, bx),
|
||||||
|
even_odd: false,
|
||||||
|
layer,
|
||||||
|
obj,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Shape::Image { asset, w, h, crop } => {
|
||||||
|
let frame = path::rect(*w, *h, 0.0);
|
||||||
|
fill(self, &frame);
|
||||||
|
if let Some((pw, ph)) = self.asset(asset) {
|
||||||
|
let it = mul(t, mul(translate(crop.x, crop.y), scale(crop.w / pw as f32, crop.h / ph as f32)));
|
||||||
|
self.items.push(Item::Image {
|
||||||
|
asset: asset.clone(),
|
||||||
|
t: it,
|
||||||
|
clip: Some(path::write(&frame)),
|
||||||
|
clip_t: t,
|
||||||
|
smooth: true,
|
||||||
|
layer,
|
||||||
|
obj,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
stroke(self, &frame);
|
||||||
|
}
|
||||||
|
Shape::Text { w, text, style } => {
|
||||||
|
let l = text::layout(self.book, text, style, *w);
|
||||||
|
let mut glyphs = Vec::new();
|
||||||
|
for line in &l.lines {
|
||||||
|
for g in &line.glyphs {
|
||||||
|
let def = self.glyph(g.font, g.gid);
|
||||||
|
glyphs.push(DGlyph {
|
||||||
|
g: def,
|
||||||
|
x: g.x,
|
||||||
|
y: line.baseline,
|
||||||
|
font: g.font,
|
||||||
|
gid: g.gid,
|
||||||
|
advance: g.advance,
|
||||||
|
text: g.text.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let frame = path::rect(bx[2], bx[3], 0.0);
|
||||||
|
fill(self, &frame);
|
||||||
|
self.items.push(Item::Text {
|
||||||
|
t,
|
||||||
|
color: style.color.0,
|
||||||
|
size: style.size,
|
||||||
|
glyphs,
|
||||||
|
family: style.family.clone(),
|
||||||
|
weight: style.weight,
|
||||||
|
italic: style.italic,
|
||||||
|
layer,
|
||||||
|
obj,
|
||||||
|
});
|
||||||
|
stroke(self, &frame);
|
||||||
|
}
|
||||||
|
Shape::Group { objects } => {
|
||||||
|
for c in objects {
|
||||||
|
self.object(c, t, layer, obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if group {
|
||||||
|
self.items.push(Item::Pop);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layers(&mut self, ls: &[Layer], objects: &mut Vec<ObjectInfo>) {
|
||||||
|
for l in ls {
|
||||||
|
if !l.visible {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let group = l.opacity < 0.999;
|
||||||
|
if group {
|
||||||
|
self.items.push(Item::Push { opacity: l.opacity.max(0.0) });
|
||||||
|
}
|
||||||
|
match &l.kind {
|
||||||
|
LayerKind::Vector { objects: os } => {
|
||||||
|
for o in os {
|
||||||
|
self.object(o, identity(), l.id, None);
|
||||||
|
if o.visible {
|
||||||
|
objects.push(info(o, l.id, l.locked, self.book));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LayerKind::Bitmap { asset, x, y, w, h } => {
|
||||||
|
if let Some((pw, ph)) = self.asset(asset) {
|
||||||
|
let t = mul(translate(*x, *y), scale(w / pw as f32, h / ph as f32));
|
||||||
|
let exact = (w - pw as f32).abs() < 1e-3 && (h - ph as f32).abs() < 1e-3;
|
||||||
|
self.items.push(Item::Image {
|
||||||
|
asset: asset.clone(),
|
||||||
|
t,
|
||||||
|
clip: None,
|
||||||
|
clip_t: identity(),
|
||||||
|
smooth: !exact,
|
||||||
|
layer: l.id,
|
||||||
|
obj: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LayerKind::Group { layers } => self.layers(layers, objects),
|
||||||
|
}
|
||||||
|
if group {
|
||||||
|
self.items.push(Item::Pop);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn info(o: &Object, layer: Id, layer_locked: bool, book: &FontBook) -> ObjectInfo {
|
||||||
|
let b = local_box(o, book);
|
||||||
|
let pts = [[b[0], b[1]], [b[0] + b[2], b[1]], [b[0] + b[2], b[1] + b[3]], [b[0], b[1] + b[3]]];
|
||||||
|
let corners = pts.map(|[x, y]| apply_tf(o.transform, x, y));
|
||||||
|
let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
|
||||||
|
for [x, y] in corners {
|
||||||
|
bounds = [bounds[0].min(x), bounds[1].min(y), bounds[2].max(x), bounds[3].max(y)];
|
||||||
|
}
|
||||||
|
let kind = match o.shape {
|
||||||
|
Shape::Rect { .. } => "rect",
|
||||||
|
Shape::Ellipse { .. } => "ellipse",
|
||||||
|
Shape::Line { .. } => "line",
|
||||||
|
Shape::Path { .. } => "path",
|
||||||
|
Shape::Text { .. } => "text",
|
||||||
|
Shape::Image { .. } => "image",
|
||||||
|
Shape::Group { .. } => "group",
|
||||||
|
};
|
||||||
|
ObjectInfo {
|
||||||
|
id: o.id,
|
||||||
|
layer,
|
||||||
|
kind,
|
||||||
|
local: b,
|
||||||
|
transform: o.transform,
|
||||||
|
corners,
|
||||||
|
bounds,
|
||||||
|
locked: o.locked || layer_locked,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The display list of one page.
|
||||||
|
pub fn build(doc: &Document, page: &Page, book: &FontBook) -> DisplayList {
|
||||||
|
let mut b =
|
||||||
|
Builder { book, doc, glyph_index: HashMap::new(), glyphs: Vec::new(), items: Vec::new(), assets: Vec::new() };
|
||||||
|
let mut objects = Vec::new();
|
||||||
|
b.layers(&page.layers, &mut objects);
|
||||||
|
DisplayList {
|
||||||
|
width: page.width,
|
||||||
|
height: page.height,
|
||||||
|
background: page.background.map(|c| c.0),
|
||||||
|
glyphs: b.glyphs,
|
||||||
|
items: b.items,
|
||||||
|
objects,
|
||||||
|
assets: b.assets,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,934 @@
|
|||||||
|
//! Exports: PNG at a scale, JPG on white, SVG (vector layers as SVG, pixels embedded as PNG) and PDF with pdf-writer
|
||||||
|
//! (vectors stay vectors, text is real text in subset fonts with a ToUnicode map, each page at its exact size).
|
||||||
|
//! All of them walk the display list (`display::build`), the same one the screen is painted from.
|
||||||
|
use crate::display::{self, DGlyph, DPaint, DisplayList, Item, Tf};
|
||||||
|
use crate::model::*;
|
||||||
|
use crate::path;
|
||||||
|
use crate::text::{Embedding, FontBook, FontKey};
|
||||||
|
use pdf_writer::{Content, Filter, Finish, Name, Pdf, Rect as PRect, Ref, Str};
|
||||||
|
use std::collections::{BTreeMap, HashMap};
|
||||||
|
use std::fmt::Write as _;
|
||||||
|
use std::io::Write as _;
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ExportError {
|
||||||
|
#[error("The font \u{201c}{family}\u{201d} cannot be put in a PDF: {reason}. Choose another font for that text.")]
|
||||||
|
FontNotEmbeddable { family: String, reason: &'static str },
|
||||||
|
#[error("The font \u{201c}{0}\u{201d} could not be prepared for the PDF.")]
|
||||||
|
FontBroken(String),
|
||||||
|
#[error("The picture is too large to export at this scale.")]
|
||||||
|
TooLarge,
|
||||||
|
#[error("Could not encode the picture: {0}")]
|
||||||
|
Encode(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page as PNG at `scale` pixels per point.
|
||||||
|
pub fn png(doc: &Document, page: &Page, book: &FontBook, scale: f32) -> Result<Vec<u8>, ExportError> {
|
||||||
|
let r = raster(doc, page, book, scale)?;
|
||||||
|
crate::format::encode_png(&r).map_err(|e| ExportError::Encode(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page as JPG (quality 0–100) at `scale`, on white where the page is transparent.
|
||||||
|
pub fn jpg(doc: &Document, page: &Page, book: &FontBook, scale: f32, quality: u8) -> Result<Vec<u8>, ExportError> {
|
||||||
|
use image::ImageEncoder;
|
||||||
|
let r = raster(doc, page, book, scale)?;
|
||||||
|
let mut rgb = Vec::with_capacity(r.rgba.len() / 4 * 3);
|
||||||
|
for p in r.rgba.as_chunks::<4>().0 {
|
||||||
|
let a = p[3] as u32;
|
||||||
|
for c in &p[..3] {
|
||||||
|
rgb.push(((*c as u32 * a + 255 * (255 - a) + 127) / 255) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100))
|
||||||
|
.write_image(&rgb, r.width, r.height, image::ExtendedColorType::Rgb8)
|
||||||
|
.map_err(|e| ExportError::Encode(e.to_string()))?;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn raster(doc: &Document, page: &Page, book: &FontBook, scale: f32) -> Result<Raster, ExportError> {
|
||||||
|
let px = (page.width * scale) as u64 * (page.height * scale) as u64;
|
||||||
|
if scale.is_nan() || scale <= 0.0 || px > 200_000_000 {
|
||||||
|
return Err(ExportError::TooLarge);
|
||||||
|
}
|
||||||
|
crate::render::page(doc, page, book, scale).ok_or(ExportError::TooLarge)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- SVG ----------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn hex(c: [u8; 4]) -> String {
|
||||||
|
format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn esc(s: &str) -> String {
|
||||||
|
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mat(t: Tf) -> String {
|
||||||
|
format!("matrix({} {} {} {} {} {})", t[0], t[1], t[2], t[3], t[4], t[5])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page as SVG. Text is written as `<text>` with each character's x, so it stays text.
|
||||||
|
pub fn svg(doc: &Document, page: &Page, book: &FontBook) -> String {
|
||||||
|
use base64::Engine as _;
|
||||||
|
let list = display::build(doc, page, book);
|
||||||
|
let mut defs = String::new();
|
||||||
|
let mut body = String::new();
|
||||||
|
let mut n = 0;
|
||||||
|
let mut paint = |p: &DPaint, defs: &mut String| -> (String, Option<f32>) {
|
||||||
|
match p {
|
||||||
|
DPaint::Solid { c } => (hex(*c), (c[3] < 255).then_some(c[3] as f32 / 255.0)),
|
||||||
|
DPaint::Linear { x1, y1, x2, y2, stops } => {
|
||||||
|
n += 1;
|
||||||
|
let _ = write!(
|
||||||
|
defs,
|
||||||
|
r#"<linearGradient id="g{n}" gradientUnits="userSpaceOnUse" x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}">"#
|
||||||
|
);
|
||||||
|
for (o, c) in stops {
|
||||||
|
let _ = write!(
|
||||||
|
defs,
|
||||||
|
r#"<stop offset="{o}" stop-color="{}" stop-opacity="{}"/>"#,
|
||||||
|
hex(*c),
|
||||||
|
c[3] as f32 / 255.0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
defs.push_str("</linearGradient>");
|
||||||
|
(format!("url(#g{n})"), None)
|
||||||
|
}
|
||||||
|
DPaint::Radial { cx, cy, r, stops } => {
|
||||||
|
n += 1;
|
||||||
|
let _ = write!(
|
||||||
|
defs,
|
||||||
|
r#"<radialGradient id="g{n}" gradientUnits="userSpaceOnUse" cx="{cx}" cy="{cy}" r="{r}">"#
|
||||||
|
);
|
||||||
|
for (o, c) in stops {
|
||||||
|
let _ = write!(
|
||||||
|
defs,
|
||||||
|
r#"<stop offset="{o}" stop-color="{}" stop-opacity="{}"/>"#,
|
||||||
|
hex(*c),
|
||||||
|
c[3] as f32 / 255.0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
defs.push_str("</radialGradient>");
|
||||||
|
(format!("url(#g{n})"), None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut clips = 0;
|
||||||
|
let mut pngs: HashMap<&str, String> = HashMap::new();
|
||||||
|
for item in &list.items {
|
||||||
|
match item {
|
||||||
|
Item::Push { opacity } => {
|
||||||
|
let _ = write!(body, r#"<g opacity="{opacity}">"#);
|
||||||
|
}
|
||||||
|
Item::Pop => body.push_str("</g>"),
|
||||||
|
Item::Fill { d, t, paint: p, even_odd, .. } => {
|
||||||
|
let (f, a) = paint(p, &mut defs);
|
||||||
|
let _ = write!(body, r#"<path d="{d}" transform="{}" fill="{f}""#, mat(*t));
|
||||||
|
if let Some(a) = a {
|
||||||
|
let _ = write!(body, r#" fill-opacity="{a}""#);
|
||||||
|
}
|
||||||
|
if *even_odd {
|
||||||
|
body.push_str(r#" fill-rule="evenodd""#);
|
||||||
|
}
|
||||||
|
body.push_str("/>");
|
||||||
|
}
|
||||||
|
Item::Stroke { d, t, paint: p, width, cap, join, dash, .. } => {
|
||||||
|
let (s, a) = paint(p, &mut defs);
|
||||||
|
let _ = write!(
|
||||||
|
body,
|
||||||
|
r#"<path d="{d}" transform="{}" fill="none" stroke="{s}" stroke-width="{width}""#,
|
||||||
|
mat(*t)
|
||||||
|
);
|
||||||
|
if let Some(a) = a {
|
||||||
|
let _ = write!(body, r#" stroke-opacity="{a}""#);
|
||||||
|
}
|
||||||
|
let cap = match cap {
|
||||||
|
Cap::Butt => "butt",
|
||||||
|
Cap::Round => "round",
|
||||||
|
Cap::Square => "square",
|
||||||
|
};
|
||||||
|
let join = match join {
|
||||||
|
Join::Miter => "miter",
|
||||||
|
Join::Round => "round",
|
||||||
|
Join::Bevel => "bevel",
|
||||||
|
};
|
||||||
|
let _ = write!(body, r#" stroke-linecap="{cap}" stroke-linejoin="{join}""#);
|
||||||
|
if !dash.is_empty() {
|
||||||
|
let d: Vec<String> = dash.iter().map(|v| v.to_string()).collect();
|
||||||
|
let _ = write!(body, r#" stroke-dasharray="{}""#, d.join(" "));
|
||||||
|
}
|
||||||
|
body.push_str("/>");
|
||||||
|
}
|
||||||
|
Item::Image { asset, t, clip, clip_t, .. } => {
|
||||||
|
let Some(r) = doc.assets.get(asset) else { continue };
|
||||||
|
let href = pngs.entry(asset.as_str()).or_insert_with(|| {
|
||||||
|
let png = crate::format::encode_png(r).unwrap_or_default();
|
||||||
|
format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(png))
|
||||||
|
});
|
||||||
|
if let Some(cd) = clip {
|
||||||
|
clips += 1;
|
||||||
|
let _ = write!(
|
||||||
|
defs,
|
||||||
|
r#"<clipPath id="c{clips}"><path d="{cd}" transform="{}"/></clipPath>"#,
|
||||||
|
mat(*clip_t)
|
||||||
|
);
|
||||||
|
let _ = write!(body, r#"<g clip-path="url(#c{clips})">"#);
|
||||||
|
}
|
||||||
|
let _ = write!(
|
||||||
|
body,
|
||||||
|
r#"<image href="{href}" width="{}" height="{}" transform="{}" preserveAspectRatio="none"/>"#,
|
||||||
|
r.width,
|
||||||
|
r.height,
|
||||||
|
mat(*t)
|
||||||
|
);
|
||||||
|
if clip.is_some() {
|
||||||
|
body.push_str("</g>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Item::Text { t, color, size, glyphs, family, weight, italic, .. } => {
|
||||||
|
// One <text> per line (glyphs that share a baseline), every character placed at its glyph's x.
|
||||||
|
let mut lines: BTreeMap<i64, Vec<&DGlyph>> = BTreeMap::new();
|
||||||
|
for g in glyphs {
|
||||||
|
lines.entry((g.y * 100.0) as i64).or_default().push(g);
|
||||||
|
}
|
||||||
|
let _ = write!(
|
||||||
|
body,
|
||||||
|
r#"<g transform="{}" font-family="{}" font-size="{size}" font-weight="{weight}"{} fill="{}"{}>"#,
|
||||||
|
mat(*t),
|
||||||
|
esc(family),
|
||||||
|
if *italic { r#" font-style="italic""# } else { "" },
|
||||||
|
hex(*color),
|
||||||
|
if color[3] < 255 {
|
||||||
|
format!(r#" fill-opacity="{}""#, color[3] as f32 / 255.0)
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
for gs in lines.values() {
|
||||||
|
let mut xs = Vec::new();
|
||||||
|
let mut s = String::new();
|
||||||
|
for g in gs {
|
||||||
|
for (i, ch) in g.text.chars().enumerate() {
|
||||||
|
xs.push(format!(
|
||||||
|
"{}",
|
||||||
|
g.x + if i == 0 { 0.0 } else { g.advance * i as f32 / g.text.chars().count() as f32 }
|
||||||
|
));
|
||||||
|
s.push(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.trim().is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let _ = write!(
|
||||||
|
body,
|
||||||
|
r#"<text xml:space="preserve" x="{}" y="{}">{}</text>"#,
|
||||||
|
xs.join(" "),
|
||||||
|
gs[0].y,
|
||||||
|
esc(&s)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
body.push_str("</g>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = format!(
|
||||||
|
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}pt" height="{h}pt" viewBox="0 0 {w} {h}">"#,
|
||||||
|
w = list.width,
|
||||||
|
h = list.height
|
||||||
|
);
|
||||||
|
if !defs.is_empty() {
|
||||||
|
let _ = write!(out, "<defs>{defs}</defs>");
|
||||||
|
}
|
||||||
|
if let Some(bg) = list.background {
|
||||||
|
let _ = write!(out, r#"<rect width="{}" height="{}" fill="{}"/>"#, list.width, list.height, hex(bg));
|
||||||
|
}
|
||||||
|
out.push_str(&body);
|
||||||
|
out.push_str("</svg>");
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- PDF ----------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn deflate(data: &[u8]) -> Vec<u8> {
|
||||||
|
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(6));
|
||||||
|
let _ = e.write_all(data);
|
||||||
|
e.finish().unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FontUse {
|
||||||
|
name: String,
|
||||||
|
/// Subset fonts are addressed by the subset's glyph ids (CID = new gid); others by their own ids.
|
||||||
|
subset: bool,
|
||||||
|
remapper: subsetter::GlyphRemapper,
|
||||||
|
/// CID → (original glyph id, the text it stands for).
|
||||||
|
glyphs: BTreeMap<u16, (u16, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fonts a set of display lists uses, and whether each may be embedded.
|
||||||
|
pub fn check_fonts(lists: &[DisplayList], book: &FontBook) -> Result<(), ExportError> {
|
||||||
|
for l in lists {
|
||||||
|
for it in &l.items {
|
||||||
|
if let Item::Text { glyphs, .. } = it {
|
||||||
|
for g in glyphs {
|
||||||
|
let f = book.font(g.font);
|
||||||
|
if let Embedding::Forbidden(reason) = f.embedding {
|
||||||
|
return Err(ExportError::FontNotEmbeddable { family: f.family.clone(), reason });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Writer<'a> {
|
||||||
|
pdf: Pdf,
|
||||||
|
next: i32,
|
||||||
|
book: &'a FontBook,
|
||||||
|
fonts: BTreeMap<FontKey, (Ref, FontUse)>,
|
||||||
|
images: BTreeMap<String, (Ref, String)>,
|
||||||
|
alphas: BTreeMap<(u8, u8), (Ref, String)>,
|
||||||
|
patterns: Vec<(Ref, String, DPaint, Tf)>,
|
||||||
|
forms: Vec<(Ref, String, Vec<u8>)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Writer<'_> {
|
||||||
|
fn alloc(&mut self) -> Ref {
|
||||||
|
self.next += 1;
|
||||||
|
Ref::new(self.next)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn alpha(&mut self, fill: u8, stroke: u8) -> String {
|
||||||
|
if let Some((_, n)) = self.alphas.get(&(fill, stroke)) {
|
||||||
|
return n.clone();
|
||||||
|
}
|
||||||
|
let r = self.alloc();
|
||||||
|
let n = format!("A{}", self.alphas.len());
|
||||||
|
self.alphas.insert((fill, stroke), (r, n.clone()));
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pattern(&mut self, p: &DPaint, full: Tf) -> String {
|
||||||
|
let r = self.alloc();
|
||||||
|
let n = format!("P{}", self.patterns.len());
|
||||||
|
self.patterns.push((r, n.clone(), p.clone(), full));
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
fn image(&mut self, asset: &str) -> String {
|
||||||
|
if let Some((_, n)) = self.images.get(asset) {
|
||||||
|
return n.clone();
|
||||||
|
}
|
||||||
|
let r = self.alloc();
|
||||||
|
let n = format!("Im{}", self.images.len());
|
||||||
|
self.images.insert(asset.to_string(), (r, n.clone()));
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
fn font(&mut self, key: FontKey) -> String {
|
||||||
|
if let Some((_, u)) = self.fonts.get(&key) {
|
||||||
|
return u.name.clone();
|
||||||
|
}
|
||||||
|
let r = self.alloc();
|
||||||
|
let n = format!("F{}", self.fonts.len());
|
||||||
|
let f = self.book.font(key);
|
||||||
|
let subset = ttf_parser::Face::parse(&f.data, f.index).map(|fc| fc.is_subsetting_allowed()).unwrap_or(false);
|
||||||
|
let u = FontUse { name: n.clone(), subset, remapper: subsetter::GlyphRemapper::new(), glyphs: BTreeMap::new() };
|
||||||
|
self.fonts.insert(key, (r, u));
|
||||||
|
n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The names a page or form refers to, copied out of the writer so the PDF can be written while they are used.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ResTable {
|
||||||
|
fonts: Vec<(String, Ref)>,
|
||||||
|
xobjects: Vec<(String, Ref)>,
|
||||||
|
states: Vec<(String, Ref)>,
|
||||||
|
patterns: Vec<(String, Ref)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Writer<'_> {
|
||||||
|
fn table(&self) -> ResTable {
|
||||||
|
ResTable {
|
||||||
|
fonts: self.fonts.values().map(|(r, u)| (u.name.clone(), *r)).collect(),
|
||||||
|
xobjects: self
|
||||||
|
.images
|
||||||
|
.values()
|
||||||
|
.map(|(r, n)| (n.clone(), *r))
|
||||||
|
.chain(self.forms.iter().map(|(r, n, _)| (n.clone(), *r)))
|
||||||
|
.collect(),
|
||||||
|
states: self.alphas.values().map(|(r, n)| (n.clone(), *r)).collect(),
|
||||||
|
patterns: self.patterns.iter().map(|(r, n, _, _)| (n.clone(), *r)).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_resources(t: &ResTable, res: &mut pdf_writer::writers::Resources) {
|
||||||
|
let mut f = res.fonts();
|
||||||
|
for (n, r) in &t.fonts {
|
||||||
|
f.pair(Name(n.as_bytes()), *r);
|
||||||
|
}
|
||||||
|
f.finish();
|
||||||
|
let mut x = res.x_objects();
|
||||||
|
for (n, r) in &t.xobjects {
|
||||||
|
x.pair(Name(n.as_bytes()), *r);
|
||||||
|
}
|
||||||
|
x.finish();
|
||||||
|
let mut g = res.ext_g_states();
|
||||||
|
for (n, r) in &t.states {
|
||||||
|
g.pair(Name(n.as_bytes()), *r);
|
||||||
|
}
|
||||||
|
g.finish();
|
||||||
|
let mut p = res.patterns();
|
||||||
|
for (n, r) in &t.patterns {
|
||||||
|
p.pair(Name(n.as_bytes()), *r);
|
||||||
|
}
|
||||||
|
p.finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path_ops(c: &mut Content, d: &str) {
|
||||||
|
let Ok(segs) = path::parse(d) else { return };
|
||||||
|
let (mut cx, mut cy) = (0.0f32, 0.0f32);
|
||||||
|
for s in segs {
|
||||||
|
match s {
|
||||||
|
path::Seg::Move(x, y) => {
|
||||||
|
c.move_to(x, y);
|
||||||
|
(cx, cy) = (x, y);
|
||||||
|
}
|
||||||
|
path::Seg::Line(x, y) => {
|
||||||
|
c.line_to(x, y);
|
||||||
|
(cx, cy) = (x, y);
|
||||||
|
}
|
||||||
|
path::Seg::Quad(a, b, x, y) => {
|
||||||
|
// Quadratic → cubic.
|
||||||
|
let (c1x, c1y) = (cx + 2.0 / 3.0 * (a - cx), cy + 2.0 / 3.0 * (b - cy));
|
||||||
|
let (c2x, c2y) = (x + 2.0 / 3.0 * (a - x), y + 2.0 / 3.0 * (b - y));
|
||||||
|
c.cubic_to(c1x, c1y, c2x, c2y, x, y);
|
||||||
|
(cx, cy) = (x, y);
|
||||||
|
}
|
||||||
|
path::Seg::Cubic(a, b, e, f, x, y) => {
|
||||||
|
c.cubic_to(a, b, e, f, x, y);
|
||||||
|
(cx, cy) = (x, y);
|
||||||
|
}
|
||||||
|
path::Seg::Close => {
|
||||||
|
c.close_path();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rgb(c: [u8; 4]) -> (f32, f32, f32) {
|
||||||
|
(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The alpha a paint is drawn with (a gradient's stops share one: the average of theirs).
|
||||||
|
fn paint_alpha(p: &DPaint) -> u8 {
|
||||||
|
match p {
|
||||||
|
DPaint::Solid { c } => c[3],
|
||||||
|
DPaint::Linear { stops, .. } | DPaint::Radial { stops, .. } => {
|
||||||
|
if stops.is_empty() {
|
||||||
|
255
|
||||||
|
} else {
|
||||||
|
(stops.iter().map(|(_, c)| c[3] as u32).sum::<u32>() / stops.len() as u32) as u8
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_paint(w: &mut Writer, c: &mut Content, p: &DPaint, full: Tf, stroke: bool) {
|
||||||
|
match p {
|
||||||
|
DPaint::Solid { c: col } => {
|
||||||
|
let (r, g, b) = rgb(*col);
|
||||||
|
if stroke {
|
||||||
|
c.set_stroke_rgb(r, g, b);
|
||||||
|
} else {
|
||||||
|
c.set_fill_rgb(r, g, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let n = w.pattern(p, full);
|
||||||
|
if stroke {
|
||||||
|
c.set_stroke_color_space(pdf_writer::types::ColorSpaceOperand::Pattern);
|
||||||
|
c.set_stroke_pattern(None, Name(n.as_bytes()));
|
||||||
|
} else {
|
||||||
|
c.set_fill_color_space(pdf_writer::types::ColorSpaceOperand::Pattern);
|
||||||
|
c.set_fill_pattern(None, Name(n.as_bytes()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The document as PDF: every page at its size, vectors as vectors, real text, pictures with their alpha.
|
||||||
|
pub fn pdf(doc: &Document, book: &FontBook) -> Result<Vec<u8>, ExportError> {
|
||||||
|
let lists: Vec<DisplayList> = doc.pages.iter().map(|p| display::build(doc, p, book)).collect();
|
||||||
|
check_fonts(&lists, book)?;
|
||||||
|
let mut w = Writer {
|
||||||
|
pdf: Pdf::new(),
|
||||||
|
next: 0,
|
||||||
|
book,
|
||||||
|
fonts: BTreeMap::new(),
|
||||||
|
images: BTreeMap::new(),
|
||||||
|
alphas: BTreeMap::new(),
|
||||||
|
patterns: Vec::new(),
|
||||||
|
forms: Vec::new(),
|
||||||
|
};
|
||||||
|
let catalog = w.alloc();
|
||||||
|
let pages_id = w.alloc();
|
||||||
|
let mut page_refs = Vec::new();
|
||||||
|
let mut contents = Vec::new();
|
||||||
|
for list in &lists {
|
||||||
|
let flip: Tf = [1.0, 0.0, 0.0, -1.0, 0.0, list.height];
|
||||||
|
let mut stack: Vec<(Content, f32)> = vec![(Content::new(), 1.0)];
|
||||||
|
{
|
||||||
|
let c = &mut stack[0].0;
|
||||||
|
c.transform(flip);
|
||||||
|
if let Some(bg) = list.background {
|
||||||
|
let (r, g, b) = rgb(bg);
|
||||||
|
c.set_fill_rgb(r, g, b);
|
||||||
|
c.rect(0.0, 0.0, list.width, list.height);
|
||||||
|
c.fill_nonzero();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for item in &list.items {
|
||||||
|
match item {
|
||||||
|
Item::Push { opacity } => stack.push((Content::new(), *opacity)),
|
||||||
|
Item::Pop => {
|
||||||
|
if stack.len() > 1 {
|
||||||
|
let (inner, opacity) = stack.pop().unwrap();
|
||||||
|
let r = w.alloc();
|
||||||
|
let n = format!("X{}", w.forms.len());
|
||||||
|
w.forms.push((r, n.clone(), inner.finish().to_vec()));
|
||||||
|
let a = w.alpha((opacity * 255.0).round() as u8, (opacity * 255.0).round() as u8);
|
||||||
|
let c = &mut stack.last_mut().unwrap().0;
|
||||||
|
c.save_state();
|
||||||
|
c.set_parameters(Name(a.as_bytes()));
|
||||||
|
c.x_object(Name(n.as_bytes()));
|
||||||
|
c.restore_state();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Item::Fill { d, t, paint, even_odd, .. } => {
|
||||||
|
let full = display::mul(flip, *t);
|
||||||
|
let alpha = paint_alpha(paint);
|
||||||
|
let a = (alpha < 255).then(|| w.alpha(alpha, 255));
|
||||||
|
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
|
||||||
|
c.save_state();
|
||||||
|
if let Some(a) = &a {
|
||||||
|
c.set_parameters(Name(a.as_bytes()));
|
||||||
|
}
|
||||||
|
c.transform(*t);
|
||||||
|
set_paint(&mut w, &mut c, paint, full, false);
|
||||||
|
path_ops(&mut c, d);
|
||||||
|
if *even_odd {
|
||||||
|
c.fill_even_odd();
|
||||||
|
} else {
|
||||||
|
c.fill_nonzero();
|
||||||
|
}
|
||||||
|
c.restore_state();
|
||||||
|
stack.last_mut().unwrap().0 = c;
|
||||||
|
}
|
||||||
|
Item::Stroke { d, t, paint, width, cap, join, dash, .. } => {
|
||||||
|
let full = display::mul(flip, *t);
|
||||||
|
let alpha = paint_alpha(paint);
|
||||||
|
let a = (alpha < 255).then(|| w.alpha(255, alpha));
|
||||||
|
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
|
||||||
|
c.save_state();
|
||||||
|
if let Some(a) = &a {
|
||||||
|
c.set_parameters(Name(a.as_bytes()));
|
||||||
|
}
|
||||||
|
c.transform(*t);
|
||||||
|
set_paint(&mut w, &mut c, paint, full, true);
|
||||||
|
c.set_line_width(*width);
|
||||||
|
c.set_line_cap(match cap {
|
||||||
|
Cap::Butt => pdf_writer::types::LineCapStyle::ButtCap,
|
||||||
|
Cap::Round => pdf_writer::types::LineCapStyle::RoundCap,
|
||||||
|
Cap::Square => pdf_writer::types::LineCapStyle::ProjectingSquareCap,
|
||||||
|
});
|
||||||
|
c.set_line_join(match join {
|
||||||
|
Join::Miter => pdf_writer::types::LineJoinStyle::MiterJoin,
|
||||||
|
Join::Round => pdf_writer::types::LineJoinStyle::RoundJoin,
|
||||||
|
Join::Bevel => pdf_writer::types::LineJoinStyle::BevelJoin,
|
||||||
|
});
|
||||||
|
c.set_miter_limit(10.0);
|
||||||
|
if dash.len() >= 2 && dash.iter().any(|v| *v > 0.0) {
|
||||||
|
c.set_dash_pattern(dash.iter().copied(), 0.0);
|
||||||
|
}
|
||||||
|
path_ops(&mut c, d);
|
||||||
|
c.stroke();
|
||||||
|
c.restore_state();
|
||||||
|
stack.last_mut().unwrap().0 = c;
|
||||||
|
}
|
||||||
|
Item::Image { asset, t, clip, clip_t, .. } => {
|
||||||
|
let Some(r) = doc.assets.get(asset) else { continue };
|
||||||
|
let (pw, ph) = (r.width as f32, r.height as f32);
|
||||||
|
let n = w.image(asset);
|
||||||
|
let c = &mut stack.last_mut().unwrap().0;
|
||||||
|
c.save_state();
|
||||||
|
let rel = match clip {
|
||||||
|
Some(cd) => {
|
||||||
|
c.transform(*clip_t);
|
||||||
|
path_ops(c, cd);
|
||||||
|
c.clip_nonzero();
|
||||||
|
c.end_path();
|
||||||
|
display::mul(display::invert(*clip_t), *t)
|
||||||
|
}
|
||||||
|
None => *t,
|
||||||
|
};
|
||||||
|
c.transform(rel);
|
||||||
|
// The image's unit square, its first row at the top (the page runs y down here).
|
||||||
|
c.transform([pw, 0.0, 0.0, -ph, 0.0, ph]);
|
||||||
|
c.x_object(Name(n.as_bytes()));
|
||||||
|
c.restore_state();
|
||||||
|
}
|
||||||
|
Item::Text { t, color, size, glyphs, .. } => {
|
||||||
|
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
|
||||||
|
c.save_state();
|
||||||
|
if color[3] < 255 {
|
||||||
|
let a = w.alpha(color[3], 255);
|
||||||
|
c.set_parameters(Name(a.as_bytes()));
|
||||||
|
}
|
||||||
|
c.transform(*t);
|
||||||
|
let (r, g, b) = rgb(*color);
|
||||||
|
c.set_fill_rgb(r, g, b);
|
||||||
|
c.begin_text();
|
||||||
|
// Runs of glyphs that share a line and a font.
|
||||||
|
let mut i = 0;
|
||||||
|
while i < glyphs.len() {
|
||||||
|
let font = glyphs[i].font;
|
||||||
|
let y = glyphs[i].y;
|
||||||
|
let mut j = i + 1;
|
||||||
|
while j < glyphs.len() && glyphs[j].font == font && glyphs[j].y == y {
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
let run = &glyphs[i..j];
|
||||||
|
let fname = w.font(font);
|
||||||
|
let f = book.font(font);
|
||||||
|
let face = ttf_parser::Face::parse(&f.data, f.index).ok();
|
||||||
|
let width_of = |gid: u16| -> f32 {
|
||||||
|
face.as_ref()
|
||||||
|
.and_then(|fc| fc.glyph_hor_advance(ttf_parser::GlyphId(gid)))
|
||||||
|
.map(|a| a as f32 * 1000.0 / f.units_per_em)
|
||||||
|
.unwrap_or(0.0)
|
||||||
|
};
|
||||||
|
let cids: Vec<u16> = {
|
||||||
|
let u = &mut w.fonts.get_mut(&font).unwrap().1;
|
||||||
|
run.iter()
|
||||||
|
.map(|g| {
|
||||||
|
let cid = if u.subset { u.remapper.remap(g.gid) } else { g.gid };
|
||||||
|
let e = u.glyphs.entry(cid).or_insert_with(|| (g.gid, String::new()));
|
||||||
|
if e.1.is_empty() {
|
||||||
|
e.1.push_str(&g.text);
|
||||||
|
}
|
||||||
|
cid
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
c.set_font(Name(fname.as_bytes()), *size);
|
||||||
|
c.set_text_matrix([1.0, 0.0, 0.0, -1.0, run[0].x, y]);
|
||||||
|
let mut items_buf: Vec<(Vec<u8>, f32)> = Vec::new();
|
||||||
|
let mut x = run[0].x;
|
||||||
|
for (k, g) in run.iter().enumerate() {
|
||||||
|
// Where the PDF would put the next glyph vs where the layout put it.
|
||||||
|
let adv = width_of(g.gid) * size / 1000.0;
|
||||||
|
let next_x = run.get(k + 1).map(|n| n.x).unwrap_or(x + adv);
|
||||||
|
let adjust = (next_x - (x + adv)) * 1000.0 / size;
|
||||||
|
items_buf.push((cids[k].to_be_bytes().to_vec(), adjust));
|
||||||
|
x = next_x;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let mut sp = c.show_positioned();
|
||||||
|
let mut its = sp.items();
|
||||||
|
for (bytes, adjust) in &items_buf {
|
||||||
|
its.show(Str(bytes));
|
||||||
|
if adjust.abs() > 0.01 {
|
||||||
|
its.adjust(-adjust);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i = j;
|
||||||
|
}
|
||||||
|
c.end_text();
|
||||||
|
c.restore_state();
|
||||||
|
stack.last_mut().unwrap().0 = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while stack.len() > 1 {
|
||||||
|
let (inner, opacity) = stack.pop().unwrap();
|
||||||
|
let r = w.alloc();
|
||||||
|
let n = format!("X{}", w.forms.len());
|
||||||
|
w.forms.push((r, n.clone(), inner.finish().to_vec()));
|
||||||
|
let a = w.alpha((opacity * 255.0).round() as u8, (opacity * 255.0).round() as u8);
|
||||||
|
let c = &mut stack.last_mut().unwrap().0;
|
||||||
|
c.save_state();
|
||||||
|
c.set_parameters(Name(a.as_bytes()));
|
||||||
|
c.x_object(Name(n.as_bytes()));
|
||||||
|
c.restore_state();
|
||||||
|
}
|
||||||
|
let page_ref = w.alloc();
|
||||||
|
let content_ref = w.alloc();
|
||||||
|
page_refs.push(page_ref);
|
||||||
|
contents.push((page_ref, content_ref, stack.pop().unwrap().0.finish().to_vec(), list.width, list.height));
|
||||||
|
}
|
||||||
|
|
||||||
|
type FontJob = (FontKey, Ref, bool, subsetter::GlyphRemapper, BTreeMap<u16, (u16, String)>);
|
||||||
|
let font_list: Vec<FontJob> =
|
||||||
|
w.fonts.iter().map(|(k, (r, u))| (*k, *r, u.subset, u.remapper.clone(), u.glyphs.clone())).collect();
|
||||||
|
for (key, type0, subset, remapper, glyphs) in font_list {
|
||||||
|
write_font(&mut w, key, type0, subset, &remapper, &glyphs)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let images: Vec<(String, Ref)> = w.images.iter().map(|(a, (r, _))| (a.clone(), *r)).collect();
|
||||||
|
for (asset, r) in images {
|
||||||
|
let raster = &doc.assets[&asset];
|
||||||
|
let mut rgb_data = Vec::with_capacity(raster.rgba.len() / 4 * 3);
|
||||||
|
let mut alpha = Vec::with_capacity(raster.rgba.len() / 4);
|
||||||
|
for p in raster.rgba.as_chunks::<4>().0 {
|
||||||
|
rgb_data.extend_from_slice(&p[..3]);
|
||||||
|
alpha.push(p[3]);
|
||||||
|
}
|
||||||
|
let has_alpha = alpha.iter().any(|a| *a < 255);
|
||||||
|
let mask_ref = has_alpha.then(|| w.alloc());
|
||||||
|
let data = deflate(&rgb_data);
|
||||||
|
let mut im = w.pdf.image_xobject(r, &data);
|
||||||
|
im.filter(Filter::FlateDecode);
|
||||||
|
im.width(raster.width as i32);
|
||||||
|
im.height(raster.height as i32);
|
||||||
|
im.color_space().device_rgb();
|
||||||
|
im.bits_per_component(8);
|
||||||
|
if let Some(m) = mask_ref {
|
||||||
|
im.s_mask(m);
|
||||||
|
}
|
||||||
|
im.finish();
|
||||||
|
if let Some(m) = mask_ref {
|
||||||
|
let data = deflate(&alpha);
|
||||||
|
let mut sm = w.pdf.image_xobject(m, &data);
|
||||||
|
sm.filter(Filter::FlateDecode);
|
||||||
|
sm.width(raster.width as i32);
|
||||||
|
sm.height(raster.height as i32);
|
||||||
|
sm.color_space().device_gray();
|
||||||
|
sm.bits_per_component(8);
|
||||||
|
sm.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let alphas: Vec<((u8, u8), Ref)> = w.alphas.iter().map(|(k, (r, _))| (*k, *r)).collect();
|
||||||
|
for ((fa, sa), r) in alphas {
|
||||||
|
w.pdf.ext_graphics(r).non_stroking_alpha(fa as f32 / 255.0).stroking_alpha(sa as f32 / 255.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let patterns = std::mem::take(&mut w.patterns);
|
||||||
|
for (r, _, p, full) in &patterns {
|
||||||
|
let shading = w.alloc();
|
||||||
|
let func = w.alloc();
|
||||||
|
let (stops, kind, coords): (&Vec<(f32, [u8; 4])>, _, Vec<f32>) = match p {
|
||||||
|
DPaint::Linear { x1, y1, x2, y2, stops } => {
|
||||||
|
(stops, pdf_writer::types::FunctionShadingType::Axial, vec![*x1, *y1, *x2, *y2])
|
||||||
|
}
|
||||||
|
DPaint::Radial { cx, cy, r, stops } => {
|
||||||
|
(stops, pdf_writer::types::FunctionShadingType::Radial, vec![*cx, *cy, 0.0, *cx, *cy, *r])
|
||||||
|
}
|
||||||
|
DPaint::Solid { .. } => continue,
|
||||||
|
};
|
||||||
|
write_stops(&mut w, func, stops);
|
||||||
|
{
|
||||||
|
let mut sh = w.pdf.function_shading(shading);
|
||||||
|
sh.shading_type(kind);
|
||||||
|
sh.color_space().device_rgb();
|
||||||
|
sh.coords(coords);
|
||||||
|
sh.function(func);
|
||||||
|
sh.extend([true, true]);
|
||||||
|
}
|
||||||
|
let mut pat = w.pdf.shading_pattern(*r);
|
||||||
|
pat.pair(Name(b"Shading"), shading);
|
||||||
|
pat.matrix(*full);
|
||||||
|
}
|
||||||
|
w.patterns = patterns;
|
||||||
|
|
||||||
|
let table = w.table();
|
||||||
|
let forms = std::mem::take(&mut w.forms);
|
||||||
|
let (pw, ph) = lists.first().map(|l| (l.width, l.height)).unwrap_or((1.0, 1.0));
|
||||||
|
for (r, _, content) in &forms {
|
||||||
|
let data = deflate(content);
|
||||||
|
let mut f = w.pdf.form_xobject(*r, &data);
|
||||||
|
f.filter(Filter::FlateDecode);
|
||||||
|
let maxw = lists.iter().map(|l| l.width).fold(pw, f32::max);
|
||||||
|
let maxh = lists.iter().map(|l| l.height).fold(ph, f32::max);
|
||||||
|
f.bbox(PRect::new(-1.0, -1.0, maxw + 1.0, maxh + 1.0));
|
||||||
|
f.group().transparency().isolated(true);
|
||||||
|
let mut res = f.resources();
|
||||||
|
write_resources(&table, &mut res);
|
||||||
|
res.finish();
|
||||||
|
f.finish();
|
||||||
|
}
|
||||||
|
w.forms = forms;
|
||||||
|
|
||||||
|
for (page_ref, content_ref, content, width, height) in &contents {
|
||||||
|
let data = deflate(content);
|
||||||
|
w.pdf.stream(*content_ref, &data).filter(Filter::FlateDecode);
|
||||||
|
let mut page = w.pdf.page(*page_ref);
|
||||||
|
page.media_box(PRect::new(0.0, 0.0, *width, *height));
|
||||||
|
page.parent(pages_id);
|
||||||
|
page.contents(*content_ref);
|
||||||
|
let mut res = page.resources();
|
||||||
|
write_resources(&table, &mut res);
|
||||||
|
res.finish();
|
||||||
|
page.finish();
|
||||||
|
}
|
||||||
|
w.pdf.pages(pages_id).kids(page_refs.iter().copied()).count(page_refs.len() as i32);
|
||||||
|
w.pdf.catalog(catalog).pages(pages_id);
|
||||||
|
let info = w.alloc();
|
||||||
|
w.pdf.document_info(info).producer(pdf_writer::TextStr("Pictor"));
|
||||||
|
Ok(w.pdf.finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_stops(w: &mut Writer, func: Ref, stops: &[(f32, [u8; 4])]) {
|
||||||
|
let col = |c: [u8; 4]| {
|
||||||
|
let (r, g, b) = rgb(c);
|
||||||
|
[r, g, b]
|
||||||
|
};
|
||||||
|
let mut stops: Vec<(f32, [u8; 4])> = stops.to_vec();
|
||||||
|
if stops.is_empty() {
|
||||||
|
stops.push((0.0, [0, 0, 0, 255]));
|
||||||
|
}
|
||||||
|
if stops.len() == 1 {
|
||||||
|
stops.push(stops[0]);
|
||||||
|
}
|
||||||
|
if stops.len() == 2 {
|
||||||
|
w.pdf.exponential_function(func).domain([0.0, 1.0]).c0(col(stops[0].1)).c1(col(stops[1].1)).n(1.0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Stitch one exponential function per pair of stops.
|
||||||
|
let mut parts = Vec::new();
|
||||||
|
for pair in stops.windows(2) {
|
||||||
|
let r = w.alloc();
|
||||||
|
w.pdf.exponential_function(r).domain([0.0, 1.0]).c0(col(pair[0].1)).c1(col(pair[1].1)).n(1.0);
|
||||||
|
parts.push(r);
|
||||||
|
}
|
||||||
|
let bounds: Vec<f32> = stops[1..stops.len() - 1].iter().map(|s| s.0).collect();
|
||||||
|
let encode: Vec<f32> = parts.iter().flat_map(|_| [0.0, 1.0]).collect();
|
||||||
|
let mut s = w.pdf.stitching_function(func);
|
||||||
|
s.domain([0.0, 1.0]);
|
||||||
|
s.functions(parts);
|
||||||
|
s.bounds(bounds);
|
||||||
|
s.encode(encode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a Type 0 font: the font program (a subset when its licence allows), its descriptor, widths and the
|
||||||
|
/// ToUnicode map. CIDs are the subset's glyph ids (or the font's own when it is embedded whole), so CIDToGIDMap is
|
||||||
|
/// the identity.
|
||||||
|
fn write_font(
|
||||||
|
w: &mut Writer,
|
||||||
|
key: FontKey,
|
||||||
|
type0: Ref,
|
||||||
|
subset: bool,
|
||||||
|
remapper: &subsetter::GlyphRemapper,
|
||||||
|
glyphs: &BTreeMap<u16, (u16, String)>,
|
||||||
|
) -> Result<(), ExportError> {
|
||||||
|
let f = w.book.font(key);
|
||||||
|
let face = ttf_parser::Face::parse(&f.data, f.index).map_err(|_| ExportError::FontBroken(f.family.clone()))?;
|
||||||
|
let program: Vec<u8> = if subset {
|
||||||
|
subsetter::subset(&f.data, f.index, remapper).map_err(|_| ExportError::FontBroken(f.family.clone()))?
|
||||||
|
} else {
|
||||||
|
f.data.to_vec()
|
||||||
|
};
|
||||||
|
let cid_ref = w.alloc();
|
||||||
|
let desc_ref = w.alloc();
|
||||||
|
let file_ref = w.alloc();
|
||||||
|
let cmap_ref = w.alloc();
|
||||||
|
// A subset tag from the glyph set, so two subsets of one font get different names.
|
||||||
|
let tag: String = {
|
||||||
|
use sha2::Digest;
|
||||||
|
let mut h = sha2::Sha256::new();
|
||||||
|
for (cid, (gid, _)) in glyphs {
|
||||||
|
h.update(cid.to_be_bytes());
|
||||||
|
h.update(gid.to_be_bytes());
|
||||||
|
}
|
||||||
|
h.update(f.post_script_name.as_bytes());
|
||||||
|
h.finalize().iter().take(6).map(|b| (b'A' + b % 26) as char).collect()
|
||||||
|
};
|
||||||
|
let ps: String = f.post_script_name.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
|
||||||
|
let ps = if ps.is_empty() { "Font".to_string() } else { ps };
|
||||||
|
let base = if subset { format!("{tag}+{ps}") } else { ps };
|
||||||
|
let s = 1000.0 / f.units_per_em;
|
||||||
|
|
||||||
|
w.pdf
|
||||||
|
.type0_font(type0)
|
||||||
|
.base_font(Name(base.as_bytes()))
|
||||||
|
.encoding_predefined(Name(b"Identity-H"))
|
||||||
|
.descendant_font(cid_ref)
|
||||||
|
.to_unicode(cmap_ref);
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut cid = w.pdf.cid_font(cid_ref);
|
||||||
|
cid.subtype(if f.cff { pdf_writer::types::CidFontType::Type0 } else { pdf_writer::types::CidFontType::Type2 });
|
||||||
|
cid.base_font(Name(base.as_bytes()));
|
||||||
|
cid.system_info(pdf_writer::types::SystemInfo {
|
||||||
|
registry: Str(b"Adobe"),
|
||||||
|
ordering: Str(b"Identity"),
|
||||||
|
supplement: 0,
|
||||||
|
});
|
||||||
|
cid.font_descriptor(desc_ref);
|
||||||
|
cid.default_width(0.0);
|
||||||
|
if !f.cff {
|
||||||
|
cid.cid_to_gid_map_predefined(Name(b"Identity"));
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let mut ws = cid.widths();
|
||||||
|
for (cid_v, (gid, _)) in glyphs {
|
||||||
|
let adv = face.glyph_hor_advance(ttf_parser::GlyphId(*gid)).unwrap_or(0) as f32 * s;
|
||||||
|
ws.consecutive(*cid_v, [adv]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cid.finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
let bbox = face.global_bounding_box();
|
||||||
|
{
|
||||||
|
let mut fd = w.pdf.font_descriptor(desc_ref);
|
||||||
|
fd.name(Name(base.as_bytes()));
|
||||||
|
let mut flags = pdf_writer::types::FontFlags::SYMBOLIC;
|
||||||
|
if f.italic {
|
||||||
|
flags |= pdf_writer::types::FontFlags::ITALIC;
|
||||||
|
}
|
||||||
|
fd.flags(flags);
|
||||||
|
fd.bbox(PRect::new(bbox.x_min as f32 * s, bbox.y_min as f32 * s, bbox.x_max as f32 * s, bbox.y_max as f32 * s));
|
||||||
|
fd.italic_angle(face.italic_angle());
|
||||||
|
fd.ascent(f.ascender * s);
|
||||||
|
fd.descent(f.descender * s);
|
||||||
|
fd.cap_height(f.cap_height * s);
|
||||||
|
fd.stem_v(80.0 + (f.weight as f32 - 400.0).max(0.0) / 5.0);
|
||||||
|
if f.cff {
|
||||||
|
fd.font_file3(file_ref);
|
||||||
|
} else {
|
||||||
|
fd.font_file2(file_ref);
|
||||||
|
}
|
||||||
|
fd.finish();
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let data = deflate(&program);
|
||||||
|
let mut st = w.pdf.stream(file_ref, &data);
|
||||||
|
st.filter(Filter::FlateDecode);
|
||||||
|
if f.cff {
|
||||||
|
st.pair(Name(b"Subtype"), Name(b"OpenType"));
|
||||||
|
} else {
|
||||||
|
st.pair(Name(b"Length1"), program.len() as i32);
|
||||||
|
}
|
||||||
|
st.finish();
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let mut cmap = pdf_writer::types::UnicodeCmap::new(
|
||||||
|
Name(b"Custom"),
|
||||||
|
pdf_writer::types::SystemInfo { registry: Str(b"Adobe"), ordering: Str(b"UCS"), supplement: 0 },
|
||||||
|
);
|
||||||
|
for (cid, (_, text)) in glyphs {
|
||||||
|
if !text.is_empty() {
|
||||||
|
cmap.pair_with_multiple(*cid, text.chars());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let data = cmap.finish();
|
||||||
|
w.pdf.cmap(cmap_ref, &data);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
//! Fixture documents: the format round trip, the undo property test, the core's renders and the app's fidelity test
|
||||||
|
//! (the face's canvas painter against the core's PNG) all use these.
|
||||||
|
use crate::model::*;
|
||||||
|
|
||||||
|
fn obj(doc: &mut Document, shape: Shape) -> Object {
|
||||||
|
Object {
|
||||||
|
id: doc.new_id(),
|
||||||
|
name: String::new(),
|
||||||
|
transform: identity(),
|
||||||
|
opacity: 1.0,
|
||||||
|
visible: true,
|
||||||
|
locked: false,
|
||||||
|
fill: None,
|
||||||
|
stroke: None,
|
||||||
|
shape,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn at(mut o: Object, x: f32, y: f32) -> Object {
|
||||||
|
o.transform[4] = x;
|
||||||
|
o.transform[5] = y;
|
||||||
|
o
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rgb(hex: &str) -> Rgba {
|
||||||
|
Rgba::hex(hex).expect("a hex colour")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A generated picture (no files): a gradient with a disc, `w` × `h`.
|
||||||
|
pub fn picture(w: u32, h: u32) -> Raster {
|
||||||
|
let mut r = Raster::new(w, h);
|
||||||
|
for y in 0..h {
|
||||||
|
for x in 0..w {
|
||||||
|
let i = ((y * w + x) * 4) as usize;
|
||||||
|
let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32);
|
||||||
|
let d = ((fx - 0.6).powi(2) + (fy - 0.4).powi(2)).sqrt();
|
||||||
|
let disc = d < 0.22;
|
||||||
|
r.rgba[i] = if disc { 242 } else { (40.0 + 180.0 * fx) as u8 };
|
||||||
|
r.rgba[i + 1] = if disc { 122 } else { (60.0 + 120.0 * fy) as u8 };
|
||||||
|
r.rgba[i + 2] = if disc { 185 } else { 150 };
|
||||||
|
r.rgba[i + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
fn vector_layer(doc: &mut Document, name: &str, objects: Vec<Object>) -> Layer {
|
||||||
|
let mut l = Layer::vector(doc.new_id(), name);
|
||||||
|
l.kind = LayerKind::Vector { objects };
|
||||||
|
l
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shapes: rounded rectangle with a stroke, an ellipse with a linear gradient, a dashed path with curves, an arrow,
|
||||||
|
/// a half-transparent group, a rotated rectangle.
|
||||||
|
pub fn shapes() -> Document {
|
||||||
|
let mut d = Document::with_page(400.0, 300.0, Some(Rgba::WHITE));
|
||||||
|
let mut r = at(obj(&mut d, Shape::Rect { w: 140.0, h: 90.0, radius: 14.0 }), 20.0, 20.0);
|
||||||
|
r.fill = Some(Paint::solid(rgb("1f2a44")));
|
||||||
|
r.stroke = Some(Stroke {
|
||||||
|
paint: Paint::solid(rgb("b08d57")),
|
||||||
|
width: 4.0,
|
||||||
|
dash: vec![],
|
||||||
|
cap: Cap::Butt,
|
||||||
|
join: Join::Round,
|
||||||
|
});
|
||||||
|
let mut e = at(obj(&mut d, Shape::Ellipse { w: 150.0, h: 100.0 }), 200.0, 20.0);
|
||||||
|
e.fill = Some(Paint::Linear {
|
||||||
|
x1: 0.0,
|
||||||
|
y1: 0.0,
|
||||||
|
x2: 1.0,
|
||||||
|
y2: 1.0,
|
||||||
|
stops: vec![Stop { offset: 0.0, color: rgb("f27ab9") }, Stop { offset: 1.0, color: rgb("d3d98f") }],
|
||||||
|
});
|
||||||
|
let mut p = at(
|
||||||
|
obj(&mut d, Shape::Path { d: "M0 60 C40 0 80 120 120 60 Q150 20 180 60 L180 90 L0 90 Z".into() }),
|
||||||
|
20.0,
|
||||||
|
150.0,
|
||||||
|
);
|
||||||
|
p.fill = Some(Paint::solid(Rgba([74, 163, 255, 160])));
|
||||||
|
p.stroke = Some(Stroke {
|
||||||
|
paint: Paint::solid(rgb("111111")),
|
||||||
|
width: 2.0,
|
||||||
|
dash: vec![8.0, 4.0],
|
||||||
|
cap: Cap::Round,
|
||||||
|
join: Join::Miter,
|
||||||
|
});
|
||||||
|
let mut a =
|
||||||
|
obj(&mut d, Shape::Line { x1: 230.0, y1: 280.0, x2: 370.0, y2: 160.0, arrow_start: false, arrow_end: true });
|
||||||
|
a.stroke = Some(Stroke {
|
||||||
|
paint: Paint::solid(rgb("ff3b3b")),
|
||||||
|
width: 5.0,
|
||||||
|
dash: vec![],
|
||||||
|
cap: Cap::Round,
|
||||||
|
join: Join::Round,
|
||||||
|
});
|
||||||
|
let mut g1 = at(obj(&mut d, Shape::Rect { w: 60.0, h: 60.0, radius: 0.0 }), 0.0, 0.0);
|
||||||
|
g1.fill = Some(Paint::solid(rgb("3ad07a")));
|
||||||
|
let mut g2 = at(obj(&mut d, Shape::Ellipse { w: 60.0, h: 60.0 }), 30.0, 20.0);
|
||||||
|
g2.fill = Some(Paint::solid(rgb("ffd23f")));
|
||||||
|
let mut g = at(obj(&mut d, Shape::Group { objects: vec![g1, g2] }), 220.0, 150.0);
|
||||||
|
g.opacity = 0.5;
|
||||||
|
let mut rot = obj(&mut d, Shape::Rect { w: 50.0, h: 30.0, radius: 4.0 });
|
||||||
|
let (s, c) = 0.5f32.sin_cos();
|
||||||
|
rot.transform = [c, s, -s, c, 330.0, 240.0];
|
||||||
|
rot.fill = Some(Paint::Radial {
|
||||||
|
cx: 0.5,
|
||||||
|
cy: 0.5,
|
||||||
|
r: 0.6,
|
||||||
|
stops: vec![Stop { offset: 0.0, color: rgb("ffffff") }, Stop { offset: 1.0, color: rgb("1f2a44") }],
|
||||||
|
});
|
||||||
|
let layer = vector_layer(&mut d, "Shapes", vec![r, e, p, a, g, rot]);
|
||||||
|
d.pages[0].layers = vec![layer];
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text: wrapped, centred, right-aligned and justified boxes, bold and italic, letter spacing, Czech letters.
|
||||||
|
pub fn text() -> Document {
|
||||||
|
let mut d = Document::with_page(420.0, 300.0, Some(Rgba::WHITE));
|
||||||
|
let style = |family: &str, weight: u16, italic: bool, size: f32, color: &str, align: Align| TextStyle {
|
||||||
|
family: family.into(),
|
||||||
|
weight,
|
||||||
|
italic,
|
||||||
|
size,
|
||||||
|
color: rgb(color),
|
||||||
|
align,
|
||||||
|
line_height: 1.25,
|
||||||
|
letter_spacing: 0.0,
|
||||||
|
};
|
||||||
|
let t1 = at(
|
||||||
|
obj(
|
||||||
|
&mut d,
|
||||||
|
Shape::Text {
|
||||||
|
w: 0.0,
|
||||||
|
text: "Monika Nováková".into(),
|
||||||
|
style: style("Georgia", 700, false, 26.0, "1f2a44", Align::Left),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
20.0,
|
||||||
|
16.0,
|
||||||
|
);
|
||||||
|
let mut s2 = style("Arial", 400, false, 9.0, "b08d57", Align::Left);
|
||||||
|
s2.letter_spacing = 2.0;
|
||||||
|
let t2 = at(obj(&mut d, Shape::Text { w: 0.0, text: "PROJEKTOVÁ MANAŽERKA".into(), style: s2 }), 22.0, 52.0);
|
||||||
|
let body = "Pictor lays text out in the core: shaping, line breaks and alignment, so the screen and the PDF agree. Příliš žluťoučký kůň úpěl ďábelské ódy.";
|
||||||
|
let t3 = at(
|
||||||
|
obj(
|
||||||
|
&mut d,
|
||||||
|
Shape::Text {
|
||||||
|
w: 180.0,
|
||||||
|
text: body.into(),
|
||||||
|
style: style("Segoe UI", 400, false, 10.0, "222222", Align::Justify),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
20.0,
|
||||||
|
80.0,
|
||||||
|
);
|
||||||
|
let t4 = at(
|
||||||
|
obj(
|
||||||
|
&mut d,
|
||||||
|
Shape::Text {
|
||||||
|
w: 180.0,
|
||||||
|
text: "Centred\nin two lines".into(),
|
||||||
|
style: style("Segoe UI", 600, false, 12.0, "1f2a44", Align::Center),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
220.0,
|
||||||
|
80.0,
|
||||||
|
);
|
||||||
|
let t5 = at(
|
||||||
|
obj(
|
||||||
|
&mut d,
|
||||||
|
Shape::Text {
|
||||||
|
w: 180.0,
|
||||||
|
text: "Right, italic".into(),
|
||||||
|
style: style("Georgia", 400, true, 12.0, "7a2e4d", Align::Right),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
220.0,
|
||||||
|
140.0,
|
||||||
|
);
|
||||||
|
let layer = vector_layer(&mut d, "Text", vec![t1, t2, t3, t4, t5]);
|
||||||
|
d.pages[0].layers = vec![layer];
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A photo-like bitmap layer at 70 % with a vector layer above (a half-transparent rectangle and an outline).
|
||||||
|
pub fn bitmap() -> Document {
|
||||||
|
let mut d = Document::from_image(picture(240, 160), "Photo");
|
||||||
|
let mut r = at(obj(&mut d, Shape::Rect { w: 100.0, h: 60.0, radius: 6.0 }), 20.0, 80.0);
|
||||||
|
r.fill = Some(Paint::solid(Rgba([255, 255, 255, 120])));
|
||||||
|
r.stroke = Some(Stroke {
|
||||||
|
paint: Paint::solid(rgb("1f2a44")),
|
||||||
|
width: 3.0,
|
||||||
|
dash: vec![],
|
||||||
|
cap: Cap::Butt,
|
||||||
|
join: Join::Miter,
|
||||||
|
});
|
||||||
|
if let LayerKind::Vector { objects } = &mut d.pages[0].layers[1].kind {
|
||||||
|
objects.push(r);
|
||||||
|
}
|
||||||
|
d.pages[0].layers[0].opacity = 0.7;
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A placed picture cropped inside its frame, with a border, over a radial gradient background shape.
|
||||||
|
pub fn image() -> Document {
|
||||||
|
let mut d = Document::with_page(300.0, 220.0, Some(Rgba::WHITE));
|
||||||
|
let asset = "i1".to_string();
|
||||||
|
d.assets.insert(asset.clone(), picture(200, 140));
|
||||||
|
let mut bg = obj(&mut d, Shape::Rect { w: 300.0, h: 220.0, radius: 0.0 });
|
||||||
|
bg.fill = Some(Paint::Radial {
|
||||||
|
cx: 0.3,
|
||||||
|
cy: 0.3,
|
||||||
|
r: 0.9,
|
||||||
|
stops: vec![
|
||||||
|
Stop { offset: 0.0, color: rgb("d3d98f") },
|
||||||
|
Stop { offset: 0.5, color: rgb("f27ab9") },
|
||||||
|
Stop { offset: 1.0, color: rgb("1f2a44") },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
let mut im = at(
|
||||||
|
obj(&mut d, Shape::Image { asset, w: 120.0, h: 120.0, crop: Rect { x: -60.0, y: -10.0, w: 200.0, h: 140.0 } }),
|
||||||
|
90.0,
|
||||||
|
50.0,
|
||||||
|
);
|
||||||
|
im.stroke = Some(Stroke {
|
||||||
|
paint: Paint::solid(rgb("ffffff")),
|
||||||
|
width: 4.0,
|
||||||
|
dash: vec![],
|
||||||
|
cap: Cap::Butt,
|
||||||
|
join: Join::Miter,
|
||||||
|
});
|
||||||
|
let layer = vector_layer(&mut d, "Picture", vec![bg, im]);
|
||||||
|
d.pages[0].layers = vec![layer];
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn all() -> Vec<(&'static str, Document)> {
|
||||||
|
vec![("shapes", shapes()), ("text", text()), ("bitmap", bitmap()), ("image", image())]
|
||||||
|
}
|
||||||
@@ -0,0 +1,448 @@
|
|||||||
|
//! The .pictor file: a zip with `document.json`, `assets/<id>.png` and `fonts/<sha256>.<ttf|otf>`
|
||||||
|
//! (docs/FORMATS.md, "The .pictor document"). Reading is strict: entries are read by known name with a size cap and
|
||||||
|
//! never extracted to disk, every name is checked, every referenced asset must be there and match its size, and a
|
||||||
|
//! newer format is refused before anything else is read.
|
||||||
|
use crate::model::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::io::{Cursor, Read, Write};
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum FormatError {
|
||||||
|
#[error("This is not a Pictor document (it is not a zip with document.json).")]
|
||||||
|
NotPictor,
|
||||||
|
#[error(
|
||||||
|
"This file was made by a newer Pictor (format {0}); this one reads format {FORMAT}. Update Pictor to open it."
|
||||||
|
)]
|
||||||
|
Newer(u32),
|
||||||
|
#[error("The document is damaged: {0}")]
|
||||||
|
Damaged(String),
|
||||||
|
#[error("The document is too large to open safely: {0}")]
|
||||||
|
TooLarge(String),
|
||||||
|
#[error("The document has an unsafe entry name: {0}")]
|
||||||
|
UnsafeName(String),
|
||||||
|
#[error("The document refers to a missing picture: {0}")]
|
||||||
|
MissingAsset(String),
|
||||||
|
#[error("Could not write the document: {0}")]
|
||||||
|
Write(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Caps for reading a .pictor from outside.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct Limits {
|
||||||
|
pub max_entries: usize,
|
||||||
|
pub max_json_bytes: u64,
|
||||||
|
pub max_entry_bytes: u64,
|
||||||
|
pub max_total_bytes: u64,
|
||||||
|
/// Uncompressed size ÷ compressed size, per entry.
|
||||||
|
pub max_ratio: u64,
|
||||||
|
pub max_pixels: u64,
|
||||||
|
pub max_total_pixels: u64,
|
||||||
|
pub max_page_side_pt: f32,
|
||||||
|
pub max_depth: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Limits {
|
||||||
|
fn default() -> Self {
|
||||||
|
Limits {
|
||||||
|
max_entries: 4096,
|
||||||
|
max_json_bytes: 64 << 20,
|
||||||
|
max_entry_bytes: 256 << 20,
|
||||||
|
max_total_bytes: 1 << 30,
|
||||||
|
max_ratio: 1000,
|
||||||
|
max_pixels: 100_000_000,
|
||||||
|
max_total_pixels: 400_000_000,
|
||||||
|
max_page_side_pt: 14_400.0,
|
||||||
|
max_depth: 32,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A font stored in a document.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct FontFile {
|
||||||
|
pub family: String,
|
||||||
|
pub weight: u16,
|
||||||
|
pub italic: bool,
|
||||||
|
pub data: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct AssetEntry {
|
||||||
|
id: String,
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct FontEntry {
|
||||||
|
family: String,
|
||||||
|
weight: u16,
|
||||||
|
italic: bool,
|
||||||
|
file: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct OnDisk {
|
||||||
|
#[serde(flatten)]
|
||||||
|
doc: Document,
|
||||||
|
#[serde(default)]
|
||||||
|
assets: Vec<AssetEntry>,
|
||||||
|
#[serde(default)]
|
||||||
|
fonts: Vec<FontEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct VersionOnly {
|
||||||
|
format: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asset ids are short letters, digits, `-` and `_` (they become file names).
|
||||||
|
pub fn valid_asset_id(id: &str) -> bool {
|
||||||
|
!id.is_empty() && id.len() <= 80 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write(doc: &Document, fonts: &[FontFile]) -> Result<Vec<u8>, FormatError> {
|
||||||
|
use sha2::Digest;
|
||||||
|
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||||
|
let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||||
|
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||||
|
let used = used_assets(doc);
|
||||||
|
let mut assets = Vec::new();
|
||||||
|
for (id, r) in &doc.assets {
|
||||||
|
if !used.contains(id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !valid_asset_id(id) {
|
||||||
|
return Err(FormatError::Write(format!("asset id {id:?}")));
|
||||||
|
}
|
||||||
|
assets.push(AssetEntry { id: id.clone(), width: r.width, height: r.height });
|
||||||
|
let png = encode_png(r)?;
|
||||||
|
zip.start_file(format!("assets/{id}.png"), stored).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||||
|
zip.write_all(&png).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||||
|
}
|
||||||
|
let mut font_entries = Vec::new();
|
||||||
|
for f in fonts {
|
||||||
|
let ext = if f.data.get(0..4) == Some(b"OTTO") { "otf" } else { "ttf" };
|
||||||
|
let hex: String = sha2::Sha256::digest(&f.data).iter().map(|b| format!("{b:02x}")).collect();
|
||||||
|
let name = format!("fonts/{hex}.{ext}");
|
||||||
|
if !font_entries.iter().any(|e: &FontEntry| e.file == name) {
|
||||||
|
zip.start_file(name.clone(), deflate).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||||
|
zip.write_all(&f.data).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||||
|
}
|
||||||
|
font_entries.push(FontEntry { family: f.family.clone(), weight: f.weight, italic: f.italic, file: name });
|
||||||
|
}
|
||||||
|
let on_disk = OnDisk { doc: doc.clone(), assets, fonts: font_entries };
|
||||||
|
let json = serde_json::to_vec(&on_disk).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||||
|
zip.start_file("document.json", deflate).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||||
|
zip.write_all(&json).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||||
|
let out = zip.finish().map_err(|e| FormatError::Write(e.to_string()))?;
|
||||||
|
Ok(out.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode_png(r: &Raster) -> Result<Vec<u8>, FormatError> {
|
||||||
|
use image::ImageEncoder;
|
||||||
|
let mut png = Vec::new();
|
||||||
|
image::codecs::png::PngEncoder::new_with_quality(
|
||||||
|
&mut png,
|
||||||
|
image::codecs::png::CompressionType::Fast,
|
||||||
|
image::codecs::png::FilterType::Adaptive,
|
||||||
|
)
|
||||||
|
.write_image(&r.rgba, r.width, r.height, image::ExtendedColorType::Rgba8)
|
||||||
|
.map_err(|e| FormatError::Write(e.to_string()))?;
|
||||||
|
Ok(png)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The asset ids the pages refer to.
|
||||||
|
pub fn used_assets(doc: &Document) -> std::collections::BTreeSet<String> {
|
||||||
|
let mut out = std::collections::BTreeSet::new();
|
||||||
|
fn objects(os: &[Object], out: &mut std::collections::BTreeSet<String>) {
|
||||||
|
for o in os {
|
||||||
|
match &o.shape {
|
||||||
|
Shape::Image { asset, .. } => {
|
||||||
|
out.insert(asset.clone());
|
||||||
|
}
|
||||||
|
Shape::Group { objects: g } => objects(g, out),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn layers(ls: &[Layer], out: &mut std::collections::BTreeSet<String>) {
|
||||||
|
for l in ls {
|
||||||
|
match &l.kind {
|
||||||
|
LayerKind::Vector { objects: os } => objects(os, out),
|
||||||
|
LayerKind::Bitmap { asset, .. } => {
|
||||||
|
out.insert(asset.clone());
|
||||||
|
}
|
||||||
|
LayerKind::Group { layers: g } => layers(g, out),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for p in &doc.pages {
|
||||||
|
layers(&p.layers, &mut out);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn safe_name(name: &str) -> bool {
|
||||||
|
!name.is_empty()
|
||||||
|
&& name.len() <= 200
|
||||||
|
&& !name.starts_with('/')
|
||||||
|
&& !name.contains('\\')
|
||||||
|
&& !name.contains(':')
|
||||||
|
&& !name.split('/').any(|part| part.is_empty() || part == ".." || part == ".")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_entry<R: Read + std::io::Seek>(
|
||||||
|
zip: &mut zip::ZipArchive<R>,
|
||||||
|
name: &str,
|
||||||
|
cap: u64,
|
||||||
|
limits: &Limits,
|
||||||
|
total: &mut u64,
|
||||||
|
) -> Result<Vec<u8>, FormatError> {
|
||||||
|
let mut f = zip.by_name(name).map_err(|_| FormatError::MissingAsset(name.to_string()))?;
|
||||||
|
let declared = f.size();
|
||||||
|
let compressed = f.compressed_size().max(1);
|
||||||
|
if declared > cap {
|
||||||
|
return Err(FormatError::TooLarge(format!("{name} is {declared} bytes")));
|
||||||
|
}
|
||||||
|
if declared / compressed > limits.max_ratio && declared > 1 << 20 {
|
||||||
|
return Err(FormatError::TooLarge(format!("{name} expands {}×", declared / compressed)));
|
||||||
|
}
|
||||||
|
let mut out = Vec::with_capacity(declared.min(cap) as usize);
|
||||||
|
(&mut f).take(cap + 1).read_to_end(&mut out).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||||
|
if out.len() as u64 > cap || out.len() as u64 != declared {
|
||||||
|
return Err(FormatError::TooLarge(format!("{name} is larger than it says")));
|
||||||
|
}
|
||||||
|
*total += out.len() as u64;
|
||||||
|
if *total > limits.max_total_bytes {
|
||||||
|
return Err(FormatError::TooLarge("the entries together".into()));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a .pictor. Fonts come back as data for the font book; the document's assets are decoded.
|
||||||
|
pub fn read(bytes: &[u8], limits: &Limits) -> Result<(Document, Vec<FontFile>), FormatError> {
|
||||||
|
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|_| FormatError::NotPictor)?;
|
||||||
|
if zip.len() > limits.max_entries {
|
||||||
|
return Err(FormatError::TooLarge(format!("{} entries", zip.len())));
|
||||||
|
}
|
||||||
|
for i in 0..zip.len() {
|
||||||
|
let f = zip.by_index_raw(i).map_err(|e| FormatError::Damaged(e.to_string()))?;
|
||||||
|
let name = f.name().to_string();
|
||||||
|
if !safe_name(&name) {
|
||||||
|
return Err(FormatError::UnsafeName(name));
|
||||||
|
}
|
||||||
|
if f.is_dir() || f.is_symlink() {
|
||||||
|
return Err(FormatError::UnsafeName(name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if zip.index_for_name("document.json").is_none() {
|
||||||
|
return Err(FormatError::NotPictor);
|
||||||
|
}
|
||||||
|
let mut total = 0u64;
|
||||||
|
let json = read_entry(&mut zip, "document.json", limits.max_json_bytes, limits, &mut total)?;
|
||||||
|
// The version first: a newer document is refused before its schema is trusted.
|
||||||
|
let v: VersionOnly =
|
||||||
|
serde_json::from_slice(&json).map_err(|e| FormatError::Damaged(format!("document.json: {e}")))?;
|
||||||
|
if v.format > FORMAT {
|
||||||
|
return Err(FormatError::Newer(v.format));
|
||||||
|
}
|
||||||
|
if v.format == 0 {
|
||||||
|
return Err(FormatError::Damaged("format 0".into()));
|
||||||
|
}
|
||||||
|
let on_disk: OnDisk =
|
||||||
|
serde_json::from_slice(&json).map_err(|e| FormatError::Damaged(format!("document.json: {e}")))?;
|
||||||
|
let mut doc = on_disk.doc;
|
||||||
|
validate(&doc, limits)?;
|
||||||
|
let used = used_assets(&doc);
|
||||||
|
let mut pixels = 0u64;
|
||||||
|
for a in &on_disk.assets {
|
||||||
|
if !valid_asset_id(&a.id) {
|
||||||
|
return Err(FormatError::UnsafeName(a.id.clone()));
|
||||||
|
}
|
||||||
|
let px = a.width as u64 * a.height as u64;
|
||||||
|
if px == 0 || px > limits.max_pixels {
|
||||||
|
return Err(FormatError::TooLarge(format!("picture {} is {}×{}", a.id, a.width, a.height)));
|
||||||
|
}
|
||||||
|
pixels += px;
|
||||||
|
if pixels > limits.max_total_pixels {
|
||||||
|
return Err(FormatError::TooLarge("the pictures together".into()));
|
||||||
|
}
|
||||||
|
let name = format!("assets/{}.png", a.id);
|
||||||
|
let png = read_entry(&mut zip, &name, limits.max_entry_bytes, limits, &mut total)?;
|
||||||
|
let raster =
|
||||||
|
decode_png(&png, a.width, a.height, limits).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||||
|
doc.assets.insert(a.id.clone(), raster);
|
||||||
|
}
|
||||||
|
for id in &used {
|
||||||
|
if !doc.assets.contains_key(id) {
|
||||||
|
return Err(FormatError::MissingAsset(id.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut fonts = Vec::new();
|
||||||
|
for f in &on_disk.fonts {
|
||||||
|
if !safe_name(&f.file) || !f.file.starts_with("fonts/") {
|
||||||
|
return Err(FormatError::UnsafeName(f.file.clone()));
|
||||||
|
}
|
||||||
|
let data = read_entry(&mut zip, &f.file, limits.max_entry_bytes, limits, &mut total)?;
|
||||||
|
if ttf_parser::Face::parse(&data, 0).is_err() {
|
||||||
|
return Err(FormatError::Damaged(format!("{} is not a font", f.file)));
|
||||||
|
}
|
||||||
|
fonts.push(FontFile { family: f.family.clone(), weight: f.weight, italic: f.italic, data });
|
||||||
|
}
|
||||||
|
Ok((doc, fonts))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decode_png(png: &[u8], width: u32, height: u32, limits: &Limits) -> Result<Raster, String> {
|
||||||
|
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
|
||||||
|
let mut l = image::Limits::default();
|
||||||
|
l.max_image_width = Some(width);
|
||||||
|
l.max_image_height = Some(height);
|
||||||
|
l.max_alloc = Some((limits.max_pixels * 8).min(u64::MAX / 2));
|
||||||
|
reader.limits(l);
|
||||||
|
let img = reader.decode().map_err(|e| e.to_string())?;
|
||||||
|
if img.width() != width || img.height() != height {
|
||||||
|
return Err(format!("is {}×{}, not {width}×{height}", img.width(), img.height()));
|
||||||
|
}
|
||||||
|
Ok(Raster { width, height, rgba: img.into_rgba8().into_raw() })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Structural checks of a parsed document: sizes, numbers, ids, paths, depth.
|
||||||
|
pub fn validate(doc: &Document, limits: &Limits) -> Result<(), FormatError> {
|
||||||
|
let bad = |s: String| Err(FormatError::Damaged(s));
|
||||||
|
if doc.pages.is_empty() {
|
||||||
|
return bad("no pages".into());
|
||||||
|
}
|
||||||
|
let mut ids = std::collections::HashSet::new();
|
||||||
|
let mut check_id = |id: Id| -> Result<(), FormatError> {
|
||||||
|
if id == 0 || id >= doc.next_id || !ids.insert(id) {
|
||||||
|
return Err(FormatError::Damaged(format!("id {id} is repeated or out of range")));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
|
let fin = |v: f32, what: &str| -> Result<(), FormatError> {
|
||||||
|
if v.is_finite() && v.abs() <= 1e6 { Ok(()) } else { Err(FormatError::Damaged(format!("{what} is {v}"))) }
|
||||||
|
};
|
||||||
|
fn obj(
|
||||||
|
o: &Object,
|
||||||
|
depth: usize,
|
||||||
|
limits: &Limits,
|
||||||
|
check_id: &mut dyn FnMut(Id) -> Result<(), FormatError>,
|
||||||
|
fin: &dyn Fn(f32, &str) -> Result<(), FormatError>,
|
||||||
|
) -> Result<(), FormatError> {
|
||||||
|
if depth > limits.max_depth {
|
||||||
|
return Err(FormatError::TooLarge("groups nested too deep".into()));
|
||||||
|
}
|
||||||
|
check_id(o.id)?;
|
||||||
|
for v in o.transform {
|
||||||
|
fin(v, "a transform")?;
|
||||||
|
}
|
||||||
|
if !(0.0..=1.0).contains(&o.opacity) {
|
||||||
|
return Err(FormatError::Damaged(format!("opacity {}", o.opacity)));
|
||||||
|
}
|
||||||
|
if let Some(s) = &o.stroke {
|
||||||
|
fin(s.width, "a stroke width")?;
|
||||||
|
if s.dash.len() > 64 {
|
||||||
|
return Err(FormatError::Damaged("a dash pattern is too long".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match &o.shape {
|
||||||
|
Shape::Rect { w, h, radius } => {
|
||||||
|
fin(*w, "a width")?;
|
||||||
|
fin(*h, "a height")?;
|
||||||
|
fin(*radius, "a radius")?
|
||||||
|
}
|
||||||
|
Shape::Ellipse { w, h } => {
|
||||||
|
fin(*w, "a width")?;
|
||||||
|
fin(*h, "a height")?
|
||||||
|
}
|
||||||
|
Shape::Line { x1, y1, x2, y2, .. } => {
|
||||||
|
for v in [x1, y1, x2, y2] {
|
||||||
|
fin(*v, "a line end")?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Shape::Path { d } => {
|
||||||
|
let segs = crate::path::parse(d).map_err(|e| FormatError::Damaged(e.to_string()))?;
|
||||||
|
if !matches!(segs.first(), None | Some(crate::path::Seg::Move(..))) {
|
||||||
|
return Err(FormatError::Damaged("a path starts with M".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Shape::Text { w, text, style } => {
|
||||||
|
fin(*w, "a text width")?;
|
||||||
|
if text.len() > 1 << 20 {
|
||||||
|
return Err(FormatError::TooLarge("a text box".into()));
|
||||||
|
}
|
||||||
|
if !(0.5..=2000.0).contains(&style.size) || !(0.5..=10.0).contains(&style.line_height) {
|
||||||
|
return Err(FormatError::Damaged("a text size".into()));
|
||||||
|
}
|
||||||
|
fin(style.letter_spacing, "letter spacing")?;
|
||||||
|
}
|
||||||
|
Shape::Image { asset, w, h, crop } => {
|
||||||
|
if !valid_asset_id(asset) {
|
||||||
|
return Err(FormatError::UnsafeName(asset.clone()));
|
||||||
|
}
|
||||||
|
for v in [w, h, &crop.x, &crop.y, &crop.w, &crop.h] {
|
||||||
|
fin(*v, "an image frame")?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Shape::Group { objects } => {
|
||||||
|
for c in objects {
|
||||||
|
obj(c, depth + 1, limits, check_id, fin)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn layers(
|
||||||
|
ls: &[Layer],
|
||||||
|
depth: usize,
|
||||||
|
limits: &Limits,
|
||||||
|
check_id: &mut dyn FnMut(Id) -> Result<(), FormatError>,
|
||||||
|
fin: &dyn Fn(f32, &str) -> Result<(), FormatError>,
|
||||||
|
) -> Result<(), FormatError> {
|
||||||
|
if depth > limits.max_depth {
|
||||||
|
return Err(FormatError::TooLarge("layers nested too deep".into()));
|
||||||
|
}
|
||||||
|
for l in ls {
|
||||||
|
check_id(l.id)?;
|
||||||
|
if !(0.0..=1.0).contains(&l.opacity) {
|
||||||
|
return Err(FormatError::Damaged(format!("opacity {}", l.opacity)));
|
||||||
|
}
|
||||||
|
match &l.kind {
|
||||||
|
LayerKind::Vector { objects } => {
|
||||||
|
for o in objects {
|
||||||
|
obj(o, depth + 1, limits, check_id, fin)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LayerKind::Bitmap { asset, x, y, w, h } => {
|
||||||
|
if !valid_asset_id(asset) {
|
||||||
|
return Err(FormatError::UnsafeName(asset.clone()));
|
||||||
|
}
|
||||||
|
for v in [x, y, w, h] {
|
||||||
|
fin(*v, "a layer's place")?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LayerKind::Group { layers: g } => layers(g, depth + 1, limits, check_id, fin)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
for p in &doc.pages {
|
||||||
|
check_id(p.id)?;
|
||||||
|
if !(p.width >= 1.0
|
||||||
|
&& p.width <= limits.max_page_side_pt
|
||||||
|
&& p.height >= 1.0
|
||||||
|
&& p.height <= limits.max_page_side_pt)
|
||||||
|
{
|
||||||
|
return bad(format!("a page is {} × {} pt", p.width, p.height));
|
||||||
|
}
|
||||||
|
for m in p.margins {
|
||||||
|
fin(m, "a margin")?;
|
||||||
|
}
|
||||||
|
if p.guides.len() > 1000 {
|
||||||
|
return bad("too many guides".into());
|
||||||
|
}
|
||||||
|
layers(&p.layers, 0, limits, &mut check_id, &fin)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
//! Pictor's document: pages of layers (vector objects, bitmaps, groups), operations with exact undo, the .pictor
|
||||||
|
//! file, text layout, the display list both painters draw, the tiny-skia render, bitmap tools, SVG import and the
|
||||||
|
//! PNG / JPG / SVG / PDF exports. Pure: no network, no processes, no registry; fonts come from the caller's font book.
|
||||||
|
pub mod bitmap;
|
||||||
|
pub mod display;
|
||||||
|
pub mod export;
|
||||||
|
pub mod fixtures;
|
||||||
|
pub mod format;
|
||||||
|
pub mod model;
|
||||||
|
pub mod ops;
|
||||||
|
pub mod path;
|
||||||
|
pub mod render;
|
||||||
|
pub mod svg;
|
||||||
|
pub mod text;
|
||||||
|
|
||||||
|
pub use format::{FontFile, FormatError, Limits};
|
||||||
|
pub use model::*;
|
||||||
|
pub use ops::{History, Op, OpError, apply};
|
||||||
|
pub use text::FontBook;
|
||||||
@@ -0,0 +1,580 @@
|
|||||||
|
//! The document: pages, layers, objects. Everything here is plain data that serialises to `document.json`
|
||||||
|
//! (docs/FORMATS.md, "The .pictor document"). Pixels live in [`Raster`] assets, outside the JSON.
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
/// The format version this code writes and the newest it reads.
|
||||||
|
pub const FORMAT: u32 = 1;
|
||||||
|
|
||||||
|
pub type Id = u64;
|
||||||
|
|
||||||
|
/// Points per millimetre (1 pt = 1/72 in).
|
||||||
|
pub const PT_PER_MM: f32 = 72.0 / 25.4;
|
||||||
|
/// A4 in points.
|
||||||
|
pub const A4: (f32, f32) = (595.276, 841.89);
|
||||||
|
/// US Letter in points.
|
||||||
|
pub const LETTER: (f32, f32) = (612.0, 792.0);
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Document {
|
||||||
|
pub format: u32,
|
||||||
|
/// The next free id for pages, layers and objects.
|
||||||
|
pub next_id: Id,
|
||||||
|
pub pages: Vec<Page>,
|
||||||
|
/// Pixels of bitmap layers and placed images, by asset id. Written as PNG files beside `document.json`.
|
||||||
|
#[serde(skip)]
|
||||||
|
pub assets: BTreeMap<String, Raster>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Straight (not premultiplied) RGBA, 8 bits per channel, rows top to bottom.
|
||||||
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
|
pub struct Raster {
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub rgba: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Raster {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "Raster({}×{})", self.width, self.height)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Raster {
|
||||||
|
pub fn new(width: u32, height: u32) -> Raster {
|
||||||
|
Raster { width, height, rgba: vec![0; width as usize * height as usize * 4] }
|
||||||
|
}
|
||||||
|
pub fn filled(width: u32, height: u32, rgba: [u8; 4]) -> Raster {
|
||||||
|
let mut r = Raster::new(width, height);
|
||||||
|
for px in r.rgba.as_chunks_mut::<4>().0 {
|
||||||
|
px.copy_from_slice(&rgba);
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
|
||||||
|
let i = (y as usize * self.width as usize + x as usize) * 4;
|
||||||
|
[self.rgba[i], self.rgba[i + 1], self.rgba[i + 2], self.rgba[i + 3]]
|
||||||
|
}
|
||||||
|
/// A copy of a rectangle (clamped to the raster).
|
||||||
|
pub fn crop(&self, r: PixelRect) -> Raster {
|
||||||
|
let r = r.clamp(self.width, self.height);
|
||||||
|
let mut out = Raster::new(r.w, r.h);
|
||||||
|
for y in 0..r.h {
|
||||||
|
let src = ((r.y + y) as usize * self.width as usize + r.x as usize) * 4;
|
||||||
|
let dst = y as usize * r.w as usize * 4;
|
||||||
|
out.rgba[dst..dst + r.w as usize * 4].copy_from_slice(&self.rgba[src..src + r.w as usize * 4]);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
/// Writes `src` at (x, y) (clamped).
|
||||||
|
pub fn put(&mut self, x: u32, y: u32, src: &Raster) {
|
||||||
|
let w = src.width.min(self.width.saturating_sub(x));
|
||||||
|
let h = src.height.min(self.height.saturating_sub(y));
|
||||||
|
for row in 0..h {
|
||||||
|
let s = row as usize * src.width as usize * 4;
|
||||||
|
let d = ((y + row) as usize * self.width as usize + x as usize) * 4;
|
||||||
|
self.rgba[d..d + w as usize * 4].copy_from_slice(&src.rgba[s..s + w as usize * 4]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A rectangle of whole pixels.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct PixelRect {
|
||||||
|
pub x: u32,
|
||||||
|
pub y: u32,
|
||||||
|
pub w: u32,
|
||||||
|
pub h: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PixelRect {
|
||||||
|
pub fn clamp(self, width: u32, height: u32) -> PixelRect {
|
||||||
|
let x = self.x.min(width);
|
||||||
|
let y = self.y.min(height);
|
||||||
|
PixelRect { x, y, w: self.w.min(width - x), h: self.h.min(height - y) }
|
||||||
|
}
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.w == 0 || self.h == 0
|
||||||
|
}
|
||||||
|
pub fn union(self, o: PixelRect) -> PixelRect {
|
||||||
|
if self.is_empty() {
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
if o.is_empty() {
|
||||||
|
return self;
|
||||||
|
}
|
||||||
|
let x0 = self.x.min(o.x);
|
||||||
|
let y0 = self.y.min(o.y);
|
||||||
|
let x1 = (self.x + self.w).max(o.x + o.w);
|
||||||
|
let y1 = (self.y + self.h).max(o.y + o.h);
|
||||||
|
PixelRect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Page {
|
||||||
|
pub id: Id,
|
||||||
|
pub width: f32,
|
||||||
|
pub height: f32,
|
||||||
|
/// Top, right, bottom, left, in points.
|
||||||
|
#[serde(default)]
|
||||||
|
pub margins: [f32; 4],
|
||||||
|
#[serde(default)]
|
||||||
|
pub guides: Vec<Guide>,
|
||||||
|
/// The paper colour; none = transparent (an image document).
|
||||||
|
#[serde(default)]
|
||||||
|
pub background: Option<Rgba>,
|
||||||
|
pub layers: Vec<Layer>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Guide {
|
||||||
|
pub vertical: bool,
|
||||||
|
pub at: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Layer {
|
||||||
|
pub id: Id,
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub visible: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub locked: bool,
|
||||||
|
#[serde(default = "one")]
|
||||||
|
pub opacity: f32,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub kind: LayerKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||||
|
pub enum LayerKind {
|
||||||
|
Vector {
|
||||||
|
objects: Vec<Object>,
|
||||||
|
},
|
||||||
|
/// Pixels (the asset, at its own size) placed on the page in the rectangle x, y, w, h (points).
|
||||||
|
Bitmap {
|
||||||
|
asset: String,
|
||||||
|
x: f32,
|
||||||
|
y: f32,
|
||||||
|
w: f32,
|
||||||
|
h: f32,
|
||||||
|
},
|
||||||
|
Group {
|
||||||
|
layers: Vec<Layer>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Object {
|
||||||
|
pub id: Id,
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
/// a b c d e f: x' = a·x + c·y + e, y' = b·x + d·y + f (the canvas and SVG order).
|
||||||
|
#[serde(default = "identity")]
|
||||||
|
pub transform: [f32; 6],
|
||||||
|
#[serde(default = "one")]
|
||||||
|
pub opacity: f32,
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub visible: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub locked: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub fill: Option<Paint>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub stroke: Option<Stroke>,
|
||||||
|
pub shape: Shape,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
|
pub enum Shape {
|
||||||
|
Rect {
|
||||||
|
w: f32,
|
||||||
|
h: f32,
|
||||||
|
#[serde(default)]
|
||||||
|
radius: f32,
|
||||||
|
},
|
||||||
|
Ellipse {
|
||||||
|
w: f32,
|
||||||
|
h: f32,
|
||||||
|
},
|
||||||
|
Line {
|
||||||
|
x1: f32,
|
||||||
|
y1: f32,
|
||||||
|
x2: f32,
|
||||||
|
y2: f32,
|
||||||
|
#[serde(default)]
|
||||||
|
arrow_start: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
arrow_end: bool,
|
||||||
|
},
|
||||||
|
/// SVG path data, absolute M L C Q Z only (`crate::path`).
|
||||||
|
Path {
|
||||||
|
d: String,
|
||||||
|
},
|
||||||
|
/// A text box `w` points wide (0 = no wrapping); its height follows from the text.
|
||||||
|
Text {
|
||||||
|
w: f32,
|
||||||
|
text: String,
|
||||||
|
style: TextStyle,
|
||||||
|
},
|
||||||
|
/// A picture in a frame `w` × `h`; `crop` is where the whole picture lies, in the frame's coordinates.
|
||||||
|
Image {
|
||||||
|
asset: String,
|
||||||
|
w: f32,
|
||||||
|
h: f32,
|
||||||
|
crop: Rect,
|
||||||
|
},
|
||||||
|
Group {
|
||||||
|
objects: Vec<Object>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Rect {
|
||||||
|
pub x: f32,
|
||||||
|
pub y: f32,
|
||||||
|
pub w: f32,
|
||||||
|
pub h: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct TextStyle {
|
||||||
|
pub family: String,
|
||||||
|
#[serde(default = "regular")]
|
||||||
|
pub weight: u16,
|
||||||
|
#[serde(default)]
|
||||||
|
pub italic: bool,
|
||||||
|
pub size: f32,
|
||||||
|
pub color: Rgba,
|
||||||
|
#[serde(default)]
|
||||||
|
pub align: Align,
|
||||||
|
/// A multiple of the size.
|
||||||
|
#[serde(default = "line_height")]
|
||||||
|
pub line_height: f32,
|
||||||
|
/// Extra space after each character, in points.
|
||||||
|
#[serde(default)]
|
||||||
|
pub letter_spacing: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Align {
|
||||||
|
#[default]
|
||||||
|
Left,
|
||||||
|
Center,
|
||||||
|
Right,
|
||||||
|
Justify,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// sRGB, straight alpha.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Rgba(pub [u8; 4]);
|
||||||
|
|
||||||
|
impl Rgba {
|
||||||
|
pub const BLACK: Rgba = Rgba([0, 0, 0, 255]);
|
||||||
|
pub const WHITE: Rgba = Rgba([255, 255, 255, 255]);
|
||||||
|
pub fn hex(s: &str) -> Option<Rgba> {
|
||||||
|
let s = s.trim_start_matches('#');
|
||||||
|
let v = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok();
|
||||||
|
match s.len() {
|
||||||
|
6 => Some(Rgba([v(0)?, v(2)?, v(4)?, 255])),
|
||||||
|
8 => Some(Rgba([v(0)?, v(2)?, v(4)?, v(6)?])),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
|
pub enum Paint {
|
||||||
|
Solid {
|
||||||
|
color: Rgba,
|
||||||
|
},
|
||||||
|
/// From (x1, y1) to (x2, y2), as fractions of the shape's box (0..1).
|
||||||
|
Linear {
|
||||||
|
x1: f32,
|
||||||
|
y1: f32,
|
||||||
|
x2: f32,
|
||||||
|
y2: f32,
|
||||||
|
stops: Vec<Stop>,
|
||||||
|
},
|
||||||
|
/// Centre and radius as fractions of the shape's box (the radius of its width).
|
||||||
|
Radial {
|
||||||
|
cx: f32,
|
||||||
|
cy: f32,
|
||||||
|
r: f32,
|
||||||
|
stops: Vec<Stop>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Paint {
|
||||||
|
pub fn solid(c: Rgba) -> Paint {
|
||||||
|
Paint::Solid { color: c }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Stop {
|
||||||
|
pub offset: f32,
|
||||||
|
pub color: Rgba,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Stroke {
|
||||||
|
pub paint: Paint,
|
||||||
|
pub width: f32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub dash: Vec<f32>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub cap: Cap,
|
||||||
|
#[serde(default)]
|
||||||
|
pub join: Join,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Cap {
|
||||||
|
#[default]
|
||||||
|
Butt,
|
||||||
|
Round,
|
||||||
|
Square,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Join {
|
||||||
|
#[default]
|
||||||
|
Miter,
|
||||||
|
Round,
|
||||||
|
Bevel,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn yes() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
fn one() -> f32 {
|
||||||
|
1.0
|
||||||
|
}
|
||||||
|
fn regular() -> u16 {
|
||||||
|
400
|
||||||
|
}
|
||||||
|
fn line_height() -> f32 {
|
||||||
|
1.2
|
||||||
|
}
|
||||||
|
pub fn identity() -> [f32; 6] {
|
||||||
|
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Document {
|
||||||
|
fn default() -> Self {
|
||||||
|
Document { format: FORMAT, next_id: 1, pages: Vec::new(), assets: BTreeMap::new() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Document {
|
||||||
|
pub fn new_id(&mut self) -> Id {
|
||||||
|
let id = self.next_id;
|
||||||
|
self.next_id += 1;
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A blank page of the given size with one empty vector layer.
|
||||||
|
pub fn with_page(width: f32, height: f32, background: Option<Rgba>) -> Document {
|
||||||
|
let mut d = Document::default();
|
||||||
|
let pid = d.new_id();
|
||||||
|
let lid = d.new_id();
|
||||||
|
d.pages.push(Page {
|
||||||
|
id: pid,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
margins: [0.0; 4],
|
||||||
|
guides: Vec::new(),
|
||||||
|
background,
|
||||||
|
layers: vec![Layer::vector(lid, "Layer 1")],
|
||||||
|
});
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An A4 page, white, with 15 mm margins.
|
||||||
|
pub fn a4() -> Document {
|
||||||
|
let mut d = Document::with_page(A4.0, A4.1, Some(Rgba::WHITE));
|
||||||
|
d.pages[0].margins = [15.0 * PT_PER_MM; 4];
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An image document: the page is the image's size (1 pt = 1 px), the image a bitmap layer, an empty vector
|
||||||
|
/// layer above it.
|
||||||
|
pub fn from_image(raster: Raster, name: &str) -> Document {
|
||||||
|
let (w, h) = (raster.width as f32, raster.height as f32);
|
||||||
|
let mut d = Document::default();
|
||||||
|
let pid = d.new_id();
|
||||||
|
let bid = d.new_id();
|
||||||
|
let vid = d.new_id();
|
||||||
|
let asset = format!("b{bid}");
|
||||||
|
d.assets.insert(asset.clone(), raster);
|
||||||
|
d.pages.push(Page {
|
||||||
|
id: pid,
|
||||||
|
width: w,
|
||||||
|
height: h,
|
||||||
|
margins: [0.0; 4],
|
||||||
|
guides: Vec::new(),
|
||||||
|
background: None,
|
||||||
|
layers: vec![
|
||||||
|
Layer {
|
||||||
|
id: bid,
|
||||||
|
name: name.to_string(),
|
||||||
|
visible: true,
|
||||||
|
locked: false,
|
||||||
|
opacity: 1.0,
|
||||||
|
kind: LayerKind::Bitmap { asset, x: 0.0, y: 0.0, w, h },
|
||||||
|
},
|
||||||
|
Layer::vector(vid, "Layer 2"),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn page(&self, id: Id) -> Option<&Page> {
|
||||||
|
self.pages.iter().find(|p| p.id == id)
|
||||||
|
}
|
||||||
|
pub fn page_mut(&mut self, id: Id) -> Option<&mut Page> {
|
||||||
|
self.pages.iter_mut().find(|p| p.id == id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Layer {
|
||||||
|
pub fn vector(id: Id, name: &str) -> Layer {
|
||||||
|
Layer {
|
||||||
|
id,
|
||||||
|
name: name.to_string(),
|
||||||
|
visible: true,
|
||||||
|
locked: false,
|
||||||
|
opacity: 1.0,
|
||||||
|
kind: LayerKind::Vector { objects: Vec::new() },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Page {
|
||||||
|
/// The layer with this id, at any depth.
|
||||||
|
pub fn layer(&self, id: Id) -> Option<&Layer> {
|
||||||
|
fn find(ls: &[Layer], id: Id) -> Option<&Layer> {
|
||||||
|
for l in ls {
|
||||||
|
if l.id == id {
|
||||||
|
return Some(l);
|
||||||
|
}
|
||||||
|
if let LayerKind::Group { layers } = &l.kind
|
||||||
|
&& let Some(f) = find(layers, id)
|
||||||
|
{
|
||||||
|
return Some(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
find(&self.layers, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The list that holds layers: the page's own (`parent` none) or a group layer's.
|
||||||
|
pub fn layer_list_mut(&mut self, parent: Option<Id>) -> Option<&mut Vec<Layer>> {
|
||||||
|
match parent {
|
||||||
|
None => Some(&mut self.layers),
|
||||||
|
Some(pid) => {
|
||||||
|
fn find(ls: &mut [Layer], id: Id) -> Option<&mut Vec<Layer>> {
|
||||||
|
for l in ls {
|
||||||
|
if let LayerKind::Group { layers } = &mut l.kind {
|
||||||
|
if l.id == id {
|
||||||
|
return Some(layers);
|
||||||
|
}
|
||||||
|
if let Some(f) = find(layers, id) {
|
||||||
|
return Some(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
find(&mut self.layers, pid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn layer_mut(&mut self, id: Id) -> Option<&mut Layer> {
|
||||||
|
fn find(ls: &mut [Layer], id: Id) -> Option<&mut Layer> {
|
||||||
|
for l in ls {
|
||||||
|
if l.id == id {
|
||||||
|
return Some(l);
|
||||||
|
}
|
||||||
|
if let LayerKind::Group { layers } = &mut l.kind
|
||||||
|
&& let Some(f) = find(layers, id)
|
||||||
|
{
|
||||||
|
return Some(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
find(&mut self.layers, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The list that holds objects: a vector layer's own (`parent` none) or a group object's.
|
||||||
|
pub fn object_list_mut(layer: &mut Layer, parent: Option<Id>) -> Option<&mut Vec<Object>> {
|
||||||
|
let LayerKind::Vector { objects } = &mut layer.kind else { return None };
|
||||||
|
match parent {
|
||||||
|
None => Some(objects),
|
||||||
|
Some(pid) => {
|
||||||
|
fn find(os: &mut [Object], id: Id) -> Option<&mut Vec<Object>> {
|
||||||
|
for o in os {
|
||||||
|
if let Shape::Group { objects } = &mut o.shape {
|
||||||
|
if o.id == id {
|
||||||
|
return Some(objects);
|
||||||
|
}
|
||||||
|
if let Some(f) = find(objects, id) {
|
||||||
|
return Some(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
find(objects, pid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The object with this id, at any depth of a vector layer.
|
||||||
|
pub fn find_object_mut(layer: &mut Layer, id: Id) -> Option<&mut Object> {
|
||||||
|
let LayerKind::Vector { objects } = &mut layer.kind else { return None };
|
||||||
|
fn find(os: &mut [Object], id: Id) -> Option<&mut Object> {
|
||||||
|
for o in os {
|
||||||
|
if o.id == id {
|
||||||
|
return Some(o);
|
||||||
|
}
|
||||||
|
if let Shape::Group { objects } = &mut o.shape
|
||||||
|
&& let Some(f) = find(objects, id)
|
||||||
|
{
|
||||||
|
return Some(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
find(objects, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find_object(layer: &Layer, id: Id) -> Option<&Object> {
|
||||||
|
let LayerKind::Vector { objects } = &layer.kind else { return None };
|
||||||
|
fn find(os: &[Object], id: Id) -> Option<&Object> {
|
||||||
|
for o in os {
|
||||||
|
if o.id == id {
|
||||||
|
return Some(o);
|
||||||
|
}
|
||||||
|
if let Shape::Group { objects } = &o.shape
|
||||||
|
&& let Some(f) = find(objects, id)
|
||||||
|
{
|
||||||
|
return Some(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
find(objects, id)
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
//! Every edit is an [`Op`]. Applying one returns its exact inverse, so undo is applying inverses back; the
|
||||||
|
//! [`History`] keeps both without a limit within a session.
|
||||||
|
use crate::model::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "op", rename_all = "snake_case")]
|
||||||
|
pub enum Op {
|
||||||
|
InsertPage {
|
||||||
|
index: usize,
|
||||||
|
page: Page,
|
||||||
|
},
|
||||||
|
RemovePage {
|
||||||
|
index: usize,
|
||||||
|
},
|
||||||
|
/// Size, margins, guides and paper colour (the layers are untouched).
|
||||||
|
SetPage {
|
||||||
|
page: Id,
|
||||||
|
width: f32,
|
||||||
|
height: f32,
|
||||||
|
margins: [f32; 4],
|
||||||
|
guides: Vec<Guide>,
|
||||||
|
background: Option<Rgba>,
|
||||||
|
},
|
||||||
|
/// Into the page's layers (`parent` none) or a group layer's, at `index`.
|
||||||
|
InsertLayer {
|
||||||
|
page: Id,
|
||||||
|
parent: Option<Id>,
|
||||||
|
index: usize,
|
||||||
|
layer: Layer,
|
||||||
|
},
|
||||||
|
RemoveLayer {
|
||||||
|
page: Id,
|
||||||
|
parent: Option<Id>,
|
||||||
|
index: usize,
|
||||||
|
},
|
||||||
|
/// Name, visibility, lock, opacity and, for a bitmap layer, its placement (not its children).
|
||||||
|
SetLayer {
|
||||||
|
page: Id,
|
||||||
|
layer: Id,
|
||||||
|
name: String,
|
||||||
|
visible: bool,
|
||||||
|
locked: bool,
|
||||||
|
opacity: f32,
|
||||||
|
place: Option<Rect>,
|
||||||
|
},
|
||||||
|
InsertObject {
|
||||||
|
page: Id,
|
||||||
|
layer: Id,
|
||||||
|
parent: Option<Id>,
|
||||||
|
index: usize,
|
||||||
|
object: Object,
|
||||||
|
},
|
||||||
|
RemoveObject {
|
||||||
|
page: Id,
|
||||||
|
layer: Id,
|
||||||
|
parent: Option<Id>,
|
||||||
|
index: usize,
|
||||||
|
},
|
||||||
|
/// The whole object with this id, replaced (a move, scale, colour or text change).
|
||||||
|
ReplaceObject {
|
||||||
|
page: Id,
|
||||||
|
layer: Id,
|
||||||
|
object: Object,
|
||||||
|
},
|
||||||
|
/// Pixels of an asset: `rect` gets `pixels` (w × h RGBA).
|
||||||
|
Patch {
|
||||||
|
asset: String,
|
||||||
|
rect: PixelRect,
|
||||||
|
#[serde(skip)]
|
||||||
|
pixels: Vec<u8>,
|
||||||
|
},
|
||||||
|
/// Adds (`raster` some), replaces or removes (none) an asset.
|
||||||
|
PutAsset {
|
||||||
|
asset: String,
|
||||||
|
#[serde(skip)]
|
||||||
|
raster: Option<Raster>,
|
||||||
|
},
|
||||||
|
Batch {
|
||||||
|
ops: Vec<Op>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||||
|
pub enum OpError {
|
||||||
|
#[error("there is no page {0}")]
|
||||||
|
NoPage(Id),
|
||||||
|
#[error("there is no layer {0}")]
|
||||||
|
NoLayer(Id),
|
||||||
|
#[error("there is no object {0}")]
|
||||||
|
NoObject(Id),
|
||||||
|
#[error("there is no asset {0}")]
|
||||||
|
NoAsset(String),
|
||||||
|
#[error("index {0} is out of range")]
|
||||||
|
Index(usize),
|
||||||
|
#[error("layer {0} does not hold objects")]
|
||||||
|
NotVector(Id),
|
||||||
|
#[error("the pixels do not fit the rectangle")]
|
||||||
|
PatchSize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies `op` and returns its inverse. On an error the document is unchanged.
|
||||||
|
pub fn apply(doc: &mut Document, op: Op) -> Result<Op, OpError> {
|
||||||
|
match op {
|
||||||
|
Op::InsertPage { index, page } => {
|
||||||
|
if index > doc.pages.len() {
|
||||||
|
return Err(OpError::Index(index));
|
||||||
|
}
|
||||||
|
doc.pages.insert(index, page);
|
||||||
|
Ok(Op::RemovePage { index })
|
||||||
|
}
|
||||||
|
Op::RemovePage { index } => {
|
||||||
|
if index >= doc.pages.len() {
|
||||||
|
return Err(OpError::Index(index));
|
||||||
|
}
|
||||||
|
let page = doc.pages.remove(index);
|
||||||
|
Ok(Op::InsertPage { index, page })
|
||||||
|
}
|
||||||
|
Op::SetPage { page, width, height, margins, guides, background } => {
|
||||||
|
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||||
|
let inv = Op::SetPage {
|
||||||
|
page,
|
||||||
|
width: p.width,
|
||||||
|
height: p.height,
|
||||||
|
margins: p.margins,
|
||||||
|
guides: std::mem::take(&mut p.guides),
|
||||||
|
background: p.background,
|
||||||
|
};
|
||||||
|
p.width = width;
|
||||||
|
p.height = height;
|
||||||
|
p.margins = margins;
|
||||||
|
p.guides = guides;
|
||||||
|
p.background = background;
|
||||||
|
Ok(inv)
|
||||||
|
}
|
||||||
|
Op::InsertLayer { page, parent, index, layer } => {
|
||||||
|
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||||
|
let list = p.layer_list_mut(parent).ok_or(OpError::NoLayer(parent.unwrap_or(0)))?;
|
||||||
|
if index > list.len() {
|
||||||
|
return Err(OpError::Index(index));
|
||||||
|
}
|
||||||
|
list.insert(index, layer);
|
||||||
|
Ok(Op::RemoveLayer { page, parent, index })
|
||||||
|
}
|
||||||
|
Op::RemoveLayer { page, parent, index } => {
|
||||||
|
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||||
|
let list = p.layer_list_mut(parent).ok_or(OpError::NoLayer(parent.unwrap_or(0)))?;
|
||||||
|
if index >= list.len() {
|
||||||
|
return Err(OpError::Index(index));
|
||||||
|
}
|
||||||
|
let layer = list.remove(index);
|
||||||
|
Ok(Op::InsertLayer { page, parent, index, layer })
|
||||||
|
}
|
||||||
|
Op::SetLayer { page, layer, name, visible, locked, opacity, place } => {
|
||||||
|
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||||
|
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||||
|
let old_place = match &mut l.kind {
|
||||||
|
LayerKind::Bitmap { x, y, w, h, .. } => {
|
||||||
|
let old = Rect { x: *x, y: *y, w: *w, h: *h };
|
||||||
|
if let Some(r) = place {
|
||||||
|
(*x, *y, *w, *h) = (r.x, r.y, r.w, r.h);
|
||||||
|
}
|
||||||
|
Some(old)
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let inv = Op::SetLayer {
|
||||||
|
page,
|
||||||
|
layer,
|
||||||
|
name: std::mem::replace(&mut l.name, name),
|
||||||
|
visible: std::mem::replace(&mut l.visible, visible),
|
||||||
|
locked: std::mem::replace(&mut l.locked, locked),
|
||||||
|
opacity: std::mem::replace(&mut l.opacity, opacity),
|
||||||
|
place: if place.is_some() { old_place } else { None },
|
||||||
|
};
|
||||||
|
Ok(inv)
|
||||||
|
}
|
||||||
|
Op::InsertObject { page, layer, parent, index, object } => {
|
||||||
|
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||||
|
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||||
|
let list = object_list_mut(l, parent).ok_or(match parent {
|
||||||
|
Some(o) => OpError::NoObject(o),
|
||||||
|
None => OpError::NotVector(layer),
|
||||||
|
})?;
|
||||||
|
if index > list.len() {
|
||||||
|
return Err(OpError::Index(index));
|
||||||
|
}
|
||||||
|
list.insert(index, object);
|
||||||
|
Ok(Op::RemoveObject { page, layer, parent, index })
|
||||||
|
}
|
||||||
|
Op::RemoveObject { page, layer, parent, index } => {
|
||||||
|
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||||
|
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||||
|
let list = object_list_mut(l, parent).ok_or(match parent {
|
||||||
|
Some(o) => OpError::NoObject(o),
|
||||||
|
None => OpError::NotVector(layer),
|
||||||
|
})?;
|
||||||
|
if index >= list.len() {
|
||||||
|
return Err(OpError::Index(index));
|
||||||
|
}
|
||||||
|
let object = list.remove(index);
|
||||||
|
Ok(Op::InsertObject { page, layer, parent, index, object })
|
||||||
|
}
|
||||||
|
Op::ReplaceObject { page, layer, object } => {
|
||||||
|
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||||
|
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||||
|
let o = find_object_mut(l, object.id).ok_or(OpError::NoObject(object.id))?;
|
||||||
|
let old = std::mem::replace(o, object);
|
||||||
|
Ok(Op::ReplaceObject { page, layer, object: old })
|
||||||
|
}
|
||||||
|
Op::Patch { asset, rect, pixels } => {
|
||||||
|
let r = doc.assets.get_mut(&asset).ok_or_else(|| OpError::NoAsset(asset.clone()))?;
|
||||||
|
if rect.clamp(r.width, r.height) != rect || pixels.len() != rect.w as usize * rect.h as usize * 4 {
|
||||||
|
return Err(OpError::PatchSize);
|
||||||
|
}
|
||||||
|
let before = r.crop(rect);
|
||||||
|
r.put(rect.x, rect.y, &Raster { width: rect.w, height: rect.h, rgba: pixels });
|
||||||
|
Ok(Op::Patch { asset, rect, pixels: before.rgba })
|
||||||
|
}
|
||||||
|
Op::PutAsset { asset, raster } => {
|
||||||
|
let old = match raster {
|
||||||
|
Some(r) => doc.assets.insert(asset.clone(), r),
|
||||||
|
None => doc.assets.remove(&asset),
|
||||||
|
};
|
||||||
|
Ok(Op::PutAsset { asset, raster: old })
|
||||||
|
}
|
||||||
|
Op::Batch { ops } => {
|
||||||
|
let mut done: Vec<Op> = Vec::with_capacity(ops.len());
|
||||||
|
for op in ops {
|
||||||
|
match apply(doc, op) {
|
||||||
|
Ok(inv) => done.push(inv),
|
||||||
|
Err(e) => {
|
||||||
|
// Roll back what was done, so a failed batch leaves no trace.
|
||||||
|
for inv in done.into_iter().rev() {
|
||||||
|
let _ = apply(doc, inv);
|
||||||
|
}
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
done.reverse();
|
||||||
|
Ok(Op::Batch { ops: done })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A patch op for the rectangle `rect` that turns `before` into `after` (both the whole asset).
|
||||||
|
pub fn patch_between(asset: &str, after: &Raster, rect: PixelRect) -> Op {
|
||||||
|
Op::Patch { asset: asset.to_string(), rect, pixels: after.crop(rect).rgba }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Done and undone operations, each with its inverse.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct History {
|
||||||
|
done: Vec<(Op, Op)>,
|
||||||
|
undone: Vec<(Op, Op)>,
|
||||||
|
/// Bumped on every change, so the face and "unsaved changes" can tell.
|
||||||
|
pub revision: u64,
|
||||||
|
saved_revision: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl History {
|
||||||
|
/// Applies an operation and records it.
|
||||||
|
pub fn apply(&mut self, doc: &mut Document, op: Op) -> Result<(), OpError> {
|
||||||
|
let inv = apply(doc, op.clone())?;
|
||||||
|
self.done.push((op, inv));
|
||||||
|
self.undone.clear();
|
||||||
|
self.revision += 1;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records an operation that was applied outside (`op` was applied, `inverse` undoes it).
|
||||||
|
pub fn record(&mut self, op: Op, inverse: Op) {
|
||||||
|
self.done.push((op, inverse));
|
||||||
|
self.undone.clear();
|
||||||
|
self.revision += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn undo(&mut self, doc: &mut Document) -> Result<bool, OpError> {
|
||||||
|
let Some((op, inv)) = self.done.pop() else { return Ok(false) };
|
||||||
|
match apply(doc, inv.clone()) {
|
||||||
|
Ok(_) => {
|
||||||
|
self.undone.push((op, inv));
|
||||||
|
self.revision += 1;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
self.done.push((op, inv));
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn redo(&mut self, doc: &mut Document) -> Result<bool, OpError> {
|
||||||
|
let Some((op, inv)) = self.undone.pop() else { return Ok(false) };
|
||||||
|
match apply(doc, op.clone()) {
|
||||||
|
Ok(_) => {
|
||||||
|
self.done.push((op, inv));
|
||||||
|
self.revision += 1;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
self.undone.push((op, inv));
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn can_undo(&self) -> bool {
|
||||||
|
!self.done.is_empty()
|
||||||
|
}
|
||||||
|
pub fn can_redo(&self) -> bool {
|
||||||
|
!self.undone.is_empty()
|
||||||
|
}
|
||||||
|
pub fn mark_saved(&mut self) {
|
||||||
|
self.saved_revision = self.revision;
|
||||||
|
}
|
||||||
|
pub fn is_dirty(&self) -> bool {
|
||||||
|
self.revision != self.saved_revision
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
//! Path data: the subset of SVG path syntax Pictor writes and reads (M L H V C Q Z, absolute or relative; numbers in
|
||||||
|
//! plain or exponent form). Parsed into absolute segments; arcs are not accepted (SVG import turns them into curves).
|
||||||
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub enum Seg {
|
||||||
|
Move(f32, f32),
|
||||||
|
Line(f32, f32),
|
||||||
|
Quad(f32, f32, f32, f32),
|
||||||
|
Cubic(f32, f32, f32, f32, f32, f32),
|
||||||
|
Close,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||||
|
#[error("path data is not understood at {at}: {why}")]
|
||||||
|
pub struct PathError {
|
||||||
|
pub at: usize,
|
||||||
|
pub why: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The most segments one path may have (a hostile document could otherwise ask for any amount of work).
|
||||||
|
pub const MAX_SEGMENTS: usize = 200_000;
|
||||||
|
|
||||||
|
pub fn parse(d: &str) -> Result<Vec<Seg>, PathError> {
|
||||||
|
let b = d.as_bytes();
|
||||||
|
let mut i = 0;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let (mut cx, mut cy, mut sx, mut sy) = (0f32, 0f32, 0f32, 0f32);
|
||||||
|
let mut cmd = 0u8;
|
||||||
|
let skip = |i: &mut usize| {
|
||||||
|
while *i < b.len() && (b[*i].is_ascii_whitespace() || b[*i] == b',') {
|
||||||
|
*i += 1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let num = |i: &mut usize| -> Result<f32, PathError> {
|
||||||
|
skip(i);
|
||||||
|
let start = *i;
|
||||||
|
if *i < b.len() && (b[*i] == b'-' || b[*i] == b'+') {
|
||||||
|
*i += 1;
|
||||||
|
}
|
||||||
|
let mut dot = false;
|
||||||
|
let mut digits = false;
|
||||||
|
while *i < b.len() && (b[*i].is_ascii_digit() || (b[*i] == b'.' && !dot)) {
|
||||||
|
if b[*i] == b'.' {
|
||||||
|
dot = true;
|
||||||
|
} else {
|
||||||
|
digits = true;
|
||||||
|
}
|
||||||
|
*i += 1;
|
||||||
|
}
|
||||||
|
if *i < b.len() && (b[*i] == b'e' || b[*i] == b'E') && digits {
|
||||||
|
*i += 1;
|
||||||
|
if *i < b.len() && (b[*i] == b'-' || b[*i] == b'+') {
|
||||||
|
*i += 1;
|
||||||
|
}
|
||||||
|
while *i < b.len() && b[*i].is_ascii_digit() {
|
||||||
|
*i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !digits {
|
||||||
|
return Err(PathError { at: start, why: "a number was expected" });
|
||||||
|
}
|
||||||
|
let v: f32 = d[start..*i].parse().map_err(|_| PathError { at: start, why: "a number was expected" })?;
|
||||||
|
if !v.is_finite() {
|
||||||
|
return Err(PathError { at: start, why: "the number is too large" });
|
||||||
|
}
|
||||||
|
Ok(v)
|
||||||
|
};
|
||||||
|
loop {
|
||||||
|
skip(&mut i);
|
||||||
|
if i >= b.len() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if b[i].is_ascii_alphabetic() {
|
||||||
|
cmd = b[i];
|
||||||
|
i += 1;
|
||||||
|
if cmd == b'Z' || cmd == b'z' {
|
||||||
|
out.push(Seg::Close);
|
||||||
|
cx = sx;
|
||||||
|
cy = sy;
|
||||||
|
cmd = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else if cmd == 0 {
|
||||||
|
return Err(PathError { at: i, why: "a command was expected" });
|
||||||
|
}
|
||||||
|
let rel = cmd.is_ascii_lowercase();
|
||||||
|
let (ox, oy) = if rel { (cx, cy) } else { (0.0, 0.0) };
|
||||||
|
match cmd.to_ascii_uppercase() {
|
||||||
|
b'M' => {
|
||||||
|
let (x, y) = (num(&mut i)? + ox, num(&mut i)? + oy);
|
||||||
|
out.push(Seg::Move(x, y));
|
||||||
|
(cx, cy, sx, sy) = (x, y, x, y);
|
||||||
|
cmd = if rel { b'l' } else { b'L' };
|
||||||
|
}
|
||||||
|
b'L' => {
|
||||||
|
let (x, y) = (num(&mut i)? + ox, num(&mut i)? + oy);
|
||||||
|
out.push(Seg::Line(x, y));
|
||||||
|
(cx, cy) = (x, y);
|
||||||
|
}
|
||||||
|
b'H' => {
|
||||||
|
let x = num(&mut i)? + ox;
|
||||||
|
out.push(Seg::Line(x, cy));
|
||||||
|
cx = x;
|
||||||
|
}
|
||||||
|
b'V' => {
|
||||||
|
let y = num(&mut i)? + oy;
|
||||||
|
out.push(Seg::Line(cx, y));
|
||||||
|
cy = y;
|
||||||
|
}
|
||||||
|
b'C' => {
|
||||||
|
let v = [num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?];
|
||||||
|
let s = Seg::Cubic(v[0] + ox, v[1] + oy, v[2] + ox, v[3] + oy, v[4] + ox, v[5] + oy);
|
||||||
|
out.push(s);
|
||||||
|
(cx, cy) = (v[4] + ox, v[5] + oy);
|
||||||
|
}
|
||||||
|
b'Q' => {
|
||||||
|
let v = [num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?];
|
||||||
|
out.push(Seg::Quad(v[0] + ox, v[1] + oy, v[2] + ox, v[3] + oy));
|
||||||
|
(cx, cy) = (v[2] + ox, v[3] + oy);
|
||||||
|
}
|
||||||
|
_ => return Err(PathError { at: i.saturating_sub(1), why: "only M L H V C Q Z are allowed" }),
|
||||||
|
}
|
||||||
|
if out.len() > MAX_SEGMENTS {
|
||||||
|
return Err(PathError { at: i, why: "the path has too many segments" });
|
||||||
|
}
|
||||||
|
if !matches!(out.first(), Some(Seg::Move(..))) {
|
||||||
|
return Err(PathError { at: 0, why: "a path starts with M" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes segments as compact absolute path data.
|
||||||
|
pub fn write(segs: &[Seg]) -> String {
|
||||||
|
let mut s = String::new();
|
||||||
|
let n = |v: f32| -> String {
|
||||||
|
let r = (v * 1000.0).round() / 1000.0;
|
||||||
|
if r == r.trunc() { format!("{}", r as i64) } else { format!("{r}") }
|
||||||
|
};
|
||||||
|
for seg in segs {
|
||||||
|
if !s.is_empty() {
|
||||||
|
s.push(' ');
|
||||||
|
}
|
||||||
|
let _ = match *seg {
|
||||||
|
Seg::Move(x, y) => write!(s, "M{} {}", n(x), n(y)),
|
||||||
|
Seg::Line(x, y) => write!(s, "L{} {}", n(x), n(y)),
|
||||||
|
Seg::Quad(a, b, x, y) => write!(s, "Q{} {} {} {}", n(a), n(b), n(x), n(y)),
|
||||||
|
Seg::Cubic(a, b, c, d, x, y) => write!(s, "C{} {} {} {} {} {}", n(a), n(b), n(c), n(d), n(x), n(y)),
|
||||||
|
Seg::Close => write!(s, "Z"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The control-point box (contains the curve).
|
||||||
|
pub fn bounds(segs: &[Seg]) -> Option<[f32; 4]> {
|
||||||
|
let mut b: Option<[f32; 4]> = None;
|
||||||
|
let mut add = |x: f32, y: f32| {
|
||||||
|
b = Some(match b {
|
||||||
|
None => [x, y, x, y],
|
||||||
|
Some([a, c, d, e]) => [a.min(x), c.min(y), d.max(x), e.max(y)],
|
||||||
|
})
|
||||||
|
};
|
||||||
|
for s in segs {
|
||||||
|
match *s {
|
||||||
|
Seg::Move(x, y) | Seg::Line(x, y) => add(x, y),
|
||||||
|
Seg::Quad(a, c, x, y) => {
|
||||||
|
add(a, c);
|
||||||
|
add(x, y)
|
||||||
|
}
|
||||||
|
Seg::Cubic(a, c, d, e, x, y) => {
|
||||||
|
add(a, c);
|
||||||
|
add(d, e);
|
||||||
|
add(x, y)
|
||||||
|
}
|
||||||
|
Seg::Close => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_skia(segs: &[Seg]) -> Option<tiny_skia::Path> {
|
||||||
|
let mut pb = tiny_skia::PathBuilder::new();
|
||||||
|
for s in segs {
|
||||||
|
match *s {
|
||||||
|
Seg::Move(x, y) => pb.move_to(x, y),
|
||||||
|
Seg::Line(x, y) => pb.line_to(x, y),
|
||||||
|
Seg::Quad(a, b, x, y) => pb.quad_to(a, b, x, y),
|
||||||
|
Seg::Cubic(a, b, c, d, x, y) => pb.cubic_to(a, b, c, d, x, y),
|
||||||
|
Seg::Close => pb.close(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pb.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bézier constant for a quarter circle.
|
||||||
|
const K: f32 = 0.552_284_8;
|
||||||
|
|
||||||
|
pub fn rect(w: f32, h: f32, radius: f32) -> Vec<Seg> {
|
||||||
|
let r = radius.max(0.0).min(w.abs() / 2.0).min(h.abs() / 2.0);
|
||||||
|
if r <= 0.0 {
|
||||||
|
return vec![Seg::Move(0.0, 0.0), Seg::Line(w, 0.0), Seg::Line(w, h), Seg::Line(0.0, h), Seg::Close];
|
||||||
|
}
|
||||||
|
let k = r * (1.0 - K);
|
||||||
|
vec![
|
||||||
|
Seg::Move(r, 0.0),
|
||||||
|
Seg::Line(w - r, 0.0),
|
||||||
|
Seg::Cubic(w - k, 0.0, w, k, w, r),
|
||||||
|
Seg::Line(w, h - r),
|
||||||
|
Seg::Cubic(w, h - k, w - k, h, w - r, h),
|
||||||
|
Seg::Line(r, h),
|
||||||
|
Seg::Cubic(k, h, 0.0, h - k, 0.0, h - r),
|
||||||
|
Seg::Line(0.0, r),
|
||||||
|
Seg::Cubic(0.0, k, k, 0.0, r, 0.0),
|
||||||
|
Seg::Close,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ellipse(w: f32, h: f32) -> Vec<Seg> {
|
||||||
|
let (rx, ry) = (w / 2.0, h / 2.0);
|
||||||
|
let (cx, cy) = (rx, ry);
|
||||||
|
let (kx, ky) = (rx * K, ry * K);
|
||||||
|
vec![
|
||||||
|
Seg::Move(cx + rx, cy),
|
||||||
|
Seg::Cubic(cx + rx, cy + ky, cx + kx, cy + ry, cx, cy + ry),
|
||||||
|
Seg::Cubic(cx - kx, cy + ry, cx - rx, cy + ky, cx - rx, cy),
|
||||||
|
Seg::Cubic(cx - rx, cy - ky, cx - kx, cy - ry, cx, cy - ry),
|
||||||
|
Seg::Cubic(cx + kx, cy - ry, cx + rx, cy - ky, cx + rx, cy),
|
||||||
|
Seg::Close,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An arrow head at (x2, y2) pointing away from (x1, y1), for a line of width `w`.
|
||||||
|
pub fn arrow_head(x1: f32, y1: f32, x2: f32, y2: f32, w: f32) -> Vec<Seg> {
|
||||||
|
let (dx, dy) = (x2 - x1, y2 - y1);
|
||||||
|
let len = (dx * dx + dy * dy).sqrt().max(1e-3);
|
||||||
|
let (ux, uy) = (dx / len, dy / len);
|
||||||
|
let size = (w * 4.0).max(8.0);
|
||||||
|
let (bx, by) = (x2 - ux * size, y2 - uy * size);
|
||||||
|
let (px, py) = (-uy * size * 0.5, ux * size * 0.5);
|
||||||
|
vec![Seg::Move(x2, y2), Seg::Line(bx + px, by + py), Seg::Line(bx - px, by - py), Seg::Close]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a line meets its arrow head (so the stroke stops under the head instead of poking through its tip).
|
||||||
|
pub fn shorten(x1: f32, y1: f32, x2: f32, y2: f32, w: f32) -> (f32, f32) {
|
||||||
|
let (dx, dy) = (x2 - x1, y2 - y1);
|
||||||
|
let len = (dx * dx + dy * dy).sqrt().max(1e-3);
|
||||||
|
let size = (w * 4.0).max(8.0) * 0.8;
|
||||||
|
let t = (size / len).min(1.0);
|
||||||
|
(x2 - dx * t, y2 - dy * t)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_relative_and_writes_absolute() {
|
||||||
|
let s = parse("m10 10 l5 0 h5 v-5 c1 1 2 2 3 3 q1 1 2 2 z").unwrap();
|
||||||
|
assert_eq!(s[0], Seg::Move(10.0, 10.0));
|
||||||
|
assert_eq!(s[1], Seg::Line(15.0, 10.0));
|
||||||
|
assert_eq!(s[2], Seg::Line(20.0, 10.0));
|
||||||
|
assert_eq!(s[3], Seg::Line(20.0, 5.0));
|
||||||
|
assert_eq!(s[4], Seg::Cubic(21.0, 6.0, 22.0, 7.0, 23.0, 8.0));
|
||||||
|
assert_eq!(write(&parse(&write(&s)).unwrap()), write(&s));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refuses_arcs_garbage_and_huge_numbers() {
|
||||||
|
assert!(parse("M0 0 A 5 5 0 0 1 10 10").is_err());
|
||||||
|
assert!(parse("M0 0 L x 1").is_err());
|
||||||
|
assert!(parse("L 1 1").is_err());
|
||||||
|
assert!(parse("M 1e39 0").is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
//! The core's painter: a display list to pixels with tiny-skia (PNG and JPG export, thumbnails, the fidelity
|
||||||
|
//! reference). The face's canvas painter (`apps/desktop/src/editor/paint.ts`) follows the same rules.
|
||||||
|
use crate::display::*;
|
||||||
|
use crate::model::*;
|
||||||
|
use crate::path;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use tiny_skia as sk;
|
||||||
|
|
||||||
|
fn tf(t: Tf) -> sk::Transform {
|
||||||
|
sk::Transform::from_row(t[0], t[1], t[2], t[3], t[4], t[5])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color(c: [u8; 4]) -> sk::Color {
|
||||||
|
sk::Color::from_rgba8(c[0], c[1], c[2], c[3])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shader(p: &DPaint) -> Option<sk::Shader<'static>> {
|
||||||
|
let stops = |s: &[(f32, [u8; 4])]| s.iter().map(|(o, c)| sk::GradientStop::new(*o, color(*c))).collect::<Vec<_>>();
|
||||||
|
match p {
|
||||||
|
DPaint::Solid { c } => Some(sk::Shader::SolidColor(color(*c))),
|
||||||
|
DPaint::Linear { x1, y1, x2, y2, stops: s } => sk::LinearGradient::new(
|
||||||
|
sk::Point::from_xy(*x1, *y1),
|
||||||
|
sk::Point::from_xy(*x2, *y2),
|
||||||
|
stops(s),
|
||||||
|
sk::SpreadMode::Pad,
|
||||||
|
sk::Transform::identity(),
|
||||||
|
)
|
||||||
|
.or_else(|| s.last().map(|(_, c)| sk::Shader::SolidColor(color(*c)))),
|
||||||
|
DPaint::Radial { cx, cy, r, stops: s } => sk::RadialGradient::new(
|
||||||
|
sk::Point::from_xy(*cx, *cy),
|
||||||
|
0.0,
|
||||||
|
sk::Point::from_xy(*cx, *cy),
|
||||||
|
*r,
|
||||||
|
stops(s),
|
||||||
|
sk::SpreadMode::Pad,
|
||||||
|
sk::Transform::identity(),
|
||||||
|
)
|
||||||
|
.or_else(|| s.last().map(|(_, c)| sk::Shader::SolidColor(color(*c)))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Straight RGBA → a premultiplied pixmap.
|
||||||
|
pub fn pixmap_of(r: &Raster) -> Option<sk::Pixmap> {
|
||||||
|
let mut pm = sk::Pixmap::new(r.width, r.height)?;
|
||||||
|
for (dst, src) in pm.pixels_mut().iter_mut().zip(r.rgba.as_chunks::<4>().0) {
|
||||||
|
*dst = sk::ColorU8::from_rgba(src[0], src[1], src[2], src[3]).premultiply();
|
||||||
|
}
|
||||||
|
Some(pm)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A premultiplied pixmap → straight RGBA.
|
||||||
|
pub fn raster_of(pm: &sk::Pixmap) -> Raster {
|
||||||
|
let mut rgba = Vec::with_capacity(pm.data().len());
|
||||||
|
for p in pm.pixels() {
|
||||||
|
let c = p.demultiply();
|
||||||
|
rgba.extend_from_slice(&[c.red(), c.green(), c.blue(), c.alpha()]);
|
||||||
|
}
|
||||||
|
Raster { width: pm.width(), height: pm.height(), rgba }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paints a display list at `scale` pixels per point. `assets` are the document's pixels.
|
||||||
|
pub fn paint(
|
||||||
|
list: &DisplayList,
|
||||||
|
assets: &std::collections::BTreeMap<String, Raster>,
|
||||||
|
scale: f32,
|
||||||
|
) -> Option<sk::Pixmap> {
|
||||||
|
let w = (list.width * scale).round().max(1.0) as u32;
|
||||||
|
let h = (list.height * scale).round().max(1.0) as u32;
|
||||||
|
let mut stack: Vec<(sk::Pixmap, f32)> = vec![(sk::Pixmap::new(w, h)?, 1.0)];
|
||||||
|
if let Some(bg) = list.background {
|
||||||
|
stack[0].0.fill(color(bg));
|
||||||
|
}
|
||||||
|
let base: Tf = [scale, 0.0, 0.0, scale, 0.0, 0.0];
|
||||||
|
let mut images: HashMap<&str, sk::Pixmap> = HashMap::new();
|
||||||
|
let glyph_paths: Vec<Option<sk::Path>> =
|
||||||
|
list.glyphs.iter().map(|g| path::parse(&g.d).ok().and_then(|s| path::to_skia(&s))).collect();
|
||||||
|
for item in &list.items {
|
||||||
|
match item {
|
||||||
|
Item::Push { opacity } => stack.push((sk::Pixmap::new(w, h)?, *opacity)),
|
||||||
|
Item::Pop => {
|
||||||
|
if stack.len() > 1 {
|
||||||
|
let (top, opacity) = stack.pop()?;
|
||||||
|
let pp = sk::PixmapPaint { opacity, ..Default::default() };
|
||||||
|
stack.last_mut()?.0.draw_pixmap(0, 0, top.as_ref(), &pp, sk::Transform::identity(), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Item::Fill { d, t, paint, even_odd, .. } => {
|
||||||
|
let Some(p) = path::parse(d).ok().and_then(|s| path::to_skia(&s)) else { continue };
|
||||||
|
let Some(sh) = shader(paint) else { continue };
|
||||||
|
let pt = sk::Paint { shader: sh, anti_alias: true, ..Default::default() };
|
||||||
|
let rule = if *even_odd { sk::FillRule::EvenOdd } else { sk::FillRule::Winding };
|
||||||
|
stack.last_mut()?.0.fill_path(&p, &pt, rule, tf(mul(base, *t)), None);
|
||||||
|
}
|
||||||
|
Item::Stroke { d, t, paint, width, cap, join, dash, .. } => {
|
||||||
|
let Some(p) = path::parse(d).ok().and_then(|s| path::to_skia(&s)) else { continue };
|
||||||
|
let Some(sh) = shader(paint) else { continue };
|
||||||
|
let pt = sk::Paint { shader: sh, anti_alias: true, ..Default::default() };
|
||||||
|
let stroke = sk::Stroke {
|
||||||
|
width: *width,
|
||||||
|
line_cap: match cap {
|
||||||
|
Cap::Butt => sk::LineCap::Butt,
|
||||||
|
Cap::Round => sk::LineCap::Round,
|
||||||
|
Cap::Square => sk::LineCap::Square,
|
||||||
|
},
|
||||||
|
line_join: match join {
|
||||||
|
Join::Miter => sk::LineJoin::Miter,
|
||||||
|
Join::Round => sk::LineJoin::Round,
|
||||||
|
Join::Bevel => sk::LineJoin::Bevel,
|
||||||
|
},
|
||||||
|
miter_limit: 10.0,
|
||||||
|
dash: if dash.len() >= 2 && dash.iter().all(|v| *v >= 0.0) && dash.iter().any(|v| *v > 0.0) {
|
||||||
|
let mut d = dash.clone();
|
||||||
|
if d.len() % 2 == 1 {
|
||||||
|
d.extend_from_within(..);
|
||||||
|
}
|
||||||
|
sk::StrokeDash::new(d, 0.0)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
},
|
||||||
|
};
|
||||||
|
stack.last_mut()?.0.stroke_path(&p, &pt, &stroke, tf(mul(base, *t)), None);
|
||||||
|
}
|
||||||
|
Item::Image { asset, t, clip, clip_t, smooth, .. } => {
|
||||||
|
let Some(r) = assets.get(asset) else { continue };
|
||||||
|
if !images.contains_key(asset.as_str()) {
|
||||||
|
images.insert(asset.as_str(), pixmap_of(r)?);
|
||||||
|
}
|
||||||
|
let img = &images[asset.as_str()];
|
||||||
|
let full = mul(base, *t);
|
||||||
|
let exact = !*smooth
|
||||||
|
&& full[1] == 0.0
|
||||||
|
&& full[2] == 0.0
|
||||||
|
&& (full[0] - 1.0).abs() < 1e-4
|
||||||
|
&& (full[3] - 1.0).abs() < 1e-4;
|
||||||
|
let quality = if exact { sk::FilterQuality::Nearest } else { sk::FilterQuality::Bilinear };
|
||||||
|
let mask = match clip {
|
||||||
|
Some(cd) => {
|
||||||
|
let Some(cp) = path::parse(cd).ok().and_then(|s| path::to_skia(&s)) else { continue };
|
||||||
|
let mut m = sk::Mask::new(w, h)?;
|
||||||
|
m.fill_path(&cp, sk::FillRule::Winding, true, tf(mul(base, *clip_t)));
|
||||||
|
Some(m)
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let pt = sk::Paint {
|
||||||
|
shader: sk::Pattern::new(
|
||||||
|
img.as_ref(),
|
||||||
|
sk::SpreadMode::Pad,
|
||||||
|
quality,
|
||||||
|
1.0,
|
||||||
|
sk::Transform::identity(),
|
||||||
|
),
|
||||||
|
anti_alias: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let rect = sk::Rect::from_xywh(0.0, 0.0, img.width() as f32, img.height() as f32)?;
|
||||||
|
stack.last_mut()?.0.fill_rect(rect, &pt, tf(full), mask.as_ref());
|
||||||
|
}
|
||||||
|
Item::Text { t, color: c, size, glyphs, .. } => {
|
||||||
|
let pt =
|
||||||
|
sk::Paint { shader: sk::Shader::SolidColor(color(*c)), anti_alias: true, ..Default::default() };
|
||||||
|
for g in glyphs {
|
||||||
|
let Some(gi) = g.g else { continue };
|
||||||
|
let Some(Some(p)) = glyph_paths.get(gi as usize) else { continue };
|
||||||
|
let upem = list.glyphs[gi as usize].upem;
|
||||||
|
let s = size / upem;
|
||||||
|
let gt = mul(base, mul(*t, [s, 0.0, 0.0, -s, g.x, g.y]));
|
||||||
|
stack.last_mut()?.0.fill_path(p, &pt, sk::FillRule::Winding, tf(gt), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while stack.len() > 1 {
|
||||||
|
let (top, opacity) = stack.pop()?;
|
||||||
|
let pp = sk::PixmapPaint { opacity, ..Default::default() };
|
||||||
|
stack.last_mut()?.0.draw_pixmap(0, 0, top.as_ref(), &pp, sk::Transform::identity(), None);
|
||||||
|
}
|
||||||
|
stack.pop().map(|(p, _)| p)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page rendered to straight RGBA at `scale` pixels per point.
|
||||||
|
pub fn page(doc: &Document, page: &Page, book: &crate::text::FontBook, scale: f32) -> Option<Raster> {
|
||||||
|
let list = build(doc, page, book);
|
||||||
|
paint(&list, &doc.assets, scale).map(|p| raster_of(&p))
|
||||||
|
}
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
//! SVG import with usvg: paths (with their fills, strokes and gradients), images and text (as outlines) become vector
|
||||||
|
//! objects in one group, scaled from CSS pixels to points. Runs in the worker: an SVG is an outside file.
|
||||||
|
use crate::model::*;
|
||||||
|
use crate::path::{self, Seg};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum SvgError {
|
||||||
|
#[error("This SVG could not be read: {0}")]
|
||||||
|
Parse(String),
|
||||||
|
#[error("This SVG is too large to import.")]
|
||||||
|
TooLarge,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The most objects one import makes.
|
||||||
|
const MAX_OBJECTS: usize = 50_000;
|
||||||
|
|
||||||
|
struct Ctx {
|
||||||
|
doc: Document,
|
||||||
|
count: usize,
|
||||||
|
images: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rgba(c: usvg::Color, opacity: f32) -> Rgba {
|
||||||
|
Rgba([c.red, c.green, c.blue, (opacity.clamp(0.0, 1.0) * 255.0).round() as u8])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn paint(p: &usvg::Paint, opacity: f32, ts: tiny_skia::Transform, bbox: [f32; 4]) -> Option<Paint> {
|
||||||
|
let [bx, by, bw, bh] = bbox;
|
||||||
|
let frac = |x: f32, y: f32| -> (f32, f32) {
|
||||||
|
let mut pt = tiny_skia::Point::from_xy(x, y);
|
||||||
|
ts.map_point(&mut pt);
|
||||||
|
((pt.x - bx) / bw.max(1e-3), (pt.y - by) / bh.max(1e-3))
|
||||||
|
};
|
||||||
|
let stops = |s: &[usvg::Stop]| {
|
||||||
|
s.iter()
|
||||||
|
.map(|s| Stop { offset: s.offset().get(), color: rgba(s.color(), s.opacity().get() * opacity) })
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
match p {
|
||||||
|
usvg::Paint::Color(c) => Some(Paint::Solid { color: rgba(*c, opacity) }),
|
||||||
|
usvg::Paint::LinearGradient(g) => {
|
||||||
|
let t = ts.pre_concat(g.transform());
|
||||||
|
let frac = |x: f32, y: f32| {
|
||||||
|
let mut pt = tiny_skia::Point::from_xy(x, y);
|
||||||
|
t.map_point(&mut pt);
|
||||||
|
((pt.x - bx) / bw.max(1e-3), (pt.y - by) / bh.max(1e-3))
|
||||||
|
};
|
||||||
|
let (x1, y1) = frac(g.x1(), g.y1());
|
||||||
|
let (x2, y2) = frac(g.x2(), g.y2());
|
||||||
|
Some(Paint::Linear { x1, y1, x2, y2, stops: stops(g.stops()) })
|
||||||
|
}
|
||||||
|
usvg::Paint::RadialGradient(g) => {
|
||||||
|
let t = ts.pre_concat(g.transform());
|
||||||
|
let mut c = tiny_skia::Point::from_xy(g.cx(), g.cy());
|
||||||
|
t.map_point(&mut c);
|
||||||
|
let (sx, sy) = t.get_scale();
|
||||||
|
let r = g.r().get() * sx.max(sy);
|
||||||
|
let _ = frac;
|
||||||
|
Some(Paint::Radial {
|
||||||
|
cx: (c.x - bx) / bw.max(1e-3),
|
||||||
|
cy: (c.y - by) / bh.max(1e-3),
|
||||||
|
r: r / bw.abs().max(bh.abs()).max(1e-3),
|
||||||
|
stops: stops(g.stops()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// Patterns are not kept: their first colour stands in.
|
||||||
|
usvg::Paint::Pattern(_) => Some(Paint::Solid { color: Rgba([128, 128, 128, (opacity * 255.0) as u8]) }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object(ctx: &mut Ctx, shape: Shape) -> Object {
|
||||||
|
Object {
|
||||||
|
id: ctx.doc.new_id(),
|
||||||
|
name: String::new(),
|
||||||
|
transform: identity(),
|
||||||
|
opacity: 1.0,
|
||||||
|
visible: true,
|
||||||
|
locked: false,
|
||||||
|
fill: None,
|
||||||
|
stroke: None,
|
||||||
|
shape,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn group(ctx: &mut Ctx, g: &usvg::Group, out: &mut Vec<Object>) -> Result<(), SvgError> {
|
||||||
|
for node in g.children() {
|
||||||
|
ctx.count += 1;
|
||||||
|
if ctx.count > MAX_OBJECTS {
|
||||||
|
return Err(SvgError::TooLarge);
|
||||||
|
}
|
||||||
|
match node {
|
||||||
|
usvg::Node::Group(child) => {
|
||||||
|
if child.opacity().get() < 0.999 {
|
||||||
|
let mut inner = Vec::new();
|
||||||
|
group(ctx, child, &mut inner)?;
|
||||||
|
let mut o = object(ctx, Shape::Group { objects: inner });
|
||||||
|
o.opacity = child.opacity().get();
|
||||||
|
out.push(o);
|
||||||
|
} else {
|
||||||
|
group(ctx, child, out)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
usvg::Node::Path(p) => {
|
||||||
|
if !p.is_visible() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let ts = p.abs_transform();
|
||||||
|
let mut segs = Vec::new();
|
||||||
|
for s in p.data().segments() {
|
||||||
|
let map = |pt: tiny_skia::Point| {
|
||||||
|
let mut q = pt;
|
||||||
|
ts.map_point(&mut q);
|
||||||
|
(q.x, q.y)
|
||||||
|
};
|
||||||
|
segs.push(match s {
|
||||||
|
tiny_skia::PathSegment::MoveTo(a) => {
|
||||||
|
let (x, y) = map(a);
|
||||||
|
Seg::Move(x, y)
|
||||||
|
}
|
||||||
|
tiny_skia::PathSegment::LineTo(a) => {
|
||||||
|
let (x, y) = map(a);
|
||||||
|
Seg::Line(x, y)
|
||||||
|
}
|
||||||
|
tiny_skia::PathSegment::QuadTo(a, b) => {
|
||||||
|
let ((ax, ay), (x, y)) = (map(a), map(b));
|
||||||
|
Seg::Quad(ax, ay, x, y)
|
||||||
|
}
|
||||||
|
tiny_skia::PathSegment::CubicTo(a, b, c) => {
|
||||||
|
let ((ax, ay), (bx, by), (x, y)) = (map(a), map(b), map(c));
|
||||||
|
Seg::Cubic(ax, ay, bx, by, x, y)
|
||||||
|
}
|
||||||
|
tiny_skia::PathSegment::Close => Seg::Close,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let Some(b) = path::bounds(&segs) else { continue };
|
||||||
|
let bbox = [b[0], b[1], b[2] - b[0], b[3] - b[1]];
|
||||||
|
let mut o = object(ctx, Shape::Path { d: path::write(&segs) });
|
||||||
|
if let Some(f) = p.fill() {
|
||||||
|
o.fill = paint(f.paint(), f.opacity().get(), ts, bbox);
|
||||||
|
}
|
||||||
|
if let Some(s) = p.stroke() {
|
||||||
|
let (sx, sy) = ts.get_scale();
|
||||||
|
let k = (sx * sy).abs().sqrt();
|
||||||
|
o.stroke = paint(s.paint(), s.opacity().get(), ts, bbox).map(|pt| Stroke {
|
||||||
|
paint: pt,
|
||||||
|
width: s.width().get() * k,
|
||||||
|
dash: s.dasharray().map(|d| d.iter().map(|v| v * k).collect()).unwrap_or_default(),
|
||||||
|
cap: match s.linecap() {
|
||||||
|
usvg::LineCap::Butt => Cap::Butt,
|
||||||
|
usvg::LineCap::Round => Cap::Round,
|
||||||
|
usvg::LineCap::Square => Cap::Square,
|
||||||
|
},
|
||||||
|
join: match s.linejoin() {
|
||||||
|
usvg::LineJoin::Round => Join::Round,
|
||||||
|
usvg::LineJoin::Bevel => Join::Bevel,
|
||||||
|
_ => Join::Miter,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if o.fill.is_some() || o.stroke.is_some() {
|
||||||
|
out.push(o);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
usvg::Node::Image(im) => {
|
||||||
|
if !im.is_visible() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let data: Option<&Arc<Vec<u8>>> = match im.kind() {
|
||||||
|
usvg::ImageKind::PNG(d)
|
||||||
|
| usvg::ImageKind::JPEG(d)
|
||||||
|
| usvg::ImageKind::GIF(d)
|
||||||
|
| usvg::ImageKind::WEBP(d) => Some(d),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let Some(data) = data else { continue };
|
||||||
|
let mut reader = image::ImageReader::new(std::io::Cursor::new(data.as_slice()));
|
||||||
|
reader = match reader.with_guessed_format() {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(_) => continue,
|
||||||
|
};
|
||||||
|
let mut l = image::Limits::default();
|
||||||
|
l.max_image_width = Some(12_000);
|
||||||
|
l.max_image_height = Some(12_000);
|
||||||
|
l.max_alloc = Some(600 << 20);
|
||||||
|
reader.limits(l);
|
||||||
|
let Ok(img) = reader.decode() else { continue };
|
||||||
|
let rgba_img = img.into_rgba8();
|
||||||
|
ctx.images += 1;
|
||||||
|
let asset = format!("s{}", ctx.images);
|
||||||
|
let (pw, ph) = (rgba_img.width(), rgba_img.height());
|
||||||
|
ctx.doc.assets.insert(asset.clone(), Raster { width: pw, height: ph, rgba: rgba_img.into_raw() });
|
||||||
|
let size = im.size();
|
||||||
|
let t = im.abs_transform();
|
||||||
|
let mut o = object(
|
||||||
|
ctx,
|
||||||
|
Shape::Image {
|
||||||
|
asset,
|
||||||
|
w: size.width(),
|
||||||
|
h: size.height(),
|
||||||
|
crop: Rect { x: 0.0, y: 0.0, w: size.width(), h: size.height() },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
o.transform = [t.sx, t.ky, t.kx, t.sy, t.tx, t.ty];
|
||||||
|
out.push(o);
|
||||||
|
}
|
||||||
|
usvg::Node::Text(t) => group(ctx, t.flattened(), out)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The SVG as a document: one page of the SVG's size (in points), one vector layer holding one group.
|
||||||
|
pub fn import(data: &[u8], fontdb: Arc<fontdb::Database>) -> Result<Document, SvgError> {
|
||||||
|
if data.len() > 64 << 20 {
|
||||||
|
return Err(SvgError::TooLarge);
|
||||||
|
}
|
||||||
|
let opt = usvg::Options { fontdb, ..Default::default() };
|
||||||
|
let tree = usvg::Tree::from_data(data, &opt).map_err(|e| SvgError::Parse(e.to_string()))?;
|
||||||
|
let size = tree.size();
|
||||||
|
let px_to_pt = 0.75;
|
||||||
|
let mut ctx = Ctx { doc: Document::default(), count: 0, images: 0 };
|
||||||
|
let mut objects = Vec::new();
|
||||||
|
group(&mut ctx, tree.root(), &mut objects)?;
|
||||||
|
let mut g = object(&mut ctx, Shape::Group { objects });
|
||||||
|
g.name = "SVG".into();
|
||||||
|
g.transform = [px_to_pt, 0.0, 0.0, px_to_pt, 0.0, 0.0];
|
||||||
|
let pid = ctx.doc.new_id();
|
||||||
|
let lid = ctx.doc.new_id();
|
||||||
|
let mut layer = Layer::vector(lid, "SVG");
|
||||||
|
layer.kind = LayerKind::Vector { objects: vec![g] };
|
||||||
|
ctx.doc.pages.push(Page {
|
||||||
|
id: pid,
|
||||||
|
width: (size.width() * px_to_pt).clamp(1.0, 14_400.0),
|
||||||
|
height: (size.height() * px_to_pt).clamp(1.0, 14_400.0),
|
||||||
|
margins: [0.0; 4],
|
||||||
|
guides: Vec::new(),
|
||||||
|
background: None,
|
||||||
|
layers: vec![layer],
|
||||||
|
});
|
||||||
|
Ok(ctx.doc)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The system fonts as usvg wants them (for SVG text).
|
||||||
|
pub fn system_fontdb() -> Arc<fontdb::Database> {
|
||||||
|
let mut db = fontdb::Database::new();
|
||||||
|
db.load_system_fonts();
|
||||||
|
Arc::new(db)
|
||||||
|
}
|
||||||
@@ -0,0 +1,419 @@
|
|||||||
|
//! Text: the font book (system fonts through fontdb, plus fonts stored in documents), shaping with rustybuzz, line
|
||||||
|
//! breaking and alignment, glyph outlines with ttf-parser. Both painters and every export use the same layout.
|
||||||
|
use crate::model::{Align, TextStyle};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fmt::Write;
|
||||||
|
use std::sync::{Arc, RwLock};
|
||||||
|
|
||||||
|
/// A loaded font face: its data, where it came from and what its licence allows.
|
||||||
|
pub struct Font {
|
||||||
|
pub data: Arc<Vec<u8>>,
|
||||||
|
pub index: u32,
|
||||||
|
pub family: String,
|
||||||
|
pub post_script_name: String,
|
||||||
|
pub weight: u16,
|
||||||
|
pub italic: bool,
|
||||||
|
pub units_per_em: f32,
|
||||||
|
pub ascender: f32,
|
||||||
|
pub descender: f32,
|
||||||
|
pub cap_height: f32,
|
||||||
|
pub embedding: Embedding,
|
||||||
|
/// The file is OpenType with CFF outlines (else TrueType).
|
||||||
|
pub cff: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the font's OS/2 `fsType` allows.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum Embedding {
|
||||||
|
/// Installable or editable: may be stored in a document and embedded in a PDF.
|
||||||
|
Editable,
|
||||||
|
/// Preview and print: may be embedded in a PDF, not stored for editing.
|
||||||
|
PrintOnly,
|
||||||
|
/// Restricted licence, or bitmap-only embedding: may not be embedded.
|
||||||
|
Forbidden(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type FontKey = usize;
|
||||||
|
|
||||||
|
/// A glyph's outline as path data, or none for an empty glyph.
|
||||||
|
type Outlined = Option<Arc<str>>;
|
||||||
|
|
||||||
|
/// The fonts Pictor can use. Cheap to share between threads.
|
||||||
|
pub struct FontBook {
|
||||||
|
db: RwLock<fontdb::Database>,
|
||||||
|
loaded: RwLock<Vec<Arc<Font>>>,
|
||||||
|
by_id: RwLock<HashMap<fontdb::ID, FontKey>>,
|
||||||
|
outlines: RwLock<HashMap<(FontKey, u16), Outlined>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fallbacks for characters the chosen font lacks, in order.
|
||||||
|
const FALLBACKS: &[&str] =
|
||||||
|
&["Segoe UI", "Arial", "Segoe UI Symbol", "Segoe UI Emoji", "DejaVu Sans", "Liberation Sans"];
|
||||||
|
|
||||||
|
impl Default for FontBook {
|
||||||
|
fn default() -> Self {
|
||||||
|
FontBook::empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FontBook {
|
||||||
|
pub fn empty() -> FontBook {
|
||||||
|
FontBook {
|
||||||
|
db: RwLock::new(fontdb::Database::new()),
|
||||||
|
loaded: RwLock::new(Vec::new()),
|
||||||
|
by_id: RwLock::new(HashMap::new()),
|
||||||
|
outlines: RwLock::new(HashMap::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The system's fonts (Windows: the Fonts folder and the per-user fonts folder).
|
||||||
|
pub fn system() -> FontBook {
|
||||||
|
let book = FontBook::empty();
|
||||||
|
{
|
||||||
|
let mut db = book.db.write().unwrap();
|
||||||
|
db.load_system_fonts();
|
||||||
|
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
|
||||||
|
let user = std::path::Path::new(&local).join("Microsoft").join("Windows").join("Fonts");
|
||||||
|
if user.is_dir() {
|
||||||
|
db.load_fonts_dir(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
book
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a font from memory (a font stored in a document). Returns false when it is not a font.
|
||||||
|
pub fn add(&self, data: Vec<u8>) -> bool {
|
||||||
|
if ttf_parser::Face::parse(&data, 0).is_err() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
self.db.write().unwrap().load_font_data(data);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Family names, sorted, without duplicates.
|
||||||
|
pub fn families(&self) -> Vec<String> {
|
||||||
|
let db = self.db.read().unwrap();
|
||||||
|
let mut v: Vec<String> = db.faces().filter_map(|f| f.families.first().map(|(n, _)| n.clone())).collect();
|
||||||
|
v.sort_by_key(|s| s.to_lowercase());
|
||||||
|
v.dedup();
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The closest face of a family (none when the family is not installed).
|
||||||
|
pub fn find(&self, family: &str, weight: u16, italic: bool) -> Option<FontKey> {
|
||||||
|
let id = {
|
||||||
|
let db = self.db.read().unwrap();
|
||||||
|
let q = fontdb::Query {
|
||||||
|
families: &[fontdb::Family::Name(family)],
|
||||||
|
weight: fontdb::Weight(weight),
|
||||||
|
stretch: fontdb::Stretch::Normal,
|
||||||
|
style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
|
||||||
|
};
|
||||||
|
let id = db.query(&q)?;
|
||||||
|
// fontdb falls back to any face when nothing matches the name; insist on the family.
|
||||||
|
let face = db.face(id)?;
|
||||||
|
if !face.families.iter().any(|(n, _)| n.eq_ignore_ascii_case(family)) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
id
|
||||||
|
};
|
||||||
|
self.load(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The face for a style, falling back to Segoe UI, then Arial, then any face.
|
||||||
|
pub fn resolve(&self, family: &str, weight: u16, italic: bool) -> Option<FontKey> {
|
||||||
|
self.find(family, weight, italic)
|
||||||
|
.or_else(|| FALLBACKS.iter().find_map(|f| self.find(f, weight, italic)))
|
||||||
|
.or_else(|| {
|
||||||
|
let id = self.db.read().unwrap().faces().next().map(|f| f.id)?;
|
||||||
|
self.load(id)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(&self, id: fontdb::ID) -> Option<FontKey> {
|
||||||
|
if let Some(k) = self.by_id.read().unwrap().get(&id) {
|
||||||
|
return Some(*k);
|
||||||
|
}
|
||||||
|
let (data, index, family, psn) = {
|
||||||
|
let db = self.db.read().unwrap();
|
||||||
|
let info = db.face(id)?;
|
||||||
|
let family = info.families.first().map(|(n, _)| n.clone()).unwrap_or_default();
|
||||||
|
let psn = info.post_script_name.clone();
|
||||||
|
let index = info.index;
|
||||||
|
let data = db.with_face_data(id, |d, _| d.to_vec())?;
|
||||||
|
(data, index, family, psn)
|
||||||
|
};
|
||||||
|
let face = ttf_parser::Face::parse(&data, index).ok()?;
|
||||||
|
let embedding = if !face.is_outline_embedding_allowed() {
|
||||||
|
Embedding::Forbidden("its licence allows only bitmap embedding")
|
||||||
|
} else {
|
||||||
|
match face.permissions() {
|
||||||
|
Some(ttf_parser::Permissions::Restricted) => {
|
||||||
|
Embedding::Forbidden("its licence forbids embedding (fsType: restricted)")
|
||||||
|
}
|
||||||
|
Some(ttf_parser::Permissions::PreviewAndPrint) => Embedding::PrintOnly,
|
||||||
|
_ => Embedding::Editable,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let font = Font {
|
||||||
|
index,
|
||||||
|
family,
|
||||||
|
post_script_name: psn,
|
||||||
|
weight: face.weight().to_number(),
|
||||||
|
italic: face.is_italic(),
|
||||||
|
units_per_em: face.units_per_em() as f32,
|
||||||
|
ascender: face.ascender() as f32,
|
||||||
|
descender: face.descender() as f32,
|
||||||
|
cap_height: face.capital_height().unwrap_or(face.ascender()) as f32,
|
||||||
|
cff: face.tables().cff.is_some(),
|
||||||
|
embedding,
|
||||||
|
data: Arc::new(data),
|
||||||
|
};
|
||||||
|
let mut loaded = self.loaded.write().unwrap();
|
||||||
|
let key = loaded.len();
|
||||||
|
loaded.push(Arc::new(font));
|
||||||
|
self.by_id.write().unwrap().insert(id, key);
|
||||||
|
Some(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn font(&self, key: FontKey) -> Arc<Font> {
|
||||||
|
self.loaded.read().unwrap()[key].clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_glyph(&self, key: FontKey, c: char) -> bool {
|
||||||
|
let f = self.font(key);
|
||||||
|
ttf_parser::Face::parse(&f.data, f.index).ok().and_then(|face| face.glyph_index(c)).is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A glyph's outline as path data in font units (y up), or none for an empty glyph (a space).
|
||||||
|
pub fn outline(&self, key: FontKey, gid: u16) -> Option<Arc<str>> {
|
||||||
|
if let Some(o) = self.outlines.read().unwrap().get(&(key, gid)) {
|
||||||
|
return o.clone();
|
||||||
|
}
|
||||||
|
let f = self.font(key);
|
||||||
|
let out = ttf_parser::Face::parse(&f.data, f.index).ok().and_then(|face| {
|
||||||
|
let mut b = Outline(String::new());
|
||||||
|
face.outline_glyph(ttf_parser::GlyphId(gid), &mut b)?;
|
||||||
|
Some(Arc::<str>::from(b.0))
|
||||||
|
});
|
||||||
|
self.outlines.write().unwrap().insert((key, gid), out.clone());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Outline(String);
|
||||||
|
|
||||||
|
impl ttf_parser::OutlineBuilder for Outline {
|
||||||
|
fn move_to(&mut self, x: f32, y: f32) {
|
||||||
|
let _ = write!(self.0, "M{x} {y}");
|
||||||
|
}
|
||||||
|
fn line_to(&mut self, x: f32, y: f32) {
|
||||||
|
let _ = write!(self.0, "L{x} {y}");
|
||||||
|
}
|
||||||
|
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
|
||||||
|
let _ = write!(self.0, "Q{x1} {y1} {x} {y}");
|
||||||
|
}
|
||||||
|
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
|
||||||
|
let _ = write!(self.0, "C{x1} {y1} {x2} {y2} {x} {y}");
|
||||||
|
}
|
||||||
|
fn close(&mut self) {
|
||||||
|
self.0.push('Z');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A glyph placed in a text box: `x` from the box's left, on its line's baseline.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Glyph {
|
||||||
|
pub font: FontKey,
|
||||||
|
pub gid: u16,
|
||||||
|
pub x: f32,
|
||||||
|
pub advance: f32,
|
||||||
|
/// The characters this glyph stands for (the whole cluster on its first glyph, empty on the rest).
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Line {
|
||||||
|
pub baseline: f32,
|
||||||
|
pub glyphs: Vec<Glyph>,
|
||||||
|
/// From the first glyph to the end of the last visible one.
|
||||||
|
pub width: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Layout {
|
||||||
|
pub lines: Vec<Line>,
|
||||||
|
pub width: f32,
|
||||||
|
pub height: f32,
|
||||||
|
pub size: f32,
|
||||||
|
/// The face the style asked for (or its fallback): the one the box's metrics come from.
|
||||||
|
pub primary: Option<FontKey>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Shaped {
|
||||||
|
font: FontKey,
|
||||||
|
gid: u16,
|
||||||
|
advance: f32,
|
||||||
|
/// Index of the cluster's first char in the paragraph.
|
||||||
|
cluster: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lays out a text box `w` points wide (0 = no wrapping).
|
||||||
|
pub fn layout(book: &FontBook, text: &str, style: &TextStyle, w: f32) -> Layout {
|
||||||
|
let size = style.size;
|
||||||
|
let primary = book.resolve(&style.family, style.weight, style.italic);
|
||||||
|
let line_box = size * style.line_height;
|
||||||
|
let (asc, desc) = match primary {
|
||||||
|
Some(k) => {
|
||||||
|
let f = book.font(k);
|
||||||
|
(f.ascender * size / f.units_per_em, -f.descender * size / f.units_per_em)
|
||||||
|
}
|
||||||
|
None => (size * 0.8, size * 0.2),
|
||||||
|
};
|
||||||
|
let baseline_in_box = (line_box - (asc + desc)) / 2.0 + asc;
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
for para in text.split('\n') {
|
||||||
|
let para = para.strip_suffix('\r').unwrap_or(para);
|
||||||
|
let chars: Vec<char> = para.chars().collect();
|
||||||
|
let shaped = match primary {
|
||||||
|
Some(p) => shape(book, &chars, p, style),
|
||||||
|
None => Vec::new(),
|
||||||
|
};
|
||||||
|
let mut start = 0;
|
||||||
|
let is_space = |g: &Shaped| chars.get(g.cluster).is_some_and(|c| c.is_whitespace());
|
||||||
|
let breaks_after = |g: &Shaped| {
|
||||||
|
chars.get(g.cluster).is_some_and(|c| c.is_whitespace() || *c == '-' || *c == '\u{2010}' || *c == '/')
|
||||||
|
};
|
||||||
|
let mut para_lines: Vec<(usize, usize)> = Vec::new();
|
||||||
|
while start < shaped.len() {
|
||||||
|
let mut x = 0.0;
|
||||||
|
let mut end = shaped.len();
|
||||||
|
let mut last_break: Option<usize> = None;
|
||||||
|
for (i, g) in shaped.iter().enumerate().skip(start) {
|
||||||
|
let fits = w <= 0.0 || x + g.advance <= w + 0.01 || is_space(g);
|
||||||
|
if !fits {
|
||||||
|
end = match last_break {
|
||||||
|
Some(b) => b + 1,
|
||||||
|
None if i > start => i,
|
||||||
|
None => i + 1,
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
x += g.advance;
|
||||||
|
if breaks_after(g) {
|
||||||
|
last_break = Some(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A break never splits a cluster.
|
||||||
|
while end < shaped.len() && end > start + 1 && shaped[end].cluster == shaped[end - 1].cluster {
|
||||||
|
end -= 1;
|
||||||
|
}
|
||||||
|
para_lines.push((start, end));
|
||||||
|
start = end;
|
||||||
|
}
|
||||||
|
if para_lines.is_empty() {
|
||||||
|
para_lines.push((0, 0));
|
||||||
|
}
|
||||||
|
let n = para_lines.len();
|
||||||
|
for (li, (s, e)) in para_lines.into_iter().enumerate() {
|
||||||
|
let slice = &shaped[s..e];
|
||||||
|
let visible_end = slice.iter().rposition(|g| !is_space(g)).map(|i| i + 1).unwrap_or(0);
|
||||||
|
let natural: f32 = slice[..visible_end].iter().map(|g| g.advance).sum();
|
||||||
|
let spaces = slice[..visible_end].iter().filter(|g| is_space(g)).count();
|
||||||
|
let last = li + 1 == n;
|
||||||
|
let (offset, extra) = match style.align {
|
||||||
|
_ if w <= 0.0 => (0.0, 0.0),
|
||||||
|
Align::Left => (0.0, 0.0),
|
||||||
|
Align::Center => ((w - natural) / 2.0, 0.0),
|
||||||
|
Align::Right => (w - natural, 0.0),
|
||||||
|
Align::Justify if !last && spaces > 0 => (0.0, (w - natural) / spaces as f32),
|
||||||
|
Align::Justify => (0.0, 0.0),
|
||||||
|
};
|
||||||
|
let mut x = offset;
|
||||||
|
let mut glyphs = Vec::with_capacity(slice.len());
|
||||||
|
for (i, g) in slice.iter().enumerate() {
|
||||||
|
let first_of_cluster = i == 0 || slice[i - 1].cluster != g.cluster;
|
||||||
|
let next =
|
||||||
|
slice.get(i + 1..).and_then(|r| r.iter().find(|n| n.cluster != g.cluster)).map(|n| n.cluster);
|
||||||
|
let next = next.unwrap_or_else(|| shaped.get(e).map(|n| n.cluster).unwrap_or(chars.len()));
|
||||||
|
let text: String = if first_of_cluster && next > g.cluster {
|
||||||
|
chars[g.cluster..next].iter().collect()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
let mut advance = g.advance;
|
||||||
|
if extra > 0.0 && i < visible_end && is_space(g) {
|
||||||
|
advance += extra;
|
||||||
|
}
|
||||||
|
glyphs.push(Glyph { font: g.font, gid: g.gid, x, advance, text });
|
||||||
|
x += advance;
|
||||||
|
}
|
||||||
|
let width = if visible_end == 0 {
|
||||||
|
0.0
|
||||||
|
} else {
|
||||||
|
glyphs[visible_end - 1].x + glyphs[visible_end - 1].advance - offset
|
||||||
|
};
|
||||||
|
let baseline = lines.len() as f32 * line_box + baseline_in_box;
|
||||||
|
lines.push(Line { baseline, glyphs, width });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let width = if w > 0.0 { w } else { lines.iter().map(|l| l.width).fold(0.0, f32::max) };
|
||||||
|
Layout { height: lines.len() as f32 * line_box, lines, width, size, primary }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shapes a paragraph, splitting it into runs by the font that has each character.
|
||||||
|
fn shape(book: &FontBook, chars: &[char], primary: FontKey, style: &TextStyle) -> Vec<Shaped> {
|
||||||
|
let mut fonts: Vec<FontKey> = Vec::with_capacity(chars.len());
|
||||||
|
let mut fallback_cache: HashMap<char, FontKey> = HashMap::new();
|
||||||
|
for &c in chars {
|
||||||
|
let k = if c.is_whitespace() || c.is_control() || book.has_glyph(primary, c) {
|
||||||
|
primary
|
||||||
|
} else {
|
||||||
|
*fallback_cache.entry(c).or_insert_with(|| {
|
||||||
|
FALLBACKS
|
||||||
|
.iter()
|
||||||
|
.filter_map(|f| book.find(f, style.weight, style.italic))
|
||||||
|
.find(|k| book.has_glyph(*k, c))
|
||||||
|
.unwrap_or(primary)
|
||||||
|
})
|
||||||
|
};
|
||||||
|
fonts.push(k);
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
while i < chars.len() {
|
||||||
|
let k = fonts[i];
|
||||||
|
let mut j = i + 1;
|
||||||
|
while j < chars.len() && fonts[j] == k {
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
let run: String = chars[i..j].iter().collect();
|
||||||
|
// Byte offset in the run → char index in the paragraph.
|
||||||
|
let mut byte_to_char = vec![0usize; run.len() + 1];
|
||||||
|
for (ci, (b, _)) in run.char_indices().enumerate() {
|
||||||
|
byte_to_char[b] = i + ci;
|
||||||
|
}
|
||||||
|
let f = book.font(k);
|
||||||
|
if let Some(face) = rustybuzz::Face::from_slice(&f.data, f.index) {
|
||||||
|
let mut buf = rustybuzz::UnicodeBuffer::new();
|
||||||
|
buf.push_str(&run);
|
||||||
|
buf.set_direction(rustybuzz::Direction::LeftToRight);
|
||||||
|
buf.guess_segment_properties();
|
||||||
|
let shaped = rustybuzz::shape(&face, &[], buf);
|
||||||
|
let scale = style.size / f.units_per_em;
|
||||||
|
let infos = shaped.glyph_infos();
|
||||||
|
for (gi, (info, pos)) in infos.iter().zip(shaped.glyph_positions()).enumerate() {
|
||||||
|
let cluster = byte_to_char[info.cluster as usize];
|
||||||
|
let starts_cluster = gi == 0 || infos[gi - 1].cluster != info.cluster;
|
||||||
|
let mut advance = pos.x_advance as f32 * scale;
|
||||||
|
if starts_cluster {
|
||||||
|
advance += style.letter_spacing;
|
||||||
|
}
|
||||||
|
out.push(Shaped { font: k, gid: info.glyph_id as u16, advance, cluster });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i = j;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
//! Bitmap tools: fill tolerance, magic wand, lasso, delete, brush clipped by a selection, adjustments' identities,
|
||||||
|
//! the clone stamp, and exact undo of a pixel edit.
|
||||||
|
use pictor_doc::bitmap::{self, Adjust, Brush, Mask};
|
||||||
|
use pictor_doc::ops::History;
|
||||||
|
use pictor_doc::*;
|
||||||
|
|
||||||
|
/// Left half red, right half a slightly different red, with a black wall at x = 30.
|
||||||
|
fn two_reds() -> Raster {
|
||||||
|
let mut r = Raster::new(60, 40);
|
||||||
|
for y in 0..40 {
|
||||||
|
for x in 0..60 {
|
||||||
|
let i = (y * 60 + x) * 4;
|
||||||
|
let c = if x == 30 {
|
||||||
|
[0, 0, 0, 255]
|
||||||
|
} else if x < 30 {
|
||||||
|
[200, 20, 20, 255]
|
||||||
|
} else {
|
||||||
|
[206, 24, 20, 255]
|
||||||
|
};
|
||||||
|
r.rgba[i..i + 4].copy_from_slice(&c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fill_respects_tolerance_and_walls() {
|
||||||
|
let mut r = two_reds();
|
||||||
|
bitmap::fill(&mut r, 5, 5, 0, [0, 0, 255, 255], None);
|
||||||
|
assert_eq!(r.pixel(29, 39), [0, 0, 255, 255]);
|
||||||
|
assert_eq!(r.pixel(30, 5), [0, 0, 0, 255], "the wall stays");
|
||||||
|
assert_eq!(r.pixel(40, 5), [206, 24, 20, 255], "behind the wall nothing changes");
|
||||||
|
// Without the wall, tolerance 10 takes the near red too, tolerance 0 does not.
|
||||||
|
let mut r = two_reds();
|
||||||
|
for y in 0..40 {
|
||||||
|
let i = (y * 60 + 30) * 4;
|
||||||
|
r.rgba[i..i + 4].copy_from_slice(&[203, 22, 20, 255]);
|
||||||
|
}
|
||||||
|
let mut strict = r.clone();
|
||||||
|
bitmap::fill(&mut strict, 5, 5, 0, [0, 255, 0, 255], None);
|
||||||
|
assert_eq!(strict.pixel(45, 5), [206, 24, 20, 255]);
|
||||||
|
bitmap::fill(&mut r, 5, 5, 10, [0, 255, 0, 255], None);
|
||||||
|
assert_eq!(r.pixel(45, 5), [0, 255, 0, 255]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wand_selects_a_region_and_delete_clears_only_it() {
|
||||||
|
let mut r = two_reds();
|
||||||
|
let m = bitmap::region(&r, 5, 5, 0);
|
||||||
|
assert_eq!(m.bbox(), PixelRect { x: 0, y: 0, w: 30, h: 40 });
|
||||||
|
bitmap::clear(&mut r, Some(&m));
|
||||||
|
assert_eq!(r.pixel(10, 10)[3], 0);
|
||||||
|
assert_eq!(r.pixel(30, 10), [0, 0, 0, 255]);
|
||||||
|
assert_eq!(r.pixel(50, 10), [206, 24, 20, 255]);
|
||||||
|
assert!(!m.outline().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wand_and_delete_take_a_stroke_with_its_soft_edge() {
|
||||||
|
let mut r = Raster::new(120, 60);
|
||||||
|
let b = Brush { radius: 8.0, hardness: 0.3, color: [31, 42, 68, 255], opacity: 1.0, erase: false };
|
||||||
|
bitmap::brush(&mut r, &[(10.0, 30.0, 1.0), (110.0, 30.0, 1.0)], &b, None);
|
||||||
|
assert!(r.rgba.as_chunks::<4>().0.iter().any(|p| p[3] > 0 && p[3] < 255), "the stroke has a soft edge");
|
||||||
|
let m = bitmap::region(&r, 60, 30, 24);
|
||||||
|
bitmap::clear(&mut r, Some(&m));
|
||||||
|
assert!(r.rgba.as_chunks::<4>().0.iter().all(|p| p[3] == 0), "pixels of the stroke were left behind");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lasso_and_rect_masks() {
|
||||||
|
let m = Mask::polygon(100, 100, &[(10.0, 10.0), (90.0, 10.0), (10.0, 90.0)]);
|
||||||
|
assert_eq!(m.get(20, 20), 255);
|
||||||
|
assert_eq!(m.get(80, 80), 0);
|
||||||
|
let r = Mask::rect(50, 50, PixelRect { x: 10, y: 10, w: 5, h: 5 });
|
||||||
|
assert_eq!(r.bbox(), PixelRect { x: 10, y: 10, w: 5, h: 5 });
|
||||||
|
let o = r.outline();
|
||||||
|
assert_eq!(o.matches('M').count(), 4, "{o}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_brush_stroke_paints_along_its_path_inside_the_selection() {
|
||||||
|
let mut r = Raster::filled(100, 60, [255, 255, 255, 255]);
|
||||||
|
let sel = Mask::rect(100, 60, PixelRect { x: 0, y: 0, w: 50, h: 60 });
|
||||||
|
let b = Brush { radius: 6.0, hardness: 0.8, color: [0, 0, 0, 255], opacity: 1.0, erase: false };
|
||||||
|
let dirty = bitmap::brush(&mut r, &[(10.0, 30.0, 1.0), (90.0, 30.0, 1.0)], &b, Some(&sel));
|
||||||
|
assert!(dirty.w > 70);
|
||||||
|
assert_eq!(r.pixel(30, 30), [0, 0, 0, 255], "painted on the line");
|
||||||
|
assert_eq!(r.pixel(30, 5), [255, 255, 255, 255], "away from the line");
|
||||||
|
assert_eq!(r.pixel(70, 30), [255, 255, 255, 255], "outside the selection");
|
||||||
|
// The eraser takes the alpha.
|
||||||
|
bitmap::brush(&mut r, &[(30.0, 30.0, 1.0)], &Brush { erase: true, ..b }, None);
|
||||||
|
assert_eq!(r.pixel(30, 30)[3], 0);
|
||||||
|
// A pencil sets exact pixels.
|
||||||
|
bitmap::pencil(&mut r, &[(0.0, 0.0), (5.0, 0.0)], 1, [1, 2, 3, 255], false, None);
|
||||||
|
assert_eq!(r.pixel(3, 0), [1, 2, 3, 255]);
|
||||||
|
assert_eq!(r.pixel(3, 1), [255, 255, 255, 255]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn neutral_adjustments_change_nothing_and_invert_twice_returns() {
|
||||||
|
let src = fixtures::picture(64, 48);
|
||||||
|
for a in [
|
||||||
|
Adjust::Brightness { amount: 0.0 },
|
||||||
|
Adjust::Contrast { amount: 0.0 },
|
||||||
|
Adjust::Levels { in_black: 0.0, in_white: 255.0, gamma: 1.0, out_black: 0.0, out_white: 255.0 },
|
||||||
|
Adjust::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 0.0 },
|
||||||
|
Adjust::Sharpen { amount: 0.0, radius: 2.0 },
|
||||||
|
] {
|
||||||
|
let mut dst = src.clone();
|
||||||
|
bitmap::adjust(&src, &mut dst, &a, None);
|
||||||
|
let worst = src.rgba.iter().zip(&dst.rgba).map(|(a, b)| (*a as i16 - *b as i16).abs()).max().unwrap();
|
||||||
|
assert!(worst <= 1, "{a:?} changed a pixel by {worst}");
|
||||||
|
}
|
||||||
|
let mut once = src.clone();
|
||||||
|
bitmap::adjust(&src, &mut once, &Adjust::Invert, None);
|
||||||
|
assert_ne!(once, src);
|
||||||
|
let mut twice = once.clone();
|
||||||
|
bitmap::adjust(&once, &mut twice, &Adjust::Invert, None);
|
||||||
|
assert_eq!(twice, src);
|
||||||
|
// Brightness +50 makes a mid grey lighter; a blur smooths an edge.
|
||||||
|
let grey = Raster::filled(4, 4, [100, 100, 100, 255]);
|
||||||
|
let mut lighter = grey.clone();
|
||||||
|
bitmap::adjust(&grey, &mut lighter, &Adjust::Brightness { amount: 50.0 }, None);
|
||||||
|
assert!(lighter.pixel(0, 0)[0] > 200);
|
||||||
|
let mut edge = Raster::filled(20, 1, [0, 0, 0, 255]);
|
||||||
|
for x in 10..20 {
|
||||||
|
edge.rgba[x * 4..x * 4 + 3].copy_from_slice(&[255, 255, 255]);
|
||||||
|
}
|
||||||
|
let mut soft = edge.clone();
|
||||||
|
bitmap::adjust(&edge, &mut soft, &Adjust::Blur { radius: 3.0 }, None);
|
||||||
|
let mid = soft.pixel(10, 0)[0];
|
||||||
|
assert!(mid > 40 && mid < 230, "{mid}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_clone_stamp_copies_from_its_offset() {
|
||||||
|
let src = fixtures::picture(80, 80);
|
||||||
|
let mut r = src.clone();
|
||||||
|
let b = Brush { radius: 4.0, hardness: 1.0, color: [0; 4], opacity: 1.0, erase: false };
|
||||||
|
bitmap::clone_stamp(&mut r, &src, (30.0, 10.0), &[(20.0, 20.0, 1.0)], &b, None);
|
||||||
|
assert_eq!(r.pixel(20, 20), src.pixel(50, 30));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_pixel_edit_undoes_exactly() {
|
||||||
|
let mut doc = fixtures::bitmap();
|
||||||
|
let original = doc.clone();
|
||||||
|
let asset = doc.assets.keys().next().unwrap().clone();
|
||||||
|
let b = Brush { radius: 10.0, hardness: 0.3, color: [10, 200, 30, 255], opacity: 0.8, erase: false };
|
||||||
|
let (op, inv) =
|
||||||
|
bitmap::edit(&mut doc, &asset, |r| bitmap::brush(r, &[(20.0, 20.0, 1.0), (200.0, 140.0, 0.5)], &b, None))
|
||||||
|
.unwrap();
|
||||||
|
let mut h = History::default();
|
||||||
|
h.record(op, inv);
|
||||||
|
assert_ne!(doc, original);
|
||||||
|
assert!(h.undo(&mut doc).unwrap());
|
||||||
|
assert_eq!(doc, original);
|
||||||
|
assert!(h.redo(&mut doc).unwrap());
|
||||||
|
assert_ne!(doc, original);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn svg_import_makes_objects() {
|
||||||
|
let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" viewBox="0 0 200 100">
|
||||||
|
<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#f27ab9"/><stop offset="1" stop-color="#1f2a44"/></linearGradient></defs>
|
||||||
|
<rect x="10" y="10" width="80" height="40" rx="6" fill="url(#g)" stroke="#000" stroke-width="2"/>
|
||||||
|
<g opacity="0.5"><circle cx="150" cy="50" r="30" fill="#3ad07a"/></g>
|
||||||
|
<path d="M10 90 A 20 20 0 0 1 50 90" fill="none" stroke="red" stroke-width="3" stroke-dasharray="4 2"/>
|
||||||
|
<text x="100" y="95" font-family="Arial" font-size="12">Hello</text>
|
||||||
|
</svg>"##;
|
||||||
|
let doc = svg::import(svg, svg::system_fontdb()).unwrap();
|
||||||
|
assert!((doc.pages[0].width - 150.0).abs() < 0.01, "200 px = 150 pt");
|
||||||
|
let LayerKind::Vector { objects } = &doc.pages[0].layers[0].kind else { panic!() };
|
||||||
|
let Shape::Group { objects: inner } = &objects[0].shape else { panic!() };
|
||||||
|
assert!(inner.len() >= 4, "{}", inner.len());
|
||||||
|
assert!(inner.iter().any(|o| matches!(o.fill, Some(Paint::Linear { .. }))));
|
||||||
|
assert!(inner.iter().any(|o| matches!(o.shape, Shape::Group { .. }) && o.opacity < 0.6));
|
||||||
|
assert!(inner.iter().any(|o| o.stroke.as_ref().is_some_and(|s| !s.dash.is_empty())));
|
||||||
|
// It renders and round-trips through the format.
|
||||||
|
let book = FontBook::system();
|
||||||
|
assert!(render::page(&doc, &doc.pages[0], &book, 1.0).is_some());
|
||||||
|
let bytes = format::write(&doc, &[]).unwrap();
|
||||||
|
assert_eq!(format::read(&bytes, &Limits::default()).unwrap().0, doc);
|
||||||
|
assert!(svg::import(b"<svg><g", svg::system_fontdb()).is_err());
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
//! Day 3 mandatory test 3 (the PDF half): a PDF export keeps its text extractable in reading order and every page at
|
||||||
|
//! its exact size; pdfium draws it like the core's own render. Also PNG at a scale, JPG and SVG.
|
||||||
|
use pictor_doc::{Document, FontBook, export, fixtures, render};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
|
fn book() -> &'static FontBook {
|
||||||
|
static B: OnceLock<FontBook> = OnceLock::new();
|
||||||
|
B.get_or_init(FontBook::system)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn engine() -> &'static pictor_pdf::Engine {
|
||||||
|
let dir = std::env::var_os("PDFIUM_DYNAMIC_LIB_PATH")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
|
||||||
|
pictor_pdf::Engine::load(Some(&dir)).expect("pdfium: run scripts/fetch-pdfium.ps1 first")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An A4 page with the text fixture's boxes on it, plus a second page of another size.
|
||||||
|
fn a4_with_text() -> Document {
|
||||||
|
let mut d = fixtures::text();
|
||||||
|
d.pages[0].width = pictor_doc::A4.0;
|
||||||
|
d.pages[0].height = pictor_doc::A4.1;
|
||||||
|
let mut second = fixtures::shapes().pages.remove(0);
|
||||||
|
second.id = d.new_id();
|
||||||
|
for l in &mut second.layers {
|
||||||
|
l.id = d.new_id();
|
||||||
|
if let pictor_doc::LayerKind::Vector { objects } = &mut l.kind {
|
||||||
|
for o in objects {
|
||||||
|
o.id = d.new_id();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.pages.push(second);
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
fn squash(s: &str) -> String {
|
||||||
|
s.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pdf_text_is_extractable_in_order_and_pages_are_exact() {
|
||||||
|
let doc = a4_with_text();
|
||||||
|
let pdf = export::pdf(&doc, book()).unwrap();
|
||||||
|
std::fs::write(format!("{}/export-text.pdf", env!("CARGO_TARGET_TMPDIR")), &pdf).unwrap();
|
||||||
|
let sizes = pictor_pdf::page_sizes(engine(), &pdf, None).unwrap();
|
||||||
|
assert_eq!(sizes.len(), 2);
|
||||||
|
assert!((sizes[0].0 - 595.276).abs() < 0.01 && (sizes[0].1 - 841.89).abs() < 0.01, "A4 is {sizes:?}");
|
||||||
|
assert!((sizes[1].0 - 400.0).abs() < 0.01 && (sizes[1].1 - 300.0).abs() < 0.01, "{sizes:?}");
|
||||||
|
let text = pictor_pdf::extract_text(engine(), &pdf, None).unwrap();
|
||||||
|
let t = squash(&text[0]);
|
||||||
|
let mut at = 0;
|
||||||
|
for w in [
|
||||||
|
"Monika Nováková",
|
||||||
|
"Pictor lays text out in the core: shaping,",
|
||||||
|
"line breaks and alignment, so the screen",
|
||||||
|
"Příliš žluťoučký kůň",
|
||||||
|
"úpěl ďábelské ódy.",
|
||||||
|
"Centred",
|
||||||
|
"in two lines",
|
||||||
|
"Right, italic",
|
||||||
|
] {
|
||||||
|
match t[at..].find(w) {
|
||||||
|
Some(i) => at += i + w.len(),
|
||||||
|
None => panic!("{w:?} missing or out of order in:\n{t}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Letter-spaced capitals: pdfium may read the tracking as spaces; the letters are all there, in order.
|
||||||
|
assert!(t.replace(' ', "").contains("PROJEKTOVÁMANAŽERKA"), "{t}");
|
||||||
|
// The fonts are embedded subsets.
|
||||||
|
let raw = String::from_utf8_lossy(&pdf);
|
||||||
|
assert!(raw.contains("/FontFile2") || raw.contains("/FontFile3"), "no embedded font program");
|
||||||
|
assert!(raw.contains("/ToUnicode"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn diff(a: &image::RgbaImage, b: &pictor_doc::Raster) -> f64 {
|
||||||
|
assert_eq!((a.width(), a.height()), (b.width, b.height));
|
||||||
|
let mut sum = 0u64;
|
||||||
|
for (p, q) in a.as_raw().as_chunks::<4>().0.iter().zip(b.rgba.as_chunks::<4>().0) {
|
||||||
|
// The core's pixels over white paper, as pdfium draws them.
|
||||||
|
let a = q[3] as i32;
|
||||||
|
for i in 0..3 {
|
||||||
|
let over_white = (q[i] as i32 * a + 255 * (255 - a)) / 255;
|
||||||
|
sum += (p[i] as i32 - over_white).unsigned_abs() as u64;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum as f64 / (a.width() as f64 * a.height() as f64 * 3.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pdfium_draws_the_pdf_like_the_core_does() {
|
||||||
|
for (name, doc) in fixtures::all() {
|
||||||
|
let pdf = export::pdf(&doc, book()).unwrap();
|
||||||
|
std::fs::write(format!("{}/export-{name}.pdf", env!("CARGO_TARGET_TMPDIR")), &pdf).unwrap();
|
||||||
|
let page = &doc.pages[0];
|
||||||
|
let scale = 2.0;
|
||||||
|
let core = render::page(&doc, page, book(), scale).unwrap();
|
||||||
|
let theirs = pictor_pdf::render_page(engine(), &pdf, None, 0, core.width).unwrap().into_rgba8();
|
||||||
|
let theirs = image::imageops::resize(&theirs, core.width, core.height, image::imageops::FilterType::Triangle);
|
||||||
|
let d = diff(&theirs, &core);
|
||||||
|
theirs.save(format!("{}/export-{name}-pdfium.png", env!("CARGO_TARGET_TMPDIR"))).unwrap();
|
||||||
|
// Anti-aliasing and image filtering differ; a misplaced shape or a missing glyph run costs far more.
|
||||||
|
assert!(d < 3.0, "{name}: mean difference {d:.2} per channel");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn png_jpg_and_svg() {
|
||||||
|
let doc = fixtures::shapes();
|
||||||
|
let page = &doc.pages[0];
|
||||||
|
let png = export::png(&doc, page, book(), 3.0).unwrap();
|
||||||
|
let img = image::load_from_memory(&png).unwrap();
|
||||||
|
assert_eq!((img.width(), img.height()), (1200, 900));
|
||||||
|
let jpg = export::jpg(&doc, page, book(), 1.0, 90).unwrap();
|
||||||
|
let img = image::load_from_memory(&jpg).unwrap();
|
||||||
|
assert_eq!((img.width(), img.height()), (400, 300));
|
||||||
|
for (name, doc) in fixtures::all() {
|
||||||
|
let svg = export::svg(&doc, &doc.pages[0], book());
|
||||||
|
std::fs::write(format!("{}/export-{name}.svg", env!("CARGO_TARGET_TMPDIR")), &svg).unwrap();
|
||||||
|
let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||||
|
assert!(tree.root().has_children(), "{name}: empty SVG");
|
||||||
|
}
|
||||||
|
let svg = export::svg(&fixtures::text(), &fixtures::text().pages[0], book());
|
||||||
|
assert!(svg.contains(">Monika Nováková</text>"), "text is not text in the SVG");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_huge_png_is_refused() {
|
||||||
|
let doc = fixtures::shapes();
|
||||||
|
assert!(matches!(export::png(&doc, &doc.pages[0], book(), 100.0), Err(export::ExportError::TooLarge)));
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
//! Day 3 mandatory test 4: a font whose licence forbids embedding (OS/2 fsType) is refused for PDF export, and the
|
||||||
|
//! error names the font and the reason. The test font is a system font with its fsType patched in memory.
|
||||||
|
use pictor_doc::export::{self, ExportError};
|
||||||
|
use pictor_doc::text::Embedding;
|
||||||
|
use pictor_doc::*;
|
||||||
|
|
||||||
|
fn system_font() -> Vec<u8> {
|
||||||
|
for p in [r"C:\Windows\Fonts\arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"] {
|
||||||
|
if let Ok(d) = std::fs::read(p) {
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("no system font to patch");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The font with OS/2 fsType set to `fs_type` (and version ≥ 2 so the bits mean what they say).
|
||||||
|
fn with_fs_type(mut data: Vec<u8>, fs_type: u16) -> Vec<u8> {
|
||||||
|
let n = u16::from_be_bytes([data[4], data[5]]) as usize;
|
||||||
|
for i in 0..n {
|
||||||
|
let rec = 12 + i * 16;
|
||||||
|
if &data[rec..rec + 4] == b"OS/2" {
|
||||||
|
let off = u32::from_be_bytes(data[rec + 8..rec + 12].try_into().unwrap()) as usize;
|
||||||
|
let version = u16::from_be_bytes([data[off], data[off + 1]]);
|
||||||
|
assert!(version >= 2, "the OS/2 table is too old for this test");
|
||||||
|
data[off + 8..off + 10].copy_from_slice(&fs_type.to_be_bytes());
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("no OS/2 table");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn family_of(data: &[u8]) -> String {
|
||||||
|
let book = FontBook::empty();
|
||||||
|
assert!(book.add(data.to_vec()));
|
||||||
|
book.families().remove(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn doc_with_text(family: &str) -> Document {
|
||||||
|
let mut d = Document::a4();
|
||||||
|
let id = d.new_id();
|
||||||
|
if let LayerKind::Vector { objects } = &mut d.pages[0].layers[0].kind {
|
||||||
|
objects.push(Object {
|
||||||
|
id,
|
||||||
|
name: String::new(),
|
||||||
|
transform: [1.0, 0.0, 0.0, 1.0, 50.0, 50.0],
|
||||||
|
opacity: 1.0,
|
||||||
|
visible: true,
|
||||||
|
locked: false,
|
||||||
|
fill: None,
|
||||||
|
stroke: None,
|
||||||
|
shape: Shape::Text {
|
||||||
|
w: 0.0,
|
||||||
|
text: "Embedding test".into(),
|
||||||
|
style: TextStyle {
|
||||||
|
family: family.into(),
|
||||||
|
weight: 400,
|
||||||
|
italic: false,
|
||||||
|
size: 14.0,
|
||||||
|
color: Rgba::BLACK,
|
||||||
|
align: Align::Left,
|
||||||
|
line_height: 1.2,
|
||||||
|
letter_spacing: 0.0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
fn export_with(font: Vec<u8>) -> (String, Result<Vec<u8>, ExportError>) {
|
||||||
|
let family = family_of(&font);
|
||||||
|
let book = FontBook::empty();
|
||||||
|
assert!(book.add(font));
|
||||||
|
let r = export::pdf(&doc_with_text(&family), &book);
|
||||||
|
(family, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_restricted_font_is_refused_with_its_name_and_the_reason() {
|
||||||
|
let (family, r) = export_with(with_fs_type(system_font(), 0x0002));
|
||||||
|
match r {
|
||||||
|
Err(e @ ExportError::FontNotEmbeddable { .. }) => {
|
||||||
|
let msg = e.to_string();
|
||||||
|
assert!(msg.contains(&family), "{msg}");
|
||||||
|
assert!(msg.contains("forbids embedding"), "{msg}");
|
||||||
|
}
|
||||||
|
other => panic!("a restricted font was embedded: {:?}", other.map(|b| b.len())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bitmap_only_font_is_refused() {
|
||||||
|
let (_, r) = export_with(with_fs_type(system_font(), 0x0200));
|
||||||
|
assert!(matches!(r, Err(ExportError::FontNotEmbeddable { reason, .. }) if reason.contains("bitmap")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn installable_editable_and_print_fonts_are_embedded() {
|
||||||
|
for fs in [0x0000u16, 0x0004, 0x0008] {
|
||||||
|
let (_, r) = export_with(with_fs_type(system_font(), fs));
|
||||||
|
let pdf = r.unwrap_or_else(|e| panic!("fsType {fs:#06x}: {e}"));
|
||||||
|
assert!(String::from_utf8_lossy(&pdf).contains("/FontFile2"));
|
||||||
|
}
|
||||||
|
let book = FontBook::empty();
|
||||||
|
assert!(book.add(with_fs_type(system_font(), 0x0004)));
|
||||||
|
let k = book.resolve(&book.families()[0], 400, false).unwrap();
|
||||||
|
assert_eq!(book.font(k).embedding, Embedding::PrintOnly);
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
//! Day 3 mandatory test 1: the .pictor format. Fixture documents round-trip without loss; hostile zips (zip slip,
|
||||||
|
//! bombs, a huge picture, too many entries, a missing asset, broken JSON) are refused cleanly; a newer format is
|
||||||
|
//! refused with its message.
|
||||||
|
use pictor_doc::format::{self, FormatError, Limits};
|
||||||
|
use pictor_doc::{FontFile, fixtures};
|
||||||
|
use std::io::{Cursor, Write};
|
||||||
|
|
||||||
|
fn zip_of(entries: &[(&str, &[u8])], method: zip::CompressionMethod) -> Vec<u8> {
|
||||||
|
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||||
|
let opts = zip::write::SimpleFileOptions::default().compression_method(method);
|
||||||
|
for (name, data) in entries {
|
||||||
|
z.start_file(*name, opts).unwrap();
|
||||||
|
z.write_all(data).unwrap();
|
||||||
|
}
|
||||||
|
z.finish().unwrap().into_inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A valid document.json for a one-page document with no assets.
|
||||||
|
fn plain_json() -> Vec<u8> {
|
||||||
|
let bytes = format::write(&pictor_doc::Document::a4(), &[]).unwrap();
|
||||||
|
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||||
|
let mut s = Vec::new();
|
||||||
|
std::io::Read::read_to_end(&mut z.by_name("document.json").unwrap(), &mut s).unwrap();
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fixtures_round_trip_without_loss() {
|
||||||
|
for (name, doc) in fixtures::all() {
|
||||||
|
let font = FontFile { family: "Fixture".into(), weight: 400, italic: false, data: fake_font() };
|
||||||
|
let bytes = format::write(&doc, std::slice::from_ref(&font)).unwrap();
|
||||||
|
let (back, fonts) = format::read(&bytes, &Limits::default()).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||||
|
assert_eq!(back, doc, "{name} changed in the round trip");
|
||||||
|
assert_eq!(fonts, vec![font], "{name}: fonts");
|
||||||
|
// Writing again gives the same bytes' content (stable).
|
||||||
|
let again = format::write(&back, &fonts).unwrap();
|
||||||
|
assert_eq!(format::read(&again, &Limits::default()).unwrap().0, doc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The smallest font ttf-parser accepts is a real one: take any system font if there is one, else skip the font part.
|
||||||
|
fn fake_font() -> Vec<u8> {
|
||||||
|
for p in [r"C:\Windows\Fonts\arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"] {
|
||||||
|
if let Ok(d) = std::fs::read(p) {
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("no system font to embed in the fixture");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn err(bytes: &[u8]) -> FormatError {
|
||||||
|
match format::read(bytes, &Limits::default()) {
|
||||||
|
Ok(_) => panic!("a hostile file was accepted"),
|
||||||
|
Err(e) => e,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn zip_slip_and_odd_names_are_refused() {
|
||||||
|
let json = plain_json();
|
||||||
|
for bad in ["../evil.txt", "assets/../../evil.png", "/etc/passwd", "C:/Windows/x.dll", "assets\\x.png", "a//b"] {
|
||||||
|
let z = zip_of(&[("document.json", &json), (bad, b"x")], zip::CompressionMethod::Stored);
|
||||||
|
assert!(matches!(err(&z), FormatError::UnsafeName(_)), "{bad} was not refused as unsafe");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bomb_is_refused_by_size_and_ratio() {
|
||||||
|
// 300 MB of zeros, compressed to a few hundred KB: refused by its declared size before anything is inflated.
|
||||||
|
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||||
|
let opts =
|
||||||
|
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).large_file(true);
|
||||||
|
z.start_file("document.json", opts).unwrap();
|
||||||
|
let block = vec![b' '; 1 << 20];
|
||||||
|
for _ in 0..300 {
|
||||||
|
z.write_all(&block).unwrap();
|
||||||
|
}
|
||||||
|
let bomb = z.finish().unwrap().into_inner();
|
||||||
|
assert!(bomb.len() < 2 << 20, "the bomb itself is small ({} bytes)", bomb.len());
|
||||||
|
assert!(matches!(err(&bomb), FormatError::TooLarge(_)));
|
||||||
|
|
||||||
|
// A 5 MB asset of zeros compresses over 1000×: refused for its ratio.
|
||||||
|
let json = String::from_utf8(plain_json()).unwrap();
|
||||||
|
let json = json.replacen("\"assets\":[]", "\"assets\":[{\"id\":\"b9\",\"width\":1000,\"height\":1250}]", 1);
|
||||||
|
let zeros = vec![0u8; 5 << 20];
|
||||||
|
let z = zip_of(&[("document.json", json.as_bytes()), ("assets/b9.png", &zeros)], zip::CompressionMethod::Deflated);
|
||||||
|
assert!(matches!(err(&z), FormatError::TooLarge(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_huge_picture_is_refused_before_decoding() {
|
||||||
|
let json = String::from_utf8(plain_json()).unwrap();
|
||||||
|
let json = json.replacen("\"assets\":[]", "\"assets\":[{\"id\":\"b9\",\"width\":50000,\"height\":50000}]", 1);
|
||||||
|
let z = zip_of(
|
||||||
|
&[("document.json", json.as_bytes()), ("assets/b9.png", b"not even a png")],
|
||||||
|
zip::CompressionMethod::Stored,
|
||||||
|
);
|
||||||
|
assert!(matches!(err(&z), FormatError::TooLarge(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn too_many_entries_are_refused() {
|
||||||
|
let json = plain_json();
|
||||||
|
let names: Vec<String> = (0..5000).map(|i| format!("extra/{i}")).collect();
|
||||||
|
let mut entries: Vec<(&str, &[u8])> = vec![("document.json", &json)];
|
||||||
|
entries.extend(names.iter().map(|n| (n.as_str(), b"" as &[u8])));
|
||||||
|
let z = zip_of(&entries, zip::CompressionMethod::Stored);
|
||||||
|
assert!(matches!(err(&z), FormatError::TooLarge(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_missing_or_wrong_asset_is_refused() {
|
||||||
|
// The bitmap fixture without its picture.
|
||||||
|
let bytes = format::write(&fixtures::bitmap(), &[]).unwrap();
|
||||||
|
let mut src = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||||
|
let mut json = Vec::new();
|
||||||
|
std::io::Read::read_to_end(&mut src.by_name("document.json").unwrap(), &mut json).unwrap();
|
||||||
|
let z = zip_of(&[("document.json", &json)], zip::CompressionMethod::Deflated);
|
||||||
|
assert!(matches!(err(&z), FormatError::MissingAsset(_)), "{:?}", err(&z));
|
||||||
|
// A picture that is not the size the document says.
|
||||||
|
let wrong = format::encode_png(&fixtures::picture(10, 10)).unwrap();
|
||||||
|
let asset = src.file_names().find(|n| n.starts_with("assets/")).unwrap().to_string();
|
||||||
|
let z = zip_of(&[("document.json", &json), (&asset, &wrong)], zip::CompressionMethod::Stored);
|
||||||
|
assert!(matches!(err(&z), FormatError::Damaged(_)), "{:?}", err(&z));
|
||||||
|
// An asset referenced by a layer but not listed.
|
||||||
|
let json2 = String::from_utf8(json.clone()).unwrap();
|
||||||
|
let start = json2.find("\"assets\":[").unwrap();
|
||||||
|
let end = json2[start..].find(']').unwrap() + start + 1;
|
||||||
|
let json2 = format!("{}\"assets\":[]{}", &json2[..start], &json2[end..]);
|
||||||
|
let z = zip_of(&[("document.json", json2.as_bytes())], zip::CompressionMethod::Stored);
|
||||||
|
assert!(matches!(err(&z), FormatError::MissingAsset(_)), "{:?}", err(&z));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broken_json_and_non_zips_are_refused() {
|
||||||
|
let z = zip_of(&[("document.json", b"{\"format\":1,\"pages\":[{")], zip::CompressionMethod::Stored);
|
||||||
|
assert!(matches!(err(&z), FormatError::Damaged(_)));
|
||||||
|
assert!(matches!(err(b"%PDF-1.7 not a zip"), FormatError::NotPictor));
|
||||||
|
let z = zip_of(&[("readme.txt", b"hi")], zip::CompressionMethod::Stored);
|
||||||
|
assert!(matches!(err(&z), FormatError::NotPictor));
|
||||||
|
// Valid JSON with lies in it: a repeated id, a NaN-like size, a bad path, an asset id with a slash.
|
||||||
|
let good = String::from_utf8(plain_json()).unwrap();
|
||||||
|
for (from, to) in [
|
||||||
|
("\"next_id\":3", "\"next_id\":1"),
|
||||||
|
("\"width\":595.276", "\"width\":-5"),
|
||||||
|
(
|
||||||
|
"\"layers\":[{",
|
||||||
|
"\"layers\":[{\"kind\":\"bitmap\",\"asset\":\"../x\",\"x\":0,\"y\":0,\"w\":1,\"h\":1,\"id\":9,\"name\":\"x\"},{",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
assert!(good.contains(from), "fixture json lacks {from}: {good}");
|
||||||
|
let bad = good.replacen(from, to, 1);
|
||||||
|
let z = zip_of(&[("document.json", bad.as_bytes())], zip::CompressionMethod::Stored);
|
||||||
|
let e = err(&z);
|
||||||
|
assert!(matches!(e, FormatError::Damaged(_) | FormatError::UnsafeName(_)), "{from} → {to}: {e:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_newer_format_is_refused_with_its_message() {
|
||||||
|
let z = zip_of(&[("document.json", b"{\"format\":2,\"anything\":\"new\"}")], zip::CompressionMethod::Stored);
|
||||||
|
let e = err(&z);
|
||||||
|
assert!(matches!(e, FormatError::Newer(2)), "{e:?}");
|
||||||
|
let msg = e.to_string();
|
||||||
|
assert!(msg.contains("newer Pictor") && msg.contains("format 2") && msg.contains("format 1"), "{msg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bad_path_is_refused() {
|
||||||
|
let good = String::from_utf8(plain_json()).unwrap();
|
||||||
|
let mut doc = pictor_doc::Document::a4();
|
||||||
|
let id = doc.new_id();
|
||||||
|
if let pictor_doc::LayerKind::Vector { objects } = &mut doc.pages[0].layers[0].kind {
|
||||||
|
objects.push(pictor_doc::Object {
|
||||||
|
id,
|
||||||
|
name: String::new(),
|
||||||
|
transform: pictor_doc::identity(),
|
||||||
|
opacity: 1.0,
|
||||||
|
visible: true,
|
||||||
|
locked: false,
|
||||||
|
fill: None,
|
||||||
|
stroke: None,
|
||||||
|
shape: pictor_doc::Shape::Path { d: "M0 0 A 1 1 0 0 1 5 5".into() },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let bytes = format::write(&doc, &[]).unwrap();
|
||||||
|
assert!(matches!(format::read(&bytes, &Limits::default()), Err(FormatError::Damaged(_))));
|
||||||
|
drop(good);
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
//! The core's painter: fixture documents render to what they say (spot colours at known places), and every fixture
|
||||||
|
//! is written to `target/tmp/render-<name>.png` for a look.
|
||||||
|
use pictor_doc::{FontBook, fixtures, render};
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
|
pub fn book() -> &'static FontBook {
|
||||||
|
static B: OnceLock<FontBook> = OnceLock::new();
|
||||||
|
B.get_or_init(FontBook::system)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn near(a: [u8; 4], b: [u8; 4], tol: i32) -> bool {
|
||||||
|
a.iter().zip(b).all(|(x, y)| (*x as i32 - y as i32).abs() <= tol)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fixtures_render_and_are_written_for_a_look() {
|
||||||
|
for (name, doc) in fixtures::all() {
|
||||||
|
let r = render::page(&doc, &doc.pages[0], book(), 2.0).expect("renders");
|
||||||
|
assert_eq!(
|
||||||
|
(r.width, r.height),
|
||||||
|
((doc.pages[0].width * 2.0).round() as u32, (doc.pages[0].height * 2.0).round() as u32)
|
||||||
|
);
|
||||||
|
let png = pictor_doc::format::encode_png(&r).unwrap();
|
||||||
|
std::fs::write(format!("{}/render-{name}.png", env!("CARGO_TARGET_TMPDIR")), png).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shapes_land_where_the_document_says() {
|
||||||
|
let doc = fixtures::shapes();
|
||||||
|
let r = render::page(&doc, &doc.pages[0], book(), 1.0).unwrap();
|
||||||
|
// Inside the navy rounded rectangle (20,20 140×90), away from its brass stroke.
|
||||||
|
assert!(near(r.pixel(90, 65), [0x1f, 0x2a, 0x44, 255], 2), "{:?}", r.pixel(90, 65));
|
||||||
|
// On its brass stroke (top edge at y = 20).
|
||||||
|
assert!(near(r.pixel(90, 20), [0xb0, 0x8d, 0x57, 255], 30), "{:?}", r.pixel(90, 20));
|
||||||
|
// The white paper outside everything.
|
||||||
|
assert_eq!(r.pixel(390, 5), [255, 255, 255, 255]);
|
||||||
|
// The group at 50 %: green over white is a light green.
|
||||||
|
let g = r.pixel(225, 155);
|
||||||
|
assert!(near(g, [0x9c, 0xe7, 0xbc, 255], 6), "{g:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bitmap_layer_at_scale_one_keeps_its_pixels() {
|
||||||
|
let mut doc = fixtures::bitmap();
|
||||||
|
doc.pages[0].layers[0].opacity = 1.0;
|
||||||
|
doc.pages[0].layers.truncate(1);
|
||||||
|
let r = render::page(&doc, &doc.pages[0], book(), 1.0).unwrap();
|
||||||
|
assert_eq!(r, doc.assets.values().next().unwrap().clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn text_is_drawn_in_its_colour() {
|
||||||
|
let doc = fixtures::text();
|
||||||
|
let r = render::page(&doc, &doc.pages[0], book(), 2.0).unwrap();
|
||||||
|
// Somewhere in the title's band there is navy ink.
|
||||||
|
let navy = (40..140)
|
||||||
|
.flat_map(|x| (36..90).map(move |y| (x, y)))
|
||||||
|
.any(|(x, y)| near(r.pixel(x, y), [0x1f, 0x2a, 0x44, 255], 20));
|
||||||
|
assert!(navy, "no navy title ink");
|
||||||
|
}
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
//! Day 3 mandatory test 2: undo is exact. Any random sequence of operations followed by the same number of undos
|
||||||
|
//! returns the document to its original state, and as many redos return the edited one.
|
||||||
|
use pictor_doc::ops::History;
|
||||||
|
use pictor_doc::*;
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
/// What a random step does; turned into a concrete operation against the document as it is at that moment.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
enum Step {
|
||||||
|
AddRect { x: f32, y: f32, w: f32, h: f32, color: [u8; 4] },
|
||||||
|
AddText { text: String, size: f32 },
|
||||||
|
RemoveObject { pick: usize },
|
||||||
|
MoveObject { pick: usize, dx: f32, dy: f32 },
|
||||||
|
Recolour { pick: usize, color: [u8; 4] },
|
||||||
|
AddLayer { at: usize },
|
||||||
|
RemoveLayer { pick: usize },
|
||||||
|
HideLayer { pick: usize, opacity: f32 },
|
||||||
|
Resize { w: f32, h: f32 },
|
||||||
|
Paint { x: u32, y: u32, w: u32, h: u32, color: [u8; 4] },
|
||||||
|
NewBitmap { w: u32, h: u32 },
|
||||||
|
Group { pick: usize },
|
||||||
|
AddPage,
|
||||||
|
RemovePage { pick: usize },
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step() -> impl Strategy<Value = Step> {
|
||||||
|
let color = any::<[u8; 4]>();
|
||||||
|
let f = -500.0f32..500.0;
|
||||||
|
prop_oneof![
|
||||||
|
(f.clone(), f.clone(), 1.0f32..300.0, 1.0f32..300.0, color).prop_map(|(x, y, w, h, color)| Step::AddRect {
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
w,
|
||||||
|
h,
|
||||||
|
color
|
||||||
|
}),
|
||||||
|
("[a-zA-Zá-ž ]{0,30}", 4.0f32..60.0).prop_map(|(text, size)| Step::AddText { text, size }),
|
||||||
|
any::<usize>().prop_map(|pick| Step::RemoveObject { pick }),
|
||||||
|
(any::<usize>(), f.clone(), f.clone()).prop_map(|(pick, dx, dy)| Step::MoveObject { pick, dx, dy }),
|
||||||
|
(any::<usize>(), color).prop_map(|(pick, color)| Step::Recolour { pick, color }),
|
||||||
|
any::<usize>().prop_map(|at| Step::AddLayer { at }),
|
||||||
|
any::<usize>().prop_map(|pick| Step::RemoveLayer { pick }),
|
||||||
|
(any::<usize>(), 0.0f32..=1.0).prop_map(|(pick, opacity)| Step::HideLayer { pick, opacity }),
|
||||||
|
(1.0f32..2000.0, 1.0f32..2000.0).prop_map(|(w, h)| Step::Resize { w, h }),
|
||||||
|
(0u32..300, 0u32..200, 1u32..120, 1u32..120, color).prop_map(|(x, y, w, h, color)| Step::Paint {
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
w,
|
||||||
|
h,
|
||||||
|
color
|
||||||
|
}),
|
||||||
|
(1u32..64, 1u32..64).prop_map(|(w, h)| Step::NewBitmap { w, h }),
|
||||||
|
any::<usize>().prop_map(|pick| Step::Group { pick }),
|
||||||
|
Just(Step::AddPage),
|
||||||
|
any::<usize>().prop_map(|pick| Step::RemovePage { pick }),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object(doc: &mut Document, shape: Shape, fill: Option<Paint>) -> Object {
|
||||||
|
Object {
|
||||||
|
id: doc.new_id(),
|
||||||
|
name: String::new(),
|
||||||
|
transform: identity(),
|
||||||
|
opacity: 1.0,
|
||||||
|
visible: true,
|
||||||
|
locked: false,
|
||||||
|
fill,
|
||||||
|
stroke: None,
|
||||||
|
shape,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every (page, vector layer, object) in the document.
|
||||||
|
fn all_objects(doc: &Document) -> Vec<(Id, Id, Object)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for p in &doc.pages {
|
||||||
|
fn walk(p: Id, ls: &[Layer], out: &mut Vec<(Id, Id, Object)>) {
|
||||||
|
for l in ls {
|
||||||
|
match &l.kind {
|
||||||
|
LayerKind::Vector { objects } => out.extend(objects.iter().map(|o| (p, l.id, o.clone()))),
|
||||||
|
LayerKind::Group { layers } => walk(p, layers, out),
|
||||||
|
LayerKind::Bitmap { .. } => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(p.id, &p.layers, &mut out);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn first_vector_layer(doc: &Document) -> Option<(Id, Id)> {
|
||||||
|
doc.pages
|
||||||
|
.iter()
|
||||||
|
.find_map(|p| p.layers.iter().find(|l| matches!(l.kind, LayerKind::Vector { .. })).map(|l| (p.id, l.id)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The operation for a step, or none when the document has nothing for it to act on. `doc` is only read, except
|
||||||
|
/// that taking new ids moves `next_id` (which the operation does not undo, as in the app).
|
||||||
|
fn op_for(doc: &mut Document, s: &Step) -> Option<Op> {
|
||||||
|
let objs = all_objects(doc);
|
||||||
|
let pick = |n: usize, len: usize| if len == 0 { None } else { Some(n % len) };
|
||||||
|
Some(match s {
|
||||||
|
Step::AddRect { x, y, w, h, color } => {
|
||||||
|
let (page, layer) = first_vector_layer(doc)?;
|
||||||
|
let mut o = object(doc, Shape::Rect { w: *w, h: *h, radius: 0.0 }, Some(Paint::solid(Rgba(*color))));
|
||||||
|
o.transform[4] = *x;
|
||||||
|
o.transform[5] = *y;
|
||||||
|
Op::InsertObject { page, layer, parent: None, index: 0, object: o }
|
||||||
|
}
|
||||||
|
Step::AddText { text, size } => {
|
||||||
|
let (page, layer) = first_vector_layer(doc)?;
|
||||||
|
let style = TextStyle {
|
||||||
|
family: "Arial".into(),
|
||||||
|
weight: 400,
|
||||||
|
italic: false,
|
||||||
|
size: *size,
|
||||||
|
color: Rgba::BLACK,
|
||||||
|
align: Align::Left,
|
||||||
|
line_height: 1.2,
|
||||||
|
letter_spacing: 0.0,
|
||||||
|
};
|
||||||
|
let o = object(doc, Shape::Text { w: 100.0, text: text.clone(), style }, None);
|
||||||
|
Op::InsertObject { page, layer, parent: None, index: 0, object: o }
|
||||||
|
}
|
||||||
|
Step::RemoveObject { pick: n } => {
|
||||||
|
let (page, layer, o) = objs.get(pick(*n, objs.len())?)?.clone();
|
||||||
|
let index = layer_objects(doc, page, layer).iter().position(|x| x.id == o.id)?;
|
||||||
|
Op::RemoveObject { page, layer, parent: None, index }
|
||||||
|
}
|
||||||
|
Step::MoveObject { pick: n, dx, dy } => {
|
||||||
|
let (page, layer, mut o) = objs.get(pick(*n, objs.len())?)?.clone();
|
||||||
|
o.transform[4] += dx;
|
||||||
|
o.transform[5] += dy;
|
||||||
|
Op::ReplaceObject { page, layer, object: o }
|
||||||
|
}
|
||||||
|
Step::Recolour { pick: n, color } => {
|
||||||
|
let (page, layer, mut o) = objs.get(pick(*n, objs.len())?)?.clone();
|
||||||
|
o.fill = Some(Paint::solid(Rgba(*color)));
|
||||||
|
Op::ReplaceObject { page, layer, object: o }
|
||||||
|
}
|
||||||
|
Step::AddLayer { at } => {
|
||||||
|
let page = doc.pages.first()?.id;
|
||||||
|
let len = doc.pages[0].layers.len();
|
||||||
|
let id = doc.new_id();
|
||||||
|
Op::InsertLayer { page, parent: None, index: at % (len + 1), layer: Layer::vector(id, "New") }
|
||||||
|
}
|
||||||
|
Step::RemoveLayer { pick: n } => {
|
||||||
|
let p = doc.pages.first()?;
|
||||||
|
Op::RemoveLayer { page: p.id, parent: None, index: pick(*n, p.layers.len())? }
|
||||||
|
}
|
||||||
|
Step::HideLayer { pick: n, opacity } => {
|
||||||
|
let p = doc.pages.first()?;
|
||||||
|
let l = &p.layers[pick(*n, p.layers.len())?];
|
||||||
|
Op::SetLayer {
|
||||||
|
page: p.id,
|
||||||
|
layer: l.id,
|
||||||
|
name: format!("{} *", l.name),
|
||||||
|
visible: !l.visible,
|
||||||
|
locked: !l.locked,
|
||||||
|
opacity: *opacity,
|
||||||
|
place: match l.kind {
|
||||||
|
LayerKind::Bitmap { .. } => Some(Rect { x: 1.0, y: 2.0, w: 30.0, h: 40.0 }),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Step::Resize { w, h } => {
|
||||||
|
let p = doc.pages.first()?;
|
||||||
|
Op::SetPage {
|
||||||
|
page: p.id,
|
||||||
|
width: *w,
|
||||||
|
height: *h,
|
||||||
|
margins: [w / 20.0; 4],
|
||||||
|
guides: vec![Guide { vertical: true, at: w / 2.0 }],
|
||||||
|
background: Some(Rgba::WHITE),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Step::Paint { x, y, w, h, color } => {
|
||||||
|
let (asset, r) = doc.assets.iter().next()?;
|
||||||
|
let rect = PixelRect { x: *x, y: *y, w: *w, h: *h }.clamp(r.width, r.height);
|
||||||
|
if rect.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let pixels = std::iter::repeat_n(*color, (rect.w * rect.h) as usize).flatten().collect();
|
||||||
|
Op::Patch { asset: asset.clone(), rect, pixels }
|
||||||
|
}
|
||||||
|
Step::NewBitmap { w, h } => {
|
||||||
|
let page = doc.pages.first()?.id;
|
||||||
|
let id = doc.new_id();
|
||||||
|
let asset = format!("b{id}");
|
||||||
|
let layer = Layer {
|
||||||
|
id,
|
||||||
|
name: "Paint".into(),
|
||||||
|
visible: true,
|
||||||
|
locked: false,
|
||||||
|
opacity: 1.0,
|
||||||
|
kind: LayerKind::Bitmap { asset: asset.clone(), x: 0.0, y: 0.0, w: *w as f32, h: *h as f32 },
|
||||||
|
};
|
||||||
|
Op::Batch {
|
||||||
|
ops: vec![
|
||||||
|
Op::PutAsset { asset, raster: Some(Raster::filled(*w, *h, [9, 8, 7, 6])) },
|
||||||
|
Op::InsertLayer { page, parent: None, index: 0, layer },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Step::Group { pick: n } => {
|
||||||
|
// Group two objects of one layer: remove both, insert a group holding them.
|
||||||
|
let (page, layer) = first_vector_layer(doc)?;
|
||||||
|
let list = layer_objects(doc, page, layer);
|
||||||
|
if list.len() < 2 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let i = n % (list.len() - 1);
|
||||||
|
let (a, b) = (list[i].clone(), list[i + 1].clone());
|
||||||
|
let g = object(doc, Shape::Group { objects: vec![a, b] }, None);
|
||||||
|
Op::Batch {
|
||||||
|
ops: vec![
|
||||||
|
Op::RemoveObject { page, layer, parent: None, index: i + 1 },
|
||||||
|
Op::RemoveObject { page, layer, parent: None, index: i },
|
||||||
|
Op::InsertObject { page, layer, parent: None, index: i, object: g },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Step::AddPage => {
|
||||||
|
let pid = doc.new_id();
|
||||||
|
let lid = doc.new_id();
|
||||||
|
let page = Page {
|
||||||
|
id: pid,
|
||||||
|
width: 100.0,
|
||||||
|
height: 100.0,
|
||||||
|
margins: [0.0; 4],
|
||||||
|
guides: vec![],
|
||||||
|
background: None,
|
||||||
|
layers: vec![Layer::vector(lid, "Layer")],
|
||||||
|
};
|
||||||
|
Op::InsertPage { index: doc.pages.len(), page }
|
||||||
|
}
|
||||||
|
Step::RemovePage { pick: n } => {
|
||||||
|
if doc.pages.len() < 2 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Op::RemovePage { index: n % doc.pages.len() }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layer_objects(doc: &Document, page: Id, layer: Id) -> Vec<Object> {
|
||||||
|
match doc.page(page).and_then(|p| p.layer(layer)).map(|l| &l.kind) {
|
||||||
|
Some(LayerKind::Vector { objects }) => objects.clone(),
|
||||||
|
_ => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 256, .. ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn random_edits_then_as_many_undos_restore_the_document(
|
||||||
|
start in 0usize..4,
|
||||||
|
steps in proptest::collection::vec(step(), 1..60),
|
||||||
|
) {
|
||||||
|
let mut doc = fixtures::all().swap_remove(start).1;
|
||||||
|
let mut history = History::default();
|
||||||
|
let mut n = 0;
|
||||||
|
for s in &steps {
|
||||||
|
if let Some(op) = op_for(&mut doc, s) {
|
||||||
|
history.apply(&mut doc, op).expect("a well-formed operation applies");
|
||||||
|
n += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// next_id only grows (ids are never reused); compare everything else.
|
||||||
|
let edited = doc.clone();
|
||||||
|
let mut original = fixtures::all().swap_remove(start).1;
|
||||||
|
original.next_id = doc.next_id;
|
||||||
|
for _ in 0..n {
|
||||||
|
prop_assert!(history.undo(&mut doc).unwrap());
|
||||||
|
}
|
||||||
|
prop_assert!(!history.undo(&mut doc).unwrap(), "more undos than edits");
|
||||||
|
prop_assert_eq!(&doc, &original);
|
||||||
|
for _ in 0..n {
|
||||||
|
prop_assert!(history.redo(&mut doc).unwrap());
|
||||||
|
}
|
||||||
|
prop_assert_eq!(&doc, &edited);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failing_batch_leaves_nothing_behind() {
|
||||||
|
let mut doc = fixtures::shapes();
|
||||||
|
let before = doc.clone();
|
||||||
|
let page = doc.pages[0].id;
|
||||||
|
let layer = doc.pages[0].layers[0].id;
|
||||||
|
let bad = Op::Batch {
|
||||||
|
ops: vec![
|
||||||
|
Op::RemoveObject { page, layer, parent: None, index: 0 },
|
||||||
|
Op::RemoveObject { page, layer, parent: None, index: 99 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let mut h = History::default();
|
||||||
|
assert!(h.apply(&mut doc, bad).is_err());
|
||||||
|
assert_eq!(doc, before);
|
||||||
|
assert!(!h.can_undo());
|
||||||
|
}
|
||||||
@@ -14,7 +14,10 @@ lopdf.workspace = true
|
|||||||
pdfium-render.workspace = true
|
pdfium-render.workspace = true
|
||||||
pictor-meta.workspace = true
|
pictor-meta.workspace = true
|
||||||
getrandom.workspace = true
|
getrandom.workspace = true
|
||||||
|
docx-rs.workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
flate2.workspace = true
|
flate2.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
|
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||||
|
tempfile.workspace = true
|
||||||
|
|||||||
@@ -0,0 +1,246 @@
|
|||||||
|
//! Compress presets (Day 2): images are downsampled to the preset's resolution and re-encoded as JPEG, every stream
|
||||||
|
//! is Flate-compressed, unreferenced objects are dropped and the file is written with object streams. Text, fonts,
|
||||||
|
//! vector content and the page structure are not touched, so all text stays extractable.
|
||||||
|
//!
|
||||||
|
//! "Resolution" needs no content-stream analysis: an image is never shown larger than the largest page, so its
|
||||||
|
//! pixel size is capped at (largest page side in inches × the preset's dpi). Images Pictor cannot decode safely
|
||||||
|
//! (JPEG 2000, CCITT, JBIG2, indexed or 16-bit colour, masks) are left as they are. Fonts are not subset (a gap,
|
||||||
|
//! recorded in docs/02_v1-1.md of the app).
|
||||||
|
use crate::{PdfError, lopdf_load};
|
||||||
|
use image::{DynamicImage, GenericImageView};
|
||||||
|
use lopdf::{Dictionary, Document, Object, Stream};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum CompressPreset {
|
||||||
|
/// Small enough to attach to an e-mail: target 5 MB or less.
|
||||||
|
Email,
|
||||||
|
/// For the web and the screen.
|
||||||
|
Web,
|
||||||
|
/// Good enough to print.
|
||||||
|
Print,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The E-mail preset's target.
|
||||||
|
pub const EMAIL_TARGET: usize = 5 << 20;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Compressed {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub before: usize,
|
||||||
|
pub after: usize,
|
||||||
|
pub images_changed: usize,
|
||||||
|
/// Plain sentences (for example: the E-mail target could not be reached).
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Step {
|
||||||
|
dpi: f32,
|
||||||
|
quality: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn steps(preset: CompressPreset) -> &'static [Step] {
|
||||||
|
match preset {
|
||||||
|
CompressPreset::Email => {
|
||||||
|
&[Step { dpi: 120.0, quality: 62 }, Step { dpi: 96.0, quality: 55 }, Step { dpi: 72.0, quality: 50 }]
|
||||||
|
}
|
||||||
|
CompressPreset::Web => &[Step { dpi: 150.0, quality: 72 }],
|
||||||
|
CompressPreset::Print => &[Step { dpi: 300.0, quality: 86 }],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compresses a document with a preset. A protected document stays protected with the same password.
|
||||||
|
pub fn compress(bytes: &[u8], password: Option<&str>, preset: CompressPreset) -> Result<Compressed, PdfError> {
|
||||||
|
let mut last = None;
|
||||||
|
for (i, step) in steps(preset).iter().enumerate() {
|
||||||
|
let r = compress_step(bytes, password, step)?;
|
||||||
|
let done = preset != CompressPreset::Email || r.after <= EMAIL_TARGET || i + 1 == steps(preset).len();
|
||||||
|
last = Some(r);
|
||||||
|
if done {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut r = last.expect("at least one step");
|
||||||
|
if preset == CompressPreset::Email && r.after > EMAIL_TARGET {
|
||||||
|
r.warnings.push(format!(
|
||||||
|
"Pictor got it down to {:.1} MB; the rest is text, fonts and drawings it does not change.",
|
||||||
|
r.after as f64 / 1048576.0
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Never hand back something bigger than the original.
|
||||||
|
if r.after >= r.before {
|
||||||
|
r.bytes = bytes.to_vec();
|
||||||
|
r.after = r.before;
|
||||||
|
r.images_changed = 0;
|
||||||
|
r.warnings.push("This PDF is already as small as Pictor can make it.".into());
|
||||||
|
}
|
||||||
|
Ok(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compress_step(bytes: &[u8], password: Option<&str>, step: &Step) -> Result<Compressed, PdfError> {
|
||||||
|
let mut doc = lopdf_load(bytes, password)?;
|
||||||
|
let largest_side_in = largest_page_side(&doc) / 72.0;
|
||||||
|
let max_px = (largest_side_in * step.dpi).ceil().max(64.0) as u32;
|
||||||
|
let ids: Vec<_> = doc.objects.keys().copied().collect();
|
||||||
|
let masks = soft_masks(&doc);
|
||||||
|
let mut changed = 0;
|
||||||
|
for id in ids {
|
||||||
|
if masks.contains(&id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(Object::Stream(s)) = doc.objects.get(&id) else { continue };
|
||||||
|
if !is_image(&s.dict) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(new) = recompress(&doc, s, max_px, step.quality) else { continue };
|
||||||
|
if let Some(Object::Stream(s)) = doc.objects.get_mut(&id) {
|
||||||
|
*s = new;
|
||||||
|
changed += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
doc.compress();
|
||||||
|
doc.prune_objects();
|
||||||
|
let opts = lopdf::SaveOptions::builder().use_object_streams(true).use_xref_streams(true).build();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
match password {
|
||||||
|
Some(p) => {
|
||||||
|
let plain = {
|
||||||
|
let mut v = Vec::new();
|
||||||
|
doc.save_with_options(&mut v, opts).map_err(|e| PdfError::Write(e.to_string()))?;
|
||||||
|
v
|
||||||
|
};
|
||||||
|
out = crate::protect(&plain, None, p, None)?;
|
||||||
|
}
|
||||||
|
None => doc.save_with_options(&mut out, opts).map_err(|e| PdfError::Write(e.to_string()))?,
|
||||||
|
}
|
||||||
|
Ok(Compressed { before: bytes.len(), after: out.len(), bytes: out, images_changed: changed, warnings: Vec::new() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn largest_page_side(doc: &Document) -> f32 {
|
||||||
|
let mut side: f32 = 0.0;
|
||||||
|
for page in doc.get_pages().values() {
|
||||||
|
let f = crate::edit::lopdf_frame(doc, *page);
|
||||||
|
side = side.max(f.crop[2] - f.crop[0]).max(f.crop[3] - f.crop[1]);
|
||||||
|
}
|
||||||
|
if side <= 0.0 { 842.0 } else { side.min(14_400.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Images used as another image's soft mask: left alone (their size must stay what their parent expects).
|
||||||
|
fn soft_masks(doc: &Document) -> std::collections::HashSet<lopdf::ObjectId> {
|
||||||
|
doc.objects
|
||||||
|
.values()
|
||||||
|
.filter_map(|o| match o {
|
||||||
|
Object::Stream(s) => s.dict.get(b"SMask").ok().and_then(|m| m.as_reference().ok()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_image(d: &Dictionary) -> bool {
|
||||||
|
matches!(d.get(b"Subtype"), Ok(Object::Name(n)) if n == b"Image")
|
||||||
|
&& !matches!(d.get(b"ImageMask"), Ok(Object::Boolean(true)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name_or_first(o: Option<&Object>) -> Option<Vec<u8>> {
|
||||||
|
match o? {
|
||||||
|
Object::Name(n) => Some(n.clone()),
|
||||||
|
Object::Array(a) if a.len() == 1 => a[0].as_name().ok().map(|n| n.to_vec()),
|
||||||
|
Object::Array(a) if a.is_empty() => Some(Vec::new()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Channels of a colour space Pictor can re-encode as JPEG: DeviceGray, DeviceRGB, or ICCBased with N 1 or 3.
|
||||||
|
fn channels(doc: &Document, cs: Option<&Object>) -> Option<u8> {
|
||||||
|
let cs = match cs? {
|
||||||
|
Object::Reference(r) => doc.get_object(*r).ok()?,
|
||||||
|
o => o,
|
||||||
|
};
|
||||||
|
match cs {
|
||||||
|
Object::Name(n) if n == b"DeviceGray" => Some(1),
|
||||||
|
Object::Name(n) if n == b"DeviceRGB" => Some(3),
|
||||||
|
Object::Array(a) if a.len() == 2 && a[0].as_name().ok() == Some(b"ICCBased") => {
|
||||||
|
let s = match &a[1] {
|
||||||
|
Object::Reference(r) => doc.get_object(*r).ok()?.as_stream().ok()?,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
match s.dict.get(b"N").ok()?.as_i64().ok()? {
|
||||||
|
1 => Some(1),
|
||||||
|
3 => Some(3),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recompress(doc: &Document, s: &Stream, max_px: u32, quality: u8) -> Option<Stream> {
|
||||||
|
let d = &s.dict;
|
||||||
|
let w = d.get(b"Width").ok()?.as_i64().ok()? as u32;
|
||||||
|
let h = d.get(b"Height").ok()?.as_i64().ok()? as u32;
|
||||||
|
if w == 0 || h == 0 || (w as u64) * (h as u64) > 150_000_000 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if d.get(b"BitsPerComponent").ok().and_then(|b| b.as_i64().ok()) != Some(8) || d.has(b"Decode") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n = channels(doc, d.get(b"ColorSpace").ok())?;
|
||||||
|
let filter = name_or_first(d.get(b"Filter").ok()).unwrap_or_default();
|
||||||
|
let img: DynamicImage = match &filter[..] {
|
||||||
|
b"DCTDecode" => {
|
||||||
|
let i = image::load_from_memory_with_format(&s.content, image::ImageFormat::Jpeg).ok()?;
|
||||||
|
// CMYK JPEGs (Adobe) and odd channel counts are left alone.
|
||||||
|
if i.color().channel_count() != n {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
i
|
||||||
|
}
|
||||||
|
b"FlateDecode" | b"" => {
|
||||||
|
let raw = if filter.is_empty() {
|
||||||
|
s.content.clone()
|
||||||
|
} else {
|
||||||
|
s.decompressed_content_with_limit(600 << 20).ok()?
|
||||||
|
};
|
||||||
|
let need = (w as usize) * (h as usize) * n as usize;
|
||||||
|
if raw.len() < need {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match n {
|
||||||
|
1 => DynamicImage::ImageLuma8(image::GrayImage::from_raw(w, h, raw[..need].to_vec())?),
|
||||||
|
_ => DynamicImage::ImageRgb8(image::RgbImage::from_raw(w, h, raw[..need].to_vec())?),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
let (iw, ih) = img.dimensions();
|
||||||
|
let img = if iw.max(ih) > max_px + max_px / 10 {
|
||||||
|
let k = max_px as f32 / iw.max(ih) as f32;
|
||||||
|
img.resize_exact(
|
||||||
|
((iw as f32 * k).round() as u32).max(1),
|
||||||
|
((ih as f32 * k).round() as u32).max(1),
|
||||||
|
image::imageops::FilterType::Lanczos3,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
img
|
||||||
|
};
|
||||||
|
let mut jpeg = Vec::new();
|
||||||
|
let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, quality);
|
||||||
|
match n {
|
||||||
|
1 => img.to_luma8().write_with_encoder(enc).ok()?,
|
||||||
|
_ => img.to_rgb8().write_with_encoder(enc).ok()?,
|
||||||
|
}
|
||||||
|
let old = s.content.len();
|
||||||
|
if jpeg.len() as f64 > old as f64 * 0.9 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut dict = d.clone();
|
||||||
|
dict.set("Width", img.width() as i64);
|
||||||
|
dict.set("Height", img.height() as i64);
|
||||||
|
dict.set("Filter", "DCTDecode");
|
||||||
|
dict.remove(b"DecodeParms");
|
||||||
|
dict.remove(b"Length");
|
||||||
|
let mut out = Stream::new(dict, jpeg);
|
||||||
|
out.allows_compression = false;
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
//! Every function takes the document as bytes plus an optional password and returns new bytes: nothing here touches
|
//! Every function takes the document as bytes plus an optional password and returns new bytes: nothing here touches
|
||||||
//! the file system. Outside files are hostile; call these only inside `pictor-worker`.
|
//! the file system. Outside files are hostile; call these only inside `pictor-worker`.
|
||||||
|
|
||||||
|
mod compress;
|
||||||
mod edit;
|
mod edit;
|
||||||
mod engine;
|
mod engine;
|
||||||
mod error;
|
mod error;
|
||||||
@@ -16,7 +17,9 @@ mod pages;
|
|||||||
mod reader;
|
mod reader;
|
||||||
mod redact;
|
mod redact;
|
||||||
mod security;
|
mod security;
|
||||||
|
mod word;
|
||||||
|
|
||||||
|
pub use compress::{CompressPreset, Compressed, EMAIL_TARGET, compress};
|
||||||
pub use edit::*;
|
pub use edit::*;
|
||||||
pub use engine::Engine;
|
pub use engine::Engine;
|
||||||
pub use error::PdfError;
|
pub use error::PdfError;
|
||||||
@@ -25,6 +28,7 @@ pub use pages::*;
|
|||||||
pub use reader::*;
|
pub use reader::*;
|
||||||
pub use redact::{RedactOptions, Redacted, Redaction, redact};
|
pub use redact::{RedactOptions, Redacted, Redaction, redact};
|
||||||
pub use security::{is_encrypted, protect, unlock};
|
pub use security::{is_encrypted, protect, unlock};
|
||||||
|
pub use word::{WordOptions, WordResult, to_word};
|
||||||
|
|
||||||
/// lopdf loading with the caps Pictor uses everywhere (a stream may decompress to at most 256 MiB).
|
/// lopdf loading with the caps Pictor uses everywhere (a stream may decompress to at most 256 MiB).
|
||||||
pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result<lopdf::Document, PdfError> {
|
pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result<lopdf::Document, PdfError> {
|
||||||
|
|||||||
@@ -0,0 +1,504 @@
|
|||||||
|
//! PDF to Word (Day 2): editable text with its structure, not a pixel copy ("Layout is approximate").
|
||||||
|
//!
|
||||||
|
//! pdfium gives every character with its box, size, weight and slant. Pictor rebuilds, per page, top to bottom:
|
||||||
|
//! lines (characters on one baseline), segments (pieces of a line split by a wide gap), tables (two or more
|
||||||
|
//! consecutive lines whose segments start at the same columns), paragraphs (consecutive single-segment lines of the
|
||||||
|
//! same size and left edge, close together), headings (clearly larger or bold-and-short text, measured against the
|
||||||
|
//! document's body size) and images (each image object, at its place). The .docx is written by docx-rs.
|
||||||
|
//!
|
||||||
|
//! A page with (almost) no text but an image is a scan: it is listed in `scanned_pages`, and text recognised
|
||||||
|
//! elsewhere (Fundamentum's Lector, through the app) can be passed back in `WordOptions::ocr` for those pages.
|
||||||
|
use crate::{Engine, PdfError};
|
||||||
|
use docx_rs::{BreakType, Docx, Paragraph, Pic, Run, RunFonts, Style, StyleType, Table, TableCell, TableRow};
|
||||||
|
use pdfium_render::prelude::*;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct WordOptions {
|
||||||
|
/// Recognised text for scanned pages (0-based page → text; blank lines separate paragraphs).
|
||||||
|
pub ocr: HashMap<usize, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct WordResult {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub pages: usize,
|
||||||
|
/// Pages with no text layer (scans) that had no OCR text given.
|
||||||
|
pub scanned_pages: Vec<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Ch {
|
||||||
|
c: char,
|
||||||
|
x0: f32,
|
||||||
|
x1: f32,
|
||||||
|
y0: f32,
|
||||||
|
y1: f32,
|
||||||
|
size: f32,
|
||||||
|
bold: bool,
|
||||||
|
italic: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct Line {
|
||||||
|
chars: Vec<Ch>,
|
||||||
|
top: f32,
|
||||||
|
bottom: f32,
|
||||||
|
size: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Line {
|
||||||
|
fn left(&self) -> f32 {
|
||||||
|
self.chars.first().map(|c| c.x0).unwrap_or(0.0)
|
||||||
|
}
|
||||||
|
/// Pieces of the line separated by a gap wider than 2.2 × the font size.
|
||||||
|
fn segments(&self) -> Vec<Vec<Ch>> {
|
||||||
|
let mut out: Vec<Vec<Ch>> = Vec::new();
|
||||||
|
let mut cur: Vec<Ch> = Vec::new();
|
||||||
|
for ch in &self.chars {
|
||||||
|
if let Some(prev) = cur.iter().rev().find(|c| !c.c.is_whitespace())
|
||||||
|
&& ch.x0 - prev.x1 > 2.2 * self.size.max(1.0)
|
||||||
|
&& !ch.c.is_whitespace()
|
||||||
|
{
|
||||||
|
out.push(std::mem::take(&mut cur));
|
||||||
|
}
|
||||||
|
cur.push(ch.clone());
|
||||||
|
}
|
||||||
|
if !cur.is_empty() {
|
||||||
|
out.push(cur);
|
||||||
|
}
|
||||||
|
out.into_iter().map(trim).filter(|s| !s.is_empty()).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trim(mut v: Vec<Ch>) -> Vec<Ch> {
|
||||||
|
while v.first().is_some_and(|c| c.c.is_whitespace()) {
|
||||||
|
v.remove(0);
|
||||||
|
}
|
||||||
|
while v.last().is_some_and(|c| c.c.is_whitespace()) {
|
||||||
|
v.pop();
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Item {
|
||||||
|
Lines(Vec<Line>),
|
||||||
|
Image { top: f32, png: Vec<u8>, w_px: u32, h_px: u32, w_pt: f32, h_pt: f32 },
|
||||||
|
}
|
||||||
|
|
||||||
|
fn item_top(i: &Item) -> f32 {
|
||||||
|
match i {
|
||||||
|
Item::Lines(l) => l.first().map(|l| l.top).unwrap_or(0.0),
|
||||||
|
Item::Image { top, .. } => *top,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn page_chars(page: &PdfPage) -> Result<Vec<Ch>, PdfError> {
|
||||||
|
let text = page.text().map_err(PdfError::from_pdfium)?;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for ch in text.chars().iter() {
|
||||||
|
let Some(c) = ch.unicode_char() else { continue };
|
||||||
|
if c == '\r' || c == '\n' || c == '\u{2}' || c == '\u{fffe}' {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Ok(b) = ch.loose_bounds() else { continue };
|
||||||
|
let name = ch.font_name().to_ascii_lowercase();
|
||||||
|
let weight = matches!(ch.font_weight(), Some(w) if matches!(w, PdfFontWeight::Weight600 | PdfFontWeight::Weight700Bold | PdfFontWeight::Weight800 | PdfFontWeight::Weight900 | PdfFontWeight::Custom(600..)));
|
||||||
|
out.push(Ch {
|
||||||
|
c,
|
||||||
|
x0: b.left().value,
|
||||||
|
x1: b.right().value,
|
||||||
|
y0: b.bottom().value,
|
||||||
|
y1: b.top().value,
|
||||||
|
size: ch.scaled_font_size().value.max(1.0),
|
||||||
|
bold: weight || name.contains("bold") || name.contains("black") || name.contains("heavy"),
|
||||||
|
italic: ch.font_is_italic() || name.contains("italic") || name.contains("oblique"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The median gap between neighbouring visible characters of a line (sorted by x), not below 0; 0 for short lines.
|
||||||
|
fn median_gap(chars: &[Ch]) -> f32 {
|
||||||
|
let visible: Vec<&Ch> = chars.iter().filter(|c| !c.c.is_whitespace()).collect();
|
||||||
|
let mut gaps: Vec<f32> = visible.windows(2).map(|w| w[1].x0 - w[0].x1).collect();
|
||||||
|
if gaps.len() < 4 {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
gaps.sort_by(f32::total_cmp);
|
||||||
|
gaps[gaps.len() / 2].max(0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Characters in pdfium's order → lines, top to bottom (PDF y grows upwards).
|
||||||
|
fn lines(chars: Vec<Ch>) -> Vec<Line> {
|
||||||
|
let mut lines: Vec<Line> = Vec::new();
|
||||||
|
for ch in chars {
|
||||||
|
let mid = (ch.y0 + ch.y1) / 2.0;
|
||||||
|
let found = lines.iter_mut().rev().take(3).find(|l| {
|
||||||
|
let lmid = (l.top + l.bottom) / 2.0;
|
||||||
|
(mid - lmid).abs() < 0.45 * l.size.max(ch.size)
|
||||||
|
});
|
||||||
|
match found {
|
||||||
|
Some(l) => {
|
||||||
|
l.top = l.top.max(ch.y1);
|
||||||
|
l.bottom = l.bottom.min(ch.y0);
|
||||||
|
if !ch.c.is_whitespace() {
|
||||||
|
l.size = l.size.max(ch.size);
|
||||||
|
}
|
||||||
|
l.chars.push(ch);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let size = ch.size;
|
||||||
|
lines.push(Line { top: ch.y1, bottom: ch.y0, size, chars: vec![ch] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for l in &mut lines {
|
||||||
|
l.chars.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
||||||
|
// Spaces come from the gaps between letters, not from pdfium's whitespace: many PDFs have no space glyphs,
|
||||||
|
// and pdfium then invents zero-width spaces, some of them inside a word where the producer split it into
|
||||||
|
// two text objects ("Dichotomou" + "s"). A whitespace character only lowers the gap a space needs.
|
||||||
|
// The gap is measured against the line's own letter spacing (its median gap: most neighbours are letters of
|
||||||
|
// one word), so justified text with narrow word gaps (0.14 em) is spaced and tracked-out headings are not
|
||||||
|
// split into letters.
|
||||||
|
let letter_gap = median_gap(&l.chars);
|
||||||
|
let mut with_spaces: Vec<Ch> = Vec::with_capacity(l.chars.len());
|
||||||
|
let mut whitespace_seen = false;
|
||||||
|
for ch in std::mem::take(&mut l.chars) {
|
||||||
|
if ch.c.is_whitespace() {
|
||||||
|
whitespace_seen = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(prev) = with_spaces.last() {
|
||||||
|
let gap = ch.x0 - prev.x1 - letter_gap;
|
||||||
|
let size = ch.size.max(prev.size);
|
||||||
|
if gap > 0.1 * size || (whitespace_seen && gap > 0.05 * size) {
|
||||||
|
let mut sp = prev.clone();
|
||||||
|
sp.c = ' ';
|
||||||
|
with_spaces.push(sp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
whitespace_seen = false;
|
||||||
|
with_spaces.push(ch);
|
||||||
|
}
|
||||||
|
l.chars = with_spaces;
|
||||||
|
}
|
||||||
|
lines.retain(|l| l.chars.iter().any(|c| !c.c.is_whitespace()));
|
||||||
|
lines.sort_by(|a, b| b.top.total_cmp(&a.top));
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body_size(all: &[Vec<Line>]) -> f32 {
|
||||||
|
let mut counts: HashMap<u32, usize> = HashMap::new();
|
||||||
|
for l in all.iter().flatten() {
|
||||||
|
*counts.entry((l.size * 2.0).round() as u32).or_default() += l.chars.len();
|
||||||
|
}
|
||||||
|
counts.into_iter().max_by_key(|(_, n)| *n).map(|(s, _)| s as f32 / 2.0).unwrap_or(11.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn heading_level(chars: &[Ch], size: f32, body: f32) -> Option<usize> {
|
||||||
|
let len = chars.iter().filter(|c| !c.c.is_whitespace()).count();
|
||||||
|
let bold = chars.iter().filter(|c| !c.c.is_whitespace()).all(|c| c.bold);
|
||||||
|
if size >= body * 1.8 {
|
||||||
|
Some(1)
|
||||||
|
} else if size >= body * 1.25 {
|
||||||
|
Some(2)
|
||||||
|
} else if bold && len <= 80 && size >= body * 1.05 {
|
||||||
|
Some(3)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn runs(chars: &[Ch]) -> Vec<Run> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
while i < chars.len() {
|
||||||
|
let (b, it, sz) = (chars[i].bold, chars[i].italic, (chars[i].size * 2.0).round() as usize);
|
||||||
|
let mut j = i;
|
||||||
|
let mut s = String::new();
|
||||||
|
while j < chars.len() && chars[j].bold == b && chars[j].italic == it {
|
||||||
|
s.push(chars[j].c);
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
let mut r = Run::new().add_text(s).size(sz.clamp(8, 144));
|
||||||
|
if b {
|
||||||
|
r = r.bold();
|
||||||
|
}
|
||||||
|
if it {
|
||||||
|
r = r.italic();
|
||||||
|
}
|
||||||
|
out.push(r);
|
||||||
|
i = j;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One page's lines → paragraphs and tables, in order.
|
||||||
|
fn blocks(lines: Vec<Line>, body: f32, mut out: Docx) -> Docx {
|
||||||
|
let mut i = 0;
|
||||||
|
while i < lines.len() {
|
||||||
|
// A table: two or more consecutive lines with ≥ 2 segments whose starts line up.
|
||||||
|
let segs = lines[i].segments();
|
||||||
|
if segs.len() >= 2 {
|
||||||
|
let cols: Vec<f32> = segs.iter().map(|s| s[0].x0).collect();
|
||||||
|
let mut rows = vec![segs];
|
||||||
|
let mut j = i + 1;
|
||||||
|
while j < lines.len() {
|
||||||
|
let s = lines[j].segments();
|
||||||
|
let fits = s.len() == cols.len()
|
||||||
|
&& s.iter().zip(&cols).all(|(seg, x)| (seg[0].x0 - x).abs() < 0.8 * lines[j].size.max(6.0));
|
||||||
|
let close = lines[j - 1].bottom - lines[j].top < 2.5 * lines[j].size;
|
||||||
|
if !fits || !close {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
rows.push(s);
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
if rows.len() >= 2 {
|
||||||
|
let table = Table::new(
|
||||||
|
rows.iter()
|
||||||
|
.map(|r| {
|
||||||
|
TableRow::new(
|
||||||
|
r.iter()
|
||||||
|
.map(|cell| {
|
||||||
|
TableCell::new().add_paragraph(
|
||||||
|
runs(cell).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r)),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
);
|
||||||
|
out = out.add_table(table);
|
||||||
|
i = j;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A paragraph: join following lines of the same size and left edge that sit close below.
|
||||||
|
let first = &lines[i];
|
||||||
|
let mut chars: Vec<Ch> = first.chars.clone();
|
||||||
|
let mut j = i + 1;
|
||||||
|
while j < lines.len() {
|
||||||
|
let (prev, next) = (&lines[j - 1], &lines[j]);
|
||||||
|
let same_size = (next.size - first.size).abs() < 0.6;
|
||||||
|
let same_left = (next.left() - first.left()).abs() < 1.5 * first.size;
|
||||||
|
let close = prev.bottom - next.top < 1.0 * first.size;
|
||||||
|
if !(same_size && same_left && close)
|
||||||
|
|| next.segments().len() > 1
|
||||||
|
|| heading_level(&first.chars, first.size, body).is_some()
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// A hyphen at a line end joins the word; else a space.
|
||||||
|
if chars.last().is_some_and(|c| c.c == '-' || c.c == '\u{ad}') {
|
||||||
|
chars.pop();
|
||||||
|
} else {
|
||||||
|
let mut sp = chars.last().cloned().expect("non-empty");
|
||||||
|
sp.c = ' ';
|
||||||
|
chars.push(sp);
|
||||||
|
}
|
||||||
|
chars.extend(next.chars.iter().cloned());
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
let chars = trim(chars);
|
||||||
|
let mut p = runs(&chars).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r));
|
||||||
|
if let Some(level) = heading_level(&chars, first.size, body) {
|
||||||
|
p = p.style(&format!("Heading{level}"));
|
||||||
|
}
|
||||||
|
out = out.add_paragraph(p);
|
||||||
|
i = j;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn styles(doc: Docx) -> Docx {
|
||||||
|
doc.add_style(Style::new("Heading1", StyleType::Paragraph).name("heading 1").size(40).bold().outline_lvl(0))
|
||||||
|
.add_style(Style::new("Heading2", StyleType::Paragraph).name("heading 2").size(30).bold().outline_lvl(1))
|
||||||
|
.add_style(Style::new("Heading3", StyleType::Paragraph).name("heading 3").size(24).bold().outline_lvl(2))
|
||||||
|
.default_fonts(RunFonts::new().ascii("Calibri").hi_ansi("Calibri").cs("Calibri").east_asia("Calibri"))
|
||||||
|
.default_size(22)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts a PDF to a .docx.
|
||||||
|
pub fn to_word(
|
||||||
|
engine: &Engine,
|
||||||
|
bytes: &[u8],
|
||||||
|
password: Option<&str>,
|
||||||
|
opts: &WordOptions,
|
||||||
|
) -> Result<WordResult, PdfError> {
|
||||||
|
let doc = engine.open(bytes, password)?;
|
||||||
|
let n = doc.pages().len() as usize;
|
||||||
|
if n > 2000 {
|
||||||
|
return Err(PdfError::TooLarge(format!("{n} pages")));
|
||||||
|
}
|
||||||
|
let mut per_page: Vec<Vec<Item>> = Vec::with_capacity(n);
|
||||||
|
let mut all_lines: Vec<Vec<Line>> = Vec::with_capacity(n);
|
||||||
|
let mut scanned = Vec::new();
|
||||||
|
for (i, page) in doc.pages().iter().enumerate() {
|
||||||
|
let chars = page_chars(&page)?;
|
||||||
|
let visible = chars.iter().filter(|c| !c.c.is_whitespace()).count();
|
||||||
|
let mut items = Vec::new();
|
||||||
|
let mut images = 0;
|
||||||
|
for obj in page.objects().iter() {
|
||||||
|
let Some(img) = obj.as_image_object() else { continue };
|
||||||
|
let Ok(b) = obj.bounds() else { continue };
|
||||||
|
let Ok(raw) = img.get_raw_image() else { continue };
|
||||||
|
let (w_pt, h_pt) = (b.width().value, b.height().value);
|
||||||
|
if w_pt < 8.0 || h_pt < 8.0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
images += 1;
|
||||||
|
// Keep pictures a sensible size in the document (at most 1600 px on the long side).
|
||||||
|
let raw = if raw.width().max(raw.height()) > 1600 {
|
||||||
|
raw.resize(1600, 1600, image::imageops::FilterType::Triangle)
|
||||||
|
} else {
|
||||||
|
raw
|
||||||
|
};
|
||||||
|
let mut png = Vec::new();
|
||||||
|
if raw.to_rgb8().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
items.push(Item::Image { top: b.top().value, png, w_px: raw.width(), h_px: raw.height(), w_pt, h_pt });
|
||||||
|
}
|
||||||
|
let page_lines = lines(chars);
|
||||||
|
if visible < 10 && images > 0 {
|
||||||
|
if opts.ocr.contains_key(&i) {
|
||||||
|
items.clear(); // the recognised text replaces the scan
|
||||||
|
} else {
|
||||||
|
scanned.push(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
all_lines.push(page_lines);
|
||||||
|
per_page.push(items);
|
||||||
|
}
|
||||||
|
let body = body_size(&all_lines);
|
||||||
|
let mut docx = styles(Docx::new());
|
||||||
|
for (i, (page_lines, images)) in all_lines.into_iter().zip(per_page).enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_break(BreakType::Page)));
|
||||||
|
}
|
||||||
|
if let Some(t) = opts.ocr.get(&i) {
|
||||||
|
for para in
|
||||||
|
t.split("\n\n").map(|p| p.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|p| !p.is_empty())
|
||||||
|
{
|
||||||
|
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_text(para)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Interleave text runs and images by their top edge.
|
||||||
|
let mut items: Vec<Item> = images;
|
||||||
|
let mut group: Vec<Line> = Vec::new();
|
||||||
|
let mut groups: Vec<Item> = Vec::new();
|
||||||
|
let tops: Vec<f32> = items.iter().map(item_top).collect();
|
||||||
|
for l in page_lines {
|
||||||
|
if tops.iter().any(|t| *t < (group.last().map(|g: &Line| g.top).unwrap_or(f32::MAX)) && *t >= l.top)
|
||||||
|
&& !group.is_empty()
|
||||||
|
{
|
||||||
|
groups.push(Item::Lines(std::mem::take(&mut group)));
|
||||||
|
}
|
||||||
|
group.push(l);
|
||||||
|
}
|
||||||
|
if !group.is_empty() {
|
||||||
|
groups.push(Item::Lines(group));
|
||||||
|
}
|
||||||
|
items.extend(groups);
|
||||||
|
items.sort_by(|a, b| item_top(b).total_cmp(&item_top(a)));
|
||||||
|
for item in items {
|
||||||
|
match item {
|
||||||
|
Item::Lines(ls) => docx = blocks(ls, body, docx),
|
||||||
|
Item::Image { png, w_px, h_px, w_pt, h_pt, .. } => {
|
||||||
|
// Size in EMU (1 pt = 12 700 EMU), at most 6.5 inches wide.
|
||||||
|
let k = (468.0 / w_pt).min(1.0);
|
||||||
|
let pic = Pic::new_with_dimensions(png, w_px, h_px)
|
||||||
|
.size((w_pt * k * 12_700.0) as u32, (h_pt * k * 12_700.0) as u32);
|
||||||
|
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_image(pic)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = std::io::Cursor::new(Vec::new());
|
||||||
|
docx.build().pack(&mut out).map_err(|e| PdfError::Write(e.to_string()))?;
|
||||||
|
Ok(WordResult { bytes: out.into_inner(), pages: n, scanned_pages: scanned })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn ch(c: char, x0: f32, x1: f32, size: f32) -> Ch {
|
||||||
|
Ch { c, x0, x1, y0: 700.0, y1: 700.0 + size, size, bold: false, italic: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(line: &Line) -> String {
|
||||||
|
line.chars.iter().map(|c| c.c).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The characters pdfium gave for a WPS Writer PDF (no space glyphs, words split over text objects): a
|
||||||
|
/// zero-width space of size 1 between the touching "u" and "s" of "Dichotomous", and a misplaced one in the
|
||||||
|
/// real 4 pt gap before "Segmentation".
|
||||||
|
#[test]
|
||||||
|
fn invented_spaces_inside_a_word_are_dropped_and_gaps_make_spaces() {
|
||||||
|
let s = 15.9;
|
||||||
|
let chars = vec![
|
||||||
|
ch('o', 277.86, 285.83, s),
|
||||||
|
ch('u', 285.86, 294.72, s),
|
||||||
|
ch(' ', 292.53, 292.53, 1.0),
|
||||||
|
ch('s', 294.75, 300.96, s),
|
||||||
|
ch('I', 304.92, 311.12, s),
|
||||||
|
ch('m', 311.15, 324.43, s),
|
||||||
|
ch('e', 324.47, 332.45, s),
|
||||||
|
ch(' ', 326.0, 326.0, 1.0),
|
||||||
|
ch('S', 336.60, 345.47, s),
|
||||||
|
];
|
||||||
|
let l = lines(chars);
|
||||||
|
assert_eq!(l.len(), 1);
|
||||||
|
assert_eq!(text(&l[0]), "ous Ime S");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A PDF with real space glyphs keeps one space per gap, and a narrow space (a condensed font) still counts.
|
||||||
|
#[test]
|
||||||
|
fn real_space_glyphs_still_make_spaces() {
|
||||||
|
let s = 10.0;
|
||||||
|
let chars = vec![
|
||||||
|
ch('a', 0.0, 5.0, s),
|
||||||
|
ch(' ', 5.0, 6.2, s),
|
||||||
|
ch('b', 6.2, 11.0, s),
|
||||||
|
ch(' ', 11.0, 11.5, s),
|
||||||
|
ch(' ', 11.5, 14.0, s),
|
||||||
|
ch('c', 14.0, 19.0, s),
|
||||||
|
ch('d', 19.02, 24.0, s),
|
||||||
|
];
|
||||||
|
assert_eq!(text(&lines(chars)[0]), "a b cd");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lays a line out from words: letters `track` apart, words `space` apart (in points), no space glyphs.
|
||||||
|
fn laid_out(words: &[&str], size: f32, track: f32, space: f32) -> Vec<Ch> {
|
||||||
|
let mut x = 0.0;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (i, w) in words.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
x += space - track;
|
||||||
|
}
|
||||||
|
for c in w.chars() {
|
||||||
|
out.push(ch(c, x, x + 0.5 * size, size));
|
||||||
|
x += 0.5 * size + track;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Justified text from the same WPS PDF: "of personal" is 1.55 pt apart at 11 pt (0.14 em).
|
||||||
|
#[test]
|
||||||
|
fn narrow_justified_word_gaps_are_spaces() {
|
||||||
|
let chars = laid_out(&["terms", "of", "personal", "data"], 11.05, 0.03, 1.55);
|
||||||
|
assert_eq!(text(&lines(chars)[0]), "terms of personal data");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A heading tracked out to 0.15 em between letters is not split into letters.
|
||||||
|
#[test]
|
||||||
|
fn tracked_out_letters_stay_one_word() {
|
||||||
|
let chars = laid_out(&["CHAPTER", "ONE"], 20.0, 3.0, 12.0);
|
||||||
|
assert_eq!(text(&lines(chars)[0]), "CHAPTER ONE");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
//! Day 2 mandatory test 5: compress presets. The output is smaller, opens in pdfium, keeps every page and keeps all
|
||||||
|
//! text extractable; the E-mail preset reaches its 5 MB target for a heavy scan-like PDF.
|
||||||
|
mod common;
|
||||||
|
use common::*;
|
||||||
|
use lopdf::{Document, Object, Stream, dictionary};
|
||||||
|
use pictor_pdf::CompressPreset;
|
||||||
|
|
||||||
|
/// `pages` A4 pages, each with a line of text and a noisy `px` × `px` photo (Flate RGB, or JPEG at q95).
|
||||||
|
fn heavy_pdf(pages: usize, px: u32, jpeg: bool) -> Vec<u8> {
|
||||||
|
let mut doc = Document::with_version("1.7");
|
||||||
|
let pages_id = doc.new_object_id();
|
||||||
|
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
|
||||||
|
let mut kids = Vec::new();
|
||||||
|
let mut seed = 0x1234_5678u32;
|
||||||
|
for p in 0..pages {
|
||||||
|
let img = image::RgbImage::from_fn(px, px, |x, y| {
|
||||||
|
seed ^= seed << 13;
|
||||||
|
seed ^= seed >> 17;
|
||||||
|
seed ^= seed << 5;
|
||||||
|
let n = (seed & 0x1f) as u8;
|
||||||
|
image::Rgb([(x * 255 / px) as u8 ^ n, (y * 255 / px) as u8, 120u8.wrapping_add(n)])
|
||||||
|
});
|
||||||
|
let stream = if jpeg {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95).encode_image(&img).unwrap();
|
||||||
|
let mut s = Stream::new(
|
||||||
|
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => px as i64, "Height" => px as i64,
|
||||||
|
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Filter" => "DCTDecode"},
|
||||||
|
out,
|
||||||
|
);
|
||||||
|
s.allows_compression = false;
|
||||||
|
s
|
||||||
|
} else {
|
||||||
|
let mut s = Stream::new(
|
||||||
|
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => px as i64, "Height" => px as i64,
|
||||||
|
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8},
|
||||||
|
img.into_raw(),
|
||||||
|
);
|
||||||
|
s.compress().unwrap();
|
||||||
|
s
|
||||||
|
};
|
||||||
|
let im = doc.add_object(stream);
|
||||||
|
let content = format!(
|
||||||
|
"BT /F1 18 Tf 72 780 Td (Invoice page {} of the compress test) Tj ET q 450 0 0 450 72 250 cm /Im0 Do Q",
|
||||||
|
p + 1
|
||||||
|
);
|
||||||
|
let c = doc.add_object(Stream::new(dictionary! {}, content.into_bytes()));
|
||||||
|
let page = doc.add_object(dictionary! {
|
||||||
|
"Type" => "Page", "Parent" => pages_id, "Contents" => c,
|
||||||
|
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}, "XObject" => dictionary! {"Im0" => im}},
|
||||||
|
});
|
||||||
|
kids.push(Object::Reference(page));
|
||||||
|
}
|
||||||
|
doc.objects.insert(
|
||||||
|
pages_id,
|
||||||
|
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => pages as i64,
|
||||||
|
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||||
|
);
|
||||||
|
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||||
|
doc.trailer.set("Root", cat);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
doc.save_to(&mut out).unwrap();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn texts(bytes: &[u8]) -> Vec<String> {
|
||||||
|
pictor_pdf::extract_text(engine(), bytes, None).unwrap().into_iter().map(|t| t.trim().to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_preset_makes_it_smaller_and_keeps_the_text() {
|
||||||
|
let input = heavy_pdf(3, 2400, false);
|
||||||
|
let before = texts(&input);
|
||||||
|
for preset in [CompressPreset::Email, CompressPreset::Web, CompressPreset::Print] {
|
||||||
|
let out = pictor_pdf::compress(&input, None, preset).unwrap();
|
||||||
|
assert!(out.bytes.len() < input.len(), "{preset:?} did not shrink ({} → {})", input.len(), out.bytes.len());
|
||||||
|
assert_eq!(out.before, input.len());
|
||||||
|
assert_eq!(out.after, out.bytes.len());
|
||||||
|
assert_eq!(texts(&out.bytes), before, "{preset:?} lost text");
|
||||||
|
let sizes = pictor_pdf::page_sizes(engine(), &out.bytes, None).unwrap();
|
||||||
|
assert_eq!(sizes.len(), 3);
|
||||||
|
assert!(out.images_changed >= 3, "{preset:?}: {} images changed", out.images_changed);
|
||||||
|
// It still renders: the photo is there (not white) in the middle of the page.
|
||||||
|
let img = pictor_pdf::render_page(engine(), &out.bytes, None, 0, 595).unwrap().to_rgb8();
|
||||||
|
let p = img.get_pixel(297, 400).0;
|
||||||
|
assert!(p != [255, 255, 255], "{preset:?}: the photo disappeared");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn presets_are_ordered_email_smallest_print_largest() {
|
||||||
|
let input = heavy_pdf(2, 2400, true);
|
||||||
|
let email = pictor_pdf::compress(&input, None, CompressPreset::Email).unwrap().after;
|
||||||
|
let web = pictor_pdf::compress(&input, None, CompressPreset::Web).unwrap().after;
|
||||||
|
let print = pictor_pdf::compress(&input, None, CompressPreset::Print).unwrap().after;
|
||||||
|
assert!(email <= web && web <= print, "email {email}, web {web}, print {print}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn email_reaches_five_megabytes() {
|
||||||
|
let input = heavy_pdf(8, 3000, false);
|
||||||
|
assert!(input.len() > 20 << 20, "fixture too small: {}", input.len());
|
||||||
|
let out = pictor_pdf::compress(&input, None, CompressPreset::Email).unwrap();
|
||||||
|
assert!(out.after <= 5 << 20, "E-mail preset left {} bytes", out.after);
|
||||||
|
assert_eq!(texts(&out.bytes).len(), 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_pdf_with_nothing_to_shrink_is_left_alone_and_says_so() {
|
||||||
|
let input = numbered_pdf(2, "Plain");
|
||||||
|
let out = pictor_pdf::compress(&input, None, CompressPreset::Web).unwrap();
|
||||||
|
assert_eq!(out.images_changed, 0);
|
||||||
|
assert!(out.after <= out.before + 64, "grew from {} to {}", out.before, out.after);
|
||||||
|
assert_eq!(texts(&out.bytes), ["Plain page 1", "Plain page 2"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_protected_pdf_needs_its_password_and_stays_readable() {
|
||||||
|
let locked = pictor_pdf::protect(&heavy_pdf(1, 1600, false), None, "pw", None).unwrap();
|
||||||
|
assert!(pictor_pdf::compress(&locked, None, CompressPreset::Web).is_err());
|
||||||
|
let out = pictor_pdf::compress(&locked, Some("pw"), CompressPreset::Web).unwrap();
|
||||||
|
assert!(out.after < out.before);
|
||||||
|
// Still protected, with the same password.
|
||||||
|
assert!(pictor_pdf::is_encrypted(&out.bytes));
|
||||||
|
let text = pictor_pdf::extract_text(engine(), &out.bytes, Some("pw")).unwrap();
|
||||||
|
assert_eq!(text[0].trim(), "Invoice page 1 of the compress test");
|
||||||
|
}
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
//! Day 2 mandatory test 4 (core part): PDF to Word. A PDF with a title, headings, a wrapped paragraph, a table and
|
||||||
|
//! an image becomes a .docx with every word in reading order, heading styles, one table of 4 rows and the image.
|
||||||
|
//! LibreOffice (when installed) reads the same text back. "Opens in Scriptum" is checked in the app repository
|
||||||
|
//! (Scriptum's engine, Prelum, is private): Pictor/apps/desktop/src-tauri/tests/word_scriptum.rs.
|
||||||
|
mod common;
|
||||||
|
use common::*;
|
||||||
|
use lopdf::{Document, Object, Stream, dictionary};
|
||||||
|
use std::io::Read;
|
||||||
|
|
||||||
|
const BODY: &[&str] = &[
|
||||||
|
"Pictor turns this PDF into a document you can edit.",
|
||||||
|
"The paragraph wraps over three lines on purpose, so",
|
||||||
|
"that the converter has to join the lines back together.",
|
||||||
|
];
|
||||||
|
|
||||||
|
pub fn report_pdf() -> Vec<u8> {
|
||||||
|
let mut doc = Document::with_version("1.7");
|
||||||
|
let pages_id = doc.new_object_id();
|
||||||
|
let reg = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"});
|
||||||
|
let bold = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica-Bold", "Encoding" => "WinAnsiEncoding"});
|
||||||
|
let img = image::RgbImage::from_fn(120, 80, |x, y| image::Rgb([(x * 2) as u8, (y * 3) as u8, 200]));
|
||||||
|
let mut im = Stream::new(
|
||||||
|
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => 120, "Height" => 80, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8},
|
||||||
|
img.into_raw(),
|
||||||
|
);
|
||||||
|
im.compress().unwrap();
|
||||||
|
let im = doc.add_object(im);
|
||||||
|
let mut c1 = String::new();
|
||||||
|
c1 += "BT /F2 26 Tf 72 770 Td (Quarterly report) Tj ET\n";
|
||||||
|
c1 += "BT /F2 16 Tf 72 730 Td (Summary) Tj ET\n";
|
||||||
|
for (i, line) in BODY.iter().enumerate() {
|
||||||
|
c1 += &format!("BT /F1 11 Tf 72 {} Td ({line}) Tj ET\n", 705 - i as i32 * 14);
|
||||||
|
}
|
||||||
|
c1 += "BT /F2 16 Tf 72 640 Td (Figures) Tj ET\n";
|
||||||
|
let rows = [
|
||||||
|
["Month", "Sales", "Notes"],
|
||||||
|
["January", "1200", "cold"],
|
||||||
|
["February", "1350", "better"],
|
||||||
|
["March", "1600", "best"],
|
||||||
|
];
|
||||||
|
for (r, row) in rows.iter().enumerate() {
|
||||||
|
for (c, cell) in row.iter().enumerate() {
|
||||||
|
let font = if r == 0 { "/F2" } else { "/F1" };
|
||||||
|
c1 += &format!("BT {font} 11 Tf {} {} Td ({cell}) Tj ET\n", 72 + c * 150, 615 - r as i32 * 18);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c1 += "q 120 0 0 80 72 420 cm /Im0 Do Q\n";
|
||||||
|
c1 += "BT /F1 11 Tf 72 400 Td (A picture of the gradient above.) Tj ET\n";
|
||||||
|
let c2 = "BT /F2 16 Tf 72 770 Td (Next steps) Tj ET\nBT /F1 11 Tf 72 745 Td (Page two closes the report.) Tj ET\n";
|
||||||
|
let res =
|
||||||
|
|| dictionary! {"Font" => dictionary! {"F1" => reg, "F2" => bold}, "XObject" => dictionary! {"Im0" => im}};
|
||||||
|
let mut kids = Vec::new();
|
||||||
|
for c in [c1, c2.to_string()] {
|
||||||
|
let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes()));
|
||||||
|
kids.push(Object::Reference(doc.add_object(
|
||||||
|
dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid, "Resources" => res()},
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
doc.objects.insert(
|
||||||
|
pages_id,
|
||||||
|
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => 2,
|
||||||
|
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||||
|
);
|
||||||
|
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||||
|
doc.trailer.set("Root", cat);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
doc.save_to(&mut out).unwrap();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn part(docx: &[u8], name: &str) -> Option<Vec<u8>> {
|
||||||
|
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||||
|
let mut f = z.by_name(name).ok()?;
|
||||||
|
let mut v = Vec::new();
|
||||||
|
f.read_to_end(&mut v).unwrap();
|
||||||
|
Some(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn entries(docx: &[u8]) -> Vec<String> {
|
||||||
|
let z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||||
|
z.file_names().map(String::from).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text of word/document.xml: every w:t, a newline per paragraph.
|
||||||
|
fn text_of(xml: &str) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut rest = xml;
|
||||||
|
while let Some(i) = rest.find('<') {
|
||||||
|
let tag_end = rest[i..].find('>').map(|j| i + j).unwrap_or(rest.len() - 1);
|
||||||
|
let tag = &rest[i + 1..tag_end];
|
||||||
|
if tag.starts_with("w:t") && !tag.ends_with('/') && (tag == "w:t" || tag.starts_with("w:t ")) {
|
||||||
|
let body = &rest[tag_end + 1..];
|
||||||
|
let end = body.find("</w:t>").unwrap_or(0);
|
||||||
|
out.push_str(&body[..end].replace("&", "&").replace("<", "<").replace(">", ">"));
|
||||||
|
} else if tag == "/w:p" {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
rest = &rest[tag_end + 1..];
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_in_order(text: &str, words: &[&str]) {
|
||||||
|
let mut at = 0;
|
||||||
|
for w in words {
|
||||||
|
match text[at..].find(w) {
|
||||||
|
Some(i) => at += i + w.len(),
|
||||||
|
None => panic!("{w:?} missing or out of order in:\n{text}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const ORDER: &[&str] = &[
|
||||||
|
"Quarterly report",
|
||||||
|
"Summary",
|
||||||
|
"Pictor turns",
|
||||||
|
"edit.",
|
||||||
|
"wraps over three lines",
|
||||||
|
"join the lines back together.",
|
||||||
|
"Figures",
|
||||||
|
"Month",
|
||||||
|
"Sales",
|
||||||
|
"Notes",
|
||||||
|
"January",
|
||||||
|
"1200",
|
||||||
|
"cold",
|
||||||
|
"March",
|
||||||
|
"1600",
|
||||||
|
"best",
|
||||||
|
"A picture of the gradient",
|
||||||
|
"Next steps",
|
||||||
|
"Page two closes the report.",
|
||||||
|
];
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn headings_paragraphs_table_and_image_come_out_in_order() {
|
||||||
|
let r = pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap();
|
||||||
|
assert!(r.scanned_pages.is_empty(), "{:?}", r.scanned_pages);
|
||||||
|
let xml = String::from_utf8(part(&r.bytes, "word/document.xml").expect("document.xml")).unwrap();
|
||||||
|
let text = text_of(&xml);
|
||||||
|
assert_in_order(&text, ORDER);
|
||||||
|
// The wrapped paragraph is one paragraph, not three.
|
||||||
|
assert!(text.contains("so that the converter"), "the wrapped lines were not joined:\n{text}");
|
||||||
|
// Headings: the title and the section heads carry heading styles.
|
||||||
|
assert!(xml.matches("w:pStyle w:val=\"Heading1\"").count() >= 1, "no Heading 1");
|
||||||
|
assert!(xml.matches("w:pStyle w:val=\"Heading2\"").count() >= 3, "fewer than 3 Heading 2");
|
||||||
|
// One table of 4 rows × 3 cells.
|
||||||
|
assert_eq!(xml.matches("<w:tbl>").count(), 1, "tables");
|
||||||
|
assert_eq!(xml.matches("<w:tr").count() - xml.matches("<w:trPr").count(), 4, "rows");
|
||||||
|
// The image is embedded.
|
||||||
|
assert!(xml.contains("<w:drawing>"), "no picture");
|
||||||
|
assert!(entries(&r.bytes).iter().any(|e| e.starts_with("word/media/")), "no media part");
|
||||||
|
// A page break between the two pages.
|
||||||
|
assert!(xml.contains("w:type=\"page\""), "no page break");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_page_without_text_is_reported_as_scanned_and_takes_ocr_text() {
|
||||||
|
// A "scan": one page that is only an image.
|
||||||
|
let input = pictor_pdf::images_to_pdf(
|
||||||
|
&[(
|
||||||
|
Vec::new(),
|
||||||
|
image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(800, 1100, image::Rgb([240, 240, 240]))),
|
||||||
|
)],
|
||||||
|
pictor_pdf::PageFit::A4,
|
||||||
|
0.0,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let r = pictor_pdf::to_word(engine(), &input, None, &Default::default()).unwrap();
|
||||||
|
assert_eq!(r.scanned_pages, vec![0]);
|
||||||
|
let mut opts = pictor_pdf::WordOptions::default();
|
||||||
|
opts.ocr.insert(0, "Recognised line one\n\nSecond paragraph from OCR".into());
|
||||||
|
let r = pictor_pdf::to_word(engine(), &input, None, &opts).unwrap();
|
||||||
|
let text = text_of(&String::from_utf8(part(&r.bytes, "word/document.xml").unwrap()).unwrap());
|
||||||
|
assert_in_order(&text, &["Recognised line one", "Second paragraph from OCR"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn libreoffice_reads_every_word_in_order() {
|
||||||
|
let soffice = std::path::Path::new(r"C:\Program Files\LibreOffice\program\soffice.com");
|
||||||
|
if !soffice.exists() {
|
||||||
|
println!("LibreOffice is not installed here: skipped");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||||
|
let docx = dir.path().join("report.docx");
|
||||||
|
std::fs::write(&docx, pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap().bytes)
|
||||||
|
.unwrap();
|
||||||
|
let profile = format!("file:///{}", dir.path().join("lo-profile").display().to_string().replace('\\', "/"));
|
||||||
|
// A fresh LibreOffice profile makes the first start exit with 1 while it restarts itself and still converts:
|
||||||
|
// wait for the file rather than trusting the exit code (one retry if nothing comes).
|
||||||
|
let out = dir.path().join("report.txt");
|
||||||
|
for _ in 0..2 {
|
||||||
|
let _ = std::process::Command::new(soffice)
|
||||||
|
.args([
|
||||||
|
&format!("-env:UserInstallation={profile}"),
|
||||||
|
"--headless",
|
||||||
|
"--invisible",
|
||||||
|
"--norestore",
|
||||||
|
"--nolockcheck",
|
||||||
|
])
|
||||||
|
.args(["--convert-to", "txt:Text (encoded):UTF8", "--outdir"])
|
||||||
|
.arg(dir.path())
|
||||||
|
.arg(&docx)
|
||||||
|
.status();
|
||||||
|
let start = std::time::Instant::now();
|
||||||
|
while !out.exists() && start.elapsed() < std::time::Duration::from_secs(60) {
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
if out.exists() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||||
|
let text = std::fs::read_to_string(&out).expect("LibreOffice converted the .docx");
|
||||||
|
assert_in_order(&text, ORDER);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A PDF written like many real ones (Word's own export among them): no space glyphs between words, only gaps, and
|
||||||
|
/// a word split over two text objects where the line was justified ("Dichotomou" | "s"). pdfium invents a
|
||||||
|
/// zero-width space at such a split; the .docx must not break the word there, and must still space the words.
|
||||||
|
fn no_space_glyphs_pdf() -> Vec<u8> {
|
||||||
|
let mut doc = Document::with_version("1.7");
|
||||||
|
let pages_id = doc.new_object_id();
|
||||||
|
let reg = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"});
|
||||||
|
// Helvetica advance widths (AFM, /1000 em) for the pieces, so each piece starts exactly where the last ended.
|
||||||
|
let w = |s: &str| -> f32 {
|
||||||
|
s.chars()
|
||||||
|
.map(|c| match c {
|
||||||
|
'D' => 722.0,
|
||||||
|
'I' | 'i' | 'l' | 'j' => 222.0,
|
||||||
|
'c' | 'k' | 's' | 'v' | 'x' | 'y' | 'z' => 500.0,
|
||||||
|
'f' | 't' => 278.0,
|
||||||
|
'm' => 833.0,
|
||||||
|
'r' => 333.0,
|
||||||
|
'w' => 722.0,
|
||||||
|
'S' | 'H' | 'A' | 'E' => 667.0,
|
||||||
|
_ => 556.0,
|
||||||
|
})
|
||||||
|
.sum::<f32>()
|
||||||
|
* 16.0
|
||||||
|
/ 1000.0
|
||||||
|
};
|
||||||
|
let mut c = String::new();
|
||||||
|
// Line 1: words as separate objects, a 4 pt gap between them, "Dichotomous" split in two touching objects.
|
||||||
|
let mut x = 72.0;
|
||||||
|
for (piece, gap_after) in [
|
||||||
|
("Highly", 4.0),
|
||||||
|
("Accurate", 4.0),
|
||||||
|
("Dichotomou", 0.0),
|
||||||
|
("s", 4.0),
|
||||||
|
("Image", 4.0),
|
||||||
|
("Segmentat", 0.0),
|
||||||
|
("ion", 0.0),
|
||||||
|
] {
|
||||||
|
c += &format!("BT /F1 16 Tf {x:.2} 700 Td ({piece}) Tj ET\n");
|
||||||
|
x += w(piece) + gap_after;
|
||||||
|
}
|
||||||
|
// Line 2: the same inside one text object, moved with Td (the other common way).
|
||||||
|
c += "BT /F1 16 Tf 72 670 Td (evalu) Tj ";
|
||||||
|
c += &format!("{:.2} 0 Td (ation) Tj {:.2} 0 Td (of) Tj ET\n", w("evalu"), w("ation") + 4.0);
|
||||||
|
// Line 3, as WPS Writer writes it: the page flipped (y down), each word a text object with a flipped Tm at
|
||||||
|
// 319 pt × 0.05, and every glyph its own Tj moved by TD in glyph widths.
|
||||||
|
c += "q 1 0 0 -1 0 842 cm
|
||||||
|
";
|
||||||
|
let mut x = 72.0;
|
||||||
|
for word in ["Dichotomous", "Image", "Segmentation", "Dataset"] {
|
||||||
|
c += &format!("q BT /F1 319 Tf 0.05 0 0 -0.05 {x:.3} 230 Tm ");
|
||||||
|
for (i, ch) in word.chars().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
let prev = word.chars().nth(i - 1).unwrap().to_string();
|
||||||
|
c += &format!("{:.3} -0 TD ", w(&prev) / 16.0 * 319.0);
|
||||||
|
}
|
||||||
|
c += &format!("({ch}) Tj ");
|
||||||
|
}
|
||||||
|
c += "ET Q
|
||||||
|
";
|
||||||
|
x += w(word) / 16.0 * 319.0 * 0.05 + 4.0;
|
||||||
|
}
|
||||||
|
c += "Q
|
||||||
|
";
|
||||||
|
let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes()));
|
||||||
|
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid,
|
||||||
|
"Resources" => dictionary! {"Font" => dictionary! {"F1" => reg}}});
|
||||||
|
doc.objects.insert(
|
||||||
|
pages_id,
|
||||||
|
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1,
|
||||||
|
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||||
|
);
|
||||||
|
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||||
|
doc.trailer.set("Root", cat);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
doc.save_to(&mut out).unwrap();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn words_split_over_text_objects_stay_whole() {
|
||||||
|
let r = pictor_pdf::to_word(engine(), &no_space_glyphs_pdf(), None, &Default::default()).unwrap();
|
||||||
|
let text = text_of(&String::from_utf8(part(&r.bytes, "word/document.xml").unwrap()).unwrap());
|
||||||
|
let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||||
|
assert!(flat.contains("Highly Accurate Dichotomous Image Segmentation"), "{flat:?}");
|
||||||
|
assert!(flat.contains("evaluation of"), "{flat:?}");
|
||||||
|
assert!(flat.contains("Dichotomous Image Segmentation Dataset"), "{flat:?}");
|
||||||
|
}
|
||||||
@@ -25,6 +25,7 @@ pictor-pdf.workspace = true
|
|||||||
pictor-meta.workspace = true
|
pictor-meta.workspace = true
|
||||||
pictor-qr.workspace = true
|
pictor-qr.workspace = true
|
||||||
pictor-save.workspace = true
|
pictor-save.workspace = true
|
||||||
|
pictor-doc.workspace = true
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_Security"] }
|
windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_Security"] }
|
||||||
@@ -33,3 +34,4 @@ windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_JobO
|
|||||||
tempfile.workspace = true
|
tempfile.workspace = true
|
||||||
lopdf.workspace = true
|
lopdf.workspace = true
|
||||||
flate2.workspace = true
|
flate2.workspace = true
|
||||||
|
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||||
|
|||||||
@@ -100,6 +100,18 @@ fn png(img: &image::DynamicImage) -> Result<Vec<u8>, OpError> {
|
|||||||
|
|
||||||
use image::ImageEncoder;
|
use image::ImageEncoder;
|
||||||
|
|
||||||
|
fn doc_error(e: impl std::fmt::Display + std::fmt::Debug) -> OpError {
|
||||||
|
let msg = e.to_string();
|
||||||
|
let code = if msg.contains("newer Pictor") {
|
||||||
|
"newer"
|
||||||
|
} else if msg.contains("too large") {
|
||||||
|
"too_large"
|
||||||
|
} else {
|
||||||
|
"damaged"
|
||||||
|
};
|
||||||
|
OpError::new(code, msg)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError> {
|
pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError> {
|
||||||
match op {
|
match op {
|
||||||
// ---- PDF sessions -------------------------------------------------------------------------------------
|
// ---- PDF sessions -------------------------------------------------------------------------------------
|
||||||
@@ -224,6 +236,58 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
|
|||||||
}
|
}
|
||||||
Ok(json!({"paths": paths}))
|
Ok(json!({"paths": paths}))
|
||||||
}
|
}
|
||||||
|
"pdf.compress" => {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct A {
|
||||||
|
doc: u32,
|
||||||
|
preset: pictor_pdf::CompressPreset,
|
||||||
|
output: String,
|
||||||
|
}
|
||||||
|
let a: A = args(a)?;
|
||||||
|
let d = state.doc(a.doc)?;
|
||||||
|
let r = pictor_pdf::compress(&d.bytes, d.password.as_deref(), a.preset)?;
|
||||||
|
let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?;
|
||||||
|
out["before"] = json!(r.before);
|
||||||
|
out["after"] = json!(r.after);
|
||||||
|
out["images_changed"] = json!(r.images_changed);
|
||||||
|
out["warnings"] = json!(r.warnings);
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
"pdf.to_word" => {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct A {
|
||||||
|
doc: u32,
|
||||||
|
output: String,
|
||||||
|
/// Recognised text for scanned pages: {"0": "text", …}.
|
||||||
|
#[serde(default)]
|
||||||
|
ocr: std::collections::HashMap<usize, String>,
|
||||||
|
}
|
||||||
|
let a: A = args(a)?;
|
||||||
|
let engine = state.engine()?;
|
||||||
|
let d = state.doc(a.doc)?;
|
||||||
|
let r =
|
||||||
|
pictor_pdf::to_word(engine, &d.bytes, d.password.as_deref(), &pictor_pdf::WordOptions { ocr: a.ocr })?;
|
||||||
|
let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?;
|
||||||
|
out["pages"] = json!(r.pages);
|
||||||
|
out["scanned_pages"] = json!(r.scanned_pages);
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
"pdf.page_png" => {
|
||||||
|
// A page as a PNG file (for OCR of a scanned page by Fundamentum's Lector, through the app).
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct A {
|
||||||
|
doc: u32,
|
||||||
|
page: usize,
|
||||||
|
dpi: u32,
|
||||||
|
output: String,
|
||||||
|
}
|
||||||
|
let a: A = args(a)?;
|
||||||
|
let engine = state.engine()?;
|
||||||
|
let d = state.doc(a.doc)?;
|
||||||
|
let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[a.page], a.dpi)?.remove(0);
|
||||||
|
let bytes = png(&img)?;
|
||||||
|
write_out(&a.output, &bytes, SaveMode::Overwrite)
|
||||||
|
}
|
||||||
// ---- PDF files ----------------------------------------------------------------------------------------
|
// ---- PDF files ----------------------------------------------------------------------------------------
|
||||||
"pdf.merge" => {
|
"pdf.merge" => {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -316,6 +380,38 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
|
|||||||
pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?;
|
pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?;
|
||||||
Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h}))
|
Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h}))
|
||||||
}
|
}
|
||||||
|
// ---- Documents (.pictor, SVG) ------------------------------------------------------------------------
|
||||||
|
// An outside .pictor or SVG is read here, with caps, and written back as a clean .pictor of the worker's
|
||||||
|
// own making; the tray process opens only that copy.
|
||||||
|
"doc.open" => {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct A {
|
||||||
|
input: String,
|
||||||
|
output: String,
|
||||||
|
}
|
||||||
|
let a: A = args(a)?;
|
||||||
|
let src = read_file(&a.input)?;
|
||||||
|
let (doc, fonts) = pictor_doc::format::read(&src, &pictor_doc::Limits::default()).map_err(doc_error)?;
|
||||||
|
let clean = pictor_doc::format::write(&doc, &fonts).map_err(doc_error)?;
|
||||||
|
pictor_save::save_overwrite(Path::new(&a.output), &clean)?;
|
||||||
|
Ok(json!({"path": a.output, "pages": doc.pages.len(), "format": doc.format}))
|
||||||
|
}
|
||||||
|
"doc.import_svg" => {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct A {
|
||||||
|
input: String,
|
||||||
|
output: String,
|
||||||
|
}
|
||||||
|
let a: A = args(a)?;
|
||||||
|
let src = read_file(&a.input)?;
|
||||||
|
if src.len() > 64 << 20 {
|
||||||
|
return Err(OpError::new("too_large", "This SVG is larger than 64 MB, which Pictor does not import."));
|
||||||
|
}
|
||||||
|
let doc = pictor_doc::svg::import(&src, pictor_doc::svg::system_fontdb()).map_err(doc_error)?;
|
||||||
|
let clean = pictor_doc::format::write(&doc, &[]).map_err(doc_error)?;
|
||||||
|
pictor_save::save_overwrite(Path::new(&a.output), &clean)?;
|
||||||
|
Ok(json!({"path": a.output, "width": doc.pages[0].width, "height": doc.pages[0].height}))
|
||||||
|
}
|
||||||
"image.convert" => {
|
"image.convert" => {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct A {
|
struct A {
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
//! The worker's side of documents: `doc.open` turns a good .pictor into a clean copy and refuses hostile ones
|
||||||
|
//! (zip slip, a bomb, a newer format) with a clear error, staying alive for the next request; `doc.import_svg`
|
||||||
|
//! turns an SVG into a .pictor.
|
||||||
|
use pictor_worker::client::{Worker, WorkerOptions};
|
||||||
|
use serde_json::json;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
const CAP: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
|
fn worker() -> Worker {
|
||||||
|
let mut o = WorkerOptions::new(env!("CARGO_BIN_EXE_pictor-worker"));
|
||||||
|
o.pdfium_dir = Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
|
||||||
|
o.memory_mb = 1024;
|
||||||
|
o.debug = true;
|
||||||
|
Worker::new(o)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn zip_of(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||||
|
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||||
|
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||||
|
for (n, d) in entries {
|
||||||
|
z.start_file(*n, opts).unwrap();
|
||||||
|
z.write_all(d).unwrap();
|
||||||
|
}
|
||||||
|
z.finish().unwrap().into_inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn doc_open_cleans_good_files_and_refuses_hostile_ones() {
|
||||||
|
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||||
|
let mut w = worker();
|
||||||
|
let good = dir.path().join("good.pictor");
|
||||||
|
std::fs::write(&good, pictor_doc::format::write(&pictor_doc::fixtures::bitmap(), &[]).unwrap()).unwrap();
|
||||||
|
let out = dir.path().join("clean.pictor");
|
||||||
|
let r = w.call("doc.open", json!({"input": good, "output": out}), CAP).expect("a good document opens");
|
||||||
|
assert_eq!(r["pages"], 1);
|
||||||
|
let (doc, _) = pictor_doc::format::read(&std::fs::read(&out).unwrap(), &Default::default()).unwrap();
|
||||||
|
assert_eq!(doc, pictor_doc::fixtures::bitmap());
|
||||||
|
|
||||||
|
let json = br#"{"format":1,"next_id":3,"pages":[{"id":1,"width":100,"height":100,"layers":[]}]}"#;
|
||||||
|
let cases: Vec<(&str, Vec<u8>, &str)> = vec![
|
||||||
|
("slip", zip_of(&[("document.json", json), ("../../evil.dll", b"MZ")]), "damaged"),
|
||||||
|
("newer", zip_of(&[("document.json", br#"{"format":9}"#)]), "newer"),
|
||||||
|
("not a zip", b"hello".to_vec(), "damaged"),
|
||||||
|
];
|
||||||
|
for (name, bytes, code) in cases {
|
||||||
|
let p = dir.path().join(format!("{}.pictor", name.replace(' ', "-")));
|
||||||
|
std::fs::write(&p, bytes).unwrap();
|
||||||
|
let e = w.call("doc.open", json!({"input": p, "output": dir.path().join("x.pictor")}), CAP).expect_err(name);
|
||||||
|
let msg = format!("{e:?}");
|
||||||
|
assert!(msg.contains(code), "{name}: {msg}");
|
||||||
|
assert!(!dir.path().join("evil.dll").exists() && !dir.path().parent().unwrap().join("evil.dll").exists());
|
||||||
|
}
|
||||||
|
// Still alive for the next request.
|
||||||
|
w.call("doc.open", json!({"input": good, "output": out}), CAP).expect("the worker survives hostile files");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn doc_import_svg_writes_a_document() {
|
||||||
|
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||||
|
let svg = dir.path().join("logo.svg");
|
||||||
|
std::fs::write(&svg, br##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><circle cx="20" cy="20" r="18" fill="#f27ab9"/></svg>"##).unwrap();
|
||||||
|
let out = dir.path().join("logo.pictor");
|
||||||
|
let r = worker().call("doc.import_svg", json!({"input": svg, "output": out}), CAP).unwrap();
|
||||||
|
assert_eq!(r["width"], 30.0);
|
||||||
|
let (doc, _) = pictor_doc::format::read(&std::fs::read(&out).unwrap(), &Default::default()).unwrap();
|
||||||
|
assert_eq!(doc.pages.len(), 1);
|
||||||
|
}
|
||||||
+98
-2
@@ -33,13 +33,22 @@ script exit 1, and the feature that needs it waits (the brief: "it never gets a
|
|||||||
| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG |
|
| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG |
|
||||||
| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata |
|
| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata |
|
||||||
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) |
|
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) |
|
||||||
|
| docx-rs | 0.4 | MIT | pdf | PDF to Word: writing the .docx (headings, runs, tables, inline images) |
|
||||||
| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target |
|
| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target |
|
||||||
| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check |
|
| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check |
|
||||||
| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF |
|
| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF |
|
||||||
| flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) |
|
| flate2 | 1 | MIT OR Apache-2.0 | doc (and pdf tests) | compressing PDF export streams; building compressed hostile fixtures (a deflate bomb) |
|
||||||
| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), MFTEnumEx (is an HEVC decoder installed?), Job Objects |
|
| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), MFTEnumEx (is an HEVC decoder installed?), Job Objects |
|
||||||
| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) |
|
| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) |
|
||||||
| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests |
|
| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests |
|
||||||
|
| tiny-skia | 0.12 | BSD-3-Clause | doc | the core's 2D painter: PNG/JPG export, thumbnails, brush dabs, the fidelity reference |
|
||||||
|
| usvg | 0.50 | Apache-2.0 OR MIT | doc | SVG import into vector layers (text as outlines); brings fontdb and the same ttf-parser |
|
||||||
|
| fontdb | 0.24 | MIT | doc | the system font list (C:\Windows\Fonts, the per-user fonts folder) and the fonts inside a .pictor |
|
||||||
|
| rustybuzz | 0.20 | MIT | doc | text shaping (a harfbuzz port in safe Rust) |
|
||||||
|
| ttf-parser | 0.25 | MIT OR Apache-2.0 | doc | glyph outlines, metrics and the OS/2 fsType embedding flags |
|
||||||
|
| pdf-writer | 0.15 | MIT OR Apache-2.0 | doc | PDF export of a document: vectors, shadings, images with SMask, Type 0 fonts with ToUnicode |
|
||||||
|
| subsetter | 0.2 | MIT OR Apache-2.0 | doc | subsetting the embedded fonts of a PDF export (TrueType and CFF) |
|
||||||
|
| zip | 8 | MIT | doc | reading and writing .pictor files (deflate only, no default features) |
|
||||||
|
|
||||||
## Binaries (fetched, never in git)
|
## Binaries (fetched, never in git)
|
||||||
|
|
||||||
@@ -85,7 +94,7 @@ support depends on pdfium, which the brief chose).
|
|||||||
Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
||||||
|
|
||||||
<!-- deps:begin -->
|
<!-- deps:begin -->
|
||||||
141 crates; 0 outside the allowed set.
|
228 crates; 0 outside the allowed set.
|
||||||
|
|
||||||
| Crate | Version | Licence | Allowed |
|
| Crate | Version | Licence | Allowed |
|
||||||
| :-- | :-- | :-- | :-- |
|
| :-- | :-- | :-- | :-- |
|
||||||
@@ -93,8 +102,12 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| aes | 0.9.2 | MIT OR Apache-2.0 | yes |
|
| aes | 0.9.2 | MIT OR Apache-2.0 | yes |
|
||||||
| alloc-no-stdlib | 2.0.4 | BSD-3-Clause | yes |
|
| alloc-no-stdlib | 2.0.4 | BSD-3-Clause | yes |
|
||||||
| alloc-stdlib | 0.2.4 | BSD-3-Clause | yes |
|
| alloc-stdlib | 0.2.4 | BSD-3-Clause | yes |
|
||||||
|
| android_system_properties | 0.1.6 | MIT OR Apache-2.0 | yes |
|
||||||
|
| arrayref | 0.3.9 | BSD-2-Clause | yes |
|
||||||
|
| arrayvec | 0.7.8 | MIT OR Apache-2.0 | yes |
|
||||||
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
|
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
|
||||||
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
|
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| base64 | 0.23.1 | MIT OR Apache-2.0 | yes |
|
||||||
| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes |
|
| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes |
|
||||||
| bit-vec | 0.10.2 | Apache-2.0 OR MIT | yes |
|
| bit-vec | 0.10.2 | Apache-2.0 OR MIT | yes |
|
||||||
| bitflags | 2.13.2 | MIT OR Apache-2.0 | yes |
|
| bitflags | 2.13.2 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -103,57 +116,88 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| borsh | 1.8.1 | MIT OR Apache-2.0 | yes |
|
| borsh | 1.8.1 | MIT OR Apache-2.0 | yes |
|
||||||
| borsh-derive | 1.8.1 | Apache-2.0 | yes |
|
| borsh-derive | 1.8.1 | Apache-2.0 | yes |
|
||||||
| brotli-decompressor | 5.0.3 | BSD-3-Clause/MIT | yes |
|
| brotli-decompressor | 5.0.3 | BSD-3-Clause/MIT | yes |
|
||||||
|
| bumpalo | 3.20.4 | MIT OR Apache-2.0 | yes |
|
||||||
| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes |
|
| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||||
|
| bytemuck_derive | 1.12.1 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||||
| byteorder | 1.5.0 | Unlicense OR MIT | yes |
|
| byteorder | 1.5.0 | Unlicense OR MIT | yes |
|
||||||
| byteorder-lite | 0.1.0 | Unlicense OR MIT | yes |
|
| byteorder-lite | 0.1.0 | Unlicense OR MIT | yes |
|
||||||
| bytes | 1.12.1 | MIT | yes |
|
| bytes | 1.12.1 | MIT | yes |
|
||||||
| cbc | 0.2.1 | MIT OR Apache-2.0 | yes |
|
| cbc | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| cc | 1.11.2 | MIT OR Apache-2.0 | yes |
|
||||||
| cfg_aliases | 0.2.2 | MIT | yes |
|
| cfg_aliases | 0.2.2 | MIT | yes |
|
||||||
| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes |
|
| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes |
|
||||||
| chacha20 | 0.10.2 | MIT OR Apache-2.0 | yes |
|
| chacha20 | 0.10.2 | MIT OR Apache-2.0 | yes |
|
||||||
| chrono | 0.4.45 | MIT OR Apache-2.0 | yes |
|
| chrono | 0.4.45 | MIT OR Apache-2.0 | yes |
|
||||||
| cipher | 0.5.2 | MIT OR Apache-2.0 | yes |
|
| cipher | 0.5.2 | MIT OR Apache-2.0 | yes |
|
||||||
| color_quant | 1.1.0 | MIT | yes |
|
| color_quant | 1.1.0 | MIT | yes |
|
||||||
|
| console_error_panic_hook | 0.1.7 | Apache-2.0/MIT | yes |
|
||||||
|
| console_log | 1.1.0 | MIT/Apache-2.0 | yes |
|
||||||
| const-oid | 0.10.3 | Apache-2.0 OR MIT | yes |
|
| const-oid | 0.10.3 | Apache-2.0 OR MIT | yes |
|
||||||
| core_detect | 1.0.0 | MIT/Apache-2.0 | yes |
|
| core_detect | 1.0.0 | MIT/Apache-2.0 | yes |
|
||||||
|
| core_maths | 0.1.1 | MIT | yes |
|
||||||
|
| core-foundation-sys | 0.8.7 | MIT OR Apache-2.0 | yes |
|
||||||
| cpubits | 0.1.1 | MIT OR Apache-2.0 | yes |
|
| cpubits | 0.1.1 | MIT OR Apache-2.0 | yes |
|
||||||
| cpufeatures | 0.3.1 | MIT OR Apache-2.0 | yes |
|
| cpufeatures | 0.3.1 | MIT OR Apache-2.0 | yes |
|
||||||
| crc32fast | 1.5.5 | MIT OR Apache-2.0 | yes |
|
| crc32fast | 1.5.5 | MIT OR Apache-2.0 | yes |
|
||||||
|
| crunchy | 0.2.4 | MIT | yes |
|
||||||
| crypto-common | 0.2.2 | MIT OR Apache-2.0 | yes |
|
| crypto-common | 0.2.2 | MIT OR Apache-2.0 | yes |
|
||||||
|
| data-url | 0.3.2 | MIT OR Apache-2.0 | yes |
|
||||||
| digest | 0.11.3 | MIT OR Apache-2.0 | yes |
|
| digest | 0.11.3 | MIT OR Apache-2.0 | yes |
|
||||||
|
| docx-rs | 0.4.22 | MIT | yes |
|
||||||
| ecb | 0.2.1 | MIT OR Apache-2.0 | yes |
|
| ecb | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||||
| either | 1.19.0 | MIT OR Apache-2.0 | yes |
|
| either | 1.19.0 | MIT OR Apache-2.0 | yes |
|
||||||
| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes |
|
| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes |
|
||||||
| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes |
|
| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes |
|
||||||
|
| errno | 0.3.15 | MIT OR Apache-2.0 | yes |
|
||||||
|
| euclid | 0.22.14 | MIT OR Apache-2.0 | yes |
|
||||||
| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes |
|
| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes |
|
||||||
| fax | 0.2.7 | MIT | yes |
|
| fax | 0.2.7 | MIT | yes |
|
||||||
| fdeflate | 0.3.7 | MIT OR Apache-2.0 | yes |
|
| fdeflate | 0.3.7 | MIT OR Apache-2.0 | yes |
|
||||||
|
| find-msvc-tools | 0.1.15 | MIT OR Apache-2.0 | yes |
|
||||||
| flate2 | 1.1.11 | MIT OR Apache-2.0 | yes |
|
| flate2 | 1.1.11 | MIT OR Apache-2.0 | yes |
|
||||||
|
| float-cmp | 0.9.0 | MIT | yes |
|
||||||
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
|
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
|
||||||
| foldhash | 0.2.0 | Zlib | yes |
|
| foldhash | 0.2.0 | Zlib | yes |
|
||||||
|
| font-types | 0.11.3 | MIT OR Apache-2.0 | yes |
|
||||||
|
| font-types | 0.12.7 | MIT OR Apache-2.0 | yes |
|
||||||
|
| fontconfig-parser | 0.5.8 | MIT | yes |
|
||||||
|
| fontdb | 0.24.0 | MIT | yes |
|
||||||
|
| futures-core | 0.3.34 | MIT OR Apache-2.0 | yes |
|
||||||
|
| futures-task | 0.3.34 | MIT OR Apache-2.0 | yes |
|
||||||
|
| futures-util | 0.3.34 | MIT OR Apache-2.0 | yes |
|
||||||
| g2gen | 1.2.2 | MIT/Apache-2.0 | yes |
|
| g2gen | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||||
| g2p | 1.2.2 | MIT/Apache-2.0 | yes |
|
| g2p | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||||
| g2poly | 1.2.2 | MIT/Apache-2.0 | yes |
|
| g2poly | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||||
| getrandom | 0.4.3 | MIT OR Apache-2.0 | yes |
|
| getrandom | 0.4.3 | MIT OR Apache-2.0 | yes |
|
||||||
| gif | 0.14.2 | MIT OR Apache-2.0 | yes |
|
| gif | 0.14.2 | MIT OR Apache-2.0 | yes |
|
||||||
| half | 2.7.1 | MIT OR Apache-2.0 | yes |
|
| half | 2.7.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| harfrust | 0.15.0 | MIT | yes |
|
||||||
| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes |
|
| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes |
|
||||||
| hybrid-array | 0.4.15 | MIT OR Apache-2.0 | yes |
|
| hybrid-array | 0.4.15 | MIT OR Apache-2.0 | yes |
|
||||||
|
| iana-time-zone | 0.1.65 | MIT OR Apache-2.0 | yes |
|
||||||
|
| iana-time-zone-haiku | 0.1.2 | MIT OR Apache-2.0 | yes |
|
||||||
| image | 0.25.10 | MIT OR Apache-2.0 | yes |
|
| image | 0.25.10 | MIT OR Apache-2.0 | yes |
|
||||||
| image-webp | 0.2.4 | MIT OR Apache-2.0 | yes |
|
| image-webp | 0.2.4 | MIT OR Apache-2.0 | yes |
|
||||||
|
| imagesize | 0.15.0 | MIT | yes |
|
||||||
| img-parts | 0.4.2 | MIT OR Apache-2.0 | yes |
|
| img-parts | 0.4.2 | MIT OR Apache-2.0 | yes |
|
||||||
| indexmap | 2.14.2 | Apache-2.0 OR MIT | yes |
|
| indexmap | 2.14.2 | Apache-2.0 OR MIT | yes |
|
||||||
| inout | 0.2.6 | MIT OR Apache-2.0 | yes |
|
| inout | 0.2.6 | MIT OR Apache-2.0 | yes |
|
||||||
| itertools | 0.15.0 | MIT OR Apache-2.0 | yes |
|
| itertools | 0.15.0 | MIT OR Apache-2.0 | yes |
|
||||||
| itoa | 1.0.19 | MIT OR Apache-2.0 | yes |
|
| itoa | 1.0.19 | MIT OR Apache-2.0 | yes |
|
||||||
|
| js-sys | 0.3.107 | MIT OR Apache-2.0 | yes |
|
||||||
| kamadak-exif | 0.6.2 | BSD-2-Clause | yes |
|
| kamadak-exif | 0.6.2 | BSD-2-Clause | yes |
|
||||||
|
| kurbo | 0.13.1 | Apache-2.0 OR MIT | yes |
|
||||||
|
| libc | 0.2.191 | MIT OR Apache-2.0 | yes |
|
||||||
| libloading | 0.9.1 | ISC | yes |
|
| libloading | 0.9.1 | ISC | yes |
|
||||||
|
| libm | 0.2.16 | MIT | yes |
|
||||||
|
| linux-raw-sys | 0.12.1 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | yes |
|
||||||
| log | 0.4.35 | MIT OR Apache-2.0 | yes |
|
| log | 0.4.35 | MIT OR Apache-2.0 | yes |
|
||||||
| lopdf | 0.47.0 | MIT | yes |
|
| lopdf | 0.47.0 | MIT | yes |
|
||||||
| lru | 0.18.5 | MIT | yes |
|
| lru | 0.18.5 | MIT | yes |
|
||||||
| maybe-owned | 0.3.4 | MIT OR Apache-2.0 | yes |
|
| maybe-owned | 0.3.4 | MIT OR Apache-2.0 | yes |
|
||||||
| md-5 | 0.11.0 | MIT OR Apache-2.0 | yes |
|
| md-5 | 0.11.0 | MIT OR Apache-2.0 | yes |
|
||||||
| memchr | 2.8.3 | Unlicense OR MIT | yes |
|
| memchr | 2.8.3 | Unlicense OR MIT | yes |
|
||||||
|
| memmap2 | 0.9.12 | MIT OR Apache-2.0 | yes |
|
||||||
| miniz_oxide | 0.8.9 | MIT OR Zlib OR Apache-2.0 | yes |
|
| miniz_oxide | 0.8.9 | MIT OR Zlib OR Apache-2.0 | yes |
|
||||||
| miniz_oxide | 0.9.1 | MIT OR Zlib OR Apache-2.0 | yes |
|
| miniz_oxide | 0.9.1 | MIT OR Zlib OR Apache-2.0 | yes |
|
||||||
| moxcms | 0.8.1 | BSD-3-Clause OR Apache-2.0 | yes |
|
| moxcms | 0.8.1 | BSD-3-Clause OR Apache-2.0 | yes |
|
||||||
@@ -162,9 +206,13 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| nom | 8.0.0 | MIT | yes |
|
| nom | 8.0.0 | MIT | yes |
|
||||||
| num-traits | 0.2.19 | MIT OR Apache-2.0 | yes |
|
| num-traits | 0.2.19 | MIT OR Apache-2.0 | yes |
|
||||||
| once_cell | 1.21.4 | MIT OR Apache-2.0 | yes |
|
| once_cell | 1.21.4 | MIT OR Apache-2.0 | yes |
|
||||||
|
| pdf-writer | 0.15.0 | MIT OR Apache-2.0 | yes |
|
||||||
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | yes |
|
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | yes |
|
||||||
|
| pico-args | 0.5.0 | MIT | yes |
|
||||||
|
| pin-project-lite | 0.2.17 | Apache-2.0 OR MIT | yes |
|
||||||
| piston-float | 1.0.1 | MIT | yes |
|
| piston-float | 1.0.1 | MIT | yes |
|
||||||
| png | 0.18.1 | MIT OR Apache-2.0 | yes |
|
| png | 0.18.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| polycool | 0.4.0 | MIT OR Apache-2.0 | yes |
|
||||||
| proc-macro-crate | 3.5.0 | MIT OR Apache-2.0 | yes |
|
| proc-macro-crate | 3.5.0 | MIT OR Apache-2.0 | yes |
|
||||||
| proc-macro2 | 1.0.107 | MIT OR Apache-2.0 | yes |
|
| proc-macro2 | 1.0.107 | MIT OR Apache-2.0 | yes |
|
||||||
| proptest | 1.12.0 | MIT OR Apache-2.0 | yes |
|
| proptest | 1.12.0 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -172,43 +220,83 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| qrcode | 0.14.1 | MIT OR Apache-2.0 | yes |
|
| qrcode | 0.14.1 | MIT OR Apache-2.0 | yes |
|
||||||
| quick-error | 1.2.3 | MIT/Apache-2.0 | yes |
|
| quick-error | 1.2.3 | MIT/Apache-2.0 | yes |
|
||||||
| quick-error | 2.0.1 | MIT/Apache-2.0 | yes |
|
| quick-error | 2.0.1 | MIT/Apache-2.0 | yes |
|
||||||
|
| quick-xml | 0.41.0 | MIT | yes |
|
||||||
| quote | 1.0.47 | MIT OR Apache-2.0 | yes |
|
| quote | 1.0.47 | MIT OR Apache-2.0 | yes |
|
||||||
|
| r-efi | 6.0.0 | MIT OR Apache-2.0 OR LGPL-2.1-or-later | yes |
|
||||||
| rand | 0.10.4 | MIT OR Apache-2.0 | yes |
|
| rand | 0.10.4 | MIT OR Apache-2.0 | yes |
|
||||||
| rand_core | 0.10.1 | MIT OR Apache-2.0 | yes |
|
| rand_core | 0.10.1 | MIT OR Apache-2.0 | yes |
|
||||||
| rand_xorshift | 0.5.0 | MIT OR Apache-2.0 | yes |
|
| rand_xorshift | 0.5.0 | MIT OR Apache-2.0 | yes |
|
||||||
| rangemap | 1.8.0 | MIT/Apache-2.0 | yes |
|
| rangemap | 1.8.0 | MIT/Apache-2.0 | yes |
|
||||||
|
| read-fonts | 0.39.2 | MIT OR Apache-2.0 | yes |
|
||||||
|
| read-fonts | 0.46.0 | MIT OR Apache-2.0 | yes |
|
||||||
| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes |
|
| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes |
|
||||||
|
| roxmltree | 0.20.0 | MIT OR Apache-2.0 | yes |
|
||||||
|
| roxmltree | 0.21.2 | MIT OR Apache-2.0 | yes |
|
||||||
| rqrr | 0.11.0 | (MIT OR Apache-2.0) AND ISC | yes |
|
| rqrr | 0.11.0 | (MIT OR Apache-2.0) AND ISC | yes |
|
||||||
|
| rustc-hash | 2.1.3 | Apache-2.0 OR MIT | yes |
|
||||||
|
| rustix | 1.1.6 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | yes |
|
||||||
| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes |
|
| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes |
|
||||||
| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes |
|
| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes |
|
||||||
|
| rustybuzz | 0.20.1 | MIT | yes |
|
||||||
|
| ryu | 1.0.23 | Apache-2.0 OR BSL-1.0 | yes |
|
||||||
| scopeguard | 1.2.0 | MIT OR Apache-2.0 | yes |
|
| scopeguard | 1.2.0 | MIT OR Apache-2.0 | yes |
|
||||||
| serde | 1.0.229 | MIT OR Apache-2.0 | yes |
|
| serde | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||||
| serde_core | 1.0.229 | MIT OR Apache-2.0 | yes |
|
| serde_core | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||||
| serde_derive | 1.0.229 | MIT OR Apache-2.0 | yes |
|
| serde_derive | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||||
| serde_json | 1.0.154 | MIT OR Apache-2.0 | yes |
|
| serde_json | 1.0.154 | MIT OR Apache-2.0 | yes |
|
||||||
| sha2 | 0.11.1 | MIT OR Apache-2.0 | yes |
|
| sha2 | 0.11.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| shlex | 2.0.1 | MIT OR Apache-2.0 | yes |
|
||||||
| simd-adler32 | 0.3.10 | MIT | yes |
|
| simd-adler32 | 0.3.10 | MIT | yes |
|
||||||
| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes |
|
| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes |
|
||||||
|
| simplecss | 0.2.2 | Apache-2.0 OR MIT | yes |
|
||||||
|
| siphasher | 1.0.4 | MIT OR Apache-2.0 | yes |
|
||||||
|
| skrifa | 0.42.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| skrifa | 0.49.0 | MIT OR Apache-2.0 | yes |
|
||||||
|
| slab | 0.4.12 | MIT | yes |
|
||||||
|
| slotmap | 1.1.1 | Zlib | yes |
|
||||||
|
| smallvec | 1.16.5 | MIT OR Apache-2.0 | yes |
|
||||||
|
| stable_deref_trait | 1.2.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| strict-num | 0.1.1 | MIT | yes |
|
||||||
| stringprep | 0.1.5 | MIT/Apache-2.0 | yes |
|
| stringprep | 0.1.5 | MIT/Apache-2.0 | yes |
|
||||||
|
| subsetter | 0.2.6 | MIT OR Apache-2.0 | yes |
|
||||||
|
| svgtypes | 0.16.2 | Apache-2.0 OR MIT | yes |
|
||||||
| syn | 2.0.119 | MIT OR Apache-2.0 | yes |
|
| syn | 2.0.119 | MIT OR Apache-2.0 | yes |
|
||||||
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
|
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
|
||||||
|
| synstructure | 0.14.0 | MIT | yes |
|
||||||
| tempfile | 3.27.0 | MIT OR Apache-2.0 | yes |
|
| tempfile | 3.27.0 | MIT OR Apache-2.0 | yes |
|
||||||
| thiserror | 2.0.21 | MIT OR Apache-2.0 | yes |
|
| thiserror | 2.0.21 | MIT OR Apache-2.0 | yes |
|
||||||
| thiserror-impl | 2.0.21 | MIT OR Apache-2.0 | yes |
|
| thiserror-impl | 2.0.21 | MIT OR Apache-2.0 | yes |
|
||||||
| tiff | 0.11.3 | MIT | yes |
|
| tiff | 0.11.3 | MIT | yes |
|
||||||
|
| tiny-skia | 0.12.0 | BSD-3-Clause | yes |
|
||||||
|
| tiny-skia-path | 0.12.0 | BSD-3-Clause | yes |
|
||||||
| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes |
|
| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||||
|
| tokio | 1.54.1 | MIT | yes |
|
||||||
| toml_datetime | 1.1.3+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
| toml_datetime | 1.1.3+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||||
| toml_edit | 0.25.19+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
| toml_edit | 0.25.19+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||||
| toml_parser | 1.1.5+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
| toml_parser | 1.1.5+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||||
|
| ttf-parser | 0.25.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| typed-path | 0.12.4 | MIT OR Apache-2.0 | yes |
|
||||||
| typenum | 1.20.1 | MIT OR Apache-2.0 | yes |
|
| typenum | 1.20.1 | MIT OR Apache-2.0 | yes |
|
||||||
| unarray | 0.1.4 | MIT OR Apache-2.0 | yes |
|
| unarray | 0.1.4 | MIT OR Apache-2.0 | yes |
|
||||||
| unicode-bidi | 0.3.18 | MIT OR Apache-2.0 | yes |
|
| unicode-bidi | 0.3.18 | MIT OR Apache-2.0 | yes |
|
||||||
|
| unicode-bidi-mirroring | 0.4.0 | MIT/Apache-2.0 | yes |
|
||||||
|
| unicode-ccc | 0.4.0 | MIT/Apache-2.0 | yes |
|
||||||
| unicode-ident | 1.0.27 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
| unicode-ident | 1.0.27 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||||
| unicode-normalization | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
| unicode-normalization | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||||
| unicode-properties | 0.1.5 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
| unicode-properties | 0.1.5 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||||
|
| unicode-script | 0.5.9 | MIT OR Apache-2.0 | yes |
|
||||||
|
| unicode-vo | 0.1.0 | MIT/Apache-2.0 | yes |
|
||||||
|
| usvg | 0.50.0 | Apache-2.0 OR MIT | yes |
|
||||||
| utf16string | 0.2.0 | MIT OR Apache-2.0 | yes |
|
| utf16string | 0.2.0 | MIT OR Apache-2.0 | yes |
|
||||||
| vecmath | 1.0.0 | MIT | yes |
|
| vecmath | 1.0.0 | MIT | yes |
|
||||||
|
| version_check | 0.9.5 | MIT/Apache-2.0 | yes |
|
||||||
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
|
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen-futures | 0.4.80 | MIT OR Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen-macro | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen-macro-support | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen-shared | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||||
|
| web-sys | 0.3.107 | MIT OR Apache-2.0 | yes |
|
||||||
| weezl | 0.1.12 | MIT OR Apache-2.0 | yes |
|
| weezl | 0.1.12 | MIT OR Apache-2.0 | yes |
|
||||||
| weezl | 0.2.1 | MIT OR Apache-2.0 | yes |
|
| weezl | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||||
| windows | 0.62.2 | MIT OR Apache-2.0 | yes |
|
| windows | 0.62.2 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -224,10 +312,18 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| windows-sys | 0.61.2 | MIT OR Apache-2.0 | yes |
|
| windows-sys | 0.61.2 | MIT OR Apache-2.0 | yes |
|
||||||
| windows-threading | 0.2.1 | MIT OR Apache-2.0 | yes |
|
| windows-threading | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||||
| winnow | 1.0.5 | MIT | yes |
|
| winnow | 1.0.5 | MIT | yes |
|
||||||
|
| write-fonts | 0.48.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| xmlwriter | 0.1.0 | MIT | yes |
|
||||||
|
| yoke | 0.8.4 | Unicode-3.0 | yes |
|
||||||
|
| yoke-derive | 0.8.4 | Unicode-3.0 | yes |
|
||||||
| zerocopy | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
| zerocopy | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
||||||
| zerocopy-derive | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
| zerocopy-derive | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
||||||
|
| zerofrom | 0.1.8 | Unicode-3.0 | yes |
|
||||||
|
| zerofrom-derive | 0.1.8 | Unicode-3.0 | yes |
|
||||||
|
| zip | 8.6.0 | MIT | yes |
|
||||||
| zlib-rs | 0.6.8 | Zlib | yes |
|
| zlib-rs | 0.6.8 | Zlib | yes |
|
||||||
| zmij | 1.0.23 | MIT | yes |
|
| zmij | 1.0.23 | MIT | yes |
|
||||||
|
| zopfli | 0.8.4 | Apache-2.0 | yes |
|
||||||
| zune-core | 0.5.3 | MIT OR Apache-2.0 OR Zlib | yes |
|
| zune-core | 0.5.3 | MIT OR Apache-2.0 OR Zlib | yes |
|
||||||
| zune-jpeg | 0.5.15 | MIT OR Apache-2.0 OR Zlib | yes |
|
| zune-jpeg | 0.5.15 | MIT OR Apache-2.0 OR Zlib | yes |
|
||||||
<!-- deps:end -->
|
<!-- deps:end -->
|
||||||
|
|||||||
+63
-1
@@ -43,6 +43,8 @@ page as displayed (the crop box, `/Rotate` applied). `geometry::PageFrame` conve
|
|||||||
| password on | lopdf, AES-256 (V5/R6), no permission restrictions | pdfium cannot write encryption; qpdf was not needed |
|
| password on | lopdf, AES-256 (V5/R6), no permission restrictions | pdfium cannot write encryption; qpdf was not needed |
|
||||||
| password off | lopdf decrypting load + plain save | |
|
| password off | lopdf decrypting load + plain save | |
|
||||||
| true redaction | pdfium render + lopdf rebuild (below) | |
|
| true redaction | pdfium render + lopdf rebuild (below) | |
|
||||||
|
| compress presets (Day 2) | lopdf: images capped at the largest page side × the preset's dpi and re-encoded as JPEG (E-mail 120 → 96 → 72 dpi until ≤ 5 MB, Web 150, Print 300); Flate everywhere; object streams | text, fonts and vectors untouched, so text stays extractable; fonts are not subset (gap) |
|
||||||
|
| PDF to Word (Day 2) | pdfium characters (box, size, weight, slant) → lines, segments, tables, paragraphs, headings; images at their place; docx-rs writes the .docx | "Layout is approximate"; spaces come from the gaps between letters (measured against the line's own letter spacing), never from pdfium's invented whitespace, so PDFs without space glyphs keep whole words; glyphs without a Unicode mapping stay U+FFFD; scanned pages are reported, and OCR text from Fundamentum's Lector can be passed in |
|
||||||
|
|
||||||
### True redaction
|
### True redaction
|
||||||
|
|
||||||
@@ -61,6 +63,61 @@ XObjects, inline images, clipping, shadings, Type 3 fonts), and any gap leaves t
|
|||||||
(`crates/pdf/tests/redaction.rs`) check pdfium text extraction, a lopdf scan of every string, name and stream (raw
|
(`crates/pdf/tests/redaction.rs`) check pdfium text extraction, a lopdf scan of every string, name and stream (raw
|
||||||
and decompressed), and a raw byte grep.
|
and decompressed), and a raw byte grep.
|
||||||
|
|
||||||
|
## The .pictor document (crates/doc), format 1
|
||||||
|
|
||||||
|
A `.pictor` file is a zip:
|
||||||
|
|
||||||
|
| Entry | What |
|
||||||
|
| :-- | :-- |
|
||||||
|
| `document.json` | the document (below), compressed |
|
||||||
|
| `assets/<id>.png` | the pixels of each bitmap layer and placed picture, RGBA, stored (PNG is already compressed) |
|
||||||
|
| `fonts/<sha256>.ttf` / `.otf` | the fonts the document uses whose licence allows embedding (OS/2 `fsType` installable or editable) |
|
||||||
|
|
||||||
|
`document.json` (every length in points, 1/72 in; a document made from an image has 1 pt = 1 px):
|
||||||
|
|
||||||
|
```
|
||||||
|
{ "format": 1, "next_id": 12,
|
||||||
|
"pages": [ { "id": 1, "width": 595.276, "height": 841.89, "margins": [t, r, b, l], "guides": [{"vertical": true, "at": 297.6}],
|
||||||
|
"background": [255, 255, 255, 255] | null,
|
||||||
|
"layers": [ { "id": 2, "name": "Layer 1", "visible": true, "locked": false, "opacity": 1,
|
||||||
|
"kind": "vector", "objects": [ … ] }
|
||||||
|
| { …, "kind": "bitmap", "asset": "b3", "x": 0, "y": 0, "w": 800, "h": 600 }
|
||||||
|
| { …, "kind": "group", "layers": [ … ] } ] } ],
|
||||||
|
"assets": [ { "id": "b3", "width": 800, "height": 600 } ],
|
||||||
|
"fonts": [ { "family": "Georgia", "weight": 700, "italic": false, "file": "fonts/<sha256>.ttf" } ] }
|
||||||
|
```
|
||||||
|
|
||||||
|
An object is `{ "id", "name", "transform": [a, b, c, d, e, f], "opacity", "visible", "locked", "fill", "stroke",
|
||||||
|
"shape" }` with `shape.type` one of `rect {w, h, radius}`, `ellipse {w, h}`, `line {x1, y1, x2, y2, arrow_start,
|
||||||
|
arrow_end}`, `path {d}` (absolute or relative M L H V C Q Z; no arcs), `text {w, text, style}` (style: `family,
|
||||||
|
weight, italic, size, color, align` left / center / right / justify, `line_height` as a multiple of the size,
|
||||||
|
`letter_spacing` in points), `image {asset, w, h, crop {x, y, w, h}}` (the whole picture's place inside the frame)
|
||||||
|
or `group {objects}`. A paint is `{"type": "solid", "color": [r, g, b, a]}`, `linear {x1, y1, x2, y2, stops}` or
|
||||||
|
`radial {cx, cy, r, stops}` with coordinates as fractions of the shape's box; a stroke is `{paint, width, dash, cap,
|
||||||
|
join}`. Colours are sRGB with straight alpha.
|
||||||
|
|
||||||
|
**Reading is strict** (`format::read`, `Limits`): at most 4096 entries; every entry name relative, without `..`,
|
||||||
|
`\`, `:` or empty parts, no directories or links (refused even when unused); entries are read by known name, never
|
||||||
|
extracted; `document.json` at most 64 MB and any entry 256 MB, the whole 1 GB, and no entry over 1 MB may expand
|
||||||
|
more than 1000×; the declared size must be the real one; `format` is read first and a newer one is refused
|
||||||
|
("made by a newer Pictor"); ids unique and below `next_id`, numbers finite, pages 1–14 400 pt, opacities 0–1, paths
|
||||||
|
parsed, nesting at most 32 deep; every picture at most 100 MP (400 MP together), decoded with its declared size as
|
||||||
|
the limit, and every asset a layer or object refers to must be present. A font must parse.
|
||||||
|
|
||||||
|
**Undo** is an operation log (`ops::Op`, `ops::History`): insert / remove / set a page, layer or object, replace an
|
||||||
|
object, patch an asset's pixels, put an asset, a batch. Applying an operation returns its exact inverse.
|
||||||
|
|
||||||
|
**Rendering** goes through one display list (`display::build`): fills, strokes, images (with a clip), glyph runs
|
||||||
|
(glyph outlines in font units, defined once) and opacity groups. The core paints it with tiny-skia; the app's
|
||||||
|
canvas painter follows the same rules; the PDF and SVG exports walk it too.
|
||||||
|
|
||||||
|
**PDF export** (`export::pdf`): pdf-writer; vectors as paths, gradients as shading patterns (a gradient's stops
|
||||||
|
share one alpha, their average), opacity as ExtGState alpha or an isolated transparency group, pictures as
|
||||||
|
FlateDecode RGB with an SMask, text as Type 0 fonts (Identity-H, CIDs are the subset's glyph ids, CIDToGIDMap
|
||||||
|
Identity) with a ToUnicode map and widths, so the layout's positions are kept with TJ adjustments; a font whose
|
||||||
|
`fsType` is restricted or bitmap-only is refused with its name and the reason; fonts that forbid subsetting are
|
||||||
|
embedded whole. Each page's MediaBox is its exact size.
|
||||||
|
|
||||||
## The worker protocol (crates/worker), version 1
|
## The worker protocol (crates/worker), version 1
|
||||||
|
|
||||||
`pictor-worker.exe` reads one JSON object per line on stdin and answers one per line on stdout. Its first line is
|
`pictor-worker.exe` reads one JSON object per line on stdin and answers one per line on stdout. Its first line is
|
||||||
@@ -73,7 +130,7 @@ and decompressed), and a raw byte grep.
|
|||||||
```
|
```
|
||||||
|
|
||||||
Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_large`, `codec_missing`, `invalid`,
|
Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_large`, `codec_missing`, `invalid`,
|
||||||
`io`, `exists`, `not_open`, `cannot_reach_target`, `engine_missing`; the client adds `timed_out`,
|
`io`, `exists`, `not_open`, `newer` (a .pictor from a newer Pictor), `cannot_reach_target`, `engine_missing`; the client adds `timed_out`,
|
||||||
`out_of_memory`, `crashed` and `spawn`. `message` is a plain sentence for the user.
|
`out_of_memory`, `crashed` and `spawn`. `message` is a plain sentence for the user.
|
||||||
|
|
||||||
| Operation | Arguments | Result |
|
| Operation | Arguments | Result |
|
||||||
@@ -86,6 +143,9 @@ Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_
|
|||||||
| `pdf.form` | `doc` | `fields`: name, kind, value, options, page, rect, read_only, multiline |
|
| `pdf.form` | `doc` | `fields`: name, kind, value, options, page, rect, read_only, multiline |
|
||||||
| `pdf.save` | `doc`, `edits` (see `pictor_pdf::Edits`), `output`, `mode` (`new` / `overwrite`) | `path`, `bytes`, `bak?`, `warnings` |
|
| `pdf.save` | `doc`, `edits` (see `pictor_pdf::Edits`), `output`, `mode` (`new` / `overwrite`) | `path`, `bytes`, `bak?`, `warnings` |
|
||||||
| `pdf.extract` | `doc`, `pages`, `output` | `path` |
|
| `pdf.extract` | `doc`, `pages`, `output` | `path` |
|
||||||
|
| `pdf.compress` | `doc`, `preset` (`email` ≤ 5 MB / `web` / `print`), `output` | `path`, `before`, `after`, `images_changed`, `warnings` |
|
||||||
|
| `pdf.to_word` | `doc`, `output` (.docx), `ocr?` ({page: text} for scanned pages) | `path`, `pages`, `scanned_pages` |
|
||||||
|
| `pdf.page_png` | `doc`, `page`, `dpi`, `output` | `path` (a page for OCR) |
|
||||||
| `pdf.to_images` | `doc`, `pages`, `dpi`, `format`, `output` (with `{n}`) | `paths` |
|
| `pdf.to_images` | `doc`, `pages`, `dpi`, `format`, `output` (with `{n}`) | `paths` |
|
||||||
| `pdf.merge` | `inputs` [{`path`, `password?`}], `output` | `path` |
|
| `pdf.merge` | `inputs` [{`path`, `password?`}], `output` | `path` |
|
||||||
| `pdf.split` | `path`, `password?`, `ranges` ("1-3, 5, 8-"), `output` (with `{n}`) | `paths` |
|
| `pdf.split` | `path`, `password?`, `ranges` ("1-3, 5, 8-"), `output` (with `{n}`) | `paths` |
|
||||||
@@ -93,6 +153,8 @@ Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_
|
|||||||
| `image.probe` | `path` | `format`, `width`, `height`, `has_alpha`, `frames`, `bytes` |
|
| `image.probe` | `path` | `format`, `width`, `height`, `has_alpha`, `frames`, `bytes` |
|
||||||
| `image.thumb` | `path`, `max` | `png`, original `width`, `height` |
|
| `image.thumb` | `path`, `max` | `png`, original `width`, `height` |
|
||||||
| `image.convert` | `input`, `output`, `format`, `quality?`, `crop?`, `rotate?`, `resize?`, `preset?`, `target_bytes?`, `overwrite?` | `path`, `bytes`, `format`, `width`, `height` |
|
| `image.convert` | `input`, `output`, `format`, `quality?`, `crop?`, `rotate?`, `resize?`, `preset?`, `target_bytes?`, `overwrite?` | `path`, `bytes`, `format`, `width`, `height` |
|
||||||
|
| `doc.open` | `input`, `output` | `path`, `pages`, `format` (a clean .pictor of the worker's making at `output`) |
|
||||||
|
| `doc.import_svg` | `input`, `output` | `path`, `width`, `height` (the SVG as a one-page .pictor; text as outlines) |
|
||||||
| `image.heif_support` | — | `support` |
|
| `image.heif_support` | — | `support` |
|
||||||
| `meta.read` | `path` | `report` (items by group), `groups` (with labels) |
|
| `meta.read` | `path` | `report` (items by group), `groups` (with labels) |
|
||||||
| `meta.strip` | `input`, `output`, `overwrite?` | `path`, `removed` |
|
| `meta.strip` | `input`, `output`, `overwrite?` | `path`, `removed` |
|
||||||
|
|||||||
+4
-3
@@ -32,11 +32,12 @@ export function allowed(expr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function main() {
|
function main() {
|
||||||
const meta = JSON.parse(execFileSync('cargo', ['metadata', '--format-version', '1', '--locked', '--filter-platform', 'x86_64-pc-windows-msvc'], {
|
// Every package in Cargo.lock (all platforms): a crate that is locked must be listed, whatever it is built for.
|
||||||
|
const meta = JSON.parse(execFileSync('cargo', ['metadata', '--format-version', '1', '--locked'], {
|
||||||
cwd: root, maxBuffer: 1 << 28, encoding: 'utf8',
|
cwd: root, maxBuffer: 1 << 28, encoding: 'utf8',
|
||||||
}));
|
}));
|
||||||
// Only crates reachable on Windows x64 (the one target of V1), not every lockfile entry of every platform:
|
// resolve.nodes lists every package the lockfile resolves (all targets).
|
||||||
// with --filter-platform, resolve.nodes lists what the workspace really depends on there.
|
|
||||||
const used = new Set(meta.resolve.nodes.map((n) => n.id));
|
const used = new Set(meta.resolve.nodes.map((n) => n.id));
|
||||||
const workspace = new Set(meta.workspace_members);
|
const workspace = new Set(meta.workspace_members);
|
||||||
const rows = meta.packages
|
const rows = meta.packages
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// The licence rule's SPDX evaluator (scripts/deps.mjs). Run: node --test scripts/deps.test.mjs
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { allowed } from './deps.mjs';
|
||||||
|
|
||||||
|
test('the allowed licences pass', () => {
|
||||||
|
for (const l of ['MIT', 'Apache-2.0', 'BSD-3-Clause', 'Zlib', 'MPL-2.0', 'ISC', 'Unicode-3.0', 'MIT OR Apache-2.0', 'MIT/Apache-2.0', '(MIT OR Apache-2.0) AND Unicode-3.0', 'Apache-2.0 WITH LLVM-exception'])
|
||||||
|
assert.ok(allowed(l), l);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('copyleft, non-commercial and missing licences fail', () => {
|
||||||
|
for (const l of ['GPL-3.0', 'AGPL-3.0-only', 'LGPL-2.1', 'CC-BY-NC-4.0', 'MIT AND GPL-2.0', '', undefined, 'SSPL-1.0', 'OpenSSL'])
|
||||||
|
assert.equal(allowed(l), false, String(l));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('OR needs one allowed branch, AND needs all', () => {
|
||||||
|
assert.ok(allowed('GPL-2.0 OR MIT'));
|
||||||
|
assert.equal(allowed('GPL-2.0 AND MIT'), false);
|
||||||
|
assert.ok(allowed('(GPL-2.0 OR MIT) AND Apache-2.0'));
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user