Merge pull request #11647 from Triwarr/pdf

PDF: import pages as artboards, export a page per artboard (+ recursive group export)
This commit is contained in:
FredApps authored and GitHub committed 2026-11-08 05:01:46 +01:00
commit aae9b7ea61
18 files changed
+1477 -114

No files matched your search

+13
View File
@@ -166,3 +166,16 @@ are adapted from Skyfuller1303’s MIT OR Apache-2.0 implementation in
`897f20072762fdf0eb688adcdb8d8cda7b38ce66`. Don Omondi’s embedded AI/PDF/EPS
extension and current-main integration build on that source. Clipboard and unrelated
Shape Tools changes from that branch are not included.
## Assets bundled by the PDF reader dependency (craft-pdf)
PhotoCraft imports PDF pages through `craft-pdf`, pinned to the craft-libs revision
`c5a1cbfb5f9049f9270955caffb5bee5997aebf7`. The renderer vendors Hayro and the assets below;
they ship inside the dependency rather than being copied into this repository. PDFium is no
longer used or shipped.
| Crate / file | Author | Source | Licence | Use |
| --- | --- | --- | --- | --- |
| `hayro-interpret 0.7.0 / assets/Foxit*.pfb` (13 standard-14 font files) | Foxit Software Inc. / PDFium Authors | <https://github.com/storytold/craft-libs/tree/c5a1cbfb5f9049f9270955caffb5bee5997aebf7/vendor/hayro-interpret/assets> | BSD-3-Clause | Renders non-embedded standard-14 PDF fonts |
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | <https://github.com/storytold/craft-libs/tree/c5a1cbfb5f9049f9270955caffb5bee5997aebf7/vendor/hayro-interpret/assets> | CC0-1.0 | Default CMYK colour conversion |
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | <https://github.com/storytold/craft-libs/tree/c5a1cbfb5f9049f9270955caffb5bee5997aebf7/vendor/hayro-cmap/assets> | BSD-3-Clause | Character-code mapping for CJK PDFs |
Generated
+298 -20
View File
@@ -22,7 +22,7 @@ dependencies = [
"accesskit",
"accesskit_consumer",
"atspi-common",
"phf",
"phf 0.14.0",
"serde",
"zvariant",
]
@@ -826,6 +826,17 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "brotli"
version = "8.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"brotli-decompressor",
]
[[package]]
name = "brotli-decompressor"
version = "5.0.3"
@@ -1443,6 +1454,18 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"bytemuck",
"hayro",
"hayro-interpret",
"hayro-syntax",
"thiserror 2.0.21",
]
[[package]]
name = "craft-print"
version = "0.1.0"
@@ -1472,7 +1495,7 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"serde",
"skrifa",
"skrifa 0.44.0",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
@@ -2107,7 +2130,7 @@ dependencies = [
"ecolor",
"emath",
"epaint_default_fonts",
"font-types",
"font-types 0.12.5",
"harfrust",
"log",
"nohash-hasher",
@@ -2115,13 +2138,13 @@ dependencies = [
"profiling",
"self_cell",
"serde",
"skrifa",
"skrifa 0.44.0",
"smallvec",
"unicode-bidi",
"unicode-general-category",
"unicode-properties",
"unicode-segmentation",
"vello_cpu",
"vello_cpu 0.2.0",
]
[[package]]
@@ -2377,6 +2400,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "font-types"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
dependencies = [
"bytemuck",
]
[[package]]
name = "font-types"
version = "0.12.5"
@@ -2423,7 +2455,7 @@ dependencies = [
"objc2-core-text",
"objc2-foundation 0.3.2",
"parlance",
"read-fonts",
"read-fonts 0.41.0",
"roxmltree 0.21.1",
"smallvec",
"windows",
@@ -2717,6 +2749,23 @@ dependencies = [
"xml-rs",
]
[[package]]
name = "glifo"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e"
dependencies = [
"bytemuck",
"foldhash 0.2.0",
"hashbrown 0.17.1",
"log",
"peniko",
"png 0.18.1",
"skrifa 0.42.1",
"smallvec",
"vello_common 0.0.9",
]
[[package]]
name = "glifo"
version = "0.3.0"
@@ -2728,9 +2777,9 @@ dependencies = [
"hashbrown 0.17.1",
"log",
"peniko",
"skrifa",
"skrifa 0.44.0",
"smallvec",
"vello_common",
"vello_common 0.2.0",
]
[[package]]
@@ -2879,7 +2928,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
"smallvec",
]
@@ -2912,6 +2961,94 @@ dependencies = [
"foldhash 0.2.0",
]
[[package]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"bytemuck",
"hayro-interpret",
"image",
"kurbo 0.13.1",
"log",
"pic-scale",
"vello_cpu 0.0.8",
]
[[package]]
name = "hayro-ccitt"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a14afde3344be69225fec4f6f44f6a219a3a492f9d8301eb25ef608fe4b7014c"
dependencies = [
"brotli",
"hayro-postscript",
]
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
"hayro-syntax",
"kurbo 0.13.1",
"moxcms",
"phf 0.13.1",
"rustc-hash 2.1.3",
"siphasher",
"skrifa 0.47.0",
"smallvec",
"yoke",
]
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"fearless_simd",
"hayro-ccitt",
]
[[package]]
name = "hayro-jpeg2000"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
dependencies = [
"fearless_simd",
]
[[package]]
name = "hayro-postscript"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"flate2",
"hayro-ccitt",
"hayro-jbig2",
"hayro-jpeg2000",
"memchr",
"rustc-hash 2.1.3",
"smallvec",
"stringprep",
"zune-jpeg 0.5.15",
]
[[package]]
name = "heck"
version = "0.5.0"
@@ -5001,7 +5138,7 @@ dependencies = [
"linebender_resource_handle",
"parlance",
"parley_data",
"skrifa",
"skrifa 0.44.0",
]
[[package]]
@@ -5080,17 +5217,37 @@ dependencies = [
"indexmap",
]
[[package]]
name = "phf"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros 0.13.1",
"phf_shared 0.13.1",
]
[[package]]
name = "phf"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
dependencies = [
"phf_macros",
"phf_shared",
"phf_macros 0.14.0",
"phf_shared 0.14.0",
"serde",
]
[[package]]
name = "phf_generator"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared 0.13.1",
]
[[package]]
name = "phf_generator"
version = "0.14.0"
@@ -5098,7 +5255,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100"
dependencies = [
"fastrand",
"phf_shared",
"phf_shared 0.14.0",
]
[[package]]
name = "phf_macros"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
dependencies = [
"phf_generator 0.13.1",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
@@ -5107,13 +5277,22 @@ version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"
dependencies = [
"phf_generator",
"phf_shared",
"phf_generator 0.14.0",
"phf_shared 0.14.0",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.14.0"
@@ -5435,6 +5614,7 @@ version = "0.20.1"
dependencies = [
"blake3",
"craft-docpath",
"craft-pdf",
"crc32fast",
"flate2",
"imagesize",
@@ -5586,7 +5766,7 @@ dependencies = [
"photocraft-psd",
"photocraft-raster",
"rayon",
"skrifa",
"skrifa 0.44.0",
]
[[package]]
@@ -5682,6 +5862,16 @@ dependencies = [
"web-sys",
]
[[package]]
name = "pic-scale"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6edb0ff645d35accaec252de081d55984a0d6c952cb1e5dc2b9afa7c78f07288"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "pico-args"
version = "0.5.0"
@@ -6307,6 +6497,16 @@ dependencies = [
"crossbeam-utils",
]
[[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.41.0"
@@ -6314,7 +6514,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [
"bytemuck",
"font-types",
"font-types 0.12.5",
"once_cell",
]
[[package]]
name = "read-fonts"
version = "0.44.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8"
dependencies = [
"bytemuck",
"font-types 0.12.5",
"once_cell",
]
@@ -7261,6 +7472,16 @@ 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.44.0"
@@ -7268,7 +7489,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
]
[[package]]
name = "skrifa"
version = "0.47.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f"
dependencies = [
"bytemuck",
"read-fonts 0.44.0",
]
[[package]]
@@ -8273,6 +8504,40 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "vello_common"
version = "0.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee"
dependencies = [
"bytemuck",
"fearless_simd",
"guillotiere",
"hashbrown 0.17.1",
"log",
"peniko",
"png 0.18.1",
"smallvec",
"thiserror 2.0.21",
]
[[package]]
name = "vello_common"
version = "0.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19d672facaa2d697285a786cd9d44d614cd2ce54cdc022504bf339f8fff3b750"
dependencies = [
"bytemuck",
"fearless_simd",
"guillotiere",
"hashbrown 0.17.1",
"log",
"peniko",
"png 0.18.1",
"smallvec",
"thiserror 2.0.21",
]
[[package]]
name = "vello_common"
version = "0.2.0"
@@ -8288,6 +8553,19 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "vello_cpu"
version = "0.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0"
dependencies = [
"bytemuck",
"glifo 0.1.1",
"hashbrown 0.17.1",
"png 0.18.1",
"vello_common 0.0.8",
]
[[package]]
name = "vello_cpu"
version = "0.2.0"
@@ -8295,9 +8573,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9"
dependencies = [
"bytemuck",
"glifo",
"glifo 0.3.0",
"hashbrown 0.17.1",
"vello_common",
"vello_common 0.2.0",
]
[[package]]
+6
View File
@@ -40,6 +40,7 @@ photocraft-ipp = { path = "crates/ipp" }
# external
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["raster"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" }
@@ -203,3 +204,8 @@ eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968157
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README).
hayro = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
+48
View File
@@ -70,3 +70,51 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Optional PDF reader (craft-pdf)
PhotoCraft imports PDF pages through craft-pdf (https://github.com/storytold/craft-libs,
MIT OR Apache-2.0), pinned to revision c5a1cbfb5f9049f9270955caffb5bee5997aebf7. It vendors
Hayro 0.7.1, hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0 and
hayro-cmap 0.1.0 (https://github.com/LaurenzV/hayro, MIT OR Apache-2.0). The reader bundles
the standard-14 Foxit fonts (BSD-3-Clause), Adobe CMaps (BSD-3-Clause) and a Compact ICC
profile by Clinton Ingram (CC0-1.0); per-file sources and hashes are in craft-libs
ATTRIBUTION.md. No PDF assets are copied into this repository, and PDFium is no longer used or
shipped.
Licence texts for the optional PDF reader
Hayro (MIT):
Copyright (c) The Hayro Authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Standard-14 Foxit fonts (BSD-3-Clause):
Copyright 2014 PDFium Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Adobe CMaps (BSD-3-Clause):
Copyright 1990-2023 Adobe. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Adobe nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Compact ICC profile: CC0 1.0 Universal (public domain dedication), by Clinton Ingram (saucecontrol/Compact-ICC-Profiles).
+30
View File
@@ -119,6 +119,12 @@ pub(crate) struct ConvertArgs {
/// Explicitly approve high-memory PSD/PSB imports within the hard memory budget
#[arg(long)]
pub(crate) approve_high_memory: bool,
/// PDF import resolution in DPI (default 300)
#[arg(long, value_name = "DPI", value_parser = pdf_dpi)]
pub(crate) pdf_dpi: Option<f32>,
/// PDF pages to import, 1-based: "3" or "2-7" (default all)
#[arg(long)]
pub(crate) pdf_pages: Option<String>,
#[command(flatten)]
pub(crate) gpu: GpuArgs,
#[command(flatten)]
@@ -322,6 +328,8 @@ enum ValueError {
Metadata,
#[error("expected on or off")]
OnOff,
#[error("expected a positive number")]
PdfDpi,
/// Why a `--bridge` value, or a PHOTOCRAFT_CONTROL_PORT value for `mcp`, is refused.
#[error("expected a port, 0-65535 (--bridge also takes 127.0.0.1:<PORT>)")]
Bridge,
@@ -390,6 +398,12 @@ fn on_off(s: &str) -> Result<bool, ValueError> {
}
}
/// A PDF import DPI: a finite number greater than zero. The importer's fallback to 300 DPI is
/// for absent preferences, not for a mistyped flag.
fn pdf_dpi(s: &str) -> Result<f32, ValueError> {
s.parse::<f32>().ok().filter(|dpi| dpi.is_finite() && *dpi > 0.0).ok_or(ValueError::PdfDpi)
}
fn jpeg_format(s: &str) -> Result<JpegFormat, ValueError> {
JpegFormat::parse(s).ok_or(ValueError::JpegFormat)
}
@@ -548,3 +562,19 @@ fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, tr
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// `--pdf-dpi` only takes a positive finite number: a mistyped value is refused at parse time
/// instead of silently becoming the importer's 300 DPI fallback.
#[test]
fn pdf_dpi_rejects_non_positive_and_non_finite_values() {
assert!(pdf_dpi("300").is_ok());
assert!(pdf_dpi("0.5").is_ok());
for bad in ["0", "-1", "nan", "inf", "-inf", "abc"] {
assert!(pdf_dpi(bad).is_err(), "{bad} should be refused");
}
}
}
+18 -1
View File
@@ -26,11 +26,28 @@ fn refuse_overwriting_input(in_place: bool, input: &Path, output: &Path) -> Resu
Ok(())
}
/// `N` or `N-M`, 1-based and inclusive, into a normalized `(first, last)`.
fn parse_pdf_pages(s: &str) -> Result<(u32, u32)> {
let (a, b) = s.split_once('-').unwrap_or((s, s));
let bad = || CliError::Other(format!("invalid --pdf-pages {s:?}; use N or N-M"));
let a = a.trim().parse::<u32>().map_err(|_| bad())?;
let b = b.trim().parse::<u32>().map_err(|_| bad())?;
if a == 0 || b == 0 {
return Err(CliError::Other(format!("--pdf-pages is 1-based; {s:?} starts at 0")));
}
Ok((a.min(b), a.max(b)))
}
pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write) -> Result {
let (input, output) = (&a.input, &a.output);
let opts = ExportOptions::from(&a.export);
refuse_overwriting_input(a.in_place, input, output)?;
let import_opts = photocraft_io::ImportOptions { psd_high_memory_approved: a.approve_high_memory, ..Default::default() };
let import_opts = photocraft_io::ImportOptions {
psd_high_memory_approved: a.approve_high_memory,
pdf_dpi: a.pdf_dpi.unwrap_or(300.0),
pdf_pages: a.pdf_pages.as_deref().map(parse_pdf_pages).transpose()?,
..Default::default()
};
let mut o = files::open_with_options(input, &import_opts)?;
// Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw.
photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document);
+8
View File
@@ -957,6 +957,14 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor
photocraft_io::ImportOptions {
max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize,
demosaic: prefs.raw_defaults.demosaic.method(),
pdf_dpi: prefs.file_handling.pdf_dpi,
pdf_pages: match (prefs.file_handling.pdf_first_page, prefs.file_handling.pdf_last_page) {
(0, 0) => None,
(first, last) => {
let first = first.max(1);
Some((first, if last == 0 { u32::MAX } else { last.max(first) }))
}
},
..Default::default()
}
}
+9
View File
@@ -570,6 +570,12 @@ pub struct FileHandling {
pub recover_on_launch: bool,
/// Open a file with no ICC profile as untagged even when its EXIF ColorSpace tag says sRGB.
pub ignore_exif_profile_tag: bool,
/// PDF import resolution in DPI; the document keeps it so the page's print size is preserved.
pub pdf_dpi: f32,
/// The first PDF page to import (1-based; 0 imports from the first page).
pub pdf_first_page: u32,
/// The last PDF page to import (1-based; 0 imports to the last page).
pub pdf_last_page: u32,
/// Most renderers write ACEScg EXRs without stating the colour space. With this on, an EXR
/// that would otherwise open as linear sRGB opens as ACEScg (AP1, linear) instead.
pub exr_aces_cg: bool,
@@ -607,6 +613,9 @@ impl Default for FileHandling {
autosave_minutes: 10,
recover_on_launch: true,
ignore_exif_profile_tag: false,
pdf_dpi: 300.0,
pdf_first_page: 0,
pdf_last_page: 0,
exr_aces_cg: false,
ask_before_saving_layered_tiff: true,
maximize_psd_compatibility: Ask::Always,
+2
View File
@@ -51,6 +51,8 @@ imagesize = "0.13"
resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] }
# The SVG fallback font search keeps each font file's character map (already in the tree through usvg).
ttf-parser = { version = "0.25", default-features = false }
# PDF import (pdf_import.rs): craft-pdf rasterizes pages in pure Rust; no shared library ships.
craft-pdf = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] }
+92 -6
View File
@@ -65,6 +65,7 @@ pub use ora::losses as ora_losses;
pub mod pattern_map;
mod pcraft_cache;
pub mod pdf;
mod pdf_import;
mod pdn;
pub use pcraft_cache::PcraftExportCache;
pub mod pixels;
@@ -513,8 +514,8 @@ pub enum ImportPreflight {
/// A flat raster decoded into one image, bounded by
/// [`ImportOptions::flat_max_pixel_bytes`].
Flat,
/// Affinity, OpenRaster, Krita, XCF, PDN, SVG, camera raw and `.pcraft` files: this build has
/// no header-only estimate of their pixel memory before decoding.
/// Affinity, OpenRaster, Krita, XCF, PDN, SVG, camera raw, PDF and `.pcraft` files: this
/// build has no header-only estimate of their pixel memory before decoding.
Unbounded,
}
@@ -555,6 +556,11 @@ pub fn import_preflight(name: &str, bytes: &[u8]) -> ImportPreflight {
if is_psd_input(name, bytes) {
return ImportPreflight::Psd;
}
// PDF (craft-pdf, pure Rust). `.ai` files that start with `%PDF-` are PDFs and take this
// importer too; a recognized raster signature wins over a misleading `.pdf` suffix.
if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && photocraft_codecs::detect(bytes).is_none()) {
return ImportPreflight::Unbounded;
}
if photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) { ImportPreflight::Tiff } else { ImportPreflight::Flat }
}
@@ -601,6 +607,11 @@ pub struct ImportOptions {
/// Decoded-pixel allowance for a flat raster (the buffer a codec decodes into). May lower
/// the codec's default cap; 0 uses it. PSD/PSB and layered TIFF use `psd_max_pixel_bytes`.
pub flat_max_pixel_bytes: u64,
/// Resolution (dots per inch) PDF pages are rendered at on import; the document keeps it so
/// the page's print size is preserved. Defaults to 300.
pub pdf_dpi: f32,
/// The 1-based, inclusive page range to import; `None` imports every page (up to the cap).
pub pdf_pages: Option<(u32, u32)>,
/// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget.
pub psd_high_memory_approved: bool,
/// Optional estimate limit for high-memory approval. When set, approval only applies if
@@ -615,6 +626,8 @@ impl Default for ImportOptions {
demosaic: raw::Demosaic::default(),
psd_max_pixel_bytes: 0,
flat_max_pixel_bytes: 0,
pdf_dpi: 300.0,
pdf_pages: None,
psd_high_memory_approved: false,
psd_approved_estimate: None,
}
@@ -975,6 +988,16 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route {
/// Dispatches format-specific importers and propagates a structured PSD damage
/// flag alongside the ordinary best-effort import result.
fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result<ImportResult, IoError> {
// SVG content wins over a misleading `.pdf` suffix, matching the preflight (which checks SVG
// before PDF).
if is_svg_input(name, bytes) {
return svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth);
}
// PDF (craft-pdf, pure Rust). `.ai` files that start with `%PDF-` are PDFs and take this
// importer too; a recognized raster signature wins over a misleading `.pdf` suffix.
if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && photocraft_codecs::detect(bytes).is_none()) {
return pdf_import::import(name, bytes, opts, ctl);
}
match route(name, bytes) {
Route::Pcraft => {
let document = photocraft_format::load_from_bytes(bytes)?;
@@ -999,10 +1022,28 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o
pub fn is_svg_input(name: &str, bytes: &[u8]) -> bool {
// Keep the SVG extension as a fallback for malformed files so the SVG parser can return an
// actionable SVG error. A recognized raster signature still wins over a misleading `.svg`
// suffix (for example, a WebP downloaded as Firefox_logo.svg).
// suffix (for example, a WebP downloaded as Firefox_logo.svg), and so does every other
// format's signature: a PDF named `.svg` must reach the PDF importer.
svg::is_svg(bytes)
|| (has_extension(name, "svg") && photocraft_codecs::detect(bytes).is_none())
|| (has_extension(name, "svgz") && bytes.starts_with(&[0x1f, 0x8b]))
|| (has_extension(name, "svg") && photocraft_codecs::detect(bytes).is_none() && !has_format_signature(name, bytes))
|| (has_extension(name, "svgz") && bytes.starts_with(&[0x1f, 0x8b]) && !has_format_signature(name, bytes))
}
/// A non-raster format's signature or declared extension, checked before the `.svg` suffix
/// fallback so a misnamed file keeps its own importer.
fn has_format_signature(name: &str, bytes: &[u8]) -> bool {
is_psd(bytes)
|| pdf_import::is_pdf(bytes)
|| is_psd_input(name, bytes)
|| raw::is_raw(bytes)
|| affinity::is_affinity(bytes)
|| ora::is_ora(bytes)
|| kra::is_kra(bytes)
|| xcf::is_xcf(bytes)
|| has_extension(name, "pdn")
|| bytes.starts_with(b"PDN3")
|| photocraft_format::is_pcraft(bytes)
|| has_extension(name, photocraft_format::EXTENSION)
}
fn extension(name_or_ext: &str) -> String {
@@ -1154,7 +1195,7 @@ fn export_stages_with_renderer(
return Ok(res.into());
}
if ext == "pdf" {
let mut res = pdf::export(doc)?;
let mut res = pdf::export(doc, ctl)?;
if let Some(r) = renderer {
res.warnings.push("PDF export uses CPU compositor; GPU rendering applies to flat formats".into());
res.warnings.extend(r.drain_diagnostics());
@@ -1570,4 +1611,49 @@ mod tests {
assert_eq!(d.bounds().height(), 8, "{name}");
}
}
/// A PDF named `.svg` (a save-as mistake) must reach the PDF importer, not the SVG parser;
/// SVG content still wins over a `.pdf` suffix.
#[test]
fn a_pdf_named_svg_stays_a_pdf() {
let pdf = b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n";
assert!(!is_svg_input("drawing.svg", pdf));
assert!(!is_svg_input("drawing.svgz", pdf));
assert!(is_svg_input("drawing.svg", b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>"));
assert_eq!(crate::route("drawing.svg", pdf), crate::Route::Flat);
}
/// `.ai` files that start with `%PDF-` are PDFs: both preflight and dispatch send them to the
/// PDF importer rather than the flat decoder.
#[test]
fn an_ai_with_pdf_content_takes_the_pdf_importer() {
use lopdf::{Document as PdfDocument, Object, Stream, dictionary};
let mut pdf = PdfDocument::with_version("1.5");
let pages_id = pdf.new_object_id();
let content = b"0 0 1 rg 10 10 20 20 re f";
let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec()));
let page_id = pdf.add_object(dictionary! {
"Type" => "Page",
"Parent" => pages_id,
"MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(100.0), Object::Real(100.0)]),
"Contents" => content_id,
"Resources" => dictionary! {},
});
pdf.objects.insert(
pages_id,
Object::Dictionary(dictionary! {
"Type" => "Pages",
"Kids" => Object::Array(vec![Object::Reference(page_id)]),
"Count" => 1,
}),
);
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
pdf.trailer.set("Root", catalog);
let mut bytes = Vec::new();
pdf.save_to(&mut bytes).expect("writing the .ai fixture");
assert!(crate::pdf_import::is_pdf(&bytes));
assert_eq!(import_preflight("illustration.ai", &bytes), ImportPreflight::Unbounded);
let result = import("illustration.ai", &bytes).expect("an .ai starting with %PDF- takes the PDF importer");
assert_eq!(result.document.artboards().len(), 1);
}
}
+207 -65
View File
@@ -44,6 +44,8 @@ pub struct PrintPage {
pub marks: Marks,
pub description: Option<String>,
pub label: Option<String>,
/// The page's name in the PDF `/PageLabels` tree (Unicode-capable; not drawn on the page).
pub page_label: Option<String>,
}
pub(super) fn pdf_string(s: &str) -> String {
@@ -62,6 +64,16 @@ pub(super) fn pdf_string(s: &str) -> String {
o
}
/// A PDF text string with UTF-16BE hex (the Unicode-capable form, byte-order mark included).
fn pdf_unicode_string(s: &str) -> String {
let mut o = String::from("<FEFF");
for u in s.encode_utf16() {
o.push_str(&format!("{u:04X}"));
}
o.push('>');
o
}
fn deflate(data: &[u8]) -> Vec<u8> {
// Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static
// Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger
@@ -109,10 +121,20 @@ fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String {
/// A one-page PDF.
pub fn print_pdf(page: &PrintPage) -> Vec<u8> {
print_pdf_with_vectors(page, "", &selection::SelectionFont::default())
print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default(), &photocraft_raster::Interrupt::NONE).unwrap_or_default()
}
fn print_pdf_with_vectors(page: &PrintPage, vectors: &str, selection_font: &selection::SelectionFont) -> Vec<u8> {
/// A PDF with one page per entry; `vectors[i]` (when present) is drawn over page `i`.
fn print_pdf_pages(
pages: &[PrintPage],
vectors: &[String],
selection_font: &selection::SelectionFont,
ctl: &photocraft_raster::Interrupt,
) -> std::result::Result<Vec<u8>, IoError> {
if ctl.check().is_err() {
return Err(IoError::Cancelled);
}
let Some(first) = pages.first() else { return Ok(Vec::new()) };
let mut out: Vec<u8> = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec();
let mut offsets: Vec<usize> = Vec::new();
let mut obj = |out: &mut Vec<u8>, body: &[u8]| {
@@ -121,72 +143,112 @@ fn print_pdf_with_vectors(page: &PrintPage, vectors: &str, selection_font: &sele
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
};
let img = &page.image;
let (pw, ph) = page.paper;
let (x, y, w, h) = page.rect;
let selection_base = if img.icc.is_some() { 8 } else { 7 };
// 1 catalog, 2 pages, 3 page, 4 contents, 5 image, 6 font, 7 ICC (optional).
obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>");
obj(&mut out, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
obj(
&mut out,
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 5 0 R >> /Font << /F1 6 0 R /FSelect {selection_base} 0 R >> >> /Contents 4 0 R >>"
let n = pages.len();
// A label tree is written only for a non-empty name: an all-empty tree would be `/Nums []`,
// and filtering the first empty name away would start the tree at page index 1, not 0.
let labels_on = pages.iter().any(|p| p.page_label.as_deref().is_some_and(|label| !label.is_empty()));
// 1 catalog, 2 pages, then per page: page, contents, image; then the shared font/ICC/selection.
let font_obj = 3 + n * 3;
let icc = first.image.icc.as_ref();
let icc_obj = icc.map(|_| font_obj + 1);
let selection_base = font_obj + if icc.is_some() { 2 } else { 1 };
let selection_objects = selection_font.objects(selection_base);
let labels_obj = labels_on.then_some((selection_base + selection_objects.len()) as u32);
obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{} >>", labels_obj.map(|o| format!(" /PageLabels {o} 0 R")).unwrap_or_default()).as_bytes());
let kids = (0..n).map(|i| format!("{} 0 R", 3 + i * 3)).collect::<Vec<_>>().join(" ");
obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes());
for (i, page) in pages.iter().enumerate() {
let page_obj = 3 + i * 3;
let content_obj = page_obj + 1;
let image_obj = page_obj + 2;
let (pw, ph) = page.paper;
let (x, y, w, h) = page.rect;
obj(
&mut out,
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 {image_obj} 0 R >> /Font << /F1 {font_obj} 0 R /FSelect {selection_base} 0 R >> >> /Contents {content_obj} 0 R >>"
)
.as_bytes(),
);
// An explicit white page, so every viewer (and rasteriser) shows paper, not transparency.
let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\nq {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n");
if let Some(v) = vectors.get(i) {
content.push_str(v);
}
content.push_str(&marks_ops(page.marks, page.rect));
let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration;
let pad = if any_marks { 30.0 } else { 6.0 };
if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) {
content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l)));
}
if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) {
content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d)));
}
let c = deflate(content.as_bytes());
let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes();
body.extend_from_slice(&c);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
let img = &page.image;
let device = match img.channels {
1 => "/DeviceGray",
4 => "/DeviceCMYK",
_ => "/DeviceRGB",
};
let cs = match icc_obj {
Some(obj) => format!("[/ICCBased {obj} 0 R]"),
None => device.to_string(),
};
let z = deflate(&img.data);
let mut body = format!(
"<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n",
img.width,
img.height,
z.len()
)
.as_bytes(),
);
// An explicit white page, so every viewer (and rasteriser) shows paper, not transparency.
let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\nq {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n");
content.push_str(vectors);
content.push_str(&marks_ops(page.marks, page.rect));
let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration;
let pad = if any_marks { 30.0 } else { 6.0 };
if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) {
content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l)));
}
if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) {
content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d)));
}
let c = deflate(content.as_bytes());
let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes();
body.extend_from_slice(&c);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
let device = match img.channels {
1 => "/DeviceGray",
4 => "/DeviceCMYK",
_ => "/DeviceRGB",
};
let cs = if img.icc.is_some() { "[/ICCBased 7 0 R]".to_string() } else { device.to_string() };
let z = deflate(&img.data);
let mut body = format!(
"<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n",
img.width,
img.height,
z.len()
)
.into_bytes();
body.extend_from_slice(&z);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>");
if let Some(icc) = &img.icc {
let z = deflate(icc);
let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", img.channels, z.len()).into_bytes();
.into_bytes();
body.extend_from_slice(&z);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
}
for body in selection_font.objects(selection_base) {
obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>");
if let Some(icc) = icc {
let device = match first.image.channels {
1 => "/DeviceGray",
4 => "/DeviceCMYK",
_ => "/DeviceRGB",
};
let z = deflate(icc);
let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", first.image.channels, z.len()).into_bytes();
body.extend_from_slice(&z);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
}
for body in &selection_objects {
obj(&mut out, body);
}
if labels_obj.is_some() {
// Every page gets an entry: a number-tree range runs until the next key, so omitting an
// empty name would make that page inherit the previous page's label. An empty
// dictionary gives the page the default (decimal) label instead.
let nums = pages
.iter()
.enumerate()
.map(|(i, p)| match p.page_label.as_deref().filter(|label| !label.is_empty()) {
Some(label) => format!("{i} << /P {} >>", pdf_unicode_string(label)),
None => format!("{i} << >>"),
})
.collect::<Vec<_>>()
.join(" ");
obj(&mut out, format!("<< /Nums [{nums}] >>").as_bytes());
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
for o in &offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
out
Ok(out)
}
/// The vector operators for the contiguous visible top prefix of `doc`, top to bottom, with the
@@ -261,10 +323,17 @@ fn collect_vectors(doc: &Document) -> (Vec<(usize, String)>, selection::Selectio
(layers, selection_font)
}
/// File › Save As / Save a Copy › PDF (#3401): the flattened document, at its print size
/// (pixels ÷ resolution × 72 pt), as a one-page PDF. Layers and transparency are dropped — the
/// warning says so — and the embedded profile travels with the image.
pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
/// Pixels in `rect`, saturating on overflow.
fn rect_pixels(rect: photocraft_geom::Rect) -> u64 {
u64::from(rect.width()).saturating_mul(u64::from(rect.height()))
}
/// File › Save As / Save a Copy › PDF (#3401): the flattened document at its print size
/// (pixels ÷ resolution × 72 pt). One page per artboard when the document has artboards, else one
/// page for the whole document. Layers and transparency are dropped — the warning says so — and
/// the embedded profile travels with the images.
pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result::Result<ExportResult, IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
let (w, h) = (usize::try_from(doc.size.width).unwrap_or(0), usize::try_from(doc.size.height).unwrap_or(0));
if w == 0 || h == 0 {
return Err(IoError::Unsupported("PDF needs a document with non-zero width and height; nothing was written".into()));
@@ -277,6 +346,82 @@ pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
};
let fmt = doc.pixel_format();
let n = fmt.channels().max(1);
let dpi = f64::from(doc.resolution_dpi.max(1.0));
let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 };
let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
let icc = doc.icc_profile.as_ref().map(|p| p.to_vec());
let artboards = doc.artboards();
if !artboards.is_empty() {
// Every page's encoded pixels are kept until the PDF is assembled; bound that peak.
const MAX_PDF_EXPORT_BYTES: u64 = 1 << 30;
let page_pixels: u64 = artboards.iter().fold(0u64, |bytes, (_, _, a)| bytes.saturating_add(rect_pixels(a.rect)));
let retained = page_pixels.saturating_mul(device as u64);
// One page renders at a time: its f32 composite surface plus the region read back from
// it, both `n` channels at 4 bytes per pixel. The whole-document canvas is never held.
let largest = artboards.iter().map(|(_, _, a)| rect_pixels(a.rect)).max().unwrap_or(0);
let temporary = largest.saturating_mul(n as u64).saturating_mul(4).saturating_mul(2);
let estimate = retained.saturating_add(temporary);
if estimate > MAX_PDF_EXPORT_BYTES {
return Err(IoError::Unsupported(format!(
"PDF export would need about {} MB for {} artboards; export them in smaller batches",
estimate >> 20,
artboards.len()
)));
}
// One document shell is reused for every page. Each page renders a document holding only
// its artboard group (the same isolation as `artboard_document`), so an overlapping board
// cannot paint on another board's page. Layer pixels are shared with `doc`; this one
// clone and the per-page group clone hold no new pixel buffers, but they are outside the
// 1 GiB estimate because they are not retained page data.
let mut one = doc.clone();
let mut pages = Vec::with_capacity(artboards.len());
for (id, name, artboard) in &artboards {
ctl.check().map_err(|_| IoError::Cancelled)?;
let rect = artboard.rect;
let (aw, ah) = (rect.width(), rect.height());
if aw == 0 || ah == 0 {
continue;
}
// A hidden artboard still gets its page, rendered from its own content rather than
// left blank by the group's visibility.
let Some(layer) = doc.layer(*id) else { continue };
let mut group = layer.clone();
group.visible = true;
one.layers.clear();
one.layers.push(group);
// Render only this artboard's rect; the surface never holds the whole document.
let surface = photocraft_compose::composite_to_surface(&one, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None);
let values = surface.read_region(rect);
let mut data = Vec::with_capacity((aw as usize * ah as usize).saturating_mul(device));
for px in values.chunks(n) {
let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0);
for v in px.iter().take(device) {
data.push(to8(v * a + paper * (1.0 - a)));
}
}
let image = PrintImage { width: aw, height: ah, channels: device, data, icc: icc.clone() };
let (pw, ph) = (f64::from(aw) * 72.0 / dpi, f64::from(ah) * 72.0 / dpi);
pages.push(PrintPage {
paper: (pw, ph),
image,
rect: (0.0, 0.0, pw, ph),
marks: Marks::default(),
description: None,
label: None,
page_label: Some((*name).to_string()),
});
}
if pages.is_empty() {
return Err(IoError::Unsupported("PDF: the document's artboards have no area".into()));
}
let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()];
warnings.push(format!("PDF exported {} artboards as {} pages; vector/text layers on artboards are rasterised", artboards.len(), pages.len()));
if !doc.metadata.text.is_empty() {
warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into());
}
let vectors = vec![String::new(); pages.len()];
return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default(), ctl)?, warnings });
}
let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32);
// Simple topmost shapes and text layers can be drawn over the flattened backdrop without changing
// compositing. Stop at the first unsupported visible layer, since it may depend on the
@@ -290,10 +435,8 @@ pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
}
let surface = photocraft_compose::flatten_to_surface(&backdrop, PixelFormat::new(fmt.mode, fmt.sample, true), None);
let values = surface.read_region(canvas);
let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
// Straight alpha, composited here over paper: white in RGB/Gray (1 = full light), zero ink
// in CMYK (0 = paper).
let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 };
let mut data = Vec::with_capacity((w * h).saturating_mul(device));
for px in values.chunks(n) {
let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0);
@@ -301,10 +444,9 @@ pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
data.push(to8(v * a + paper * (1.0 - a)));
}
}
let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: doc.icc_profile.as_ref().map(|p| p.to_vec()) };
let dpi = f64::from(doc.resolution_dpi.max(1.0));
let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: icc.clone() };
let (pw, ph) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi);
let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None };
let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None, page_label: None };
let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()];
if !doc.metadata.text.is_empty() {
warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into());
@@ -315,7 +457,7 @@ pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
vectors.push_str(ops);
}
vectors.push_str("Q\n");
Ok(ExportResult { bytes: print_pdf_with_vectors(&page, &vectors, &selection_font), warnings })
Ok(ExportResult { bytes: print_pdf_pages(&[page], &[vectors], &selection_font, ctl)?, warnings })
}
#[cfg(test)]
+170 -18
View File
@@ -1,10 +1,11 @@
//! PDF export: structure, pixel oracle, colour modes and refusal paths.
use super::*;
use lopdf::{Object, StringFormat};
use photocraft_color::{PixelFormat, SampleType};
use photocraft_doc::{Layer, LayerContent, Size};
use photocraft_doc::{Artboard, Group, Layer, LayerContent, Size};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use photocraft_raster::{Interrupt, Surface};
fn solid(fmt: PixelFormat, x0: i32, y0: i32, x1: i32, y1: i32, px: &[f32]) -> Surface {
let mut s = Surface::new(fmt);
@@ -68,7 +69,7 @@ fn check_structure(pdf: &[u8]) {
#[test]
fn a_flat_rgb_document_saves_as_one_page_pdf() {
let d = doc(ColorMode::Rgb);
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
let pdf = &out.bytes;
check_structure(pdf);
assert!(has(pdf, "/MediaBox [0 0 4.00 2.00]"), "page = image size at 72 pt/in");
@@ -85,7 +86,7 @@ fn layers_composite_over_white_before_the_page() {
let mut d = doc(ColorMode::Rgb);
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
d.layers.push(Layer::new("Half red", LayerContent::Raster(solid(fmt, 1, 0, 3, 2, &[1.0, 0.0, 0.0, 0.5]))));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
let img = stream_after(&out.bytes, "/Subtype /Image");
// Pixels 1-2 of row 0: 0.5 red over white = (1.0, 0.5, 0.5); elsewhere plain white.
assert_eq!(&img[3..6], &[255, 128, 128], "the blend lands: {:?}", &img[3..6]);
@@ -102,7 +103,7 @@ fn topmost_solid_shape_is_exported_as_a_vector_path() {
..Default::default()
};
d.layers.push(Layer::new("Shape", LayerContent::Shape(shape)));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let content = stream_after(&out.bytes, "/Contents 4 0 R");
let content = String::from_utf8(content).unwrap();
@@ -128,7 +129,7 @@ fn topmost_text_layer_is_exported_with_selectable_text_and_vector_outlines() {
let baseline = layout.lines.get(cluster.line).expect("a line").baseline;
let origin = text.transform.apply(photocraft_geom::Point::new(f64::from(cluster.x), f64::from(baseline)));
d.layers.push(Layer::new("Text", LayerContent::Text(text)));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let content = stream_after(&out.bytes, "/Contents 4 0 R");
let content = String::from_utf8(content).unwrap();
@@ -159,7 +160,7 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() {
d.layers.push(Layer::new("Shape", LayerContent::Shape(shape)));
let text = TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() };
d.layers.push(Layer::new("Text", LayerContent::Text(text)));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let content = stream_after(&out.bytes, "/Contents 4 0 R");
let content = String::from_utf8(content).unwrap();
@@ -173,10 +174,10 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() {
#[test]
fn greyscale_and_cmyk_pages_keep_their_channels() {
let g = export(&doc(ColorMode::Grayscale)).unwrap();
let g = export(&doc(ColorMode::Grayscale), &Interrupt::NONE).unwrap();
assert!(has(&g.bytes, "/ColorSpace /DeviceGray"), "gray is DeviceGray");
assert_eq!(stream_after(&g.bytes, "/Subtype /Image"), vec![255; 4 * 2], "one sample per pixel");
let c = export(&doc(ColorMode::Cmyk)).unwrap();
let c = export(&doc(ColorMode::Cmyk), &Interrupt::NONE).unwrap();
assert!(has(&c.bytes, "/ColorSpace /DeviceCMYK"), "cmyk is DeviceCMYK");
assert_eq!(stream_after(&c.bytes, "/Subtype /Image"), vec![0; 4 * 2 * 4], "zero ink over the whole page");
}
@@ -188,7 +189,7 @@ fn the_page_measures_at_the_document_resolution() {
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 300, 150, &[1.0, 1.0, 1.0, 1.0])))];
d.resolution_dpi = 300.0;
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
assert!(has(&out.bytes, "/MediaBox [0 0 72.00 36.00]"), "300 px at 300 dpi is one inch");
}
@@ -196,7 +197,7 @@ fn the_page_measures_at_the_document_resolution() {
fn an_embedded_profile_travels_as_iccbased() {
let mut d = doc(ColorMode::Rgb);
d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8]));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
assert!(has(&out.bytes, "[/ICCBased 7 0 R]"), "the image refers to the profile");
assert_eq!(stream_after(&out.bytes, "/N 3 /Alternate"), vec![1, 2, 3, 4, 5, 6, 7, 8], "the profile bytes survive");
}
@@ -204,7 +205,7 @@ fn an_embedded_profile_travels_as_iccbased() {
#[test]
fn other_modes_are_refused_with_an_actionable_error() {
let d = doc(ColorMode::Lab);
let e = export(&d).unwrap_err().to_string();
let e = export(&d, &Interrupt::NONE).unwrap_err().to_string();
assert!(e.contains("RGB") && e.contains("Mode"), "{e}");
assert!(crate::export(&d, "x.pdf", &crate::ExportOptions::default()).is_err());
}
@@ -226,7 +227,7 @@ fn unicode_text_over_a_photo_extracts_through_a_pdf_reader() {
..Default::default()
}),
));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), text);
assert!(has(&pdf, "/Subtype /Image"));
@@ -266,7 +267,7 @@ fn text_with_compositing_or_a_profile_stays_in_the_raster_backdrop() {
_ => d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4])),
}
d.layers.push(layer);
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
assert!(!content.contains("/ActualText"), "case {case} must retain the raster composite");
assert!(stream_after(&pdf, "/Subtype /Image").iter().any(|v| *v != 255), "case {case} must retain visible text");
@@ -304,7 +305,7 @@ fn text_outside_the_vector_prefix_does_not_consume_the_selection_font() {
"Top text",
LayerContent::Text(TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() }),
));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), "Hi", "case {case}: only the top text is selectable");
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
@@ -355,7 +356,7 @@ fn a_text_layer_refused_at_emission_keeps_the_upper_vectors_and_stays_raster() {
..Default::default()
}),
));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
check_structure(&pdf);
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
assert!(content.contains("/ActualText <FEFF0048"), "the upper text stays vector:\n{content}");
@@ -377,7 +378,7 @@ fn multiline_text_keeps_its_paragraph_breaks_in_the_selection() {
use photocraft_doc::TextLayer;
let mut d = doc(ColorMode::Rgb);
d.layers.push(Layer::new("Text", LayerContent::Text(TextLayer { text: "A\nB".into(), size_pt: 12.0, ..Default::default() })));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), "A\nB", "the paragraph break survives selection");
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
@@ -389,7 +390,158 @@ fn leading_newline_stays_in_the_first_selection_span() {
use photocraft_doc::TextLayer;
let mut d = doc(ColorMode::Rgb);
d.layers.push(Layer::new("Text", LayerContent::Text(TextLayer { text: "\nA".into(), size_pt: 12.0, ..Default::default() })));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
assert!(content.contains("/ActualText <FEFF000A0041>"), "the first span retains the leading newline:\n{content}");
}
#[test]
/// Each artboard becomes one labelled page, in document order.
fn artboards_export_as_one_page_each() {
use photocraft_doc::{Artboard, Group};
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
let mut d = Document::new("pages.pdf", Size { width: 40, height: 30 }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 72.0;
for (rect, px) in [(Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]), (Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 1.0])] {
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, rect.y0, rect.x1, rect.y1, &px)));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new("Page", LayerContent::Group(group)));
}
let out = export(&d, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
let pages = parsed.get_pages();
assert_eq!(pages.len(), 2);
for id in pages.values() {
let page = parsed.get_dictionary(*id).unwrap();
let media = page.get(b"MediaBox").unwrap().as_array().unwrap();
let w = media[2].as_float().or_else(|_| media[2].as_i64().map(|v| v as f32)).unwrap();
let h = media[3].as_float().or_else(|_| media[3].as_i64().map(|v| v as f32)).unwrap();
assert!((w - 20.0).abs() < 0.01 && (h - 30.0).abs() < 0.01, "page {w}x{h}");
}
assert_eq!(out.bytes.windows(15).filter(|w| *w == b"/Subtype /Image").count(), 2);
}
/// Side-by-side 2x2 artboards at 72 dpi, named by `names` (empty names are kept).
fn artboard_doc(names: &[&str]) -> Document {
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
let width = (names.len() as u32).saturating_mul(2).max(2);
let mut d = Document::new("labels.pdf", Size { width, height: 2 }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 72.0;
for (index, name) in names.iter().enumerate() {
let x0 = (index as i32) * 2;
let rect = Rect::new(x0, 0, x0 + 2, 2);
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, rect.y0, rect.x1, rect.y1, &[0.5, 0.5, 0.5, 1.0])));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new(*name, LayerContent::Group(group)));
}
d
}
/// The decompressed samples of page `id`'s first image XObject (`/Im0`).
fn page_image(pdf: &lopdf::Document, id: lopdf::ObjectId) -> Vec<u8> {
let page = pdf.get_dictionary(id).expect("page dictionary");
let resources = page.get(b"Resources").expect("page resources").as_dict().expect("resources dictionary");
let xobjects = resources.get(b"XObject").expect("xobjects").as_dict().expect("xobject dictionary");
let image = xobjects.get(b"Im0").expect("Im0").as_reference().expect("image reference");
pdf.get_object(image).expect("image object").as_stream().expect("image stream").decompressed_content().expect("image samples")
}
/// A named artboard gives every page a `/PageLabels` entry, and an empty name gets an empty
/// label dictionary rather than inheriting the previous name.
#[test]
fn page_labels_name_every_page_and_an_empty_name_does_not_inherit() {
let d = artboard_doc(&["A", "", "C"]);
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
check_structure(&pdf);
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
let labels = parsed
.catalog()
.unwrap()
.get(b"PageLabels")
.expect("a named artboard gives the PDF page labels")
.as_reference()
.expect("the label tree is an indirect object");
let nums = parsed.get_dictionary(labels).unwrap().get(b"Nums").unwrap().as_array().unwrap();
assert_eq!(nums.len(), 6, "one key and one label dictionary per page");
for page in 0..3 {
assert_eq!(nums[page * 2].as_i64().unwrap(), page as i64, "the tree starts at page index 0 and covers every page");
}
let label = |page: usize| nums[page * 2 + 1].as_dict().unwrap();
assert_eq!(label(0).get(b"P").unwrap(), &Object::String(vec![0xFE, 0xFF, 0x00, 0x41], StringFormat::Hexadecimal), "page 1 is A");
assert!(label(1).get(b"P").is_err(), "the empty name gets an empty dictionary, not A");
assert_eq!(label(2).get(b"P").unwrap(), &Object::String(vec![0xFE, 0xFF, 0x00, 0x43], StringFormat::Hexadecimal), "page 3 is C");
assert_eq!(parsed.get_pages().len(), 3);
}
/// With no non-empty name there is no label tree at all: an empty `/Nums` would be invalid.
#[test]
fn an_all_empty_artboard_names_document_has_no_page_labels_tree() {
let d = artboard_doc(&["", "", ""]);
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
check_structure(&pdf);
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert!(parsed.catalog().unwrap().get(b"PageLabels").is_err(), "no names means no /PageLabels");
assert!(!has(&pdf, "/PageLabels"));
assert_eq!(parsed.get_pages().len(), 3, "the pages themselves are still written");
}
/// Two artboards at the same rectangle: each page must hold only its own board's pixels, not
/// the other board composited over it.
#[test]
fn overlapping_artboards_export_only_their_own_pixels() {
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
let mut d = Document::new("overlap.pdf", Size { width: 2, height: 2 }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 72.0;
for (name, color) in [("Red", [1.0, 0.0, 0.0, 1.0]), ("Blue", [0.0, 0.0, 1.0, 1.0])] {
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, 0, 0, 2, 2, &color)));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(Rect::new(0, 0, 2, 2))), frame_stroke: None };
d.layers.push(Layer::new(name, LayerContent::Group(group)));
}
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
let pages = parsed.get_pages();
let images = pages.values().map(|id| page_image(&parsed, *id)).collect::<Vec<_>>();
assert_eq!(images.len(), 2);
assert_eq!(images[0], [255u8, 0, 0].repeat(4), "the bottom board's page is red, not blue over red");
assert_eq!(images[1], [0u8, 0, 255].repeat(4), "the top board's page is blue");
}
/// A large, mostly empty canvas must not be charged as if its whole area were rendered.
#[test]
fn sparse_canvas_artboards_export_without_a_false_memory_limit() {
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
let mut d = Document::new("sparse.pdf", Size { width: 9000, height: 9000 }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 72.0;
for index in 0..2 {
let x0 = index * 10;
let rect = Rect::new(x0, 0, x0 + 2, 2);
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, 0, rect.x1, 2, &[1.0, 0.0, 0.0, 1.0])));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new("Page", LayerContent::Group(group)));
}
let out = export(&d, &Interrupt::NONE).expect("two 2x2 boards on a 9000x9000 canvas must fit the export budget");
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
assert_eq!(parsed.get_pages().len(), 2);
}
/// Seven US Letter boards at 300 dpi with the importer's gaps: the pages are retained as encoded
/// data, but no whole-canvas buffer exists, so the old whole-canvas charge rejected this.
#[test]
fn seven_us_letter_artboards_export_without_a_false_memory_limit() {
const PAGE_W: u32 = 2550;
const PAGE_H: u32 = 3300;
const GAP: u32 = 80;
const PAGES: u32 = 7;
let mut d = Document::new("letters.pdf", Size { width: PAGES * PAGE_W + (PAGES - 1) * GAP, height: PAGE_H }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 300.0;
for index in 0..PAGES {
let x0 = (index * (PAGE_W + GAP)) as i32;
let rect = Rect::new(x0, 0, x0 + PAGE_W as i32, PAGE_H as i32);
let group = Group { children: Vec::new(), expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new(format!("Letter {}", index + 1), LayerContent::Group(group)));
}
let out = export(&d, &Interrupt::NONE).expect("seven US Letter pages at 300 dpi fit the export budget");
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
assert_eq!(parsed.get_pages().len(), 7);
}
+374
View File
@@ -0,0 +1,374 @@
//! PDF import: craft-pdf (a Rust PDF reader and renderer built on Hayro) rasterizes the
//! selected pages, and each page becomes one artboard.
//!
//! Raster pages only: editable text and vector import would need craft-pdf's `interpret`
//! device and is not part of this importer. The renderer's hard output bounds (8192 px per
//! side and 64M px per page) and a document-wide strip budget are respected by lowering the
//! effective DPI, so each page keeps its physical size: pixels / resolution * 72 pt.
//!
//! The renderer is pure Rust and runs on every desktop platform: no shared library is loaded
//! or shipped, and a malformed file is reported as an error rather than taking the process down.
//!
//! Pages are drawn with the interpreter's default annotation settings, so annotations and
//! filled-in form fields are rendered; comments are not hidden.
use crate::{ImportOptions, ImportResult, IoError};
#[cfg(not(target_arch = "wasm32"))]
use craft_pdf::interpret::InterpreterSettings;
#[cfg(not(target_arch = "wasm32"))]
use craft_pdf::raster::{self, RenderCache};
#[cfg(not(target_arch = "wasm32"))]
use photocraft_color::{ColorMode, PixelFormat, SampleType};
#[cfg(not(target_arch = "wasm32"))]
use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent};
#[cfg(not(target_arch = "wasm32"))]
use photocraft_geom::{Rect, Size};
use photocraft_raster::Interrupt;
#[cfg(not(target_arch = "wasm32"))]
use photocraft_raster::Surface;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(not(target_arch = "wasm32"))]
use std::time::Duration;
/// `%PDF-` magic. `.ai` files that start with it are PDFs and render through this importer.
pub fn is_pdf(bytes: &[u8]) -> bool {
bytes.starts_with(b"%PDF-")
}
/// PDF import is not available in the web build.
#[cfg(target_arch = "wasm32")]
pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrupt) -> Result<ImportResult, IoError> {
Err(IoError::Unsupported("PDF import needs the desktop build".into()))
}
/// Renders the selected PDF pages and opens each as one artboard.
#[cfg(not(target_arch = "wasm32"))]
pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -> Result<ImportResult, IoError> {
/// The most pages one import renders.
const MAX_PAGES: usize = 16;
/// Gap between the artboards, in document pixels.
const GAP: u32 = 80;
/// The document-wide raster budget across every imported page, in pixels.
const MAX_UNION_PIXELS: u64 = 200_000_000;
/// The default pixel-memory budget when the caller sets none: a zero
/// [`ImportOptions::flat_max_pixel_bytes`] still bounds the import.
const DEFAULT_MAX_PIXEL_BYTES: u64 = 2 << 30;
ctl.check().map_err(|_| IoError::Cancelled)?;
let requested = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { f64::from(opts.pdf_dpi) } else { 300.0 };
let pdf = craft_pdf::open_slice_with_options(bytes, None, &craft_pdf::OpenOptions::default()).map_err(open_error)?;
let total = pdf.pages().len();
if total == 0 {
return Err(IoError::Unsupported("PDF has no pages".into()));
}
let (first, last) = match opts.pdf_pages {
Some((a, b)) => {
let a = a.max(1);
let b = if b == 0 { u32::MAX } else { b.max(a) };
if u64::from(a) > total as u64 {
return Err(IoError::Unsupported(format!("PDF page range starts at {a}, but the PDF has {total} pages")));
}
((a as usize).min(total), (b as usize).min(total))
}
None => (1, total),
};
let page_count = last - first + 1;
let count = page_count.min(MAX_PAGES);
// Page sizes in points first: the effective DPI must fit the renderer's bounds without
// changing any page's physical size.
let mut sizes = Vec::with_capacity(count);
for index in 0..count {
let page = &pdf.pages()[first - 1 + index];
let (width, height) = page.render_dimensions();
if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 {
return Err(IoError::Unsupported(format!("PDF page {} has no area", first + index)));
}
sizes.push((f64::from(width), f64::from(height)));
ctl.check().map_err(|_| IoError::Cancelled)?;
}
let dpi = effective_dpi(requested, &sizes, u64::from(raster::MAX_SIDE), raster::MAX_PIXELS, MAX_UNION_PIXELS);
let mut doc_width: u64 = 0;
let mut doc_height: u64 = 0;
let mut retained: u64 = 0;
for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() {
let width = page_pixels(width_pt, dpi);
let height = page_pixels(height_pt, dpi);
doc_width = doc_width.saturating_add(u64::from(width)).saturating_add(if index + 1 < count { u64::from(GAP) } else { 0 });
doc_height = doc_height.max(u64::from(height));
let tiles_x = (u64::from(width)).div_ceil(256);
let tiles_y = (u64::from(height)).div_ceil(256);
retained = retained.saturating_add(tiles_x.saturating_mul(tiles_y).saturating_mul(256 * 256 * 4));
}
if doc_width == 0 || doc_height == 0 {
return Err(IoError::Unsupported("PDF pages have no area".into()));
}
if doc_width > u64::from(u32::MAX) || doc_height > u64::from(u32::MAX) {
return Err(IoError::Unsupported("PDF import is too large at this DPI; lower the import DPI".into()));
}
// Retained tiles plus the converting page's raster (4 B/px); the f32 conversion runs in
// 256-row bands, so it adds only a constant-sized buffer rather than a second full page.
let max_page = sizes.iter().map(|&(w, h)| u64::from(page_pixels(w, dpi)) * u64::from(page_pixels(h, dpi))).max().unwrap_or(0);
let estimate = retained.saturating_add(max_page.saturating_mul(4));
let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES };
if estimate > budget {
return Err(IoError::Unsupported(format!(
"PDF import needs about {} MB of pixel memory; the limit is {} MB (lower the import DPI)",
estimate >> 20,
budget >> 20
)));
}
let mut warnings = Vec::new();
if first > 1 || last < total || count < page_count {
let shown_last = first + count - 1;
let reason = if count < page_count { " (the page limit is 16)" } else { "" };
warnings.push(format!("PDF has {total} pages; imported pages {first}-{shown_last}{reason}"));
}
if dpi + 0.5 < requested {
warnings.push(format!("PDF was rendered at {:.0} dpi to fit the import limits", dpi.max(1.0)));
}
let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8);
doc.resolution_dpi = dpi as f32;
let mut x: u32 = 0;
for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() {
ctl.check().map_err(|_| IoError::Cancelled)?;
let page_number = first + index;
let page = &pdf.pages()[page_number - 1];
let width = page_pixels(width_pt, dpi);
let height = page_pixels(height_pt, dpi);
// The DPI solve keeps these inside the renderer's bounds; re-check rather than panic if
// rounding on an edge moves one pixel past them.
if width > raster::MAX_SIDE || height > raster::MAX_SIDE || u64::from(width) * u64::from(height) > raster::MAX_PIXELS {
return Err(IoError::Unsupported(format!("PDF page {page_number} is too large at {dpi:.0} dpi; lower the import DPI")));
}
// A cache per page, deliberately: a shared one would keep decoded images and fonts alive
// across up to 16 pages outside the pixel budget, and would hide an image-decode warning
// on a later page after the page that first hit it.
let cache = RenderCache::new();
let options = raster::Options {
scale: [(dpi / 72.0) as f32; 2],
size: Some([width, height]),
offset: [0.0, 0.0],
// PDF pages composite onto white, as every PDF viewer and the previous importer did.
// craft-pdf returns premultiplied RGBA8; an opaque background makes alpha 1, so the
// bytes below can be written as straight alpha. A transparent background would need
// un-premultiplying (dividing each colour by alpha) first.
background: [255, 255, 255, 255],
color_replacement: None,
};
let rendered = render_page(page, &cache, &options, ctl).map_err(|error| render_error(page_number, dpi, error))?;
if rendered.diagnostics.image_decode_failed {
warnings.push(format!("PDF page {page_number}: an image could not be decoded and is missing"));
}
// craft-pdf's hayro backend does not emit this flag yet (its README says so); keep the
// warning ready so a backend that starts reporting font substitution needs no change here.
if rendered.diagnostics.unsupported_font {
warnings.push(format!("PDF page {page_number}: a font could not be used and was substituted, so text may look different"));
}
if rendered.diagnostics.content_truncated {
warnings.push(format!("PDF page {page_number}: some content was omitted (a decode or memory limit)"));
}
ctl.check().map_err(|_| IoError::Cancelled)?;
let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
let bytes = rendered.bytes();
// Convert and write in row bands: the f32 buffer stays bounded instead of a second
// 16-bytes-per-pixel copy of the whole page, and cancellation is polled per band.
const BAND_ROWS: usize = 256;
let row_bytes = width as usize * 4;
let band_bytes = row_bytes.saturating_mul(BAND_ROWS);
let mut data: Vec<f32> = Vec::new();
if data.try_reserve_exact(band_bytes).is_err() {
return Err(IoError::Unsupported(format!("PDF page {page_number} needs more memory than is available")));
}
for (band, rows) in bytes.chunks(band_bytes).enumerate() {
ctl.check().map_err(|_| IoError::Cancelled)?;
data.clear();
data.extend(rows.iter().map(|&value| f32::from(value) / 255.0));
let top = (band * BAND_ROWS) as i32;
let band_height = (rows.len() / row_bytes) as u32;
surface.write_region(Rect::from_xywh(x as i32, top, width, band_height), &data);
}
let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32);
let layer = Layer::new(format!("Page {page_number}"), LayerContent::Raster(surface));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
doc.layers.push(Layer::new(format!("Page {page_number}"), LayerContent::Group(group)));
x = x.saturating_add(width).saturating_add(GAP);
ctl.progress((index + 1) as f32 / count as f32);
}
Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false })
}
/// Renders one page, forwarding `ctl`'s cancellation to craft-pdf while it interprets content.
///
/// craft-pdf checks `InterpreterSettings::cancelled` between content operators, so a dense
/// vector page (CAD, maps) can be stopped part-way through. `Interrupt` is a borrowed callback
/// while the setting needs an owned flag, so a scoped watcher thread copies one into the other
/// every few milliseconds until the render returns.
#[cfg(not(target_arch = "wasm32"))]
fn render_page<'a>(
page: &'a craft_pdf::syntax::page::Page<'a>,
cache: &RenderCache<'a>,
options: &raster::Options,
ctl: &Interrupt,
) -> Result<raster::Raster, raster::Error> {
if ctl.cancelled() {
return Err(raster::Error::Cancelled);
}
let cancelled = Arc::new(AtomicBool::new(false));
let finished = Arc::new(AtomicBool::new(false));
let settings = InterpreterSettings { cancelled: Some(Arc::clone(&cancelled)), ..InterpreterSettings::default() };
std::thread::scope(|scope| {
let flag = Arc::clone(&cancelled);
let done = Arc::clone(&finished);
let ctl = *ctl;
scope.spawn(move || {
while !done.load(Ordering::Relaxed) {
if ctl.cancelled() {
flag.store(true, Ordering::Relaxed);
}
std::thread::sleep(Duration::from_millis(5));
}
});
let rendered = raster::render(page, cache, &settings, options);
finished.store(true, Ordering::Relaxed);
rendered
})
}
/// One page's raster width or height in pixels at `dpi`, at least one.
#[cfg(not(target_arch = "wasm32"))]
fn page_pixels(points: f64, dpi: f64) -> u32 {
(points * dpi / 72.0).round().max(1.0) as u32
}
/// The highest DPI not above `requested` that keeps every page inside the renderer's side and
/// pixel bounds and the whole strip inside `max_union_pixels`. Rendering at that DPI keeps each
/// page's physical size unchanged; unreachable bounds report 1 DPI and the render call then fails
/// with a clear message.
#[cfg(not(target_arch = "wasm32"))]
fn effective_dpi(requested: f64, sizes: &[(f64, f64)], max_side: u64, max_page_pixels: u64, max_union_pixels: u64) -> f64 {
let mut dpi = requested.clamp(1.0, 2400.0);
loop {
let mut union = 0u64;
let mut fits = true;
for &(width_pt, height_pt) in sizes {
let width = u64::from(page_pixels(width_pt, dpi));
let height = u64::from(page_pixels(height_pt, dpi));
if width > max_side || height > max_side || width.saturating_mul(height) > max_page_pixels {
fits = false;
break;
}
union = union.saturating_add(width.saturating_mul(height));
}
if fits && union <= max_union_pixels {
return dpi;
}
if dpi <= 1.0 {
return 1.0;
}
// The strip's gaps contribute a constant width, so a geometric step converges without
// needing a closed form per page.
dpi = (dpi * 0.9).max(1.0);
}
}
/// Maps a craft-pdf open failure to the importer's error.
#[cfg(not(target_arch = "wasm32"))]
fn open_error(error: craft_pdf::OpenError) -> IoError {
use craft_pdf::OpenError;
match error {
OpenError::InputLimit { limit } => IoError::Unsupported(format!("PDF is larger than the {limit}-byte input limit")),
OpenError::Allocation => IoError::Unsupported("PDF needs more memory than is available".into()),
OpenError::BackendPanic => IoError::Unsupported("PDF reader failed on this file; it may be damaged".into()),
OpenError::Load(error) => IoError::Unsupported(format!("PDF: {error:?}")),
}
}
/// Maps a craft-pdf render failure to the importer's error.
#[cfg(not(target_arch = "wasm32"))]
fn render_error(page: usize, dpi: f64, error: raster::Error) -> IoError {
use raster::Error;
match error {
Error::Cancelled => IoError::Cancelled,
Error::OutputLimit => IoError::Unsupported(format!("PDF page {page} is too large at {dpi:.0} dpi; lower the import DPI")),
Error::InvalidPage => IoError::Unsupported(format!("PDF page {page} has an empty or invalid page box")),
Error::Allocation => IoError::Unsupported(format!("PDF page {page} needs more memory than is available")),
Error::BackendPanic => IoError::Unsupported(format!("PDF renderer failed on page {page}; it may be damaged")),
Error::InvalidOptions | Error::BufferLength => IoError::Unsupported(format!("PDF page {page} could not be rendered")),
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use std::sync::atomic::AtomicUsize;
use lopdf::{Document as PdfDocument, Object, Stream, dictionary};
use super::*;
/// A one-page PDF whose content stream is `operators` short strokes: rendering costs time
/// per operator, not per pixel.
fn dense_operator_pdf(operators: usize) -> Result<Vec<u8>, lopdf::Error> {
let mut pdf = PdfDocument::with_version("1.5");
let pages_id = pdf.new_object_id();
let mut content = String::with_capacity(operators.saturating_mul(24));
content.push_str("0 0 1 RG 0.5 w\n");
for i in 0..operators {
let x = (i % 200) as f32 * 0.5;
let y = ((i / 200) % 100) as f32 * 0.5;
content.push_str(&format!("{x:.1} {y:.1} m {:.1} {y:.1} l S\n", x + 0.4));
}
let content_id = pdf.add_object(Stream::new(dictionary! {}, content.into_bytes()));
let page_id = pdf.add_object(dictionary! {
"Type" => "Page",
"Parent" => pages_id,
"MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(200.0), Object::Real(100.0)]),
"Contents" => content_id,
"Resources" => dictionary! {},
});
pdf.objects.insert(
pages_id,
Object::Dictionary(dictionary! {
"Type" => "Pages",
"Kids" => Object::Array(vec![Object::Reference(page_id)]),
"Count" => 1,
}),
);
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
pdf.trailer.set("Root", catalog);
let mut bytes = Vec::new();
pdf.save_to(&mut bytes)?;
Ok(bytes)
}
/// Hundreds of thousands of path operators take far longer than the watcher's polling
/// interval, so the interrupt lands mid-render and the page reports Cancelled. A million
/// strokes leaves a wide margin even on a fast, optimised test build.
#[test]
fn a_dense_page_stops_when_the_interrupt_fires_mid_render() {
let pdf = dense_operator_pdf(1_000_000).expect("writing the dense PDF");
let document = craft_pdf::open_slice_with_options(&pdf, None, &craft_pdf::OpenOptions::default()).expect("the dense PDF opens");
let cache = RenderCache::new();
let options =
raster::Options { scale: [1.0, 1.0], size: Some([200, 100]), offset: [0.0, 0.0], background: [255, 255, 255, 255], color_replacement: None };
let polls = AtomicUsize::new(0);
// `render_page` checks once before spawning; the watcher then polls every 5 ms. Ten
// polls put the cancellation about 45 ms into a render that takes much longer.
let cancel = || polls.fetch_add(1, Ordering::SeqCst) >= 9;
let ctl = Interrupt::cancel_only(&cancel);
let error = match render_page(&document.pages()[0], &cache, &options, &ctl) {
Err(error) => error,
Ok(_) => panic!("the dense page rendered to completion before the interrupt fired"),
};
assert!(matches!(render_error(1, 72.0, error), IoError::Cancelled), "the render error maps to Cancelled");
assert!(polls.load(Ordering::SeqCst) >= 10, "the watcher must keep polling the interrupt");
}
}
+1
View File
@@ -44,6 +44,7 @@ mod orientation;
mod pattern_fill_psd;
mod pcraft_full_composite;
mod pcraft_manifest_name;
mod pdf_import;
mod pdn_corpus;
mod png_steps;
mod png_text_metadata;
+196
View File
@@ -0,0 +1,196 @@
//! PDF import end-to-end through craft-pdf (pure Rust, no shared library).
//!
//! A six-page synthetic PDF (plain, CropBox offset, rotations 90/180/270 and an oversized
//! CropBox) imports at 72 and 300 DPI as one artboard per page, with the page's print size kept,
//! a blue rectangle sampled from the raster, and the renderer's side/pixel limits respected by
//! lowering the effective DPI on a huge page.
use std::sync::atomic::{AtomicBool, Ordering};
use lopdf::{Document as PdfDocument, Object, Stream, dictionary};
use photocraft_doc::LayerContent;
use photocraft_geom::Rect;
use photocraft_io::{ImportOptions, IoError, import_with_options_and_interrupt};
use photocraft_raster::Interrupt;
const PAGE_W: f64 = 200.0;
const PAGE_H: f64 = 100.0;
/// Six one-page variants: plain, CropBox offset to (10, 20, 210, 120), rotations of 90/180/270
/// degrees and an oversized CropBox (-50, -50, 250, 150) around the 200 x 100 MediaBox. Each page
/// draws a 40 x 40 blue rectangle at (20, 30) in PDF space.
fn variant_pdf() -> Vec<u8> {
let pages: [(Option<i64>, Option<[f32; 4]>); 6] = [
(None, None),
(None, Some([10.0, 20.0, 210.0, 120.0])),
(Some(90), None),
(Some(180), None),
(Some(270), None),
(None, Some([-50.0, -50.0, 250.0, 150.0])),
];
let mut pdf = PdfDocument::with_version("1.5");
let pages_id = pdf.new_object_id();
let mut kids = Vec::new();
for (rotate, crop) in pages {
let content = b"0 0 1 rg 20 30 40 40 re f";
let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec()));
let mut page = dictionary! {
"Type" => "Page",
"Parent" => pages_id,
"MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(PAGE_W as f32), Object::Real(PAGE_H as f32)]),
"Contents" => content_id,
"Resources" => dictionary! {},
};
if let Some(rotate) = rotate {
page.set("Rotate", rotate);
}
if let Some([left, bottom, right, top]) = crop {
page.set("CropBox", Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)]));
}
kids.push(Object::Reference(pdf.add_object(page)));
}
let count = kids.len() as i64;
pdf.objects.insert(
pages_id,
Object::Dictionary(dictionary! {
"Type" => "Pages",
"Kids" => Object::Array(kids),
"Count" => count,
}),
);
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
pdf.trailer.set("Root", catalog);
let mut bytes = Vec::new();
pdf.save_to(&mut bytes).expect("writing the variant PDF");
bytes
}
/// One page of `width` x `height` points with the same blue rectangle.
fn one_page_pdf(width: f32, height: f32) -> Vec<u8> {
let mut pdf = PdfDocument::with_version("1.5");
let pages_id = pdf.new_object_id();
let content_id = pdf.add_object(Stream::new(dictionary! {}, b"0 0 1 rg 20 30 40 40 re f".to_vec()));
let page_id = pdf.add_object(dictionary! {
"Type" => "Page",
"Parent" => pages_id,
"MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(width), Object::Real(height)]),
"Contents" => content_id,
"Resources" => dictionary! {},
});
pdf.objects.insert(
pages_id,
Object::Dictionary(dictionary! {
"Type" => "Pages",
"Kids" => Object::Array(vec![Object::Reference(page_id)]),
"Count" => 1,
}),
);
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
pdf.trailer.set("Root", catalog);
let mut bytes = Vec::new();
pdf.save_to(&mut bytes).expect("writing the page PDF");
bytes
}
/// The first artboard rectangle of `document`.
fn first_artboard(document: &photocraft_doc::Document) -> Rect {
let layer = document.layers.first().expect("an imported page group");
let group = match &layer.content {
LayerContent::Group(group) => group,
_ => panic!("{} is not a group", layer.name),
};
group.artboard.as_ref().expect("page artboard").rect
}
/// Each page becomes its own artboard at 72 and 300 DPI, with the print size preserved.
#[test]
fn imports_every_page_as_an_artboard_with_its_print_size() {
let pdf = variant_pdf();
for dpi in [72.0f32, 300.0] {
let options = ImportOptions { pdf_dpi: dpi, ..Default::default() };
let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &Interrupt::NONE).expect("PDF import");
assert_eq!(result.document.layers.len(), 6, "one artboard per page at {dpi} dpi");
let mut top_left = 0i32;
for (index, layer) in result.document.layers.iter().enumerate() {
let group = match &layer.content {
LayerContent::Group(group) => group,
_ => panic!("{} is not a page group", layer.name),
};
let artboard = group.artboard.as_ref().expect("page artboard").rect;
let expected = match index {
// CropBox [10, 20, 210, 120] intersected with the MediaBox is 190 x 80 points.
1 => (190.0, 80.0),
// Rotations 90 and 270 swap the axes.
2 | 4 => (100.0, 200.0),
_ => (200.0, 100.0),
};
let print_width = f64::from(artboard.width()) * 72.0 / f64::from(dpi);
let print_height = f64::from(artboard.height()) * 72.0 / f64::from(dpi);
assert!((print_width - expected.0).abs() < 1.0, "page {} width is {print_width:.1} pt, expected {} at {dpi} dpi", index + 1, expected.0);
assert!((print_height - expected.1).abs() < 1.0, "page {} height is {print_height:.1} pt, expected {} at {dpi} dpi", index + 1, expected.1);
assert_eq!(artboard.x0, top_left, "pages lay out side by side from x=0");
top_left = artboard.x1 + 80;
let surface = group.children.first().and_then(|layer| layer.surface()).expect("page raster layer");
if index == 0 {
// The rectangle's centre in PDF space is (40, 50); at the document's top-left
// origin that is y = PAGE_H - 50.
let scale = f64::from(dpi) / 72.0;
let x = artboard.x0 + (40.0 * scale).round() as i32;
let y = ((PAGE_H - 50.0) * scale).round() as i32;
let mut pixel = [[0u8; 4]; 1];
surface.read_rgba8_into(Rect::from_xywh(x, y, 1, 1), &mut pixel);
assert!(pixel[0][2] > 120 && pixel[0][0] < 120, "page 1 should be blue inside the rectangle, got {:?}", pixel[0]);
let mut background = [[0u8; 4]; 1];
surface.read_rgba8_into(Rect::from_xywh(artboard.x0 + 2, 2, 1, 1), &mut background);
assert!(background[0][0] > 240 && background[0][1] > 240 && background[0][2] > 240, "page background should be white, got {:?}", background[0]);
}
}
}
}
/// A page over the renderer's side limit lowers the effective DPI instead of failing.
#[test]
fn huge_pages_lower_the_effective_dpi_within_the_renderer_bounds() {
// 3000 pt at 300 dpi would be 12500 px wide, over craft-pdf's 8192 px side limit.
let pdf = one_page_pdf(3000.0, 100.0);
let options = ImportOptions { pdf_dpi: 300.0, ..Default::default() };
let result = import_with_options_and_interrupt("wide.pdf", &pdf, &options, &Interrupt::NONE).expect("PDF import");
assert!(result.warnings.iter().any(|warning| warning.contains("rendered at")), "warnings: {:?}", result.warnings);
let artboard = first_artboard(&result.document);
assert!(artboard.width() <= 8192, "width {} is over the renderer's side limit", artboard.width());
assert!(result.document.resolution_dpi < 300.0, "the effective DPI should be lowered");
let print_width = f64::from(artboard.width()) * 72.0 / f64::from(result.document.resolution_dpi);
assert!((print_width - 3000.0).abs() < 1.0, "print width {print_width:.1} pt should stay 3000 pt");
}
/// Cancelling at the public boundary or between pages returns Cancelled, never a document.
///
/// The renderer's watcher polls the interrupt while a page is being interpreted, so the number
/// of checks is not fixed any more; these triggers do not depend on counting them.
#[test]
fn cancelling_before_and_between_pages_is_reported() {
let pdf = variant_pdf();
let options = ImportOptions { pdf_dpi: 72.0, ..Default::default() };
// The boundary check before dispatch: already cancelled.
let always = || true;
let ctl = Interrupt::cancel_only(&always);
match import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl) {
Err(IoError::Cancelled) => {}
other => panic!("an already-cancelled import returned {:?}", other.map(|_| ())),
}
// The per-page loop's check: the first page's progress cancels the next iteration.
let cancelled = AtomicBool::new(false);
let cancel = || cancelled.load(Ordering::SeqCst);
let progress = |fraction: f32| {
if fraction > 0.0 {
cancelled.store(true, Ordering::SeqCst);
}
};
let ctl = Interrupt::new(&cancel, &progress);
match import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl) {
Err(IoError::Cancelled) => {}
other => panic!("cancelling after the first page returned {:?}", other.map(|_| ())),
}
}
+1 -1
View File
@@ -183,7 +183,7 @@ photocraft/
3. **`photocraft-psd` depends on no workspace crate.** The doc ⇄ PSD mapping lives in `io`. This keeps the PSD crate publishable and reusable by other projects. The same holds for every standalone crate, with one documented exception: `codecs` → `heif` (both standalone and publishable; `STANDALONE_EXCEPTIONS` in `xtask/src/layers.rs`).
4. **wasm gate:** every crate in L0–L5 (except feature-gated native backends) must build for `wasm32-unknown-unknown`. CI runs `cargo build -p photocraft-engine --target wasm32-unknown-unknown --no-default-features --features web`.
5. `gpu` is optional for `engine`. Engine features are `gpu` (default on) and `cpu-only`, and `cpu-only` builds are what the headless CLI and CI tests use.
6. **C dependencies** (optional LibRaw, pdfium) only behind features, only in `codecs`, `raw` or `io`, and never on by default for the web target.
6. **C dependencies** (optional LibRaw) only behind features, only in `codecs`, `raw` or `io`, and never on by default for the web target.
---
+2 -1
View File
@@ -40,7 +40,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity.
| Portable Bit Map (PBM/PGM/PPM/PNM/PFM/PAM) | R/W | yes | yes | 8/16/32f |
| FITS | R/W (FITS Liberator plug-in) | yes | yes | 8/16/32f gray or RGB, header cards kept; no fpack, no debayer |
| Targa | R/W | yes | yes | 8-bit |
| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541) |
| Photoshop PDF | R/W | yes, raster pages (craft-pdf; up to 16 pages, 8192 px per side, 64M px per page) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF) | Read renders each page as a raster artboard: no editable text/vector layers yet (craft-pdf `interpret` is the follow-up), no PDF forms or annotations; write is still one flattened page, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10) |
| Photoshop EPS, DCS 1.0/2.0, EPS TIFF/PICT preview | R/W | no | no | |
| Generic EPS / AI | R (rasterize) | no | no | |
| SVG | R (rasterize) | yes, as editable shape layers or a vector smart object | no | Better than Photoshop for editing; gradients approximated (FILE-215-9) |
@@ -152,6 +152,7 @@ The original reference entry retains its source date and historical totals; curr
| Date | Change | Summary |
|---|---|---|
| 2026-11-07 | minor | Photoshop PDF read: pages import as raster artboards through the shared craft-pdf (Hayro) renderer, up to 16 pages, 8192 px per side and 64M px per page; editable text/vectors and PDFium are gone. Write is unchanged. |
| 2026-11-06 | minor | Scripted PSD/PSB saves take `maximizeCompatibility` (Save, Save As, Save a Copy, `app.save`, serve `doc.save`, MCP `doc_save`/`doc_export`, Batch, Image Processor, Layers to Files) over Preferences › File Handling for one save, and the CLI `--no-maximize-compatibility` (#8064). Layer channels and the merged image were already RLE (ZIP with prediction at 32-bit), as Photoshop writes them (#8645) |
| 2026-10-24 | minor | Hasselblad 3FR/FFF: the X2D II 100C's 16-bit uncompressed CFA decodes; compressed 3FR still opens as the embedded preview |
| 2026-11-02 | minor | Actions Shear (`Shr `) loads, plays and saves the measured curve points and edge mode; unsafe subranges and unrepresentable forms remain kept steps (#10605). |
+2 -2
View File
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) |
| [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 |
| [Tools](#tools) | 36 | 9 | 0 | |
| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 196 (target 0) |
| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 199 (target 0) |
| [Type](#type) | 5 | 5 | 0 | |
| [Automation](#automation) | 5 | 4 | 2 | 662 of 662 menu items live (100.0%) |
| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present |
@@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu
## Workspace and UI
**Settings that do nothing: 10 of 196** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
**Settings that do nothing: 10 of 199** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`.