Integrate shared unsaved question and preserve Revert confirmation

This commit is contained in:
FredApps
2026-12-04 18:46:09 +01:00
183 changed files with 11592 additions and 833 deletions
Generated
+87 -87
View File
@@ -1365,7 +1365,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-atomic",
"craft-automation",
@@ -1405,7 +1405,7 @@ dependencies = [
[[package]]
name = "craft-atomic"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"rustix 1.1.6",
]
@@ -1413,7 +1413,7 @@ dependencies = [
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1438,7 +1438,7 @@ dependencies = [
[[package]]
name = "craft-behavior"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"accesskit",
"bitflags 2.13.2",
@@ -1456,7 +1456,7 @@ dependencies = [
[[package]]
name = "craft-browse"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1474,12 +1474,12 @@ dependencies = [
[[package]]
name = "craft-cfb"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"egui",
]
@@ -1487,7 +1487,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"md-5 0.10.6",
"rayon",
@@ -1496,12 +1496,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-cms",
@@ -1521,7 +1521,7 @@ dependencies = [
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"getrandom 0.3.4",
"serde",
@@ -1531,7 +1531,7 @@ dependencies = [
[[package]]
name = "craft-csv"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"thiserror 2.0.21",
]
@@ -1539,7 +1539,7 @@ dependencies = [
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"rayon",
]
@@ -1547,7 +1547,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"block2 0.6.2",
"craft-atomic",
@@ -1572,7 +1572,7 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"serde",
]
@@ -1580,7 +1580,7 @@ dependencies = [
[[package]]
name = "craft-docx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"base64 0.23.1",
"chrono",
@@ -1600,7 +1600,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1619,7 +1619,7 @@ dependencies = [
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"chrono",
"craft-xml",
@@ -1631,7 +1631,7 @@ dependencies = [
[[package]]
name = "craft-flow"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-wordmodel",
"image",
@@ -1641,7 +1641,7 @@ dependencies = [
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1656,7 +1656,7 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -1675,7 +1675,7 @@ dependencies = [
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1696,12 +1696,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1714,7 +1714,7 @@ dependencies = [
[[package]]
name = "craft-html"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-mime",
]
@@ -1722,7 +1722,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"chrono",
"fixed_decimal",
@@ -1750,7 +1750,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1777,7 +1777,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1795,7 +1795,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"thiserror 2.0.21",
]
@@ -1803,7 +1803,7 @@ dependencies = [
[[package]]
name = "craft-jsonrpc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"serde_json",
]
@@ -1811,7 +1811,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1826,7 +1826,7 @@ dependencies = [
[[package]]
name = "craft-markdown"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-flow",
"craft-html",
@@ -1836,7 +1836,7 @@ dependencies = [
[[package]]
name = "craft-math"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-xml",
"roxmltree 0.21.2",
@@ -1846,7 +1846,7 @@ dependencies = [
[[package]]
name = "craft-mcp-server"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"serde_json",
]
@@ -1854,7 +1854,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1872,7 +1872,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
@@ -1884,7 +1884,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"encoding_rs",
"image",
@@ -1895,7 +1895,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"chardetng",
"chrono",
@@ -1915,7 +1915,7 @@ dependencies = [
[[package]]
name = "craft-offcrypto"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"aes",
"base64 0.23.1",
@@ -1932,7 +1932,7 @@ dependencies = [
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1943,7 +1943,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1959,7 +1959,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"aes",
"bytemuck",
@@ -1982,7 +1982,7 @@ dependencies = [
[[package]]
name = "craft-pkcs7"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"aes",
"aws-lc-rs",
@@ -2014,7 +2014,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"arboard",
"async-channel",
@@ -2049,7 +2049,7 @@ dependencies = [
[[package]]
name = "craft-pptx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-drawingml",
"craft-opc",
@@ -2064,7 +2064,7 @@ dependencies = [
[[package]]
name = "craft-prc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2073,7 +2073,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2097,7 +2097,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"dispatch2",
"egui",
@@ -2110,7 +2110,7 @@ dependencies = [
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -2129,7 +2129,7 @@ dependencies = [
[[package]]
name = "craft-rtf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-codepage",
"craft-flow",
@@ -2142,7 +2142,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-atomic",
"craft-host",
@@ -2159,7 +2159,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"fax",
"hayro-ccitt",
@@ -2170,7 +2170,7 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-xml",
"flate2",
@@ -2187,7 +2187,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2199,7 +2199,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-font-manager",
@@ -2224,7 +2224,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -2239,7 +2239,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2254,7 +2254,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2264,7 +2264,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2273,7 +2273,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2288,12 +2288,12 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -2307,7 +2307,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -2323,7 +2323,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2361,7 +2361,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2372,7 +2372,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2390,7 +2390,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2411,7 +2411,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2432,7 +2432,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2451,7 +2451,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"chrono",
"craft-host",
@@ -2480,7 +2480,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"js-sys",
"serde_json",
@@ -2491,7 +2491,7 @@ dependencies = [
[[package]]
name = "craft-web-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-host",
"craft-platform",
@@ -2503,7 +2503,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"winsafe",
]
@@ -2511,7 +2511,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2541,7 +2541,7 @@ dependencies = [
[[package]]
name = "craft-wordmodel"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"base64 0.23.1",
"craft-math",
@@ -2555,7 +2555,7 @@ dependencies = [
[[package]]
name = "craft-xfa"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-xml",
]
@@ -2563,7 +2563,7 @@ dependencies = [
[[package]]
name = "craft-xfdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"craft-xml",
"thiserror 2.0.21",
@@ -2572,7 +2572,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2582,7 +2582,7 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -4151,7 +4151,7 @@ dependencies = [
[[package]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"bytemuck",
"hayro-interpret",
@@ -4171,7 +4171,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"brotli",
"hayro-postscript",
@@ -4180,7 +4180,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -4198,7 +4198,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -4216,12 +4216,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -5090,7 +5090,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -11132,4 +11132,4 @@ source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d9
[[patch.unused]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8"
source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e"
+39 -39
View File
@@ -13,55 +13,55 @@ repository = "https://github.com/storytold/pdfcraft"
[workspace.dependencies]
# The framework facade: every framework crate is reached through it (contract head); its features pick the crates.
craft = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", default-features = false }
craft-markdown = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e", default-features = false }
craft-markdown = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# Small, revision-bound UI drafts; the existing engine remains the owner of PDF edits/history.
edit-session = { path = "vendor/edit-session", version = "=0.1.0-alpha.2" }
# Shared frontend components; engines remain independent of egui.
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# Quit the macOS way (#1136): ⌘Q asks about unsaved changes, and closing quits through `terminate:`.
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# One menu definition for the native macOS menu bar and the in-window bar elsewhere.
craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", default-features = false }
craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e", default-features = false }
# Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at
# the commit in `craft-i18n.rev`). Already in the tree through craft-ui.
craft-i18n = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-i18n = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# Shared system spooler; document composition remains in pdfcraft-print.
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# ICC transforms for app-managed print colour; at craft-print's commit, so one craft-libs checkout.
craft-cms = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-zip = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-cms = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-zip = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# Whether a path stored in a document may be opened (GoToR link targets).
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# The installed-font catalog the engine reads faces from (Edit ▸ Add text, font embedding).
craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", default-features = false }
craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e", default-features = false }
# The craft-fonts manifest parser and `EmbeddedFace`, the face table the interface font stack takes; already in the
# tree through craft-ui.
craft-fonts-build = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-fonts-build = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", features = ["ui"] }
craft-pdf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", features = ["cos", "crypt", "filters", "fonts"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e", features = ["ui"] }
craft-pdf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e", features = ["cos", "crypt", "filters", "fonts"] }
# The writers the Word and RTF exports map onto (storytold/craft-libs#793), at storytold/craft-libs#1467:
# its font and colour lookups take constant time, as PdfCraft's own writer did. craft-rtf, craft-wordmodel and
# craft-docx move together: craft_rtf::doc::export takes its own revision's Document.
craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# Shared Base64 encoder; use the existing RTF revision to reuse its codepage dependency.
craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-csv = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-csv = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# Shared MCP stdio framing and JSON-RPC 2.0 envelopes (storytold/craft-libs#778).
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
# internal
@@ -98,8 +98,8 @@ pdfcraft-engine = { path = "crates/engine", version = "0.23.1" }
pdfcraft-platform = { path = "crates/platform", version = "0.23.1" }
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.23.1" }
pdfcraft-automation = { path = "crates/automation", version = "0.23.1", default-features = false }
pdfcraft-prc = { package = "craft-prc", git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-prc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
pdfcraft-prc = { package = "craft-prc", git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-prc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
pdfcraft-prc-render = { path = "crates/prc-render", version = "0.23.1" }
# pdf
@@ -182,14 +182,14 @@ unset_env = ["CRAFT_FONTS_DIR", "CRAFT_FONTS_REQUIRED", "CRAFT_I18N_DIR", "CRAFT
# BEGIN port-kit framework patch
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
+2
View File
@@ -547,6 +547,8 @@ Every other Linux build needs glibc 2.35 or newer (Ubuntu 22.04+, Debian 12+, Fe
### FreeBSD
Current prebuilt FreeBSD release packages require FreeBSD 15.1 or later. They are built using the shared FreeBSD 15.1-STABLE release target; older FreeBSD releases are not supported by these binaries.
| Build | File |
|---|---|
| x86_64 | `pdfcraft-<ver>-freebsd-x86_64.tar.gz` |
+1
View File
@@ -362,6 +362,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-26 (M3, view.text-select):** Text selection runs across pages: dragging onto another page (also a quick flick off the page, and the edge and wheel scrolling of #721/#1670) or ⇧-clicking there selects the rest of the first page, the pages between and the last page up to the pointer. Copy has each page's part on a line of its own, reading pages not yet read off the UI thread; highlight, underline, strikethrough and Redact put one mark on each page in one undo step (a tool that finishes first marks once the pages are read; Redact refuses a selection over a page whose text could not be read); Add comment and Replace text stay one-page. A drag from one page's text that is already over the next when it starts no longer begins a Redact or area-highlight box there. Estimates unchanged.
- **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged.
- **2026-10-25 (M7, #2750):** Single-style Keep source fonts edits retain source glyphs and batch only missing glyphs in fallback fonts. Per-rewrite character eligibility and widths are cached; source and fallback edge spaces stay extractable. Estimates unchanged.
- **2026-10-25 (M2, #2670):** Malformed-object diagnostics share a bounded per-load budget across compressed objects and encrypted containers, with a strict-mode summary and silent metadata reads. Estimates unchanged.
- **2026-10-25 (M4, #2725):** Dismissing the ordinary form-field reminder persists across launches, while security, repair and XFA notices keep their independent controls and defaults. Estimates unchanged.
- **2026-10-25 (M10, #4399):** The printer picker has a wider searchable list, wrapped device names, stable selection while filtering, and Search and Save as PDF kept visible. Synthetic fleet UI regressions cover long lists and a smaller window. Estimates unchanged.
- **2026-10-25 (web, same-document host mode):** A page that loads the PdfCraft web module into its own document (no iframe) can opt into the host bridge with `data-host="page"` on the app's canvas — the exact value `page`; any other value keeps the normal app with downloads, unless a same-origin framed `?host=parent` selects the parent bridge (unframed or cross-origin, `?host=parent` also keeps the normal app). It is the `?host=parent` bridge with the transport swapped: the same five messages travel as non-bubbling `CustomEvent`s on the canvas (`detail` holds the parent messages' fields without `type`; the host answers with a `pdfcraft:open` event), so saves reach the host instead of downloading and dirty and start-up-failure reporting are unchanged. Unit tests cover the opt-in rule; no parity or estimate changes.
+2 -2
View File
@@ -15,8 +15,8 @@ pdfcraft-ui-egui = { workspace = true }
craft = { workspace = true, features = ["automation", "platform-browser", "ui", "window"] }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.pdfcraft over the UI control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e", version = "0.1.0" }
eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
serde_json = { workspace = true }
+24 -2
View File
@@ -43,8 +43,17 @@ fn main() {
.i18n(pdfcraft_ui_egui::i18n::host_catalogs())
.build();
let mut app = PdfCraftApp::with_host(Arc::new(app_host), AppServices::system(&cc.egui_ctx, intake));
app.session = std::mem::take(&mut app.session).with_wall_clock(
|| (js_sys::Date::now() / 1000.0).floor() as i64,
// JavaScript reports minutes west of UTC; the session uses seconds east.
|| (-js_sys::Date::new_0().get_timezone_offset() * 60.0) as i64,
);
app.apply_settings(&settings.get());
app.attach_settings(settings);
// `?embedded`: hide external community links when framed without `allow-popups` (#2490).
if query_flag("embedded") {
app.embedded = true;
}
// `?file=<url>` opens a PDF from a URL (same-origin or CORS-enabled).
if let Some(url) = query_param("file") {
let opens = opens.clone();
@@ -78,6 +87,7 @@ fn main() {
app.comment_prefs.author = author.chars().take(200).collect();
}
bridge.listen(opens.clone());
app.host_save = Some(bridge.save_fn());
app.host_dirty = Some(bridge.dirty_fn());
bridge.post_ready();
} else if query_param("host").as_deref() == Some("parent") {
@@ -133,6 +143,13 @@ fn query_param(key: &str) -> Option<String> {
web_sys::UrlSearchParams::new_with_str(&search).ok()?.get(key)
}
#[cfg(target_arch = "wasm32")]
fn query_flag(key: &str) -> bool {
let Some(search) = web_sys::window().and_then(|w| w.location().search().ok()) else { return false };
let Ok(params) = web_sys::UrlSearchParams::new_with_str(&search) else { return false };
params.has(key) && params.get(key).as_deref() != Some("0") && params.get(key).as_deref() != Some("false")
}
#[cfg(target_arch = "wasm32")]
async fn fetch_bytes(url: &str) -> Result<Vec<u8>, String> {
use eframe::wasm_bindgen::JsCast;
@@ -167,8 +184,8 @@ fn app_canvas() -> Option<web_sys::HtmlCanvasElement> {
/// says `file: false` and a host sends `bytes`.
/// - `pdfcraft:open` (from the host): `{ name, bytes }` holding a PDF. It opens in a tab, like a
/// `?file=` URL; a file over [`host::MAX_OPEN_BYTES`] is refused before it is copied.
/// - `pdfcraft:save` (to the host): `{ name, saveAs, bytes }` when the user saves, posted by the
/// browser file service. The host stores the file (and reports its own errors).
/// - `pdfcraft:save` (to the host): `{ name, saveAs, bytes }` when the user saves through the
/// connected bridge. The host stores the file and reports its own errors.
/// - `pdfcraft:dirty` whenever unsaved work appears or goes away, `pdfcraft:failed` when the app
/// couldn't start.
#[cfg(target_arch = "wasm32")]
@@ -220,6 +237,11 @@ mod host {
});
}
pub fn save_fn(&self) -> pdfcraft_ui_egui::HostSaveFn {
let host = self.host.clone();
Box::new(move |name, bytes, save_as| host.post_save(name, bytes, None, save_as))
}
pub fn dirty_fn(&self) -> pdfcraft_ui_egui::HostDirtyFn {
let host = self.host.clone();
// A host starts out clean: the first report is a change only when it is dirty.
+64
View File
@@ -0,0 +1,64 @@
//! Supply the real Windows desktop coordinates and work areas for menus and modal dialogs.
use craft::behavior::{Monitor, MonitorKey};
use craft::window::system::{SystemWindows, WindowSystem};
use std::sync::{Arc, Mutex, Weak};
use std::time::{Duration, Instant};
use winit::window::Window;
use winsafe::{HMONITOR, POINT, co};
pub(super) struct DesktopWindows {
window: Weak<Window>,
monitors: Mutex<Option<(Instant, Vec<Monitor>)>>,
}
impl DesktopWindows {
pub(super) fn new(window: Option<&Arc<Window>>) -> Self {
Self { window: window.map(Arc::downgrade).unwrap_or_default(), monitors: Mutex::default() }
}
}
impl WindowSystem for DesktopWindows {
fn desktop_pointer(&self) -> Option<[f32; 2]> {
SystemWindows.desktop_pointer()
}
fn primary_held(&self) -> Option<bool> {
SystemWindows.primary_held()
}
fn command_held(&self) -> Option<bool> {
SystemWindows.command_held()
}
fn warp_pointer(&self, point: [f32; 2]) -> bool {
SystemWindows.warp_pointer(point)
}
fn monitors(&self) -> Vec<Monitor> {
let mut cached = self.monitors.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some((when, displays)) = cached.as_ref()
&& when.elapsed() < Duration::from_secs(1)
{
return displays.clone();
}
let Some(window) = self.window.upgrade() else { return Vec::new() };
let displays: Vec<_> = window
.available_monitors()
.map(|handle| {
let size = handle.size();
let size = [size.width, size.height];
let pos = handle.position();
let monitor =
Monitor::new(MonitorKey::new(handle.name().unwrap_or_default(), size), [pos.x, pos.y], size, handle.scale_factor() as f32);
let point = POINT { x: pos.x, y: pos.y };
let Ok(info) = HMONITOR::MonitorFromPoint(point, co::MONITOR::DEFAULTTONULL).GetMonitorInfo() else { return monitor };
let work = info.rcWork;
let (Ok(w), Ok(h)) = (u32::try_from(work.right - work.left), u32::try_from(work.bottom - work.top)) else { return monitor };
monitor.with_work_px([work.left, work.top], [w, h])
})
.collect();
*cached = Some((Instant::now(), displays.clone()));
displays
}
}
+20
View File
@@ -156,11 +156,28 @@ mod tests {
}
}
// A successful prepare permanently installs the nightly profile for this process. Keep it
// out of the test process that also exercises the stable title, icon and launch identity.
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
fn run_socket_test_in_child(name: &str) -> bool {
const CHILD: &str = "PDFCRAFT_TEST_NIGHTLY_SOCKET";
if std::env::var(CHILD).as_deref() == Ok(name) {
return false;
}
let status =
std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", name, "--nocapture"]).env(CHILD, name).status().unwrap();
assert!(status.success(), "isolated nightly profile test exited with {status}");
true
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn linux_nightly_profile_accepts_existing_single_instance_socket() {
use std::os::unix::net::UnixListener;
if run_socket_test_in_child("launch_profile::tests::linux_nightly_profile_accepts_existing_single_instance_socket") {
return;
}
let tmp = TempProfileDir::new("si");
let profile = tmp.0.join("p");
let single_instance = profile.join("single-instance");
@@ -186,6 +203,9 @@ mod tests {
#[cfg(windows)]
#[test]
fn windows_nightly_profile_accepts_existing_single_instance_socket() {
if run_socket_test_in_child("launch_profile::tests::windows_nightly_profile_accepts_existing_single_instance_socket") {
return;
}
let tmp = TempProfileDir::new("si");
let profile = tmp.0.join("p");
let single_instance = profile.join("single-instance");
+24 -6
View File
@@ -44,6 +44,8 @@ mod apple_events;
mod build_channel;
mod build_flavor;
mod compositor_gpu;
#[cfg(target_os = "windows")]
mod desktop_monitors;
mod launch_profile;
mod nightly_session;
mod process_identity;
@@ -52,6 +54,8 @@ mod reopen;
mod single_instance;
mod startup;
#[cfg(target_os = "windows")]
mod window_frame;
#[cfg(target_os = "windows")]
mod window_placement;
#[cfg(test)]
#[path = "windows_manifest.rs"]
@@ -579,13 +583,13 @@ fn install_runtime(
) -> Result<(), String> {
use craft::host::target::{Backend, ShellInfo};
use craft::ui::InstallSpec;
use craft::window::system::SystemWindows;
let ctx = cc.egui_ctx.clone();
let system = craft::ui::runtime::env::SystemReader::start(move || ctx.request_repaint());
let spec = InstallSpec::new(ShellInfo::default().backend(Backend::from_env()), std::sync::Arc::new(SystemWindows))
.system(system)
.app_id(app_id())
.frame(frame);
#[cfg(target_os = "windows")]
let windows = std::sync::Arc::new(desktop_monitors::DesktopWindows::new(cc.winit_window()));
#[cfg(not(target_os = "windows"))]
let windows = std::sync::Arc::new(craft::window::system::SystemWindows);
let spec = InstallSpec::new(ShellInfo::default().backend(Backend::from_env()), windows).system(system).app_id(app_id()).frame(frame);
craft::ui::shell::embed::install(&cc.egui_ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(lang))
.map(drop)
.map_err(|error| format!("the runtime could not be installed: {error}"))
@@ -640,6 +644,9 @@ fn app_creator<'a>(
#[cfg(target_os = "macos")] apple_events: &'a apple_events::AppleEvents,
) -> eframe::AppCreator<'a> {
let Launch { startup_time, files, options, control, create_images, combine, frame, lang, two_paged, nightly_watch } = launch;
// Whether the app's own bar is the title bar, so the window is undecorated.
#[cfg(target_os = "windows")]
let integrated = !matches!(frame.frame, craft::window::policy::Frame::Native);
Box::new(move |cc| {
started.set(true);
startup_stage(startup_time, "renderer ready, installing fonts and runtime");
@@ -681,7 +688,18 @@ fn app_creator<'a>(
app.attach_settings(settings);
#[cfg(target_os = "windows")]
if let Some(window) = cc.winit_window() {
window_placement::restore(window);
window_placement::restore(window, cc.storage, cc.egui_ctx.zoom_factor());
let root = std::sync::Arc::downgrade(window);
app.save_window_placement = Some(Box::new(move |storage| {
if let Some(window) = root.upgrade() {
window_placement::save(&window, storage);
}
}));
// The undecorated window must stay borderless, or the caption and border the toolkit gives it
// offset the drawn content from the pointer on some systems (#8845, #8793).
if integrated {
app.window_frame = window_frame::guard(window);
}
set_taskbar_icon(window);
}
app.set_startup_update_check(!is_nightly());
+86
View File
@@ -0,0 +1,86 @@
//! Keeps the custom (integrated) title bar's undecorated window truly borderless on Windows
//! (#8845, #8793, #9040).
//!
//! winit 0.30 gives an undecorated window the `WS_CAPTION | WS_BORDER` styles and hides the
//! non-client area by spreading the client rect over it (`WM_NCCALCSIZE`). On some systems the
//! desktop compositor still reserves that frame for the window surface: the content is drawn
//! offset by the caption and border, leaving a black bar at the top, while the pointer keeps the
//! un-offset client coordinates, so a click lands above the control that is drawn under it.
//!
//! PhotoCraft (storytold/photocraft#2401, #2246), VectorCraft, FigCraft and DesignCraft fixed the
//! same symptom the same way: strip `WS_CAPTION`/`WS_BORDER` and have Windows recalculate the
//! frame. winit puts the styles back whenever it changes the window flags (maximize, restore,
//! ...), so the guard runs every frame; once they are gone it only reads the style.
//!
//! The Windows calls go through safe `winsafe` wrappers; the workspace forbids `unsafe`, and
//! winsafe cannot wrap a raw handle without it, so the window is found among the UI thread's
//! windows by its handle, as `window_placement` does.
use std::sync::Weak;
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
use winsafe::{HWND, HwndPlace, POINT, SIZE, co};
/// A guard that keeps `window` borderless; call it once per frame on the UI thread. `None` when
/// the window's handle is not a Win32 one.
pub(super) fn guard(window: &std::sync::Arc<winit::window::Window>) -> Option<Box<dyn FnMut()>> {
let RawWindowHandle::Win32(raw) = window.window_handle().ok()?.as_raw() else { return None };
let target = raw.hwnd.get();
let root: Weak<winit::window::Window> = std::sync::Arc::downgrade(window);
let guard = move || {
// The window is gone once the app is closing.
if root.upgrade().is_none() {
return;
}
let _ = winsafe::EnumThreadWindows(winsafe::GetCurrentThreadId(), |hwnd| {
if hwnd.ptr() as isize == target {
strip(&hwnd);
}
true
});
};
guard();
Some(Box::new(guard))
}
/// Removes `WS_CAPTION`/`WS_BORDER` and has Windows recalculate the frame. A no-op once they are
/// gone, so it is cheap to call every frame.
fn strip(hwnd: &HWND) {
let style = hwnd.style();
let without = borderless(style);
if without.raw() == style.raw() {
return;
}
hwnd.set_style(without);
let _ = hwnd.SetWindowPos(
HwndPlace::None,
POINT::new(),
SIZE::new(),
co::SWP::FRAMECHANGED | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE,
);
}
/// `style` without the OS title bar and frame (`WS_CAPTION`, which already includes `WS_BORDER`).
/// The sizing border (`WS_THICKFRAME`) stays, so edge resizing and Aero snap keep working.
fn borderless(style: co::WS) -> co::WS {
style & !(co::WS::CAPTION | co::WS::BORDER)
}
#[cfg(test)]
mod tests {
use super::borderless;
use winsafe::co;
#[test]
fn the_borderless_style_drops_the_caption_and_border_only() {
// `WS_CAPTION` is 0x00c0_0000 and already contains `WS_BORDER` (0x0080_0000).
let decorated = co::WS::CAPTION | co::WS::BORDER | co::WS::SYSMENU | co::WS::THICKFRAME | co::WS::MAXIMIZEBOX | co::WS::MINIMIZEBOX;
let bare = borderless(decorated);
assert!(!bare.has(co::WS::CAPTION), "caption gone");
assert!(!bare.has(co::WS::BORDER), "border gone");
assert!(bare.has(co::WS::THICKFRAME), "edge resizing kept");
assert!(bare.has(co::WS::MAXIMIZEBOX) && bare.has(co::WS::SYSMENU), "window buttons kept");
// Already borderless: unchanged, so the per-frame call does nothing.
assert_eq!(bare.raw(), borderless(bare).raw());
}
}
+70 -3
View File
@@ -3,20 +3,79 @@
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
use winsafe::{HMONITOR, HWND, POINT, RECT, WINDOWPLACEMENT, co};
pub(super) fn restore(window: &winit::window::Window) {
// Win32 keeps the normal outer rectangle in workspace coordinates even while the HWND is iconic.
// Store it without translating it through the minimized window's client size, location or DPI.
const RESTORE_KEY: &str = "pdfcraft.win32.minimized_restore";
type NormalPlacement = ([i32; 4], bool);
pub(super) fn save(window: &winit::window::Window, storage: &mut dyn eframe::Storage) {
with_hwnd(window, |hwnd| {
if hwnd.IsIconic() {
// eframe just wrote the iconic window into this slot. A normal first-run window is
// preferable even if Windows cannot supply its placement during shutdown.
storage.remove_string("window");
let mut p = WINDOWPLACEMENT::default();
hwnd.GetWindowPlacement(&mut p)?;
let r = p.rcNormalPosition;
if r.right > r.left && r.bottom > r.top {
let normal: NormalPlacement = ([r.left, r.top, r.right, r.bottom], p.flags.has(co::WPF::RESTORETOMAXIMIZED));
eframe::set_value(storage, RESTORE_KEY, &normal);
}
} else {
// eframe's ordinary placement supersedes any previous minimized save.
storage.remove_string(RESTORE_KEY);
}
Ok(())
});
}
pub(super) fn restore(window: &winit::window::Window, storage: Option<&dyn eframe::Storage>, zoom: f32) {
// Presentation belongs to the document session. An OS fullscreen flag restored
// by eframe while PdfCraft is showing Home otherwise leaves Home without captions.
if window.fullscreen().is_some() {
window.set_fullscreen(None);
}
let previous = storage.and_then(|s| eframe::get_value::<NormalPlacement>(s, RESTORE_KEY));
with_hwnd(window, |hwnd| {
if let Some(([left, top, right, bottom], maximized)) = previous
&& right > left
&& bottom > top
{
let mut p = WINDOWPLACEMENT::default();
hwnd.GetWindowPlacement(&mut p)?;
p.rcNormalPosition = RECT { left, top, right, bottom };
p.showCmd = if maximized { co::SW::SHOWMAXIMIZED } else { co::SW::SHOWNORMAL };
hwnd.SetWindowPlacement(&p)?;
} else if storage.is_some_and(|s| s.get_string("window").is_some()) && !hwnd.IsIconic() {
// Releases before this guard can reopen at egui's 64-point floor. At 100% Windows
// also imposes a 160px minimum width, so testing for 64 in both axes misses it.
let scale = window.scale_factor() * f64::from(zoom);
let inner = window.inner_size().to_logical::<f64>(scale);
if is_minimized_floor(inner.width, inner.height) {
let monitor = hwnd.MonitorFromWindow(co::MONITOR::DEFAULTTONEAREST).GetMonitorInfo()?;
let work = monitor.rcWork;
let width = (1440.0 * scale).min(0.9 * f64::from(work.right - work.left)).round() as u32;
let height = (920.0 * scale).min(0.9 * f64::from(work.bottom - work.top)).round() as u32;
let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(width, height));
}
}
fit_restore_bounds(hwnd)
});
}
fn is_minimized_floor(width: f64, height: f64) -> bool {
width < f64::from(pdfcraft_ui_egui::MIN_WINDOW_SIZE[0]) && height <= 64.5
}
fn with_hwnd(window: &winit::window::Window, mut action: impl FnMut(&HWND) -> winsafe::SysResult<()>) {
let Ok(handle) = window.window_handle() else { return };
let RawWindowHandle::Win32(raw) = handle.as_raw() else { return };
// Borrow the matching handle from the window thread using winsafe's safe API.
if let Err(error) = winsafe::EnumThreadWindows(winsafe::GetCurrentThreadId(), |hwnd| {
if hwnd.ptr() as isize == raw.hwnd.get()
&& let Err(error) = fit_restore_bounds(&hwnd)
&& let Err(error) = action(&hwnd)
{
log::warn!("could not fit the restored PdfCraft window: {error}");
log::warn!("could not apply the PdfCraft window placement: {error}");
}
true
}) {
@@ -81,6 +140,14 @@ fn fitted(rect: RECT, work: RECT) -> Option<RECT> {
mod tests {
use super::*;
#[test]
fn detects_the_minimized_floor_after_windows_clamps_the_saved_size() {
assert!(is_minimized_floor(160.0, 64.0));
assert!(is_minimized_floor(64.0, 64.0));
assert!(!is_minimized_floor(860.0, 570.0));
assert!(!is_minimized_floor(160.0, 520.0));
}
#[test]
fn restore_after_high_dpi_startup_keeps_the_caption_controls_on_screen() {
let work = RECT { left: 0, top: 0, right: 3456, bottom: 2040 };
+50 -5
View File
@@ -138,6 +138,24 @@ fn page_fonts(doc: &Document, page: &Dict) -> Dict {
.unwrap_or_default()
}
/// Marked-content tags the text editor writes inside a text object.
const EDITOR_MARKS: [&[u8]; 4] = [b"Span", b"PCSoft", b"PCHard", b"P"];
/// Whether `op` opens one of the text editor's marked-content sequences. One that carries an
/// `/MCID` is another writer's structure content and would collide with the new MCIDs; `/OC`
/// layers and the like are not the editor's. An imported PDF can carry surplus operands, which the
/// renderer reads from the end, so the operand count (one for BMC, two for BDC) is checked first.
fn editor_mark(op: &Op) -> bool {
match (op.op.as_slice(), op.operands.len()) {
(b"BMC", 1) => op.name(0).is_some_and(|tag| EDITOR_MARKS.contains(&tag)),
(b"BDC", 2) => {
op.name(0).is_some_and(|tag| EDITOR_MARKS.contains(&tag))
&& op.operands.get(1).and_then(Object::as_dict).is_some_and(|d| !d.contains(b"MCID"))
}
_ => false,
}
}
fn harmless_outside(op: &[u8]) -> bool {
matches!(
op,
@@ -151,6 +169,15 @@ fn harmless_outside(op: &[u8]) -> bool {
| b"ri"
| b"i"
| b"gs"
// Text state is legal outside BT/ET and carries into the next text object; a text edit
// writes it there after its own text object.
| b"Tf"
| b"Tc"
| b"Tw"
| b"Tz"
| b"TL"
| b"Tr"
| b"Ts"
| b"G"
| b"g"
| b"RG"
@@ -251,14 +278,23 @@ fn plan_page(
}
let xobjects = page_xobjects(doc, &page.dict);
let (mut start, mut has_text, mut spans, mut artifacts) = (None, false, Vec::new(), HashMap::new());
// Marked-content boundaries must enclose the whole path, not just its paint operator.
let mut path = None;
// The text editor's own marked content (`/Span` keeps an /ActualText, `/PCSoft` and `/PCHard`
// mark wrapped lines, `/P` a paragraph), in or between text objects. It stays in the stream,
// around or inside the paragraph's own marked content, and must be balanced: `open` counts the
// sequences now open, `base` those open at the current BT, which an EMC inside it may not close.
let (mut open, mut base) = (0usize, 0usize);
// Marked-content boundaries must enclose the whole path, not just its paint operator. `events`
// counts every mark opened or closed so far and the path keeps its value at the first operator:
// any mark opened or closed inside the path (even one that leaves `open` as it was, such as a
// close followed by another open) would cross the artifact wrapper added around it.
let (mut events, mut path): (usize, Option<(usize, usize)>) = (0, None);
for (at, op) in parsed.ops.iter().enumerate() {
if path.is_some() && matches!(op.op.as_slice(), b"BT" | b"Do" | b"BI" | b"sh") {
return Err(unsupported(index, "painted content interrupts an unfinished path"));
}
match op.op.as_slice() {
b"BT" if start.is_none() => (start, has_text) = (Some(at), false),
b"BT" if start.is_none() => (start, has_text, base) = (Some(at), false, open),
b"ET" if start.is_some() && open != base => return Err(unsupported(index, "unterminated marked content in a text object")),
b"ET" => {
let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
if has_text {
@@ -270,16 +306,22 @@ fn plan_page(
}
b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
name if start.is_some() && harmless_inside(name) => {}
b"BDC" | b"BMC" if editor_mark(op) => (open, events) = (open + 1, events + 1),
b"EMC" if op.operands.is_empty() && open > if start.is_some() { base } else { 0 } => (open, events) = (open - 1, events + 1),
name if start.is_none() && harmless_outside(name) => match name {
b"m" | b"re" => {
path.get_or_insert(at);
path.get_or_insert((at, events));
}
b"n" => path = None,
_ => {}
},
_ if start.is_none() && painted_outside(doc, &xobjects, op) => {
let first = if matches!(op.op.as_slice(), b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s") {
path.take().unwrap_or(at)
match path.take() {
Some((_, seen)) if seen != events => return Err(unsupported(index, "marked content opens or closes inside a path")),
Some((first, _)) => first,
None => at,
}
} else {
at
};
@@ -288,6 +330,9 @@ fn plan_page(
_ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
}
}
if open > 0 {
return Err(unsupported(index, "unterminated marked content"));
}
if start.is_some() {
return Err(unsupported(index, "unterminated BT text object"));
}
+63
View File
@@ -258,3 +258,66 @@ fn mark_decorative_and_mark_artifact_keep_cross_stream_comment_hidden() {
let report_after = check(&comment_only, &Options { rules: [Rule::TaggedContent].into(), pages: None });
assert_eq!(report_after.result(Rule::TaggedContent).expect("rule result").status, Status::Passed);
}
fn one_stream(content: &str) -> Document {
build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>".into()),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into()),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 5 0 R /Resources << /Font << /F1 4 0 R >> >> >>".into()),
(4, FONT.into()),
(5, stream(content)),
])
}
/// #7416: the text editor's own balanced marked content, in and between text objects, does not
/// stop Auto-tag and stays in the stream.
#[test]
fn autotag_accepts_the_text_editors_balanced_marked_content() {
let content = "/P BMC /Span <</ActualText (ab)>> BDC BT /F1 12 Tf 72 700 Td (a) Tj /PCSoft <</N 1>> BDC EMC (b) Tj /PCHard BMC EMC ET EMC EMC\n\
/P BMC BT /F1 12 Tf 72 680 Td /Span <</ActualText (cd)>> BDC (c) Tj EMC ET EMC";
let mut doc = one_stream(content);
let result = autotag_text(&mut doc).expect("autotag succeeds");
assert_eq!(result.paragraphs, 2);
let (ops, skipped) = joined_ops(&doc);
assert_eq!(skipped, 0);
let count = |name: &str| ops.iter().filter(|op| op.is(name)).count();
assert_eq!(count("BDC"), count("EMC") - count("BMC"), "every mark is closed");
let mut open = Vec::new();
for op in &ops {
if op.is("BDC") || op.is("BMC") {
open.push(op.name(0).unwrap().to_vec());
} else if op.is("EMC") {
open.pop().expect("no stray EMC");
} else if op.is("Tj") {
assert!(open.iter().any(|t| t == b"P"), "text sits inside a paragraph mark");
}
}
assert!(open.is_empty());
assert!(
ops.iter()
.any(|op| op.is("BDC") && op.name(0) == Some(b"Span".as_slice()) && op.operands[1].as_dict().is_some_and(|d| d.contains(b"ActualText")))
);
}
/// What stays refused: marks that are not the editor's, or that are not balanced.
#[test]
fn autotag_refuses_marked_content_it_cannot_nest() {
for (why, content) in [
("an optional-content layer in a text object", "BT /F1 12 Tf 72 700 Td /OC /L BDC (a) Tj EMC ET"),
("a stray EMC", "BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"),
("an EMC in a text object closing a mark opened before it", "/P BMC BT /F1 12 Tf 72 700 Td (a) Tj EMC ET"),
("a span open at ET", "BT /F1 12 Tf 72 700 Td /Span <</ActualText (a)>> BDC (a) Tj ET EMC"),
("a span never closed", "/Span <</ActualText (a)>> BDC BT /F1 12 Tf 72 700 Td (a) Tj ET"),
("a span opened inside a path", "0 0 m /Span BMC 10 10 l S BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"),
("a span closed inside a path", "/Span BMC 0 0 m EMC 10 10 l S BT /F1 12 Tf 72 700 Td (a) Tj ET"),
("a mark closed and another opened inside a path", "/P BMC 0 0 m EMC /Span BMC 10 10 l S BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"),
("surplus operands before BMC", "/P /OC BMC BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"),
("surplus operands before BDC", "/P <<>> /Span <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"),
("an operand before EMC", "/P BMC BT /F1 12 Tf 72 700 Td (a) Tj ET /Unexpected EMC"),
("another writer's span with an MCID", "/Span <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"),
] {
let mut doc = one_stream(content);
let err = autotag_text(&mut doc).expect_err(why);
assert!(err.to_string().contains("unsupported") || err.to_string().contains("page 1"), "{why}: {err}");
}
}
+18 -1
View File
@@ -939,12 +939,25 @@ fn markup_overreach(subtype: &[u8], h: f64) -> f64 {
}
}
/// Zigzag vertices one squiggly underline's appearance draws in all: past it the zigzag is coarser
/// (about 5 MB of content stream at most).
const MAX_SQUIGGLY_VERTICES: usize = 200_000;
fn draw_markup(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
let subtype = context.subtype;
let stroke = context.stroke;
let c = &mut drawing.content;
let q = quads(context)?;
let col = stroke?;
// Zigzag vertices for all the squiggly quads together: a file can list tens of thousands of
// long, thin areas, and each alone is within its own cap.
let mut vertices = MAX_SQUIGGLY_VERTICES;
let mut remaining = q.len();
// Range edits accept at most 50,000 quads: three vertices each need only 150,000.
// A larger imported annotation may not fit even that minimum; keep its old appearance.
if subtype == b"Squiggly" && remaining > MAX_SQUIGGLY_VERTICES / 3 {
return None;
}
for quad in q.iter() {
let p = |i: usize| (quad[2 * i], quad[2 * i + 1]);
let (p1, p2, p3, p4) = (p(0), p(1), p(2), p(3));
@@ -967,7 +980,11 @@ fn draw_markup(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing)
let (lw, amp) = squiggle(h);
let len = (p4.0 - p3.0).hypot(p4.1 - p3.1);
let step = (h / 4.0).max(1.5);
let steps = ((len / step).ceil() as usize).clamp(1, 10_000);
remaining = remaining.saturating_sub(1);
// Reserve m + 2 l for every later quad before granting this one extra detail.
let available = vertices.saturating_sub(remaining.saturating_mul(3)).saturating_sub(1).max(2);
let steps = ((len / step).ceil() as usize).clamp(2, 10_000).min(available);
vertices = vertices.saturating_sub(steps.saturating_add(1));
c.push_str(&format!("{}{} w 1 j\n", rg_stroke(col), n(lw)));
for i in 0..=steps {
let t = i as f64 / steps as f64;
+5 -1
View File
@@ -149,7 +149,11 @@ pub(crate) fn base_dict(subtype: &str, rect: [f64; 4], page: ObjRef, contents: &
d.set(b"Type".to_vec(), Object::name("Annot"));
d.set(b"Subtype".to_vec(), Object::name(subtype));
d.set(b"Rect".to_vec(), num_array(&rect));
d.set(b"Contents".to_vec(), PdfString::text(contents));
// Only a comment with text has `/Contents`, as in Acrobat: macOS Preview marks a markup
// comment with the key, even empty, as holding a note (#7434).
if !contents.is_empty() {
d.set(b"Contents".to_vec(), PdfString::text(contents));
}
if !author.is_empty() {
d.set(b"T".to_vec(), PdfString::text(author));
}
+16 -1
View File
@@ -46,6 +46,21 @@ pub(crate) fn can_draw(doc: &Document, d: &Dict) -> bool {
build_appearance(doc, d, &with_direct_values(doc, d), None).is_some()
}
/// The appearance for `d`, an annotation that page `page` lists, built but not stored: with
/// [`store_built`], [`draw_appearance`] in two halves, so an edit can refuse before it changes
/// anything. `None` when it can't be drawn.
pub(crate) fn build_listed_by(doc: &Document, d: &Dict, page: ObjRef) -> Option<Built> {
let crop = appearance::is_drawn_from_points(d).then(|| page_with_inherited_boxes(doc, page).crop(doc));
let direct = with_direct_values(doc, d);
let stream = build_appearance(doc, d, &direct, crop)?;
Some(Built::new(stream, &direct))
}
/// Store an appearance [`build_listed_by`] built from `d` on the annotation `r`.
pub(crate) fn store_built(doc: &mut Document, r: ObjRef, d: &Dict, built: Built) -> Result<(), AnnotError> {
apply_appearance(doc, r, d, built)
}
/// The visible region (`Page::crop`) of the page that lists `r` among its annotations: the page
/// its `/P` names when that page lists it, read up its own `/Parent` chain, else the first page
/// of the tree that lists it. An annotation is listed by one page only (ISO 32000-2 §12.5.2), so
@@ -249,7 +264,7 @@ fn direct_value(doc: &Document, o: &Object, depth: usize, budget: &mut usize) ->
/// A built appearance and what storing it needs from the dictionary it was drawn from, read
/// with references followed, so a cached one is stored without following them again.
#[derive(Clone, Debug)]
struct Built {
pub(crate) struct Built {
stream: Stream,
/// The first character the standard fonts can't draw (it came out as `?`).
missing: Option<char>,
+1 -1
View File
@@ -46,7 +46,7 @@ pub(crate) use modify::n;
pub use modify::{
add_reply, add_text_replacement, deletable, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation, release_members,
set_border_color, set_border_shape, set_contents, set_fill, set_font_size, set_locked, set_marked, set_part_opacity, set_points, set_popup,
set_rect, set_review_state, set_style, with_replies_and_popups,
set_quads, set_rect, set_review_state, set_style, with_replies_and_popups,
};
pub use threed::{Activation as Activation3d, MAX_MODEL_BYTES, ModelFormat, NewModel3d, PosterPicture, add_3d_model, check_model};
pub use types::{
+152 -27
View File
@@ -2,7 +2,7 @@ use super::create::{
CALLOUT_SLACK, add_annotation, base_dict, bounds, callout_attach, callout_knee, callout_side, ending_draws, ending_pair, finite, grow,
ink_bounds, normalize, num_array, on_side, polygon_rect, rect_for, rgb,
};
use super::draw::{draw_appearance, redraw_or_restore, set_appearance};
use super::draw::{build_listed_by, draw_appearance, redraw_or_restore, set_appearance, store_built};
use super::info::{is_comment_subtype, is_group_subordinate, line_endings_of, own_popup, popup_info, text_value};
use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, change_annots, is_fill_sign, page_ref, set_annots};
use super::text_style::{self, TextStyle};
@@ -306,7 +306,12 @@ pub fn set_contents(doc: &mut Document, page: usize, index: usize, text: &str, m
// The text keeps the look it is drawn with (`/DA`, or `/DS` where it sets one).
let style = text_style::text_style(&before, text_style::dr_face(doc, &before));
doc.update_dict(r, |d| {
d.set(b"Contents".to_vec(), PdfString::text(text));
// Cleared text leaves no `/Contents`, as a new comment without text has none (#7434).
if text.is_empty() {
d.remove(b"Contents");
} else {
d.set(b"Contents".to_vec(), PdfString::text(text));
}
// The rich-text version follows the new plain text (text boxes), or would contradict it.
if free_text {
rich_text_in(d, style);
@@ -855,6 +860,98 @@ pub fn set_points(doc: &mut Document, page: usize, index: usize, points: &[[f64;
redraw_or_restore(doc, r, before)
}
const MAX_QUADS: usize = 50_000;
/// Give a highlight, underline, strikethrough or squiggly underline new text area `quads` (user
/// space, a `/QuadPoints` quadrilateral each): the range it covers is extended or reduced, as
/// Acrobat lets one select the markup and change the text it marks. `/Rect` follows the
/// quadrilaterals and the appearance is redrawn; the colour, opacity, contents, replies and every
/// other entry are kept. A locked markup, another kind of comment, a redaction (its area is what
/// is removed) or an empty or non-finite area is refused, and nothing changes.
///
/// Each quad's corners may come in the order Acrobat writes and the appearance draws (top left,
/// top right, bottom left, bottom right), or around the area as ISO 32000-2 §12.5.6.10 (Table
/// 182) describes it, the text running from the first corner to the second; the latter are stored
/// in the former order. A quad whose first two corners are opposite each other is refused.
pub fn set_quads(doc: &mut Document, page: usize, index: usize, quads: &[[f64; 8]], meta: &Meta) -> Result<(), AnnotError> {
if quads.len() > MAX_QUADS {
return Err(AnnotError::Invalid(format!("at most {MAX_QUADS} text areas")));
}
let bad_area = || AnnotError::Invalid("text areas need quadrilaterals with nonzero finite area".into());
if quads.is_empty() {
return Err(bad_area());
}
// Non-collinear corners span an area in either Z-order or perimeter order. Validate every
// quad before annot_ref can promote an inline annotation to a reference.
let mut stored = Vec::with_capacity(quads.len());
for quad in quads {
let [x0, y0, x1, y1, x2, y2, x3, y3] = *quad;
let (a, b, c) = ([x1 - x0, y1 - y0], [x2 - x0, y2 - y0], [x3 - x0, y3 - y0]);
let cross = |[ax, ay]: [f64; 2], [bx, by]: [f64; 2]| ax * by - ay * bx;
let areas = [cross(a, b), cross(a, c), cross(b, c)];
if !areas.iter().all(|area| area.is_finite()) || areas.iter().all(|area| *area == 0.0) {
return Err(bad_area());
}
stored.push(z_order(*quad).ok_or_else(|| AnnotError::Invalid("a text area's first two corners must be adjacent".into()))?);
}
let quads = stored.as_slice();
// Read without promotion: even valid geometry must leave an inline entry untouched when
// its lock or subtype refuses the edit.
let mut d = annots(doc, page_ref(doc, page)?)
.get(index)
.and_then(|entry| doc.resolve(entry).as_dict().cloned())
.ok_or(AnnotError::NoSuchAnnotation { page, index })?;
if annotation_flags(doc, &d) & FLAG_LOCKED != 0 {
return Err(AnnotError::Invalid("the comment is locked".into()));
}
let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
let kind = match subtype.as_str() {
"Highlight" => Markup::Highlight,
"Underline" => Markup::Underline,
"StrikeOut" => Markup::StrikeOut,
"Squiggly" => Markup::Squiggly,
other => return Err(AnnotError::Invalid(format!("{other} comments have no text range to change"))),
};
// Derive the bounds from the validated quadrilaterals.
let rect = rect_for(&Shape::TextMarkup { kind, quads: quads.to_vec() }, &Style::default())?;
d.set(b"QuadPoints".to_vec(), num_array(&quads.concat()));
d.set(b"Rect".to_vec(), num_array(&rect));
touch(&mut d, meta);
// Build before promotion: a redraw refusal must not add an object or rewrite /Annots.
refuse_foreign_text(doc, &d)?;
let built = build_listed_by(doc, &d, page_ref(doc, page)?).ok_or(AnnotError::Unsupported(subtype))?;
let (_, r) = annot_ref(doc, page, index)?;
doc.set(r, Object::Dict(d.clone()));
// r is now a dictionary, and adding the stream cannot replace an existing object, so
// store_built's dictionary update cannot fail after promotion.
store_built(doc, r, &d, built)
}
/// `quad` with its corners in the order the appearance draws them (top left, top right, bottom
/// left, bottom right): kept when already so, reordered from a perimeter order (see
/// [`set_quads`]), `None` when its first two corners are opposite each other.
fn z_order(quad: [f64; 8]) -> Option<[f64; 8]> {
let [x1, y1, x2, y2, x3, y3, x4, y4] = quad;
let (p1, p2, p3, p4) = ([x1, y1], [x2, y2], [x3, y3], [x4, y4]);
let side = |a: [f64; 2], b: [f64; 2], c: [f64; 2]| (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
// Compare signs, not a product, which underflows to zero for a tiny quad.
let opposite = |s: f64, t: f64| (s < 0.0 && t > 0.0) || (s > 0.0 && t < 0.0);
// Whether segments ab and cd cross at a point inside both.
let crosses = |a, b, c, d| opposite(side(a, b, c), side(a, b, d)) && opposite(side(c, d, a), side(c, d, b));
// The outline drawn from Z-order corners: 1, 2, 4, 3.
if !crosses(p1, p2, p4, p3) && !crosses(p2, p4, p3, p1) {
return Some(quad);
}
if crosses(p1, p2, p3, p4) || crosses(p2, p3, p4, p1) {
return None;
}
// Around the area: the text runs from corner 1 to corner 2 with the area on its left
// (counterclockwise, 1-2 the bottom edge) or on its right (clockwise, 1-2 the top edge).
let counterclockwise = side(p1, p2, p3) > 0.0;
let [tl, tr, bl, br] = if counterclockwise { [p4, p3, p1, p2] } else { [p1, p2, p4, p3] };
Some([tl[0], tl[1], tr[0], tr[1], bl[0], bl[1], br[0], br[1]])
}
/// Scale a drawing's strokes into `rect`. The margin between the strokes and the old `/Rect` (half
/// the line width and a little more) stays the same on each side, so the line isn't clipped.
/// Most stroke points a stored drawing may have for resizing or erasing it. Counted as each
@@ -1097,20 +1194,27 @@ fn ink_rect_for_width(d: &Dict, old_w: f64, w: f64) -> Option<[f64; 4]> {
/// annotation has no border) and neither part has line endings. All or nothing: if one member
/// can't be restyled, none is.
pub fn set_style(doc: &mut Document, page: usize, index: usize, change: StyleChange, meta: &Meta) -> Result<(), AnnotError> {
let (_, r) = annot_ref(doc, page, index)?;
let others = replace_text_partners(doc, page, r)?;
// Check every partner before changing anything.
// Check the target and every partner before annot_ref can promote an inline target: a
// refused restyle must not add an object or rewrite /Annots.
let entry = annots(doc, page_ref(doc, page)?).get(index).cloned().ok_or(AnnotError::NoSuchAnnotation { page, index })?;
let target = doc.resolve(&entry).as_dict().cloned().filter(crate::lookup::is_comment_dict).ok_or(AnnotError::NoSuchAnnotation { page, index })?;
check_style(doc, &target, &change)?;
let others = replace_text_partners(doc, page, &entry)?;
for &o in &others {
// A partner the change leaves alone is checked for its lock only, as before.
unlocked(doc, o)?;
let part = partner_change(doc, o, &change);
if !part_unchanged(&part) {
check_style(doc, &annot_dict(doc, o), &part)?;
}
}
let (_, r) = annot_ref(doc, page, index)?;
let before: Vec<(ObjRef, Dict)> = others.iter().map(|&o| (o, annot_dict(doc, o))).collect();
let mut done: Vec<(ObjRef, Dict)> = vec![(r, annot_dict(doc, r))];
style_one(doc, r, change.clone(), meta)?;
for (o, d) in before {
let caret = d.name(b"Subtype") == Some(b"Caret");
let part = StyleChange { color: change.color, opacity: change.opacity, width: change.width.filter(|_| caret), endings: None };
let unchanged = part.color.is_none() && part.opacity.is_none() && part.width.is_none();
if unchanged {
let part = partner_change(doc, o, &change);
if part_unchanged(&part) {
continue;
}
if let Err(e) = style_one(doc, o, part, meta) {
@@ -1128,41 +1232,62 @@ pub fn set_style(doc: &mut Document, page: usize, index: usize, change: StyleCha
/// The other members of the Replace Text proposal `r` belongs to, on `page`: for its caret, the
/// strikeouts grouped under it; for a strikeout, its caret and any other strikeout under it.
/// Empty for anything else.
fn replace_text_partners(doc: &Document, page: usize, r: ObjRef) -> Result<Vec<ObjRef>, AnnotError> {
let own = Object::Ref(r);
let caret = match replaced_by(doc, &own) {
Some(c) => c,
None if annot_dict(doc, r).name(b"Subtype") == Some(b"Caret") => r,
None => return Ok(Vec::new()),
/// `entry` is the target's `/Annots` entry; written inline, it is no other member's caret.
fn replace_text_partners(doc: &Document, page: usize, entry: &Object) -> Result<Vec<ObjRef>, AnnotError> {
let own = entry.as_ref();
let caret = match (replaced_by(doc, entry), own) {
(Some(c), _) => c,
(None, Some(r)) if annot_dict(doc, r).name(b"Subtype") == Some(b"Caret") => r,
_ => return Ok(Vec::new()),
};
let list = annots(doc, page_ref(doc, page)?);
let strikes = list.iter().filter(|e| replaced_by(doc, e) == Some(caret)).filter_map(Object::as_ref);
// `/Annots` may list one annotation twice: restyle each once.
let mut seen: HashSet<ObjRef> = HashSet::from([r]);
let mut seen: HashSet<ObjRef> = own.into_iter().collect();
Ok(std::iter::once(caret).chain(strikes).filter(|&o| seen.insert(o)).collect())
}
/// [`set_style`] on one annotation.
fn style_one(doc: &mut Document, r: ObjRef, change: StyleChange, meta: &Meta) -> Result<(), AnnotError> {
let StyleChange { color, opacity, width, endings } = change;
unlocked(doc, r)?;
let d = annot_dict(doc, r);
let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
// Check before changing anything: a stale appearance would contradict the new style.
if !crate::draw::can_draw(doc, &d) {
return Err(AnnotError::Unsupported(subtype.clone()));
/// What a Replace Text partner `o` takes of `change`: colour and opacity, and line width for
/// its caret only.
fn partner_change(doc: &Document, o: ObjRef, change: &StyleChange) -> StyleChange {
let caret = annot_dict(doc, o).name(b"Subtype") == Some(b"Caret");
StyleChange { color: change.color, opacity: change.opacity, width: change.width.filter(|_| caret), endings: None }
}
fn part_unchanged(part: &StyleChange) -> bool {
part.color.is_none() && part.opacity.is_none() && part.width.is_none()
}
/// Whether [`style_one`] would refuse `change` on the annotation `d`, without changing anything.
fn check_style(doc: &Document, d: &Dict, change: &StyleChange) -> Result<(), AnnotError> {
if annotation_flags(doc, d) & FLAG_LOCKED != 0 {
return Err(AnnotError::Invalid("the comment is locked".into()));
}
let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
// A stale appearance would contradict the new style.
if !crate::draw::can_draw(doc, d) {
return Err(AnnotError::Unsupported(subtype));
}
let StyleChange { color, opacity, width, endings } = change;
if color.is_some_and(|c| !finite(&c)) || opacity.is_some_and(|o| !o.is_finite()) || width.is_some_and(|w| !w.is_finite()) {
return Err(AnnotError::Invalid("invalid style".into()));
}
if let Some(ends) = &endings {
if let Some(ends) = endings {
let callout = subtype == "FreeText" && d.contains(b"CL");
let pair = matches!(subtype.as_str(), "Line" | "PolyLine");
if (callout && ends.len() != 1) || (pair && ends.len() != 2) || (!callout && !pair) {
return Err(AnnotError::Invalid("this comment has no line endings to change".into()));
}
}
refuse_foreign_text(doc, &d)?;
refuse_foreign_text(doc, d)
}
/// [`set_style`] on one annotation.
fn style_one(doc: &mut Document, r: ObjRef, change: StyleChange, meta: &Meta) -> Result<(), AnnotError> {
let d = annot_dict(doc, r);
check_style(doc, &d, &change)?;
let StyleChange { color, opacity, width, endings } = change;
let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
let free_text = subtype == "FreeText";
// The face and size the text is drawn in, which the new colour keeps.
let drawn = text_style::text_style(&d, text_style::dr_face(doc, &d));
+377
View File
@@ -423,6 +423,344 @@ fn deleting_the_last_comment_removes_annots() {
assert!(!doc.get(page_refs(&doc).unwrap()[0]).as_dict().unwrap().contains(b"Annots"));
}
/// #4824: a text markup's range can be extended or reduced; everything else about it stays.
#[test]
fn set_quads_changes_the_marked_range_and_keeps_the_rest() {
let mut doc = fixture();
let one = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
let two = [72.0, 700.0, 150.0, 700.0, 72.0, 688.0, 150.0, 688.0];
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![one] }), &meta("h")).unwrap();
let before = ap_content(&doc, &list(&doc, 0)[h]);
set_quads(&mut doc, 0, h, &[one, two], &meta("h2")).unwrap();
let now = reopen(&doc);
let d = &list(&now, 0)[h];
let qp: Vec<f64> = d.get(b"QuadPoints").unwrap().as_array().unwrap().iter().map(|o| o.as_f64().unwrap()).collect();
assert_eq!(qp, [one, two].concat(), "both lines are marked");
assert_eq!(rect(d), [72.0, 688.0, 200.0, 712.0], "/Rect follows the area");
assert_ne!(ap_content(&now, d), before, "the appearance is redrawn over the new area");
assert_eq!(d.get(b"C").unwrap().as_array().unwrap().len(), 3, "the colour is kept");
assert_eq!(crate::info::text_value(&now, d, b"Contents").as_deref(), Some("hello"));
// And reduced again, to the second line only.
set_quads(&mut doc, 0, h, &[two], &meta("h3")).unwrap();
assert_eq!(rect(&list(&reopen(&doc), 0)[h]), [72.0, 688.0, 150.0, 700.0]);
}
/// #4824: an imported markup keeps its opacity and colour when its range changes, though the file
/// keeps them behind references.
#[test]
fn set_quads_redraws_with_the_opacity_and_colour_kept_behind_references() {
let mut doc = fixture();
let q = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![q] }), &meta("h")).unwrap();
let (_, r) = crate::lookup::annot_ref(&mut doc, 0, h).unwrap();
let ca = doc.add(Object::Real(0.25));
let c = doc.add(Object::Array(vec![Object::Real(0.0), Object::Real(1.0), Object::Real(0.0)]));
doc.update_dict(r, |d| {
d.set(b"CA".to_vec(), Object::Ref(ca));
d.set(b"C".to_vec(), Object::Ref(c));
})
.unwrap();
set_quads(&mut doc, 0, h, &[q, [72.0, 700.0, 150.0, 700.0, 72.0, 688.0, 150.0, 688.0]], &meta("h2")).unwrap();
let d = &list(&doc, 0)[h];
assert!(matches!(d.get(b"CA"), Some(Object::Ref(_))) && matches!(d.get(b"C"), Some(Object::Ref(_))), "the file's own entries stay as they were");
let ap = d.get(b"AP").unwrap().as_dict().unwrap().reference(b"N").unwrap();
let res = doc.get(ap).as_dict().unwrap().get(b"Resources").cloned().unwrap();
let gs = res.as_dict().unwrap().get(b"ExtGState").unwrap().as_dict().unwrap().get(b"GS0").unwrap().as_dict().unwrap().clone();
assert_eq!(gs.get(b"ca").and_then(|o| o.as_f64()), Some(0.25), "the drawn opacity is the file's");
assert!(ap_content(&doc, d).contains("0 1 0 rg"), "and its colour: {}", ap_content(&doc, d));
}
/// #4824: many long, thin squiggly areas stay within one total drawing budget.
#[test]
fn set_quads_bounds_the_squiggly_appearance_as_a_whole() {
let mut doc = fixture();
let q = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Squiggly, quads: vec![q] }), &meta("s")).unwrap();
let long = [0.0, 1.0, 20_000.0, 1.0, 0.0, 0.0, 20_000.0, 0.0];
set_quads(&mut doc, 0, h, &vec![long; 50_000], &meta("s2")).unwrap();
let content = ap_content(&doc, &list(&doc, 0)[h]);
assert!(content.len() < 8 << 20, "the appearance is {} bytes", content.len());
assert_eq!(content.matches(" m\n").count(), 50_000, "every area is still drawn");
}
/// Long quads must leave every later squiggly at least one zigzag, including very short quads.
#[test]
fn set_quads_keeps_every_squiggly_zigzag_within_the_total_vertex_budget() {
let mut doc = fixture();
let long = [0.0, 1.0, 20_000.0, 1.0, 0.0, 0.0, 20_000.0, 0.0];
let short = [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0];
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Squiggly, quads: vec![long] }), &meta("s")).unwrap();
let mut quads = vec![long; 64];
quads.resize(50_000, short);
set_quads(&mut doc, 0, h, &quads, &meta("s2")).unwrap();
let content = ap_content(&doc, &list(&doc, 0)[h]);
let (mut paths, mut vertices) = (Vec::new(), 0usize);
for line in content.lines() {
if line.ends_with(" m") {
assert_eq!(vertices, 0, "the preceding path was stroked");
vertices = 1;
} else if line.ends_with(" l") {
vertices += 1;
} else if line == "S" {
paths.push(vertices);
vertices = 0;
}
}
assert_eq!(paths.len(), quads.len(), "every quad has its own stroked path");
assert_eq!(vertices, 0);
for (quad, vertices) in paths.iter().enumerate() {
assert!(*vertices >= 3, "quad {quad} has only {vertices} vertices: a squiggly needs m + 2 l");
}
let total = paths.iter().sum::<usize>();
assert!(total <= 200_000, "the appearance has {total} vertices, above the shared 200000 cap");
}
/// Imported annotations can exceed the range-edit limit. Refuse a redraw whose minimum
/// zigzags cannot fit the appearance budget, preserving its existing dictionary and appearance.
#[test]
fn restyling_a_squiggly_refuses_more_quads_than_the_minimum_vertex_budget_allows() {
let short = [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0];
for (count, refused) in [(66_666, false), (66_667, true)] {
let mut doc = fixture();
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Squiggly, quads: vec![short] }), &meta("s")).unwrap();
let (_, r) = crate::lookup::annot_ref(&mut doc, 0, h).unwrap();
doc.update_dict(r, |d| d.set(b"QuadPoints".to_vec(), create::num_array(&vec![short; count].concat()))).unwrap();
let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
let change = StyleChange::new(Some([0.0, 1.0, 0.0]), None, None, None);
let result = set_style(&mut doc, 0, h, change, &meta("restyle"));
assert_eq!(result.is_err(), refused, "{count} quads need {} vertices", count * 3);
if refused {
assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before, "a refused redraw changes nothing");
}
}
}
/// A restyle refused for an inline annotation (one too large to redraw, one that can't be drawn,
/// one locked) must not promote it: no object is added and /Annots is not rewritten.
#[test]
fn set_style_refusal_leaves_an_inline_annotation_unpromoted() {
let short = [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0];
let cloud = Object::Dict(Dict::from_iter([(b"S".to_vec(), Object::name("C")), (b"I".to_vec(), Object::Int(2))]));
let cases: [(Markup, &[u8], Object); 3] = [
(Markup::Squiggly, b"QuadPoints", create::num_array(&vec![short; 66_667].concat())),
(Markup::Highlight, b"BE", cloud),
(Markup::Highlight, b"F", Object::Int(crate::types::FLAG_LOCKED)),
];
for (kind, key, value) in cases {
let mut doc = fixture();
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind, quads: vec![short] }), &meta("s")).unwrap();
let page = page_refs(&doc).unwrap()[0];
let mut dict = list(&doc, 0)[h].clone();
dict.set(key.to_vec(), value);
let mut entries = annots(&doc, page);
entries[h] = Object::Dict(dict);
set_annots(&mut doc, page, entries).unwrap();
let mut doc = reopen(&doc);
let snapshot = |doc: &Document| {
(write_incremental(doc, &SaveOptions::default()).unwrap(), format!("{:?}", doc.get(page)), doc.object_numbers().len(), doc.is_modified())
};
let before = snapshot(&doc);
let change = StyleChange::new(Some([0.0, 1.0, 0.0]), None, None, None);
assert!(set_style(&mut doc, 0, h, change, &meta("restyle")).is_err(), "{}", String::from_utf8_lossy(key));
assert!(snapshot(&doc) == before, "refusing {} promoted the inline annotation", String::from_utf8_lossy(key));
}
}
/// Corners given around the area, clockwise or (as ISO 32000-2 Table 182 describes) counter-
/// clockwise, are stored and drawn as the same corners in drawing order: the highlight fills
/// the area instead of crossing itself and the underline runs along its bottom.
#[test]
fn set_quads_draws_perimeter_order_corners_as_the_area() {
// Each case: the drawing-order quad, then the same area given around it each way.
let level = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
let tilted = [10.0, 30.0, 40.0, 40.0, 14.0, 18.0, 44.0, 28.0];
let around = |[a, b, c, d, e, f, g, h]: [f64; 8]| [[a, b, c, d, g, h, e, f], [e, f, g, h, c, d, a, b]];
let drawn = |quad: [f64; 8]| {
let mut doc = fixture();
let start = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![start] }), &meta("h")).unwrap();
let u = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Underline, quads: vec![start] }), &meta("u")).unwrap();
set_quads(&mut doc, 0, h, &[quad], &meta("h")).unwrap();
set_quads(&mut doc, 0, u, &[quad], &meta("u")).unwrap();
let all = list(&doc, 0);
let qp: Vec<f64> = all[h].get(b"QuadPoints").unwrap().as_array().unwrap().iter().map(|o| o.as_f64().unwrap()).collect();
(qp, ap_content(&doc, &all[h]), ap_content(&doc, &all[u]))
};
for z in [level, tilted] {
let expected = drawn(z);
for quad in around(z) {
assert!(drawn(quad) == expected, "{quad:?} is stored and drawn as {z:?}");
}
}
// Opposite first corners name no edge for the text to run along.
let mut doc = fixture();
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![level] }), &meta("h")).unwrap();
let diagonal = [72.0, 712.0, 200.0, 700.0, 200.0, 712.0, 72.0, 700.0];
assert!(set_quads(&mut doc, 0, h, &[diagonal], &meta("bad")).is_err());
}
/// A tiny quad given around its area is still reordered: the sides of its corners are so small
/// that their product underflows to zero, so the crossing test must compare signs.
#[test]
fn set_quads_reorders_a_tiny_perimeter_order_quad() {
let z = [0.0, 1e-100, 1e-100, 1e-100, 0.0, 0.0, 1e-100, 0.0];
let around = [0.0, 1e-100, 1e-100, 1e-100, 1e-100, 0.0, 0.0, 0.0];
let mut doc = fixture();
let start = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![start] }), &meta("h")).unwrap();
set_quads(&mut doc, 0, h, &[around], &meta("h")).unwrap();
let qp: Vec<f64> = list(&doc, 0)[h].get(b"QuadPoints").unwrap().as_array().unwrap().iter().map(|o| o.as_f64().unwrap()).collect();
assert_eq!(qp, z.to_vec(), "stored in drawing order");
}
/// Zero-area quadrilaterals, including collinear diagonals with a nonempty bounding box,
/// never replace a markup. Reject them before even promoting an inline annotation to a reference.
#[test]
fn set_quads_rejects_zero_area_quads_without_changing_the_markup() {
let valid = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
for inline in [false, true] {
let mut doc = fixture();
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![valid] }), &meta("h")).unwrap();
let page = page_refs(&doc).unwrap()[0];
if inline {
let dict = list(&doc, 0)[h].clone();
let mut entries = annots(&doc, page);
entries[h] = Object::Dict(dict);
set_annots(&mut doc, page, entries).unwrap();
}
let snapshot = |doc: &Document| {
(format!("{:?}", list(doc, 0)), format!("{:?}", doc.get(page)), doc.object_numbers().len(), ap_content(doc, &list(doc, 0)[h]))
};
let before = snapshot(&doc);
for quads in [
vec![[0.0; 8]],
vec![[0.0, 1.0, 10.0, 1.0, 20.0, 1.0, 30.0, 1.0]],
vec![[1.0, 0.0, 1.0, 10.0, 1.0, 20.0, 1.0, 30.0]],
vec![[0.0, 0.0, 10.0, 10.0, 20.0, 20.0, 30.0, 30.0]],
vec![valid, [0.0; 8]],
vec![[0.0; 8], valid],
vec![[-f64::MAX, 0.0, f64::MAX, 0.0, 0.0, 1.0, 1.0, 1.0]],
Vec::new(),
] {
assert!(set_quads(&mut doc, 0, h, &quads, &meta("bad")).is_err(), "inline={inline}, {quads:?}");
assert_eq!(snapshot(&doc), before, "no dictionary, appearance or page reference changed: {quads:?}");
}
// Area does not depend on the point order: both Z-order and perimeter-order corners
// span the same rectangle, and a rotated/skewed area is valid too.
for quad in [valid, [72.0, 712.0, 200.0, 712.0, 200.0, 700.0, 72.0, 700.0], [0.0, 0.0, 10.0, 10.0, -2.0, 2.0, 8.0, 12.0]] {
set_quads(&mut doc, 0, h, &[quad], &meta("good")).unwrap();
}
}
}
/// Valid geometry must not promote an inline annotation before a lock or subtype refusal.
#[test]
fn set_quads_refuses_inline_locked_or_non_markup_annotations_without_promotion() {
let q = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
let mut changed = Vec::new();
for inline in [false, true] {
for (shape, locked) in [
(Shape::TextMarkup { kind: Markup::Highlight, quads: vec![q] }, true),
(Shape::Ink { strokes: vec![vec![[10.0, 10.0], [20.0, 20.0]]] }, false),
(Shape::Redact { quads: vec![q], overlay: String::new(), look: Default::default() }, false),
] {
let mut doc = fixture();
let index = add_annotation(&mut doc, &new(0, shape), &meta("source")).unwrap();
let page = page_refs(&doc).unwrap()[0];
let mut dict = list(&doc, 0)[index].clone();
let subtype = String::from_utf8_lossy(dict.name(b"Subtype").unwrap()).into_owned();
if locked {
// Indirect flags must be checked before promotion too.
let flags = doc.add(Object::Int(crate::types::FLAG_LOCKED));
dict.set(b"F".to_vec(), Object::Ref(flags));
}
let mut entries = annots(&doc, page);
entries[index] = if inline { Object::Dict(dict) } else { Object::Ref(doc.add(Object::Dict(dict))) };
set_annots(&mut doc, page, entries).unwrap();
let snapshot = |doc: &Document| {
(
pdfcraft_cos::write_full(doc, &Default::default()).unwrap(),
format!("{:?}", doc.get(page)),
doc.object_numbers().len(),
doc.is_modified(),
)
};
let before = snapshot(&doc);
let error = set_quads(&mut doc, 0, index, &[q], &meta("refused")).unwrap_err().to_string();
assert!(error.contains(if locked { "locked" } else { "no text range" }), "{error}");
if snapshot(&doc) != before {
changed.push(format!("inline={inline}, subtype={subtype}, locked={locked}"));
}
}
}
assert!(changed.is_empty(), "refusal changed objects or page entries: {changed:?}");
}
/// A cloudy imported markup cannot be redrawn. Refusal must not promote an inline dictionary,
/// rewrite either form of /Annots, allocate objects, or replace the existing appearance.
#[test]
fn set_quads_redraw_failure_preserves_inline_and_indirect_annotations_byte_for_byte() {
let q = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
let replacement = [72.0, 700.0, 150.0, 700.0, 72.0, 688.0, 150.0, 688.0];
for inline in [true, false] {
for indirect_annots in [false, true] {
let mut doc = fixture();
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![q] }), &meta("source")).unwrap();
let page = page_refs(&doc).unwrap()[0];
let mut dict = list(&doc, 0)[h].clone();
dict.set(b"BE".to_vec(), Object::Dict(Dict::from_iter([(b"S".to_vec(), Object::name("C")), (b"I".to_vec(), Object::Int(2))])));
assert!(appearance::build(&doc, &dict).is_none(), "cloudy highlight appearances are unsupported");
let mut entries = annots(&doc, page);
entries[h] = if inline { Object::Dict(dict) } else { Object::Ref(doc.add(Object::Dict(dict))) };
if indirect_annots {
let array = doc.add(Object::Array(entries));
doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Ref(array))).unwrap();
} else {
set_annots(&mut doc, page, entries).unwrap();
}
let mut doc = reopen(&doc);
assert!(!doc.is_modified(), "the imported fixture starts clean");
let snapshot = |doc: &Document| {
(
write_incremental(doc, &SaveOptions::default()).unwrap(),
format!("{:?}", doc.get(page)),
doc.object_numbers().len(),
ap_content(doc, &list(doc, 0)[h]),
doc.is_modified(),
)
};
let before = snapshot(&doc);
assert!(matches!(set_quads(&mut doc, 0, h, &[replacement], &meta("refused")), Err(AnnotError::Unsupported(kind)) if kind == "Highlight"));
assert_eq!(snapshot(&doc), before, "inline={inline}, indirect Annots={indirect_annots}");
}
}
}
/// #4824: what is refused changes nothing.
#[test]
fn set_quads_refuses_other_comments_locked_markup_and_bad_areas() {
let mut doc = fixture();
let q = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Underline, quads: vec![q] }), &meta("h")).unwrap();
let ink = add_annotation(&mut doc, &new(0, Shape::Ink { strokes: vec![vec![[10.0, 10.0], [20.0, 20.0]]] }), &meta("i")).unwrap();
let redact =
add_annotation(&mut doc, &new(0, Shape::Redact { quads: vec![q], overlay: String::new(), look: Default::default() }), &meta("r")).unwrap();
let snapshot = |doc: &Document| format!("{:?}", list(doc, 0));
let before = snapshot(&doc);
assert!(set_quads(&mut doc, 0, ink, &[q], &meta("")).is_err(), "a drawing has no text range");
assert!(set_quads(&mut doc, 0, redact, &[q], &meta("")).is_err(), "a redaction's area is what is removed");
assert!(set_quads(&mut doc, 0, h, &[], &meta("")).is_err(), "an empty area");
assert!(set_quads(&mut doc, 0, h, &[[f64::NAN; 8]], &meta("")).is_err(), "a non-finite area");
assert!(set_quads(&mut doc, 0, h, &vec![q; 50_001], &meta("")).is_err(), "a capped number of areas");
assert!(set_quads(&mut doc, 0, 99, &[q], &meta("")).is_err(), "no such comment");
set_locked(&mut doc, 0, h, true).unwrap();
let locked = snapshot(&doc);
assert!(set_quads(&mut doc, 0, h, &[q], &meta("")).is_err(), "a locked markup");
assert_eq!(snapshot(&doc), locked);
set_locked(&mut doc, 0, h, false).unwrap();
assert_eq!(snapshot(&doc), before, "nothing changed");
}
#[test]
fn move_shifts_all_geometry_and_the_popup() {
let mut doc = fixture();
@@ -1936,6 +2274,14 @@ fn restyling_a_replace_text_pair_restyles_both_members() {
set_locked(&mut locked, 0, s, true).unwrap();
assert!(set_style(&mut locked, 0, c, StyleChange::new(Some(green), None, None, None), &meta("")).is_err());
assert_eq!(color(&locked, c), red.color.to_vec(), "the caret keeps its colour");
// A width takes no part of the strikeout, so one that can't be redrawn doesn't refuse it.
let mut cloudy = doc.clone();
let (_, sr) = crate::lookup::annot_ref(&mut cloudy, 0, s).unwrap();
let cloud = Object::Dict(Dict::from_iter([(b"S".to_vec(), Object::name("C")), (b"I".to_vec(), Object::Int(2))]));
cloudy.update_dict(sr, |d| d.set(b"BE".to_vec(), cloud)).unwrap();
assert!(!crate::draw::can_draw(&cloudy, &crate::lookup::annot_dict(&cloudy, sr)), "a cloudy strikeout can't be drawn");
set_style(&mut cloudy, 0, c, StyleChange::new(None, None, Some(3.0), None), &meta("")).unwrap();
}
#[test]
@@ -4664,6 +5010,37 @@ fn pop_ups_open_close_and_move_and_are_reported() {
assert_eq!(listed.popup, Some(PopupInfo { rect: [150.0, 100.0, 290.0, 200.0], open: false }), "listed through {via:?}");
}
/// #7434: a comment nobody wrote in is saved without `/Contents`, as Acrobat saves a highlight
/// without a note. macOS Preview marks a markup comment that has the key, even empty, as
/// holding a note. Clearing a comment's text removes the key, and its summary reads no text
/// either way.
#[test]
fn a_comment_without_text_is_saved_without_contents() {
let mut doc = fixture();
let quads = vec![[20.0, 200.0, 120.0, 200.0, 20.0, 190.0, 120.0, 190.0]];
let highlight = |doc: &mut Document, contents: &str, id: &str| {
let shape = Shape::TextMarkup { kind: Markup::Highlight, quads: quads.clone() };
add_annotation(doc, &NewAnnotation { contents: contents.into(), ..new(0, shape) }, &meta(id)).unwrap()
};
let plain = highlight(&mut doc, "", "h1");
let noted = highlight(&mut doc, "hello", "h2");
let saved = list(&reopen(&doc), 0);
assert_eq!(saved[plain].get(b"Contents"), None, "a highlight without a note");
assert_eq!(text(&saved[noted], b"Contents"), "hello");
// A note opened on it (a double-click) gives it a pop-up; still no text, so still no key.
set_popup(&mut doc, 0, plain, None, Some(true), &meta("h1")).unwrap();
let popup = summaries(&doc).into_iter().find(|s| s.index == plain).unwrap().popup;
assert_eq!(popup.map(|p| p.open), Some(true), "the pop-up is open");
assert_eq!(list(&reopen(&doc), 0)[plain].get(b"Contents"), None, "with an open pop-up");
set_contents(&mut doc, 0, noted, "", &meta("h2")).unwrap();
assert_eq!(list(&reopen(&doc), 0)[noted].get(b"Contents"), None, "its text cleared");
for index in [plain, noted] {
assert_eq!(summaries(&doc).into_iter().find(|s| s.index == index).unwrap().contents, None);
}
}
/// #2137 review: a pop-up that is not the mark's own is neither reported as its pop-up nor
/// changed through it (part of `pop_ups_open_close_and_move_and_are_reported`).
fn foreign_pop_ups_are_not_the_marks(doc: &mut Document, note: ObjRef, mark: usize, mr: ObjRef) {
+9 -5
View File
@@ -190,9 +190,7 @@ proptest! {
}
}
/// Text, author and id survive exactly — including the empty string. `/Contents` is stored even
/// when empty (an empty PDF string), while `/T` and `/NM` follow the crate's emptiness rule:
/// no author or id means the key is not written at all.
/// Nonempty text, author and id survive exactly; empty values omit their corresponding keys.
#[test]
fn text_author_and_id_survive_exactly(contents in text_of(40), author in text_of(16), id in id_of(12)) {
for path in [Save::Incremental, Save::FullTable] {
@@ -204,14 +202,20 @@ proptest! {
prop_assert_eq!(entries.len(), 1, "{}: exactly the one comment", tag(path));
let d = dict_of(&reopened, &entries[0]).expect("one annotation");
let storedcontents = str_of(&reopened, &d, b"Contents");
prop_assert_eq!(storedcontents.as_deref(), Some(contents.as_str()), "{}: /Contents round trip for {:?}", tag(path), contents);
if contents.is_empty() {
prop_assert!(storedcontents.is_none(), "{}: empty text writes no /Contents", tag(path));
prop_assert!(d.get(b"Contents").is_none(), "{}: /Contents key is absent", tag(path));
prop_assert!(bytes::texts_of(&file, "Contents").is_empty(), "{}: no /Contents in the file", tag(path));
} else {
prop_assert_eq!(storedcontents.as_deref(), Some(contents.as_str()), "{}: /Contents round trip for {:?}", tag(path), contents);
prop_assert!(bytes::texts_of(&file, "Contents").contains(&contents), "{:?} must appear in the file as a PDF string", contents);
}
let storedid = str_of(&reopened, &d, b"NM");
if id.is_empty() {
prop_assert!(storedid.is_none(), "{}: an empty id writes no /NM, got {storedid:?}", tag(path));
} else {
prop_assert_eq!(storedid.as_deref(), Some(id.as_str()), "{}: /NM round trip", tag(path));
}
prop_assert!(bytes::texts_of(&file, "Contents").contains(&contents), "{:?} must appear in the file as a PDF string", contents);
if id.is_empty() {
prop_assert!(bytes::texts_of(&file, "NM").is_empty(), "{}: no /NM in the file for an empty id", tag(path));
} else {
+7
View File
@@ -91,6 +91,13 @@ semantics; they never silently act on partial text.
## Shared field properties
`form_add_field_table` accepts `source_field` and the optional 1-based `source_widget` to create
independent copies of an existing text field or check box instead of blank text fields. Each copy
starts with the source's value and properties but has its own name and can be filled independently.
Radio groups, signatures, choice fields, buttons and check boxes whose widgets export different
values are not supported by this option yet. The grid is one undoable edit and any invalid cell or
name refuses the entire operation.
For an individual push button, `form_set_props` also edits its visible normal label:
```json
+1 -1
View File
@@ -614,7 +614,7 @@ impl Automation {
}
/// `out` with `warnings` added to its `warnings` list (made when it has none).
fn with_warnings(mut out: Value, warnings: Vec<String>) -> Value {
pub(crate) fn with_warnings(mut out: Value, warnings: Vec<String>) -> Value {
if warnings.is_empty() {
return out;
}
+44 -5
View File
@@ -173,10 +173,31 @@ impl Automation {
Ok((old, new))
}
fn compare_pages_arg(&self, a: &Args) -> Result<Vec<usize>> {
let Some(raw) = a.opt_ints("pages")? else { return Ok(Vec::new()) };
if raw.is_empty() {
return Err(ToolError::InvalidArgs("pages must list at least one page".into()));
}
let new = self.doc(a)?.id;
let other = a.int("other")?;
let max_pages = [new, u64::try_from(other).ok().and_then(|o| self.session.get(pdfcraft_engine::DocId(o))).map(|d| d.id).unwrap_or(new)]
.iter()
.filter_map(|id| self.session.get(*id))
.map(|d| d.info.pages.len())
.max()
.unwrap_or(0);
let pages = crate::json::one_based(&raw)?;
if let Some(p) = pages.iter().find(|p| **p >= max_pages) {
return Err(ToolError::InvalidArgs(format!("page {} is out of range: the document has {max_pages} pages", p + 1)));
}
Ok(pages)
}
pub(crate) fn doc_compare(&self, a: &Args) -> Result<Value> {
use pdfcraft_engine::compare::Kind;
let (old, new) = self.compare_ids(a)?;
let c = self.session.compare(old, new).map_err(failed)?;
let pages = self.compare_pages_arg(a)?;
let c = self.session.compare_pages(old, new, &pages).map_err(failed)?;
let limit = a.opt_int("limit")?.unwrap_or(500).max(1) as usize;
let r2 = |r: &[f64; 4]| r.map(|v| (v * 100.0).round() / 100.0);
let side =
@@ -188,7 +209,12 @@ impl Automation {
.map(|ch| json!({ "kind": ch.kind.label().to_lowercase(), "old": side(&ch.old), "new": side(&ch.new) }))
.collect();
let visual: Vec<Value> = if a.opt_bool("visual")?.unwrap_or(false) {
self.session.compare_visual(old, new, 72.0).map_err(failed)?.iter().map(|(p, r)| json!({ "page": p + 1, "rect": r2(r) })).collect()
self.session
.compare_visual_on_pages(old, new, 72.0, &pages)
.map_err(failed)?
.iter()
.map(|(p, r)| json!({ "page": p + 1, "rect": r2(r) }))
.collect()
} else {
Vec::new()
};
@@ -206,7 +232,8 @@ impl Automation {
pub(crate) fn doc_compare_report(&self, a: &Args) -> Result<Value> {
let (old, new) = self.compare_ids(a)?;
let bytes = self.session.compare_report(old, new).map_err(failed)?;
let pages = self.compare_pages_arg(a)?;
let bytes = self.session.compare_report_of(old, new, &pages).map_err(failed)?;
let path = self.resolve(a.str("path")?, true)?;
write_atomic(&path, &bytes)?;
Ok(json!({ "path": path.to_string_lossy(), "bytes": bytes.len() }))
@@ -214,7 +241,19 @@ impl Automation {
pub(crate) fn doc_compare_mark(&mut self, a: &Args) -> Result<Value> {
let (old, new) = self.compare_ids(a)?;
let (n, out) = self.session.with_own_js_output(new, |s| s.mark_differences(old, new)).map_err(failed)?;
Ok(with_warnings(json!({ "comments": n }), out.errors))
let pages = self.compare_pages_arg(a)?;
// Mark one page at a time so words that repeat on an earlier page cannot be
// mistaken for the changed words on the page the diff actually touches.
let page_count =
self.session.get(new).map(|d| d.info.pages.len()).unwrap_or(0).max(self.session.get(old).map(|d| d.info.pages.len()).unwrap_or(0));
let targets: Vec<usize> = if pages.is_empty() { (0..page_count).collect() } else { pages };
let mut total = 0usize;
let mut all_errors: Vec<String> = Vec::new();
for page in targets {
let (n, out) = self.session.with_own_js_output(new, |s| s.mark_differences_of(old, new, &[page])).map_err(failed)?;
total += n;
all_errors.extend(out.errors);
}
Ok(with_warnings(json!({ "comments": total }), all_errors))
}
}
+44 -32
View File
@@ -290,6 +290,44 @@ impl Automation {
Ok(json!({ "count": roots.len(), "comments": roots }))
}
/// The text area `find` (the first hit on the page, every one with `all`) or `quads` (page
/// coordinates) names, as quadrilaterals in user space; `None` when neither is given.
fn text_area(&mut self, a: &Args, page: usize, info: &PageInfo) -> Result<Option<Vec<[f64; 8]>>> {
let quads = match (a.opt_str("find")?, a.get("quads")) {
(Some(needle), _) => {
let id = self.doc(a)?.id;
let text = self.page_texts(id, &[page])?.remove(0);
let mut hits = text.find(needle);
if hits.is_empty() {
return Err(failed(format!("{needle:?} was not found on page {}", page + 1)));
}
if !a.opt_bool("all")?.unwrap_or(false) {
hits.truncate(1);
}
hits.into_iter().flat_map(|r| text.line_rects(r)).map(|r| info.view_rect_to_quad(r)).collect()
}
(None, Some(q)) => {
let wrong = || ToolError::InvalidArgs("quads must be arrays of 8 numbers".into());
let quads = q.as_array().ok_or_else(wrong)?;
quads
.iter()
.map(|q| {
let v: Vec<f64> = q.as_array().ok_or_else(wrong)?.iter().map(|x| x.as_f64()).collect::<Option<_>>().ok_or_else(wrong)?;
let v: [f64; 8] = v.try_into().map_err(|_| wrong())?;
let mut out = [0.0; 8];
for i in 0..4 {
let [x, y] = to_user(info, v[2 * i], v[2 * i + 1]);
(out[2 * i], out[2 * i + 1]) = (x, y);
}
Ok(out)
})
.collect::<Result<Vec<_>>>()?
}
(None, None) => return Ok(None),
};
Ok(Some(quads))
}
pub(crate) fn comment_add(&mut self, a: &Args) -> Result<Value> {
let page = self.page(a)?;
let info = self.doc(a)?.info.pages[page].clone();
@@ -312,37 +350,8 @@ impl Automation {
_ => None,
};
let shape = if let Some(markup) = markup {
let quads = match (a.opt_str("find")?, a.get("quads")) {
(Some(needle), _) => {
let id = self.doc(a)?.id;
let text = self.page_texts(id, &[page])?.remove(0);
let mut hits = text.find(needle);
if hits.is_empty() {
return Err(failed(format!("{needle:?} was not found on page {}", page + 1)));
}
if !a.opt_bool("all")?.unwrap_or(false) {
hits.truncate(1);
}
hits.into_iter().flat_map(|r| text.line_rects(r)).map(|r| info.view_rect_to_quad(r)).collect()
}
(None, Some(q)) => {
let wrong = || ToolError::InvalidArgs("quads must be arrays of 8 numbers".into());
let quads = q.as_array().ok_or_else(wrong)?;
quads
.iter()
.map(|q| {
let v: Vec<f64> = q.as_array().ok_or_else(wrong)?.iter().map(|x| x.as_f64()).collect::<Option<_>>().ok_or_else(wrong)?;
let v: [f64; 8] = v.try_into().map_err(|_| wrong())?;
let mut out = [0.0; 8];
for i in 0..4 {
let [x, y] = to_user(&info, v[2 * i], v[2 * i + 1]);
(out[2 * i], out[2 * i + 1]) = (x, y);
}
Ok(out)
})
.collect::<Result<Vec<_>>>()?
}
(None, None) => return Err(ToolError::InvalidArgs(format!("{kind} needs `find` (text to mark) or `quads`"))),
let Some(quads) = self.text_area(a, page, &info)? else {
return Err(ToolError::InvalidArgs(format!("{kind} needs `find` (text to mark) or `quads`")));
};
Shape::TextMarkup { kind: markup, quads }
} else {
@@ -804,6 +813,9 @@ impl Automation {
let (o, d) = (to_user(&info, 0.0, 0.0), to_user(&info, dx, dy));
edits.push(Edit::MoveAnnotation { page, index, dx: d[0] - o[0], dy: d[1] - o[1] });
}
if let Some(quads) = self.text_area(a, page, &info)? {
edits.push(Edit::SetMarkupRange { page, index, quads });
}
if let Some(pts) = a.get("points") {
let wrong = || ToolError::InvalidArgs("points must be an array of [x, y] points (a line's two ends, or every corner)".into());
let points = pts
@@ -819,7 +831,7 @@ impl Automation {
}
if edits.is_empty() {
return Err(ToolError::InvalidArgs(
"nothing to change: pass contents, color, opacity, fill_opacity, text_opacity, width, fill, border_color, border_shape, font_size, rect, move or points".into(),
"nothing to change: pass contents, color, opacity, fill_opacity, text_opacity, width, fill, border_color, border_shape, font_size, rect, move, points, find or quads".into(),
));
}
let edit = if edits.len() == 1 { edits.remove(0) } else { Edit::Batch { label: "Edit comment".into(), edits } };
+6 -5
View File
@@ -1,7 +1,7 @@
use super::error::{Result, ToolError, failed};
use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary, text_style_levels};
use super::paths::{read_input, write_atomic};
use super::{Arc, Automation, Edit, Value, block_overlapping, comments, content, json, tools};
use super::{Arc, Automation, Edit, Value, a11y, block_overlapping, comments, content, json, tools};
/// One piece of a tool's result.
#[derive(Clone, Debug, PartialEq)]
@@ -139,13 +139,13 @@ impl Automation {
Some(m) => pdfcraft_engine::camera_clean::Look::from_name(m)
.ok_or_else(|| ToolError::InvalidArgs(format!("unknown mode {m:?} (original, colour, greyscale, bw)")))?,
};
self.session.enhance_camera_page_at(id, page, corners, look, level).map_err(failed)?;
let ((), own) = self.session.with_own_js_output(id, |s| s.enhance_camera_page_at(id, page, corners, look, level)).map_err(failed)?;
let r = |v: f32| (v * 100.0).round() / 100.0;
let used: Vec<f32> = corners.iter().flat_map(|&[x, y]| info.user_to_view(x as f32, y as f32)).map(r).collect();
let mut out = summary(self.doc(&a)?);
out["corners"] = json!(used);
out["detected"] = json!(given.is_none());
out
a11y::with_warnings(out, own.errors)
}
"page_enhance_scan" => self.page_enhance_scan(&a)?,
"page_delete" => {
@@ -750,6 +750,7 @@ impl Automation {
"form_add_field" => self.form_add_field(&a)?,
"form_add_field_table" => self.form_add_field_table(&a)?,
"form_set_props" => self.form_set_props(&a)?,
"form_copy_field" => self.form_copy_field(&a)?,
"form_delete_field" => self.form_delete_field(&a)?,
"form_tab_order" => self.form_tab_order(&a)?,
"form_calculation_order" => self.form_calculation_order(&a)?,
@@ -1037,7 +1038,7 @@ impl Automation {
settings.despeckle = on;
}
let id = self.doc(a)?.id;
let report = self.session.enhance_scanned_pages(id, &pages, settings).map_err(failed)?;
let (report, own) = self.session.with_own_js_output(id, |s| s.enhance_scanned_pages(id, &pages, settings)).map_err(failed)?;
let numbered = |p: &[usize]| p.iter().map(|p| p + 1).collect::<Vec<_>>();
let skipped: Vec<Value> = report.skipped.iter().map(|k| json!({ "pages": numbered(&k.pages), "name": k.name, "reason": k.reason })).collect();
let mut out = summary(self.doc(a)?);
@@ -1045,6 +1046,6 @@ impl Automation {
out["images"] = json!(report.images);
out["not_scanned"] = json!(numbered(&report.not_scanned));
out["skipped"] = json!(skipped);
Ok(out)
Ok(a11y::with_warnings(out, own.errors))
}
}
+41 -4
View File
@@ -547,12 +547,31 @@ impl Automation {
table.column_gap = a.opt_num("column_gap")?.unwrap_or(0.0);
table.first_row = a.opt_int("first_row")?.map_or(1, |n| usize::try_from(n).unwrap_or(usize::MAX));
let info = doc.info.pages.get(page).ok_or_else(|| bad(format!("page {} does not exist", page + 1)))?;
let edit = field_table::edit(&table, page, info, &doc.form).map_err(|e| bad(e.to_string()))?;
let edit = if let Some(source) = a.opt_str("source_field")? {
let widget = a.opt_int("source_widget")?.unwrap_or(1);
let widget = usize::try_from(widget).ok().and_then(|n| n.checked_sub(1)).ok_or_else(|| bad("source_widget must be at least 1"))?;
let field = doc.form.iter().find(|f| f.name == source).ok_or_else(|| bad(format!("field {source:?} does not exist")))?;
if field.widgets.get(widget).is_none() {
return Err(bad("source_widget does not exist"));
}
// `copy_edit` refuses, with the reason, a field `field_table::copyable` says no to.
field_table::copy_edit(&table, page, info, &doc.form, source, widget).map_err(|e| bad(e.to_string()))?
} else {
if a.get("source_widget").is_some() {
return Err(bad("source_widget requires source_field"));
}
field_table::edit(&table, page, info, &doc.form).map_err(|e| bad(e.to_string()))?
};
// The names the batch adds, in the order it adds them.
let fields: Vec<String> = match &edit {
Edit::Batch { edits, .. } => {
edits.iter().filter_map(|e| if let Edit::AddField { name, .. } = e { name.clone() } else { None }).collect()
}
Edit::Batch { edits, .. } => edits
.iter()
.filter_map(|e| match e {
Edit::AddField { name, .. } => name.clone(),
Edit::CopyField { name, .. } => Some(name.clone()),
_ => None,
})
.collect(),
_ => Vec::new(),
};
(edit, fields)
@@ -861,6 +880,24 @@ impl Automation {
Ok(json!(names))
}
pub(crate) fn form_copy_field(&mut self, a: &Args) -> Result<Value> {
let page = self.page(a)?;
let doc = self.doc(a)?;
let name = a.str("field")?.to_owned();
if !doc.form.iter().any(|f| f.name == name) {
return Err(failed(format!("there is no field named {name:?} (see form_fields)")));
}
let (dx, dy) = (a.opt_num("dx")?.unwrap_or(0.0), a.opt_num("dy")?.unwrap_or(0.0));
// Points right and down on the displayed page → a move in user space.
let p = doc.info.pages.get(page).ok_or_else(|| failed(format!("page {} does not exist", page + 1)))?;
let (o, m) = (p.view_to_user_f64(0.0, 0.0), p.view_to_user_f64(dx, dy));
let offset = [m[0] - o[0], m[1] - o[1]];
let before: Vec<String> = doc.form.iter().map(|f| f.name.clone()).collect();
let mut out = self.apply(a, Edit::PasteField { name, widgets: Vec::new(), page, offset })?;
out["field"] = json!(self.doc(a)?.form.iter().map(|f| &f.name).find(|n| !before.contains(n)));
Ok(out)
}
pub(crate) fn form_delete_field(&mut self, a: &Args) -> Result<Value> {
let name = a.str("field")?.to_owned();
if !self.doc(a)?.form.iter().any(|f| f.name == name) {
+17 -2
View File
@@ -51,7 +51,17 @@ impl Automation {
pub(crate) fn measurement_list(&self, a: &Args) -> Result<Value> {
let doc = self.doc(a)?;
let all = doc.measurements().map_err(failed)?;
let only = a.opt_int("page")?.map(|n| usize::try_from(n.max(1).saturating_sub(1)).unwrap_or(usize::MAX));
let only = match a.opt_int("page")? {
Some(n) => {
let n = u64::try_from(n).ok().filter(|n| *n >= 1).ok_or_else(|| ToolError::InvalidArgs("page must be 1 or more".into()))?;
let pages = doc.info.pages.len() as u64;
if n > pages {
return Err(ToolError::InvalidArgs(format!("page {n} is out of range: the document has {pages} pages")));
}
Some((n - 1) as usize)
}
None => None,
};
let measurements: Vec<Value> = all
.measurements
.iter()
@@ -128,6 +138,12 @@ impl Automation {
pub(crate) fn measurement_snap(&self, a: &Args) -> Result<Value> {
let page = self.page(a)?;
let at = a.nums::<2>("at")?.ok_or_else(|| failed("snapping needs at"))?;
// Reject a bad tolerance before the page's geometry is extracted: it is the argument
// that decides how much of it is read.
let tolerance = a.opt_num("tolerance")?.unwrap_or(6.0);
if !tolerance.is_finite() || !(0.0..=10_000.0).contains(&tolerance) {
return Err(ToolError::InvalidArgs("tolerance must be finite, 0 or more, and no more than 10000 points".into()));
}
let [x, y] = self.doc(a)?.measurement_to_user(page, at).map_err(failed)?;
let geometry = self.doc(a)?.measurement_paths(page).map_err(failed)?;
let options = measure::snap::SnapOptions {
@@ -136,7 +152,6 @@ impl Automation {
intersections: a.opt_bool("intersections")?.unwrap_or(true),
paths: a.opt_bool("paths")?.unwrap_or(true),
};
let tolerance = a.opt_num("tolerance")?.unwrap_or(6.0);
let adjacent = self.doc(a)?.measurement_to_user(page, [at[0] + tolerance, at[1]]).map_err(failed)?;
let tolerance = measure::distance([x, y], adjacent);
let intersection_limited = options.intersections && geometry.intersection_limited([x, y], tolerance);
+16 -6
View File
@@ -599,7 +599,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"form_add_field_table",
"Prepare form: add a table of text fields",
"Divide rect into rows and columns of text fields, one per cell, as one undo step. rect in points from the top-left of the displayed page [x0, y0, x1, y1]; rows 1-100 from the top; columns 1-50, or as many as names or widths list. Each column names its cells from its pattern in names: an N on its own after _ - / or : (price_N), # or {row} is the row number, {col} the column number, {seq} counts every cell along the rows, starting at first_row; with none of them the row number goes at the end. Rows count from first_row (default 1). Without names the columns are Table1_N, Table1_c2_N, … using the first free TableK. widths are relative (default equal); row_gap and column_gap are points between cells (default 0). Nothing is added if a cell would be under 4 points or a name would contain a period, repeat, or already exist; the error says which. Returns the fields' names. Undoable.",
"Divide rect into rows and columns of fields, one per cell, as one undo step. By default these are new text fields; source_field copies an existing text field or check box with its properties and value into independent fields. rect in points from the top-left of the displayed page [x0, y0, x1, y1]; rows 1-100 from the top; columns 1-50, or as many as names or widths list. Each column names its cells from its pattern in names: an N on its own after _ - / or : (price_N), # or {row} is the row number, {col} the column number, {seq} counts every cell along the rows, starting at first_row; with none of them the row number goes at the end. Rows count from first_row (default 1). Without names the columns are Table1_N, Table1_c2_N, … using the first free TableK. widths are relative (default equal); row_gap and column_gap are points between cells (default 0). Nothing is added if a cell would be under 4 points or a name would contain a period, repeat, or already exist; the error says which. Returns the fields' names. Undoable.",
)
.cmd("form.add.text_table")
.with(schema(
@@ -614,6 +614,8 @@ pub fn tools() -> Vec<ToolDef> {
"row_gap": { "type": "number", "minimum": 0 },
"column_gap": { "type": "number", "minimum": 0 },
"first_row": { "type": "integer", "minimum": 0, "maximum": 99999 },
"source_field": { "type": "string", "description": "Copy this existing text field or check box into each cell instead of creating blank text fields." },
"source_widget": { "type": "integer", "minimum": 1, "description": "1-based widget of source_field (default 1)." },
}),
&["doc", "page", "rect", "rows"],
)),
@@ -700,6 +702,11 @@ pub fn tools() -> Vec<ToolDef> {
.with(schema(json!({ "doc": doc(), "path": { "type": "string" }, "what": { "type": "string", "enum": ["all", "comments", "fields"] } }), &["doc", "path"])),
t("doc_import_data", "Import comments or form data", "Import comments and/or field values from an XFDF, FDF, XML, CSV or tab-delimited text file (detected from its content), or the comments of another PDF, each onto the page with the same number (comments on pages past this document's last page are left out). Comments with the same name are replaced; values go through the form's formats and validation. For an XFA form, an XDP, datasets or data XML file replaces the form's data: a laid-out form is laid out again from it (rows included) and its calculations run. Undoable. The result lists in `import_repairs` what this import left out (values the form refused, comments taken without their appearance); the import fails instead only when the form refuses every value and no comment is taken.")
.with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
t("form_copy_field", "Copy and paste a field", "Prepare form ▸ copy and paste: a new field of its own (its own name and value) with the field's type, flags, options, value, appearance and actions, on page, moved by dx and dy (points right and down on the displayed page, default 0). Every widget of the field is copied; a signature's value is not. Returns the new field's name (the next free one: Check Box1 → Check Box2). Undoable.")
.with(schema(
json!({ "doc": doc(), "field": { "type": "string" }, "page": { "type": "integer", "minimum": 1 }, "dx": { "type": "number" }, "dy": { "type": "number" } }),
&["doc", "field", "page"],
)),
t("form_delete_field", "Delete a field", "Delete a form field and all its widgets, or with widget only that one: one radio button of a group (widget n is the nth of the radio group's options in form_fields), or one copy of a duplicated field. A field's last widget takes the field with it. Undoable.")
.destructive()
.with(schema(json!({ "doc": doc(), "field": { "type": "string" }, "widget": { "type": "integer", "minimum": 1, "description": "Delete only this widget (1-based)." } }), &["doc", "field"])),
@@ -1128,7 +1135,7 @@ pub fn tools() -> Vec<ToolDef> {
json!({ "doc": doc(), "sort": { "type": "string", "enum": ["page", "author", "date", "type"] }, "out": save_out, "open": open }),
&["doc"],
)),
t("comment_edit", "Edit a comment", "Change a comment's text, colour, opacity (the whole comment's, or its fill's and text's own), line width, font size (text box/typewriter/callout), fill (rectangle/oval/polygon/text box/callout; \"none\" removes it), border colour (`border_color`, text box/typewriter/callout; \"text\" gives it the text's colour again), rectangle (rectangle/oval/text box/stamp, or a callout's text box: its arrow point stays and its leader line re-attaches), position (`move` [dx, dy] in points) or shape (`points`: a line's two ends, the corners of connected lines, a polygon or a cloud, or a callout's arrow point and knee, as comment_list gives them). Stamps keep their original appearance when resized. One undo step.").with(schema(
t("comment_edit", "Edit a comment", "Change a comment's text, colour, opacity (the whole comment's, or its fill's and text's own), line width, font size (text box/typewriter/callout), fill (rectangle/oval/polygon/text box/callout; \"none\" removes it), border colour (`border_color`, text box/typewriter/callout; \"text\" gives it the text's colour again), rectangle (rectangle/oval/text box/stamp, or a callout's text box: its arrow point stays and its leader line re-attaches), position (`move` [dx, dy] in points) or shape (`points`: a line's two ends, the corners of connected lines, a polygon or a cloud, or a callout's arrow point and knee, as comment_list gives them), or, for a highlight, underline, strikethrough or squiggly underline, the text it marks (`find`: text on the page, the first match or every match with `all`; or `quads`), which extends or reduces it and keeps its colour and replies. Stamps keep their original appearance when resized. One undo step.").with(schema(
comment_ref(json!({
"contents": { "type": "string" },
"color": color(),
@@ -1143,6 +1150,9 @@ pub fn tools() -> Vec<ToolDef> {
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
"move": point(),
"points": { "type": "array", "items": point(), "minItems": 1, "description": "A line's two ends, every corner of connected lines, a polygon or a cloud, or a callout's arrow point and (optionally) knee, in page coordinates. A callout given its arrow point alone keeps the knee it has." },
"find": { "type": "string", "description": "Highlight, underline, strikethrough or squiggly underline only: the text on the page (case-insensitive) it now marks, in place of what it marked." },
"all": { "type": "boolean", "description": "With `find`: mark every match on the page, not just the first." },
"quads": { "type": "array", "items": { "type": "array", "items": { "type": "number" }, "minItems": 8, "maxItems": 8 }, "description": "Highlight, underline, strikethrough or squiggly underline only: the text area it now marks, a quadrilateral per line, in page coordinates." },
})),
&["doc"],
)),
@@ -1527,13 +1537,13 @@ pub fn tools() -> Vec<ToolDef> {
t("doc_compare", "Compare files", "Compare the text of two open documents: other is the older version, doc the newer. Returns counts and each change (replaced, inserted, deleted) with the old and new text, pages (1-based) and rectangles (points, origin bottom-left).")
.ro()
.cmd("doc.compare")
.with(schema(json!({ "doc": doc(), "other": { "type": "integer", "description": "The older document (from doc_open)." }, "limit": { "type": "integer", "minimum": 1, "description": "List at most this many changes (default 500)." }, "visual": { "type": "boolean", "description": "Also compare how pages look (page n with page n): regions that differ visually." } }), &["doc", "other"])),
.with(schema(json!({ "doc": doc(), "other": { "type": "integer", "description": "The older document (from doc_open)." }, "pages": pages("to compare (default: all)"), "limit": { "type": "integer", "minimum": 1, "description": "List at most this many changes (default 500)." }, "visual": { "type": "boolean", "description": "Also compare how pages look (page n with page n): regions that differ visually." } }), &["doc", "other"])),
t("doc_compare_report", "Compare report", "Write the compare summary report (a PDF listing every change) to path.")
.cmd("doc.compare")
.with(schema(json!({ "doc": doc(), "other": { "type": "integer" }, "path": { "type": "string" } }), &["doc", "other", "path"])),
t("doc_compare_mark", "Mark differences as comments", "Add the differences from other (older) to doc (newer) as comments in doc: highlights over replaced (blue) and inserted (green) text, notes where text was deleted (red), authored Compare. Undoable.")
.with(schema(json!({ "doc": doc(), "other": { "type": "integer" }, "path": { "type": "string" }, "pages": pages("to compare (default: all)") }), &["doc", "other", "path"])),
t("doc_compare_mark", "Mark differences as comments", "Add the differences from other (older) to doc (newer) as comments in doc: highlights over replaced (blue) and inserted (green) text, notes where text was deleted (red), authored Compare. Undoable, one undo step per page marked.")
.cmd("doc.compare")
.with(schema(json!({ "doc": doc(), "other": { "type": "integer" } }), &["doc", "other"])),
.with(schema(json!({ "doc": doc(), "other": { "type": "integer" }, "pages": pages("to compare (default: all)") }), &["doc", "other"])),
t("form_detect_fields", "Detect form fields", "Prepare a form ▸ automatic field detection: find the blanks a printed form asks to be filled (underscore runs, lines, empty boxes, rows of comb boxes, small squares for check boxes; on scanned pages read from the pixels) and name each field from its label. With add (default true) the fields are created as one undoable step; otherwise they are only proposed. Returns page (1-based), kind, name and rect (points, origin bottom-left); a row of comb boxes is one text field with comb set to its number of cells, created with the comb flag and that character limit.")
.cmd("form.detect")
.with(schema(json!({ "doc": doc(), "pages": pages("to look at (default: all)"), "add": { "type": "boolean" } }), &["doc"])),
+374
View File
@@ -640,6 +640,89 @@ fn autotag_apply_writes_reviewable_tags_and_survives_save_reopen() {
assert!(pages.iter().all(|page| page.dict.contains(b"StructParents")));
}
/// #7416: the text state a PDFCraft text edit writes after its text object (`0 Tc`, `0 Tw`,
/// `100 Tz`, `0 TL`, `0 Ts`) is legal outside BT/ET and must not stop Auto-tag.
#[test]
fn autotag_apply_accepts_text_state_written_by_a_text_edit() {
let dir = workdir("autotag-after-edit");
let page = |text: &str| format!("BT /FR 12 Tf 1 0 0 1 40 180 Tm ({text}) Tj ET");
std::fs::write(dir.join("moss.pdf"), bold_and_regular_pdf(&page("Moss stays green."), &page("Quiet control page."))).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "moss.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "text": "Fern stays green." }));
let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc }));
assert_eq!(applied["count"], 3, "Document plus one paragraph per page");
assert_eq!(applied["tags"][1]["type"], "P");
std::fs::remove_dir_all(dir).unwrap();
}
/// #7416: a wrapped edit in the repo font (Helvetica, no /Encoding) writes `/PCSoft BDC EMC` between
/// its lines inside the text object; Auto-tag takes it, keeps it in the stream inside the
/// paragraph's mark. (The `/Span` + `/ActualText` form is covered in the a11y tests.)
#[test]
fn autotag_apply_accepts_line_markers_written_by_a_text_edit() {
let dir = workdir("autotag-after-edit-span");
std::fs::write(dir.join("one.pdf"), fixture(1)).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "one.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "text": "Fern stays green." }));
let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc }));
assert_eq!(applied["count"], 2, "Document plus the edited paragraph");
assert_eq!(applied["tags"][1]["type"], "P");
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "tagged.pdf" }));
let re = ok(&mut a, "doc_open", json!({ "path": "tagged.pdf" }))["doc"].as_u64().unwrap();
assert_eq!(page_text(&mut a, re), ["Fern stays\ngreen."]);
let content = page_content(&dir.join("tagged.pdf"));
assert!(content.find("/MCID").unwrap() < content.find("/PCSoft").unwrap(), "the line marker stays inside the paragraph's mark: {content}");
std::fs::remove_dir_all(dir).unwrap();
}
/// #7416: a typed newline, mixed styles and text the font cannot show take the editor's rich path, which writes `/P BMC`,
/// `/PCHard BMC` and `/Span` marks between and around its text objects; Auto-tag takes them too.
#[test]
fn autotag_apply_accepts_a_newline_and_mixed_style_edit() {
for (name, edit) in [
("newline", json!({ "text": "a\nb" })),
("fallback", json!({ "text": "Fern \u{3a9} stays" })),
("ranges", json!({ "text": "Fern stays", "ranges": [{ "range": [0, 4], "size": 16, "color": "#cc0000" }] })),
] {
let dir = workdir(&format!("autotag-rich-{name}"));
std::fs::write(dir.join("one.pdf"), fixture(1)).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "one.pdf" }))["doc"].as_u64().unwrap();
let mut args = json!({ "doc": doc, "page": 1, "paragraph": 1 });
args.as_object_mut().unwrap().extend(edit.as_object().unwrap().clone());
ok(&mut a, "text_edit", args);
let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc }));
assert_eq!(applied["tags"][1]["type"], "P", "{name}");
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "tagged.pdf" }));
let content = page_content(&dir.join("tagged.pdf"));
assert!(content.contains("/MCID"), "{name}: {content}");
let (begins, ends) = (content.matches("BDC").count() + content.matches("BMC").count(), content.matches("EMC").count());
assert_eq!(begins, ends, "{name}: marks stay balanced: {content}");
std::fs::remove_dir_all(dir).unwrap();
}
}
/// The decoded content stream of the first page of the PDF at `path`.
fn page_content(path: &Path) -> String {
let doc = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(path).unwrap())).unwrap();
let page = &pdfcraft_model::pages(&doc)[0];
let contents = doc.resolve(page.dict.get(b"Contents").unwrap());
let streams = match &*contents {
pdfcraft_cos::Object::Array(items) => items.iter().map(|i| doc.resolve(i)).collect(),
_ => vec![contents.clone()],
};
streams
.iter()
.filter_map(|s| match &**s {
pdfcraft_cos::Object::Stream(s) => Some(String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
/// #7062: Apply tags short text larger than the body as headings, ranked across the pages, and
/// the body text as paragraphs.
#[test]
@@ -2842,6 +2925,80 @@ fn freehand_highlight_through_tools() {
assert_eq!(ok(&mut a, "comment_list", json!({ "doc": doc }))["count"], 0);
}
/// #4824: a highlight's range is changed through `comment_edit` (`find` or `quads`), keeping its
/// colour, contents and replies, in one undo step; other comments and misses are refused.
#[test]
fn a_markups_marked_text_can_be_changed() {
let dir = workdir("markup-range");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let hl = ok(
&mut a,
"comment_add",
json!({ "doc": doc, "page": 2, "type": "highlight", "find": "page 2", "contents": "check", "author": "Ada", "color": "#FF8800" }),
);
let id = hl["comment"]["id"].as_str().unwrap().to_string();
ok(&mut a, "comment_reply", json!({ "doc": doc, "id": id, "text": "ok", "author": "Bob" }));
let note = ok(&mut a, "comment_add", json!({ "doc": doc, "page": 2, "type": "note", "at": [150, 20], "contents": "Sticky" }))["comment"]["id"]
.as_str()
.unwrap()
.to_string();
let get = |a: &mut Automation, id: &str| -> Value {
let list = ok(a, "comment_list", json!({ "doc": doc }));
list["comments"].as_array().unwrap().iter().find(|c| c["id"] == id).unwrap().clone()
};
let width = |c: &Value| c["rect"][2].as_f64().unwrap() - c["rect"][0].as_f64().unwrap();
let whole = get(&mut a, &id);
// Reduced to the word "Page", then extended back to "Page 2".
ok(&mut a, "comment_edit", json!({ "doc": doc, "id": id, "find": "Page" }));
let word = get(&mut a, &id);
assert!(width(&word) < width(&whole) - 1.0, "{word} vs {whole}");
assert_eq!((word["color"].as_str(), word["contents"].as_str()), (whole["color"].as_str(), Some("check")));
assert_eq!(word["replies"].as_array().unwrap().len(), 1, "the reply stays");
ok(&mut a, "comment_edit", json!({ "doc": doc, "id": id, "find": "page 2" }));
assert_eq!(get(&mut a, &id)["rect"], whole["rect"]);
// By quadrilaterals in page coordinates, with another property in the same edit.
ok(&mut a, "comment_edit", json!({ "doc": doc, "id": id, "quads": [[20, 140, 60, 140, 20, 156, 60, 156]], "opacity": 0.5 }));
let by_quad = get(&mut a, &id);
assert!(width(&by_quad) < width(&whole) - 1.0, "{by_quad}");
// One undo step puts the last range back.
ok(&mut a, "edit_undo", json!({ "doc": doc }));
assert_eq!(get(&mut a, &id)["rect"], whole["rect"]);
// Refused: a comment with no text range, text that is not on the page, and nothing changes.
assert!(a.call("comment_edit", &json!({ "doc": doc, "id": note, "find": "Page" })).is_err());
assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "id": id, "find": "nowhere" })), Err(ToolError::Failed(_))));
assert_eq!(get(&mut a, &id)["rect"], whole["rect"]);
}
/// A bad range in a compound comment edit keeps the annotation, document bytes and undo
/// history, even when another property was queued before its invalid geometry.
#[test]
fn comment_edit_rejects_zero_area_quads_without_changing_the_document() {
let dir = workdir("markup-zero-area");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let id = ok(&mut a, "comment_add", json!({ "doc": doc, "page": 2, "type": "highlight", "find": "Page 2", "contents": "keep" }))["comment"]["id"]
.as_str()
.unwrap()
.to_owned();
let before = ok(&mut a, "comment_list", json!({ "doc": doc }));
let bytes = a.session().get(pdfcraft_engine::DocId(doc)).unwrap().bytes.clone();
let undo = a.session().get(pdfcraft_engine::DocId(doc)).unwrap().can_undo().map(str::to_owned);
let valid = json!([20, 140, 60, 140, 20, 156, 60, 156]);
// Quarter-page coordinates keep the diagonal exactly collinear through the view's f32 transform.
for quads in [json!([[0, 0, 0, 0, 0, 0, 0, 0]]), json!([[0, 0, 50, 75, 100, 150, 150, 225]]), json!([valid, [0, 0, 0, 0, 0, 0, 0, 0]])] {
let result = a.call("comment_edit", &json!({ "doc": doc, "id": id, "contents": "discard", "quads": quads }));
assert!(result.is_err(), "zero-area range was accepted: {quads}: {result:?}");
assert_eq!(ok(&mut a, "comment_list", json!({ "doc": doc })), before);
let current = a.session().get(pdfcraft_engine::DocId(doc)).unwrap();
assert_eq!(current.bytes.as_ref(), bytes.as_ref(), "the entire compound edit was refused");
assert_eq!(current.can_undo().map(str::to_owned), undo, "no undo step was added");
}
ok(&mut a, "comment_edit", json!({ "doc": doc, "id": id, "find": "Page" }));
ok(&mut a, "edit_undo", json!({ "doc": doc }));
assert_eq!(ok(&mut a, "comment_list", json!({ "doc": doc })), before, "valid edits still undo to the original markup");
}
fn add_comment_examples(a: &mut Automation, doc: u64) -> String {
// "Page 2" sits at y = 150 (user space) = 150 from the top of the 300 pt page.
let hl = ok(a, "comment_add", json!({ "doc": doc, "page": 2, "type": "highlight", "find": "page 2", "contents": "check", "author": "Ada" }));
@@ -6247,6 +6404,56 @@ fn adding_a_field_table_through_tools() {
assert_eq!(count(&mut a), 8, "one undo takes back the whole last table");
}
#[test]
fn copying_a_field_into_a_grid_through_tools() {
let dir = workdir("copy-field-grid");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({"path": "a.pdf"}))["doc"].as_u64().unwrap();
ok(&mut a, "form_add_field", json!({"doc": doc, "page": 1, "type": "text", "name": "source", "rect": [20, 20, 180, 50], "multiline": true}));
ok(&mut a, "form_fill", json!({"doc": doc, "values": {"source": "initial"}}));
let args = json!({"doc": doc, "page": 1, "rect": [20, 70, 180, 150], "rows": 2, "names": ["copy_N"], "source_field": "source"});
assert_eq!(ok(&mut a, "form_add_field_table", args.clone())["fields"], json!(["copy_1", "copy_2"]));
ok(&mut a, "form_fill", json!({"doc": doc, "values": {"copy_1": "changed"}}));
let result = ok(&mut a, "form_fields", json!({"doc": doc}));
let fields = result["fields"].as_array().unwrap();
let get = |name: &str| fields.iter().find(|f| f["name"] == name).unwrap();
assert_eq!(get("source")["value"], "initial");
assert_eq!(get("copy_1")["value"], "changed");
assert_eq!(get("copy_2")["value"], "initial");
assert_eq!(get("copy_1")["multiline"], true);
assert_eq!(get("copy_2")["multiline"], true);
ok(&mut a, "edit_undo", json!({"doc": doc})); // undo the fill
ok(&mut a, "edit_undo", json!({"doc": doc})); // undo the complete grid
let result = ok(&mut a, "form_fields", json!({"doc": doc}));
assert_eq!(result["fields"].as_array().unwrap().len(), 1);
}
#[test]
fn copying_into_a_grid_refuses_what_it_cannot_copy() {
let dir = workdir("copy-field-grid-refusals");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({"path": "a.pdf"}))["doc"].as_u64().unwrap();
ok(&mut a, "form_add_field", json!({"doc": doc, "page": 1, "type": "text", "name": "source", "rect": [20, 20, 180, 50]}));
ok(&mut a, "form_add_field", json!({"doc": doc, "page": 1, "type": "radio", "rect": [20, 100, 34, 114], "group": "size", "export": "S"}));
ok(&mut a, "form_add_field", json!({"doc": doc, "page": 1, "type": "radio", "rect": [40, 100, 54, 114], "group": "size", "export": "L"}));
let grid = |extra: Value| {
let mut args = json!({"doc": doc, "page": 1, "rect": [20, 150, 180, 230], "rows": 2});
args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
args
};
let refused = |a: &mut Automation, extra: Value, says: &str| match err(a, "form_add_field_table", grid(extra.clone())) {
ToolError::InvalidArgs(m) => assert!(m.contains(says), "{extra}: {m}"),
other => panic!("{extra}: expected InvalidArgs, got {other:?}"),
};
refused(&mut a, json!({"source_widget": 1}), "source_widget requires source_field");
refused(&mut a, json!({"source_field": "nowhere"}), "\"nowhere\" does not exist");
refused(&mut a, json!({"source_field": "size"}), "can't be copied into a grid");
refused(&mut a, json!({"source_field": "source", "source_widget": 0}), "source_widget must be at least 1");
refused(&mut a, json!({"source_field": "source", "source_widget": 2}), "source_widget does not exist");
// Each was refused before anything was added.
assert_eq!(ok(&mut a, "form_fields", json!({"doc": doc}))["fields"].as_array().unwrap().len(), 2);
}
#[test]
fn redact_mark_respects_single_page_and_rejects_conflicting_selectors() {
let dir = workdir("redact-single-page");
@@ -10505,6 +10712,50 @@ fn comparing_documents_through_tools() {
/// `action_list` and `action_run`: built-in actions by name and ad-hoc steps run on files,
/// missing inputs are reported per file, and an unknown step is refused.
#[test]
fn compare_pages_limits_text_comparison() {
let dir = workdir("compare-pages");
let mut a = auto(&dir);
let v1 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "First page alpha\u{c}Second page 900" }))["doc"].as_u64().unwrap();
let v2 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "First page beta\u{c}Second page 950" }))["doc"].as_u64().unwrap();
let pages = page_text(&mut a, v2);
assert_eq!(pages.len(), 2, "{pages:?}");
// Scoping the comparison to page 2 alone must report only the 950 change on page 2,
// not the page 1 alpha/beta change. old_words/new_words are the scoped
// counts for page 2 alone ("Second page 900" / "Second page 950" = 3 words each).
let r = ok(&mut a, "doc_compare", json!({ "doc": v2, "other": v1, "pages": [2], "visual": true }));
assert_eq!((r["replaced"].as_u64(), r["inserted"].as_u64(), r["deleted"].as_u64()), (Some(1), Some(0), Some(0)), "{r}");
assert_eq!(r["changes"].as_array().unwrap().len(), 1, "{r}");
assert_eq!(r["changes"][0]["old"]["text"], "900", "{r}");
assert_eq!(r["changes"][0]["new"]["text"], "950", "{r}");
assert_eq!(r["changes"][0]["new"]["page"], 2, "{r}");
assert_eq!((r["old_words"].as_u64(), r["new_words"].as_u64()), (Some(3), Some(3)), "{r}");
assert!(r["visual"].as_array().unwrap().iter().all(|v| v["page"] == 2), "{r}");
// Scoping to page 1 alone must report only the alpha/beta change, with the
// page 1 word counts ("First page alpha" / "First page beta").
let r = ok(&mut a, "doc_compare", json!({ "doc": v2, "other": v1, "pages": [1] }));
assert_eq!(r["changes"].as_array().unwrap().len(), 1, "{r}");
assert_eq!(r["changes"][0]["new"]["page"], 1, "{r}");
assert_eq!((r["old_words"].as_u64(), r["new_words"].as_u64()), (Some(3), Some(3)), "{r}");
// A deletion present only on the old document's page 2 keeps that page on
// both sides, so it can be marked in the new document.
let v3 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "First page alpha\u{c}Second page 900" }))["doc"].as_u64().unwrap();
let v4 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "First page alpha\u{c}" }))["doc"].as_u64().unwrap();
let r = ok(&mut a, "doc_compare", json!({ "doc": v4, "other": v3, "pages": [2] }));
assert!(!r["changes"].as_array().unwrap().is_empty(), "{r}");
assert!(r["changes"].as_array().unwrap().iter().all(|ch| ch["old"]["page"] == 2 && ch["new"]["page"] == 2), "{r}");
}
#[test]
fn doc_compare_mark_rejects_an_empty_pages_array() {
let dir = workdir("compare-mark-empty-pages");
let mut a = auto(&dir);
let v1 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "Rent is 900 per month." }))["doc"].as_u64().unwrap();
let v2 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "Rent is 950 per month." }))["doc"].as_u64().unwrap();
let refused = a.call("doc_compare_mark", &json!({ "doc": v2, "other": v1, "pages": [] }));
assert!(matches!(refused, Err(ToolError::InvalidArgs(_))), "{refused:?}");
}
#[test]
fn actions_through_tools() {
let dir = workdir("actions");
@@ -11627,10 +11878,26 @@ fn measurements_bad_arguments_leave_document_and_history_unchanged() {
("measure_scale", json!({"doc":doc,"page":1,"points":[[0,0],[0,0]],"distance":10})),
("measure_snap", json!({"doc":doc,"page":1,"at":[1e100,0]})),
("measure_scale", json!({"doc":doc,"page":1,"units_per_point":1,"precision":8})),
// A page filter is a page number, not a clamp: 0 and past the end are mistakes.
("measure_list", json!({"doc":doc,"page":0})),
("measure_list", json!({"doc":doc,"page":-1})),
("measure_list", json!({"doc":doc,"page":4})),
// Snapping cannot reach a negative distance, and a huge tolerance would collect every path.
("measure_snap", json!({"doc":doc,"page":1,"at":[1,1],"tolerance":-1})),
("measure_snap", json!({"doc":doc,"page":1,"at":[1,1],"tolerance":1e10})),
("measure_snap", json!({"doc":doc,"page":1,"at":[1,1],"tolerance":10001})),
] {
assert!(a.call(tool, &args).is_err(), "{tool} {args}");
assert_eq!(ok(&mut a, "doc_list", json!({})), before);
}
// The valid forms still read and snap.
assert_eq!(ok(&mut a, "measure_list", json!({"doc":doc,"page":1}))["count"], 0);
assert!(ok(&mut a, "measure_snap", json!({"doc":doc,"page":1,"at":[1,1],"tolerance":0}))["snap"].is_null());
// The public schema and the handler agree on the same 10000-point bound, which is also the
// measure layer's own limit: 10000 is accepted, 10001 refused.
let snap = tools().into_iter().find(|t| t.name == "measure_snap").unwrap();
assert_eq!(snap.input_schema["properties"]["tolerance"]["maximum"], 10_000);
assert!(ok(&mut a, "measure_snap", json!({"doc":doc,"page":1,"at":[1,1],"tolerance":10000}))["snap"].is_null());
let _ = std::fs::remove_dir_all(dir);
}
@@ -11748,6 +12015,60 @@ fn edits_report_the_xfa_data_they_could_not_write_once() {
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn enhance_camera_image_reports_the_xfa_data_it_could_not_write_once() {
let dir = workdir("xfa-camera-warnings");
// The data holds structured content where the price goes, so its value can't be written.
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
"</xdp:xdp>",
"<xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data><form><page1><price><p>7</p></price></page1></form></xfa:data></xfa:datasets>\n</xdp:xdp>",
);
std::fs::write(dir.join("data.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "data.pdf" }))["doc"].as_u64().unwrap();
let structured = |out: &Value, key: &str| {
out[key].as_array().map_or(0, |w| w.iter().filter(|w| w.as_str().is_some_and(|w| w.contains("structured content"))).count())
};
let corners = json!([0, 0, 100, 0, 100, 100, 0, 100]);
let r = ok(&mut a, "page_enhance_camera", json!({ "doc": doc, "page": 1, "corners": corners }));
assert_eq!(r["undo"], "Enhance camera image", "{r}");
assert_eq!(structured(&r, "warnings"), 1, "{r}");
// The same tool through command_run reports its own warning.
let r = ok(&mut a, "command_run", json!({ "id": "ocr.enhance_camera", "params": { "doc": doc, "page": 1, "corners": corners } }));
assert_eq!(structured(&r, "warnings"), 1, "{r}");
// form_set_script lists its edit's own warning in errors, and the camera edits' are not repeated.
let r = ok(&mut a, "form_set_script", json!({ "doc": doc, "field": "qty", "event": "format", "script": "event.value = event.value;" }));
assert_eq!(structured(&r, "errors"), 1, "{r}");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn enhance_scanned_file_reports_the_xfa_data_it_could_not_write_once() {
let dir = workdir("xfa-scan-warnings");
// The data holds structured content where the price goes, so its value can't be written.
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
"</xdp:xdp>",
"<xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data><form><page1><price><p>7</p></price></page1></form></xfa:data></xfa:datasets>\n</xdp:xdp>",
);
std::fs::write(dir.join("data.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap();
// Dull paper with a dark stroke, so the cleanup changes the picture.
let gray: Vec<u8> = (0..400u32).flat_map(|y| std::iter::repeat_n(if (100..110).contains(&y) { 30 } else { 150 }, 300)).collect();
std::fs::write(dir.join("scan.jpg"), encode_jpeg_dpi(300, 400, craft_image_codecs::ChannelLayout::Gray, gray, 90, 72.0)).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "data.pdf" }))["doc"].as_u64().unwrap();
let structured = |out: &Value, key: &str| {
out[key].as_array().map_or(0, |w| w.iter().filter(|w| w.as_str().is_some_and(|w| w.contains("structured content"))).count())
};
ok(&mut a, "page_add_image", json!({ "doc": doc, "page": 1, "path": "scan.jpg", "rect": [0, 0, 612, 792] }));
let r = ok(&mut a, "page_enhance_scan", json!({ "doc": doc, "level": 100 }));
assert_eq!((r["undo"].clone(), r["images"].clone()), (json!("Enhance scanned file"), json!(1)), "{r}");
assert_eq!(structured(&r, "warnings"), 1, "{r}");
// form_set_script lists its edit's own warning in errors, and the scan edit's is not repeated.
let r = ok(&mut a, "form_set_script", json!({ "doc": doc, "field": "qty", "event": "format", "script": "event.value = event.value;" }));
assert_eq!(structured(&r, "errors"), 1, "{r}");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn growable_xfa_text_paginates_after_fill_save_and_print() {
let dir = workdir("xfa-growable-text");
@@ -15726,6 +16047,36 @@ fn explicit_bundled_thai_font_choice_layout_edit_undo_and_reopen() {
assert!(image.iter().any(|c| matches!(c, Content::Png { .. })));
}
#[test]
fn doc_compare_mark_places_marks_on_their_pages() {
let dir = workdir("compare-mark-pages");
let mut a = auto(&dir);
let v1 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "alpha beta\x0Cgamma delta" }))["doc"].as_u64().unwrap();
let v2 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "alpha one\x0Ctwo delta" }))["doc"].as_u64().unwrap();
let r = ok(&mut a, "doc_compare_mark", json!({ "doc": v2, "other": v1 }));
assert_eq!(r["comments"], 2, "{r}");
let list = ok(&mut a, "comment_list", json!({ "doc": v2 }));
let comments = list["comments"].as_array().unwrap();
assert_eq!(comments.len(), 2, "{list}");
let pages: Vec<u64> = comments.iter().map(|c| c["page"].as_u64().unwrap()).collect();
assert!(pages.contains(&1) && pages.contains(&2), "{list}");
}
#[test]
fn doc_compare_mark_does_not_place_repeated_text_on_an_earlier_page() {
let dir = workdir("compare-mark-repeated-text");
let mut a = auto(&dir);
let v1 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "same\x0Cother" }))["doc"].as_u64().unwrap();
let v2 = ok(&mut a, "doc_create", json!({ "from": "text", "text": "same\x0Csame" }))["doc"].as_u64().unwrap();
let r = ok(&mut a, "doc_compare_mark", json!({ "doc": v2, "other": v1 }));
assert_eq!(r["comments"], 1, "{r}");
let list = ok(&mut a, "comment_list", json!({ "doc": v2 }));
let comments = list["comments"].as_array().unwrap();
assert_eq!(comments.len(), 1, "{list}");
let pages: Vec<u64> = comments.iter().map(|c| c["page"].as_u64().unwrap()).collect();
assert_eq!(pages, vec![2], "{list}");
}
/// `text_prepare` refuses what it can't act on, changing nothing: a page with no grouped text
/// (with the reason), and a page the document doesn't have.
#[test]
@@ -15894,6 +16245,29 @@ fn pdf_watermark_uses_visible_source_crop_through_tools() {
}
}
#[test]
fn copying_a_field_through_tools() {
let dir = workdir("copy-field");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "form_add_field", json!({ "doc": doc, "page": 1, "type": "combo", "rect": [20, 60, 180, 82], "options": ["Red", "Green"] }));
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "Dropdown1": "Green" } }));
let r = ok(&mut a, "form_copy_field", json!({ "doc": doc, "field": "Dropdown1", "page": 2, "dx": 10, "dy": 30 }));
assert_eq!(r["field"], "Dropdown2");
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "Dropdown2": "Red" } }));
let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));
let f = fields["fields"].as_array().unwrap();
assert_eq!(
f.iter().map(|f| (f["name"].as_str().unwrap(), f["page"].as_u64().unwrap())).collect::<Vec<_>>(),
[("Dropdown1", 1), ("Dropdown2", 2)]
);
assert_eq!((f[0]["value"].clone(), f[1]["value"].clone()), (json!("Green"), json!("Red")), "two fields, two values");
assert_eq!(f[1]["options"], f[0]["options"]);
assert_eq!(f[1]["rect"], json!([30.0, 90.0, 190.0, 112.0]), "moved right and down");
assert!(matches!(a.call("form_copy_field", &json!({ "doc": doc, "field": "nope", "page": 1 })), Err(ToolError::Failed(_))));
assert!(matches!(a.call("form_copy_field", &json!({ "doc": doc, "field": "Dropdown1", "page": 9 })), Err(ToolError::InvalidArgs(_))));
}
/// #3273: images became pages as large as their pixels, so a set of photos gave pages of several
/// sizes and none of them paper. `page_size` puts them all on one sheet, scaled to fit.
#[test]
+119
View File
@@ -562,3 +562,122 @@ fn no_tool_panics_when_the_viewer_sees_fewer_pages_than_the_file_has() {
let _ = std::fs::remove_dir_all(&root);
assert!(failures.is_empty(), "{} failure(s); the first is: {}", failures.len(), failures.first().map_or("", String::as_str));
}
/// Which structure of the form refers to itself: the page tree, the named destinations, or the
/// name tree.
#[derive(Clone, Copy, Debug, PartialEq)]
enum CyclicXfa {
Pages,
Dests,
Names,
}
/// A dynamic XFA form (#9027) in which `cyclic` refers to itself: the relayout run on open used
/// to walk that cycle forever. The other structures are normal. The layout fails with a note and
/// the document opens anyway; the point is that it answers at all.
fn cyclic_xfa_pdf(cyclic: CyclicXfa) -> Vec<u8> {
let xdp = pdfcraft_xfa::fixtures::template(1);
let (page_kids, dests_key, names_key) = match cyclic {
CyclicXfa::Pages => ("3 0 R 2 0 R", "", ""),
CyclicXfa::Dests => ("3 0 R", " /Dests 6 0 R", ""),
CyclicXfa::Names => ("3 0 R", "", " /Names 7 0 R"),
};
let objs: Vec<(u32, String)> = vec![
(1, format!("<< /Type /Catalog /Pages 2 0 R /NeedsRendering true /AcroForm << /XFA 5 0 R /Fields [] >>{dests_key}{names_key} >>")),
(2, format!("<< /Type /Pages /Kids [{page_kids}] /Count 1 >>")),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>".into()),
(4, "<< /Length 44 >>\nstream\nBT /F1 12 Tf 72 700 Td (Please wait...) Tj ET\nendstream".into()),
(5, format!("<< /Length {} >>\nstream\n{xdp}\nendstream", xdp.len())),
(6, "<< /cyc 8 0 R >>".into()),
(7, "<< /Dests 9 0 R >>".into()),
(8, "<< /D 8 0 R >>".into()),
(9, "<< /Names [(end) 3 0 R] /Kids [9 0 R] >>".into()),
];
let size = 10;
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = vec![None; size];
for (num, body) in &objs {
if let Some(slot) = offsets.get_mut(*num as usize) {
*slot = Some(out.len());
}
out.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes());
for offset in offsets.iter().skip(1) {
out.extend_from_slice(
match offset {
Some(o) => format!("{o:010} 00000 n \n"),
None => "0000000000 65535 f \n".to_string(),
}
.as_bytes(),
);
}
out.extend_from_slice(format!("trailer << /Size {size} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
out
}
#[test]
fn no_tool_hangs_on_a_cyclic_xfa_form() {
// #9027: a dynamic form whose page tree, destination, or name tree refers to itself used to
// make the relayout run on open walk the cycle forever. Opening must answer (the layout
// fails with a note and the document opens anyway), and every tool must answer with a
// result or an error.
for cyclic in [CyclicXfa::Pages, CyclicXfa::Dests, CyclicXfa::Names] {
let root = tmp(&format!("cyclic-xfa-{cyclic:?}"));
let pdf = cyclic_xfa_pdf(cyclic);
let mut failures = Vec::new();
for def in tools() {
// Written again for every tool: tools that save write to `in.pdf`, the plausible path.
std::fs::write(root.join("in.pdf"), &pdf).expect("fixture");
let mut a = Automation::new().with_root(&root).expect("root");
let opened = a.call("doc_open", &json!({ "path": "in.pdf" })).expect("open the cyclic form");
let doc = opened
.into_iter()
.find_map(|c| match c {
pdfcraft_automation::Content::Json(v) => v["doc"].as_u64(),
pdfcraft_automation::Content::Png { .. } => None,
})
.expect("the opened document has an id");
if let Err(e) = guarded(&mut a, def.name, &Value::Object(plausible_with(&def, Some(doc)))) {
failures.push(e);
}
}
for f in &failures {
eprintln!(" {f}");
}
let _ = std::fs::remove_dir_all(&root);
assert!(
failures.is_empty(),
"on a cyclic {cyclic:?} form: {} failure(s); the first is: {}",
failures.len(),
failures.first().map_or("", String::as_str)
);
}
}
/// `source_widget` is 1-based and counted against the source's widgets: no value of it but the
/// source's one widget (or null, which is the default), nor the key without `source_field`,
/// panics or adds a field.
#[test]
fn hostile_source_widgets_are_refused_without_a_panic() {
let mut a = Automation::new().with_root(tmp("grid-source-widget")).expect("root");
let doc = blank_doc(&mut a);
a.call("form_add_field", &json!({"doc": doc, "page": 1, "type": "text", "name": "source", "rect": [20, 20, 180, 50]})).expect("add the source");
let mut failures = Vec::new();
for value in zoo().into_iter().chain([json!(2), json!(usize::MAX)]).filter(|v| *v != json!(1) && !v.is_null()) {
let rect = json!([20, 100, 180, 180]);
for args in [
json!({"doc": doc, "page": 1, "rect": rect, "rows": 2, "source_field": "source", "source_widget": value}),
json!({"doc": doc, "page": 1, "rect": rect, "rows": 2, "source_widget": value}),
] {
match catch_unwind(AssertUnwindSafe(|| a.call("form_add_field_table", &args))) {
Ok(Err(ToolError::InvalidArgs(_) | ToolError::Failed(_))) => {}
Ok(Ok(_)) => failures.push(format!("{args} was accepted")),
Ok(Err(e)) => failures.push(format!("{args}: {e:?}")),
Err(_) => failures.push(format!("{args} panicked")),
}
}
}
assert!(failures.is_empty(), "{failures:#?}");
}
+16
View File
@@ -269,3 +269,19 @@ fn a_font_name_the_page_already_uses_is_not_reused() {
assert_ne!(second, first);
assert!(second.starts_with(b"PCAr"), "{}", String::from_utf8_lossy(&second));
}
#[test]
fn latin_in_a_shaped_item_uses_the_collision_free_font_name() {
let mut doc = Document::new_empty();
let mut taken = Dict::new();
taken.set(b"PCFHelvetica".to_vec(), Object::Null);
let t = item();
let resources = draw::draw(&mut doc, &Content::Text(t.clone()), [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], &taken, false).unwrap().resources;
let mut fonts = resources.get(b"Font").unwrap().as_dict().unwrap().clone();
let laid = vec![("Hi ب".into(), false, 0, vec![Piece::Latin("Hi ".into()), Piece::Shaped(vec![cluster(1, 0.5)])], 20.0)];
let mut out = Vec::new();
draw_laid_shaped(&mut doc, &t, &laid, &taken, &mut fonts, &mut out, |_, _| Ok(boxed(0.5))).unwrap();
let latin = glyphs_shown(&out).into_iter().find(|(_, code)| *code == b'H').unwrap().0;
assert_eq!(latin, b"PCFHelvetica1");
assert_eq!(fonts.get(&latin).unwrap().as_dict().unwrap().name(b"BaseFont"), Some(b"Helvetica".as_slice()));
}
+162 -18
View File
@@ -8,8 +8,32 @@ use super::{
};
use pdfcraft_fonts::shaped_text::{self, ShapedFonts};
fn font_name(base: &str) -> String {
format!("PCF{}", base.replace('-', ""))
fn standard_font(t: &AddedText) -> Dict {
let mut font = Dict::new();
font.set(b"Type".to_vec(), Object::name("Font"));
font.set(b"Subtype".to_vec(), Object::name("Type1"));
font.set(b"BaseFont".to_vec(), Object::name(t.family.base_font(t.bold, t.italic)));
if t.family != Family::Courier || !t.text.is_ascii() {
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
}
font
}
fn font_name(doc: &Document, t: &AddedText, taken: &Dict) -> String {
let base = format!("PCF{}", t.family.base_font(t.bold, t.italic).replace('-', ""));
let font = standard_font(t);
let mut name = base.clone();
let mut suffix = 0usize;
// A PDF may already use our preferred name for a different font or encoding. Reuse only
// the exact font we would write, its entries in any order, so repeated edits do not
// accumulate new resources.
let same =
|f: &Object| doc.resolve(f).as_dict().is_some_and(|d| d.len() == font.len() && font.iter().all(|(key, value)| d.get(key) == Some(value)));
while taken.get(name.as_bytes()).is_some_and(|f| !same(f)) {
suffix = suffix.saturating_add(1);
name = format!("{base}{suffix}");
}
name
}
#[cfg(test)]
@@ -60,7 +84,7 @@ pub(super) fn draw_laid_shaped(
outline: impl Fn(ShapedScript, u32) -> Result<GlyphOutline, GlyphError>,
) -> Result<(), EditError> {
let r = text_rect(t);
let latin = font_name(t.family.base_font(t.bold, t.italic));
let latin = font_name(doc, t, taken);
let shaped =
ShapedFonts::new(shaped_text::clusters(laid.iter().map(|(_, _, _, pieces, _)| pieces.as_slice())), outline, taken, fonts, "PCAr", &mut |o| {
Object::Ref(doc.add(o))
@@ -71,6 +95,26 @@ pub(super) fn draw_laid_shaped(
ShapedScript::Thai => thai_error(e, &c.text),
ShapedScript::Latin => EditError::Invalid(pdfcraft_fonts::shaped_text::latin_message(e, &c.text)),
})?;
// A run the shaped layout leaves as a `Piece::Latin` but that WinAnsi cannot encode (Greek or
// Cyrillic) is drawn with the bundled Inter face, embedded, so it is not silently lost to
// WinAnsi `?`. The face is added only when a run needs it, so pure Hebrew stays as before.
const HEX_DIGITS: &[u8; 16] = b"0123456789ABCDEF";
let needs = laid.iter().any(|(_, _, _, pieces, _)| pieces.iter().any(|p| matches!(p, Piece::Latin(s) if piece_needs_inter_face(s))));
let inter: Option<(String, pdfcraft_fonts::pdf::Metrics)> = if needs {
match pdfcraft_fonts::document_latin_fonts(t.bold).into_iter().next() {
Some(face) => {
seed_full_fonts(fonts, taken);
let name = pdfcraft_fonts::embedding::embed(doc, fonts, face.bytes, face.family).map_err(EditError::Invalid)?;
let font = fonts.reference(name.as_bytes()).ok_or_else(|| EditError::Invalid("the bundled face could not be added".into()))?;
let dict = doc.dict(&Object::Ref(font)).ok_or_else(|| EditError::Invalid("the bundled face could not be read".into()))?;
let metrics = pdfcraft_fonts::pdf::Metrics::from_dict(doc, &dict);
Some((name, metrics))
}
None => None,
}
} else {
None
};
out.extend(format!("BT {}\n", t.fill_op()).bytes());
if t.char_spacing != 0.0 {
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
@@ -89,11 +133,28 @@ pub(super) fn draw_laid_shaped(
for piece in pieces {
match piece {
Piece::Latin(s) => {
out.extend(format!("/{latin} {} Tf {} Tw 1 0 0 1 {} {} Tm ", n(t.size), n(tw), n(pen), n(y)).bytes());
out.extend(literal(&win_ansi(s)));
out.extend_from_slice(b" Tj\n");
current = None;
pen += latin_width(t, s) + tw * s.matches(' ').count() as f64;
// A run WinAnsi cannot encode (Greek or Cyrillic) is drawn with the bundled Inter
// face; every other run stays on the standard font as before.
let inter_pick = inter.as_ref().filter(|_| piece_needs_inter_face(s));
// The face has no soft hyphen: draw it as a hyphen, as `draw_inter_face` does.
let encoded = inter_pick.as_ref().and_then(|(_, m)| m.encode(&s.replace('\u{ad}', "-")));
if let (Some((name, metrics)), Some(encoded)) = (inter_pick, encoded) {
out.extend(format!("/{name} {} Tf {} Tw 1 0 0 1 {} {} Tm <", n(t.size), n(tw), n(pen), n(y)).bytes());
for &b in &encoded {
out.push(HEX_DIGITS[(b >> 4) as usize]);
out.push(HEX_DIGITS[(b & 0x0F) as usize]);
}
out.extend_from_slice(b"> Tj\n");
let glyph_w: f64 = metrics.codes(&encoded).iter().map(|(c, _)| metrics.width(*c) * t.size).sum();
pen += glyph_w + t.char_spacing * s.chars().count() as f64 + tw * s.matches(' ').count() as f64;
current = None;
} else {
out.extend(format!("/{latin} {} Tf {} Tw 1 0 0 1 {} {} Tm ", n(t.size), n(tw), n(pen), n(y)).bytes());
out.extend(literal(&win_ansi(s)));
out.extend_from_slice(b" Tj\n");
current = None;
pen += latin_width(t, s) + tw * s.matches(' ').count() as f64;
}
}
Piece::Shaped(clusters) => pen = shaped.show(out, clusters, pen, y, t.size, t.char_spacing, tw, &mut current),
}
@@ -189,6 +250,89 @@ pub(super) struct DrawnItem {
pub custom_rect: Option<[f64; 4]>,
}
/// Whether `t` has a character the standard font (WinAnsi) can't draw, which the bundled Inter
/// face draws: the text is set in the embedded face, as `doc_create` does. Arabic, Hebrew and
/// Thai go to their own shaped face (or are drawn as `?` when it's missing), not the Inter face.
fn needs_inter_face(t: &AddedText) -> bool {
t.text.chars().any(|c| !matches!(c, '\n' | '\r') && !pdfcraft_fonts::win_ansi_encodable(c) && !is_arabic(c) && !is_hebrew(c) && !is_thai(c))
}
/// Whether a run the shaped layout leaves as a `Piece::Latin` must be drawn with the bundled Inter
/// face instead of WinAnsi: it holds a character WinAnsi cannot encode that the shaped face does
/// not shape (Greek or Cyrillic). WinAnsi-encodable and shaped-script runs stay on WinAnsi.
fn piece_needs_inter_face(s: &str) -> bool {
s.chars().any(|c| !matches!(c, '\n' | '\r') && !pdfcraft_fonts::win_ansi_encodable(c) && !is_arabic(c) && !is_hebrew(c) && !is_thai(c))
}
/// Copy the page's own `PCFull*` fonts into `fonts` before the bundled face is embedded. `embed`
/// names a new resource by looking only at the dict it is given, so an empty dict always yields
/// `PCFull0`, which `write` would then set over a different font the page already has under that
/// name. Seeded, it picks a free name, or reuses an identical face already on the page.
fn seed_full_fonts(fonts: &mut Dict, taken: &Dict) {
for (key, value) in taken.iter().filter(|(key, _)| key.starts_with(b"PCFull")) {
fonts.set(key.to_vec(), value.clone());
}
}
/// Draw `t` with the bundled Inter face, embedded: its real outlines, for the Latin, Greek and
/// Cyrillic letters WinAnsiEncoding lacks. A soft hyphen is drawn as a hyphen, as the face has
/// no glyph for it.
fn draw_inter_face(doc: &mut Document, t: &AddedText, taken: &Dict, mut out: Vec<u8>) -> Result<DrawnItem, EditError> {
let face = pdfcraft_fonts::document_latin_fonts(t.bold)
.into_iter()
.next()
.ok_or_else(|| EditError::Invalid("this build has no bundled Latin, Greek and Cyrillic face".into()))?;
let mut fonts = Dict::new();
seed_full_fonts(&mut fonts, taken);
let name = pdfcraft_fonts::embedding::embed(doc, &mut fonts, face.bytes, face.family).map_err(EditError::Invalid)?;
let font = fonts.reference(name.as_bytes()).ok_or_else(|| EditError::Invalid("the bundled face could not be added".into()))?;
let dict = doc.dict(&Object::Ref(font)).ok_or_else(|| EditError::Invalid("the bundled face could not be read".into()))?;
let metrics = pdfcraft_fonts::pdf::Metrics::from_dict(doc, &dict);
let mut res = Dict::new();
res.set(b"Font".to_vec(), Object::Dict(fonts));
// A soft hyphen is drawn as a hyphen: the face has no glyph for it.
let show = |s: &str| s.chars().map(|c| if c == '\u{ad}' { '-' } else { c }).collect::<String>();
let all = wrap_measured(t, |s| {
let encoded = metrics.encode(&show(s)).ok_or_else(|| {
let missing = s.chars().find(|c| metrics.encode(&show(&c.to_string())).is_none()).unwrap_or('?');
EditError::Invalid(format!("the bundled Inter face can't show U+{:04X}", u32::from(missing)))
})?;
Ok(metrics.codes(&encoded).iter().map(|(code, _)| metrics.width(*code) * t.size).sum::<f64>() + t.char_spacing * s.chars().count() as f64)
})?;
let norm_r = norm(t.rect);
let h = all.len().max(1) as f64 * t.size * 1.2;
let r = [norm_r[0], norm_r[3] - h, norm_r[2], norm_r[3]];
// Painted like standard-font text: its gray or CMYK ink when it has one, else RGB.
out.extend_from_slice(b"BT ");
out.extend(pdfcraft_content::serialize_ops(&[pdfcraft_content::Op::new("Tf", vec![Object::name(name.as_str()), Object::Real(t.size)])]));
out.extend(format!("{}\n", t.fill_op()).bytes());
if t.char_spacing != 0.0 {
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
}
let paragraphs: Vec<usize> = all.iter().map(|(_, p)| *p).collect();
const HEX_DIGITS: &[u8; 16] = b"0123456789ABCDEF";
for (i, (line, _)) in all.iter().enumerate() {
let encoded = metrics.encode(&show(line)).ok_or_else(|| {
let unencodable = line.chars().find(|c| metrics.encode(&show(&c.to_string())).is_none()).unwrap_or('?');
EditError::Invalid(format!("the bundled Inter face cannot show '{unencodable}' (U+{:04X})", u32::from(unencodable)))
})?;
let glyph_w: f64 = metrics.codes(&encoded).iter().map(|(c, _)| metrics.width(*c) * t.size).sum();
let w = glyph_w + t.char_spacing * line.chars().count() as f64;
let spaces = line.matches(' ').count();
let (x, tw) = placed(t, r, &paragraphs, i, w, spaces, false);
let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;
out.extend(format!("1 0 0 1 {} {} Tm {} Tw <", n(x), n(y), n(tw)).bytes());
for &b in &encoded {
out.push(HEX_DIGITS[(b >> 4) as usize]);
out.push(HEX_DIGITS[(b & 0x0F) as usize]);
}
out.extend_from_slice(b"> Tj\n");
}
out.extend_from_slice(b"ET\n");
out.extend_from_slice(b"Q\n");
Ok(DrawnItem { stream: out, resources: res, custom_rect: Some(r) })
}
/// Content and resources for an item; `view` maps display space to user space. `taken` holds the
/// page's font names. `existing`: the item is being replaced, so a build without the Arabic or
/// Hebrew face keeps drawing that text as `?`, as before it was supported, rather than refusing to
@@ -271,17 +415,14 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict
out.extend_from_slice(b"Q\n");
return Ok(DrawnItem { stream: out, resources: res, custom_rect: Some(r) });
}
let base = t.family.base_font(t.bold, t.italic);
let name = font_name(base);
let mut font = Dict::new();
font.set(b"Type".to_vec(), Object::name("Font"));
font.set(b"Subtype".to_vec(), Object::name("Type1"));
font.set(b"BaseFont".to_vec(), Object::name(base));
if t.family != Family::Courier || !t.text.is_ascii() {
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
}
let name = font_name(doc, t, taken);
let font = standard_font(t);
let mut fonts = Dict::new();
fonts.set(name.clone().into_bytes(), Object::Dict(font));
// Reusing a matching name must preserve its existing indirect reference as well
// as its appearance. Only new names need a resource entry in the merge.
if !taken.contains(name.as_bytes()) {
fonts.set(name.clone().into_bytes(), Object::Dict(font));
}
let face_or_new = |has: fn(char) -> bool, face: bool| t.text.chars().any(has) && (face || !existing);
if t.text.chars().any(is_thai)
|| face_or_new(is_arabic, pdfcraft_fonts::document_arabic_font().is_some())
@@ -292,6 +433,9 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict
out.extend_from_slice(b"Q\n");
return Ok(DrawnItem { stream: out, resources: res, custom_rect: None });
}
if needs_inter_face(t) {
return draw_inter_face(doc, t, taken, out);
}
res.set(b"Font".to_vec(), Object::Dict(fonts));
let r = text_rect(t);
out.extend(format!("BT /{name} {} Tf {}\n", n(t.size), t.fill_op()).bytes());
+21 -8
View File
@@ -189,10 +189,21 @@ pub(super) fn is_hebrew(c: char) -> bool {
matches!(u32::from(c), 0x0591..=0x05F4 | 0xFB1D..=0xFB4F)
}
/// Whether `c` is drawn by neither the standard font (WinAnsi) nor the bundled Inter face:
/// the character the Add-text path can't show. `\n` splits lines; other control characters
/// (a lone `\r`, `\t`'s non-tab siblings) are drawn as `?` and don't count as face coverage.
fn undrawable_char(c: char) -> bool {
if !pdfcraft_fonts::win_ansi_encodable(c) && (0..=0x1f).contains(&u32::from(c)) && c != '\n' {
return true;
}
!pdfcraft_fonts::win_ansi_encodable(c)
&& !pdfcraft_fonts::document_latin_fonts(false).into_iter().next().is_some_and(|f| pdfcraft_fonts::embedding::covers(f.bytes, &c.to_string()))
}
/// The first character of `t` that would be drawn as `?`: outside WinAnsiEncoding and not drawn
/// with the craft-fonts Arabic (#125) or Hebrew (#128) face, or Arabic or Hebrew that the face can't
/// draw (or that has no face to draw it). Page-content tools refuse such text; the Add-text editor
/// keeps it open.
/// with the bundled Inter face (Greek, Cyrillic), or not drawn with the craft-fonts Arabic (#125)
/// or Hebrew (#128) face, or Arabic or Hebrew that the face can't draw (or that has no face to
/// draw it). Page-content tools refuse such text; the Add-text editor keeps it open.
pub fn first_undrawable(t: &AddedText) -> Option<char> {
if t.font_resource.is_some() {
return None;
@@ -211,15 +222,17 @@ pub fn first_undrawable(t: &AddedText) -> Option<char> {
return Some(c);
}
if !shaped_by_a_face(t) {
// Drawn line by line in the item's standard font (`\n` splits lines). Without the face
// that is also how `draw` redraws an existing item, so it's checked that way.
return t.text.split('\n').find_map(pdfcraft_fonts::first_non_win_ansi);
// Drawn line by line in the item's standard font or the bundled Inter face (`\n` splits
// lines). Without the face that is also how `draw` redraws an existing item, so it's
// checked that way.
return t.text.split('\n').find_map(|line| line.chars().find(|c| undrawable_char(*c)));
}
// What `shaped_layout` leaves to the standard font, exactly as `draw_shaped` splits it.
// What `shaped_layout` leaves to the standard font or the bundled Inter face, exactly as
// `draw_shaped` splits it.
wrapped(t).into_iter().find_map(|(line, rtl, _)| {
let (pieces, _) = shaped_layout(t, &line, rtl).ok()?;
pieces.iter().find_map(|p| match p {
Piece::Latin(s) => pdfcraft_fonts::first_non_win_ansi(s),
Piece::Latin(s) => s.chars().find(|c| undrawable_char(*c)),
Piece::Shaped(_) => None,
})
})
+2
View File
@@ -106,4 +106,6 @@ mod paragraph_spacing_break_tests;
#[cfg(test)]
mod paragraph_spacing_tests;
#[cfg(test)]
mod raised_row_tests;
#[cfg(test)]
mod tests;
+1 -1
View File
@@ -31,7 +31,7 @@ pub(crate) fn page(content: &str) -> Document {
Document::open(Arc::new(out)).unwrap()
}
fn reopen(doc: &Document) -> Document {
pub(crate) fn reopen(doc: &Document) -> Document {
let bytes = write_incremental(doc, &SaveOptions::default()).unwrap();
Document::open(Arc::new(bytes)).unwrap()
}
+99
View File
@@ -0,0 +1,99 @@
//! Restyling a paragraph whose rows start with a raised run (`Ts`) keeps each row on its own
//! baseline: a run's baseline is the raised one, so rows are placed on the unraised one.
use crate::paragraph_spacing_tests::{page, reopen};
use crate::text;
/// Three rows whose first two start with a raised run, as another program writes a footnote mark
/// or an exponent at the start of a row: `2` and `3` at 7 pt raised 4 pt, the rest at 12 pt on
/// baselines 14 pt apart.
const RAISED_ROW_STARTS: &str = "BT /F1 7 Tf 4 Ts 72 700 Td (2) Tj /F1 12 Tf 0 Ts 4 0 Td (x plus one) Tj \
/F1 7 Tf 4 Ts -4 -14 Td (3) Tj /F1 12 Tf 0 Ts 4 0 Td (y plus two) Tj -4 -14 Td (z end) Tj ET";
/// Colours "plus" on the first row of the paragraph `content` draws, with `draft` as its text and
/// the rest of `base` applied, and reads each run back after a save and reopen as
/// `(text, unraised baseline, rise)`.
fn restyle_rows(content: &str, draft: impl Fn(&str) -> String, base: text::BlockStyle) -> Vec<(String, f64, f64)> {
let mut doc = page(content);
let blocks = text::text_blocks(&doc, 0).unwrap();
assert_eq!(blocks.len(), 1, "one paragraph: {blocks:?}");
let source = blocks[0].editor_text.clone();
let at = source.find("plus").unwrap();
let range = text::RangeStyle {
range: at..at + 4,
family: None,
resource: None,
size: None,
color: Some([1.0, 0.0, 0.0]),
underline: None,
char_spacing: None,
scale: None,
};
let style = text::BlockStyle { ranges: vec![range], ..base };
text::rewrite_block(&mut doc, 0, 0, Some(&draft(&source)), &style).unwrap();
text::text_lines(&reopen(&doc), 0).unwrap().iter().map(|l| (l.text.clone(), l.origin_baseline() - l.rise(), l.rise())).collect()
}
fn assert_on(runs: &[(String, f64, f64)], word: &str, baseline: f64, rise: f64) {
let (_, b, r) = runs.iter().find(|(t, _, _)| t.contains(word)).unwrap_or_else(|| panic!("no run shows {word:?}: {runs:?}"));
assert!((b - baseline).abs() < 1e-3 && (r - rise).abs() < 1e-3, "{word:?}: baseline {b} (want {baseline}), rise {r} (want {rise}): {runs:?}");
}
/// Restyling a paragraph whose rows start with a raised run keeps every row on its own baseline,
/// and each raised run raised by its own rise only.
#[test]
fn rows_that_start_raised_keep_their_baselines_when_restyled() {
let runs = restyle_rows(RAISED_ROW_STARTS, str::to_owned, Default::default());
assert_on(&runs, "2", 700.0, 4.0);
assert_on(&runs, "x", 700.0, 0.0);
assert_on(&runs, "3", 686.0, 4.0);
assert_on(&runs, "y", 686.0, 0.0);
assert_on(&runs, "z", 672.0, 0.0);
}
/// A row added below rows that start raised is placed as far below the last row as it is when
/// the same rows start unraised, measured between unraised baselines.
#[test]
fn a_row_added_below_rows_that_start_raised_takes_the_ordinary_step() {
let added = |source: &str| format!("{source}\nnew row");
let step = |runs: &[(String, f64, f64)]| {
let at = |word: &str| runs.iter().find(|(t, _, _)| t.contains(word)).map(|r| r.1).unwrap_or_else(|| panic!("no {word:?}: {runs:?}"));
at("z") - at("new")
};
let raised = restyle_rows(RAISED_ROW_STARTS, added, Default::default());
let plain = restyle_rows(&RAISED_ROW_STARTS.replace("4 Ts", "0 Ts"), added, Default::default());
assert_on(&raised, "z", 672.0, 0.0);
assert!(step(&plain) > 0.0, "{plain:?}");
assert!((step(&raised) - step(&plain)).abs() < 1e-3, "step {} below raised rows, {} below plain ones: {raised:?}", step(&raised), step(&plain));
}
/// With paragraph spacing set, evenly spaced rows that start raised are not read as paragraphs
/// apart: the 4 pt rise is not a gap above the next row, so `z end` stays on 672.
#[test]
fn a_raised_row_start_is_not_read_as_a_paragraph_gap() {
let runs = restyle_rows(RAISED_ROW_STARTS, str::to_owned, text::BlockStyle { paragraph_spacing: Some(6.0), ..Default::default() });
assert_on(&runs, "y", 686.0, 0.0);
assert_on(&runs, "z", 672.0, 0.0);
}
/// A paragraph given a size is laid out row by row from its first row, and that row starts on its
/// unraised baseline: `x plus one` stays on 700.
#[test]
fn a_paragraph_given_a_size_starts_on_the_unraised_baseline() {
let runs = restyle_rows(RAISED_ROW_STARTS, str::to_owned, text::BlockStyle { size: Some(12.0), ..Default::default() });
assert_on(&runs, "x", 700.0, 0.0);
}
/// A run raised on a slanted text matrix is raised by its height above the unraised baseline,
/// not by the length of the slanted y axis: `Tm` [1 0 0.5 1 72 700] with `4 Ts` sits 4 pt up.
/// Turned a quarter, the same rise still reads as 4 pt across its baseline.
#[test]
fn a_raised_run_on_a_sheared_matrix_keeps_its_height() {
let line =
|content: &str| text::text_lines(&reopen(&page(content)), 0).unwrap().into_iter().next().unwrap_or_else(|| panic!("no run: {content}"));
let sheared = line("BT /F1 12 Tf 4 Ts 1 0 0.5 1 72 700 Tm (a) Tj ET");
assert!((sheared.origin_baseline() - sheared.rise() - 700.0).abs() < 1e-3, "unraised baseline {}", sheared.origin_baseline() - sheared.rise());
assert!((sheared.rise() - 4.0).abs() < 1e-3, "rise {}", sheared.rise());
let turned = line("BT /F1 12 Tf 4 Ts 0 1 -1 0 300 300 Tm (a) Tj ET");
assert!((turned.rise() - 4.0).abs() < 1e-3, "turned rise {}", turned.rise());
}
+266
View File
@@ -1537,6 +1537,125 @@ fn added_items_follow_the_page_user_unit() {
assert_eq!((old.rect[0], old.rect[2], old.rect[3], old.size), (144.0, 600.0, 1400.0, 28.0), "scaled to points");
}
#[test]
fn added_text_preserves_an_occupied_font_name() {
let mut doc = fixture();
let page = pdfcraft_model::pages(&doc)[2].obj;
let original = Object::Ref(pdfcraft_cos::ObjRef::new(8, 0));
let mut fonts = Dict::new();
fonts.set(b"PCFHelvetica".to_vec(), original.clone());
fonts.set(b"PCFHelvetica1".to_vec(), original.clone());
let mut resources = Dict::new();
resources.set(b"Font".to_vec(), Object::Dict(fonts));
let content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"BT /PCFHelvetica 12 Tf 72 700 Td (Original) Tj ET".to_vec())));
doc.update_dict(page, |d| {
d.set(b"Resources".to_vec(), Object::Dict(resources));
d.set(b"Contents".to_vec(), Object::Ref(content));
})
.unwrap();
let original_pixels = |doc: &Document| {
let bytes = write_incremental(doc, &SaveOptions::default()).unwrap();
let mut renderer = pdfcraft_render::PageRenderer::new(Arc::new(bytes), pdfcraft_render::RenderConfig::default());
let page = renderer.render(pdfcraft_render::RenderRequest { page: 2, scale: 1.0, ..Default::default() });
page.rgba[..page.width as usize * 200 * 4].to_vec()
};
let before = original_pixels(&doc);
assert!(before.iter().any(|v| *v < 240), "the original text is visible");
let mut text = AddedText { text: "Added".into(), rect: [72.0, 500.0, 300.0, 550.0], ..Default::default() };
add_content(&mut doc, 2, &Content::Text(text.clone())).unwrap();
for replacement in ["Updated", "Again"] {
text.text = replacement.into();
update_content(&mut doc, 2, 0, &Content::Text(text.clone())).unwrap();
doc = reopen(&doc);
let p = &pdfcraft_model::pages(&doc)[2];
let res = doc.resolve(p.dict.get(b"Resources").unwrap());
let fonts = doc.resolve(res.as_dict().unwrap().get(b"Font").unwrap());
let fonts = fonts.as_dict().unwrap();
assert_eq!(fonts.get(b"PCFHelvetica"), Some(&original), "original text must keep its Courier font");
assert_eq!(fonts.get(b"PCFHelvetica1"), Some(&original));
assert_eq!(fonts.len(), 3, "repeated edits reuse the added font");
let lines = text::text_lines(&doc, 2).unwrap();
assert_eq!(lines[0].text, "Original");
assert!(streams(&doc, 2).join("\n").contains("/PCFHelvetica2 12 Tf"));
assert_eq!(original_pixels(&doc), before, "original text still renders identically");
}
}
/// A Helvetica on the page under our name, with another `/Encoding`, with none or with an entry more,
/// is another font: it stays, and the added text takes a suffixed name.
#[test]
fn added_text_does_not_reuse_a_helvetica_that_differs() {
for (key, value) in [("Encoding", Some("MacRomanEncoding")), ("Encoding", None), ("Name", Some("F1"))] {
let mut doc = fixture();
let page = pdfcraft_model::pages(&doc)[2].obj;
let mut other = Dict::new();
for (key, value) in [("Type", "Font"), ("Subtype", "Type1"), ("BaseFont", "Helvetica"), ("Encoding", "WinAnsiEncoding")] {
other.set(key.as_bytes().to_vec(), Object::name(value));
}
match value {
Some(value) => other.set(key.as_bytes().to_vec(), Object::name(value)),
None => drop(other.remove(key.as_bytes())),
}
let other = Object::Dict(other);
let mut fonts = Dict::new();
fonts.set(b"PCFHelvetica".to_vec(), other.clone());
let mut resources = Dict::new();
resources.set(b"Font".to_vec(), Object::Dict(fonts));
doc.update_dict(page, |d| d.set(b"Resources".to_vec(), Object::Dict(resources))).unwrap();
let text = AddedText { text: "Added".into(), rect: [72.0, 500.0, 300.0, 550.0], ..Default::default() };
add_content(&mut doc, 2, &Content::Text(text)).unwrap();
doc = reopen(&doc);
let p = &pdfcraft_model::pages(&doc)[2];
let resources = doc.resolve(p.dict.get(b"Resources").unwrap());
let fonts = doc.resolve(resources.as_dict().unwrap().get(b"Font").unwrap());
assert_eq!(fonts.as_dict().unwrap().get(b"PCFHelvetica"), Some(&other), "{key} {value:?}: the page's font stays");
assert!(streams(&doc, 2).join("\n").contains("/PCFHelvetica1 12 Tf"), "{key} {value:?}: the added text has its own font");
}
}
#[test]
fn added_text_reuses_an_indirect_matching_font() {
let entries = [("Type", "Font"), ("Subtype", "Type1"), ("BaseFont", "Helvetica"), ("Encoding", "WinAnsiEncoding")];
reuses_indirect_font(entries);
}
/// The entries of the page's font can come in any order.
#[test]
fn added_text_reuses_a_matching_font_whatever_its_key_order() {
let mut entries = [("Type", "Font"), ("Subtype", "Type1"), ("BaseFont", "Helvetica"), ("Encoding", "WinAnsiEncoding")];
entries.reverse();
reuses_indirect_font(entries);
}
fn reuses_indirect_font(entries: [(&str, &str); 4]) {
let mut doc = fixture();
let page = pdfcraft_model::pages(&doc)[2].obj;
let mut matching = Dict::new();
for (key, value) in entries {
matching.set(key.as_bytes().to_vec(), Object::name(value));
}
let matching = Object::Ref(doc.add(Object::Dict(matching)));
let mut fonts = Dict::new();
fonts.set(b"PCFHelvetica".to_vec(), Object::Ref(pdfcraft_cos::ObjRef::new(8, 0)));
fonts.set(b"PCFHelvetica1".to_vec(), matching.clone());
let mut resources = Dict::new();
resources.set(b"Font".to_vec(), Object::Dict(fonts));
doc.update_dict(page, |d| d.set(b"Resources".to_vec(), Object::Dict(resources))).unwrap();
let mut text = AddedText { text: "Added".into(), rect: [72.0, 500.0, 300.0, 550.0], ..Default::default() };
add_content(&mut doc, 2, &Content::Text(text.clone())).unwrap();
for value in ["Updated", "Again"] {
text.text = value.into();
update_content(&mut doc, 2, 0, &Content::Text(text.clone())).unwrap();
doc = reopen(&doc);
let p = &pdfcraft_model::pages(&doc)[2];
let resources = doc.resolve(p.dict.get(b"Resources").unwrap());
let fonts = doc.resolve(resources.as_dict().unwrap().get(b"Font").unwrap());
assert_eq!(fonts.as_dict().unwrap().get(b"PCFHelvetica1"), Some(&matching));
assert_eq!(fonts.as_dict().unwrap().len(), 2);
assert!(streams(&doc, 2).join("\n").contains("/PCFHelvetica1 12 Tf"));
}
}
fn tagged_dictionary(tag: &str, added: Option<Object>) -> Dict {
let mut dict = Dict::new();
dict.set(b"PCMark".to_vec(), Object::name(tag));
@@ -2091,6 +2210,128 @@ fn added_hebrew_text_is_drawn_right_to_left_and_stays_searchable() {
assert!(mapped.contains("<05E905"), "{mapped}");
}
/// #9016: Greek text is drawn with the bundled Inter face (embedded), not the WinAnsi
/// standard font. Without the face, it's refused with a clear message.
#[test]
fn added_greek_text_is_drawn_with_the_embedded_face() {
let mut doc = fixture();
let text = AddedText { rect: [72.0, 600.0, 400.0, 700.0], text: "Καλημέρα".into(), size: 14.0, ..AddedText::default() };
if pdfcraft_fonts::document_latin_fonts(false).is_empty() {
eprintln!("skipping the Greek drawing checks: built without a craft-fonts Latin face (set CRAFT_FONTS_DIR)");
let err = add_content(&mut doc, 0, &Content::Text(text)).unwrap_err();
assert!(err.to_string().contains("U+039A"), "{err}");
assert!(!doc.is_modified(), "nothing is written when the font is missing");
return;
}
assert_eq!(first_undrawable(&text), None);
add_content(&mut doc, 0, &Content::Text(text.clone())).unwrap();
let doc = reopen(&doc);
let added = list_added(&doc);
let Content::Text(t) = &added[0].content else { panic!() };
assert_eq!(t.text, "Καλημέρα", "the logical text is kept for editing");
// The Greek glyphs come from the embedded face, not the WinAnsi standard font. Select the
// added item's stream by its /PCMark /Added tag: the page's own "Hi" stream also has a Tj,
// so the first Tj stream is not the added one.
let item = added_stream(&doc, 0).expect("the added item's stream");
assert!(item.contains("PCFull"), "the Greek is drawn with the embedded face: {item}");
assert!(item.contains("Tf"), "the embedded face is set: {item}");
// The embedded face is a real embedded font (a FontFile in its descriptor) that maps its
// codes to Greek — not the WinAnsi standard font (Type 1).
let p = &pdfcraft_model::pages(&doc)[0];
let res = doc.resolve(p.dict.get(b"Resources").unwrap());
let fonts = doc.resolve(res.as_dict().unwrap().get(b"Font").unwrap()).as_dict().unwrap().clone();
let font = fonts
.iter()
.find(|(k, _)| k.starts_with(b"PCFull"))
.map(|(_, v)| doc.resolve(v).as_dict().unwrap().clone())
.expect("the embedded face is a resource");
assert_eq!(font.name(b"Subtype"), Some(&b"Type0"[..]), "the embedded face is a composite font, not WinAnsi");
assert!(font_has_font_file(&doc, &font), "the embedded face carries a FontFile");
let tounicode_bytes = stream_bytes(&doc, font.get(b"ToUnicode").unwrap()).unwrap();
let tounicode = String::from_utf8_lossy(&tounicode_bytes);
assert!(tounicode.contains("039A") || tounicode.contains("03B1"), "the face maps its codes to Greek: {tounicode}");
}
/// #9016: mixed Hebrew + Greek text is drawn with the Hebrew shaped face and the Greek with the
/// bundled Inter face (embedded), not WinAnsi `?` (which the pre-fix code produced for the Greek).
#[test]
fn added_mixed_hebrew_greek_text_draws_greek_with_the_embedded_face() {
let mut doc = fixture();
let text = AddedText { rect: [72.0, 600.0, 400.0, 700.0], text: "שלום Καλημέρα".into(), size: 14.0, ..AddedText::default() };
let hebrew = pdfcraft_fonts::document_hebrew_font(false).is_some();
let latin = !pdfcraft_fonts::document_latin_fonts(false).is_empty();
if !hebrew || !latin {
eprintln!("skipping the mixed Hebrew+Greek drawing checks: built without a Hebrew ({hebrew}) or Inter ({latin}) face");
return;
}
assert_eq!(first_undrawable(&text), None);
add_content(&mut doc, 0, &Content::Text(text.clone())).unwrap();
let doc = reopen(&doc);
let added = list_added(&doc);
let Content::Text(t) = &added[0].content else { panic!() };
assert_eq!(t.text, "שלום Καλημέρα", "the logical text is kept for editing");
// The Greek run is drawn with the embedded Inter face (PCFull), the Hebrew run with the
// shaped face (PCAr): both appear in the added item's stream.
let item = added_stream(&doc, 0).expect("the added item's stream");
assert!(item.contains("PCFull"), "the Greek is drawn with the embedded face: {item}");
assert!(item.contains("PCAr"), "the Hebrew is drawn with the shaped face: {item}");
assert!(!item.contains("(??????"), "the Greek is not WinAnsi placeholders: {item}");
// The embedded face maps its codes to Greek.
let p = &pdfcraft_model::pages(&doc)[0];
let res = doc.resolve(p.dict.get(b"Resources").unwrap());
let fonts = doc.resolve(res.as_dict().unwrap().get(b"Font").unwrap()).as_dict().unwrap().clone();
let font = fonts
.iter()
.find(|(k, _)| k.starts_with(b"PCFull"))
.map(|(_, v)| doc.resolve(v).as_dict().unwrap().clone())
.expect("the embedded face is a resource");
assert_eq!(font.name(b"Subtype"), Some(&b"Type0"[..]), "the embedded face is a composite font");
let tounicode_bytes = stream_bytes(&doc, font.get(b"ToUnicode").unwrap()).unwrap();
let tounicode = String::from_utf8_lossy(&tounicode_bytes);
assert!(tounicode.contains("039A") || tounicode.contains("03B1"), "the face maps its codes to Greek: {tounicode}");
}
/// The base font of each `PCFull*` resource on page 0, by resource name.
fn embedded_faces_by_resource(doc: &Document) -> std::collections::BTreeMap<String, String> {
let p = &pdfcraft_model::pages(doc)[0];
let res = doc.resolve(p.dict.get(b"Resources").unwrap());
let fonts = doc.resolve(res.as_dict().unwrap().get(b"Font").unwrap()).as_dict().unwrap().clone();
fonts
.iter()
.filter(|(k, _)| k.starts_with(b"PCFull"))
.map(|(k, v)| {
let font = doc.resolve(v).as_dict().unwrap().clone();
(String::from_utf8_lossy(k).into_owned(), String::from_utf8_lossy(font.name(b"BaseFont").unwrap_or(b"")).into_owned())
})
.collect()
}
/// #9016 review: a second added item that needs the embedded face must not take the resource name
/// of the first one's face and repoint it, so the first item keeps its own glyphs.
#[test]
fn a_second_greek_item_does_not_repoint_the_first_items_embedded_face() {
let mut doc = fixture();
if pdfcraft_fonts::document_latin_fonts(false).is_empty() {
eprintln!("skipping: built without a craft-fonts Latin face (set CRAFT_FONTS_DIR)");
return;
}
let first = AddedText { rect: [72.0, 600.0, 400.0, 700.0], text: "Καλημέρα".into(), size: 14.0, ..AddedText::default() };
add_content(&mut doc, 0, &Content::Text(first)).unwrap();
let before = embedded_faces_by_resource(&reopen(&doc));
assert!(!before.is_empty(), "the first item embeds a face");
let second = AddedText { rect: [72.0, 400.0, 400.0, 500.0], text: "Привет".into(), size: 14.0, bold: true, ..AddedText::default() };
add_content(&mut doc, 0, &Content::Text(second)).unwrap();
let after = embedded_faces_by_resource(&reopen(&doc));
for (name, base) in &before {
assert_eq!(after.get(name), Some(base), "the first item's /{name} still resolves to its own face: {before:?} -> {after:?}");
}
let regular = pdfcraft_fonts::document_latin_fonts(false).into_iter().next().map(|f| f.bytes);
let bold = pdfcraft_fonts::document_latin_fonts(true).into_iter().next().map(|f| f.bytes);
if regular != bold {
assert_eq!(after.len(), before.len() + 1, "a different face gets its own resource: {before:?} -> {after:?}");
}
}
#[test]
fn odd_hebrew_text_never_panics() {
let mut doc = fixture();
@@ -2109,6 +2350,31 @@ fn arabic_font_names(doc: &Document, page: usize) -> Vec<String> {
fonts.as_dict().unwrap().iter().map(|(k, _)| String::from_utf8_lossy(k).into_owned()).filter(|k| k.starts_with("PCAr")).collect()
}
/// The decoded content stream of the added item on `page` (by its `/PCMark /Added` tag), if any.
/// The page's own content stream also has a `Tj`, so the added stream is found by tag, not by
/// searching for `Tj`.
fn added_stream(doc: &Document, page: usize) -> Option<String> {
let p = &pdfcraft_model::pages(doc)[page];
let c = p.dict.get(b"Contents").cloned()?;
let resolved = doc.resolve(&c);
let list = match resolved.as_ref() {
Object::Array(a) => a.clone(),
other => vec![other.clone()],
};
list.iter().find(|o| stream_tag(doc, o).as_deref() == Some("Added")).map(|o| String::from_utf8_lossy(&stream_bytes(doc, o).unwrap()).into_owned())
}
/// Whether a font's descriptor carries an embedded program (`FontFile2`/`FontFile3`).
fn font_has_font_file(doc: &Document, font: &Dict) -> bool {
let Some(desc_ref) = font.get(b"DescendantFonts") else { return false };
let descendant = doc.resolve(desc_ref);
let Some(cid_ref) = descendant.as_array().and_then(|a| a.first()) else { return false };
let cid = doc.resolve(cid_ref);
let Some(desc_ref2) = cid.as_dict().and_then(|d| d.get(b"FontDescriptor")) else { return false };
let descriptor = doc.resolve(desc_ref2);
descriptor.as_dict().is_some_and(|d| d.get(b"FontFile2").is_some() || d.get(b"FontFile3").is_some())
}
#[test]
fn arabic_items_keep_their_own_fonts_through_saves_updates_and_deletes() {
let mut doc = fixture();
+15
View File
@@ -10,6 +10,21 @@ impl TextLine {
self.origin.baseline
}
/// The text rise (`Ts`, §9.3.7) the line starts drawn with, as the height it moves the
/// baseline in user space: positive is raised (a superscript), negative lowered (a
/// subscript), zero on the baseline. On upright text, `origin_baseline() - rise()` is the
/// unraised baseline.
pub fn rise(&self) -> f64 {
self.origin.state.rise * self.rise_scale()
}
/// How far one unit of `Ts` moves the baseline across itself in user space: the text space y
/// axis's part square to the baseline, so a slanted y axis counts only its height.
pub(crate) fn rise_scale(&self) -> f64 {
let m = Matrix(self.origin.tm).then(&Matrix(self.origin.ctm));
to_frame(direction(&m), (m.0[2], m.0[3])).1
}
/// Paint position of the line's first operator: `(content-stream index, operator index in
/// the page's joined stream)`. A line joins runs painted at different times, so anything
/// painted after this position may lie on top of part of it.
+10 -9
View File
@@ -1393,8 +1393,9 @@ impl<'a> RowSpacing<'a> {
fn place(&mut self, row_index: usize, mut baseline: f64) -> (f64, &'a TextLine) {
let source_row = self.sources.get(row_index).copied().flatten();
let anchor = source_row.and_then(|j| self.run_of(j));
// The baseline of the source row above the source row this row starts.
let above = source_row.and_then(|j| self.run_of(j.checked_sub(1)?)).map(|l| l.origin.baseline);
// The baseline of the source row above the source row this row starts, without its rise:
// rows are placed on unraised baselines and each run's rise is drawn on top.
let above = source_row.and_then(|j| self.run_of(j.checked_sub(1)?)).map(|l| l.origin.baseline - l.rise());
// The space this row already had above it, beyond the ordinary row step.
let existing = source_row.map_or(0.0, |j| existing_gap(self.block, self.lines, self.row_step, j));
let starts_paragraph =
@@ -1406,9 +1407,9 @@ impl<'a> RowSpacing<'a> {
// written `here - (above - previous)` so a row below unmoved rows lands exactly
// on its source baseline.
(Some(a), Some(above), Some(previous)) => {
baseline = a.origin.baseline - (above - previous) - paragraph.map_or(0.0, |gap| gap - existing);
baseline = a.origin.baseline - a.rise() - (above - previous) - paragraph.map_or(0.0, |gap| gap - existing);
}
(Some(a), _, None) => baseline = a.origin.baseline,
(Some(a), _, None) => baseline = a.origin.baseline - a.rise(),
_ => baseline -= paragraph.unwrap_or(0.0),
}
} else {
@@ -1742,9 +1743,9 @@ impl Origins {
}
}
/// The baseline of source row `row`'s first run.
/// The unraised baseline of source row `row`'s first run.
fn source_baseline(block: &TextBlock, lines: &[TextLine], row: usize) -> Option<f64> {
block.rows.get(row).and_then(|r| r.first()).and_then(|i| lines.get(*i)).map(|l| l.origin.baseline)
block.rows.get(row).and_then(|r| r.first()).and_then(|i| lines.get(*i)).map(|l| l.origin.baseline - l.rise())
}
/// The ordinary step between the block's source rows: the smallest, or `fallback` for one row.
@@ -2058,7 +2059,7 @@ pub(crate) fn rewrite_styled_block(
.filter_map(|rows| {
let a = rows[0].first().and_then(|i| lines.get(*i))?;
let b = rows[1].first().and_then(|i| lines.get(*i))?;
Some((a.origin.baseline - b.origin.baseline).abs())
Some(((a.origin.baseline - a.rise()) - (b.origin.baseline - b.rise())).abs())
})
.rfind(|v| *v > 0.0)
.unwrap_or(first.size * 1.5);
@@ -2076,7 +2077,7 @@ pub(crate) fn rewrite_styled_block(
let over = crate::revealed_under_paint(doc, page, block.invisible, reach.bounds(), &ops, at);
let initial = TextState::initial();
let drawn_from = if over { &initial } else { after };
let mut baseline = first.origin.baseline;
let mut baseline = first.origin.baseline - first.rise();
for (row_index, row) in rows.iter().enumerate() {
let anchor;
(baseline, anchor) = spacing.place(row_index, baseline);
@@ -2125,7 +2126,7 @@ pub(crate) fn rewrite_styled_block(
}
let inverse = Matrix(o.ctm).invert().ok_or_else(|| EditError::Invalid("the paragraph has a singular transform".into()))?;
let mut tm = Matrix(source.origin.tm).then(&Matrix(source.origin.ctm)).then(&inverse).0;
let (ax, ay) = back.apply(x - source.origin.x, baseline - source.origin.baseline);
let (ax, ay) = back.apply(x - source.origin.x, baseline - (source.origin.baseline - source.rise()));
tm[4] += ax;
tm[5] += ay;
let mut segment_width = segment_advances.get(&(row_index, pos)).copied().unwrap_or(0.0);
+160
View File
@@ -0,0 +1,160 @@
//! Bates numbering across several files as one run: each file's first number follows the last
//! number of the file before it. The app's Bates numbering ▸ Add to files… numbers with these
//! rules, which are the `doc_bates_multi` tool's.
use crate::{DocId, Edit, EditError, HeaderFooter, Session};
/// The most files one run numbers.
pub const BATES_MAX_FILES: usize = 1000;
/// The most characters in a prefix or a suffix.
pub const BATES_AFFIX_CHARS: usize = 128;
/// The most digits a number is padded to.
pub const BATES_MAX_DIGITS: u8 = 12;
/// The most bytes of files one run reads.
pub const BATES_MAX_BYTES: u64 = 512 * 1024 * 1024;
/// How a run's numbers read and where they are drawn.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BatesFormat {
/// The first file's first number, at least 1.
pub start: u64,
/// Numbers shorter than this are padded with zeros (1 to [`BATES_MAX_DIGITS`]).
pub digits: u8,
pub prefix: String,
pub suffix: String,
/// The header and footer box the number goes in: 0 to 2 are the header's left, centre and
/// right, 3 to 5 the footer's.
pub position: usize,
}
/// The numbers one file gets, both ends included.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BatesSpan {
pub first: u64,
pub last: u64,
}
/// Why a run can't be numbered. File indexes count from 0.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum BatesError {
#[error("the start number must be at least 1")]
Start,
#[error("the number of digits must be from 1 to 12")]
Digits,
#[error("a prefix or suffix must be at most 128 characters and can't contain # or >>")]
Affix,
#[error("the number must go in one of the six header and footer boxes")]
Position,
#[error("there are no files to number, or more than 1000")]
Count,
#[error("file {0} has no pages to number")]
NoPages(usize),
#[error("the Bates numbers of file {0} run past the largest number")]
Overflow(usize),
}
impl BatesFormat {
/// Refuses a format the Bates token can't carry.
pub fn check(&self) -> Result<(), BatesError> {
if self.start == 0 {
return Err(BatesError::Start);
}
if !(1..=BATES_MAX_DIGITS).contains(&self.digits) {
return Err(BatesError::Digits);
}
let bad = |s: &str| s.chars().count() > BATES_AFFIX_CHARS || s.contains('#') || s.contains(">>");
if bad(&self.prefix) || bad(&self.suffix) {
return Err(BatesError::Affix);
}
if self.position > 5 {
return Err(BatesError::Position);
}
Ok(())
}
/// The span of each file, in order, for files of `pages` pages each.
pub fn spans(&self, pages: &[usize]) -> Result<Vec<BatesSpan>, BatesError> {
self.check()?;
if pages.is_empty() || pages.len() > BATES_MAX_FILES {
return Err(BatesError::Count);
}
let mut spans = Vec::with_capacity(pages.len());
let mut next = Some(self.start);
for (index, &count) in pages.iter().enumerate() {
let first = next.ok_or(BatesError::Overflow(index))?;
let offset = count.checked_sub(1).ok_or(BatesError::NoPages(index))?;
let last = u64::try_from(offset).ok().and_then(|o| first.checked_add(o)).ok_or(BatesError::Overflow(index))?;
spans.push(BatesSpan { first, last });
// The last file may end on the largest number; only a file after it overflows.
next = last.checked_add(1);
}
Ok(spans)
}
/// Number `number` as the page shows it.
pub fn label(&self, number: u64) -> String {
let width = usize::from(self.digits);
format!("{}{number:0width$}{}", self.prefix, self.suffix)
}
/// Header and footer settings that number a file from `first`.
pub fn settings(&self, first: u64) -> HeaderFooter {
let mut settings = HeaderFooter::default();
if let Some(text) = settings.text.get_mut(self.position) {
*text = format!("<<Bates Number#{}#{first}#{}#{}>>", self.digits, self.prefix, self.suffix);
}
settings
}
}
impl Session {
/// Numbers every page of document `id` from `first`, as one header and footer edit.
pub fn add_bates(&mut self, id: DocId, format: &BatesFormat, first: u64) -> Result<(), EditError> {
let count = self.get(id).ok_or(EditError::NoDocument)?.info.pages.len();
self.apply(id, Edit::AddHeaderFooter { pages: (0..count).collect(), settings: format.settings(first), replace: false })
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::{BatesError, BatesFormat};
fn format(start: u64) -> BatesFormat {
BatesFormat { start, digits: 6, prefix: "CASE-".into(), suffix: String::new(), position: 5 }
}
#[test]
fn each_file_starts_after_the_last_page_of_the_file_before() {
let spans = format(17).spans(&[2, 3, 1]).unwrap();
assert_eq!(spans[0].first, 17);
for pair in spans.windows(2) {
assert_eq!(pair[1].first, pair[0].last + 1);
}
for (span, pages) in spans.iter().zip([2u64, 3, 1]) {
assert_eq!(span.last - span.first + 1, pages);
}
}
#[test]
fn only_a_file_after_the_largest_number_overflows() {
assert!(format(u64::MAX).spans(&[1]).is_ok());
assert_eq!(format(u64::MAX).spans(&[1, 1]), Err(BatesError::Overflow(1)));
assert_eq!(format(u64::MAX - 1).spans(&[3]), Err(BatesError::Overflow(0)));
assert_eq!(format(1).spans(&[2, 0]), Err(BatesError::NoPages(1)));
}
#[test]
fn a_format_the_token_cannot_carry_is_refused() {
for bad in [
BatesFormat { prefix: "A#B".into(), ..format(1) },
BatesFormat { suffix: "A>>".into(), ..format(1) },
BatesFormat { prefix: "é".repeat(129), ..format(1) },
] {
assert_eq!(bad.check(), Err(BatesError::Affix));
}
assert!(BatesFormat { prefix: "é".repeat(128), ..format(1) }.check().is_ok());
assert_eq!(BatesFormat { digits: 13, ..format(1) }.check(), Err(BatesError::Digits));
assert_eq!(format(0).check(), Err(BatesError::Start));
}
}
+2 -2
View File
@@ -145,7 +145,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[
menu_item("Header and footer", "heading", &["edit.header_footer", "edit.header_footer.update", "edit.header_footer.remove"]),
menu_item("Watermark", "stamp", &["edit.watermark", "edit.watermark.update", "edit.watermark.remove"]),
item("Link", "link", "edit.link", Ready),
item("Bates numbering", "hash", "edit.bates", Ready),
menu_item("Bates numbering", "hash", &["edit.bates", "edit.bates_files"]),
menu_item("Background", "palette", &["edit.background", "edit.background.update", "edit.background.remove"]),
item("Attach file", "paperclip", "edit.attach", Ready),
],
@@ -327,7 +327,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[
items: &[
item("Reduce file size", "file-down", "optimize.reduce", Ready),
item("Advanced optimization", "settings-2", "optimize.advanced", Ready),
item("Audit space usage", "gauge", "optimize.audit", Planned("M11")),
item("Audit space usage", "gauge", "optimize.audit", Ready),
],
}],
},
+3
View File
@@ -293,6 +293,7 @@ pub const COMMANDS: &[CommandSpec] = &[
Nothing,
"panel-left",
),
c("view.rulers", "Rulers", VIEW, Some(Shortcut::cmd("R")), Document, "ruler"),
c("ui.dock.reset", "Reset side panels", VIEW, None, Nothing, "settings"),
c("view.theme", "Switch light / dark theme", None, None, Nothing, "moon"),
c("view.theme.system", "Use system setting", None, None, Nothing, "settings"),
@@ -350,6 +351,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("edit.links_from_urls", "Create links from URLs", None, None, Modification, "link"),
c("edit.remove_links", "Remove all links", None, None, Modification, "trash-2"),
c("edit.bates", "Add Bates numbering…", None, None, Modification, "hash"),
c("edit.bates_files", "Add Bates numbering to files…", None, None, Nothing, "files"),
c("edit.image", "Add image…", None, None, Modification, "image-plus"),
c("redact.mark", "Redact text and images", None, None, Modification, "rectangle"),
c("redact.pages", "Redact pages…", None, None, Modification, "file-x"),
@@ -390,6 +392,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("export.image", "Export to image…", FILE, None, Copying, "image"),
c("optimize.reduce", "Reduce file size…", FILE, None, Document, "file-down"),
c("optimize.advanced", "Optimize PDF…", FILE, None, Document, "settings-2"),
c("optimize.audit", "Audit space usage…", None, None, Document, "gauge"),
c("export.text", "Export to text…", FILE, None, Copying, "type"),
c("export.docx", "Export to Word…", FILE, None, Copying, "file-text"),
c("export.pptx", "Export to PowerPoint…", FILE, None, Copying, "presentation"),
+281 -19
View File
@@ -26,6 +26,61 @@ pub fn colour(kind: Kind) -> crate::Rgb {
}
}
/// Merge word boxes into rectangles, keeping each rectangle on a single page. Rectangles are
/// never merged across a page boundary, so a change that spans pages keeps one rectangle per
/// page instead of attaching later-page rectangles to the first page.
fn rects_for_words(words: &[pdfcraft_compare::Word]) -> (Vec<[f64; 4]>, Vec<usize>) {
let mut out: Vec<[f64; 4]> = Vec::new();
let mut pages: Vec<usize> = Vec::new();
for w in words {
let r = w.rect;
if let Some(last) = out.last_mut() {
let last_page = pages.last().copied().unwrap_or(w.page);
if last_page == w.page
&& (last[1] - r[1]).abs() < (r[3] - r[1]).max(1.0) * 0.5
&& r[0] - last[2] < (r[3] - r[1]).max(4.0) * 2.0
&& r[0] >= last[0] - 1.0
{
last[0] = last[0].min(r[0]);
last[1] = last[1].min(r[1]);
last[2] = last[2].max(r[2]);
last[3] = last[3].max(r[3]);
continue;
}
}
out.push(r);
pages.push(w.page);
}
(out, pages)
}
fn rects_overlap(a: [f64; 4], b: [f64; 4]) -> bool {
a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1]
}
/// The first run of `text`'s words at or after `from` that reads as `text` and, for a change
/// with a position, sits where the change was found: on its page and inside its rectangles (or
/// its anchor). `None` when the document holds no such run.
fn find_run(words: &[pdfcraft_compare::Word], text: &str, from: usize, page: usize, rects: &[[f64; 4]], near: Option<[f64; 4]>) -> Option<usize> {
let wanted: Vec<&str> = text.split_whitespace().collect();
let count = wanted.len();
if count == 0 || count > words.len() || from > words.len() - count {
return None;
}
let positional = !rects.is_empty() || near.is_some();
(from..=words.len() - count).find(|&start| {
let run = &words[start..start + count];
run.iter().zip(&wanted).all(|(word, text)| word.text == *text)
&& run[0].page == page
&& (!positional
|| if rects.is_empty() {
near.is_some_and(|anchor| rects_overlap(run[0].rect, anchor))
} else {
run.iter().all(|word| rects.iter().any(|rect| rects_overlap(word.rect, *rect)))
})
})
}
impl crate::Document {
/// Standards ▸ Verify PDF/A: the rules the document breaks for `level`.
pub fn pdfa_verify(&self, level: pdfcraft_preflight::Level) -> Vec<pdfcraft_preflight::Issue> {
@@ -39,10 +94,19 @@ impl crate::Document {
/// Every word of the document in reading order, with page and box.
pub fn words(&self) -> Vec<pdfcraft_compare::Word> {
self.words_on_pages(&[])
}
/// [`Self::words`] of the 0-based `pages` only (every page when empty): pages not
/// selected are skipped before any text is extracted from them.
pub fn words_on_pages(&self, pages: &[usize]) -> Vec<pdfcraft_compare::Word> {
let config = pdfcraft_render::RenderConfig { password: self.password.as_deref().map(Arc::from), ..Default::default() };
let mut r = pdfcraft_render::PageRenderer::new(self.bytes.clone(), config);
let mut out = Vec::new();
for (page, info) in self.info.pages.iter().enumerate() {
if !pages.is_empty() && !pages.contains(&page) {
continue;
}
let res = r.render(pdfcraft_render::RenderRequest { page, kind: pdfcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() });
if let Some(t) = res.text {
out.extend(crate::js::page_words(&t, info).into_iter().map(|(text, rect)| pdfcraft_compare::Word { text, page, rect }));
@@ -56,25 +120,51 @@ impl Session {
/// Compare files: the text differences from document `old` to document `new`. The result
/// carries both documents' text, so both must allow copying it.
pub fn compare(&self, old: DocId, new: DocId) -> Result<Comparison, EditError> {
self.compare_pages(old, new, &[])
}
/// [`Session::compare`], restricted to the 0-based `pages` (every page when empty):
/// words on other pages take no part in the diff.
pub fn compare_pages(&self, old: DocId, new: DocId, pages: &[usize]) -> Result<Comparison, EditError> {
let a = self.get(old).ok_or(EditError::NoDocument)?;
let b = self.get(new).ok_or(EditError::NoDocument)?;
a.check_copying()?;
b.check_copying()?;
Ok(pdfcraft_compare::compare(&a.words(), &b.words()))
}
/// [`Session::compare`], keeping the changes on `pages` of `new` (0-based; empty: every page).
pub fn compare_pages(&self, old: DocId, new: DocId, pages: &[usize]) -> Result<Comparison, EditError> {
let mut c = self.compare(old, new)?;
if !pages.is_empty() {
c.changes.retain(|ch| pages.iter().any(|page| (ch.new.page..=ch.new.last_page).contains(page)));
let (old_words, new_words) = (a.words_on_pages(pages), b.words_on_pages(pages));
let mut c = pdfcraft_compare::compare(&old_words, &new_words);
let new_pages = b.info.pages.len();
for ch in &mut c.changes {
// A deletion keeps the newer document's own anchor when it has one. Otherwise it goes
// on the old page when the newer document has that page, or else on the newer
// document's last page, at its top left.
if ch.new.rects.is_empty() && ch.new.near.is_none() {
let page = ch.old.page.min(new_pages.saturating_sub(1));
ch.new.page = page;
ch.new.near = if ch.old.page == page { ch.old.rects.first().copied() } else { None };
if ch.new.near.is_none() {
ch.new.near = b.info.pages.get(page).map(|info| info.crop.map(f64::from));
}
}
if ch.old.rects.is_empty() {
ch.old.page = ch.new.page;
if ch.old.near.is_none() {
ch.old.near = ch.new.rects.first().copied();
}
}
}
Ok(c)
}
/// Visual compare: regions where page n of `new` looks different from page n of `old`
/// (rendered at `dpi`), as (page, user-space box in `new`).
/// (rendered at `dpi`), as (page, user-space box in `new`). Every shared page is
/// compared when `pages` is empty, otherwise only the selected pages are rendered.
pub fn compare_visual(&self, old: DocId, new: DocId, dpi: f32) -> Result<Vec<(usize, [f64; 4])>, EditError> {
self.compare_visual_on_pages(old, new, dpi, &[])
}
/// [`Session::compare_visual`] of the 0-based `pages` only (every shared page when
/// empty): pages not selected are skipped before any of them is rendered.
pub fn compare_visual_on_pages(&self, old: DocId, new: DocId, dpi: f32, pages: &[usize]) -> Result<Vec<(usize, [f64; 4])>, EditError> {
let a = self.get(old).ok_or(EditError::NoDocument)?;
let b = self.get(new).ok_or(EditError::NoDocument)?;
let renderer = |d: &crate::Document| {
@@ -87,6 +177,9 @@ impl Session {
let scale = dpi.clamp(18.0, 150.0) / 72.0;
let mut out = Vec::new();
for (page, info) in b.info.pages.iter().enumerate().take(a.info.pages.len()) {
if !pages.is_empty() && !pages.contains(&page) {
continue;
}
let req = pdfcraft_render::RenderRequest { page, scale, ..Default::default() };
let (x, y) = (ra.render(req), rb.render(req));
if x.error.is_some() || y.error.is_some() {
@@ -124,6 +217,23 @@ impl Session {
/// [`Session::mark_differences`] of the changes on `pages` ([`Session::compare_pages`]).
pub fn mark_differences_of(&mut self, old: DocId, new: DocId, pages: &[usize]) -> Result<usize, EditError> {
let c = self.compare_pages(old, new, pages)?;
let old_words = {
let a = self.get(old).ok_or(EditError::NoDocument)?;
a.words_on_pages(pages)
};
let new_words = {
let b = self.get(new).ok_or(EditError::NoDocument)?;
b.words_on_pages(pages)
};
let new_page_crops: Vec<Option<[f64; 4]>> =
self.get(new).map(|d| d.info.pages.iter().map(|info| Some(info.crop.map(f64::from))).collect()).unwrap_or_default();
let new_pages = new_page_crops.len();
// `compare` groups consecutive edits into one `Change`, and a change's new-side
// words are a contiguous run of `new_words` with unchanged words between changes.
// Track where the next run may start instead of counting only changed words, so
// unchanged words before a change are not mistaken for its words.
let mut new_search_from = 0usize;
let mut old_search_from = 0usize;
let mut edits = Vec::new();
for ch in &c.changes {
let color = colour(ch.kind);
@@ -132,18 +242,119 @@ impl Session {
Kind::Inserted => format!("Inserted: \"{}\"", ch.new.text),
Kind::Deleted => format!("Deleted: \"{}\"", ch.old.text),
};
let shape = if ch.new.rects.is_empty() {
let Some(r) = ch.new.near else { continue };
Shape::Note { at: [r[0], r[3]], icon: NoteIcon::Note }
} else {
Shape::TextMarkup {
kind: Markup::Highlight,
quads: ch.new.rects.iter().map(|r| [r[0], r[3], r[2], r[3], r[0], r[1], r[2], r[1]]).collect(),
// `compare` groups consecutive edits into one `Change`, and a change's new-side
// words are a contiguous run of `new_words` with unchanged words between changes:
// search on from the previous change's end first, then from the start.
let new_slice = match find_run(&new_words, &ch.new.text, new_search_from, ch.new.page, &ch.new.rects, ch.new.near)
.or_else(|| find_run(&new_words, &ch.new.text, 0, ch.new.page, &ch.new.rects, ch.new.near))
{
Some(start) => {
let count = ch.new.text.split_whitespace().count();
new_search_from = (start + count).min(new_words.len());
&new_words[start..start + count]
}
// The change's words aren't in the document as words (spacing, ligatures): the
// rectangles the diff found are used as they are.
None => &new_words[0..0],
};
let mut style = crate::Style::default_for(&shape);
style.color = color;
edits.push(Edit::AddAnnotation(NewAnnotation { page: ch.new.page, shape, style, contents, author: "Compare".into() }));
let old_word_count = ch.old.text.split_whitespace().count();
let mut old_slice = None;
if old_word_count > 0 && old_word_count <= old_words.len() {
let found = find_run(&old_words, &ch.old.text, old_search_from, ch.old.page, &ch.old.rects, ch.old.near)
.or_else(|| find_run(&old_words, &ch.old.text, 0, ch.old.page, &ch.old.rects, ch.old.near));
if let Some(start) = found {
old_search_from = (start + old_word_count).min(old_words.len());
if ch.kind == Kind::Deleted {
old_slice = Some(&old_words[start..start + old_word_count]);
}
}
}
if ch.kind == Kind::Deleted {
if let Some(slice) = old_slice {
let mut pages_in_order: Vec<usize> = Vec::new();
for w in slice {
if !pages_in_order.contains(&w.page) {
pages_in_order.push(w.page);
}
}
for page in pages_in_order {
let first_rect = slice.iter().filter(|w| w.page == page).map(|w| w.rect).next();
let target_page = if page < new_pages { page } else { new_pages.saturating_sub(1) };
let near = if page == target_page { first_rect } else { None };
let near = near.or_else(|| new_page_crops.get(target_page).copied().flatten());
let Some(r) = near else { continue };
let shape = Shape::Note { at: [r[0], r[3]], icon: NoteIcon::Note };
let mut style = crate::Style::default_for(&shape);
style.color = color;
edits.push(Edit::AddAnnotation(NewAnnotation {
page: target_page,
shape,
style,
contents: contents.clone(),
author: "Compare".into(),
}));
}
continue;
}
let mut pages_in_order: Vec<usize> =
if ch.old.page <= ch.old.last_page { (ch.old.page..=ch.old.last_page).collect() } else { vec![ch.old.page] };
pages_in_order.retain(|p| pages.is_empty() || pages.contains(p));
pages_in_order.sort();
pages_in_order.dedup();
if pages_in_order.is_empty() {
pages_in_order.push(ch.old.page);
}
for page in pages_in_order {
let target_page = if page < new_pages { page } else { new_pages.saturating_sub(1) };
let first_rect = if page == target_page { new_words.iter().find(|w| w.page == target_page).map(|w| w.rect) } else { None };
let near = first_rect.or_else(|| new_page_crops.get(target_page).copied().flatten());
let Some(r) = near else { continue };
let shape = Shape::Note { at: [r[0], r[3]], icon: NoteIcon::Note };
let mut style = crate::Style::default_for(&shape);
style.color = color;
edits.push(Edit::AddAnnotation(NewAnnotation {
page: target_page,
shape,
style,
contents: contents.clone(),
author: "Compare".into(),
}));
}
continue;
}
if ch.new.rects.is_empty() {
let Some(r) = ch.new.near else { continue };
let shape = Shape::Note { at: [r[0], r[3]], icon: NoteIcon::Note };
let mut style = crate::Style::default_for(&shape);
style.color = color;
edits.push(Edit::AddAnnotation(NewAnnotation { page: ch.new.page, shape, style, contents, author: "Compare".into() }));
continue;
}
// A change can span several pages, and its rectangles keep their own pages. Re-derive
// the rectangles from the change's words so later-page rectangles are not attached to
// the first page or lost.
let (rects, rect_pages) = rects_for_words(new_slice);
let (rects, rect_pages) =
if rects.is_empty() { (ch.new.rects.clone(), vec![ch.new.page; ch.new.rects.len()]) } else { (rects, rect_pages) };
let mut pages_in_order: Vec<usize> = Vec::new();
for page in &rect_pages {
if !pages_in_order.contains(page) {
pages_in_order.push(*page);
}
}
for page in pages_in_order {
let rects: Vec<[f64; 4]> = rects.iter().zip(&rect_pages).filter(|(_, p)| **p == page).map(|(r, _)| *r).collect();
let shape = Shape::TextMarkup {
kind: Markup::Highlight,
quads: rects.iter().map(|r| [r[0], r[3], r[2], r[3], r[0], r[1], r[2], r[1]]).collect(),
};
let mut style = crate::Style::default_for(&shape);
style.color = color;
edits.push(Edit::AddAnnotation(NewAnnotation { page, shape, style, contents: contents.clone(), author: "Compare".into() }));
}
}
let n = edits.len();
if n > 0 {
@@ -354,3 +565,54 @@ impl crate::Document {
OfficeExport { bytes, truncated_pages }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mark_differences_marks_each_occurrence() {
let build = |second: &str| -> Vec<u8> {
let first_text = "Rate 950";
let second_text = second;
let c1 = format!("BT /F1 12 Tf 100 700 Td ({first_text}) Tj ET");
let c2 = format!("BT /F1 12 Tf 100 700 Td ({second_text}) Tj ET");
let o1 = "<< /Type /Catalog /Pages 2 0 R >>".to_string();
let o2 = "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".to_string();
let o3 = "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 6 0 R >>".to_string();
let o4 = "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 7 0 R >>".to_string();
let o5 = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string();
let o6 = format!("<< /Length {} >>\nstream\n{}\nendstream", c1.len(), c1);
let o7 = format!("<< /Length {} >>\nstream\n{}\nendstream", c2.len(), c2);
let objects = [o1, o2, o3, o4, o5, o6, o7];
let mut pdf = String::new();
pdf.push_str("%PDF-1.4\n");
let mut offsets = Vec::new();
for obj in &objects {
offsets.push(pdf.len());
pdf.push_str(&format!("{} 0 obj\n{}\nendobj\n", offsets.len(), obj));
}
let xref = pdf.len();
pdf.push_str("xref\n0 8\n0000000000 65535 f \n");
for off in offsets {
pdf.push_str(&format!("{:010} 00000 n \n", off));
}
pdf.push_str(&format!("trailer\n<< /Size 8 /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n", xref));
pdf.into_bytes()
};
let old_bytes = build("Rate 900");
let new_bytes = build("Rate 950");
let mut session = Session::new();
let old = session.open("old.pdf", None, Arc::new(old_bytes), None).unwrap();
let new = session.open("new.pdf", None, Arc::new(new_bytes), None).unwrap();
let marked = session.mark_differences_of(old, new, &[]).unwrap();
assert_eq!(marked, 1);
let doc = session.get(new).unwrap();
assert!((0..2).any(|i| doc.comment_props(1, i).is_some()));
assert!((0..2).all(|i| doc.comment_props(0, i).is_none()));
}
}
+5
View File
@@ -776,6 +776,11 @@ impl Document {
self.editor.as_ref().and_then(|e| pdfcraft_organize::page_boxes(&e.cos).ok()).unwrap_or_default()
}
/// The page-defined bleed, trim and art boxes in user space, without fallback boxes.
pub fn defined_page_boxes(&self) -> Vec<[Option<[f64; 4]>; 3]> {
self.editor.as_ref().and_then(|e| pdfcraft_organize::defined_page_boxes(&e.cos).ok()).unwrap_or_default()
}
/// Every page's `/UserUnit`: points per user-space unit, read as Acrobat reads it (1 when absent or invalid).
pub fn page_user_units(&self) -> Vec<f64> {
self.editor.as_ref().map(|e| pdfcraft_model::pages(&e.cos).iter().map(|p| p.user_unit(&e.cos)).collect()).unwrap_or_default()
+23
View File
@@ -267,6 +267,13 @@ pub enum Edit {
rect: Option<[f64; 4]>,
open: Option<bool>,
},
/// Change the text a highlight, underline, strikethrough or squiggly underline marks: its new
/// text area, a `/QuadPoints` quadrilateral per line (user space).
SetMarkupRange {
page: usize,
index: usize,
quads: Vec<[f64; 8]>,
},
/// Resize a rectangle, oval or text box.
ResizeAnnotation {
page: usize,
@@ -363,6 +370,22 @@ pub enum Edit {
name: String,
pages: Vec<usize>,
},
/// Copy and paste a field: a new, independent field made of copies of its widgets
/// `widgets` (all when empty), on `page`, moved by `offset` (user space).
PasteField {
name: String,
widgets: Vec<usize>,
page: usize,
offset: [f64; 2],
},
/// Copy one widget into a separately named field on a page.
CopyField {
source: String,
widget: usize,
page: usize,
rect: [f64; 4],
name: String,
},
DeleteField {
name: String,
},
+6
View File
@@ -94,6 +94,7 @@ pub const EDIT_LABELS: &[&str] = &[
"Open comment pop-up",
"Close comment pop-up",
"Move comment pop-up",
"Change marked text",
"Resize comment",
"Change comment properties",
"Fill in {name}",
@@ -103,6 +104,7 @@ pub const EDIT_LABELS: &[&str] = &[
"Change field properties",
"Delete field",
"Duplicate field",
"Paste field",
"Set tab order",
"Set calculation order",
"Change initial view",
@@ -177,6 +179,7 @@ pub const BATCH_LABELS: &[&str] = &[
"Run JavaScript",
"Recognize text",
field_table::LABEL,
field_table::COPY_LABEL,
"Style",
crate::find_replace::REPLACE_ALL,
];
@@ -253,6 +256,7 @@ impl Edit {
Edit::SetAnnotationPopup { rect: Some(_), .. } => Label::of("Move comment pop-up"),
Edit::SetAnnotationPopup { open: Some(true), .. } => Label::of("Open comment pop-up"),
Edit::SetAnnotationPopup { .. } => Label::of("Close comment pop-up"),
Edit::SetMarkupRange { .. } => Label::of("Change marked text"),
Edit::ResizeAnnotation { .. } => Label::of("Resize comment"),
Edit::StyleAnnotation { .. }
| Edit::FillAnnotation { .. }
@@ -268,6 +272,8 @@ impl Edit {
Edit::SetFieldProps { .. } => Label::of("Change field properties"),
Edit::DeleteField { .. } | Edit::DeleteWidget { .. } => Label::of("Delete field"),
Edit::DuplicateField { .. } => Label::of("Duplicate field"),
Edit::PasteField { .. } => Label::of("Paste field"),
Edit::CopyField { .. } => Label::of("Duplicate field"),
Edit::SetTabOrder { .. } | Edit::MoveInTabOrder { .. } => Label::of("Set tab order"),
Edit::SetCalculationOrder { .. } => Label::of("Set calculation order"),
Edit::SetInitialView(_) => Label::of("Change initial view"),
+11
View File
@@ -65,6 +65,7 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re
| Edit::MoveAnnotation { .. }
| Edit::ReshapeAnnotation { .. }
| Edit::SetAnnotationPopup { .. }
| Edit::SetMarkupRange { .. }
| Edit::ResizeAnnotation { .. }
| Edit::StyleAnnotation { .. }
| Edit::FillAnnotation { .. }
@@ -140,6 +141,8 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re
| Edit::DeleteField { .. }
| Edit::DeleteWidget { .. }
| Edit::DuplicateField { .. }
| Edit::CopyField { .. }
| Edit::PasteField { .. }
| Edit::SetTabOrder { .. }
| Edit::MoveInTabOrder { .. }
| Edit::SetCalculationOrder { .. }
@@ -751,6 +754,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
Edit::MoveAnnotation { page, index, dx, dy } => pdfcraft_annot::move_annotation(doc, *page, *index, *dx, *dy, &cx.meta())?,
Edit::ReshapeAnnotation { page, index, points } => pdfcraft_annot::set_points(doc, *page, *index, points, &cx.meta())?,
Edit::SetAnnotationPopup { page, index, rect, open } => pdfcraft_annot::set_popup(doc, *page, *index, *rect, *open, &cx.meta())?,
Edit::SetMarkupRange { page, index, quads } => pdfcraft_annot::set_quads(doc, *page, *index, quads, &cx.meta())?,
Edit::ResizeAnnotation { page, index, rect } => pdfcraft_annot::set_rect(doc, *page, *index, *rect, &cx.meta())?,
Edit::StyleAnnotation { page, index, color, opacity, width, endings } => {
pdfcraft_annot::set_style(
@@ -880,6 +884,9 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
}
invalidate_form_script_snapshot(cx);
}
Edit::PasteField { name, widgets, page, offset } => {
pdfcraft_forms::paste_field(doc, name, widgets, *page, *offset)?;
}
Edit::DeleteField { name } => {
pdfcraft_forms::delete_field(doc, name)?;
invalidate_form_script_snapshot(cx);
@@ -888,6 +895,10 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
pdfcraft_forms::delete_widget(doc, name, *widget)?;
invalidate_form_script_snapshot(cx);
}
Edit::CopyField { source, widget, page, rect, name } => {
pdfcraft_forms::copy_field(doc, source, *widget, *page, *rect, name)?;
invalidate_form_script_snapshot(cx);
}
Edit::SetTabOrder { pages, order } => pdfcraft_forms::set_tab_order(doc, pages, *order)?,
Edit::MoveInTabOrder { name, earlier } => pdfcraft_forms::move_in_tab_order(doc, name, *earlier)?,
// As after a script edit: the values the new order gives show at once.
+83
View File
@@ -12,6 +12,9 @@ use crate::{Edit, FormField, NewField};
/// The edit's name in the history ("Undo Add text field table"), one of [`crate::BATCH_LABELS`].
pub const LABEL: &str = "Add text field table";
/// The history entry for a grid copied from an existing field.
pub const COPY_LABEL: &str = "Copy field into grid";
/// The edit adding `table`'s cells to `page` (0-based, shown as `info`) of a document whose
/// fields are `form`. Refused, with nothing added, when a cell would be too small on the page or
/// its name can't be used.
@@ -40,6 +43,35 @@ pub fn edit(table: &FieldTable, page: usize, info: &PageInfo, form: &[FormField]
Ok(Edit::Batch { label: LABEL.to_owned(), edits })
}
/// Whether a grid can copy widget `widget` of `field`: `pdfcraft_forms::copy_field`'s own test
/// ([`pdfcraft_forms::copyable_widget`]), so the preview and the copy agree.
pub fn copyable(field: &FormField, widget: usize) -> bool {
pdfcraft_forms::copyable_widget(field, widget).is_ok()
}
/// The edit laying `table` out as independent copies of widget `widget` of the field `source`,
/// one copy in each cell. Refused, with nothing added, for a field a grid can't copy
/// ([`copyable`]) and for whatever [`edit`] refuses.
pub fn copy_edit(table: &FieldTable, page: usize, info: &PageInfo, form: &[FormField], source: &str, widget: usize) -> Result<Edit, TableError> {
if !form.iter().any(|f| f.name == source && copyable(f, widget)) {
return Err(TableError::Uncopyable(source.to_owned()));
}
let batch = edit(table, page, info, form)?;
Ok(match batch {
Edit::Batch { edits, .. } => Edit::Batch {
label: COPY_LABEL.to_owned(),
edits: edits
.into_iter()
.map(|edit| match edit {
Edit::AddField { page, rect, name: Some(name), .. } => Edit::CopyField { source: source.to_owned(), widget, page, rect, name },
other => other,
})
.collect(),
},
other => other,
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -81,6 +113,57 @@ mod tests {
assert!(s.get(id).unwrap().form.is_empty(), "one undo takes the whole table back");
}
#[test]
fn a_grid_of_field_copies_is_one_undoable_edit() {
let mut s = Session::new();
let bytes = s.create_blank(300.0, 400.0, 1).unwrap();
let id = s.open("copies.pdf", None, bytes, None).unwrap();
s.apply(
id,
Edit::AddField { page: 0, rect: [30.0, 330.0, 130.0, 350.0], kind: NewField::Text { multiline: true }, name: Some("source".into()) },
)
.unwrap();
let table = grid([30.0, 100.0, 230.0, 180.0], 2, &["a_N", "b_N"]);
let doc = s.get(id).unwrap();
let edit = copy_edit(&table, 0, &doc.info.pages[0], &doc.form, "source", 0).unwrap();
s.apply(id, edit).unwrap();
let form = &s.get(id).unwrap().form;
assert_eq!(form.len(), 5);
for name in ["a_1", "b_1", "a_2", "b_2"] {
assert!(form.iter().find(|f| f.name == name).unwrap().has(pdfcraft_forms::flags::MULTILINE));
}
assert_eq!(s.undo(id).unwrap().to_string(), COPY_LABEL);
assert_eq!(s.get(id).unwrap().form.len(), 1);
}
#[test]
fn a_grid_copies_a_check_box_only_when_its_widgets_export_one_value() {
let mut s = Session::new();
let bytes = s.create_blank(300.0, 400.0, 1).unwrap();
let id = s.open("boxes.pdf", None, bytes, None).unwrap();
s.apply(id, Edit::AddField { page: 0, rect: [30.0, 330.0, 50.0, 350.0], kind: NewField::CheckBox, name: Some("box".into()) }).unwrap();
let doc = s.get(id).unwrap();
let table = grid([30.0, 100.0, 230.0, 180.0], 2, &["a_N"]);
assert!(copy_edit(&table, 0, &doc.info.pages[0], &doc.form, "box", 0).is_ok());
// The same box as two widgets with an export value each (`/Opt`), as the forms layer reads it.
let mut form = doc.form.to_vec();
let boxes = form.iter_mut().find(|f| f.name == "box").unwrap();
boxes.widgets.push(boxes.widgets[0].clone());
boxes.options = vec![("Yes".into(), "Yes".into()), ("No".into(), "No".into())];
let refused = copy_edit(&table, 0, &doc.info.pages[0], &form, "box", 0);
assert_eq!(refused.err(), Some(TableError::Uncopyable("box".into())), "the preview can't call it valid");
// One export value from every widget is a box a grid copies, `/Opt` or not.
let boxes = form.iter_mut().find(|f| f.name == "box").unwrap();
boxes.options = vec![("Yes".into(), "Yes".into()); 2];
assert!(copy_edit(&table, 0, &doc.info.pages[0], &form, "box", 0).is_ok());
// Different on states without `/Opt` are different export values.
let boxes = form.iter_mut().find(|f| f.name == "box").unwrap();
boxes.options.clear();
boxes.widgets[1].on_state = Some("Other".into());
let refused = copy_edit(&table, 0, &doc.info.pages[0], &form, "box", 0);
assert_eq!(refused.err(), Some(TableError::Uncopyable("box".into())));
}
#[test]
fn rows_run_down_a_turned_page_as_it_is_shown() {
let mut s = Session::new();
+1
View File
@@ -72,6 +72,7 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope {
| Edit::MoveAnnotation { .. }
| Edit::ReshapeAnnotation { .. }
| Edit::SetAnnotationPopup { .. }
| Edit::SetMarkupRange { .. }
| Edit::ResizeAnnotation { .. }
| Edit::StyleAnnotation { .. }
| Edit::FillAnnotation { .. }
+1 -1
View File
@@ -1658,7 +1658,7 @@ mod review_tests {
assert_eq!(outcome.changed.len(), 1);
assert_eq!(
changes(&before, &outcome.changed, &outcome.formatted),
vec![FieldChange { name: "duplicate".into(), value: Some(vec!["updated".into()]), ..Default::default() }]
vec![FieldChange { name: "duplicate".into(), value: Some(vec!["updated".into()]), formatted: true, ..Default::default() }]
);
assert!(changes(&before, &[], &formatted).is_empty());
let mut missing = first;
+4
View File
@@ -14,6 +14,8 @@
pub mod actions;
pub mod autotag;
mod bates_files;
pub use bates_files::{BATES_AFFIX_CHARS, BATES_MAX_BYTES, BATES_MAX_DIGITS, BATES_MAX_FILES, BatesError, BatesFormat, BatesSpan};
mod bookmarks;
pub mod build_info;
pub mod camera;
@@ -39,6 +41,7 @@ pub mod js;
mod layers;
pub mod links;
mod live_scripts;
mod mark_picture;
pub mod model3d;
mod object_clip;
pub mod ocr;
@@ -79,6 +82,7 @@ pub use links::{
MAX_REMOTE_DOCUMENT_BYTES, RemoteDocumentPathError, read_remote_document, remote_document_path_is_absolute, resolve_remote_document_path,
};
pub use live_scripts::{MAX_TIMER_RUNS, ScriptRun};
pub use mark_picture::{MAX_MARK_PICTURE_SIDE, MarkPicture, mark_picture};
pub use pdfcraft_edit::strip_subset_tag;
pub use rich_copy::RichCopy;
pub use signature_image::{ImageSignaturePreview, SignatureImage};
+175
View File
@@ -0,0 +1,175 @@
//! The picture of a watermark or background taken from a file (Source ▸ File), for the dialogs'
//! preview: brought in the way OK brings it in, drawn alone on a page of its shape, and rendered
//! small, transparent where it draws nothing.
use std::sync::Arc;
use pdfcraft_cos::Object;
use pdfcraft_render::{PageRenderer, Pixels, RenderConfig, RenderRequest, RenderedPage, effective_scale};
use crate::{MarkFile, guard, mark_source};
/// The longest side [`mark_picture`] renders, in pixels, whatever it is asked for.
pub const MAX_MARK_PICTURE_SIDE: u32 = 2048;
/// The longer side of the page the picture is drawn on, in points. Only its shape matters: the
/// picture is fitted to it, as a mark is fitted to the page it goes on.
const SHEET: f64 = 1000.0;
/// A mark's picture, as [`mark_picture`] renders it.
#[derive(Clone, Debug, PartialEq)]
pub struct MarkPicture {
/// The picture's size in points, which a watermark or background fits to the page at its
/// scale (`picture` in `pdfcraft-edit`).
pub size: (f64, f64),
/// The raster's size in pixels.
pub width: u32,
pub height: u32,
/// Premultiplied RGBA8, row-major: transparent where the picture draws nothing.
pub rgba: Pixels,
}
/// Render the picture `f` adds as a watermark or background, its longer side `max_side` pixels
/// (at most [`MAX_MARK_PICTURE_SIDE`]). It is brought in as OK brings it in (an image turned
/// upright by its EXIF orientation, a page of a PDF as a form, upright), so a file OK refuses is
/// refused here too. Never panics.
pub fn mark_picture(f: &MarkFile, max_side: u32) -> Result<MarkPicture, String> {
guard(|| render(f, max_side))?
}
fn render(f: &MarkFile, max_side: u32) -> Result<MarkPicture, String> {
// Two pages of the picture's shape: the picture alone, on the renderer's white paper, and
// the picture over black. Between them they give its transparency.
let mut doc = pdfcraft_create::blank(SHEET, SHEET, 2).map_err(|e| e.to_string())?;
let src = mark_source(&mut doc, f).map_err(|e| e.to_string())?;
let (w, h) = src.size;
if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
return Err(format!("{}: the picture has no size", f.name));
}
let k = SHEET / w.max(h);
let (pw, ph) = ((w * k).max(1.0), (h * k).max(1.0));
let media = Object::Array(vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)]);
for page in pdfcraft_model::pages(&doc) {
doc.update_dict(page.obj, |d| d.set(b"MediaBox".to_vec(), media.clone())).map_err(|e| e.to_string())?;
}
let black = pdfcraft_edit::Background { color: [0.0; 3], opacity: 1.0, source: None, scale: 1.0, replace_backdrop: false };
pdfcraft_edit::add_background(&mut doc, &[1], &black, false).map_err(|e| e.to_string())?;
let whole = pdfcraft_edit::Watermark { source: Some(src), scale: 1.0, opacity: 1.0, rotation: 0.0, ..Default::default() };
pdfcraft_edit::add_watermark(&mut doc, &[0, 1], &whole, false).map_err(|e| e.to_string())?;
let bytes = Arc::new(pdfcraft_cos::write_full(&doc, &pdfcraft_cos::SaveOptions::default()).map_err(|e| e.to_string())?);
let side = max_side.clamp(1, MAX_MARK_PICTURE_SIDE) as f32;
let scale = effective_scale(pw as f32, ph as f32, side / pw.max(ph) as f32);
let mut renderer = PageRenderer::new(bytes, RenderConfig::default());
let mut page = |n: usize| -> Result<RenderedPage, String> {
let out = renderer.render(RenderRequest { page: n, scale, ..Default::default() });
match out.error {
Some(e) => Err(e),
None => Ok(out),
}
};
let (on_white, on_black) = (page(0)?, page(1)?);
if (on_white.width, on_white.height) != (on_black.width, on_black.height) || on_white.rgba.len() != on_black.rgba.len() {
return Err("the picture rendered at two sizes".into());
}
Ok(MarkPicture { size: src.size, width: on_black.width, height: on_black.height, rgba: unpaper(&on_white.rgba, &on_black.rgba) })
}
/// The picture with its transparency, from its renders on white and over black. Where it lets
/// `1 − a` of what is behind it through, it is that much lighter on white than over black, and
/// over black it is itself, premultiplied.
fn unpaper(on_white: &[u8], on_black: &[u8]) -> Pixels {
let (white, _) = on_white.as_chunks::<4>();
let (black, _) = on_black.as_chunks::<4>();
let words = white
.iter()
.zip(black)
.map(|(&[wr, wg, wb, _], &[br, bg, bb, _])| {
let a = 255 - wr.saturating_sub(br).max(wg.saturating_sub(bg)).max(wb.saturating_sub(bb));
u32::from_ne_bytes([br.min(a), bg.min(a), bb.min(a), a])
})
.collect::<Vec<u32>>();
Pixels::from(words)
}
#[cfg(test)]
mod tests {
use super::*;
fn png(w: u32, h: u32, px: impl Fn(u32, u32) -> [u8; 4]) -> Vec<u8> {
let data: Vec<u8> = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| px(x, y)).collect();
let img = craft_image_codecs::Image::from_u8(w, h, craft_image_codecs::ChannelLayout::Rgba, data).unwrap();
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &Default::default()).unwrap()
}
fn file(name: &str, bytes: Vec<u8>, page: usize) -> MarkFile {
MarkFile { name: name.into(), bytes: Arc::new(bytes), page }
}
/// The pixel at (`x`, `y`) of the picture, premultiplied RGBA.
fn at(p: &MarkPicture, x: u32, y: u32) -> [u8; 4] {
let i = (y * p.width + x) as usize * 4;
p.rgba[i..i + 4].try_into().unwrap()
}
#[test]
fn an_image_keeps_its_size_colours_and_transparency() {
// 40 × 20 pixels: opaque red on the left, nothing on the right.
let bytes = png(40, 20, |x, _| if x < 20 { [255, 0, 0, 255] } else { [0, 0, 0, 0] });
let p = mark_picture(&file("half.png", bytes, 0), 80).unwrap();
assert_eq!(p.size, (40.0, 20.0), "40 × 20 px at 72 dpi, as OK lays it out");
assert_eq!((p.width, p.height), (80, 40));
assert_eq!(at(&p, 10, 20), [255, 0, 0, 255], "the red half is opaque red");
assert_eq!(at(&p, 70, 20), [0, 0, 0, 0], "the empty half lets the page through");
}
#[test]
fn a_pdf_page_is_transparent_where_it_draws_nothing_and_upright() {
// 200 × 100, turned a quarter (/Rotate 90): shown 100 wide and 200 tall. A white box
// on the left half of the unturned page, nothing on the right.
let content = "1 1 1 rg 0 0 100 100 re f";
let pdf = format!(
"%PDF-1.7
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Rotate 90 /Contents 4 0 R >> endobj
4 0 obj << /Length {} >>
stream
{content}
endstream
endobj
trailer << /Root 1 0 R >>
%%EOF",
content.len()
);
let p = mark_picture(&file("stamp.pdf", pdf.clone().into_bytes(), 0), 100).unwrap();
assert_eq!(p.size, (100.0, 200.0), "the page as displayed");
assert_eq!((p.width, p.height), (50, 100));
// Turned clockwise, the unturned left half is the top half.
assert_eq!(at(&p, 25, 25), [255, 255, 255, 255], "painted white stays opaque white");
assert_eq!(at(&p, 25, 75), [0, 0, 0, 0], "what the page leaves unpainted is transparent");
assert!(mark_picture(&file("stamp.pdf", pdf.into_bytes(), 3), 100).is_err(), "a page the file doesn't have");
}
#[test]
fn what_ok_refuses_is_refused_and_sizes_are_capped() {
assert!(mark_picture(&file("x.png", b"not an image".to_vec(), 0), 100).is_err());
assert!(mark_picture(&file("x.png", Vec::new(), 0), 100).is_err());
assert!(mark_picture(&file("x.pdf", b"%PDF-1.7 junk".to_vec(), 0), 100).is_err());
let bytes = png(4, 2, |_, _| [0, 0, 255, 255]);
let p = mark_picture(&file("blue.png", bytes.clone(), 0), u32::MAX).unwrap();
assert_eq!(p.width, MAX_MARK_PICTURE_SIDE);
let p = mark_picture(&file("blue.png", bytes, 0), 0).unwrap();
assert_eq!((p.width, p.height), (1, 1));
}
#[test]
fn transparency_comes_from_the_two_backdrops() {
// Opaque white, nothing, half-transparent black, half-transparent red: (128, 0, 0, 128)
// premultiplied lets 127 of white through.
let white = [255, 255, 255, 255, 255, 255, 255, 255, 127, 127, 127, 255, 255, 127, 127, 255];
let black = [255, 255, 255, 255, 0, 0, 0, 255, 0, 0, 0, 255, 128, 0, 0, 255];
let px = unpaper(&white, &black);
assert_eq!(&px[..], &[255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128]);
}
}
+181
View File
@@ -4534,6 +4534,49 @@ fn update_previews_on_the_page_without_the_marks_it_replaces() {
assert_eq!((doc.edit_generation(), doc.dirty, doc.can_undo()), (generation, dirty, Some("Add watermark")), "the document is unchanged");
}
/// A picture behind the page shows only where the page has nothing of its own: the pages on a
/// transparent sheet are clear where they are bare and opaque where they paint, with the marks an
/// Update replaces taken away and the others kept.
#[test]
fn the_pages_on_glass_are_clear_only_where_they_paint_nothing() {
let (mut s, id) = session_with(1);
let yellow = Background { color: [1.0, 1.0, 0.0], ..Background::default() };
s.apply(id, Edit::AddBackground { pages: vec![0], settings: yellow, replace: false, file: None }).unwrap();
let red = Watermark { text: "SECRET".into(), color: [1.0, 0.0, 0.0], opacity: 1.0, ..Watermark::default() };
s.apply(id, Edit::AddWatermark { pages: vec![0], settings: red, replace: false, file: None }).unwrap();
let doc = s.get(id).unwrap();
let alpha = |p: &pdfcraft_render::RenderedPage, x: u32, y: u32| p.rgba[(((300 - y) * p.width + x) * 4 + 3) as usize];
let opaque_reds = |p: &pdfcraft_render::RenderedPage| {
p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, a]| *r > 200 && *g < 80 && *b < 80 && *a == 255).count()
};
let page = doc.pages_on_glass(Some(MarkKind::Background), false).unwrap().render_page(0, 1.0).unwrap();
assert_eq!(alpha(&page, 5, 5), 0, "bare paper, the background taken away, is clear");
assert!(opaque_reds(&page) > 50, "the watermark stays, opaque");
let page = doc.pages_on_glass(None, false).unwrap().render_page(0, 1.0).unwrap();
assert_eq!(page.rgba[(((300 - 5) * page.width + 5) * 4) as usize..][..4], [255, 255, 0, 255], "kept, the background paints the page");
}
/// With the white backdrops a background replaces taken away, a page's own white fill goes
/// clear on the sheet, so the picture behind shows where OK shows it; kept, the fill stays.
#[test]
fn the_pages_on_glass_lose_the_white_backdrop_a_background_replaces() {
let mut s = Session::new();
let id = s.open("a.pdf", None, Arc::new(backdrop_pdf(None)), None).unwrap();
let doc = s.get(id).unwrap();
let at = |p: &pdfcraft_render::RenderedPage, x: u32, y: u32| {
let i = (((p.height - 1 - y) * p.width + x) * 4) as usize;
[p.rgba[i], p.rgba[i + 1], p.rgba[i + 2], p.rgba[i + 3]]
};
let page = doc.pages_on_glass(Some(MarkKind::Background), true).unwrap().render_page(0, 1.0).unwrap();
assert_eq!(at(&page, 5, 5)[3], 0, "the white backdrop is taken away: bare paper is clear");
let page = doc.pages_on_glass(Some(MarkKind::Background), false).unwrap().render_page(0, 1.0).unwrap();
assert_eq!(at(&page, 5, 5), [255, 255, 255, 255], "kept, the white backdrop paints the page");
}
/// #5785: Update of one header and footer previews the page without that one alone, so a second
/// header and footer on the same page, which OK keeps, is still drawn in the preview.
#[test]
@@ -8057,6 +8100,29 @@ fn comparing_two_versions_of_a_document() {
/// Built-in and custom actions run their steps on a file (with JavaScript on), report each
/// step's progress, and fail cleanly on a file that is not a PDF.
#[test]
fn marking_a_deletion_on_a_page_the_newer_file_lacks() {
let mut s = Session::new().with_clock(|| 1_700_000_000);
let text = |n: usize| {
(1..=n).map(|i| format!("Row {i} of the schedule.")).collect::<Vec<_>>().join(
"
",
)
};
let v1 = s.create_from_text("t", &text(120)).unwrap();
let v2 = s.create_from_text("t", &text(20)).unwrap();
let old = s.open("v1.pdf", None, v1, None).unwrap();
let new = s.open("v2.pdf", None, v2, None).unwrap();
assert!(s.get(old).unwrap().info.pages.len() > 1 && s.get(new).unwrap().info.pages.len() == 1);
// Page 2 of the older file has no counterpart in the one-page newer file.
let c = s.compare_pages(old, new, &[1]).unwrap();
assert!(!c.changes.is_empty() && c.changes.iter().all(|ch| ch.kind == compare::Kind::Deleted), "{:?}", c.changes);
assert!(s.mark_differences_of(old, new, &[1]).unwrap() > 0);
let marks: Vec<_> = s.get(new).unwrap().info.annotations.iter().filter(|a| a.author.as_deref() == Some("Compare")).map(|a| a.page).collect();
assert!(!marks.is_empty() && marks.iter().all(|&p| p == 0), "{marks:?}");
}
#[test]
fn actions_run_their_steps_on_files() {
let s = Session::new();
@@ -9788,6 +9854,106 @@ fn xfa_text_growth_then_a_script_relayout_both_add_pages() {
saves_and_reopens(&mut s, id, 3);
}
/// Bookmarks and named destinations that name a dynamic form's page follow the pages a
/// re-layout replaces them with: the placeholder page is laid out onto a real one, and
/// typing into a growable field lays the form out onto a second; each time, the bookmarks
/// and the named destinations resolve to the first of the pages the layout wrote, not the
/// page it replaced.
#[test]
fn xfa_relayout_keeps_bookmarks_and_named_destinations_on_the_pages_it_writes() {
let before = r#"<field name="notes" w="7.5in" minH="0.5in"><ui><textEdit multiLine="1"/></ui></field>"#;
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, before, "", "");
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("dests.pdf", None, Arc::new(pdfcraft_xfa::fixtures::dests_shell(&template)), None).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 1, "{:?}", s.take_js_output(id).errors);
let pages = dest_pages(&s, id);
assert_eq!(pages, vec![Some(0); 4], "the bookmarks and named destinations are on the first page the layout wrote");
let notes: String = (1..=60).map(|i| format!("line {i}\n")).collect();
s.apply(id, Edit::SetFieldValue { name: "notes".into(), value: FieldValue::Text(notes) }).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 2);
let pages = dest_pages(&s, id);
assert_eq!(pages, vec![Some(0); 4], "the bookmarks and named destinations follow the first page to the second layout");
saves_and_reopens(&mut s, id, 2);
}
/// The position, in the page tree, of the page each of the document's bookmarks and named
/// destinations names: the `/Dests` entry, the `/Names` tree entry, and the two `/Outlines`
/// items (one with a `/Dest`, one with a `GoTo` action). `None` when one names a page the
/// page tree does not hold.
fn dest_pages(s: &Session, id: DocId) -> Vec<Option<usize>> {
use pdfcraft_cos::{ObjRef, Object};
let doc = s.get(id).unwrap();
let cos = pdfcraft_cos::Document::open(doc.bytes.clone()).unwrap();
let catalog = cos.get(cos.root().unwrap()).as_dict().cloned().unwrap();
let pages = catalog
.get(b"Pages")
.and_then(Object::as_ref)
.map(|r| cos.get(r))
.and_then(|p| p.as_dict().and_then(|d| d.get(b"Kids")).map(|k| cos.resolve(k)))
.and_then(|k| k.as_array().cloned())
.unwrap_or_default();
let pages: Vec<ObjRef> = pages.iter().filter_map(Object::as_ref).collect();
let pos = |v: &Object| {
let resolved = cos.resolve(v);
let page_ref = match resolved.as_array() {
Some(arr) => arr.first().and_then(Object::as_ref),
None => Object::as_ref(&resolved),
};
page_ref.and_then(|p| pages.iter().position(|x| *x == p))
};
let mut out = Vec::new();
if let Some(dests) = catalog.get(b"Dests").map(|d| cos.resolve(d)).and_then(|d| d.as_dict().cloned()) {
for (_, v) in dests.iter() {
out.push(pos(v));
}
}
if let Some(names) = catalog.get(b"Names").map(|n| cos.resolve(n)).and_then(|n| n.as_dict().cloned()) {
for (cat, node) in names.iter() {
if cat.as_slice() == b"Dests" || cat.as_slice() == b"Pages" {
let Some(entries) =
cos.resolve(node).as_dict().and_then(|d| d.get(b"Names")).map(|n| cos.resolve(n)).and_then(|n| n.as_array().cloned())
else {
continue;
};
for i in (0..entries.len() / 2 * 2).step_by(2) {
if let Some(v) = entries.get(i + 1) {
out.push(pos(v));
}
}
}
}
}
let Some(first) =
catalog.get(b"Outlines").map(|o| cos.resolve(o)).and_then(|o| o.as_dict().and_then(|d| d.get(b"First")).and_then(Object::as_ref))
else {
return out;
};
let mut stack = vec![first];
while let Some(r) = stack.pop() {
let Some(d) = cos.get(r).as_dict().cloned() else {
continue;
};
if let Some(dest) = d.get(b"Dest") {
out.push(pos(dest));
}
if let Some(a) = d.get(b"A")
&& cos.resolve(a).as_dict().is_some_and(|d| d.name(b"S") == Some(b"GoTo"))
&& let Some(dest) = cos.resolve(a).as_dict().and_then(|d| d.get(b"D"))
{
out.push(pos(dest));
}
if let Some(next) = d.get(b"Next").and_then(Object::as_ref) {
stack.push(next);
}
if let Some(kids) = d.get(b"Kids").map(|k| cos.resolve(k)).and_then(|k| k.as_array().cloned()) {
for k in kids.iter().filter_map(Object::as_ref).rev() {
stack.push(k);
}
}
}
out
}
#[test]
fn xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets() {
for fixed in [false, true] {
@@ -16730,6 +16896,21 @@ fn calculate_now_applies_format_script_to_updated_appearance() {
assert!(page_texts(&session, id)[0].contains("USD 6.00"), "the appearance uses the Format script");
}
/// A button script that copies a number into a field with a Format script shows it formatted, as
/// typing it would: forms copy a looked-up rate into a currency field this way.
#[test]
fn a_value_a_script_assigns_is_shown_through_the_fields_format_script() {
let mut session = Session::new().with_clock(|| 1_700_000_000);
let id = session.open("assign-format.pdf", None, Arc::new(scripted_form()), None).unwrap();
let format = Some("event.value = 'USD ' + util.printf('%.2f', event.value);".into());
session.apply(id, Edit::SetFieldScript { name: "price".into(), event: "format".into(), script: format }).unwrap();
let out = session.run_javascript(id, "getField('price').value = 138;", Some("go")).unwrap();
assert_eq!(out.error, None);
assert_eq!(session.get(id).unwrap().form.iter().find(|field| field.name == "price").unwrap().value, ["138"], "the value stays the number");
assert!(page_texts(&session, id)[0].contains("USD 138.00"), "{:?}", page_texts(&session, id));
}
#[test]
fn javascript_non_rgb_field_colours_convert_and_keep_the_scripts_other_changes() {
let fill_after = |colour: &str| {
+29
View File
@@ -210,6 +210,35 @@ impl Document {
})?
}
/// Every page on a transparent sheet, as a mark placed behind the page content would find
/// it: without the marks of `without` when it names a kind (what Update replaces), and with
/// the white backdrops a background replaces taken away when `replace_backdrops`. Clear
/// where a page paints nothing, so a preview can draw the mark over white paper and these
/// pages over it. Read-only, like [`Self::text_edit_preview`].
pub fn pages_on_glass(&self, without: Option<crate::MarkKind>, replace_backdrops: bool) -> Result<UnmarkedPages, String> {
guard(|| {
let editor = self.editor.as_ref().ok_or("the document can't be read")?;
let mut cos = editor.cos.clone();
let all: Vec<usize> = (0..pdfcraft_model::pages(&cos).len()).collect();
if let Some(kind) = without {
pdfcraft_edit::remove_marks(&mut cos, &all, kind).map_err(|e| e.to_string())?;
}
if replace_backdrops {
// A background that paints nothing, added as OK adds one: the backdrops go the same way.
let clear = pdfcraft_edit::Background { opacity: 0.0, replace_backdrop: true, ..Default::default() };
pdfcraft_edit::add_background(&mut cos, &all, &clear, false).map_err(|e| e.to_string())?;
}
let bytes = Arc::new(pdfcraft_cos::write_incremental(&cos, &pdfcraft_cos::SaveOptions::default()).map_err(|e| e.to_string())?);
Ok(UnmarkedPages {
bytes,
config: RenderConfig { transparent: true, ..self.config.clone() },
parsed: None,
#[cfg(test)]
builds: 0,
})
})?
}
/// An added item alone, on a transparent page: what follows the pointer while it is dragged,
/// so the page under its first place doesn't come along. Read-only, like
/// [`Self::added_content_preview`].
+1 -1
View File
@@ -16,7 +16,7 @@ craft-mime.workspace = true
craft-rtf = { workspace = true, features = ["doc"] }
craft-wordmodel.workspace = true
craft-docx.workspace = true
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", version = "0.1.0", features = ["standalone"] }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e", version = "0.1.0", features = ["standalone"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
craft-pptx.workspace = true
craft-xml.workspace = true
+3 -1
View File
@@ -10,6 +10,7 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
use crate::{Field, FieldKind, FormError, Widget, appearance, fields, flags, page_refs};
mod copy;
mod edit;
mod join;
mod lifecycle;
@@ -18,9 +19,10 @@ mod tree;
pub(crate) use tree::ancestor_sets;
pub use copy::paste_field;
pub use edit::set_props;
pub(crate) use edit::set_props_object;
pub use lifecycle::{add_field, delete_field, delete_field_object, delete_widget, duplicate_field};
pub use lifecycle::{add_field, copy_field, copyable_widget, delete_field, delete_field_object, delete_widget, duplicate_field};
pub(crate) use look::button_appearance;
pub(crate) use look::redraw_field_object;
pub use look::{
+307
View File
@@ -0,0 +1,307 @@
//! Copy and paste a field (#1571): a new, independently named field from some or all of a
//! field's widgets.
use super::lifecycle::WIDGET_KEYS;
use super::look::redraw_field;
use super::tree::{add_to_fields, add_to_page, ensure_form, free_name, inherited, top_names};
use std::collections::HashMap;
use super::{Dict, Document, Field, FieldKind, FormError, ObjRef, Object, PdfString, Widget, fields, invalid, page_refs};
/// Keys a copy never takes from its source: what ties a field into the tree, names it, or binds
/// it to a structure element or an XFA template node.
pub(super) const COPY_DROPS: [&[u8]; 8] = [b"Kids", b"Parent", b"T", b"NM", b"StructParent", b"PCSom", b"PCXfaNode", b"PCItems"];
/// Give widget `w` a look of its own: every stream its `/AP` reaches (`/N`, `/D`, `/R`, directly
/// or per state) is added again as a new object, and an indirect `/MK` or `/BS` becomes direct,
/// so redrawing or restyling the copy can't change the source. Resources the streams use stay
/// shared.
pub(super) fn own_look(doc: &mut Document, w: &mut Dict) {
for key in [&b"MK"[..], b"BS"] {
if let Some(value) = w.get(key).filter(|v| Object::as_ref(v).is_some())
&& let Some(dict) = doc.resolve(value).as_dict().cloned()
{
w.set(key.to_vec(), Object::Dict(dict));
}
}
let Some(ap) = w.get(b"AP").and_then(|o| doc.resolve(o).as_dict().cloned()) else { return };
let mut fresh = Dict::new();
for (key, look) in ap.iter() {
let owned = match &*doc.resolve(look) {
Object::Stream(_) => own_stream(doc, look),
Object::Dict(states) => {
let mut mine = Dict::new();
for (state, stream) in states.iter() {
let value = own_stream(doc, stream);
mine.set(state.clone(), value);
}
Object::Dict(mine)
}
_ => look.clone(),
};
fresh.set(key.clone(), owned);
}
w.set(b"AP".to_vec(), Object::Dict(fresh));
}
/// A new object holding the stream `look` refers to; anything else as it is.
fn own_stream(doc: &mut Document, look: &Object) -> Object {
match Object::as_ref(look) {
Some(r) if matches!(&*doc.get(r), Object::Stream(_)) => {
let stream = (*doc.get(r)).clone();
Object::Ref(doc.add(stream))
}
_ => look.clone(),
}
}
/// `name` as a position in a button field's `/Opt` (`/0`, `/1` ...), as ISO 32000-2 lets the
/// on states of buttons with `/Opt` be named.
fn opt_position(name: &[u8]) -> Option<usize> {
let s = std::str::from_utf8(name).ok()?;
s.parse().ok().filter(|i: &usize| i.to_string() == s)
}
/// `name` renamed after the new position `moved` gives its old one, when it is a position.
fn renumbered(name: &[u8], moved: &HashMap<usize, usize>) -> Option<Vec<u8>> {
opt_position(name).and_then(|i| moved.get(&i)).map(|j| j.to_string().into_bytes())
}
/// Rename a copied widget's on states that are `/Opt` positions (in `/AP /N`, `/AP /D`, `/AP /R`
/// and `/AS`) after the positions its field's copied `/Opt` gives them. Other names stay.
fn renumber_states(doc: &Document, w: &mut Dict, moved: &HashMap<usize, usize>) {
if let Some(mut ap) = w.get(b"AP").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned()) {
let mut changed = false;
for k in [&b"N"[..], b"D", b"R"] {
let Some(states) = ap.get(k).map(|s| doc.resolve(s)).and_then(|s| s.as_dict().cloned()) else { continue };
if states.iter().any(|(n, _)| renumbered(n, moved).is_some()) {
let mut out = Dict::new();
for (n, v) in states.iter() {
out.set(renumbered(n, moved).unwrap_or_else(|| n.clone()), v.clone());
}
ap.set(k.to_vec(), Object::Dict(out));
changed = true;
}
}
if changed {
w.set(b"AP".to_vec(), Object::Dict(ap));
}
}
if let Some(s) = w.name(b"AS").and_then(|s| renumbered(s, moved)) {
w.set(b"AS".to_vec(), Object::Name(s));
}
}
/// "Check Box1" → "Check Box", "address.city" → "city": what a copy's name counts up from.
fn copy_base(name: &str) -> &str {
let leaf = name.rsplit('.').next().unwrap_or(name);
let base = leaf.trim_end_matches(|c: char| c.is_ascii_digit());
if base.trim().is_empty() { "Field" } else { base }
}
/// Copy and paste a field (#1571): a new field of its own, with its own name and value, made of
/// copies of widgets `widgets` (indices in [`Field::widgets`]; every widget when empty), placed
/// on `page` (0-based) and moved by `offset` in user space. Type, flags, options, value,
/// appearance and actions come along; a signature's value doesn't. The name is the first free
/// one after the original's ("Check Box1" → "Check Box2"). Returns it.
pub fn paste_field(doc: &mut Document, name: &str, widgets: &[usize], page: usize, offset: [f64; 2]) -> Result<String, FormError> {
let all = fields(doc);
let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?;
let page_ref = *page_refs(doc).get(page).ok_or_else(|| FormError::Invalid(format!("page {} does not exist", page + 1)))?;
if !offset.iter().all(|v| v.is_finite()) {
return invalid("the offset must be a finite number");
}
let picked = pick_widgets(f, widgets)?;
let own = doc.get(f.obj).as_dict().cloned().unwrap_or_default();
let (mut field, moved) = field_half(doc, f, &own, &picked);
let signature = field.name(b"FT") == Some(&b"Sig"[..]);
let new_name = free_name(&all, &top_names(doc), copy_base(&f.name));
field.set(b"T".to_vec(), PdfString::text(&new_name));
let place = Place { page: page_ref, offset };
let mut kids = Vec::new();
for w in &picked {
kids.push(widget_half(doc, f, &own, w, signature, &moved, place)?);
}
let af = ensure_form(doc)?;
let top = attach(doc, page_ref, field, kids)?;
add_to_fields(doc, af, top)?;
if signature {
redraw_field(doc, &new_name)?;
}
// A calculated field's copy calculates too.
let co = doc.get(af).as_dict().and_then(|d| d.get(b"CO").cloned()).map(|c| doc.resolve(&c)).and_then(|c| c.as_array().cloned());
if let Some(mut co) = co.filter(|co| co.iter().any(|o| o.as_ref() == Some(f.obj))) {
co.push(Object::Ref(top));
doc.update_dict(af, |d| d.set(b"CO".to_vec(), Object::Array(co)))?;
}
Ok(new_name)
}
/// Where a copied widget goes: its page, and how far it moves in user space.
#[derive(Clone, Copy)]
struct Place {
page: ObjRef,
offset: [f64; 2],
}
/// The widgets of `f` at `widgets` (each once), or every widget when `widgets` is empty.
fn pick_widgets<'a>(f: &'a Field, widgets: &[usize]) -> Result<Vec<&'a Widget>, FormError> {
let mut picked: Vec<&Widget> = Vec::new();
for i in widgets {
let w = f.widgets.get(*i).ok_or_else(|| FormError::Invalid(format!("{} has no widget {i}", f.name)))?;
if !picked.iter().any(|p| p.obj == w.obj) {
picked.push(w);
}
}
if widgets.is_empty() {
picked = f.widgets.iter().collect();
}
if picked.is_empty() {
return invalid(format!("{} has no widget", f.name));
}
Ok(picked)
}
/// The copy's field dictionary, without `/T`, and how its buttons' `/Opt` positions moved.
fn field_half(doc: &Document, f: &Field, own: &Dict, picked: &[&Widget]) -> (Dict, HashMap<usize, usize>) {
let mut field = Dict::new();
for (k, v) in own.iter() {
if !COPY_DROPS.contains(&k.as_slice()) && !WIDGET_KEYS.contains(&k.as_slice()) {
field.set(k.clone(), v.clone());
}
}
// The copy is a top-level field: it takes along what the original inherits.
for (k, v) in inherited(doc, f.obj).iter() {
field.set(k.clone(), v.clone());
}
// A signature's value is someone's signature: the copy is a blank signature field.
if field.name(b"FT") == Some(&b"Sig"[..]) {
field.remove(b"V");
field.remove(b"Lock");
}
if matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) {
off_unless_copied(doc, picked, &mut field, b"DV");
}
let moved = if matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) { copy_opt(doc, f, picked, &mut field) } else { HashMap::new() };
// Radio buttons copied without the selected one: none of the copies is selected.
if f.kind == FieldKind::Radio && !f.value.iter().any(|v| picked.iter().any(|w| w.on_state.as_ref() == Some(v) && w.state.as_ref() == Some(v))) {
field.set(b"V".to_vec(), Object::name("Off"));
}
(field, moved)
}
/// Sets the button field's `key` (`/DV`) to `Off` when it names an on state none of the copied
/// widgets has, so resetting the copy never asks for a button it lacks.
fn off_unless_copied(doc: &Document, picked: &[&Widget], field: &mut Dict, key: &[u8]) {
let Some(v) = field.get(key).map(|v| doc.resolve(v)).and_then(|v| v.as_name().map(<[u8]>::to_vec)) else { return };
if v != b"Off" && !picked.iter().any(|w| w.on_state.as_deref().map(crate::name_bytes).as_deref() == Some(v.as_slice())) {
field.set(key.to_vec(), Object::name("Off"));
}
}
/// A check box or radio group's /Opt holds one export value per widget: the copied ones'.
/// When its on states are named after those positions (/0, /1 ...), the copies' are renamed
/// after their new ones, and a value naming a button left behind is off. Returns the moves.
fn copy_opt(doc: &Document, f: &Field, picked: &[&Widget], field: &mut Dict) -> HashMap<usize, usize> {
let opt = field.get(b"Opt").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned());
let Some(opt) = opt.filter(|o| o.len() == f.widgets.len()) else { return HashMap::new() };
let at: Vec<usize> = picked.iter().filter_map(|p| f.widgets.iter().position(|w| w.obj == p.obj)).collect();
field.set(b"Opt".to_vec(), Object::Array(at.iter().filter_map(|i| opt.get(*i).cloned()).collect()));
if !f.widgets.iter().enumerate().all(|(i, w)| w.on_state.as_deref().and_then(|s| opt_position(s.as_bytes())) == Some(i)) {
return HashMap::new();
}
let moved: HashMap<usize, usize> = at.iter().enumerate().map(|(new, old)| (*old, new)).collect();
for k in [&b"V"[..], b"DV"] {
let v = field.get(k).map(|v| doc.resolve(v)).and_then(|v| v.as_name().map(<[u8]>::to_vec));
if let Some(v) = v.filter(|v| opt_position(v).is_some()) {
field.set(k.to_vec(), Object::Name(renumbered(&v, &moved).unwrap_or_else(|| b"Off".to_vec())));
}
}
moved
}
/// The copy of widget `w`, placed by `place`, with a look of its own.
fn widget_half(
doc: &mut Document,
f: &Field,
own: &Dict,
w: &Widget,
signature: bool,
moved: &HashMap<usize, usize>,
place: Place,
) -> Result<Dict, FormError> {
let mut d = if w.obj == f.obj {
let mut d = Dict::new();
for k in WIDGET_KEYS {
if let Some(v) = own.get(k) {
d.set(k.to_vec(), v.clone());
}
}
d
} else {
doc.get(w.obj).as_dict().cloned().unwrap_or_default()
};
for k in COPY_DROPS {
d.remove(k);
}
// The signer's visible signature isn't the copy's: the caller redraws it blank.
if signature {
d.remove(b"AP");
d.remove(b"AS");
}
renumber_states(doc, &mut d, moved);
own_look(doc, &mut d);
d.set(b"P".to_vec(), Object::Ref(place.page));
let (r, o) = (w.rect, place.offset);
let rect = [r[0] + o[0], r[1] + o[1], r[2] + o[0], r[3] + o[1]];
if !rect.iter().all(|v| v.is_finite()) {
return invalid("the offset moves the field out of range");
}
d.set(b"Rect".to_vec(), Object::Array(rect.iter().map(|v| Object::Real(*v)).collect()));
Ok(d)
}
/// Adds the copy to the document and to `page_ref`'s annotations. Returns its top object.
fn attach(doc: &mut Document, page_ref: ObjRef, mut field: Dict, mut kids: Vec<Dict>) -> Result<ObjRef, FormError> {
match kids.pop() {
// One widget: field and widget in one dictionary, as added fields are.
Some(only) if kids.is_empty() => {
let triggers = merged_triggers(doc, &field, &only);
for (k, v) in only.iter() {
field.set(k.clone(), v.clone());
}
if let Some(aa) = triggers {
field.set(b"AA".to_vec(), Object::Dict(aa));
}
let r = doc.add(Object::Dict(field));
add_to_page(doc, page_ref, r)?;
Ok(r)
}
last => {
kids.extend(last);
let parent = doc.add(Object::Dict(field));
let mut refs = Vec::new();
for mut d in kids {
d.set(b"Parent".to_vec(), Object::Ref(parent));
let r = doc.add(Object::Dict(d));
add_to_page(doc, page_ref, r)?;
refs.push(Object::Ref(r));
}
doc.update_dict(parent, |d| d.set(b"Kids".to_vec(), Object::Array(refs)))?;
Ok(parent)
}
}
}
/// The field's and its single widget's `/AA` in one dictionary, for a copy where the two
/// become one: the field's triggers (`K`, `F`, `V`, `C`) and the widget's (`E`, `X`, ...) use
/// different keys, so both are kept, the widget's winning a key both have. `None` unless both
/// have one.
fn merged_triggers(doc: &Document, field: &Dict, widget: &Dict) -> Option<Dict> {
let aa = |d: &Dict| d.get(b"AA").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned());
let (mut merged, own) = (aa(field)?, aa(widget)?);
for (k, v) in own.iter() {
merged.set(k.clone(), v.clone());
}
Some(merged)
}
+161 -2
View File
@@ -1,5 +1,5 @@
use super::look::redraw_field;
use super::tree::{add_to_page, attach, clash, detach, ensure_form, free_name, name_parts, top_names};
use super::tree::{add_to_page, attach, clash, detach, ensure_form, free_name, inherited, name_parts, top_names};
use super::{
Dict, Document, Field, FieldKind, FormError, MIN_FIELD_SIDE, NewField, ObjRef, Object, PdfString, Widget, appearance, fields, flags, invalid,
page_refs, rgb,
@@ -325,7 +325,8 @@ pub(super) fn drop_from_calculation_order(doc: &mut Document, gone: impl Fn(ObjR
}
/// Widget-only keys: they stay with each widget when a merged field is split.
const WIDGET_KEYS: [&[u8]; 13] = [b"Type", b"Subtype", b"Rect", b"P", b"AP", b"AS", b"MK", b"F", b"BS", b"Border", b"H", b"StructParent", b"A"];
pub(super) const WIDGET_KEYS: [&[u8]; 13] =
[b"Type", b"Subtype", b"Rect", b"P", b"AP", b"AS", b"MK", b"F", b"BS", b"Border", b"H", b"StructParent", b"A"];
/// The `/AA` triggers of a widget annotation (ISO 32000-2 §12.6.3, Table 197). The rest (`K`,
/// `F`, `V`, `C`, Table 199) belong to the field.
@@ -343,6 +344,164 @@ pub(super) fn split_triggers(aa: &Dict) -> (Option<Dict>, Option<Dict>) {
(some(widget), some(field))
}
/// Keys a grid copy never takes from its source: what ties a field into the tree, names it, or
/// binds it to an XFA template node (a new layout would replace or drop a field carrying them).
const COPY_DROPS: [&[u8]; 8] = [b"Kids", b"Parent", b"T", b"NM", b"StructParent", b"PCSom", b"PCXfaNode", b"PCItems"];
/// Copy one widget into a new, independently named field on a page.
///
/// The field's current value and properties are copied, but the new field has its own value and
/// its own appearance streams. Radio groups and signature fields require special handling and are
/// not supported here.
pub fn copy_field(doc: &mut Document, name: &str, widget: usize, page: usize, rect: [f64; 4], new_name: &str) -> Result<(), FormError> {
let all = fields(doc);
let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?;
let w = copyable_widget(f, widget)?;
let page_ref = *page_refs(doc).get(page).ok_or_else(|| FormError::Invalid(format!("page {} does not exist", page.saturating_add(1))))?;
let width = rect[2] - rect[0];
let height = rect[3] - rect[1];
if !rect.iter().all(|v| v.is_finite()) || !width.is_finite() || !height.is_finite() || width < MIN_FIELD_SIDE || height < MIN_FIELD_SIDE {
return invalid("the field is too small");
}
let parts = name_parts(new_name)?;
if let Some(why) = all.iter().find_map(|other| clash(new_name, &other.name)) {
return invalid(why);
}
let mut field = copy_source(doc, f, w)?;
for key in COPY_DROPS {
field.remove(key);
}
// A check box's `/Opt` holds an export value per widget when it has one entry per widget
// (else the on state is the export value); the copy has one widget, this one.
if f.kind == FieldKind::CheckBox && field.contains(b"Opt") {
match f.options.get(widget).filter(|_| f.options.len() == f.widgets.len()) {
Some((export, _)) => field.set(b"Opt".to_vec(), Object::Array(vec![Object::String(PdfString::text(export))])),
None => {
field.remove(b"Opt");
}
}
}
// The appearance editor updates indirect /MK and /BS dictionaries in place. Make these
// per-widget dictionaries direct so editing a copy cannot restyle the source or its siblings.
for key in [&b"MK"[..], b"BS"] {
if let Some(value) = field.get(key).filter(|v| Object::as_ref(v).is_some())
&& let Some(dict) = doc.resolve(value).as_dict().cloned()
{
field.set(key.to_vec(), Object::Dict(dict));
}
}
own_appearance(doc, &mut field);
field.set(b"P".to_vec(), Object::Ref(page_ref));
field.set(b"Rect".to_vec(), Object::Array(rect.iter().map(|v| Object::Real(*v)).collect()));
// Keep a custom appearance rather than replacing it with a generated approximation.
// A viewer scales its appearance stream to the new widget rectangle.
let has_appearance = field.get(b"AP").is_some_and(|o| matches!(&*doc.resolve(o), Object::Dict(d) if d.contains(b"N")));
let af = ensure_form(doc)?;
let copied = doc.add(Object::Dict(field));
attach(doc, af, copied, &parts)?;
add_to_page(doc, page_ref, copied)?;
if !has_appearance {
redraw_field(doc, new_name)?;
}
Ok(())
}
/// The widget `widget` of `f`, when [`copy_field`] can copy it: a text field, or a check box
/// whose widgets all have one on state and one export value. A widget without an on state
/// counts as a different value.
pub fn copyable_widget(f: &Field, widget: usize) -> Result<&Widget, FormError> {
if !matches!(f.kind, FieldKind::Text | FieldKind::CheckBox) {
return invalid("only text fields and check boxes can be copied into a grid");
}
if f.kind == FieldKind::CheckBox && f.widgets.len() > 1 {
let on = f.widgets.first().and_then(|w| w.on_state.as_deref());
let export = f.export_of(0);
let one = on.is_some() && f.widgets.iter().enumerate().all(|(i, w)| w.on_state.as_deref() == on && f.export_of(i) == export);
if !one {
return invalid("a check box whose widgets export different values cannot yet be copied into a grid");
}
}
f.widgets.get(widget).ok_or_else(|| FormError::Invalid(format!("{} has no widget {}", f.name, widget.saturating_add(1))))
}
/// The field dictionary of `f` with what it inherits and, when the widget `w` is separate, the
/// widget's own entries merged in: one merged field/widget dictionary for the copy.
fn copy_source(doc: &Document, f: &Field, w: &Widget) -> Result<Dict, FormError> {
let mut field = doc.get(f.obj).as_dict().cloned().ok_or_else(|| FormError::Invalid("field is not a dictionary".into()))?;
let widget_dict = doc.get(w.obj).as_dict().cloned().ok_or_else(|| FormError::Invalid("widget is not a dictionary".into()))?;
for (k, v) in inherited(doc, f.obj).iter() {
field.set(k.to_vec(), v.clone());
}
if w.obj == f.obj {
return Ok(field);
}
// Preserve widget entries that aren't in the field dictionary, including unfamiliar
// annotation keys, while the field's own attributes keep their precedence. A widget's /Ff
// is skipped: its radio or push-button bit would change the copy's kind, and its read-only
// bit is carried below.
for (key, value) in widget_dict.iter() {
if !field.contains(key) && !matches!(key.as_slice(), b"AA" | b"Ff") && !COPY_DROPS.contains(&key.as_slice()) {
field.set(key.clone(), value.clone());
}
}
for key in WIDGET_KEYS.iter().copied().chain([&b"DA"[..]]) {
if let Some(value) = widget_dict.get(key) {
field.set(key.to_vec(), value.clone());
}
}
// A widget can be read-only on its own (`/Ff` in the widget); the copy's one dictionary keeps it.
if w.read_only {
let ff = field.get(b"Ff").and_then(|v| doc.resolve(v).as_int()).unwrap_or(0);
field.set(b"Ff".to_vec(), Object::Int(ff | i64::from(flags::READ_ONLY)));
}
// Keep both field and widget event dictionaries when they were separate.
let mut aa = field.get(b"AA").and_then(|a| doc.resolve(a).as_dict().cloned()).unwrap_or_default();
if let Some(widget_aa) = widget_dict.get(b"AA").and_then(|a| doc.resolve(a).as_dict().cloned()) {
for (k, v) in widget_aa.iter() {
aa.set(k.to_vec(), v.clone());
}
}
if !aa.is_empty() {
field.set(b"AA".to_vec(), Object::Dict(aa));
}
Ok(field)
}
/// Give `field` appearance streams of its own: every stream its `/AP` reaches (`/N`, `/D`, `/R`,
/// directly or per state) is added again as a new object, so redrawing the copy, as a password
/// or value change does, can't rewrite the source's look. Resources the streams use stay shared.
fn own_appearance(doc: &mut Document, field: &mut Dict) {
let Some(ap) = field.get(b"AP").and_then(|o| doc.resolve(o).as_dict().cloned()) else { return };
let mut fresh = Dict::new();
for (key, look) in ap.iter() {
let owned = match &*doc.resolve(look) {
Object::Stream(_) => own_stream(doc, look),
Object::Dict(states) => {
let mut mine = Dict::new();
for (state, stream) in states.iter() {
let value = own_stream(doc, stream);
mine.set(state.clone(), value);
}
Object::Dict(mine)
}
_ => look.clone(),
};
fresh.set(key.clone(), owned);
}
field.set(b"AP".to_vec(), Object::Dict(fresh));
}
/// A new object holding the stream `look` refers to; anything else as it is.
fn own_stream(doc: &mut Document, look: &Object) -> Object {
match Object::as_ref(look) {
Some(r) if matches!(&*doc.get(r), Object::Stream(_)) => {
let stream = (*doc.get(r)).clone();
Object::Ref(doc.add(stream))
}
_ => look.clone(),
}
}
/// Duplicate a field onto other pages (Acrobat: right-click a field ▸ Duplicate): each page
/// gets a widget at the same place, belonging to the same field, so they share one value.
/// A field that is its own widget is first split into a field and a widget kid. Returns how
+1 -1
View File
@@ -153,7 +153,7 @@ pub(super) fn add_to_page(doc: &mut Document, page: ObjRef, widget: ObjRef) -> R
Ok(())
}
fn add_to_fields(doc: &mut Document, af: ObjRef, field: ObjRef) -> Result<(), FormError> {
pub(super) fn add_to_fields(doc: &mut Document, af: ObjRef, field: ObjRef) -> Result<(), FormError> {
let mut d = doc.get(af).as_dict().cloned().unwrap_or_default();
let mut list = d.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
list.push(Object::Ref(field));
+3 -2
View File
@@ -26,8 +26,9 @@ mod scripting;
pub mod table;
pub use actions::{FieldAction, Trigger, field_action_chains, field_actions, set_field_actions, widget_scripts};
pub use author::{
BorderStyle, CheckStyle, FieldFont, FieldProps, Look, LookPatch, MIN_FIELD_SIDE, NewField, add_field, check_style, delete_field,
delete_field_object, delete_widget, duplicate_field, look, redraw_field, redraw_fields, set_button_icon, set_button_icon_target, set_props,
BorderStyle, CheckStyle, FieldFont, FieldProps, Look, LookPatch, MIN_FIELD_SIDE, NewField, add_field, check_style, copy_field, copyable_widget,
delete_field, delete_field_object, delete_widget, duplicate_field, look, paste_field, redraw_field, redraw_fields, set_button_icon,
set_button_icon_target, set_props,
};
pub use calc_order::{CalculatedField, CalculationIssue, CalculationOrder, calculation_order, set_calculation_order};
pub use scripting::{
+2 -1
View File
@@ -40,7 +40,8 @@ pub struct FieldChange {
/// Optional exact object target for malformed forms with duplicate field names.
pub object: Option<ObjRef>,
pub value: Option<Vec<String>>,
/// This value came from a Calculate script; redraw it through the field's Format script.
/// This value came from a Calculate script or a `field.value` assignment; redraw it through
/// the field's Format script.
pub formatted: bool,
pub read_only: Option<bool>,
pub required: Option<bool>,
+6 -1
View File
@@ -317,6 +317,8 @@ pub enum TableError {
Twice(String),
/// The form already has a field of this name.
Taken(String),
/// The field a grid would copy is not a text field or a check box with one export value.
Uncopyable(String),
}
const ROWS: &str = "a table has 1 to {max} rows";
@@ -329,10 +331,11 @@ const COLUMN_TOO_NARROW: &str =
const PERIOD: &str = "field names can't contain a period: {name}";
const TWICE: &str = "two cells would both be named {name}";
const TAKEN: &str = "a field named {name} already exists";
const UNCOPYABLE: &str = "{name} can't be copied into a grid: only text fields and check boxes with one export value can";
/// Every sentence a [`TableError`] says, in English with its holes still in it, for an interface
/// to translate; `wordings_are_said` keeps the list in step with the errors.
pub const WORDINGS: &[&str] = &[ROWS, COLUMNS, FIRST_ROW, NUMBERS, ROWS_TOO_SHORT, COLUMN_TOO_NARROW, PERIOD, TWICE, TAKEN];
pub const WORDINGS: &[&str] = &[ROWS, COLUMNS, FIRST_ROW, NUMBERS, ROWS_TOO_SHORT, COLUMN_TOO_NARROW, PERIOD, TWICE, TAKEN, UNCOPYABLE];
/// How an interface says one of our wordings in its own language, holes and all: given the English
/// in [`WORDINGS`], the same wording in that language. [`in_english`] keeps the English.
@@ -361,6 +364,7 @@ impl TableError {
TableError::Period(name) => named(PERIOD, name),
TableError::Twice(name) => named(TWICE, name),
TableError::Taken(name) => named(TAKEN, name),
TableError::Uncopyable(name) => named(UNCOPYABLE, name),
}
}
}
@@ -612,6 +616,7 @@ mod tests {
TableError::Period("a.1".into()),
TableError::Twice("a_1".into()),
TableError::Taken("a_1".into()),
TableError::Uncopyable("a".into()),
];
assert_eq!(WORDINGS.len(), mistakes.len(), "one wording per mistake");
// Each mistake says one of the wordings: translated to a marker, only the values remain.
+670
View File
@@ -4,6 +4,21 @@ use pdfcraft_cos::{Document, Object, SaveOptions, write_incremental};
use super::*;
#[test]
fn grid_copy_and_clipboard_paste_create_independent_fields_in_one_document() {
let mut doc = fixture();
set_value(&mut doc, "notes", &FieldValue::Text("source".into())).unwrap();
copy_field(&mut doc, "notes", 0, 0, [50.0, 400.0, 250.0, 480.0], "grid_copy").unwrap();
let pasted = paste_field(&mut doc, "notes", &[], 0, [0.0, -100.0]).unwrap();
assert_ne!(pasted, "grid_copy");
set_value(&mut doc, "grid_copy", &FieldValue::Text("grid".into())).unwrap();
set_value(&mut doc, &pasted, &FieldValue::Text("pasted".into())).unwrap();
let all = fields(&doc);
assert_eq!(field(&all, "notes").value, ["source"]);
assert_eq!(field(&all, "grid_copy").value, ["grid"]);
assert_eq!(field(&all, &pasted).value, ["pasted"]);
}
/// One page with a form: text fields (plain, multiline, comb, password, read-only, nested),
/// a check box with appearances, one without, a radio group, a combo and a multi-select list,
/// and a push button.
@@ -39,6 +54,278 @@ fn fixture() -> Document {
document(&objs)
}
#[test]
fn grid_copy_preserves_properties_and_has_an_independent_value() {
let mut doc = fixture();
let source = field(&fields(&doc), "notes").clone();
copy_field(&mut doc, "notes", 0, 0, [50.0, 400.0, 250.0, 480.0], "notes_1").unwrap();
let copied = field(&fields(&doc), "notes_1").clone();
assert_eq!(copied.kind, source.kind);
assert_eq!(copied.flags, source.flags);
assert_eq!(copied.da, source.da);
assert_eq!(copied.widgets[0].rect, [50.0, 400.0, 250.0, 480.0]);
set_value(&mut doc, "notes_1", &FieldValue::Text("new value".into())).unwrap();
let reopened = reopen(&doc);
let all = fields(&reopened);
assert_eq!(field(&all, "notes_1").value, ["new value"]);
assert_ne!(field(&all, "notes").value, ["new value"]);
}
#[test]
fn grid_copy_checkbox_preserves_appearance_and_rejects_taken_names() {
let mut doc = fixture();
copy_field(&mut doc, "agree", 0, 0, [350.0, 400.0, 370.0, 420.0], "agree_copy").unwrap();
let all = fields(&doc);
assert_eq!(field(&all, "agree_copy").kind, FieldKind::CheckBox);
assert_eq!(field(&all, "agree_copy").widgets[0].on_state, field(&all, "agree").widgets[0].on_state);
let (copied, source) = (normal_states(&doc, field(&all, "agree_copy")), normal_states(&doc, field(&all, "agree")));
assert_eq!(copied.len(), source.len(), "every appearance state is copied");
for ((state, copy_ref), (source_state, source_ref)) in copied.iter().zip(&source) {
assert_eq!(state, source_state);
assert_ne!(copy_ref, source_ref, "the copy has a stream of its own");
assert_eq!(doc.get(*copy_ref), doc.get(*source_ref), "and it draws the same custom look");
}
set_value(&mut doc, "agree_copy", &FieldValue::Check(true)).unwrap();
let reopened = reopen(&doc);
let all = fields(&reopened);
assert_ne!(field(&all, "agree_copy").value, field(&all, "agree").value);
let before = all.len();
assert!(copy_field(&mut doc, "agree", 0, 0, [0.0, 0.0, 20.0, 20.0], "agree_copy").is_err());
assert_eq!(fields(&doc).len(), before);
assert!(copy_field(&mut doc, "size", 0, 0, [0.0, 0.0, 20.0, 20.0], "radio_copy").is_err());
}
#[test]
fn grid_copy_does_not_share_indirect_appearance_dictionaries() {
let mut doc = fixture();
let source = field(&fields(&doc), "name").obj;
let source_dict = doc.get(source).as_dict().unwrap().clone();
let mk = doc.add(source_dict.get(b"MK").unwrap().clone());
let mut bs = pdfcraft_cos::Dict::new();
bs.set(b"W".to_vec(), Object::Real(1.0));
let bs = doc.add(Object::Dict(bs));
doc.update_dict(source, |d| {
d.set(b"MK".to_vec(), Object::Ref(mk));
d.set(b"BS".to_vec(), Object::Ref(bs));
})
.unwrap();
copy_field(&mut doc, "name", 0, 0, [50.0, 400.0, 250.0, 420.0], "name_copy").unwrap();
let before = look(&doc, field(&fields(&doc), "name"));
let props = FieldProps {
appearance: Some(LookPatch { fill: Some(Some([0.0, 0.0, 1.0])), width: Some(3.0), ..Default::default() }),
..Default::default()
};
set_props(&mut doc, "name_copy", &props).unwrap();
let all = fields(&doc);
assert_eq!(look(&doc, field(&all, "name")), before);
assert_ne!(look(&doc, field(&all, "name_copy")), before);
}
#[test]
fn grid_copy_preserves_inherited_properties_and_rejects_invalid_geometry() {
let mut doc = fixture();
let source = field(&fields(&doc), "address.city").obj;
let parent = doc.get(source).as_dict().unwrap().reference(b"Parent").unwrap();
doc.update_dict(source, |d| {
d.remove(b"FT");
})
.unwrap();
doc.update_dict(parent, |d| {
d.set(b"FT".to_vec(), Object::name("Tx"));
d.set(b"Ff".to_vec(), Object::Int(i64::from(flags::MULTILINE)));
})
.unwrap();
copy_field(&mut doc, "address.city", 0, 0, [50.0, 400.0, 250.0, 420.0], "city_copy").unwrap();
let all = fields(&doc);
assert!(field(&all, "city_copy").has(flags::MULTILINE));
let before = all.len();
for rect in [[f64::NAN, 0.0, 20.0, 20.0], [0.0, 0.0, f64::INFINITY, 20.0], [-f64::MAX, 0.0, f64::MAX, 20.0], [0.0; 4]] {
assert!(copy_field(&mut doc, "address.city", 0, 0, rect, "invalid_copy").is_err());
assert_eq!(fields(&doc).len(), before);
}
}
#[test]
fn grid_copy_keeps_widget_overrides_when_field_and_widget_are_separate() {
let objs: Vec<String> = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
"<< /Fields [5 0 R] >>".into(),
"<< /FT /Tx /T (source) /DA (/Helv 12 Tf 0 g) /Kids [6 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /P 3 0 R /Rect [20 300 120 320] /DA (/Helv 8 Tf 1 0 0 rg) /Foo (kept) /NM (unique) >>".into(),
];
let mut doc = document(&objs);
copy_field(&mut doc, "source", 0, 0, [20.0, 250.0, 120.0, 270.0], "copy").unwrap();
let all = fields(&doc);
let copy = field(&all, "copy");
let object = doc.get(copy.obj);
let dict = object.as_dict().unwrap();
assert!(dict.contains(b"Foo"));
assert!(!dict.contains(b"NM"), "an annotation name must not be duplicated");
assert_eq!(copy.da, "/Helv 8 Tf 1 0 0 rg");
}
/// One page with a check box `box` of two widgets drawing on states `first` and `second`, with
/// `opt` (`/Opt`, PDF array body) when given.
fn two_widget_box(first: &str, second: &str, opt: Option<&str>) -> Document {
let opt = opt.map_or(String::new(), |o| format!(" /Opt [{o}]"));
let kid = |state: &str, x: u32| {
format!(
"<< /Type /Annot /Subtype /Widget /Parent 4 0 R /AS /Off /Rect [{x} 300 {} 315] /P 3 0 R /AP << /N << /{state} 7 0 R /Off 7 0 R >> >> >>",
x + 15
)
};
let objs: Vec<String> = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R] >>".into(),
format!("<< /FT /Btn /T (box) /V /Off{opt} /Kids [5 0 R 6 0 R] >>"),
kid(first, 20),
kid(second, 60),
"<< /Length 0 >>
stream
endstream"
.into(),
];
document(&objs)
}
#[test]
fn grid_copy_refuses_a_check_box_whose_widgets_export_different_values() {
for doc in [two_widget_box("A", "B", None), two_widget_box("Yes", "Yes", Some("(A) (B)"))] {
let mut doc = doc;
let before = fields(&doc).len();
assert!(copy_field(&mut doc, "box", 0, 0, [20.0, 200.0, 35.0, 215.0], "box_copy").is_err());
assert_eq!(fields(&doc).len(), before);
}
}
#[test]
fn grid_copy_takes_a_check_box_whose_widgets_export_one_value() {
let mut doc = two_widget_box("Yes", "Yes", Some("(X) (X)"));
copy_field(&mut doc, "box", 1, 0, [20.0, 200.0, 35.0, 215.0], "box_copy").unwrap();
let all = fields(&doc);
let copy = field(&all, "box_copy");
assert_eq!(copy.export_of(0), Some("X"), "the copy exports what its source widget did");
assert_eq!(copy.export_of(0), field(&all, "box").export_of(1));
}
#[test]
fn grid_copy_of_a_check_box_exports_its_on_state_when_opt_is_not_one_per_widget() {
let mut doc = two_widget_box("Yes", "Yes", Some("(A) (B) (C)"));
assert_eq!(field(&fields(&doc), "box").export_of(1), Some("Yes"));
copy_field(&mut doc, "box", 1, 0, [20.0, 200.0, 35.0, 215.0], "box_copy").unwrap();
assert_eq!(field(&fields(&doc), "box_copy").export_of(0), Some("Yes"), "a stray /Opt entry must not become the copy's export value");
}
#[test]
fn grid_copy_of_a_check_box_exports_the_value_its_widget_did_past_an_unreadable_opt_entry() {
let mut doc = two_widget_box("Yes", "Yes", Some("5 (X) (X)"));
assert_eq!(field(&fields(&doc), "box").export_of(0), Some("X"));
copy_field(&mut doc, "box", 0, 0, [20.0, 200.0, 35.0, 215.0], "box_copy").unwrap();
assert_eq!(field(&fields(&doc), "box_copy").export_of(0), Some("X"));
}
#[test]
fn grid_copy_keeps_a_widget_that_is_read_only_on_its_own() {
let objs: Vec<String> = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
"<< /Fields [5 0 R] >>".into(),
format!("<< /FT /Tx /T (source) /Ff {} /DA (/Helv 12 Tf 0 g) /Kids [6 0 R] >>", flags::MULTILINE),
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Ff 1 /P 3 0 R /Rect [20 300 120 320] >>".into(),
];
let mut doc = document(&objs);
assert!(field(&fields(&doc), "source").widgets[0].read_only);
copy_field(&mut doc, "source", 0, 0, [20.0, 250.0, 120.0, 270.0], "copy").unwrap();
let all = fields(&doc);
let copy = field(&all, "copy");
assert!(copy.widgets[0].read_only && copy.read_only(), "the copy is read-only as its source widget was");
assert!(copy.has(flags::MULTILINE), "and keeps the field's own flags");
}
#[test]
fn grid_copy_of_a_check_box_ignores_its_widgets_button_kind_bits() {
for bits in [flags::RADIO, flags::PUSH_BUTTON] {
let ff = bits | flags::READ_ONLY;
let objs: Vec<String> = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
"<< /Fields [5 0 R] >>".into(),
"<< /FT /Btn /T (box) /V /Off /Kids [6 0 R] >>".into(),
format!("<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Ff {ff} /AS /Off /P 3 0 R /Rect [20 300 35 315] >>"),
];
let mut doc = document(&objs);
assert_eq!(field(&fields(&doc), "box").kind, FieldKind::CheckBox);
copy_field(&mut doc, "box", 0, 0, [20.0, 250.0, 35.0, 265.0], "box_copy").unwrap();
let all = fields(&doc);
let copy = field(&all, "box_copy");
assert_eq!(copy.kind, FieldKind::CheckBox, "widget /Ff {ff} must not change the copy's kind");
assert!(copy.read_only(), "the widget's read-only bit still reaches the copy");
}
}
#[test]
fn grid_copy_keeps_a_transparent_borderless_multiline_look() {
let mut doc = fixture();
let bare = FieldProps {
appearance: Some(LookPatch { fill: Some(None), border: Some(None), width: Some(0.0), ..Default::default() }),
..Default::default()
};
set_props(&mut doc, "notes", &bare).unwrap();
let source = field(&fields(&doc), "notes").clone();
let styled = look(&doc, &source);
assert!(source.has(flags::MULTILINE) && styled.fill.is_none() && styled.border.is_none());
copy_field(&mut doc, "notes", 0, 0, [50.0, 400.0, 250.0, 480.0], "notes_2").unwrap();
set_value(&mut doc, "notes_2", &FieldValue::Text("one\ntwo".into())).unwrap();
let reopened = reopen(&doc);
let all = fields(&reopened);
let copy = field(&all, "notes_2");
assert!(copy.has(flags::MULTILINE), "the copy stays multi-line");
assert_eq!(look(&reopened, copy), styled, "the copy keeps no background and no border");
}
#[test]
fn grid_copy_is_no_longer_part_of_an_xfa_template() {
let mut doc = fixture();
let source = field(&fields(&doc), "notes").obj;
doc.update_dict(source, |d| d.set(b"PCSom".to_vec(), Object::String(PdfString::text("form1[0].notes[0]")))).unwrap();
copy_field(&mut doc, "notes", 0, 0, [50.0, 400.0, 250.0, 480.0], "notes_3").unwrap();
let all = fields(&doc);
assert!(doc.get(field(&all, "notes").obj).as_dict().unwrap().contains(b"PCSom"));
assert!(!doc.get(field(&all, "notes_3").obj).as_dict().unwrap().contains(b"PCSom"), "a new layout would drop a copy bound to the template");
}
#[test]
fn grid_copy_redraws_its_own_appearance_not_the_sources() {
let mut doc = fixture();
// A password field's edited appearance is redrawn in place.
set_value(&mut doc, "pin", &FieldValue::Text("12".into())).unwrap();
copy_field(&mut doc, "pin", 0, 0, [50.0, 400.0, 150.0, 420.0], "pin_copy").unwrap();
let source = normal(&doc, field(&fields(&doc), "pin"));
let before = doc.get(source);
set_value(&mut doc, "pin_copy", &FieldValue::Text("123456".into())).unwrap();
assert_eq!(normal(&doc, field(&fields(&doc), "pin")), source);
assert_eq!(doc.get(source), before, "setting the copy leaves the source's look as it was");
}
/// The widget's `/AP /N` stream.
fn normal(doc: &Document, f: &Field) -> pdfcraft_cos::ObjRef {
let ap = doc.resolve(doc.get(f.widgets[0].obj).as_dict().unwrap().get(b"AP").unwrap());
ap.as_dict().unwrap().reference(b"N").unwrap()
}
/// The widget's `/AP /N` states and their streams.
fn normal_states(doc: &Document, f: &Field) -> Vec<(Vec<u8>, pdfcraft_cos::ObjRef)> {
let ap = doc.resolve(doc.get(f.widgets[0].obj).as_dict().unwrap().get(b"AP").unwrap());
let states = doc.resolve(ap.as_dict().unwrap().get(b"N").unwrap());
states.as_dict().unwrap().iter().map(|(k, v)| (k.clone(), v.as_ref().unwrap())).collect()
}
/// A PDF of the given objects (numbered from 1).
fn document(objs: &[String]) -> Document {
let mut out = b"%PDF-1.7\n".to_vec();
@@ -3861,6 +4148,23 @@ fn check_box_redraw_keeps_down_states_it_still_draws() {
assert!(!d.contains(b"Gone"), "a state the box no longer draws");
}
/// A script that sets a check box keeps its on and off appearances: only text and combo boxes are
/// redrawn through a Format script.
#[test]
fn a_check_box_a_script_sets_keeps_its_state_appearances() {
let mut doc = one_page();
add_field(&mut doc, 0, [10.0, 40.0, 30.0, 60.0], &NewField::CheckBox, Some("agree")).unwrap();
let change = FieldChange { name: "agree".into(), value: Some(vec!["Yes".into()]), formatted: true, ..Default::default() };
apply_script_changes(&mut doc, &[change], &mut NoScripts).unwrap();
let widget = fields(&doc).into_iter().find(|f| f.name == "agree").unwrap().widgets[0].obj;
let d = doc.get(widget).as_dict().unwrap().clone();
assert_eq!(d.name(b"AS"), Some(b"Yes".as_slice()), "the box is drawn checked");
let ap = d.get(b"AP").map(|a| doc.resolve(a)).unwrap();
let normal = ap.as_dict().unwrap().get(b"N").map(|n| doc.resolve(n)).unwrap();
assert!(normal.as_dict().is_some_and(|n| n.contains(b"Yes") && n.contains(b"Off")), "{normal:?}");
}
#[test]
/// A calculation side effect on a checkbox is visible to following calculated fields.
fn recalc_chain_where_script_changes_checkbox() {
@@ -7819,3 +8123,369 @@ fn page_scripts_are_the_pages_own_then_each_annotations_in_order() {
assert_eq!(got, [(None, "close()"), (Some("anim"), "stop();")], "a URI action is not a script");
assert!(page_scripts(&doc, 1, PageEvent::Open).is_empty(), "no such page");
}
#[test]
fn copying_a_field_makes_an_independent_field() {
let mut doc = fixture();
// address.city takes its value and read-only flag from its parent.
let address = ObjRef::new(15, 0);
doc.update_dict(address, |d| {
d.set(b"V".to_vec(), PdfString::text("Paris"));
d.set(b"Ff".to_vec(), Object::Int(flags::READ_ONLY as i64));
})
.unwrap();
let city = paste_field(&mut doc, "address.city", &[], 0, [0.0, -40.0]).unwrap();
assert_eq!(city, "city1", "a top-level field named after the original's own name");
set_value(&mut doc, "size", &FieldValue::Radio(Some("L".into()))).unwrap();
// One button of a radio group: the selected one stays behind, so the copy has no choice.
let small = paste_field(&mut doc, "size", &[0], 0, [0.0, -40.0]).unwrap();
let both = paste_field(&mut doc, "size", &[], 0, [0.0, -80.0]).unwrap();
assert_eq!((small.as_str(), both.as_str()), ("size1", "size2"));
set_value(&mut doc, &both, &FieldValue::Radio(Some("S".into()))).unwrap();
let doc = reopen(&doc);
let all = fields(&doc);
let copy = field(&all, "city1");
assert_eq!((copy.kind, copy.value.as_slice(), copy.quadding), (FieldKind::Text, &["Paris".to_string()][..], 1));
assert!(copy.read_only(), "inherited flags come along");
assert_eq!(copy.widgets[0].rect, [50.0, 430.0, 250.0, 450.0]);
let small = field(&all, "size1");
assert_eq!(small.widgets.iter().map(|w| w.on_state.clone().unwrap()).collect::<Vec<_>>(), ["S"]);
assert!(small.value.is_empty(), "{:?}", small.value);
let both = field(&all, "size2");
assert_eq!(both.widgets.iter().map(|w| (w.on_state.clone().unwrap(), w.rect[1])).collect::<Vec<_>>(), [("S".into(), 570.0), ("L".into(), 570.0)]);
assert_eq!(
(both.value.as_slice(), field(&all, "size").value.as_slice()),
(&["S".to_string()][..], &["L".to_string()][..]),
"values are separate"
);
assert_eq!(field(&all, "size").widgets.len(), 2, "the original keeps its buttons");
assert!(paste_field(&mut doc.clone(), "size", &[2], 0, [0.0, 0.0]).is_err());
assert!(paste_field(&mut doc.clone(), "size", &[], 3, [0.0, 0.0]).is_err());
}
#[test]
fn copying_a_field_keeps_an_inherited_character_limit() {
let mut doc = fixture();
doc.update_dict(ObjRef::new(15, 0), |d| {
d.set(b"FT".to_vec(), Object::name("Tx"));
d.set(b"Ff".to_vec(), Object::Int(flags::COMB as i64));
d.set(b"MaxLen".to_vec(), Object::Int(5));
})
.unwrap();
assert_eq!(field(&fields(&doc), "address.city").max_len, Some(5), "pdfcraft reads MaxLen as inherited");
let copy = paste_field(&mut doc, "address.city", &[], 0, [0.0, -40.0]).unwrap();
let all = fields(&doc);
let c = field(&all, &copy);
assert!(c.has(flags::COMB), "the comb flag came along");
assert_eq!(c.max_len, Some(5), "the inherited MaxLen came along");
}
#[test]
fn copying_one_radio_button_keeps_its_export_value() {
let mut doc = fixture();
doc.update_dict(ObjRef::new(20, 0), |d| {
d.set(b"Opt".to_vec(), Object::Array(vec![Object::String(PdfString::text("Small")), Object::String(PdfString::text("Large"))]));
})
.unwrap();
assert_eq!(field(&fields(&doc), "size").export_of(1), Some("Large"));
let copy = paste_field(&mut doc, "size", &[1], 0, [0.0, -40.0]).unwrap();
let all = fields(&doc);
let c = field(&all, &copy);
assert_eq!(c.widgets.len(), 1);
assert_eq!(c.options.len(), 1, "one /Opt entry per copied widget: {:?}", c.options);
assert_eq!(c.export_of(0), Some("Large"));
}
#[test]
fn copying_a_radio_button_keeps_an_inherited_export_value() {
let mut doc = fixture();
let opt = Object::Array(vec![Object::String(PdfString::text("Small")), Object::String(PdfString::text("Large"))]);
let group = doc.add(Object::Dict({
let mut d = Dict::new();
d.set(b"T".to_vec(), PdfString::text("sizes"));
d.set(b"Opt".to_vec(), opt);
d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(20, 0))]));
d
}));
doc.update_dict(ObjRef::new(20, 0), |d| d.set(b"Parent".to_vec(), Object::Ref(group))).unwrap();
doc.update_dict(ObjRef::new(4, 0), |d| {
let listed = d.get(b"Fields").and_then(|f| f.as_array().cloned()).unwrap_or_default();
let listed = listed.into_iter().map(|f| if f.as_ref() == Some(ObjRef::new(20, 0)) { Object::Ref(group) } else { f }).collect();
d.set(b"Fields".to_vec(), Object::Array(listed));
})
.unwrap();
let copy = paste_field(&mut doc, "sizes.size", &[1], 0, [0.0, -40.0]).unwrap();
let all = fields(&doc);
let c = field(&all, &copy);
assert_eq!(c.options, [("Large".to_string(), "Large".to_string())], "the parent's /Opt, cut to the copied button");
assert_eq!(c.export_of(0), Some("Large"));
}
/// A radio group whose on states are positions in its `/Opt` (`/0`, `/1`, `/2`), as ISO 32000-2
/// allows for buttons with `/Opt`, with the third button selected.
fn numbered_radio() -> Document {
let widget = |i: usize, on: bool| {
let (x, state) = (50 + 30 * i, if on { format!("/{i}") } else { "/Off".into() });
format!(
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS {state} /Rect [{x} 700 {} 715] /P 3 0 R /AP << /N << /{i} 9 0 R /Off 9 0 R >> /D << /{i} 9 0 R /Off 9 0 R >> >> >>",
x + 15
)
};
document(&[
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R] >>".into(),
"<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),
"<< /FT /Btn /T (pick) /Ff 49152 /V /2 /DV /2 /Opt [(first) (second) (third)] /Kids [6 0 R 7 0 R 8 0 R] >>".into(),
widget(0, false),
widget(1, false),
widget(2, true),
"<< /Length 0 >>\nstream\n\nendstream".into(),
])
}
#[test]
fn copying_shared_state_radios_keeps_selection_only_with_the_selected_widget() {
let mut doc = radio_groups();
set_value(&mut doc, "plain", &FieldValue::Widget(0)).unwrap();
let off = paste_field(&mut doc, "plain", &[1], 0, [0.0, -40.0]).unwrap();
let on = paste_field(&mut doc, "plain", &[0], 0, [0.0, -80.0]).unwrap();
let all = paste_field(&mut doc, "plain", &[], 0, [0.0, -120.0]).unwrap();
let doc = reopen(&doc);
let fields = fields(&doc);
assert!(field(&fields, &off).value.is_empty());
assert_eq!(field(&fields, &off).widgets[0].state.as_deref(), Some("Off"));
assert_eq!(field(&fields, &on).value, ["Yes"]);
assert_eq!(field(&fields, &on).widgets[0].state.as_deref(), Some("Yes"));
assert_eq!(field(&fields, &all).value, ["Yes"]);
assert_eq!(field(&fields, &all).widgets[0].state.as_deref(), Some("Yes"));
assert_eq!(field(&fields, &all).widgets[1].state.as_deref(), Some("Off"));
}
#[test]
fn copying_a_numbered_radio_button_renumbers_its_state() {
let mut doc = numbered_radio();
let copy = paste_field(&mut doc, "pick", &[2], 0, [0.0, -40.0]).unwrap();
let all = fields(&doc);
let c = field(&all, &copy);
assert_eq!(c.widgets.len(), 1);
assert_eq!(c.widgets[0].on_state.as_deref(), Some("0"), "the only button is position 0 in the copy's /Opt");
assert_eq!(c.widgets[0].state.as_deref(), Some("0"));
assert_eq!((c.value.as_slice(), c.default.as_slice()), (&["0".to_string()][..], &["0".to_string()][..]));
assert_eq!(c.options, [("third".to_string(), "third".to_string())]);
let w = doc.get(c.widgets[0].obj).as_dict().cloned().unwrap();
let down = w.get(b"AP").and_then(|a| a.as_dict().and_then(|a| a.get(b"D").cloned())).unwrap();
let mut down: Vec<String> = down.as_dict().unwrap().iter().map(|(k, _)| name_text(k)).collect();
down.sort();
assert_eq!(down, ["0", "Off"], "the down appearance is renamed too");
assert_eq!(field(&all, "pick").widgets[2].on_state.as_deref(), Some("2"), "the original is untouched");
}
#[test]
fn copying_an_unselected_numbered_radio_button_copies_it_off() {
let mut doc = numbered_radio();
let copy = paste_field(&mut doc, "pick", &[1], 0, [0.0, -40.0]).unwrap();
let c = doc.get(field(&fields(&doc), &copy).obj).as_dict().cloned().unwrap();
assert_eq!((c.name(b"V"), c.name(b"DV")), (Some(&b"Off"[..]), Some(&b"Off"[..])), "/2 isn't one of the copied buttons");
assert_eq!(c.name(b"AS"), Some(&b"Off"[..]));
}
/// A radio copy made without its default button (here `size`, `/DV /S`, copied with `L` only)
/// gets `/DV /Off`, so Clear form still resets every field, the original back to `S`.
#[test]
fn a_radio_copy_without_its_default_button_still_resets() {
let mut doc = fixture();
let copy = paste_field(&mut doc, "size", &[1], 0, [0.0, -40.0]).unwrap();
let c = doc.get(field(&fields(&doc), &copy).obj).as_dict().cloned().unwrap();
assert_eq!(c.name(b"DV"), Some(&b"Off"[..]), "no copied button is /S");
set_value(&mut doc, &copy, &FieldValue::Radio(Some("L".into()))).unwrap();
reset(&mut doc, None).unwrap();
let all = fields(&doc);
assert_eq!(field(&all, "size").value, ["S"], "the original is reset to its default");
assert!(field(&all, &copy).value.iter().all(|v| v == "Off"), "the copy is reset to off: {:?}", field(&all, &copy).value);
}
/// A copy with the default button keeps it as its `/DV`.
#[test]
fn a_radio_copy_with_its_default_button_keeps_it() {
let mut doc = fixture();
let copy = paste_field(&mut doc, "size", &[0], 0, [0.0, -40.0]).unwrap();
let c = doc.get(field(&fields(&doc), &copy).obj).as_dict().cloned().unwrap();
assert_eq!(c.name(b"DV"), Some(&b"S"[..]));
}
/// A check box whose on state is `/A#23B` (the name `A#B`) and whose `/DV` names it.
fn hash_named_check_box() -> Document {
document(&[
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>".into(),
"<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),
"<< /FT /Btn /T (agree) /V /A#23B /DV /A#23B /Type /Annot /Subtype /Widget /AS /A#23B /Rect [50 700 65 715] /P 3 0 R /AP << /N << /A#23B 6 0 R /Off 6 0 R >> >> >>".into(),
"<< /Length 0 >>\nstream\n\nendstream".into(),
])
}
/// The copied button's on state is compared as name bytes: `/A#23B` keeps a `/DV /A#23B`.
#[test]
fn a_copy_keeps_a_default_whose_name_has_a_hash() {
let mut doc = hash_named_check_box();
let copy = paste_field(&mut doc, "agree", &[0], 0, [0.0, -40.0]).unwrap();
let c = doc.get(field(&fields(&doc), &copy).obj).as_dict().cloned().unwrap();
assert_eq!(c.name(b"DV"), Some(&b"A#B"[..]), "the copied button is the default");
}
/// A renumbered button's rollover look (`/AP /R`) is renamed with `/N` and `/D`.
#[test]
fn copying_a_numbered_radio_button_renames_its_rollover_look() {
let mut doc = numbered_radio();
doc.update_dict(ObjRef::new(8, 0), |d| {
let mut ap = d.get(b"AP").and_then(|a| a.as_dict().cloned()).unwrap_or_default();
let mut r = Dict::new();
r.set(b"2".to_vec(), Object::Ref(ObjRef::new(9, 0)));
r.set(b"Off".to_vec(), Object::Ref(ObjRef::new(9, 0)));
ap.set(b"R".to_vec(), Object::Dict(r));
d.set(b"AP".to_vec(), Object::Dict(ap));
})
.unwrap();
let copy = paste_field(&mut doc, "pick", &[2], 0, [0.0, -40.0]).unwrap();
let all = fields(&doc);
let w = doc.get(field(&all, &copy).widgets[0].obj).as_dict().cloned().unwrap();
let rollover = w.get(b"AP").and_then(|a| a.as_dict().and_then(|a| a.get(b"R").cloned())).unwrap();
let mut names: Vec<String> = rollover.as_dict().unwrap().iter().map(|(k, _)| name_text(k)).collect();
names.sort();
assert_eq!(names, ["0", "Off"]);
}
/// A copy of one widget of a field is one dictionary: the field's `/AA` triggers and the
/// widget's both survive the merge.
#[test]
fn a_single_widget_copy_keeps_the_field_and_widget_triggers() {
let mut doc = numbered_radio();
let pick = field(&fields(&doc), "pick").obj;
let js = |code: &str| {
let mut a = Dict::new();
a.set(b"S".to_vec(), Object::name("JavaScript"));
a.set(b"JS".to_vec(), Object::String(PdfString::literal(code.as_bytes().to_vec())));
Object::Dict(a)
};
let aa = |key: &[u8], code: &str| {
let mut d = Dict::new();
d.set(key.to_vec(), js(code));
Object::Dict(d)
};
doc.update_dict(pick, |d| d.set(b"AA".to_vec(), aa(b"C", "calc()"))).unwrap();
doc.update_dict(ObjRef::new(8, 0), |d| d.set(b"AA".to_vec(), aa(b"U", "up()"))).unwrap();
let copy = paste_field(&mut doc, "pick", &[2], 0, [0.0, -40.0]).unwrap();
let c = doc.get(field(&fields(&doc), &copy).obj).as_dict().cloned().unwrap();
let keys: Vec<String> = c.get(b"AA").and_then(|a| a.as_dict()).unwrap().iter().map(|(k, _)| name_text(k)).collect();
assert!(keys.contains(&"C".to_string()) && keys.contains(&"U".to_string()), "{keys:?}");
}
#[test]
fn a_copied_signed_signature_field_is_drawn_blank() {
let mut doc = fixture();
let name = add_field(&mut doc, 0, [50.0, 220.0, 250.0, 270.0], &NewField::Signature, None).unwrap();
let sig = field(&fields(&doc), &name).obj;
// Signed: a value and the signer's visible appearance (object 7 stands in for it).
doc.update_dict(sig, |d| {
d.set(b"V".to_vec(), Object::Ref(ObjRef::new(8, 0)));
d.set(
b"AP".to_vec(),
Object::Dict({
let mut ap = Dict::new();
ap.set(b"N".to_vec(), Object::Ref(ObjRef::new(7, 0)));
ap
}),
);
})
.unwrap();
let copy = paste_field(&mut doc, &name, &[], 0, [0.0, -60.0]).unwrap();
let all = fields(&doc);
let c = field(&all, &copy);
let w = doc.get(c.widgets[0].obj).as_dict().cloned().unwrap();
assert!(!w.contains(b"V"), "no signature value");
let n = w.get(b"AP").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().and_then(|a| a.get(b"N").cloned()));
assert_ne!(n, Some(Object::Ref(ObjRef::new(7, 0))), "the copy must not show the signer's appearance");
}
/// The widget's `/AP /N` stream, when it is one stream.
fn normal_look(doc: &Document, f: &Field) -> Option<ObjRef> {
let w = doc.get(f.widgets.first()?.obj);
let ap = doc.resolve(w.as_dict()?.get(b"AP")?);
ap.as_dict()?.reference(b"N")
}
#[test]
fn a_pasted_field_does_not_share_its_look_with_the_source() {
let mut doc = fixture();
// The source's border and background dictionaries are indirect: shared, they would be
// restyled in place for both.
let source = field(&fields(&doc), "name").obj;
let mk = doc.add(doc.get(source).as_dict().unwrap().get(b"MK").unwrap().clone());
let mut bs = pdfcraft_cos::Dict::new();
bs.set(b"W".to_vec(), Object::Real(1.0));
let bs = doc.add(Object::Dict(bs));
doc.update_dict(source, |d| {
d.set(b"MK".to_vec(), Object::Ref(mk));
d.set(b"BS".to_vec(), Object::Ref(bs));
})
.unwrap();
let copy = paste_field(&mut doc, "name", &[], 0, [0.0, -300.0]).unwrap();
let before = look(&doc, field(&fields(&doc), "name"));
assert_eq!(look(&doc, field(&fields(&doc), &copy)), before, "the copy looks like the source");
let props = FieldProps {
appearance: Some(LookPatch { fill: Some(Some([0.0, 0.0, 1.0])), width: Some(3.0), ..Default::default() }),
..Default::default()
};
set_props(&mut doc, &copy, &props).unwrap();
let all = fields(&doc);
assert_eq!(look(&doc, field(&all, "name")), before, "restyling the copy left the source alone");
assert_ne!(look(&doc, field(&all, &copy)), before);
// A password field's appearance is redrawn in place when its value changes.
set_value(&mut doc, "pin", &FieldValue::Text("12".into())).unwrap();
let pin = paste_field(&mut doc, "pin", &[], 0, [0.0, -300.0]).unwrap();
let all = fields(&doc);
let (source, copied) = (normal_look(&doc, field(&all, "pin")).unwrap(), normal_look(&doc, field(&all, &pin)).unwrap());
assert_ne!(source, copied, "the copy has an appearance stream of its own");
assert_eq!(doc.get(source), doc.get(copied), "with the source's content");
let before = doc.get(source);
set_value(&mut doc, &pin, &FieldValue::Text("123456".into())).unwrap();
assert_eq!(doc.get(source), before, "filling in the copy left the source's look as it was");
}
#[test]
fn a_transparent_borderless_multiline_field_pastes_onto_another_page_as_it_was() {
// A calendar day: a multiline text field with no background or border.
let objs: Vec<String> = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R 8 0 R] /Count 2 /MediaBox [0 0 600 800] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
"<< /Fields [6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (Mon1) /Ff 4096 /DA (/Helv 8 Tf 0 g) /F 4 /MK << >> /BS << /W 0 >> \
/Rect [40 600 120 680] /P 3 0 R /AP << /N 7 0 R >> >>"
.into(),
"<< /Length 4 /BBox [0 0 80 80] >>\nstream\n/Tx \nendstream".into(),
"<< /Type /Page /Parent 2 0 R >>".into(),
];
let mut doc = document(&objs);
let copy = paste_field(&mut doc, "Mon1", &[], 1, [0.0, 0.0]).unwrap();
assert_eq!(copy, "Mon2", "the next free name");
let doc = reopen(&doc);
let all = fields(&doc);
let (s, c) = (field(&all, "Mon1"), field(&all, &copy));
assert!(c.has(flags::MULTILINE), "still multiline");
assert_eq!(look(&doc, c), look(&doc, s), "same look");
let l = look(&doc, c);
assert_eq!((l.fill, l.border), (None, None), "still transparent with no border");
assert_eq!((c.widgets[0].page, c.widgets[0].rect), (Some(1), s.widgets[0].rect), "on page 2, in the same place");
assert_eq!((s.widgets[0].page, all.len()), (Some(0), 2), "the source stays on page 1");
let w = doc.get(c.widgets[0].obj);
let w = w.as_dict().unwrap();
assert_eq!(w.get(b"F").and_then(Object::as_int), Some(4), "printable, as the source");
let (sa, ca) = (normal_look(&doc, s).unwrap(), normal_look(&doc, c).unwrap());
assert_ne!(sa, ca);
assert_eq!(doc.get(sa), doc.get(ca), "the source's appearance, not a redrawn one");
}
+6 -1
View File
@@ -513,8 +513,13 @@ fn write_value_impl(doc: &mut Document, f: &Field, value: &FieldValue, scripts:
}
}
/// Redraw a calculated value without running input validation or calculation again.
/// Redraw a script-set value through its Format script without running input validation or
/// calculation again. Only text and combo boxes have a Format script to show; a check box's or
/// radio button's on and off appearances stay as the value's write left them.
pub(crate) fn redraw_calculated_value(doc: &mut Document, f: &Field, values: &[String], scripts: &mut dyn Scripts) -> Result<(), FormError> {
if !matches!(f.kind, FieldKind::Text | FieldKind::Combo) {
return Ok(());
}
redraw(doc, f, values, scripts)
}
+2 -1
View File
@@ -1,5 +1,6 @@
use super::host::{
FieldKey, arg, charge, colour, error, function, host, kind_of, read, s, strings, text, text_bytes, text_line, value_for, value_of, write,
write_value,
};
use super::model::{DISPLAY_HIDDEN, DISPLAY_VISIBLE, FieldType, Request};
use super::{Attribute, Context, JsArray, JsObject, JsResult, JsString, JsValue, NativeFunction, ObjectInitializer, js_string};
@@ -45,7 +46,7 @@ fn field_object_new(ctx: &mut Context, name: &str, id: Option<u64>, token: u64)
fn set(_: &JsValue, args: &[JsValue], name: &FieldKey, c: &mut Context) -> JsResult<JsValue> {
let vals = value_for(kind_of(c, name)?, strings(&arg(args, 0), c)?);
charge(c, name, |f| text_bytes(&f.value), text_bytes(&vals))?;
write(c, name, |f| f.value = vals)?;
write_value(c, name, vals)?;
Ok(JsValue::undefined())
}
function(ctx, NativeFunction::from_copy_closure_with_captures(set, n.clone()))
+13 -1
View File
@@ -249,12 +249,24 @@ pub(crate) fn read(ctx: &Context, name: &FieldKey) -> JsResult<FieldState> {
}
pub(crate) fn write(ctx: &Context, name: &FieldKey, change: impl FnOnce(&mut FieldState)) -> JsResult<()> {
write_index(ctx, name, change).map(|_| ())
}
/// [`write`] a new value, which the field shows through its Format script, as it shows a
/// calculated one.
pub(crate) fn write_value(ctx: &Context, name: &FieldKey, vals: Vec<String>) -> JsResult<()> {
let i = write_index(ctx, name, |f| f.value = vals)?;
host(ctx)?.borrow_mut().formatted.insert(i);
Ok(())
}
fn write_index(ctx: &Context, name: &FieldKey, change: impl FnOnce(&mut FieldState)) -> JsResult<usize> {
let i = field_index(ctx, name)?;
let mut h = host(ctx)?.borrow_mut();
let field = Arc::make_mut(&mut h.fields).get_mut(i).ok_or_else(|| error("the field is no longer available"))?;
change(field);
h.changed.insert(i);
Ok(())
Ok(i)
}
pub(crate) fn value_of(f: &FieldState, ctx: &mut Context) -> JsValue {
+2 -1
View File
@@ -430,7 +430,8 @@ pub struct Outcome {
pub change: String,
/// Fields whose value or properties the script changed, as they are now.
pub changed: Vec<FieldState>,
/// Fields updated by Calculate scripts; their Format script must redraw the appearance.
/// Fields given a value by a Calculate script or a `field.value` assignment; their Format
/// script must redraw the appearance.
pub formatted: std::collections::BTreeSet<String>,
/// The messages the script showed, in order.
pub alerts: Vec<Message>,
+23
View File
@@ -1167,6 +1167,29 @@ mod xfa_model {
assert_eq!(o.effects.iter().filter(|e| matches!(e, XfaEffect::AddInstance { .. })).count(), count - 2);
}
/// A field or repeating subform whose name has letters outside ASCII (`Prénom`, as French
/// forms name them) is reached by its bare name, and its instance manager as `_name`, as a
/// FormCalc script reaches it.
#[test]
fn bare_names_with_accented_letters_reach_their_nodes() {
let mut f = form();
let page = &mut f.children[0];
page.children.push(field("Prénom", "form1[0].page1[0].Prénom[0]", "Élodie", false));
page.children.push(XfaNode {
name: "Bénéficiaire".into(),
som: "form1[0].page1[0].Bénéficiaire[0]".into(),
kind: Some(XfaKind::Subform),
repeatable: true,
occur_min: 1,
children: vec![field("nom", "form1[0].page1[0].Bénéficiaire[0].nom[0]", "", false)],
..Default::default()
});
let ev = XfaEvent { activity: "click".into(), target: "form1[0].page1[0].go[0]".into(), ..Default::default() };
let o = run_xfa("Prénom.rawValue + '|' + _Bénéficiaire.count", &ev, &XfaDoc::default(), &f, Limits::default());
assert_eq!(o.error, None, "{o:?}");
assert_eq!(o.result.as_deref(), Some("Élodie|1"));
}
/// `_name` is resolved nearest first like any bare name: a nearer field called `_item` is
/// not replaced by a farther repeating subform's instance manager, nor a nearer instance
/// manager by a farther field called `_entry`.
+4 -2
View File
@@ -412,13 +412,15 @@ pub(super) fn install(ctx: &mut Context, event: &XfaEvent, doc: &XfaDoc, current
Ok(())
}
/// A name a script can write bare. JavaScript names take any Unicode letter, and forms name
/// fields in their own language (`Prénom`); these are the letters the FormCalc lexer accepts.
fn is_identifier(name: &str) -> bool {
let mut chars = name.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
Some(c) if c.is_alphabetic() || c == '_' || c == '$' => {}
_ => return false,
}
chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
chars.all(|c| c.is_alphanumeric() || c == '_' || c == '$')
&& !matches!(
name,
"var"
+17
View File
@@ -93,6 +93,23 @@ pub fn page_boxes(doc: &Document) -> Result<Vec<[[f64; 4]; 5]>, OrganizeError> {
.collect())
}
/// The bleed, trim and art boxes each page sets itself, clipped to the media box; `None` where
/// the page leaves the box to its default (the crop box). These are what Show art, trim and
/// bleed boxes draws: a default box is the crop box, the page's own edge.
pub fn defined_page_boxes(doc: &Document) -> Result<Vec<[Option<[f64; 4]>; 3]>, OrganizeError> {
Ok(walk(doc)?
.iter()
.map(|(page, inherited)| {
let obj = doc.get(*page);
let d = obj.as_dict().cloned().unwrap_or_default();
let media = rect_of(d.get(b"MediaBox").or_else(|| inherited.get(b"MediaBox")), doc).unwrap_or([0.0, 0.0, 612.0, 792.0]);
// Bleed, trim and art boxes are not inheritable (ISO 32000-2 table 31).
let own = |k: &[u8]| rect_of(d.get(k), doc).map(|c| intersect(c, media)).filter(|c| c[2] > c[0] && c[3] > c[1]);
[own(b"BleedBox"), own(b"TrimBox"), own(b"ArtBox")]
})
.collect())
}
/// Set a box on `pages` (0-based). Margins apply to each page's own media box.
pub fn set_page_box(doc: &mut Document, pages: &[usize], which: PageBox, spec: BoxSpec) -> Result<(), OrganizeError> {
let all = walk(doc)?;
+1 -1
View File
@@ -30,7 +30,7 @@ pub mod view;
mod xmp;
pub use attachments::{add_attachment, attachment_keys, delete_attachment, mime_for_name, set_attachment_description};
pub use boxes::{BoxSpec, PageBox, page_boxes, set_page_box};
pub use boxes::{BoxSpec, PageBox, defined_page_boxes, page_boxes, set_page_box};
pub use comments::import_comments;
pub use dedupe::dedupe_resources;
pub use import::{
+1 -1
View File
@@ -11,7 +11,7 @@ repository.workspace = true
workspace = true
[dependencies]
craft-cms-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-cms-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
craft-xml = { workspace = true }
pdfcraft-content = { workspace = true }
pdfcraft-cos = { workspace = true }
+619
View File
@@ -0,0 +1,619 @@
//! Keep compatibility-reader diagnostics useful when one damaged file has many bad objects.
//! This integration binary owns its logger; the lock isolates captures between tests, while
//! lopdf's default Rayon workers still execute concurrently inside each read.
use std::sync::{Arc, Mutex, Once};
use log::{Level, LevelFilter, Log, Metadata, Record};
use lopdf::{Document, LoadOptions};
static TEST_LOCK: Mutex<()> = Mutex::new(());
static RECORDS: Mutex<Vec<(Level, String)>> = Mutex::new(Vec::new());
static INIT: Once = Once::new();
struct Capture;
impl Log for Capture {
/// Capture only diagnostics emitted by the compatibility reader.
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.target().starts_with("lopdf::")
}
/// Record matching messages and severity for the serialized test capture.
fn log(&self, record: &Record<'_>) {
if self.enabled(record.metadata()) {
RECORDS.lock().unwrap_or_else(|e| e.into_inner()).push((record.level(), record.args().to_string()));
}
}
/// Keep captured records until the test explicitly clears them.
fn flush(&self) {}
}
/// Install the shared logger once and clear records under the caller's test lock.
fn start_capture() {
INIT.call_once(|| {
log::set_logger(&Capture).unwrap();
log::set_max_level(LevelFilter::Trace);
});
RECORDS.lock().unwrap_or_else(|e| e.into_inner()).clear();
}
/// Snapshot captured diagnostics, recovering the test mutex after poisoning.
fn records() -> Vec<(Level, String)> {
RECORDS.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
/// Build a readable synthetic page with requested malformed objects and stream containers.
fn fixture(bad_objects: usize, bad_streams: usize) -> Vec<u8> {
// The page is readable even though unrelated indirect objects are not.
let names = if bad_objects > 0 { " /Names 6 0 R" } else { "" };
let mut objects = vec![
format!("<< /Type /Catalog /Pages 2 0 R{names} >>").into_bytes(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>".to_vec(),
b"<< /Length 38 >>\nstream\nBT /F1 12 Tf 20 150 Td (Visible) Tj ET\nendstream".to_vec(),
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
];
objects.extend((0..bad_objects).map(|_| b"not-a-pdf-object".to_vec()));
objects.extend((0..bad_streams).map(|_| invalid_object_stream()));
pdf_with_objects(objects)
}
/// An object stream whose member-header offset lies past its one-byte content.
fn invalid_object_stream() -> Vec<u8> {
b"<< /Type /ObjStm /N 1 /First 99 /Length 1 >>\nstream\nx\nendstream".to_vec()
}
/// Serialize synthetic indirect objects with a classic cross-reference table.
fn pdf_with_objects(objects: Vec<Vec<u8>>) -> Vec<u8> {
let mut pdf = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, object) in objects.iter().enumerate() {
offsets.push(pdf.len());
pdf.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
pdf.extend_from_slice(object);
pdf.extend_from_slice(b"\nendobj\n");
}
let xref = pdf.len();
pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
for offset in offsets {
pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
pdf
}
/// Misplace startxref to exercise compatibility inspection and its diagnostic budget.
fn compatibility_fixture() -> Vec<u8> {
// A known producer mistake: startxref points just after "xref", so COS records a repair
// and inspect uses the eager compatibility reader. The ordinary parser repairs it too.
let pdf = String::from_utf8(fixture(1250, 0)).unwrap();
let xref = pdf.find("xref\n").unwrap();
let start = pdf.rfind("startxref\n").unwrap();
format!("{}startxref\n{}\n%%EOF\n", &pdf[..start], xref + 4).into_bytes()
}
/// Require eight error details, one exact summary, and no unbudgeted messages.
fn assert_bounded(messages: &[(Level, String)], total: usize, streams: usize) {
let details = messages.iter().filter(|(_, s)| s.starts_with("Object load error") || s.starts_with("Object stream load error")).count();
assert_eq!(details, 8, "expected bounded details, captured {} records", messages.len());
let summaries: Vec<_> = messages.iter().filter(|(_, s)| s.starts_with("Object loading:")).collect();
assert_eq!(summaries.len(), 1);
assert!(summaries[0].1.contains(&format!("{total} failed objects ({streams} object streams)")), "{summaries:?}");
assert!(summaries[0].1.contains(&format!("{} additional messages suppressed", total - 8)), "{summaries:?}");
assert_eq!(messages.len(), 9, "no extra per-object log sites should bypass the budget");
assert!(messages.iter().all(|(level, _)| *level == Level::Error));
}
/// Keep a readable page while summarizing 1,250 malformed objects in nine records.
#[test]
fn malformed_objects_log_bounded_details_and_an_exact_summary() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
start_capture();
let doc = Document::load_mem(&fixture(1250, 0)).unwrap();
assert_eq!(doc.get_pages().len(), 1);
assert!(doc.get_object((5, 0)).is_ok(), "readable objects are retained");
assert_bounded(&records(), 1250, 0);
}
/// Count ordinary and compressed-object failures in the same eight-detail allowance.
#[test]
fn ordinary_and_object_stream_failures_share_one_log_budget() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
start_capture();
let doc = Document::load_mem(&fixture(20, 30)).unwrap();
assert_eq!(doc.get_pages().len(), 1);
assert_bounded(&records(), 50, 30);
}
/// Give each compatibility inspection its own budget while retaining the xref repair warning.
#[test]
fn compatibility_inspection_gets_a_fresh_budget_on_every_open() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let pdf = Arc::new(compatibility_fixture());
for _ in 0..2 {
start_capture();
let info = pdfcraft_render::inspect(pdf.clone(), None).unwrap();
assert_eq!(info.pages.len(), 1);
let messages = records();
assert!(messages.iter().any(|(level, text)| *level == Level::Warn && text.starts_with("Cross-reference offset ")));
let object_messages: Vec<_> = messages.into_iter().filter(|(_, text)| !text.starts_with("Cross-reference offset ")).collect();
assert_bounded(&object_messages, 1250, 0);
}
}
/// Keep healthy reads silent and preserve every diagnostic within the allowance.
#[test]
fn healthy_and_small_damaged_files_keep_their_diagnostics() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
start_capture();
Document::load_mem(&fixture(0, 0)).unwrap();
assert!(records().is_empty());
for count in [1, 3, 8] {
start_capture();
Document::load_mem(&fixture(count, 0)).unwrap();
let messages = records();
assert_eq!(messages.len(), count);
assert!(messages.iter().all(|(level, s)| *level == Level::Error && s.starts_with("Object load error at offset ")));
}
}
/// Preserve strict read errors while bounding diagnostics from concurrent workers.
#[test]
fn strict_loading_still_refuses_malformed_objects() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for (objects, streams) in [(1250, 0), (0, 1250)] {
start_capture();
let result = Document::load_mem_with_options(&fixture(objects, streams), LoadOptions { strict: true, ..Default::default() });
assert!(result.is_err());
let messages = records();
assert!(!messages.is_empty());
assert!(messages.len() <= 9, "strict Rayon reads also share a bounded budget");
assert!(messages.iter().all(|(level, _)| *level == Level::Error));
}
}
/// Give concurrent documents separate detail allowances and summary totals.
#[test]
fn concurrent_document_reads_have_independent_budgets() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
start_capture();
let a = std::thread::spawn(|| Document::load_mem(&fixture(50, 0)).unwrap().get_pages().len());
let b = std::thread::spawn(|| Document::load_mem(&fixture(50, 0)).unwrap().get_pages().len());
assert_eq!(a.join().unwrap(), 1);
assert_eq!(b.join().unwrap(), 1);
let messages = records();
assert_eq!(messages.len(), 18, "two reads each get eight details and one summary");
assert_eq!(messages.iter().filter(|(_, s)| s.starts_with("Object loading:") && s.contains("42 additional messages suppressed")).count(), 2);
}
// Missing/broken indirect Length leaves a deferred stream; its later lookup also
// belongs to this read's budget, even though eager object collection has finished.
/// Charge missing and broken indirect lengths to the original read budget.
#[test]
fn deferred_stream_length_errors_share_the_load_budget() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for length in ["", " /Length 999999 0 R"] {
start_capture();
let objects = (0..1250).map(|_| format!("<<{length} >>\nstream\nx\nendstream").into_bytes()).collect();
let doc = Document::load_mem(&pdf_with_objects(objects)).unwrap();
assert_eq!(doc.objects.len(), 1250, "diagnostic suppression must retain the streams");
let messages = records();
assert_eq!(messages.len(), 9, "missing/broken Length logs bypass the budget");
assert_eq!(messages.iter().filter(|(_, s)| s.contains("missing the Length entry")).count(), 8);
let summary = &messages.last().unwrap().1;
assert!(summary.contains("1250 stream length errors"), "{summary}");
assert!(summary.contains("1242 additional messages suppressed"), "{summary}");
assert!(messages.iter().all(|(level, _)| *level == Level::Error));
}
}
/// Build synthetic object-stream members with bad, duplicate, or empty offsets.
fn member_stream(count: usize, kind: &str) -> Vec<u8> {
let index: String = (0..count)
.map(|i| {
let offset = match kind {
"outside" => 10000,
"duplicate" => 0,
"whitespace" => i,
_ => unreachable!(),
};
format!("{} {offset} ", 10000 + i)
})
.collect();
let body = if kind == "whitespace" { " ".repeat(count) } else { "42".to_owned() };
let content = format!("{index}{body}");
format!("<< /Type /ObjStm /N {count} /First {} /Length {} >>\nstream\n{content}\nendstream", index.len(), content.len()).into_bytes()
}
/// Share one warning allowance across every object-stream member in a document.
#[test]
fn object_stream_member_warnings_are_bounded_across_all_streams() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for kind in ["outside", "duplicate", "whitespace"] {
start_capture();
Document::load_mem(&pdf_with_objects(vec![member_stream(1000, kind), member_stream(1000, kind)])).unwrap();
let messages = records();
let total = if kind == "duplicate" { 1998 } else { 2000 };
assert_eq!(messages.len(), 9, "{kind}: per-member logs bypass the budget");
let summary = &messages.last().unwrap().1;
assert!(summary.contains(&format!("{total} object stream warnings")), "{summary}");
assert!(summary.contains(&format!("{} additional messages suppressed", total - 8)), "{summary}");
assert!(messages.iter().all(|(level, _)| *level == Level::Warn));
}
}
/// Combine diagnostic categories in one summary at the highest encountered severity.
#[test]
fn mixed_errors_and_warnings_share_one_budget_and_summary() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
start_capture();
let mut objects = vec![member_stream(1000, "outside"), b"not-an-object".to_vec()];
objects.extend((0..20).map(|_| b"<< >>\nstream\nx\nendstream".to_vec()));
Document::load_mem(&pdf_with_objects(objects)).unwrap();
let messages = records();
assert_eq!(messages.len(), 9);
let (level, summary) = messages.last().unwrap();
assert_eq!(*level, Level::Error, "the summary must retain the highest severity");
for text in
["1 failed objects (0 object streams)", "1000 object stream warnings", "20 stream length errors", "1013 additional messages suppressed"]
{
assert!(summary.contains(text), "{summary}");
}
}
/// Emit exact suppressed-message totals before returning a deterministic strict failure.
#[test]
fn strict_error_still_reports_the_suppressed_diagnostics() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
// The reader expands containers in object-number order after the ordinary-object pass.
// The first container consumes the allowance before the second produces a strict error.
start_capture();
let pdf = pdf_with_objects(vec![member_stream(1000, "outside"), invalid_object_stream()]);
let result = Document::load_mem_with_options(&pdf, LoadOptions { strict: true, ..Default::default() });
assert!(result.is_err(), "strict refusal must survive log suppression");
let messages = records();
assert_eq!(messages.len(), 9, "strict failure must emit the summary before returning");
let (level, summary) = messages.last().unwrap();
assert_eq!(*level, Level::Error);
assert!(summary.starts_with("Object loading:"), "{messages:?}");
assert!(summary.contains("1 failed objects (1 object streams)"), "{summary}");
assert!(summary.contains("1000 object stream warnings"), "{summary}");
assert!(summary.contains("993 additional messages suppressed"), "{summary}");
}
/// Preserve small diagnostic batches and retain valid members despite duplicate offsets.
#[test]
fn small_stream_diagnostics_keep_their_text_level_and_objects() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for count in [1, 8] {
start_capture();
let doc = Document::load_mem(&pdf_with_objects(vec![member_stream(count, "outside")])).unwrap();
assert_eq!(doc.objects.len(), 1, "the object-stream container is retained");
let messages = records();
assert_eq!(messages.len(), count);
assert!(messages.iter().all(|(level, text)| *level == Level::Warn && text == "out-of-bounds offset in object stream"));
start_capture();
let objects = (0..count).map(|_| b"<< >>\nstream\nx\nendstream".to_vec()).collect();
let doc = Document::load_mem(&pdf_with_objects(objects)).unwrap();
assert_eq!(doc.objects.len(), count);
let messages = records();
assert_eq!(messages.len(), count);
assert!(messages.iter().all(|(level, text)| *level == Level::Error && text.contains("missing the Length entry")));
}
start_capture();
let doc = Document::load_mem(&pdf_with_objects(vec![member_stream(1000, "duplicate")])).unwrap();
assert_eq!(doc.get_object((10000, 0)).unwrap().as_i64().unwrap(), 42, "the first valid member survives duplicate offsets");
}
/// Bound standalone object-stream parsing, including its dictionary and member warnings.
#[test]
fn direct_object_stream_parsing_also_has_a_bounded_budget() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
start_capture();
let index: String = (0..1000).map(|i| format!("{} 10000 ", i + 1)).collect();
let mut dict = lopdf::Dictionary::new();
dict.set("First", i64::try_from(index.len()).unwrap());
dict.set("N", 999); // One dictionary warning and 1000 member warnings.
let stream = lopdf::Stream::new(dict, format!("{index}42").into_bytes());
assert!(lopdf::ObjectStream::new(&stream).unwrap().objects.is_empty());
let messages = records();
assert_eq!(messages.len(), 9);
assert!(messages.last().unwrap().1.contains("1001 object stream warnings"));
assert!(messages.last().unwrap().1.contains("993 additional messages suppressed"));
assert!(messages.iter().all(|(level, _)| *level == Level::Warn));
}
/// Spending the last node preserves the first member and charges its warning to the same log.
#[test]
fn a_spent_node_budget_counts_toward_the_diagnostic_summary() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let mut index = String::from("1 0 2 3 ");
for id in 10..18 {
index.push_str(&format!("{id} 99 "));
}
let mut dict = lopdf::Dictionary::new();
dict.set("First", i64::try_from(index.len()).unwrap());
dict.set("N", 10);
let stream = lopdf::Stream::new(dict, format!("{index}42 43").into_bytes());
let budget = lopdf::NodeBudget::new(1);
start_capture();
let parsed = lopdf::ObjectStream::new_within(&stream, None, &budget).unwrap();
assert_eq!(parsed.objects.len(), 1);
assert_eq!(parsed.objects[&(1, 0)].as_i64().unwrap(), 42);
assert!(budget.spent());
let messages = records();
assert_eq!(messages.len(), 9);
assert!(messages[..8].iter().all(|(level, text)| *level == Level::Warn && text == "out-of-bounds offset in object stream"));
let (level, summary) = &messages[8];
assert_eq!(*level, Level::Warn);
assert!(summary.contains("9 object stream warnings") && summary.contains("1 additional messages suppressed"), "{summary}");
}
/// A valid compressed Length/Info pair in a stream whose N header is deliberately wrong.
/// Every content-stream lookup reparses that same container before eager collection completes.
fn compressed_lengths_fixture(count: usize) -> Vec<u8> {
let info = "<< /Title (Captured) >>";
let index = format!("5 0 6 {} ", info.len() + 1);
let members = format!("{index}{info} 3");
let mut objects = vec![
(1usize, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),
(2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()),
(3, b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << >> /Contents 7 0 R >>".to_vec()),
(4, format!("<< /Type /ObjStm /N 3 /First {} /Length {} >>\nstream\n{members}\nendstream", index.len(), members.len()).into_bytes()),
];
objects.extend((0..count).map(|i| (7 + i, b"<< /Length 6 0 R >>\nstream\nq Q\nendstream".to_vec())));
let xref_id = 7 + count;
let mut offsets = vec![0u32; xref_id + 1];
let mut pdf = b"%PDF-1.7\n".to_vec();
for (id, object) in objects {
offsets[id] = u32::try_from(pdf.len()).unwrap();
pdf.extend_from_slice(format!("{id} 0 obj\n").as_bytes());
pdf.extend_from_slice(&object);
pdf.extend_from_slice(b"\nendobj\n");
}
let xref = pdf.len();
offsets[xref_id] = u32::try_from(xref).unwrap();
let mut entries = Vec::new();
for (id, offset) in offsets.into_iter().enumerate() {
let (kind, first, second): (u8, u32, u16) = match id {
0 => (0, 0, 65535),
5 => (2, 4, 0),
6 => (2, 4, 1),
_ => (1, offset, 0),
};
entries.push(kind);
entries.extend_from_slice(&first.to_be_bytes());
entries.extend_from_slice(&second.to_be_bytes());
}
pdf.extend_from_slice(
format!("{xref_id} 0 obj\n<< /Type /XRef /Size {} /Root 1 0 R /Info 5 0 R /W [1 4 2] /Length {} >>\nstream\n", xref_id + 1, entries.len())
.as_bytes(),
);
pdf.extend_from_slice(&entries);
pdf.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{xref}\n%%EOF\n").as_bytes());
pdf
}
/// Indirect compressed Length lookups share the eager budget, including strict reads.
#[test]
fn compressed_lengths_share_the_eager_load_budget() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for strict in [false, true] {
for count in [1, 32] {
start_capture();
let doc = Document::load_mem_with_options(&compressed_lengths_fixture(count), LoadOptions { strict, ..Default::default() }).unwrap();
assert_eq!(doc.get_pages().len(), 1);
assert_eq!(doc.get_object((5, 0)).unwrap().as_dict().unwrap().get(b"Title").unwrap().as_str().unwrap(), b"Captured");
for i in 0..count {
assert_eq!(doc.get_object((u32::try_from(7 + i).unwrap(), 0)).unwrap().as_stream().unwrap().content, b"q Q");
}
let messages = records();
let total = count + 1; // One header warning per lookup plus the eager container read.
assert_eq!(messages.len(), if total <= 8 { total } else { 9 }, "strict={strict}, count={count}: {messages:?}");
assert!(messages.iter().all(|(level, _)| *level == Level::Warn));
if total > 8 {
let summary = &messages.last().unwrap().1;
assert!(summary.starts_with("Object loading:"), "{summary}");
assert!(summary.contains(&format!("{total} object stream warnings")), "{summary}");
assert!(summary.contains(&format!("{} additional messages suppressed", total - 8)), "{summary}");
}
}
}
}
/// Lightweight metadata keeps compressed fields without creating standalone log batches.
#[test]
fn compressed_lengths_metadata_does_not_start_diagnostic_batches() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
start_capture();
let metadata = Document::load_metadata_mem(&compressed_lengths_fixture(1)).unwrap();
assert_eq!(metadata.title.as_deref(), Some("Captured"));
assert_eq!(metadata.page_count, 1);
assert!(records().is_empty(), "metadata lookups have no eager-load logging context: {:?}", records());
}
/// An encrypted fixture retains real compressed references in an incremental xref stream.
/// The writer omits existing containers, so retain them and add compressed references explicitly.
fn encrypted_container_fixture(count: usize) -> Vec<u8> {
encrypted_stream_fixture(count, false)
}
/// Build encrypted compressed references, optionally replacing containers with malformed streams.
fn encrypted_stream_fixture(count: usize, broken: bool) -> Vec<u8> {
let mut doc = Document::load_mem(&fixture(0, 0)).unwrap();
doc.trailer.set("ID", lopdf::Object::Array(vec![lopdf::Object::string_literal("BBBBBBBBBBBBBBBB"); 2]));
let mut containers = Vec::new();
for i in 0..count {
let member = 10000 + u32::try_from(i).unwrap();
let index = format!("{member} 0 ");
let mut dict = lopdf::Dictionary::new();
// The writer omits existing ObjStm containers. Restore this same-length name after
// serialization; names are not encrypted and object offsets remain unchanged.
dict.set("Type", "ObjStx");
dict.set("N", if broken { 1 } else { 2 }); // Otherwise one valid member with a wrong count.
dict.set("First", if broken { 99 } else { i64::try_from(index.len()).unwrap() });
let container = doc.add_object(lopdf::Stream::new(dict, format!("{index}42").into_bytes()));
containers.push(container.0);
}
let version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "owner",
user_password: "user",
key_length: 128,
permissions: lopdf::Permissions::all(),
};
doc.encrypt(&lopdf::EncryptionState::try_from(version).unwrap()).unwrap();
let encrypt = doc.trailer.get(b"Encrypt").unwrap().as_reference().unwrap();
let mut pdf = Vec::new();
doc.save_to(&mut pdf).unwrap();
let mut restored = 0;
for i in 0..=pdf.len() - 6 {
if &pdf[i..i + 6] == b"ObjStx" {
pdf[i + 5] = b'm';
restored += 1;
}
}
assert_eq!(restored, count);
let marker = b"startxref\n";
let start = pdf.windows(marker.len()).rposition(|w| w == marker).unwrap() + marker.len();
let prev: usize = std::str::from_utf8(&pdf[start..]).unwrap().lines().next().unwrap().parse().unwrap();
let xref = pdf.len();
let xref_id = 10000 + count;
let mut entries = Vec::new();
for container in containers {
entries.push(2);
entries.extend_from_slice(&container.to_be_bytes());
entries.extend_from_slice(&0u16.to_be_bytes());
}
entries.push(1);
entries.extend_from_slice(&u32::try_from(xref).unwrap().to_be_bytes());
entries.extend_from_slice(&0u16.to_be_bytes());
let id = "42".repeat(16);
pdf.extend_from_slice(format!("\n{xref_id} 0 obj\n<< /Type /XRef /Size {} /Root 1 0 R /Encrypt {} {} R /ID [<{id}> <{id}>] /Prev {prev} /Index [10000 {}] /W [1 4 2] /Length {} >>\nstream\n", xref_id + 1, encrypt.0, encrypt.1, count + 1, entries.len()).as_bytes());
pdf.extend_from_slice(&entries);
pdf.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{xref}\n%%EOF\n").as_bytes());
pdf
}
/// All encrypted containers share one budget, retaining their decrypted members and page.
#[test]
fn encrypted_object_streams_share_the_load_budget() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for strict in [false, true] {
for count in [1, 32] {
let pdf = encrypted_container_fixture(count);
start_capture();
let doc = Document::load_mem_with_options(&pdf, LoadOptions { strict, ..LoadOptions::with_password("user") }).unwrap();
assert_eq!(doc.get_pages().len(), 1);
for i in 0..count {
let member = 10000 + u32::try_from(i).unwrap();
let value = doc.get_object((member, 0));
assert!(
value.is_ok(),
"missing member {member}: xref={:?}, container={:?}, logs={:?}",
doc.reference_table.get(member),
doc.get_object((6 + u32::try_from(i).unwrap(), 0)),
records()
);
assert_eq!(value.unwrap().as_i64().unwrap(), 42);
}
let messages = records();
assert_eq!(messages.len(), if count <= 8 { count } else { 9 }, "strict={strict}, count={count}: {messages:?}");
assert!(messages.iter().all(|(level, _)| *level == Level::Warn));
if count > 8 {
let summary = &messages.last().unwrap().1;
assert!(summary.starts_with("Object loading:"), "{summary}");
assert!(summary.contains(&format!("{count} object stream warnings")), "{summary}");
assert!(summary.contains(&format!("{} additional messages suppressed", count - 8)), "{summary}");
}
}
}
}
/// Count malformed encrypted containers without changing the diagnostic limit.
#[test]
fn encrypted_container_errors_are_counted_and_bounded() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for strict in [false, true] {
for count in [1, 32] {
let pdf = encrypted_stream_fixture(count, true);
start_capture();
let doc = Document::load_mem_with_options(&pdf, LoadOptions { strict, ..LoadOptions::with_password("user") }).unwrap();
assert_eq!(doc.get_pages().len(), 1);
assert!(doc.get_object((10000, 0)).is_err(), "the bad container was not parsed");
let messages = records();
if count > 8 {
assert_bounded(&messages, count, count);
} else {
assert_eq!(messages.len(), count, "failed encrypted containers must be recorded: {messages:?}");
assert!(messages.iter().all(|(level, text)| *level == Level::Error && text.starts_with("Object stream load error")));
}
}
}
}
/// Build cyclic or excessive indirect-Length chains that emit lookup warnings.
fn lookup_warning_fixture(count: usize, cycle: bool) -> Vec<u8> {
let mut objects = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>".to_vec(),
b"<< /Length 3 >>\nstream\nq Q\nendstream".to_vec(),
b"42".to_vec(),
];
let chain = if cycle { 1 } else { 18 };
for i in 0..chain {
let length = if cycle {
"6 0 R".to_string()
} else if i + 1 == chain {
"1".to_string()
} else {
format!("{} 0 R", 7 + i)
};
objects.push(format!("<< /Length {length} >>\nstream\nx\nendstream").into_bytes());
}
objects.extend((0..count).map(|_| b"<< /Length 6 0 R >>\nstream\nx\nendstream".to_vec()));
String::from_utf8(pdf_with_objects(objects)).unwrap().replace("/Root 1 0 R", "/Root 1 0 R /Info 6 0 R").into_bytes()
}
/// Charge cyclic and excessive-depth lookup warnings to the enclosing read budget.
#[test]
fn lookup_warnings_share_the_load_budget() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for cycle in [false, true] {
for strict in [false, true] {
for count in [1, 32] {
let pdf = lookup_warning_fixture(count, cycle);
start_capture();
let doc = Document::load_mem_with_options(&pdf, LoadOptions { strict, ..Default::default() }).unwrap();
assert_eq!(doc.get_pages().len(), 1);
assert_eq!(doc.get_object((5, 0)).unwrap().as_i64().unwrap(), 42);
let messages = records();
let warnings = count + 1;
let lengths = count + if cycle { 1 } else { 17 };
let total = warnings + lengths;
assert_eq!(messages.len(), if total <= 8 { total } else { 9 }, "cycle={cycle}, strict={strict}, count={count}: {messages:?}");
if total > 8 {
let (level, summary) = messages.last().unwrap();
assert_eq!(*level, Level::Error);
assert!(summary.contains("0 failed objects (0 object streams)"), "{summary}");
assert!(summary.contains(&format!("{warnings} object stream warnings")), "{summary}");
assert!(summary.contains(&format!("{lengths} stream length errors")), "{summary}");
assert!(summary.contains(&format!("{} additional messages suppressed", total - 8)), "{summary}");
}
}
}
}
}
/// Read lightweight metadata without starting object-load diagnostic batches.
#[test]
fn metadata_lookup_warnings_stay_silent() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for cycle in [false, true] {
let pdf = lookup_warning_fixture(0, cycle);
start_capture();
let info = Document::load_metadata_mem(&pdf).unwrap();
assert_eq!(info.page_count, 1);
assert!(records().is_empty(), "metadata lookup diagnostics escaped the silent context: {:?}", records());
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ workspace = true
[dependencies]
# Existing shared ASN.1 codec; PDF signature policy remains local.
craft-pkcs7 = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-pkcs7 = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" }
pdfcraft-cos = { workspace = true }
pdfcraft-annot = { workspace = true }
pdfcraft-content = { workspace = true }
+31 -3
View File
@@ -20,7 +20,7 @@ use craft::platform::autosave::Autosave;
use craft::platform::autosave::RecoveryStore;
use craft::platform::clipboard::Clipboard;
use craft::platform::open::FileIntake;
use craft::ui::runtime::env::{RootEnv, Scale};
use craft::ui::runtime::env::{RootEnv, Scale, WheelSpeed};
#[cfg(not(target_arch = "wasm32"))]
use craft::ui::shell::embed;
@@ -32,6 +32,8 @@ mod frame;
mod input;
mod keys;
mod links;
#[cfg(any(target_os = "macos", test))]
mod metal_fullscreen;
pub(crate) mod picks;
mod prefs;
// Reloading a document whose file changed on disk; the web watches no files.
@@ -39,6 +41,8 @@ mod prefs;
pub(crate) mod reload;
pub mod settings;
mod window;
#[cfg(target_os = "macos")]
pub(crate) use metal_fullscreen::MetalFullscreen;
pub(crate) use clipboard::{ObjectClipMark, copy_refused, print_refused};
pub(crate) use files::same_file;
@@ -302,13 +306,14 @@ impl PdfCraftApp {
show_form_field_reminder: true,
highlight_fields: true,
units: Default::default(),
show_page_boxes: false,
blank_paper: crate::paper::Paper::system(),
mode_override: None,
left: LeftPanel::AllTools,
last_right: RightPanel::Comments,
notice_inset: 0.0,
toolbar_tools_open: true,
window_narrow: false,
default_tools_width: crate::panels::side_panels::TOOLS_WIDTH,
right_before_read: None,
comments_panel_closed: false,
right_panel_closed: false,
@@ -316,6 +321,7 @@ impl PdfCraftApp {
portfolio_seen: None,
portfolio_panel: None,
quick_tool: QuickTool::Select,
text_tool_up: None,
full_screen_tool: None,
comment_prefs: Default::default(),
recent_colours: Default::default(),
@@ -326,6 +332,7 @@ impl PdfCraftApp {
suite: craft::theme_store::SuiteClient::memory(),
reading_colors: Default::default(),
show_page_edge_shadows: true,
show_rulers: false,
scroll_speed: scroll_speed::ScrollSpeed::default(),
invert_middle_drag: false,
animation_effects: craft::theme::MotionChoice::System,
@@ -373,7 +380,13 @@ impl PdfCraftApp {
reload_changed_files: true,
update_check_at_start: true,
at_exit: None,
#[cfg(target_os = "windows")]
save_window_placement: None,
#[cfg(target_os = "windows")]
window_frame: None,
startup_time: None,
#[cfg(target_os = "macos")]
metal_fullscreen: MetalFullscreen::default(),
show_secured_notice: true,
text_links: true,
always_default_view: false,
@@ -410,6 +423,7 @@ impl PdfCraftApp {
password_prompt: None,
unlock_prompt: None,
screen_mode: Default::default(),
host_save: None,
host_dirty: None,
os_events: None,
close_guard: None,
@@ -452,6 +466,7 @@ impl PdfCraftApp {
cert_viewer: None,
space_audit: Default::default(),
space_audit_of: None,
space_audit_pending: Default::default(),
combine_draft: Vec::new(),
combine_conflicts: Default::default(),
combine_tab: Default::default(),
@@ -523,6 +538,7 @@ impl PdfCraftApp {
startup_superseded: false,
startup_files: Vec::new(),
community_card_closed: false,
embedded: false,
pending_link: None,
pending_window: None,
pending_remote_link: None,
@@ -587,11 +603,16 @@ impl PdfCraftApp {
.mode(self.theme_preference)
.density(craft::theme::Size::Comfortable)
.direction(direction)
.scale(Scale::new(crate::ui_scale::zoom(self.ui_scale, system, native)));
.scale(Scale::new(crate::ui_scale::zoom(self.ui_scale, system, native)))
// Wheel notches scale through the canvas's wheel line; touchpad points through this gain (#1904).
.wheel_speed(WheelSpeed::new(1.0, self.scroll_speed.touchpad_gain()));
if let Ok(theme) = craft::theme::ThemeId::parse("craft.graphite") {
root.set_theme(theme);
}
root.sizes = Arc::clone(sizes);
// Windows caption buttons and the free title band keep the normal arrow while remaining draggable.
#[cfg(windows)]
root.values.set(craft::ui::contract::MoveBandCursor::Arrow);
// Every parameter dialog lays out as a document dialog: inline captions, shaded groups, buttons across the foot.
root.values.set(craft::ui::patterns::form_dialogs::DialogLayout(craft::ui::patterns::form_dialogs::ParamLayout::Document));
// PdfCraft's looks, opt-in over the framework's defaults: the filled dropdown triangle, shrinking document
@@ -741,6 +762,10 @@ impl eframe::App for PdfCraftApp {
/// The preferences go to the settings store, which writes them when they changed.
fn save(&mut self, _storage: &mut dyn eframe::Storage) {
#[cfg(target_os = "windows")]
if let Some(save) = &self.save_window_placement {
save(_storage);
}
self.save_settings();
}
@@ -771,6 +796,8 @@ impl eframe::App for PdfCraftApp {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
#[cfg(not(target_arch = "wasm32"))]
embed::before_ui(ui.ctx(), frame);
#[cfg(target_os = "macos")]
self.metal_fullscreen.apply(ui.ctx(), frame);
#[cfg(target_arch = "wasm32")]
let _ = frame;
self.begin_ui();
@@ -863,6 +890,7 @@ impl PdfCraftApp {
view.cancel_pointer_gestures(ctx);
}
}
self.apply_text_of_put_down_tool(ctx);
self.process_pending_edits(ctx);
self.poll_export();
self.auto_ocr_scanned_page(ctx);
+62 -2
View File
@@ -135,12 +135,20 @@ impl PdfCraftApp {
self.text_copies.reprioritize(|doc, priority| (!copied && open(views, doc)).then_some(priority));
}
/// Copy on the canvas: with objects selected in Edit a PDF, those; with no text selected, the
/// selected comments with their replies; else the text; else the selected image.
/// Copy on the canvas: while preparing a form, the selected fields; with objects selected in
/// Edit a PDF, those; with no text selected, the selected comments with their replies; else
/// the text; else the selected image.
pub(crate) fn copy_from_canvas(&mut self, ctx: &egui::Context, i: usize) -> bool {
if self.views.get(i).is_some_and(|v| v.session.forms.focus.is_some() || v.organize) {
return false;
}
if self.is_preparing()
&& let Some(names) = self.copy_selected_fields(i)
{
// A whole-document text copy still running would put its older text over the names.
self.cancel_text_copies();
return self.put_text(&names);
}
// Objects selected together in Edit a PDF take the copy.
if self.quick_tool == QuickTool::EditText && self.views.get(i).is_some_and(|v| v.session.objects.count() > 0) {
return self.copy_objects(ctx, i, false);
@@ -160,6 +168,13 @@ impl PdfCraftApp {
self.may_copy(id) && self.copy_page_image(sel.page, sel.index)
}
/// Prepare's Copy in view `i`: its selected fields, with their widgets' objects.
fn copy_selected_fields(&mut self, i: usize) -> Option<String> {
let view = self.views.get_mut(i)?;
let form = self.session.get(view.id).map(|d| d.form.clone()).unwrap_or_default();
crate::prepare::copy_selected(&mut view.session.prepare, &form)
}
/// Cut on the canvas: objects selected in Edit a PDF, else the selected image.
pub(crate) fn cut_from_canvas(&mut self, ctx: &egui::Context, i: usize) -> bool {
if self.views.get(i).is_some_and(|v| v.session.forms.focus.is_some() || v.organize) {
@@ -218,6 +233,11 @@ impl PdfCraftApp {
if !received && self.clipboard.has(&[TEXT]) { self.clipboard.read_text().ok().flatten().filter(|t| !t.is_empty()) } else { None }
});
let image = delivered_image.or_else(|| if received { None } else { self.clipboard.read_image().ok().flatten() });
// Prepare a form keeps Paste for its fields: anything else on the clipboard pastes nothing.
if self.is_preparing() {
self.paste_fields(i, text.as_deref());
return;
}
if self.quick_tool == QuickTool::EditText && self.object_clipboard.is_some() && self.pastes_objects(text.as_deref(), image.as_ref()) {
self.paste_objects(ctx, i);
return;
@@ -247,6 +267,19 @@ impl PdfCraftApp {
self.paste_image(ctx, page, None);
}
/// Paste while preparing a form: the fields Copy took, when the clipboard still holds their
/// copy (`text`), they still exist, and the document may be changed.
fn paste_fields(&mut self, i: usize, text: Option<&str>) {
let Some(view) = self.views.get_mut(i) else { return };
let Some(doc) = self.session.get(view.id) else { return };
if !crate::prepare::pastes_fields(&view.session.prepare, text) || !doc.allows_modification() {
return;
}
if let Some(edit) = crate::prepare::paste_copied(view, &doc.form, &doc.info.pages) {
view.session.pending_edit = Some(edit);
}
}
/// Copy in Edit a PDF with objects selected together: copy them for Paste in any open
/// document, and put their text (or else their first picture) on the system clipboard for
/// other applications. A cut then deletes them, as one undo step.
@@ -579,4 +612,31 @@ mod review_tests {
assert!(app.comment_clipboard.is_none(), "the comment was not copied");
assert!(writes.lock().unwrap().is_empty(), "no comment payload reached the clipboard");
}
/// Review of #8604: Copy of the selected fields while a whole-document text copy is still
/// running drops that copy, so its older text can't land over the field names later.
#[test]
fn copying_fields_drops_a_running_text_copy() {
let ctx = &egui::Context::default();
let (mut app, writes) = app_with_clipboard();
let jobs = Arc::new(ManualJobs::new());
app.text_copies = JobQueue::new(jobs.clone(), Wake::none(), QueueOptions::default());
let field = pdfcraft_engine::Edit::AddField {
page: 0,
rect: [20.0, 20.0, 50.0, 50.0],
kind: pdfcraft_engine::NewField::CheckBox,
name: Some("consent".into()),
};
assert!(app.apply_edit(ctx, field));
let id = app.views[0].id;
app.views[0].session.texts.clear();
app.views[0].session.all_text = true;
assert!(app.copy_selected_text(0));
assert!(app.text_copies.contains(&id), "the document's text copy is running");
assert!(app.execute(ctx, "form.prepare"));
app.views[0].session.prepare.selected = Some(("consent".into(), 0));
assert!(app.copy_from_canvas(ctx, 0));
assert!(!app.text_copies.contains(&id), "the older text copy was dropped");
assert_eq!(writes.lock().unwrap().len(), 1, "the field names reached the clipboard");
}
}
+19
View File
@@ -143,6 +143,25 @@ impl PdfCraftApp {
}
}
/// Applies the text box open on the page (added text, a paragraph in the editor) once Add
/// text or Edit text is put down, however that happened: a toolbar button, a key, a menu, a
/// command. Left open, the document stayed unmodified, with no undo step, until a click on
/// the page or a save applied it. Text that can't be applied keeps its tool up, so it stays
/// shown, as Undo leaves it. Read mode keeps every tool down (`enter_mode`), so there the
/// text and its warning are kept without the tool.
pub(crate) fn apply_text_of_put_down_tool(&mut self, ctx: &egui::Context) {
let up = matches!(self.quick_tool, QuickTool::EditText | QuickTool::AddText).then_some(self.quick_tool);
let Some(was) = std::mem::replace(&mut self.text_tool_up, up) else { return };
if up.is_some() {
return;
}
let Some((i, id)) = self.active_ids() else { return };
if !self.close_text_editors(ctx, i, id) && self.mode != Mode::Read {
self.quick_tool = was;
self.text_tool_up = Some(was);
}
}
/// Switches workspace because the user chose to (mode bar, Read mode command). Entering Read
/// mode closes the right panel, as Acrobat's Read mode hides its panes, and leaving it reopens
/// that panel. The rail stays in Read mode, and its buttons open panels there too (#932).
+22
View File
@@ -45,6 +45,13 @@ impl PdfCraftApp {
("show_page_edge_shadows", _) => {
self.show_page_edge_shadows = value.parse::<bool>().map_err(|_| "show_page_edge_shadows must be true or false")?;
}
("rulers", _) => {
self.show_rulers = match value {
"on" => true,
"off" => false,
_ => return Err("rulers must be on or off".into()),
};
}
("update_check_at_start", _) => {
self.update_check_at_start = value.parse::<bool>().map_err(|_| "update_check_at_start must be true or false")?;
}
@@ -328,6 +335,13 @@ impl PdfCraftApp {
}
}
("notice", Some(v)) => v.notice_dismissed = value == "off",
("embedded", _) => {
self.embedded = match value {
"true" | "on" | "1" => true,
"false" | "off" | "0" => false,
_ => return Err("embedded must be true or false".into()),
};
}
("quick", _) => {
// `--quick select|hand|note|freetext|highlight|underline|strikeout|ink|line|arrow|square|circle`
self.quick_tool = match value {
@@ -392,6 +406,14 @@ impl PdfCraftApp {
_ => return Err("hide-empty-highlight-hover must be true or false".into()),
};
}
("page-boxes", _) => {
self.show_page_boxes = match value {
"on" => true,
"off" => false,
_ => return Err("page-boxes must be on or off".into()),
};
self.sync_open_show_page_boxes();
}
("text-links", _) => {
self.text_links = match value {
"true" => true,
+6
View File
@@ -9,6 +9,12 @@ impl PdfCraftApp {
/// command states and host. eframe calls the hook once per frame, before the first pass, so
/// a second pass of the same frame runs on what this call set and fires nothing twice.
pub(super) fn prepare_raw_input(&mut self, ctx: &egui::Context, _raw: &mut egui::RawInput) {
// The toolkit gives the undecorated window its caption back whenever it changes the window's flags (maximize,
// restore, ...): take it off again before the frame is laid out.
#[cfg(target_os = "windows")]
if let Some(window_frame) = self.window_frame.as_mut() {
window_frame();
}
// Preferences and the control channel only change `title_bar_choice`; the window follows on the
// next frame. Asking the policy again when nothing changed would re-read the platform each frame.
if self.applied_title_bar != Some(self.title_bar_choice) {
@@ -0,0 +1,63 @@
//! Drawable queue depth for the root AppKit window.
#[derive(Default)]
pub(crate) struct MetalFullscreen {
fullscreen: bool,
raised_latency: bool,
}
impl MetalFullscreen {
#[cfg(target_os = "macos")]
pub(super) fn apply(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
let Some(fullscreen) = ctx.input(|i| i.viewport().fullscreen) else { return };
if self.fullscreen == fullscreen {
return;
}
let Some(mut surface) = frame.wgpu_surface_config() else {
self.fullscreen = fullscreen;
return;
};
let latency = surface.desired_maximum_frame_latency;
if let Some(depth) = self.next_latency(Some(fullscreen), latency, || {
frame.wgpu_render_state().is_some_and(|state| state.adapter.get_info().backend == eframe::wgpu::Backend::Metal)
}) {
surface.desired_maximum_frame_latency = Some(depth);
frame.set_wgpu_surface_config(surface);
}
}
fn next_latency(&mut self, fullscreen: Option<bool>, latency: Option<u32>, is_metal: impl FnOnce() -> bool) -> Option<u32> {
let fullscreen = fullscreen?;
if self.fullscreen == fullscreen {
return None;
}
self.fullscreen = fullscreen;
if fullscreen {
// With two CAMetalLayer drawables, nextDrawable can wait for the compositor
// to return the previous frame. Allow a third while in native fullscreen.
self.raised_latency = latency == Some(1) && is_metal();
self.raised_latency.then_some(2)
} else {
(std::mem::take(&mut self.raised_latency) && latency == Some(2)).then_some(1)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn native_fullscreen_uses_a_third_metal_drawable_then_restores_windowed_latency() {
let mut state = MetalFullscreen::default();
assert_eq!(state.next_latency(Some(false), Some(1), || true), None);
assert_eq!(state.next_latency(Some(true), Some(1), || true), Some(2));
assert_eq!(state.next_latency(None, Some(2), || true), None);
assert_eq!(state.next_latency(Some(true), Some(2), || true), None);
assert_eq!(state.next_latency(Some(false), Some(2), || true), Some(1));
for (latency, metal) in [(Some(2), true), (None, true), (Some(1), false)] {
assert_eq!(state.next_latency(Some(true), latency, || metal), None);
assert_eq!(state.next_latency(Some(false), latency, || metal), None);
}
}
}
+8
View File
@@ -179,6 +179,7 @@ impl PdfCraftApp {
full_screen_fill: Some(self.full_screen_fill),
full_screen_escape_exits: Some(self.full_screen_escape_exits),
units: Some(self.units),
show_page_boxes: Some(self.show_page_boxes),
always_default_view: Some(self.always_default_view),
show_form_field_reminder: Some(self.show_form_field_reminder),
highlight_fields: Some(self.highlight_fields),
@@ -192,6 +193,7 @@ impl PdfCraftApp {
fill_text_size: Some(self.fill_text_size),
fill_text_color: Some(self.fill_text_color),
show_page_edge_shadows: Some(self.show_page_edge_shadows),
show_rulers: Some(self.show_rulers),
fill_text_border: Some(self.fill_text_default.width),
fill_text_border_shape: Some(self.fill_text_default.shape.name().to_string()),
// Absent is "the text's colour": TOML has no null.
@@ -477,6 +479,9 @@ impl PdfCraftApp {
if let Some(units) = b.units {
self.units = units;
}
if let Some(on) = b.show_page_boxes {
self.show_page_boxes = on;
}
if let Some(on) = b.always_default_view {
self.always_default_view = on;
}
@@ -516,6 +521,9 @@ impl PdfCraftApp {
if let Some(show) = b.show_page_edge_shadows {
self.show_page_edge_shadows = show;
}
if let Some(show) = b.show_rulers {
self.show_rulers = show;
}
if let Some(width) = b.fill_text_border.and_then(fill_sign::valid_text_border) {
self.fill_text_default.width = width;
}
+4
View File
@@ -84,6 +84,7 @@ pub struct Behavior {
/// Esc leaves full screen (off leaves it to ⌘L / Ctrl+L only).
pub full_screen_escape_exits: Option<bool>,
pub units: Option<crate::units::Unit>,
pub show_page_boxes: Option<bool>,
pub always_default_view: Option<bool>,
pub show_form_field_reminder: Option<bool>,
pub highlight_fields: Option<bool>,
@@ -98,6 +99,7 @@ pub struct Behavior {
pub fill_text_size: Option<f64>,
pub fill_text_color: Option<[f64; 3]>,
pub show_page_edge_shadows: Option<bool>,
pub show_rulers: Option<bool>,
pub fill_text_border: Option<f64>,
pub fill_text_border_shape: Option<String>,
/// Absent is "the text's colour": TOML has no null.
@@ -661,6 +663,7 @@ pub fn import_json(text: &str) -> (PdfCraftSettings, Vec<SectionError>) {
full_screen_fill: r.bool("full_screen_fill"),
full_screen_escape_exits: r.bool("full_screen_escape_exits"),
units: r.typed("units"),
show_page_boxes: r.bool("show_page_boxes"),
always_default_view: r.bool("always_default_view"),
show_form_field_reminder: r.bool("show_form_field_reminder"),
highlight_fields: r.bool("highlight_fields"),
@@ -674,6 +677,7 @@ pub fn import_json(text: &str) -> (PdfCraftSettings, Vec<SectionError>) {
fill_text_size: r.f64("fill_text_size"),
fill_text_color: r.typed("fill_text_color"),
show_page_edge_shadows: r.bool("show_page_edge_shadows"),
show_rulers: r.bool("show_rulers"),
fill_text_border: r.f64("fill_text_border"),
fill_text_border_shape: r.string("fill_text_border_shape"),
fill_text_border_color: r.typed("fill_text_border_color"),
+83 -5
View File
@@ -45,6 +45,7 @@ pub(crate) mod page_parts;
pub(crate) mod page_tools;
pub(crate) mod pictures;
mod presenter;
pub mod rulers;
pub mod scroll_speed;
mod selection;
pub(super) mod signature_drag;
@@ -165,6 +166,7 @@ pub struct DocView {
pub from_attachment: Option<(DocId, String)>,
/// What the page view shows: the page, display, zoom, fit, rotation and scroll offset.
pub view: PageViewState,
shown_boxes: crate::shown_boxes::ShownBoxes,
/// Everything the page body touches: the tools' and editors' state, the text selection, the pages placed.
pub session: PageSession,
/// The momentary tools (Space for the Hand, with Cmd or Alt the Zoom), held across passes by the tool host.
@@ -606,6 +608,7 @@ impl DocView {
id,
from_attachment: None,
view: PageViewState::from_defaults(&defaults),
shown_boxes: Default::default(),
session: PageSession::new(info, highlight_fields),
momentary: Momentary::new(NavigationOptions::default()),
momentary_options: NavigationOptions::default(),
@@ -931,6 +934,7 @@ struct PageBodyCx<'a> {
form: &'a Arc<Vec<pdfcraft_engine::FormField>>,
today: (i64, u32, u32),
units: crate::units::Unit,
shown_boxes: &'a [[Option<[f64; 4]>; 3]],
find_marks: &'a [TextMark],
table_preview: Option<&'a crate::field_table_ui::Preview>,
}
@@ -950,6 +954,8 @@ struct BodyOut {
shown: Option<CanvasView>,
/// The Crop tool's double-click: open Set Page Boxes on that page.
open_boxes: bool,
/// The Crop tool's drawn rectangle: its page and user-space rectangle, for Set Page Boxes to open seeded from.
drawn_crop: Option<(usize, [f64; 4])>,
/// Fill & Sign asked for a signature (`false`) or initials (`true`) before it can place one.
open_signature: Option<bool>,
/// Where the canvas menu opens: a secondary press the tool did not take, or the Menu key.
@@ -1394,6 +1400,8 @@ fn page_before(ui: &mut egui::Ui, body: &PageBody<'_>, callbacks: &mut PageCallb
session.pending_page = Some((page, None));
out.open_boxes = true;
}
// A drawn rectangle opens it for the page it was drawn on, which need not be current (#5695).
out.drawn_crop = finish.drawn_crop;
out.turn = finish.turn;
out.open_signature = finish.open_signature;
let mut outcome = session.prepare.take_outcome();
@@ -1427,6 +1435,9 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, callbacks: &mut PageCallbac
(placed.page, xf, overlay.tabs)
})
.collect();
for (page, xf, _) in &tabs {
crate::shown_boxes::paint_shown(ui.painter(), xf, cx.info, *page, cx.shown_boxes);
}
// 5. The overlays.
page_overlays::PageBackdrop::new(
body.pages,
@@ -1578,7 +1589,11 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, callbacks: &mut PageCallbac
};
marks.show_at(ui, body.rect);
image_pick::drop_stale(cx.doc, session);
image_pick::resolve_pending(session, cx.geometry(body), cx.doc, cx.info, cx.tools.host.jobs_shared(), cx.tools.wake);
// Until release the press may become a text drag. Picking the scan underneath now would erase
// the text selection's anchor before the first drag event can extend it.
if !ui.input(|i| i.pointer.primary_down()) {
image_pick::resolve_pending(session, cx.geometry(body), cx.doc, cx.info, cx.tools.host.jobs_shared(), cx.tools.wake);
}
image_pick::show_picked(ui, body, session, cx.rotation, cx.info);
if let Some(at) = cx.present_at {
let (now, pointer) = ui.input(|i| (i.time, i.pointer.hover_pos()));
@@ -1714,6 +1729,8 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu
}
// The room under the notice bars, inside the rect the caller gave.
let rect = rect.intersect(ui.available_rect_before_wrap());
let (ruler_outer, rect) =
if app.show_rulers && !app.views[index].presenting() && !app.full_screen() { rulers::reserve(rect) } else { (None, rect) };
let preparing = app.is_preparing();
// Prepare a form ▸ Calculation order: the order's steps and links on the page.
@@ -1791,6 +1808,7 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu
_ => None,
};
let view_key = view.view_key();
let shown_boxes = if app.show_page_boxes { view.shown_boxes.get(doc) } else { Default::default() };
let DocView { view: state, session, momentary, revisions, reports, page_sizes, .. } = &mut *view;
let tools = page_tools::PageToolCx {
doc,
@@ -1859,6 +1877,7 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu
form: &form,
today: app.session.today(),
units: app.units,
shown_boxes: &shown_boxes,
find_marks: &find_marks,
table_preview: table_preview.as_ref(),
};
@@ -1869,17 +1888,28 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu
let out = ui
.push_id(view_key, |ui| {
PageView::new(tl!("Pages"), &source, state, DataColor::new(paper))
.floating_scrollbars()
.navigation(navigation)
.border(border)
.pasteboard(surround)
.keep(&keep)
.pixel_aligned_pages()
.turn_per_line_event(cfg!(target_os = "windows"))
// Production's Go To: the page gap above the page's top.
.go_to_place(GoToPlace::GapAbove)
.fill_screen(fill_screen)
.show_at_with(ui, rect, &mut callbacks, page_before, page_body)
})
.inner;
// A primary click on the unclaimed pasteboard gives the reader its keyboard back. In
// particular, a focused zoom editor must not keep the arrow keys after the reader clicks
// beside a page. Canvas controls and page parts handle their own focus and are excluded.
// An open form editor has its own focus handoff; leave it to that path.
if view.session.forms.focus.is_none()
&& let Some(pos) = out.canvas.click_at()
&& !out.pages.iter().any(|page| page.rect.contains(pos))
{
focus::request(ui.ctx(), FocusTarget::Id(out.canvas.response.id));
}
if view.view.continuous
&& let Some(page) = body_out.pressed_page
{
@@ -1944,6 +1974,22 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu
view.viewport = rect;
view.canvas = body_out.shown;
view.middle_scrolling = out.canvas.auto_scrolling;
if let Some(outer) = ruler_outer {
let pointer =
if unobstructed && ui.rect_contains_pointer(rect) { ui.input(|i| i.pointer.hover_pos()).filter(|p| rect.contains(*p)) } else { None };
rulers::show(
ui,
outer,
rect,
&view.session.placed,
&view.page_sizes,
view.view.current,
view.view.rotation,
view.view.zoom,
app.units,
pointer,
);
}
// Addresses written as plain text are found once per text layer that has arrived; the link parts read them.
if app.text_links {
for page in out.visible.clone() {
@@ -2081,6 +2127,7 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu
link_open,
open_table: prepare.table,
open_boxes: body_out.open_boxes,
drawn_crop: body_out.drawn_crop,
open_signature: body_out.open_signature,
form,
generation: app.session.get(doc_id).map_or(0, |d| d.edit_generation()),
@@ -2105,12 +2152,37 @@ struct FrameRequests {
open_table: Option<(usize, [f64; 4])>,
/// The Crop tool's double-click: open Set Page Boxes on the current page.
open_boxes: bool,
/// The Crop tool's drawn rectangle: open Set Page Boxes seeded from it, for its page.
drawn_crop: Option<(usize, [f64; 4])>,
/// Fill & Sign needs a signature (`false`) or initials (`true`) first.
open_signature: Option<bool>,
form: Arc<Vec<pdfcraft_engine::FormField>>,
generation: u64,
}
/// Opens what a field's menu item picked in view `index`; Properties is handled with the other property requests.
fn open_field_menu_pick(
app: &mut PdfCraftApp,
ctx: &egui::Context,
index: usize,
pick: FieldMenu,
form: &[pdfcraft_engine::FormField],
generation: u64,
) {
match pick {
FieldMenu::Duplicate(name) => crate::dialogs::duplicate_field::open(app, ctx, name),
FieldMenu::Copies(name, widget) => {
let doc = app.views[index].id;
// As for a drawn table: the window lasts while the form is prepared.
if crate::field_table_ui::open_copies(app, doc, name, widget, form, generation) {
app.left = crate::LeftPanel::Tool("form");
app.reveal_tools();
}
}
FieldMenu::Properties => {}
}
}
/// Opens the dialogs and runs the app commands the frame asked for.
#[allow(clippy::cognitive_complexity)]
fn apply_frame_requests(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize, requests: FrameRequests) {
@@ -2126,6 +2198,7 @@ fn apply_frame_requests(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize
link_open,
open_table,
open_boxes,
drawn_crop,
open_signature,
form,
generation,
@@ -2149,8 +2222,8 @@ fn apply_frame_requests(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize
if let Some((name, w)) = field_props {
crate::prepare::dialog::open(app, &name, w, crate::prepare::FieldTab::General);
}
if let Some(FieldMenu::Duplicate(name)) = field_menu {
crate::dialogs::duplicate_field::open(app, ctx, name);
if let Some(pick) = field_menu {
open_field_menu_pick(app, ctx, index, pick, &form, generation);
}
if let Some((page, rect)) = app.views[index].session.links.open_new.take() {
app.open_link_props(page, Some(rect), None);
@@ -2309,7 +2382,12 @@ fn apply_frame_requests(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize
// `signature::open(self, initials, editing)`, forms AP-4).
crate::dialogs::signature::open(app, initials, false);
}
if open_boxes {
if let Some((page, rect)) = drawn_crop {
// A drawn rectangle: Set Page Boxes with its margins for that page of this document as it is now, to adjust
// before OK crops it (#5695).
let doc = app.views[index].id;
app.open_page_boxes_for_rect(ctx, doc, page, rect);
} else if open_boxes {
// Set Page Boxes on the current page, with no draft written here.
app.open_page_boxes(ctx, true);
}
+5 -8
View File
@@ -21,14 +21,11 @@ pub(super) fn page_size_hint(ui: &mut egui::Ui, body: &PageBody<'_>, page: &pdfc
return;
}
let text = units.size(f64::from(page.width), f64::from(page.height));
// PLAN: a card notice is the framework's floating label with no interaction; its own surface padding is the inset.
// Shrink-wrapped to its text, a little in from the corner, as production's pill sits.
let font = egui::TextStyle::Body.resolve(ui.style());
let wide = ui.painter().layout_no_wrap(text.to_string(), font, egui::Color32::WHITE).size().x + 40.0;
let corner = egui::Rect::from_min_max(
egui::pos2(body.rect.min.x + 10.0, body.rect.min.y),
egui::pos2(body.rect.min.x + 10.0 + wide, body.rect.max.y - 10.0),
);
// The card measures its own text and surface padding in the active theme. Give it the
// available document width instead of guessing that width with egui's unrelated Body font.
let left = (body.rect.min.x + 10.0).min(body.rect.max.x);
let right = (body.rect.max.x - 10.0).max(left);
let corner = egui::Rect::from_min_max(egui::pos2(left, body.rect.min.y), egui::pos2(right, (body.rect.max.y - 10.0).max(body.rect.min.y)));
let builder = egui::UiBuilder::new().max_rect(corner).layout(egui::Layout::bottom_up(egui::Align::Min)).sense(egui::Sense::hover());
ui.scope_builder(builder, |ui| {
Bar::new(Tone::Neutral, text).layout(NoticeLayout::Card).icon(NoticeIcon::None).show(ui);
+7 -7
View File
@@ -1,12 +1,12 @@
//! The Crop tool (Acrobat: Edit ▸ Crop pages): drag a rectangle on a page to crop it to that
//! rectangle; double-click a page to open Set Page Boxes for it.
//! The Crop tool (Acrobat: Edit ▸ Crop pages): drag a rectangle on a page and Set Page Boxes
//! opens with its margins taken from that rectangle, to adjust before anything is cropped
//! (#5695); double-click a page to open Set Page Boxes for it as it is.
use craft::behavior::{CancelReason, Cursor, CursorIcon};
use craft::pages::ui::PlacedPage;
use craft::ui::canvas::{CanvasTool, CropShield, ToolAction, ToolContext, ToolPath, ToolPointer, paint_outside};
use craft::ui::primitives::Draw;
use craft::ui::style::DataColor;
use pdfcraft_engine::{BoxSpec, Edit, PageBox};
use pdfcraft_render::DocInfo;
use super::page_box_drag::{PageBoxDrag, page_under};
@@ -22,13 +22,13 @@ pub(crate) struct CropResult {
pub(crate) view_rect: [f32; 4],
}
/// The edit that crops `done.page` to its rectangle, in user space.
pub(crate) fn crop_edit(info: &DocInfo, done: &CropResult) -> Option<Edit> {
/// The page `done` was drawn on and its rectangle there, in user space: what Set Page Boxes opens
/// seeded from (#5695). Nothing is cropped until it is confirmed.
pub(crate) fn crop_rect(info: &DocInfo, done: &CropResult) -> Option<(usize, [f64; 4])> {
let page = info.pages.get(done.page)?;
let [x0, y0, x1, y1] = done.view_rect;
let (a, b) = (to_user(page, x0, y0), to_user(page, x1, y1));
let rect = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])];
Some(Edit::SetPageBox { pages: vec![done.page], which: PageBox::Crop, spec: BoxSpec::Rect(rect) })
Some((done.page, [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]))
}
fn to_user(page: &pdfcraft_render::PageInfo, vx: f32, vy: f32) -> [f64; 2] {
+17
View File
@@ -55,6 +55,8 @@ pub(crate) struct PageMenuPerms {
pub(crate) enum FieldMenu {
Properties,
Duplicate(String),
/// Copy into Grid: the field and the widget the press was on.
Copies(String, usize),
}
/// What a row of the default menu does when picked.
@@ -265,6 +267,21 @@ fn field_rows(
if MenuItem::new(tl!("Properties…").to_string()).show(ui).ran {
pick.field = Some(FieldMenu::Properties);
}
// One field at a time, of a kind a grid can copy; a disabled row says which it is not.
let why_not = if !view.session.prepare.also.is_empty() {
Some(tl!("Select one field to copy it into a grid"))
} else if !form.iter().find(|f| f.name == name).is_some_and(|f| pdfcraft_engine::field_table::copyable(f, widget)) {
Some(tl!("Only text fields and check boxes with one export value can be copied into a grid"))
} else {
None
};
let mut copies = MenuItem::new(tl!("Copy into Grid…").to_string()).enabled(can_modify && why_not.is_none());
if let Some(why) = why_not {
copies = copies.tooltip(craft::ui::contract::TooltipSpec::new(why).disabled_text(why));
}
if copies.show(ui).ran {
pick.field = Some(FieldMenu::Copies(name.clone(), widget));
}
if MenuItem::new(tl!("Duplicate…").to_string()).enabled(can_modify).show(ui).ran {
pick.field = Some(FieldMenu::Duplicate(name));
}
+7 -7
View File
@@ -177,14 +177,16 @@ pub(crate) struct PageTool<'a> {
/// session by [`apply`](Self::apply).
#[derive(Default)]
pub(crate) struct ToolFinish {
/// The running tool is done and the app goes back to the Select tool (a stamp placed, a crop committed).
/// The running tool is done and the app goes back to the Select tool (a stamp placed, a crop rectangle drawn).
pub(crate) back_to_select: bool,
/// A Snapshot area drawn: (page, view-space rect).
pub(crate) snapshot: Option<(usize, [f32; 4])>,
/// The Crop tool's double click: open Set Page Boxes on that page.
pub(crate) open_boxes: Option<usize>,
/// The Crop tool's drawn rectangle, which the page body turns into the crop edit.
pub(crate) crop: Option<CropResult>,
/// The Crop tool's drawn rectangle, as [`apply`](Self::apply) leaves it: its page and the rectangle in that page's
/// user space. Set Page Boxes opens seeded from it; nothing is cropped before OK (#5695).
pub(crate) drawn_crop: Option<(usize, [f64; 4])>,
crop: Option<CropResult>,
/// Fill & Sign asked for a signature (`false`) or initials (`true`) before it can place one.
pub(crate) open_signature: Option<bool>,
/// Fill & Sign refused a click, and why.
@@ -512,10 +514,8 @@ impl ToolFinish {
if let Some(edit) = self.edit.take() {
session.pending_edit = Some(edit);
}
if let Some(done) = self.crop.take()
&& let Some(edit) = super::crop::crop_edit(cx.info, &done)
{
session.pending_edit = Some(edit);
if let Some(done) = self.crop.take() {
self.drawn_crop = super::crop::crop_rect(cx.info, &done);
}
if let Some(page) = self.camera_page.take()
&& let Some(placed) = cx.pages.iter().find(|placed| placed.page == page)
+20 -2
View File
@@ -125,6 +125,8 @@ impl RenderReports {
/// One document's pages as a [`PageSource`] and the source of print previews. It owns what a render job reads, so
/// jobs outlive the pass that made them.
pub struct DocPages<'a> {
id: DocId,
generation: u64,
info: Option<&'a DocInfo>,
bytes: Arc<Vec<u8>>,
config: RenderConfig,
@@ -138,6 +140,8 @@ impl<'a> DocPages<'a> {
pub fn new(session: &'a Session, doc: DocId) -> Self {
let document = session.get(doc);
Self {
id: doc,
generation: document.map_or(0, |doc| doc.edit_generation()),
info: document.map(|d| &d.info),
bytes: document.map(|d| d.display.clone()).unwrap_or_default(),
config: session.render_config(doc).unwrap_or_default(),
@@ -169,9 +173,9 @@ impl<'a> DocPages<'a> {
}
fn revision_of(&self, page: usize, request: &ThumbRequest, print: Option<bool>) -> Revision {
let generation = self.revisions.map_or((0, 0), |r| r.of(page));
let generation = self.revisions.map_or((self.generation, 0), |r| r.of(page));
let region = request.region.map(|r| [r.min.x.to_bits(), r.min.y.to_bits(), r.max.x.to_bits(), r.max.y.to_bits()]);
Revision::of(&(generation, request.side, region, self.rotation, print))
Revision::of(&(self.id, generation, request.side, region, self.rotation, print))
}
/// The job making `page` at `request`; `print` is `Some(grayscale)` for a print preview.
@@ -343,6 +347,20 @@ mod tests {
panic!("the pictures never settled");
}
#[test]
fn organize_thumbnails_change_revision_on_rotation_and_document_switch() {
let mut session = Session::new();
let blank = session.create_blank(200.0, 300.0, 2).expect("two blank pages");
let first = session.open_new("first.pdf", blank.clone()).expect("first document");
let second = session.open_new("second.pdf", blank).expect("second document");
let request = ThumbRequest::for_cell(96.0, 1.0);
let revision = |session: &Session, id| DocPages::new(session, id).revision(&0usize, &request);
let initial = revision(&session, first);
assert_ne!(initial, revision(&session, second));
session.apply(first, pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }).expect("rotate first page");
assert_ne!(initial, revision(&session, first));
}
/// A page edit must queue a render for that page only and a document change one for every page: a wrong bump
/// leaves a stale picture on screen with no error.
#[test]
+541
View File
@@ -0,0 +1,541 @@
//! Horizontal and vertical rulers along the top and left edges of the document area (`view.rulers`).
//!
//! The rulers reserve a thin strip along the top and left of the page area so pages are never covered.
//! Origin `(0, 0)` is the top-left corner of the page under the pointer (or the current page when the
//! pointer is elsewhere), in the page's displayed orientation. Units follow the app's measurement-units
//! preference (`crate::units::Unit`). Ticks use nice 1 / 2 / 5 × 10^n intervals chosen from the active
//! zoom so labels never overlap, and are hard-capped per frame so degenerate inputs cannot stall rendering.
use craft::pages::ui::PlacedPage;
use craft::ui::runtime::env::Env;
use egui::{Align2, Color32, CornerRadius, FontId, Pos2, Rect, Stroke, pos2};
use crate::units::Unit;
/// Thickness in logical points reserved for each ruler strip (and the corner unit square).
pub const RULER_THICKNESS: f32 = 20.0;
/// Minimum screen spacing in logical points between consecutive major tick labels.
pub const MIN_MAJOR_SPACING_PX: f64 = 56.0;
/// Maximum number of ticks (major + minor) emitted per ruler per frame.
pub const MAX_TICKS: usize = 512;
/// Minimum screen spacing in logical points between minor ticks before minor ticks are omitted.
const MIN_MINOR_SPACING_PX: f64 = 3.0;
/// Whether a tick is a major labelled tick, a half-way subdivision, or a regular minor tick.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TickKind {
Major,
Half,
Minor,
}
/// One positioned tick along a ruler axis.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tick {
/// Coordinate in logical screen points along the ruler's axis.
pub screen: f32,
/// Coordinate in the active measurement unit relative to the page origin.
pub value: f64,
pub kind: TickKind,
}
/// Reserves space for the top and left ruler strips inside `area`.
///
/// Returns `(Some(area), page_rect)` when `area` is finite and larger than [`RULER_THICKNESS`] on
/// both axes; otherwise returns `(None, area)` without producing an inverted rectangle.
pub fn reserve(area: Rect) -> (Option<Rect>, Rect) {
if !area.is_finite() || area.width() <= RULER_THICKNESS || area.height() <= RULER_THICKNESS {
return (None, area);
}
let page_rect = Rect::from_min_max(pos2(area.min.x + RULER_THICKNESS, area.min.y + RULER_THICKNESS), area.max);
(Some(area), page_rect)
}
/// Chooses a "nice" major interval (`1`, `2`, or `5` × `10^n`) and minor subdivision count
/// given `px_per_unit` (logical screen pixels per 1 unit) and `min_major_px` (minimum screen
/// pixels between adjacent major labels).
///
/// Returns `None` for non-finite or non-positive inputs, or if the resulting step underflows/overflows.
pub fn nice_interval(px_per_unit: f64, min_major_px: f64) -> Option<(f64, usize)> {
if !px_per_unit.is_finite() || px_per_unit <= 0.0 || !min_major_px.is_finite() || min_major_px <= 0.0 {
return None;
}
let target = min_major_px / px_per_unit;
if !target.is_finite() || target <= 0.0 {
return None;
}
let exp = target.log10().floor();
if !exp.is_finite() {
return None;
}
let base = 10.0_f64.powf(exp);
if !base.is_finite() || base <= 0.0 {
return None;
}
let frac = target / base;
let (step, subdivisions) = if frac <= 1.0 {
(1.0 * base, 10)
} else if frac <= 2.0 {
(2.0 * base, 4)
} else if frac <= 5.0 {
(5.0 * base, 5)
} else {
(10.0 * base, 10)
};
if !step.is_finite() || step <= 0.0 {
return None;
}
Some((step, subdivisions))
}
/// Chooses `(major_step, minor_subdivisions)` in `unit` for a scale of `px_per_pt` logical screen
/// pixels per PDF point.
pub fn ruler_step(px_per_pt: f64, unit: Unit) -> Option<(f64, usize)> {
if !px_per_pt.is_finite() || px_per_pt <= 0.0 {
return None;
}
let per_point = unit.per_point();
if !per_point.is_finite() || per_point <= 0.0 {
return None;
}
let px_per_unit = px_per_pt / per_point;
let (step, subdivisions) = nice_interval(px_per_unit, MIN_MAJOR_SPACING_PX)?;
// Eighths of an inch at 1 in major intervals match standard inch rulers.
let subdivisions = if unit == Unit::Inches && (step - 1.0).abs() < 1e-6 { 8 } else { subdivisions };
Some((step, subdivisions))
}
/// Computes major and minor ticks along one ruler axis over `[range_min, range_max]`.
///
/// `origin` is the screen coordinate of unit `0`, `px_per_unit` is logical screen pixels per unit,
/// `major_step` is the distance between major ticks in units, and `subdivisions` is the number of
/// equal segments between major ticks. At most `max_ticks` ticks are returned; degenerate or
/// non-finite inputs yield an empty list without panicking or looping.
pub fn compute_ticks(
range_min: f32,
range_max: f32,
origin: f32,
px_per_unit: f64,
major_step: f64,
subdivisions: usize,
max_ticks: usize,
) -> Vec<Tick> {
if !range_min.is_finite()
|| !range_max.is_finite()
|| range_max <= range_min
|| !origin.is_finite()
|| !px_per_unit.is_finite()
|| px_per_unit <= 0.0
|| !major_step.is_finite()
|| major_step <= 0.0
|| subdivisions == 0
|| max_ticks == 0
{
return Vec::new();
}
let r_min = f64::from(range_min);
let r_max = f64::from(range_max);
let orig = f64::from(origin);
let u_min = (r_min - orig) / px_per_unit;
let u_max = (r_max - orig) / px_per_unit;
if !u_min.is_finite() || !u_max.is_finite() {
return Vec::new();
}
let first_k = (u_min / major_step).floor();
let last_k = (u_max / major_step).ceil();
if !first_k.is_finite() || !last_k.is_finite() || first_k < -1e12 || last_k > 1e12 {
return Vec::new();
}
let k_start = first_k as i64;
let k_end = last_k as i64;
if k_end < k_start {
return Vec::new();
}
let major_px = major_step * px_per_unit;
let draw_minor = subdivisions > 1 && (major_px / (subdivisions as f64)) >= MIN_MINOR_SPACING_PX;
let sub_step = major_step / (subdivisions as f64);
let mut out = Vec::new();
// Bound major-loop iterations independently so pathological inputs can never spin.
let max_major_iters = max_ticks.saturating_add(2);
for (iters, k) in (k_start..=k_end).enumerate() {
if iters >= max_major_iters || out.len() >= max_ticks {
break;
}
let val = (k as f64) * major_step;
let screen = orig + val * px_per_unit;
if screen.is_finite() && screen >= r_min - 0.5 && screen <= r_max + 0.5 {
out.push(Tick { screen: screen as f32, value: val, kind: TickKind::Major });
}
if draw_minor {
for sub in 1..subdivisions {
if out.len() >= max_ticks {
break;
}
let sub_val = val + (sub as f64) * sub_step;
let sub_screen = orig + sub_val * px_per_unit;
if sub_screen.is_finite() && sub_screen >= r_min && sub_screen <= r_max {
let kind = if subdivisions.is_multiple_of(2) && sub * 2 == subdivisions { TickKind::Half } else { TickKind::Minor };
out.push(Tick { screen: sub_screen as f32, value: sub_val, kind });
}
}
}
}
out
}
/// Formats a major tick value concisely without trailing zeroes or `-0`.
pub fn format_label(value: f64, step: f64) -> String {
if !value.is_finite() {
return String::new();
}
let eps = if step.is_finite() && step > 0.0 { (step * 1e-6).max(1e-9) } else { 1e-9 };
if value.abs() < eps {
return "0".to_string();
}
let decimals = if step.is_finite() && step > 0.0 && step < 1.0 {
let d = (-step.log10().floor()).clamp(0.0, 4.0) as usize;
// e.g. step = 0.25 needs 2 decimals even though floor(log10(0.25)) == -1.
if ((step * 10.0_f64.powi(d as i32)).fract()).abs() > 1e-4 && d < 4 { d + 1 } else { d }
} else if (value - value.round()).abs() < 1e-4 {
0
} else {
2
};
let mut s = format!("{value:.decimals$}");
if decimals > 0 && s.contains('.') {
while s.ends_with('0') {
s.pop();
}
if s.ends_with('.') {
s.pop();
}
}
if s == "-0" { "0".to_string() } else { s }
}
/// Computes the displayed top-left origin and `(px_per_pt_x, px_per_pt_y)` for a placed page.
///
/// The page is measured in its displayed orientation (swapping width and height under 90°/270°
/// view rotation). Returns `None` if `page_rect` is zero-sized or non-finite, or if no positive
/// finite scale can be determined.
pub fn page_origin_and_scale(page_rect: Rect, page_size_pt: (f32, f32), view_rotation: u16, fallback_zoom: f64) -> Option<(Pos2, f64, f64)> {
if !page_rect.is_finite() || page_rect.width() <= 0.0 || page_rect.height() <= 0.0 {
return None;
}
let (disp_w, disp_h) = if view_rotation % 180 == 90 { (page_size_pt.1, page_size_pt.0) } else { page_size_pt };
if disp_w.is_finite() && disp_w > 0.0 && disp_h.is_finite() && disp_h > 0.0 {
let sx = f64::from(page_rect.width()) / f64::from(disp_w);
let sy = f64::from(page_rect.height()) / f64::from(disp_h);
if sx.is_finite() && sx > 0.0 && sy.is_finite() && sy > 0.0 {
return Some((page_rect.left_top(), sx, sy));
}
}
if fallback_zoom.is_finite() && fallback_zoom > 0.0 {
let s = fallback_zoom * f64::from(super::PT);
if s.is_finite() && s > 0.0 {
return Some((page_rect.left_top(), s, s));
}
}
None
}
/// Converts an RGBA theme token value (`craft::theme::Rgba.0`) into an `egui::Color32`.
fn token_color([r, g, b, a]: [u8; 4]) -> Color32 {
Color32::from_rgba_unmultiplied(r, g, b, a)
}
/// Draws the top and left rulers and corner unit indicator inside the reserved strips of `outer`
/// outside `page_rect`.
///
/// Never claims the cursor or takes presses. Draws short cursor marks on both rulers only while
/// `pointer` is over a placed page.
#[allow(clippy::too_many_arguments)]
pub(super) fn show(
ui: &egui::Ui,
outer: Rect,
page_rect: Rect,
placed: &[PlacedPage],
page_sizes: &[(f32, f32)],
current_page: usize,
view_rotation: u16,
view_zoom: f64,
units: Unit,
pointer: Option<Pos2>,
) {
if !outer.is_finite() || !page_rect.is_finite() || !outer.is_positive() {
return;
}
let env = Env::of(ui);
let colors = &env.tokens.color;
let bg = token_color(colors.surface.raised.0);
let border = token_color(colors.line.control_edge.0);
let tick_major = token_color(colors.text.muted.0);
let tick_minor = token_color(colors.line.control_edge.0);
let label_ink = token_color(colors.text.normal.0);
let accent = token_color(colors.accent.solid.0);
let thin = env.tokens.stroke.thin.max(1.0);
let mut font: FontId = egui::TextStyle::Small.resolve(ui.style());
font.size = font.size.min(9.5);
let corner_rect = Rect::from_min_max(outer.min, page_rect.min);
let top_rect = Rect::from_min_max(pos2(page_rect.min.x, outer.min.y), pos2(outer.max.x, page_rect.min.y));
let left_rect = Rect::from_min_max(pos2(outer.min.x, page_rect.min.y), pos2(page_rect.min.x, outer.max.y));
// Anchor page: page under the pointer if any, otherwise the current page, otherwise the first placed page.
let pointer_page = pointer.and_then(|pos| placed.iter().find(|p| p.rect.is_finite() && p.rect.contains(pos)));
let cursor_on_page = pointer.filter(|_| pointer_page.is_some());
let anchor = pointer_page.or_else(|| placed.iter().find(|p| p.page == current_page)).or_else(|| placed.first());
let origin_scale = anchor
.and_then(|p| {
let size = page_sizes.get(p.page).copied().unwrap_or((0.0, 0.0));
page_origin_and_scale(p.rect, size, view_rotation, view_zoom)
})
.or_else(|| {
if view_zoom.is_finite() && view_zoom > 0.0 {
let s = view_zoom * f64::from(super::PT);
(s.is_finite() && s > 0.0).then_some((page_rect.min, s, s))
} else {
None
}
});
let per_point = units.per_point();
let per_point_ok = per_point.is_finite() && per_point > 0.0;
// Corner unit badge (display only; does not take clicks or claim the cursor).
{
let painter = ui.painter().with_clip_rect(corner_rect);
painter.rect_filled(corner_rect, CornerRadius::ZERO, bg);
painter.line_segment([corner_rect.right_top(), corner_rect.right_bottom()], Stroke::new(thin, border));
painter.line_segment([corner_rect.left_bottom(), corner_rect.right_bottom()], Stroke::new(thin, border));
painter.text(corner_rect.center(), Align2::CENTER_CENTER, units.label(), font.clone(), label_ink);
}
// Top horizontal ruler.
if top_rect.width() > 0.0 && top_rect.height() > 0.0 {
let painter = ui.painter().with_clip_rect(top_rect);
painter.rect_filled(top_rect, CornerRadius::ZERO, bg);
painter.line_segment([top_rect.left_bottom(), top_rect.right_bottom()], Stroke::new(thin, border));
if per_point_ok
&& let Some((origin, sx, _)) = origin_scale
&& let Some((step, subs)) = ruler_step(sx, units)
{
let px_per_unit = sx / per_point;
let ticks = compute_ticks(top_rect.min.x, top_rect.max.x, origin.x, px_per_unit, step, subs, MAX_TICKS);
for tick in ticks {
match tick.kind {
TickKind::Major => {
painter.line_segment(
[pos2(tick.screen, top_rect.max.y - 7.0), pos2(tick.screen, top_rect.max.y)],
Stroke::new(thin, tick_major),
);
let label = format_label(tick.value, step);
painter.text(pos2(tick.screen + 2.0, top_rect.min.y + 1.5), Align2::LEFT_TOP, label, font.clone(), label_ink);
}
TickKind::Half => {
painter.line_segment(
[pos2(tick.screen, top_rect.max.y - 5.0), pos2(tick.screen, top_rect.max.y)],
Stroke::new(thin, tick_minor),
);
}
TickKind::Minor => {
painter.line_segment(
[pos2(tick.screen, top_rect.max.y - 3.5), pos2(tick.screen, top_rect.max.y)],
Stroke::new(thin, tick_minor),
);
}
}
}
}
if let Some(pos) = cursor_on_page
&& pos.x >= top_rect.min.x
&& pos.x <= top_rect.max.x
{
painter.line_segment([pos2(pos.x, top_rect.min.y), pos2(pos.x, top_rect.max.y)], Stroke::new(1.5, accent));
let tip = vec![pos2(pos.x - 3.0, top_rect.max.y - 4.0), pos2(pos.x + 3.0, top_rect.max.y - 4.0), pos2(pos.x, top_rect.max.y)];
painter.add(egui::epaint::PathShape::convex_polygon(tip, accent, Stroke::NONE));
}
}
// Left vertical ruler.
if left_rect.width() > 0.0 && left_rect.height() > 0.0 {
let painter = ui.painter().with_clip_rect(left_rect);
painter.rect_filled(left_rect, CornerRadius::ZERO, bg);
painter.line_segment([left_rect.right_top(), left_rect.right_bottom()], Stroke::new(thin, border));
if per_point_ok
&& let Some((origin, _, sy)) = origin_scale
&& let Some((step, subs)) = ruler_step(sy, units)
{
let px_per_unit = sy / per_point;
let ticks = compute_ticks(left_rect.min.y, left_rect.max.y, origin.y, px_per_unit, step, subs, MAX_TICKS);
for tick in ticks {
match tick.kind {
TickKind::Major => {
painter.line_segment(
[pos2(left_rect.max.x - 7.0, tick.screen), pos2(left_rect.max.x, tick.screen)],
Stroke::new(thin, tick_major),
);
let label = format_label(tick.value, step);
let galley = painter.layout_no_wrap(label, font.clone(), label_ink);
let pos = pos2(left_rect.min.x + 2.0, tick.screen + 2.0 + galley.size().x);
painter.add(egui::epaint::TextShape::new(pos, galley, label_ink).with_angle(-std::f32::consts::FRAC_PI_2));
}
TickKind::Half => {
painter.line_segment(
[pos2(left_rect.max.x - 5.0, tick.screen), pos2(left_rect.max.x, tick.screen)],
Stroke::new(thin, tick_minor),
);
}
TickKind::Minor => {
painter.line_segment(
[pos2(left_rect.max.x - 3.5, tick.screen), pos2(left_rect.max.x, tick.screen)],
Stroke::new(thin, tick_minor),
);
}
}
}
}
if let Some(pos) = cursor_on_page
&& pos.y >= left_rect.min.y
&& pos.y <= left_rect.max.y
{
painter.line_segment([pos2(left_rect.min.x, pos.y), pos2(left_rect.max.x, pos.y)], Stroke::new(1.5, accent));
let tip = vec![pos2(left_rect.max.x - 4.0, pos.y - 3.0), pos2(left_rect.max.x - 4.0, pos.y + 3.0), pos2(left_rect.max.x, pos.y)];
painter.add(egui::epaint::PathShape::convex_polygon(tip, accent, Stroke::NONE));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::canvas::PT;
use egui::vec2;
#[test]
fn nice_interval_picks_1_2_5_multiples_across_zooms_and_units() {
for unit in Unit::ALL {
for zoom in [0.1, 0.25, 0.5, 1.0, 2.0, 4.0, 16.0, 64.0] {
let px_per_pt = zoom * f64::from(PT);
let (step, subs) = ruler_step(px_per_pt, unit).expect("finite positive zoom yields a step");
assert!(step > 0.0 && step.is_finite());
assert!(subs >= 4);
let px_per_unit = px_per_pt / unit.per_point();
let major_px = step * px_per_unit;
// Labels never overlap (at least MIN_MAJOR_SPACING_PX apart) and never get absurdly sparse.
assert!(major_px >= MIN_MAJOR_SPACING_PX - 1e-6, "unit={unit:?} zoom={zoom} major_px={major_px}");
assert!(major_px <= MIN_MAJOR_SPACING_PX * 2.51, "unit={unit:?} zoom={zoom} major_px={major_px}");
// Leading digit of step is 1, 2, or 5.
let mantissa = step / 10.0_f64.powf(step.log10().floor());
assert!(
(mantissa - 1.0).abs() < 1e-6 || (mantissa - 2.0).abs() < 1e-6 || (mantissa - 5.0).abs() < 1e-6,
"step {step} mantissa {mantissa} is not 1/2/5"
);
}
}
// Higher zoom yields smaller or equal major interval.
for unit in Unit::ALL {
let (far, _) = ruler_step(0.25 * f64::from(PT), unit).unwrap();
let (near, _) = ruler_step(4.0 * f64::from(PT), unit).unwrap();
assert!(near < far, "{unit:?}: zoomed in ({near}) should have finer step than zoomed out ({far})");
}
}
#[test]
fn tick_positions_anchor_to_page_offset() {
let origin = 120.0_f32;
let px_per_unit = 10.0_f64;
let ticks = compute_ticks(20.0, 320.0, origin, px_per_unit, 10.0, 5, MAX_TICKS);
let majors: Vec<Tick> = ticks.iter().copied().filter(|t| t.kind == TickKind::Major).collect();
// Origin 0 lands exactly at screen coordinate 120.0.
let zero = majors.iter().find(|t| t.value.abs() < 1e-9).expect("zero tick present");
assert!((zero.screen - origin).abs() < 1e-4);
// Every major tick satisfies screen == origin + value * px_per_unit and stays inside the ruler strip.
assert!(majors.len() >= 3);
for t in &majors {
let expected = origin + (t.value * px_per_unit) as f32;
assert!((t.screen - expected).abs() < 1e-3, "tick {t:?} expected {expected}");
assert!(t.screen >= 19.5 && t.screen <= 320.5);
}
// Shifting origin right by 35 px shifts every tick's screen position by +35 px for the same value.
let shifted = compute_ticks(20.0, 320.0, origin + 35.0, px_per_unit, 10.0, 5, MAX_TICKS);
let shifted_zero = shifted.iter().find(|t| t.kind == TickKind::Major && t.value.abs() < 1e-9).unwrap();
assert!((shifted_zero.screen - (origin + 35.0)).abs() < 1e-4);
}
#[test]
fn label_formatting_is_clean_and_has_no_negative_zero() {
assert_eq!(format_label(0.0, 10.0), "0");
assert_eq!(format_label(-0.0, 10.0), "0");
assert_eq!(format_label(-1e-12, 1.0), "0");
assert_eq!(format_label(100.0, 50.0), "100");
assert_eq!(format_label(-50.0, 50.0), "-50");
assert_eq!(format_label(0.5, 0.5), "0.5");
assert_eq!(format_label(1.0, 0.5), "1");
assert_eq!(format_label(1.25, 0.25), "1.25");
assert_eq!(format_label(0.05, 0.05), "0.05");
assert_eq!(format_label(f64::NAN, 1.0), "");
assert_eq!(format_label(f64::INFINITY, 1.0), "");
}
#[test]
fn tick_cap_bounds_output_on_dense_ranges() {
let cap = 32;
let ticks = compute_ticks(0.0, 100_000.0, 0.0, 10.0, 1.0, 10, cap);
assert_eq!(ticks.len(), cap);
let ticks_default = compute_ticks(0.0, 1_000_000.0, 0.0, 10.0, 1.0, 10, MAX_TICKS);
assert!(ticks_default.len() <= MAX_TICKS);
}
#[test]
fn degenerate_inputs_do_not_panic_or_loop() {
// Bad zooms: 0, negative, NaN, infinity, huge.
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e308, 1e-308] {
let _ = nice_interval(bad, MIN_MAJOR_SPACING_PX);
let _ = ruler_step(bad, Unit::Points);
let ticks = compute_ticks(0.0, 500.0, 10.0, bad, 10.0, 5, MAX_TICKS);
assert!(ticks.len() <= MAX_TICKS);
}
// Bad ranges and steps.
assert!(compute_ticks(100.0, 100.0, 0.0, 1.0, 10.0, 5, MAX_TICKS).is_empty());
assert!(compute_ticks(200.0, 100.0, 0.0, 1.0, 10.0, 5, MAX_TICKS).is_empty());
assert!(compute_ticks(f32::NAN, 100.0, 0.0, 1.0, 10.0, 5, MAX_TICKS).is_empty());
assert!(compute_ticks(0.0, 100.0, f32::NAN, 1.0, 10.0, 5, MAX_TICKS).is_empty());
assert!(compute_ticks(0.0, 100.0, 0.0, 1.0, 0.0, 5, MAX_TICKS).is_empty());
assert!(compute_ticks(0.0, 100.0, 0.0, 1.0, f64::NAN, 5, MAX_TICKS).is_empty());
assert!(compute_ticks(0.0, 100.0, 0.0, 1.0, 10.0, 0, MAX_TICKS).is_empty());
// Zero-size and tiny areas for reserve().
let zero = Rect::from_min_size(pos2(10.0, 20.0), vec2(0.0, 0.0));
assert_eq!(reserve(zero), (None, zero));
let tiny = Rect::from_min_size(pos2(0.0, 0.0), vec2(RULER_THICKNESS, 200.0));
assert_eq!(reserve(tiny), (None, tiny));
// Zero-size page and rotated pages for page_origin_and_scale().
assert!(page_origin_and_scale(zero, (0.0, 0.0), 0, 1.0).is_none());
let page = Rect::from_min_size(pos2(40.0, 50.0), vec2(400.0, 200.0));
assert!(page_origin_and_scale(page, (0.0, 0.0), 0, 0.0).is_none());
assert!(page_origin_and_scale(page, (f32::NAN, 100.0), 0, f64::NAN).is_none());
// Rotated 90°: displayed width is ph (800), displayed height is pw (400).
let (origin, sx, sy) = page_origin_and_scale(page, (400.0, 800.0), 90, 1.0).unwrap();
assert_eq!(origin, page.left_top());
assert!((sx - 0.5).abs() < 1e-6);
assert!((sy - 0.5).abs() < 1e-6);
}
}
+17
View File
@@ -4,6 +4,12 @@
//! but on Windows and Linux winit reports one line per notch, where browsers scroll about
//! 100 pixels, so the desktop default is larger than a text line. The canvas reads the two
//! distances through its navigation options.
//!
//! Touchpad motion reported in points scrolls as the system sends it, except on Linux (#1904): a
//! Wayland compositor sends the raw finger distance, which winit passes on 1:1, where X11 sends the
//! same swipe as wheel lines that the wheel line scales. The Wayland window then crawled, and the
//! preference did nothing for it. There the motion gets a gain that follows the same choice, through
//! the runtime's wheel speed, which leaves ⌘/Ctrl zooming alone.
/// The user's choice, relative to the platform's normal speed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -28,6 +34,11 @@ const NORMAL_LINE_POINTS: f32 = if cfg!(target_arch = "wasm32") {
/// Points one arrow-key step scrolls at Normal speed.
const KEY_LINE_POINTS: f32 = 40.0;
/// What touchpad motion reported in points is multiplied by at Normal speed. Windows and macOS
/// already deliver touchpad deltas that feel right; Linux under Wayland sends the raw finger
/// distance.
const NORMAL_TOUCHPAD_GAIN: f32 = if cfg!(target_os = "linux") { 3.0 } else { 1.0 };
impl ScrollSpeed {
pub const ALL: [Self; 3] = [Self::Slow, Self::Normal, Self::Fast];
@@ -58,6 +69,12 @@ impl ScrollSpeed {
KEY_LINE_POINTS * self.factor()
}
/// What touchpad motion reported in points is multiplied by: 1 everywhere but Linux, where it
/// follows the choice.
pub fn touchpad_gain(self) -> f32 {
if cfg!(target_os = "linux") { NORMAL_TOUCHPAD_GAIN * self.factor() } else { 1.0 }
}
pub fn parse(value: &str) -> Option<Self> {
Self::ALL.into_iter().find(|s| s.label().eq_ignore_ascii_case(value))
}
+10 -5
View File
@@ -347,6 +347,14 @@ impl DocView {
self.session.clear_selection();
}
/// The text selection as markup quadrilaterals in user space when all of it is on `page` and
/// read, else `None`.
pub(crate) fn selection_quads_on(&self, info: &DocInfo, page: usize) -> Option<Vec<[f64; 8]>> {
let marks = self.session.selection_quads(info, self.view.rotation);
let Ok([(p, quads)]) = <[_; 1]>::try_from(marks) else { return None };
(p == page).then_some(quads)
}
/// Select text on `page` from glyph `from` to glyph `to` (tests and automation).
pub fn select_text(&mut self, page: usize, from: usize, to: usize) {
self.session.all_text = false;
@@ -513,11 +521,8 @@ pub(super) fn selection_bar(
can_comment: bool,
can_copy: bool,
) -> bool {
if body.pass.is_some_and(|p| p.press.phase.button_down())
|| ui.ctx().text_edit_focused()
|| session.comments.composer.is_some()
|| session.comments.panel.editing.is_some()
{
// An inline note draft may stay open after focus returns to the page.
if body.pass.is_some_and(|p| p.press.phase.button_down()) || ui.ctx().text_edit_focused() || session.comments.composer.is_some() {
return false;
}
let Some(selection) = session.text.selection else {
+9 -1
View File
@@ -97,9 +97,17 @@ fn title_bar(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
};
// The button names the choice it shows; a click steps to the next one.
let theme_label = format!("{}: {theme_label}", tl!("Display theme"));
let embedded = app.embedded;
let out = TitleBar::new()
.trailing(|ui, _| {
Button::command("help.discord").label("Discord").icon(IconId::new("messages-square")).tooltip(tl!("Join the ArtCraft Discord")).show(ui);
// One click to the community, from anywhere in the app (hidden in embedded mode, #2490).
if !embedded {
Button::command("help.discord")
.label("Discord")
.icon(IconId::new("messages-square"))
.tooltip(tl!("Join the ArtCraft Discord"))
.show(ui);
}
IconButton::command(IconId::new("circle-help"), "help.shortcuts").show(ui);
let theme_button = IconButton::command(IconId::new(theme_icon), ThemeChoice::NextMode.command()).label(theme_label.clone()).show(ui);
let opener = theme_button.response().clone();
+22 -5
View File
@@ -7,6 +7,7 @@ use std::borrow::Cow;
use std::collections::HashSet;
use craft::behavior::{EditEvent, IconId, SelectionChange, keyed};
use craft::host::target::WindowState;
use craft::platform::open::CAN_REVEAL;
use craft::ui::buttons::Button;
use craft::ui::contract::overlay::Dismiss;
@@ -16,8 +17,9 @@ use craft::ui::contract::{
use craft::ui::layout_components::Row;
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::popover::Popover;
use craft::ui::runtime::windows::{WindowAction, WindowHost};
use craft::ui::runtime::windows::{self, WindowAction, WindowHost};
use craft::ui::tabs::{Tab, TabStrip, TabStripOutput};
use craft::window::policy::Frame;
use crate::PdfCraftApp;
use crate::panes::Place;
@@ -56,8 +58,10 @@ pub(crate) fn strip(app: &mut PdfCraftApp, ui: &mut egui::Ui, place: Place) {
let source = keyed(&entries, |entry: &StripEntry| entry.key.clone()).with_text(|entry: &StripEntry| Cow::Borrowed(entry.label.as_str()));
let item_count = entries.len();
let entries_ref = &entries;
let wheel_viewport = ui.scope_id().with(("document tab wheel viewport", place));
let make_strip = || {
let mut strip = TabStrip::new(strip_label.clone())
.wheel_browse(wheel_viewport)
.takes_drop(DropKind::new(DropPlace::Between, |_: &ListDrag<StripTab>, _| true))
.can_close(move |key: &StripTab| entries_ref.iter().any(|entry| &entry.key == key && entry.closable))
.reorder(ReorderRule::new())
@@ -213,7 +217,13 @@ fn show_strip_row<'a>(
};
let builder = egui::UiBuilder::new().max_rect(room).layout(layout);
let shown_open = ui.scope_builder(builder, |ui| {
Button::command("file.open").variant(craft::theme::Variant::GHOST).icon(IconId::new("plus")).show(ui).response.rect
Button::command("file.open")
.label(crate::commands::control_label("file.open"))
.variant(craft::theme::Variant::GHOST)
.icon(IconId::new("plus"))
.show(ui)
.response
.rect
});
let drawn = shown_open.response.rect.width();
let open = shown_open.inner;
@@ -242,12 +252,19 @@ fn window_drag_gap(ui: &mut egui::Ui, strip: egui::Rect, occupied: egui::Rect) {
return;
}
let host = WindowHost::of(ui.ctx());
if matches!(host.frame(), craft::window::policy::Frame::Integrated(_)) {
let frame = host.frame();
// An integrated (Windows, Linux) or inset (macOS) title bar is the app's own, so the strip's free space is its.
if matches!(frame, Frame::Integrated(_) | Frame::Inset(_)) {
let handle = ui.interact(gap, ui.scope_id().with("document-strip-window-drag"), egui::Sense::click_and_drag());
let viewport = host.current();
if handle.double_clicked() {
host.act(host.current(), WindowAction::ToggleMaximize);
// The same as a double click on the title bar: on macOS it follows the system setting.
let shell = windows::shell_of(ui.ctx(), viewport);
if let Some(action) = windows::double_click_action(&frame, shell.double_click, shell.window.state == WindowState::Maximized) {
host.act(viewport, action);
}
} else if handle.drag_started_by(egui::PointerButton::Primary) {
host.act(host.current(), WindowAction::StartMove);
host.act(viewport, WindowAction::StartMove);
}
}
}
+5 -3
View File
@@ -6,7 +6,7 @@ use craft::behavior::{DisplayOrder, IconId, ItemSource, SelectionChange};
use craft::keymap::CommandRef;
use craft::ui::bars::{Bar, BarKind};
use craft::ui::buttons::{CommandSearch, IconButton};
use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::contract::{Bind, CollectionEvent, Pad, Props as _, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::layout_components::Row;
use craft::ui::menu::HelpEntry;
use craft::ui::patterns::panels::CommandPalette;
@@ -48,7 +48,8 @@ pub(super) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let menus = app.native_menu.is_none() && !hidden.menubar;
Row::new().show(ui, |ui, _| {
if menus {
app.menu_bar_ui(ui);
// The mode bar insets its controls by the control pad. Give the menu titles the same inset.
Row::new().pad(Pad::Control).show(ui, |ui, _| app.menu_bar_ui(ui));
}
// Production replaces the search field with its icon when the field cannot keep its minimum width.
let compact_search = ui.available_width() < 140.0 + 116.0;
@@ -84,7 +85,8 @@ pub(super) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
Some(at) => strip.shown(at),
None => strip,
};
let out = strip.show_items(ui, &ModeTabs, &mut |key, _| Tab::new(tl!(MODES[*key % MODES.len()].1)));
let out = strip
.show_items(ui, &ModeTabs, &mut |key, _| Tab::new(tl!(MODES[*key % MODES.len()].1)).text_role(craft::theme::TypeRole::Label));
for event in out.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
&& let Some((mode, _)) = keys.last().and_then(|at| MODES.get(*at))
+17 -5
View File
@@ -5,7 +5,7 @@ use craft::behavior::kurbo::Size;
use craft::behavior::{DockSide, IconId};
use craft::pages::PageDisplay;
use craft::theme::TypeRole;
use craft::ui::buttons::IconButton;
use craft::ui::buttons::{IconButton, ToggleButton};
use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::display::Text;
use craft::ui::menu::{Menu, MenuItem};
@@ -17,6 +17,10 @@ use crate::PdfCraftApp;
/// Shows the rail's view cluster; nothing without an active document or a current page to view.
pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut Ui) {
ui.with_layout(egui::Layout::top_down(egui::Align::Center), |ui| controls(app, ui));
}
fn controls(app: &mut PdfCraftApp, ui: &mut Ui) {
let Some((index, id)) = app.active_ids() else { return };
let Some(doc) = app.session.get(id) else { return };
let page_count = doc.info.pages.len();
@@ -28,9 +32,10 @@ pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut Ui) {
let Some(page) = doc.info.pages.get(current) else { return };
let page_size = Size::new(f64::from(page.width.max(1.0)), f64::from(page.height.max(1.0)));
let field_size = {
let (field_size, caption_size) = {
let env = Env::of(ui);
egui::vec2(env.tokens.size.rail.button, env.tokens.size.control.md)
// The page box takes the rail's whole width, as the zoom field does, so a four-digit page number fits.
(egui::vec2(ui.available_width(), env.tokens.size.control.md), env.tokens.typography.caption.size)
};
// Taken once, in the pass that shows the field, also while the field is not focused.
let reselect = std::mem::take(&mut view.page_input_reselect);
@@ -38,6 +43,7 @@ pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut Ui) {
let (field_rect, _) = ui.allocate_exact_size(field_size, egui::Sense::hover());
let edit = TextField::new("Current page", Bind::bound(&mut view.page_input))
.id(input_id)
.centred()
.select_on_focus()
.select_all(reselect)
.submits()
@@ -64,7 +70,12 @@ pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut Ui) {
// Out of range (an empty document) reads "Page 0 of 0", never past the end.
let shown = if current < page_count { current + 1 } else { page_count };
let of = crate::i18n::fmt(crate::i18n::t("Page {p} of {n}"), &[("p", &shown.to_string()), ("n", &page_count.to_string())]);
Text::new(super::page_position(current, page_count, label)).role(TypeRole::Caption).tooltip(of).show(ui);
let position = super::page_position(current, page_count, label);
// "1488/1500" has no space to wrap at and is wider than the rail: it breaks after the slash instead.
let one_line =
ui.fonts_mut(|fonts| fonts.layout_no_wrap(position.clone(), egui::FontId::proportional(caption_size), egui::Color32::PLACEHOLDER).size().x);
let position = if one_line > ui.available_width() { position.replacen('/', "/\n", 1) } else { position };
ui.vertical_centered(|ui| Text::new(position).role(TypeRole::Caption).tooltip(of).show(ui));
IconButton::command(IconId::new("chevron_left"), "view.previous_view").show(ui);
IconButton::command(IconId::new("chevron_right"), "view.next_view").show(ui);
@@ -81,7 +92,8 @@ pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut Ui) {
IconButton::command(IconId::new("zoom_in"), "view.zoom.in").show(ui);
IconButton::command(IconId::new("zoom_out"), "view.zoom.out").show(ui);
IconButton::command(IconId::new("maximize_2"), "view.fit_toggle").show(ui);
ToggleButton::command("view.full_screen").icon(IconId::new("monitor")).icon_only().show(ui);
IconButton::command(IconId::new("maximize_2"), "view.fit_toggle").label(crate::commands::control_label("view.fit_toggle")).show(ui);
IconButton::command(IconId::new("rotate_cw"), "view.rotate.cw").show(ui);
// The rows' marks come from the commands' checked state (the catalog), not from here.
+39 -2
View File
@@ -68,6 +68,27 @@ pub(crate) fn chord_label(ctx: &egui::Context, id: &str) -> Option<String> {
Some(shortcut_text(shortcut, mac))
}
/// The English label of a command id: the registry's, the menu extras' or the catalog-only
/// commands'. The source of truth for a control bound to the command.
pub(crate) fn english_label(id: &str) -> Option<&'static str> {
if let Some(spec) = commands::command(id) {
return Some(spec.label);
}
crate::menus::EXTRA
.iter()
.find(|(i, ..)| *i == id)
.map(|(_, label, _)| *label)
.or_else(|| catalog::CATALOG_ONLY.iter().find(|(i, ..)| *i == id).map(|(_, label, _)| *label))
}
/// The label of a control bound to `id`, in the current interface language: the command's `@id`
/// entry if it keeps the English label's shape, otherwise the English label (the way the menus
/// name the same command).
pub(crate) fn control_label(id: &str) -> String {
let english = english_label(id).unwrap_or(id);
crate::i18n::menu_label(id, english)
}
impl PdfCraftApp {
/// Runs a command the runtime fired from a key, a menu row, the palette, a component or
/// automation. The catalog's app-side handlers come first; every other id is a registered
@@ -113,7 +134,7 @@ impl PdfCraftApp {
crate::menus::PASTE => Some("page.paste"),
_ => None,
};
if !organize && !self.is_preparing() && id == crate::menus::PASTE && fired.pasted.is_some() {
if !organize && id == crate::menus::PASTE && fired.pasted.is_some() {
if let Some(i) = self.active.filter(|&i| i < self.views.len()) {
self.paste_from_clipboard_at(ctx, i, fired.pasted.as_ref(), fired.paste_at);
}
@@ -295,7 +316,8 @@ impl PdfCraftApp {
|| self.active.and_then(|i| self.views.get(i)).is_some_and(|v| {
// Selected text, or a picked picture, which Copy takes in its original format.
!v.organize
&& (v.session.all_text
&& (self.is_preparing() && v.session.prepare.selected.is_some()
|| v.session.all_text
|| v.selection_waits_for_text().is_some()
|| v.selected_text().is_some_and(|t| !t.is_empty())
|| v.session.picked_image.is_some()
@@ -461,6 +483,7 @@ impl PdfCraftApp {
"protect.remove_hidden" => self.open_remove_hidden(),
"print.dialog" => self.open_print(),
"optimize.advanced" => crate::optimize_ui::open_optimizer(self, ctx),
"optimize.audit" => crate::optimize_ui::open_space_audit(self, ctx, false),
"doc.compare" => crate::compare_ui::open_compare_dialog(self, ctx),
"standards.pdfa" => self.open_pdfa(),
"actions.wizard" => crate::actions_ui::open_wizard(self, ctx, None),
@@ -592,6 +615,7 @@ impl PdfCraftApp {
self.set_full_screen(on);
}
"view.read_mode" => self.switch_mode(ctx, if self.mode == Mode::Read { Mode::AllTools } else { Mode::Read }, false),
"view.rulers" => self.show_rulers = !self.show_rulers,
"view.split" => self.toggle_split(ctx),
crate::viewer_prefs::TOGGLE => self.toggle_interface(),
"view.previous_view" | "view.next_view" => {
@@ -769,6 +793,7 @@ impl PdfCraftApp {
self.marks_draft.focused_box = 5;
self.open_marks(ctx, pdfcraft_engine::MarkKind::HeaderFooter, false);
}
"edit.bates_files" => self.open_bates_files(ctx),
"prepress.marks" => self.open_printer_marks(ctx),
"edit.header_footer.remove" | "edit.watermark.remove" | "edit.background.remove" | "prepress.marks.remove" => {
use pdfcraft_engine::MarkKind as K;
@@ -1090,4 +1115,16 @@ mod tests {
assert_eq!(tab_after(None, 0, true), None);
assert_eq!(tab_after(Some(0), 0, false), None);
}
/// A control bound to a command names it by the command's `@id` row, the way the menus do:
/// the row shows if it keeps the English label's shape, and the English label shows otherwise.
#[test]
fn control_label_uses_the_command_id_as_the_key() {
let fx = crate::i18n::fixture_lang("x-ctrl", "@id\ttools.expand\tExpand-FX\n");
crate::i18n::set_current(fx);
assert_eq!(control_label("tools.expand"), "Expand-FX", "the @id row of the command's own id is used");
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(control_label("tools.expand"), "Expand all tools", "without a row the English label shows");
assert_eq!(control_label("file.open"), "Open…", "a registry command's English label");
}
}
+5 -2
View File
@@ -18,7 +18,7 @@ use craft::pages::PageDisplay;
use craft::theme::ModeChoice;
/// Commands only the catalog knows: id, English label and icon. Their handlers are the board's.
const CATALOG_ONLY: &[(&str, &str, &str)] = &[
pub(crate) const CATALOG_ONLY: &[(&str, &str, &str)] = &[
("app.theme", "Switch theme", "moon"),
("home.unpin_tool", "Unpin tool", "pin-off"),
("form.calculation_order.back", "Back to Prepare a form", "chevron_left"),
@@ -53,7 +53,7 @@ fn kind_of(id: &str) -> CommandKind {
"view.theme.system" | "view.theme.light" | "view.theme.dark" => CommandKind::Radio { group: Some("theme".into()) },
PANEL => CommandKind::Radio { group: Some("panel".into()) },
"view.continuous" | "view.page_gaps" | "view.layout.cover" | "view.full_screen" | "view.read_mode" | "view.side_panel"
| "view.tools_pane" | "view.split" => CommandKind::Toggle,
| "view.tools_pane" | "view.split" | "view.rulers" => CommandKind::Toggle,
_ => CommandKind::Command,
}
}
@@ -204,6 +204,8 @@ fn enabled(app: &PdfCraftApp, ctx: &egui::Context, command: &CommandRef) -> bool
"file.close" if !has_doc && super::mac_shortcuts(ctx) && !cfg!(target_arch = "wasm32") => true,
"edit.copy" if organize => enabled_id("page.copy"),
"edit.copy" if view.is_some_and(|v| v.session.picked_image.is_some()) => doc.is_some_and(|d| d.allows_copying()),
// Copy takes the fields selected while preparing a form.
"edit.copy" if app.is_preparing() && view.is_some_and(|v| v.session.prepare.selected.is_some()) => true,
"edit.copy"
if app.is_preparing()
&& view.is_some_and(|v| v.session.comments.primary().is_some() && v.selected_text().is_none_or(|t| t.is_empty())) =>
@@ -240,6 +242,7 @@ fn checked(app: &PdfCraftApp, command: &CommandRef) -> Option<bool> {
"view.layout.cover" => view.is_some_and(|v| v.cover),
"view.full_screen" => app.full_screen(),
"view.read_mode" => app.mode == Mode::Read,
"view.rulers" => app.show_rulers,
"view.side_panel" => app.right().is_some(),
"view.tools_pane" => app.left_open(),
"view.split" => app.panes.split.is_some(),
+1
View File
@@ -37,6 +37,7 @@
//! reports the choice and `ui.state.theme` reports the resolved light/dark colours.
//! `form-reminder=on|off` persists ordinary form reminders. `ui.state.show_form_field_reminder` reports the setting.
//! `show_page_edge_shadows=true|false` controls page decoration app-wide.
//! `rulers=on|off` shows or hides horizontal and vertical canvas rulers; `ui.state.rulers` reports it.
//! `comment-tool-pinned=true|false` remembers the annotation quick bar's pin across restarts.
//! `folder-collapsed=<folder>=on|off` folds a pinned folder on Home down to its heading or
//! opens it again; `ui.state.pinned_folders` lists each pinned folder and whether it is.
+2
View File
@@ -94,6 +94,7 @@ impl crate::PdfCraftApp {
}),
"viewport": [v.viewport_rect().min.x, v.viewport_rect().min.y, v.viewport_rect().max.x, v.viewport_rect().max.y],
"find_open": v.find.is_some(),
"rulers": self.show_rulers,
"page_errors": v.page_errors().iter().map(|(p, e)| json!({ "page": p + 1, "error": e })).collect::<Vec<_>>(),
// Pages cut at the renderer's limits (#623), 1-based.
"cut_pages": v.cut_pages().iter().map(|p| p + 1).collect::<Vec<_>>(),
@@ -161,6 +162,7 @@ impl crate::PdfCraftApp {
"theme": format!("{:?}", self.root_env(ctx).resolved(ctx).mode),
"theme_preference": format!("{:?}", self.theme_preference),
"show_page_edge_shadows": self.show_page_edge_shadows,
"rulers": self.show_rulers,
"language": self.language,
"notice": notice,
"progress": progress,
+2
View File
@@ -5,12 +5,14 @@ use crate::PdfCraftApp;
mod about;
pub(crate) mod attachment_description;
pub(super) mod bates_files_ui;
pub mod bookmark_styles_ui;
pub(super) mod comment_props;
pub(super) mod convert_colours_ui;
pub(crate) mod duplicate_field;
pub(super) mod hairlines_ui;
pub(crate) mod host;
pub(super) mod marks_picture;
pub(super) mod marks_ui;
pub(crate) mod page_dialogs;
pub(crate) mod page_props;

Some files were not shown because too many files have changed in this diff Show More