diff --git a/Cargo.lock b/Cargo.lock index 1c15e7ec8b..f9d5de635f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 77d52682f8..91efe0f5dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/README.md b/README.md index 68071df0d6..1b6d6b4ea3 100644 --- a/README.md +++ b/README.md @@ -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--freebsd-x86_64.tar.gz` | diff --git a/ROADMAP.md b/ROADMAP.md index 39757bf47a..73aef0d191 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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. diff --git a/apps/pdfcraft-web/Cargo.toml b/apps/pdfcraft-web/Cargo.toml index 171bc0f43b..bf4b463d94 100644 --- a/apps/pdfcraft-web/Cargo.toml +++ b/apps/pdfcraft-web/Cargo.toml @@ -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 } diff --git a/apps/pdfcraft-web/src/main.rs b/apps/pdfcraft-web/src/main.rs index aae8848d58..3460f21546 100644 --- a/apps/pdfcraft-web/src/main.rs +++ b/apps/pdfcraft-web/src/main.rs @@ -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=` 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 { 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, String> { use eframe::wasm_bindgen::JsCast; @@ -167,8 +184,8 @@ fn app_canvas() -> Option { /// 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. diff --git a/apps/pdfcraft/src/desktop_monitors.rs b/apps/pdfcraft/src/desktop_monitors.rs new file mode 100644 index 0000000000..794903aab7 --- /dev/null +++ b/apps/pdfcraft/src/desktop_monitors.rs @@ -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, + monitors: Mutex)>>, +} + +impl DesktopWindows { + pub(super) fn new(window: Option<&Arc>) -> 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 { + SystemWindows.primary_held() + } + + fn command_held(&self) -> Option { + SystemWindows.command_held() + } + + fn warp_pointer(&self, point: [f32; 2]) -> bool { + SystemWindows.warp_pointer(point) + } + + fn monitors(&self) -> Vec { + 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 + } +} diff --git a/apps/pdfcraft/src/launch_profile.rs b/apps/pdfcraft/src/launch_profile.rs index fd1df09247..85c9a68d45 100644 --- a/apps/pdfcraft/src/launch_profile.rs +++ b/apps/pdfcraft/src/launch_profile.rs @@ -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"); diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index 3564efe993..70d123d9fa 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -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()); diff --git a/apps/pdfcraft/src/window_frame.rs b/apps/pdfcraft/src/window_frame.rs new file mode 100644 index 0000000000..44d68c9e22 --- /dev/null +++ b/apps/pdfcraft/src/window_frame.rs @@ -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) -> Option> { + let RawWindowHandle::Win32(raw) = window.window_handle().ok()?.as_raw() else { return None }; + let target = raw.hwnd.get(); + let root: Weak = 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()); + } +} diff --git a/apps/pdfcraft/src/window_placement.rs b/apps/pdfcraft/src/window_placement.rs index b5f085536d..92943d234f 100644 --- a/apps/pdfcraft/src/window_placement.rs +++ b/apps/pdfcraft/src/window_placement.rs @@ -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::(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::(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 { 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 }; diff --git a/crates/a11y/src/autotag.rs b/crates/a11y/src/autotag.rs index 42dc37b978..ea04615ea4 100644 --- a/crates/a11y/src/autotag.rs +++ b/crates/a11y/src/autotag.rs @@ -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")); } diff --git a/crates/a11y/tests/cross_stream.rs b/crates/a11y/tests/cross_stream.rs index d0a2f48204..b8fac8794f 100644 --- a/crates/a11y/tests/cross_stream.rs +++ b/crates/a11y/tests/cross_stream.rs @@ -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 <> BDC BT /F1 12 Tf 72 700 Td (a) Tj /PCSoft <> BDC EMC (b) Tj /PCHard BMC EMC ET EMC EMC\n\ + /P BMC BT /F1 12 Tf 72 680 Td /Span <> 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 <> BDC (a) Tj ET EMC"), + ("a span never closed", "/Span <> 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 <> 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 <> 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}"); + } +} diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rs index 9bdda6b0db..f7a6bf27c6 100644 --- a/crates/annot/src/appearance.rs +++ b/crates/annot/src/appearance.rs @@ -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; diff --git a/crates/annot/src/create.rs b/crates/annot/src/create.rs index 5af547970e..7453a157e0 100644 --- a/crates/annot/src/create.rs +++ b/crates/annot/src/create.rs @@ -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)); } diff --git a/crates/annot/src/draw.rs b/crates/annot/src/draw.rs index c0e82eb151..6d5b51adec 100644 --- a/crates/annot/src/draw.rs +++ b/crates/annot/src/draw.rs @@ -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 { + 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, diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rs index 63ff5a5be0..671670afad 100644 --- a/crates/annot/src/lib.rs +++ b/crates/annot/src/lib.rs @@ -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::{ diff --git a/crates/annot/src/modify.rs b/crates/annot/src/modify.rs index 6566337ca1..543ad54b8b 100644 --- a/crates/annot/src/modify.rs +++ b/crates/annot/src/modify.rs @@ -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, 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, 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 = HashSet::from([r]); + let mut seen: HashSet = 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)); diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rs index 2a84263cdd..53d57e6b58 100644 --- a/crates/annot/src/tests.rs +++ b/crates/annot/src/tests.rs @@ -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 = 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::(); + 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 = 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 = 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) { diff --git a/crates/annot/tests/it/properties.rs b/crates/annot/tests/it/properties.rs index ed4ffd07fa..c5d34388b4 100644 --- a/crates/annot/tests/it/properties.rs +++ b/crates/annot/tests/it/properties.rs @@ -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 { diff --git a/crates/automation/README.md b/crates/automation/README.md index 6d835d8d1d..4ccb03904e 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -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 diff --git a/crates/automation/src/a11y.rs b/crates/automation/src/a11y.rs index 2dedaade5b..4d3b467c43 100644 --- a/crates/automation/src/a11y.rs +++ b/crates/automation/src/a11y.rs @@ -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) -> Value { +pub(crate) fn with_warnings(mut out: Value, warnings: Vec) -> Value { if warnings.is_empty() { return out; } diff --git a/crates/automation/src/a11y/documents.rs b/crates/automation/src/a11y/documents.rs index bfc8b3379a..ff72f2623f 100644 --- a/crates/automation/src/a11y/documents.rs +++ b/crates/automation/src/a11y/documents.rs @@ -173,10 +173,31 @@ impl Automation { Ok((old, new)) } + fn compare_pages_arg(&self, a: &Args) -> Result> { + 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 { 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 = 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 { 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 { 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 = if pages.is_empty() { (0..page_count).collect() } else { pages }; + let mut total = 0usize; + let mut all_errors: Vec = 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)) } } diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rs index 4e7d2c491a..707f10985b 100644 --- a/crates/automation/src/comments.rs +++ b/crates/automation/src/comments.rs @@ -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>> { + 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 = q.as_array().ok_or_else(wrong)?.iter().map(|x| x.as_f64()).collect::>().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::>>()? + } + (None, None) => return Ok(None), + }; + Ok(Some(quads)) + } + pub(crate) fn comment_add(&mut self, a: &Args) -> Result { 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 = q.as_array().ok_or_else(wrong)?.iter().map(|x| x.as_f64()).collect::>().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::>>()? - } - (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 } }; diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 539feb0b26..2a4e83cccb 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -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 = 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::>(); let skipped: Vec = 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)) } } diff --git a/crates/automation/src/forms.rs b/crates/automation/src/forms.rs index 035aa49d33..8f19a0e2ed 100644 --- a/crates/automation/src/forms.rs +++ b/crates/automation/src/forms.rs @@ -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 = 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 { + 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 = 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 { let name = a.str("field")?.to_owned(); if !self.doc(a)?.form.iter().any(|f| f.name == name) { diff --git a/crates/automation/src/measure.rs b/crates/automation/src/measure.rs index 932f85ad9a..4cce474936 100644 --- a/crates/automation/src/measure.rs +++ b/crates/automation/src/measure.rs @@ -51,7 +51,17 @@ impl Automation { pub(crate) fn measurement_list(&self, a: &Args) -> Result { 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 = all .measurements .iter() @@ -128,6 +138,12 @@ impl Automation { pub(crate) fn measurement_snap(&self, a: &Args) -> Result { 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); diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 394bc8131a..61285b9a62 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -599,7 +599,7 @@ pub fn tools() -> Vec { 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 { "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 { .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 { 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 { "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 { 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"])), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index bf42019299..9154be186b 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -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::>() + .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( + "", + "

7

\n", + ); + 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( + "", + "

7

\n", + ); + 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 = (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 = 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 = 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::>(), + [("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] diff --git a/crates/automation/tests/it/hostile_args.rs b/crates/automation/tests/it/hostile_args.rs index 6364d232e7..c772d8ffa0 100644 --- a/crates/automation/tests/it/hostile_args.rs +++ b/crates/automation/tests/it/hostile_args.rs @@ -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 { + 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:#?}"); +} diff --git a/crates/edit/src/added/arabic_tests.rs b/crates/edit/src/added/arabic_tests.rs index 0671e3ce32..efd4b95d5c 100644 --- a/crates/edit/src/added/arabic_tests.rs +++ b/crates/edit/src/added/arabic_tests.rs @@ -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())); +} diff --git a/crates/edit/src/added/draw.rs b/crates/edit/src/added/draw.rs index dff0dc4f93..4551ea46f2 100644 --- a/crates/edit/src/added/draw.rs +++ b/crates/edit/src/added/draw.rs @@ -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, ) -> 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) -> Result { + 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::(); + 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::() + 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 = 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, ¶graphs, 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()); diff --git a/crates/edit/src/added/layout.rs b/crates/edit/src/added/layout.rs index cbc9826f8d..d6b30b2787 100644 --- a/crates/edit/src/added/layout.rs +++ b/crates/edit/src/added/layout.rs @@ -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 { if t.font_resource.is_some() { return None; @@ -211,15 +222,17 @@ pub fn first_undrawable(t: &AddedText) -> Option { 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, }) }) diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index 64ff26c164..728c244723 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -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; diff --git a/crates/edit/src/paragraph_spacing_tests.rs b/crates/edit/src/paragraph_spacing_tests.rs index a59d7dbde4..6a22916d12 100644 --- a/crates/edit/src/paragraph_spacing_tests.rs +++ b/crates/edit/src/paragraph_spacing_tests.rs @@ -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() } diff --git a/crates/edit/src/raised_row_tests.rs b/crates/edit/src/raised_row_tests.rs new file mode 100644 index 0000000000..c4ae04ebe3 --- /dev/null +++ b/crates/edit/src/raised_row_tests.rs @@ -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()); +} diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 46613c6ffa..b058b4846f 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -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) -> 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 { + 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 { 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 { + 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(); diff --git a/crates/edit/src/text/lines.rs b/crates/edit/src/text/lines.rs index 8e0d258ec6..bf2e1dd806 100644 --- a/crates/edit/src/text/lines.rs +++ b/crates/edit/src/text/lines.rs @@ -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. diff --git a/crates/edit/src/text_regions/styled.rs b/crates/edit/src/text_regions/styled.rs index ff475f4e22..7ca30b94c9 100644 --- a/crates/edit/src/text_regions/styled.rs +++ b/crates/edit/src/text_regions/styled.rs @@ -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 { - 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); diff --git a/crates/engine/src/bates_files.rs b/crates/engine/src/bates_files.rs new file mode 100644 index 0000000000..b10a418093 --- /dev/null +++ b/crates/engine/src/bates_files.rs @@ -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, 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!("<>", 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)); + } +} diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs index 42d5ba40a8..622859eaed 100644 --- a/crates/engine/src/catalog.rs +++ b/crates/engine/src/catalog.rs @@ -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), ], }], }, diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index d6e5e4ca2d..14fe9b4ce6 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -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"), diff --git a/crates/engine/src/compare.rs b/crates/engine/src/compare.rs index 3daac1ce26..ae46646740 100644 --- a/crates/engine/src/compare.rs +++ b/crates/engine/src/compare.rs @@ -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) { + let mut out: Vec<[f64; 4]> = Vec::new(); + let mut pages: Vec = 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 { + 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 { @@ -39,10 +94,19 @@ impl crate::Document { /// Every word of the document in reading order, with page and box. pub fn words(&self) -> Vec { + 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 { 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 { + 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 { 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 { - 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, 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, 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 { 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> = + 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 = 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 = + 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 = 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 { + 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())); + } +} diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index cf3b004ed8..bc2a501fcd 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -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 { self.editor.as_ref().map(|e| pdfcraft_model::pages(&e.cos).iter().map(|p| p.user_unit(&e.cos)).collect()).unwrap_or_default() diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index 17bd69c92a..2a763696f2 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -267,6 +267,13 @@ pub enum Edit { rect: Option<[f64; 4]>, open: Option, }, + /// 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, }, + /// 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, + 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, }, diff --git a/crates/engine/src/edit/labels.rs b/crates/engine/src/edit/labels.rs index 51d19043e4..24a40f0689 100644 --- a/crates/engine/src/edit/labels.rs +++ b/crates/engine/src/edit/labels.rs @@ -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"), diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index abeeeae8ac..0cef31fd80 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -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. diff --git a/crates/engine/src/field_table.rs b/crates/engine/src/field_table.rs index f3fd96551e..833312129d 100644 --- a/crates/engine/src/field_table.rs +++ b/crates/engine/src/field_table.rs @@ -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 { + 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(); diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 8c5578221d..ac6b138c7a 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -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 { .. } diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs index df6b8aa943..4da66c8ecd 100644 --- a/crates/engine/src/js.rs +++ b/crates/engine/src/js.rs @@ -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; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 91093b7e5e..84d4ce702f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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}; diff --git a/crates/engine/src/mark_picture.rs b/crates/engine/src/mark_picture.rs new file mode 100644 index 0000000000..d104eed314 --- /dev/null +++ b/crates/engine/src/mark_picture.rs @@ -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 { + guard(|| render(f, max_side))? +} + +fn render(f: &MarkFile, max_side: u32) -> Result { + // 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 { + 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::>(); + Pixels::from(words) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png(w: u32, h: u32, px: impl Fn(u32, u32) -> [u8; 4]) -> Vec { + let data: Vec = (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, 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]); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d99266b412..10f0e8cb02 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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::>().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#""#; + 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> { + 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 = 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| { diff --git a/crates/engine/src/text_preview.rs b/crates/engine/src/text_preview.rs index c961de4532..c0dd1f6f47 100644 --- a/crates/engine/src/text_preview.rs +++ b/crates/engine/src/text_preview.rs @@ -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, replace_backdrops: bool) -> Result { + guard(|| { + let editor = self.editor.as_ref().ok_or("the document can't be read")?; + let mut cos = editor.cos.clone(); + let all: Vec = (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`]. diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml index bbc76266b3..0607f1811f 100644 --- a/crates/export/Cargo.toml +++ b/crates/export/Cargo.toml @@ -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 diff --git a/crates/forms/src/author.rs b/crates/forms/src/author.rs index f347909b58..ced26f996e 100644 --- a/crates/forms/src/author.rs +++ b/crates/forms/src/author.rs @@ -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::{ diff --git a/crates/forms/src/author/copy.rs b/crates/forms/src/author/copy.rs new file mode 100644 index 0000000000..2d09e2ec99 --- /dev/null +++ b/crates/forms/src/author/copy.rs @@ -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 { + 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) -> Option> { + 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) { + 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 { + 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, 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) { + 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 { + 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 = 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 = 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, + place: Place, +) -> Result { + 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) -> Result { + 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 { + 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) +} diff --git a/crates/forms/src/author/lifecycle.rs b/crates/forms/src/author/lifecycle.rs index b2de1321a0..92a9309b95 100644 --- a/crates/forms/src/author/lifecycle.rs +++ b/crates/forms/src/author/lifecycle.rs @@ -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, Option) { (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 { + 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 diff --git a/crates/forms/src/author/tree.rs b/crates/forms/src/author/tree.rs index 55b84fa390..8ae4ab2a65 100644 --- a/crates/forms/src/author/tree.rs +++ b/crates/forms/src/author/tree.rs @@ -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)); diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 7c970c73ff..0d40349764 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -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::{ diff --git a/crates/forms/src/scripting.rs b/crates/forms/src/scripting.rs index 2ac70155c0..cad6ff026f 100644 --- a/crates/forms/src/scripting.rs +++ b/crates/forms/src/scripting.rs @@ -40,7 +40,8 @@ pub struct FieldChange { /// Optional exact object target for malformed forms with duplicate field names. pub object: Option, pub value: Option>, - /// 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, pub required: Option, diff --git a/crates/forms/src/table.rs b/crates/forms/src/table.rs index ae565052fc..3e886391c6 100644 --- a/crates/forms/src/table.rs +++ b/crates/forms/src/table.rs @@ -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. diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index 759747f8a5..4230424893 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -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 = 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 = 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 = 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 = 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, 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::>(), ["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::>(), [("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, ©); + 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, ©); + 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, ©); + 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, ©); + 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 = 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), ©).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), ©).obj).as_dict().cloned().unwrap(); + assert_eq!(c.name(b"DV"), Some(&b"Off"[..]), "no copied button is /S"); + set_value(&mut doc, ©, &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, ©).value.iter().all(|v| v == "Off"), "the copy is reset to off: {:?}", field(&all, ©).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), ©).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), ©).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, ©).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 = 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), ©).obj).as_dict().cloned().unwrap(); + let keys: Vec = 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, ©); + 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 { + 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), ©)), 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, ©, &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, ©)), 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 = 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, ©)); + 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"); +} diff --git a/crates/forms/src/values.rs b/crates/forms/src/values.rs index a26ea42210..de2b4674dd 100644 --- a/crates/forms/src/values.rs +++ b/crates/forms/src/values.rs @@ -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) } diff --git a/crates/js/src/document.rs b/crates/js/src/document.rs index 3e754761c8..c89cffff69 100644 --- a/crates/js/src/document.rs +++ b/crates/js/src/document.rs @@ -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, token: u64) fn set(_: &JsValue, args: &[JsValue], name: &FieldKey, c: &mut Context) -> JsResult { 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())) diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 6e41a514d5..d2aabba150 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -249,12 +249,24 @@ pub(crate) fn read(ctx: &Context, name: &FieldKey) -> JsResult { } 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) -> 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 { 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 { diff --git a/crates/js/src/model.rs b/crates/js/src/model.rs index eef92712cd..af91476fa2 100644 --- a/crates/js/src/model.rs +++ b/crates/js/src/model.rs @@ -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, - /// 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, /// The messages the script showed, in order. pub alerts: Vec, diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs index 0b2e425f8b..a675b1461f 100644 --- a/crates/js/src/tests.rs +++ b/crates/js/src/tests.rs @@ -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`. diff --git a/crates/js/src/xfa/globals.rs b/crates/js/src/xfa/globals.rs index 152726def9..10330031d0 100644 --- a/crates/js/src/xfa/globals.rs +++ b/crates/js/src/xfa/globals.rs @@ -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" diff --git a/crates/organize/src/boxes.rs b/crates/organize/src/boxes.rs index f947d2abee..70377cf3e6 100644 --- a/crates/organize/src/boxes.rs +++ b/crates/organize/src/boxes.rs @@ -93,6 +93,23 @@ pub fn page_boxes(doc: &Document) -> Result, 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; 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)?; diff --git a/crates/organize/src/lib.rs b/crates/organize/src/lib.rs index fd115ff013..f9aa850b7d 100644 --- a/crates/organize/src/lib.rs +++ b/crates/organize/src/lib.rs @@ -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::{ diff --git a/crates/preflight/Cargo.toml b/crates/preflight/Cargo.toml index 6cf3ac467f..d3e41924fc 100644 --- a/crates/preflight/Cargo.toml +++ b/crates/preflight/Cargo.toml @@ -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 } diff --git a/crates/render/tests/object_load_logging.rs b/crates/render/tests/object_load_logging.rs new file mode 100644 index 0000000000..24002a9bc1 --- /dev/null +++ b/crates/render/tests/object_load_logging.rs @@ -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> = 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 { + // 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 { + 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 { + 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 { + // 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 { + 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 { + 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 { + encrypted_stream_fixture(count, false) +} + +/// Build encrypted compressed references, optionally replacing containers with malformed streams. +fn encrypted_stream_fixture(count: usize, broken: bool) -> Vec { + 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 { + 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()); + } +} diff --git a/crates/sign/Cargo.toml b/crates/sign/Cargo.toml index 56332ed3bd..80076527f4 100644 --- a/crates/sign/Cargo.toml +++ b/crates/sign/Cargo.toml @@ -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 } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d6d4a5fb57..875311e3bc 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -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); diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 3e0904f132..8dcbcaabc9 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -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 { + 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"); + } } diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 03f8b8c203..5caff6b89f 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -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). diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 17ca59a4c8..8f676c3508 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -45,6 +45,13 @@ impl PdfCraftApp { ("show_page_edge_shadows", _) => { self.show_page_edge_shadows = value.parse::().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::().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, diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index a88a10c2a1..6d43665c62 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -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) { diff --git a/crates/ui-egui/src/app/metal_fullscreen.rs b/crates/ui-egui/src/app/metal_fullscreen.rs new file mode 100644 index 0000000000..31786cc240 --- /dev/null +++ b/crates/ui-egui/src/app/metal_fullscreen.rs @@ -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, latency: Option, is_metal: impl FnOnce() -> bool) -> Option { + 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); + } + } +} diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index ca53c89ea6..c9e9650e7e 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -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; } diff --git a/crates/ui-egui/src/app/settings.rs b/crates/ui-egui/src/app/settings.rs index 7608e2aedb..74aeea56ad 100644 --- a/crates/ui-egui/src/app/settings.rs +++ b/crates/ui-egui/src/app/settings.rs @@ -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, pub units: Option, + pub show_page_boxes: Option, pub always_default_view: Option, pub show_form_field_reminder: Option, pub highlight_fields: Option, @@ -98,6 +99,7 @@ pub struct Behavior { pub fill_text_size: Option, pub fill_text_color: Option<[f64; 3]>, pub show_page_edge_shadows: Option, + pub show_rulers: Option, pub fill_text_border: Option, pub fill_text_border_shape: Option, /// Absent is "the text's colour": TOML has no null. @@ -661,6 +663,7 @@ pub fn import_json(text: &str) -> (PdfCraftSettings, Vec) { 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) { 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"), diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 519722f97e..e814002175 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -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>, 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, /// 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, /// 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, form: Arc>, 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); } diff --git a/crates/ui-egui/src/canvas/bars.rs b/crates/ui-egui/src/canvas/bars.rs index d309b6f7c7..7c233b2694 100644 --- a/crates/ui-egui/src/canvas/bars.rs +++ b/crates/ui-egui/src/canvas/bars.rs @@ -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); diff --git a/crates/ui-egui/src/canvas/crop.rs b/crates/ui-egui/src/canvas/crop.rs index ed7b302554..8b256efee7 100644 --- a/crates/ui-egui/src/canvas/crop.rs +++ b/crates/ui-egui/src/canvas/crop.rs @@ -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 { +/// 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] { diff --git a/crates/ui-egui/src/canvas/page_menu.rs b/crates/ui-egui/src/canvas/page_menu.rs index d6c4ab4b58..5a61b218ef 100644 --- a/crates/ui-egui/src/canvas/page_menu.rs +++ b/crates/ui-egui/src/canvas/page_menu.rs @@ -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)); } diff --git a/crates/ui-egui/src/canvas/page_tools.rs b/crates/ui-egui/src/canvas/page_tools.rs index b9a5852cbf..b08490ccc5 100644 --- a/crates/ui-egui/src/canvas/page_tools.rs +++ b/crates/ui-egui/src/canvas/page_tools.rs @@ -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, - /// The Crop tool's drawn rectangle, which the page body turns into the crop edit. - pub(crate) crop: Option, + /// 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, /// Fill & Sign asked for a signature (`false`) or initials (`true`) before it can place one. pub(crate) open_signature: Option, /// 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) diff --git a/crates/ui-egui/src/canvas/pictures.rs b/crates/ui-egui/src/canvas/pictures.rs index 0e887ce6ee..6f9e80aa94 100644 --- a/crates/ui-egui/src/canvas/pictures.rs +++ b/crates/ui-egui/src/canvas/pictures.rs @@ -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>, 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) -> 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] diff --git a/crates/ui-egui/src/canvas/rulers.rs b/crates/ui-egui/src/canvas/rulers.rs new file mode 100644 index 0000000000..3f5351b7f2 --- /dev/null +++ b/crates/ui-egui/src/canvas/rulers.rs @@ -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) { + 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 { + 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, +) { + 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 = 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); + } +} diff --git a/crates/ui-egui/src/canvas/scroll_speed.rs b/crates/ui-egui/src/canvas/scroll_speed.rs index 02d26389ac..2ebe5780a2 100644 --- a/crates/ui-egui/src/canvas/scroll_speed.rs +++ b/crates/ui-egui/src/canvas/scroll_speed.rs @@ -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::ALL.into_iter().find(|s| s.label().eq_ignore_ascii_case(value)) } diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index dd2f6deabd..d3711789f0 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -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> { + 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 { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index babb1ef5d0..59d0ee91bb 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -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(); diff --git a/crates/ui-egui/src/chrome/doc_tabs.rs b/crates/ui-egui/src/chrome/doc_tabs.rs index 1563c8e8d9..6c5aa66c5d 100644 --- a/crates/ui-egui/src/chrome/doc_tabs.rs +++ b/crates/ui-egui/src/chrome/doc_tabs.rs @@ -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, _| 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); } } } diff --git a/crates/ui-egui/src/chrome/mode_bar.rs b/crates/ui-egui/src/chrome/mode_bar.rs index 4134cf7f7d..8940a5e9a7 100644 --- a/crates/ui-egui/src/chrome/mode_bar.rs +++ b/crates/ui-egui/src/chrome/mode_bar.rs @@ -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)) diff --git a/crates/ui-egui/src/chrome/view_rail.rs b/crates/ui-egui/src/chrome/view_rail.rs index ad0f464ca1..f0dd5c06a6 100644 --- a/crates/ui-egui/src/chrome/view_rail.rs +++ b/crates/ui-egui/src/chrome/view_rail.rs @@ -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. diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index 9cb58b91c2..4b58861060 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -68,6 +68,27 @@ pub(crate) fn chord_label(ctx: &egui::Context, id: &str) -> Option { 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"); + } } diff --git a/crates/ui-egui/src/commands/catalog.rs b/crates/ui-egui/src/commands/catalog.rs index 79c0308f2a..3a04b8ba61 100644 --- a/crates/ui-egui/src/commands/catalog.rs +++ b/crates/ui-egui/src/commands/catalog.rs @@ -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 { "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(), diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index f79d2a1729..651a92f9e0 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -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==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. diff --git a/crates/ui-egui/src/control/host.rs b/crates/ui-egui/src/control/host.rs index 39f04746e3..0dde19a2c9 100644 --- a/crates/ui-egui/src/control/host.rs +++ b/crates/ui-egui/src/control/host.rs @@ -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::>(), // Pages cut at the renderer's limits (#623), 1-based. "cut_pages": v.cut_pages().iter().map(|p| p + 1).collect::>(), @@ -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, diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8db45e220c..e5784c0223 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -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; diff --git a/crates/ui-egui/src/dialogs/bates_files_ui.rs b/crates/ui-egui/src/dialogs/bates_files_ui.rs new file mode 100644 index 0000000000..b81be38569 --- /dev/null +++ b/crates/ui-egui/src/dialogs/bates_files_ui.rs @@ -0,0 +1,375 @@ +//! Bates numbering ▸ Add to files…: numbers several files as one run, in list order, each file +//! starting after the last number of the one before. It writes numbered copies and never changes +//! the originals. Nothing is written unless every file can be numbered, and no copy replaces a +//! file. The numbering rules are the engine's ([`pdfcraft_engine::BatesFormat`]). + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use craft::host::{PickRequest, WriteIntent}; +use craft::theme::variant::Tone; +use craft::ui::contract::{Bind, Show as _}; +use craft::ui::dialog::dialog_id; +use craft::ui::display::{Shade, Text}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; +use pdfcraft_engine::{BATES_MAX_BYTES, BATES_MAX_FILES, BatesError, BatesFormat, EditError, Session}; +use pdfcraft_render::OpenError; + +use crate::PdfCraftApp; + +/// The dialog's key. +const KEY: &str = "edit.bates_files"; +/// The header and footer boxes, in [`BatesFormat::position`] order. +const POSITIONS: [&str; 6] = ["Top left", "Top center", "Top right", "Bottom left", "Bottom center", "Bottom right"]; +/// Characters a copy name's ending can't hold on any desktop system. +const NOT_IN_NAMES: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|']; + +/// What the dialog's fields ask for. +struct Request { + files: Vec, + format: BatesFormat, + ending: String, + /// Whether the copies go in a folder picked after OK, instead of beside each original. + to_folder: bool, +} + +impl Request { + fn read(fields: &DialogFields) -> Self { + let files = fields + .list("files") + .map(|items| items.iter().filter_map(|item| if let FieldValue::Text(path) = item { Some(PathBuf::from(path)) } else { None }).collect()) + .unwrap_or_default(); + let int = |key, default| fields.int(key).unwrap_or(default); + let format = BatesFormat { + start: u64::try_from(int("start", 1)).unwrap_or(0), + digits: u8::try_from(int("digits", 6)).unwrap_or(0), + prefix: fields.text("prefix").unwrap_or_default().to_owned(), + suffix: fields.text("suffix").unwrap_or_default().to_owned(), + position: fields.text("position").and_then(|p| p.parse().ok()).unwrap_or(5), + }; + let ending = fields.text("ending").unwrap_or_default().to_owned(); + Request { files, format, ending, to_folder: fields.text("place") == Some("folder") } + } + + /// Why OK can't run yet, if it can't. + fn refusal(&self) -> Option { + if self.files.is_empty() { + return Some(tl!("Add the files to number.").to_owned()); + } + if self.files.len() > BATES_MAX_FILES { + return Some(too_many()); + } + if let Err(error) = self.format.check() { + return Some(format_problem(&error)); + } + if self.ending.contains(NOT_IN_NAMES) || self.ending.chars().any(char::is_control) { + return Some(tl!("The name ending can't contain / \\ : * ? \" < > |").to_owned()); + } + if self.ending.is_empty() && !self.to_folder { + return Some(tl!("Copies beside the originals need a name ending, so they don't replace them.").to_owned()); + } + None + } +} + +fn too_many() -> String { + crate::i18n::fmt(tl!("A run numbers at most {n} files."), &[("n", &BATES_MAX_FILES.to_string())]) +} + +/// What is wrong with a format, in the UI language. +fn format_problem(error: &BatesError) -> String { + match error { + BatesError::Start => tl!("The start number must be at least 1.").to_owned(), + BatesError::Digits => tl!("The number of digits must be from 1 to 12.").to_owned(), + BatesError::Affix => tl!("The prefix and suffix can have at most 128 characters, and no # or >>.").to_owned(), + BatesError::Position => tl!("Choose where the number goes.").to_owned(), + BatesError::Count => too_many(), + BatesError::NoPages(_) | BatesError::Overflow(_) => error.to_string(), + } +} + +/// The dialog over the values: OK waits for files and a format the Bates number can carry, and the +/// first number is shown as the page will. +fn dialog(fields: &mut DialogFields, open: Vec) -> ParamDialog<'_> { + let request = Request::read(fields); + let refusal = request.refusal(); + let first = request.format.check().ok().map(|()| request.format.label(request.format.start)); + let positions = POSITIONS.iter().enumerate().map(|(i, name)| (i.to_string(), tl!(name).into())).collect(); + let places = vec![("beside".to_owned(), tl!("Beside each original").into()), ("folder".to_owned(), tl!("In a folder I choose").into())]; + let params = vec![ + Param::files("files", tl!("Files, numbered in this order")).open_files(open), + Param::new("prefix", tl!("Prefix"), ParamKind::text("")), + Param::new("start", tl!("Start number"), ParamKind::int(Some(1), None, 1)), + Param::new("digits", tl!("Digits"), ParamKind::int(Some(1), Some(i64::from(pdfcraft_engine::BATES_MAX_DIGITS)), 6)), + Param::new("suffix", tl!("Suffix"), ParamKind::text("")), + Param::new("position", tl!("Position"), ParamKind::choice(positions, Some("5".into()))), + Param::new("ending", tl!("Copy name ending"), ParamKind::text("_Bates")), + Param::new("place", tl!("Save copies"), ParamKind::choice(places, Some("beside".into()))), + ]; + let shown = refusal.clone(); + let mut dialog = ParamDialog::new(KEY, tl!("Add Bates Numbering to Files"), params) + .values(Bind::bound(fields)) + .ok_label(tl!("Number").into()) + .ok_enabled(refusal.is_none()) + .below(move |ui, _| { + if let Some(line) = &shown { + Text::new(line.clone()).tone(Tone::Bad).show(ui); + } else if let Some(first) = &first { + Text::new(crate::i18n::fmt(tl!("The first page is numbered {label}."), &[("label", first)])).shade(Shade::Muted).show(ui); + } + Text::new(tl!("Numbered copies are written; the original files are not changed.")).show(ui); + }); + if let Some(reason) = refusal { + dialog = dialog.ok_reason(reason.into()); + } + dialog +} + +/// A file numbered and ready to write. +struct Numbered { + target: PathBuf, + bytes: Arc>, +} + +/// The size of `path`, when it is a file on a disk this process can see. +fn size_on_disk(path: &Path) -> Option { + std::fs::metadata(path).ok().filter(std::fs::Metadata::is_file).map(|meta| meta.len()) +} + +/// The run's bytes after `read` and `len` more, if they stay within `max_bytes`. +fn within(read: u64, len: u64, max_bytes: u64) -> Option { + read.checked_add(len).filter(|total| *total <= max_bytes) +} + +fn name_of(path: &Path) -> String { + path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned()) +} + +/// Where each copy goes: `.pdf` beside its original, or in `folder`. +fn targets(files: &[PathBuf], ending: &str, folder: Option<&Path>) -> Vec { + files + .iter() + .map(|source| { + let stem = source.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let dir = folder.map_or_else(|| source.parent().map(Path::to_path_buf).unwrap_or_default(), Path::to_path_buf); + dir.join(format!("{stem}{ending}.pdf")) + }) + .collect() +} + +/// A path as compared for "the same file": letter case is ignored, as on Windows and macOS. +fn same_key(path: &Path) -> String { + path.to_string_lossy().to_lowercase() +} + +impl PdfCraftApp { + /// Bates numbering ▸ Add to files…: the dialog, offering the open documents' files. + pub(crate) fn open_bates_files(&mut self, ctx: &egui::Context) { + let open: Vec = self.session.docs().iter().filter_map(|d| d.path.as_ref().map(PathBuf::from)).collect(); + let dialog = HostedParamDialog::new(ctx, KEY, DialogFields::new(), move |fields| dialog(fields, open.clone())); + crate::dialogs::host::open(self, dialog); + } + + /// Takes the dialog's answer: Number writes the copies, after asking for the folder when they + /// go in one. + pub(crate) fn bates_files_pass(&mut self, _ctx: &egui::Context) { + let Some(answer) = self.dialogs.take_by_id::(dialog_id(KEY)) else { return }; + let Some(result) = answer.ok() else { return }; + let request = Request::read(&result.fields); + if let Some(reason) = request.refusal() { + self.notify(reason); + return; + } + if request.to_folder { + let pick = PickRequest::folder("edit.bates_files").title(tl!("Choose a folder for the numbered copies")); + self.pick_file(pick, None, move |app, _, picked| { + if let Some(dir) = picked.first_path() { + app.number_files(&request, Some(&dir)); + } + }); + } else { + self.number_files(&request, None); + } + } + + /// Numbers `request`'s files and writes the copies, or writes nothing and says why. + fn number_files(&mut self, request: &Request, folder: Option<&Path>) { + let targets = targets(&request.files, &request.ending, folder); + let numbered = self.refuse_targets(&request.files, &targets).and_then(|()| self.number_all(request, targets, BATES_MAX_BYTES)); + let (numbered, first, last) = match numbered { + Ok(done) => done, + Err(reason) => { + self.notify(crate::i18n::fmt(tl!("Nothing was numbered: {reason}"), &[("reason", &reason)])); + return; + } + }; + for (done, file) in numbered.iter().enumerate() { + if let Err(e) = self.host.files().write(&file.target, &file.bytes, WriteIntent::SaveAs) { + let (n, total) = (done.to_string(), numbered.len().to_string()); + let args = [("n", n.as_str()), ("total", total.as_str()), ("name", &name_of(&file.target)), ("e", &e.to_string())]; + self.notify_fmt("Wrote {n} of {total} numbered copies; couldn't write {name}: {e}", &args); + return; + } + } + let n = numbered.len().to_string(); + let next = last.checked_add(1).map_or_else(|| tl!("none").to_owned(), |next| next.to_string()); + let (first, last) = (request.format.label(first), request.format.label(last)); + let args = [("n", n.as_str()), ("first", &first), ("last", &last), ("next", &next)]; + // The next number is what a following run starts from, so the series can go on. + self.notify_fmt("Numbered {n} files from {first} to {last}. The next start number is {next}.", &args); + } + + /// Refuses a copy that would land on an original, on another copy, or on a file that exists. + fn refuse_targets(&self, files: &[PathBuf], targets: &[PathBuf]) -> Result<(), String> { + let sources: HashSet = files.iter().map(|p| same_key(p)).collect(); + let mut taken = HashSet::new(); + for target in targets { + let name = name_of(target); + if sources.contains(&same_key(target)) { + return Err(crate::i18n::fmt(tl!("the copy {name} would replace an original"), &[("name", &name)])); + } + if !taken.insert(same_key(target)) { + return Err(crate::i18n::fmt(tl!("two copies would be named {name}"), &[("name", &name)])); + } + if self.host.files().exists(target) { + return Err(crate::i18n::fmt(tl!("{name} already exists"), &[("name", &name)])); + } + } + Ok(()) + } + + /// Reads and numbers every file in a session of its own, so no tab opens, refusing the run once + /// its sources come to more than `max_bytes`. Gives the copies and the run's first and last numbers. + fn number_all(&self, request: &Request, targets: Vec, max_bytes: u64) -> Result<(Vec, u64, u64), String> { + let mut session = Session::new(); + let mut ids = Vec::with_capacity(request.files.len()); + let mut read = 0u64; + for source in &request.files { + ids.push(self.open_source(&mut session, source, &mut read, max_bytes)?); + } + let pages: Vec = ids.iter().map(|&id| session.get(id).map_or(0, |d| d.info.pages.len())).collect(); + let name = |index: usize| request.files.get(index).map(|p| name_of(p)).unwrap_or_default(); + let spans = request.format.spans(&pages).map_err(|error| match error { + BatesError::NoPages(i) => crate::i18n::fmt(tl!("{name} has no pages"), &[("name", &name(i))]), + BatesError::Overflow(i) => crate::i18n::fmt(tl!("the numbers run out at {name}"), &[("name", &name(i))]), + other => other.to_string(), + })?; + let mut numbered = Vec::with_capacity(ids.len()); + for (index, ((&id, span), target)) in ids.iter().zip(&spans).zip(targets).enumerate() { + let failed = |e: EditError| crate::i18n::fmt(tl!("couldn't number {name}: {e}"), &[("name", &name(index)), ("e", &e.to_string())]); + session.add_bates(id, &request.format, span.first).map_err(failed)?; + let bytes = session.save_full_bytes(id).map_err(failed)?; + session.check_save(id, &bytes).map_err(failed)?; + numbered.push(Numbered { target, bytes }); + } + let first = spans.first().map_or(request.format.start, |s| s.first); + let last = spans.last().map_or(first, |s| s.last); + Ok((numbered, first, last)) + } + + /// Opens `source` in `session`, refusing a file that can't be read, needs a password or is + /// signed (numbering would break its signature), or that takes the run's bytes in `read` past + /// `max_bytes`. + fn open_source(&self, session: &mut Session, source: &Path, read: &mut u64, max_bytes: u64) -> Result { + let name = name_of(source); + // The sources, their documents and the copies are all held until the copies are written. + let too_big = || { + let mb = (max_bytes / (1024 * 1024)).to_string(); + crate::i18n::fmt(tl!("the files come to more than {n} MB at {name}"), &[("n", &mb), ("name", &name)]) + }; + // A file on this machine's disk is measured before it is read, so an oversized one is + // never loaded. A host with no such disk (the browser) is checked on the bytes it gives. + if size_on_disk(source).is_some_and(|len| within(*read, len, max_bytes).is_none()) { + return Err(too_big()); + } + let bytes = self + .host + .files() + .read(source) + .map_err(|e| crate::i18n::fmt(tl!("couldn't read {name}: {e}"), &[("name", &name), ("e", &e.to_string())]))?; + *read = u64::try_from(bytes.len()).ok().and_then(|len| within(*read, len, max_bytes)).ok_or_else(too_big)?; + let id = session.open(name.clone(), None, Arc::new(bytes), None).map_err(|e| match e { + OpenError::NeedsPassword | OpenError::WrongPassword => crate::i18n::fmt(tl!("{name} is password-protected"), &[("name", &name)]), + other => crate::i18n::fmt(tl!("couldn't open {name}: {e}"), &[("name", &name), ("e", &other.to_string())]), + })?; + if session.get(id).is_some_and(pdfcraft_engine::Document::is_signed) { + return Err(crate::i18n::fmt(tl!("{name} is signed, and numbering it would break the signature"), &[("name", &name)])); + } + Ok(id) + } +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use craft::host::{Host, ScriptedFiles}; + + use super::*; + + /// A request for `files` that passes every other check. + fn request(files: Vec) -> Request { + let format = BatesFormat { start: 1, digits: 6, prefix: String::new(), suffix: String::new(), position: 5 }; + Request { files, format, ending: "_Bates".into(), to_folder: false } + } + + /// The app over a host holding only `files` in memory. + fn app(files: ScriptedFiles) -> PdfCraftApp { + PdfCraftApp::for_unit_tests_on(Arc::new(Host::builder(crate::APP_INFO).files(Arc::new(files)).build())) + } + + /// A file of `len` bytes named `name` in a folder of `test`'s own, with the folder. + fn on_disk(test: &str, name: &str, len: usize) -> (PathBuf, PathBuf) { + let dir = std::env::temp_dir().join(format!("pdfcraft-bates-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(name); + std::fs::write(&path, vec![0u8; len]).unwrap(); + (dir, path) + } + + /// Numbers `source` alone, refusing past `max_bytes`, and gives why it stopped. + fn refusal_for(app: &PdfCraftApp, source: &Path, max_bytes: u64) -> String { + let request = request(vec![source.to_path_buf()]); + let targets = targets(&request.files, &request.ending, None); + app.number_all(&request, targets, max_bytes).err().expect("the run is refused") + } + + #[test] + fn a_run_of_more_files_than_the_cap_is_refused_before_anything_is_read() { + let files = |n| (0..n).map(|i| PathBuf::from(format!("{i}.pdf"))).collect(); + assert_eq!(request(files(BATES_MAX_FILES)).refusal(), None, "a run of exactly the cap goes ahead"); + assert_eq!(request(files(BATES_MAX_FILES + 1)).refusal(), Some(too_many())); + } + + #[test] + fn a_file_on_disk_past_the_byte_cap_is_refused_without_being_read() { + let (dir, big) = on_disk("past", "big.pdf", 64); + // The host holds no bytes for the file, so reading it would fail with a different reason. + let reason = refusal_for(&app(ScriptedFiles::new()), &big, 63); + std::fs::remove_dir_all(dir).unwrap(); + assert!(reason.contains("more than") && reason.contains("big.pdf"), "{reason}"); + } + + #[test] + fn a_file_on_disk_exactly_at_the_byte_cap_is_read() { + let (dir, full) = on_disk("at", "full.pdf", 64); + // Not a PDF: the run gets past the cap and stops at opening it. + let reason = refusal_for(&app(ScriptedFiles::new().with_file(&full, [0u8; 64])), &full, 64); + std::fs::remove_dir_all(dir).unwrap(); + assert!(reason.contains("couldn't open full.pdf"), "{reason}"); + } + + #[test] + fn bytes_from_a_host_without_a_disk_are_held_to_the_cap_once_read() { + let path = Path::new("not-on-disk").join("big.pdf"); + let reason = refusal_for(&app(ScriptedFiles::new().with_file(&path, [0u8; 64])), &path, 63); + assert!(reason.contains("more than") && reason.contains("big.pdf"), "{reason}"); + } + + #[test] + fn the_running_total_stops_at_the_cap_and_never_wraps() { + assert_eq!(within(0, 64, 64), Some(64)); + assert_eq!(within(1, 64, 64), None); + assert_eq!(within(u64::MAX, 1, u64::MAX), None); + } +} diff --git a/crates/ui-egui/src/dialogs/host.rs b/crates/ui-egui/src/dialogs/host.rs index d755f0d2d8..f10f287ed5 100644 --- a/crates/ui-egui/src/dialogs/host.rs +++ b/crates/ui-egui/src/dialogs/host.rs @@ -61,6 +61,7 @@ fn results(app: &mut PdfCraftApp, ctx: &egui::Context) { app.about_pass(ctx); app.pin_tools_pass(ctx); app.marks_pass(ctx); + app.bates_files_pass(ctx); app.printer_marks_pass(ctx); app.convert_colours_pass(ctx); app.fix_hairlines_pass(ctx); diff --git a/crates/ui-egui/src/dialogs/marks_picture.rs b/crates/ui-egui/src/dialogs/marks_picture.rs new file mode 100644 index 0000000000..9c5ec10852 --- /dev/null +++ b/crates/ui-egui/src/dialogs/marks_picture.rs @@ -0,0 +1,245 @@ +//! Source ▸ File's picture in the watermark and background preview: rendered off the UI thread +//! the way OK brings the file in ([`pdfcraft_engine::mark_picture`]), laid out where OK puts it, +//! and drawn on top of the page or behind it. + +use std::sync::{Arc, Mutex}; + +use craft::host::queue::{JobQueue, Priority}; +use egui::emath::Rot2; +use egui::{Color32, Rect, pos2, vec2}; +use pdfcraft_engine::{DocId, MarkKind, UnmarkedPages}; + +/// Pixels along the longer side of the picture as rendered for the preview, whose page is at +/// most 190 points across: sharp on a screen of more than twice that density. +pub(super) const PICTURE_SIDE: u32 = 512; + +/// The picture as the engine rendered it, checked: made on a job, uploaded on the UI thread. +pub(super) struct Rendered { + picture: pdfcraft_engine::MarkPicture, + pixels: [usize; 2], +} + +impl Rendered { + /// A raster that doesn't add up, or is larger than asked for, is refused, never uploaded. + pub(super) fn new(picture: pdfcraft_engine::MarkPicture) -> Result { + let [w, h] = [picture.width, picture.height].map(|v| v as usize); + // A pixel over for rounding. + let side = PICTURE_SIDE as usize + 1; + if w == 0 || h == 0 || w > side || h > side { + return Err(format!("the picture came back {w}×{h} pixels")); + } + if w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(picture.rgba.len()) { + return Err("the picture came back incomplete".into()); + } + Ok(Self { picture, pixels: [w, h] }) + } +} + +/// The picture, uploaded. +#[derive(Clone)] +pub(super) struct Picture { + tex: egui::TextureHandle, + /// Its size in points, which OK fits to the page. + size: (f64, f64), +} + +impl Picture { + pub(super) fn upload(ctx: &egui::Context, r: Rendered) -> Self { + let image = crate::canvas::texture_image(r.pixels, r.picture.rgba); + let tex = ctx.load_texture("mark-file-picture", image, egui::TextureOptions::LINEAR); + Self { tex, size: r.picture.size } + } +} + +/// The file (by identity) and page (0-based) a picture is rendered for. +#[derive(Clone)] +pub(super) struct FileKey { + pub(super) bytes: Arc>, + pub(super) page: usize, +} + +impl PartialEq for FileKey { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.bytes, &other.bytes) && self.page == other.page + } +} + +impl Eq for FileKey {} + +impl std::hash::Hash for FileKey { + fn hash(&self, h: &mut H) { + Arc::as_ptr(&self.bytes).hash(h); + self.page.hash(h); + } +} + +/// Where the preview draws the picture: over the page; behind its content, over white paper and +/// under the page on a transparent sheet ([`Glass`]), which covers it wherever the page paints; +/// or not at all, because the page's own backdrop will hide it after OK. +#[derive(Clone, Copy)] +pub(super) enum Layer { + Over, + Behind(egui::TextureId), + Hidden, +} + +/// A picture mark as OK draws it: its scale relative to the page, its turn (degrees +/// counter-clockwise), its offset from the page centre (points, right and up) and its opacity. +#[derive(Clone, Copy)] +pub(super) struct PictureMark<'a> { + pub(super) picture: &'a Picture, + pub(super) scale: f64, + pub(super) rotation: f64, + pub(super) offset: [f64; 2], + pub(super) opacity: f64, +} + +impl<'a> PictureMark<'a> { + /// Laid out on the page drawn as `page`, at `s` pixels a point, where `picture` in + /// `pdfcraft-edit` puts it: fitted to the page at its scale, centred plus its offset, turned. + fn place(self, page: Rect, s: f32) -> Placed<'a> { + let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; + let (w, h) = (f64::from(page.width() / s), f64::from(page.height() / s)); + let (sw, sh) = (self.picture.size.0.max(0.01), self.picture.size.1.max(0.01)); + let k = (w / sw).min(h / sh) * if self.scale.is_finite() && self.scale > 0.0 { self.scale } else { 1.0 }; + let centre = page.center() + vec2(finite(self.offset[0]) as f32 * s, -finite(self.offset[1]) as f32 * s); + Placed { + picture: self.picture, + rect: Rect::from_center_size(centre, vec2((sw * k) as f32 * s, (sh * k) as f32 * s)), + // Counter-clockwise on the page is clockwise-negative on screen. + turn: Rot2::from_angle(-(finite(self.rotation) as f32).to_radians()), + opacity: if self.opacity.is_finite() { self.opacity.clamp(0.0, 1.0) as f32 } else { 1.0 }, + } + } + + /// Draws the mark on the page drawn as `page` at `s` pixels a point, with `painter`, kept to + /// the page: OK crops a mark at the page edge. + pub(super) fn paint(self, painter: &egui::Painter, page: Rect, s: f32, layer: Layer) { + let painter = painter.with_clip_rect(painter.clip_rect().intersect(page)); + let placed = self.place(page, s); + match layer { + Layer::Over => { + painter.add(placed.mesh()); + } + Layer::Behind(glass) => { + let full = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + let mut paper = egui::Mesh::default(); + paper.add_colored_rect(page, Color32::WHITE); + painter.add(paper); + painter.add(placed.mesh()); + let mut sheet = egui::Mesh::with_texture(glass); + sheet.add_rect_with_uv(page, full, Color32::WHITE); + painter.add(sheet); + } + Layer::Hidden => {} + } + } +} + +/// A picture laid out on the preview's page: its rectangle before the turn, turned about its centre. +struct Placed<'a> { + picture: &'a Picture, + rect: Rect, + turn: Rot2, + opacity: f32, +} + +impl Placed<'_> { + /// The picture drawn over the page. + fn mesh(&self) -> egui::Mesh { + let mut mesh = egui::Mesh::with_texture(self.picture.tex.id()); + mesh.add_rect_with_uv(self.rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE.gamma_multiply(self.opacity)); + mesh.rotate(self.turn, self.rect.center()); + mesh + } +} + +/// What a sheet render is for: the document version, whether Update takes its marks away and +/// whether the white backdrops go, the page and the scale (×1000) it is drawn at. +type GlassKey = (DocId, u64, bool, bool, usize, u32); +/// The pages a sheet is made from: a [`GlassKey`] without its page and scale. +type GlassVersion = (DocId, u64, bool, bool); + +/// The page shown on a transparent sheet ([`pdfcraft_engine::Document::pages_on_glass`]), drawn +/// over a picture behind the page so the picture shows only where the page paints nothing. The +/// pages are made once per document version and Update choice; only the page shown is kept. +pub(super) struct Glass { + pages: Option<(GlassVersion, Option>>)>, + renders: JobQueue>, + shown: Option<(GlassKey, egui::TextureHandle)>, + failed: Option, +} + +impl Glass { + pub(super) fn new(renders: JobQueue>) -> Self { + Self { pages: None, renders, shown: None, failed: None } + } + + /// `page` of `doc` on the sheet at `scale` pixels a point, without its marks of `without` + /// and, with `replace_backdrops`, its white backdrop: `None` while it renders, or when it + /// can't be. + pub(super) fn texture( + &mut self, + ctx: &egui::Context, + doc: &pdfcraft_engine::Document, + without: Option, + replace_backdrops: bool, + page: usize, + scale: f32, + ) -> Option { + let version = (doc.id, doc.edit_generation(), without.is_some(), replace_backdrops); + if self.pages.as_ref().map(|p| p.0) != Some(version) { + self.renders.reprioritize(|_, _| None); + self.shown = None; + self.failed = None; + self.pages = Some((version, doc.pages_on_glass(without, replace_backdrops).ok().map(|p| Arc::new(Mutex::new(p))))); + } + let want = (version.0, version.1, version.2, version.3, page, glass_scale(scale)?); + while let Some(done) = self.renders.try_recv() { + match done.result { + Ok(image) if done.key == want => { + self.shown = Some((want, ctx.load_texture("marks-preview-glass", image, egui::TextureOptions::LINEAR))) + } + Err(_) if done.key == want => self.failed = Some(want), + _ => {} + } + } + if let Some((key, tex)) = &self.shown + && *key == want + { + return Some(tex.id()); + } + let pages = self.pages.as_ref()?.1.clone()?; + if self.failed != Some(want) && !self.renders.contains(&want) { + self.renders.reprioritize(|_, _| None); + self.renders.submit(want, Priority::VISIBLE, move |cancel| { + if cancel.is_cancelled() { + return Err("cancelled".to_string()); + } + let mut pages = pages.lock().map_err(|_| "the pages are unavailable".to_string())?; + let out = pages.render_page(page, scale).map_err(|e| e.to_string())?; + Ok(crate::canvas::texture_image([out.width as usize, out.height as usize], out.rgba)) + }); + } + #[cfg(target_arch = "wasm32")] + self.renders.run_inline(1); + None + } +} + +/// `scale` ×1000 for a [`GlassKey`], or `None` when it is not a positive, finite size a page +/// can be rendered at. +fn glass_scale(scale: f32) -> Option { + (scale.is_finite() && scale > 0.0).then_some((scale * 1000.0) as u32).filter(|k| *k > 0) +} + +#[cfg(test)] +mod tests { + #[test] + fn a_sheet_is_rendered_only_at_a_positive_finite_scale() { + assert_eq!(super::glass_scale(1.5), Some(1500)); + for bad in [0.0, -1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 1e-6] { + assert_eq!(super::glass_scale(bad), None, "{bad}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/marks_ui.rs b/crates/ui-egui/src/dialogs/marks_ui.rs index b257e08a21..919a15f43a 100644 --- a/crates/ui-egui/src/dialogs/marks_ui.rs +++ b/crates/ui-egui/src/dialogs/marks_ui.rs @@ -26,6 +26,7 @@ use craft::ui::text::TextField; use egui::{Color32, CornerRadius, Rect, pos2, vec2}; use pdfcraft_engine::{Backdrop, Background, DocId, Edit, FontFamily, HeaderFooter, MarkKind, Watermark}; +use super::marks_picture::{FileKey, Glass, Layer, PICTURE_SIDE, Picture, PictureMark, Rendered}; use crate::PdfCraftApp; /// How far a watermark may be moved from the page centre, in points. @@ -455,17 +456,21 @@ fn behind(color: [f64; 3], opacity: f64) -> Color32 { rgb32(color.map(|c| 1.0 - a * (1.0 - c))) } -/// The preview's tint for a background colour on a page whose own backdrop is `found` (`None` -/// when it has none, or the check hasn't reached it): no colour where the page will still hide -/// the background after OK, because a picture covers it (a scan) or it keeps its white backdrop -/// with Replace unticked. -fn background_tint(d: &MarksDraft, found: Option) -> Color32 { - let hidden = match found { +/// Whether a page whose own backdrop is `found` (`None` when it has none, or the check hasn't +/// reached it) will still hide the background after OK: a picture covers it (a scan), or it keeps +/// its white backdrop with Replace unticked. +fn backdrop_hides(d: &MarksDraft, found: Option) -> bool { + match found { Some(Backdrop::Image) => true, Some(Backdrop::Fill) => !d.bg.replace_backdrop, None => false, - }; - if hidden { Color32::WHITE } else { behind(d.bg.color, d.bg.opacity) } + } +} + +/// The preview's tint for a background colour on a page whose own backdrop is `found`: no colour +/// where the page will still hide it ([`backdrop_hides`]). +fn background_tint(d: &MarksDraft, found: Option) -> Color32 { + if backdrop_hides(d, found) { Color32::WHITE } else { behind(d.bg.color, d.bg.opacity) } } /// The page (0-based) the preview shows: `current` when OK applies to it (`pages`), otherwise the @@ -946,6 +951,12 @@ pub struct MarksPreview { unmarked: Option, pictures: HashMap, failed: HashSet, + /// Source ▸ File's picture: its render, and the picture of the file and page last rendered + /// (or why there is none). + files: JobQueue>, + file: Option<(FileKey, Result)>, + /// The page shown on a transparent sheet, drawn over a file's picture behind the page. + glass: Glass, } fn queue( @@ -961,10 +972,13 @@ impl MarksPreview { Self { kind, backdrops: queue(jobs.clone(), wake.clone(), "marks-backdrops"), - renders: queue(jobs, wake, "marks-preview"), + renders: queue(jobs.clone(), wake.clone(), "marks-preview"), unmarked: None, pictures: HashMap::new(), failed: HashSet::new(), + files: queue(jobs.clone(), wake.clone(), "marks-picture"), + file: None, + glass: Glass::new(queue(jobs, wake, "marks-preview-glass")), } } @@ -1082,6 +1096,53 @@ impl MarksPreview { } } +impl MarksPreview { + /// `page` on a transparent sheet at the preview's size, without the marks Update replaces and, + /// with `replace_backdrops`, its white backdrop: `None` while it renders, or when it can't be. + fn glass_page( + &mut self, + ctx: &egui::Context, + doc: &pdfcraft_engine::Document, + replace: bool, + replace_backdrops: bool, + page: usize, + ) -> Option { + let size = doc.info.pages.get(page)?; + let scale = PREVIEW_SIDE * ctx.pixels_per_point() / size.width.max(size.height).max(1.0); + self.glass.texture(ctx, doc, replace.then_some(self.kind), replace_backdrops, page, scale) + } + + /// Source ▸ File's picture of the draft's file and page, rendered as OK brings it in + /// ([`pdfcraft_engine::mark_picture`]): `None` without a file, while it renders, or when it + /// can't be drawn. + fn file_picture(&mut self, ctx: &egui::Context, d: &MarksDraft) -> Option { + let file = mark_file(d)?; + let want = FileKey { bytes: Arc::clone(&file.bytes), page: file.page }; + while let Some(done) = self.files.try_recv() { + if done.key == want { + self.file = Some((done.key, done.result.map(|r| Picture::upload(ctx, r)))); + } + } + let shown = self.file.as_ref().is_some_and(|(k, _)| *k == want); + if !shown && !self.files.contains(&want) { + // Only the file and page shown now is worth rendering. + self.files.reprioritize(|_, _| None); + self.files.submit(want.clone(), Priority::VISIBLE, move |cancel| { + if cancel.is_cancelled() { + return Err("cancelled".to_string()); + } + pdfcraft_engine::mark_picture(&file, PICTURE_SIDE).and_then(Rendered::new) + }); + } + #[cfg(target_arch = "wasm32")] + self.files.run_inline(1); + match &self.file { + Some((k, Ok(picture))) if *k == want => Some(picture.clone()), + _ => None, + } + } +} + /// The picture of `page` from the page thumbnails, with the pages next to it asked for ahead. fn thumbnail_picture(ctx: &egui::Context, source: &impl ThumbSource, page: usize, near: &[usize]) -> PreviewState { let ppp = ctx.pixels_per_point(); @@ -1101,10 +1162,26 @@ fn thumbnail_picture(ctx: &egui::Context, source: &impl ThumbSource, page } } +/// Where the preview draws Source ▸ File's picture: over the page; behind it, on the page's +/// transparent sheet from `sheet`; or nowhere, when the page's own backdrop hides it after OK. +/// `None` while the sheet renders or when it can't be, so the preview shows the file's name +/// frame instead of nothing. +fn file_layer(on_top: bool, behind: bool, sheet: impl FnOnce() -> Option) -> Option { + if on_top { + Some(Layer::Over) + } else if behind { + sheet().map(Layer::Behind) + } else { + Some(Layer::Hidden) + } +} + /// The marks laid out on the preview's page: what the preview closure drew over the picture, and /// `over` over them, the picture of what OK keeps drawn over an updated header and footer. -fn overlay(kind: MarkKind, d: &MarksDraft, size: (f64, f64), over: Option) -> SharedOverlay { +/// `file` is Source ▸ File's picture, once rendered, and where it goes. +fn overlay(kind: MarkKind, d: &MarksDraft, size: (f64, f64), over: Option, file: Option<(Picture, Layer)>) -> SharedOverlay { let hf = d.hf.clone(); + let (bg_scale, bg_opacity) = (d.bg.scale, d.bg.opacity); let (wm, fit, use_file) = (d.wm.clone(), d.fit, d.use_file); let file_name = d.file.as_ref().map(|f| f.0.clone()); let (page_w, page_h) = (size.0.max(1.0), size.1.max(1.0)); @@ -1141,6 +1218,16 @@ fn overlay(kind: MarkKind, d: &MarksDraft, size: (f64, f64), over: Option { + if let Some((picture, layer)) = &file { + let mark = match kind { + MarkKind::Background => PictureMark { picture, scale: bg_scale, rotation: 0.0, offset: [0.0; 2], opacity: bg_opacity }, + _ => PictureMark { picture, scale: wm.scale, rotation: wm.rotation, offset: wm.offset, opacity: wm.opacity }, + }; + mark.paint(p, r, s, *layer); + } + } + // Until the picture arrives, or when the file can't be drawn: a frame with its name. MarkKind::Watermark if use_file => { if let Some(name) = &file_name { p.rect_stroke(r.shrink(6.0), CornerRadius::ZERO, egui::Stroke::new(1.0, Color32::GRAY), egui::StrokeKind::Inside); @@ -1240,6 +1327,10 @@ impl PdfCraftApp { Text::new(tl!("Replaces the existing one on those pages.")).show(ui); } }); + if kind == MarkKind::HeaderFooter { + // Restore a readable page sample without enlarging other document dialogs. + dialog = dialog.document_preview_width(142.5); + } if let Some(reason) = ¬es.reason { dialog = dialog.ok_reason(reason.clone().into()); } @@ -1371,7 +1462,17 @@ impl PdfCraftApp { (kind == MarkKind::Background && !d.use_file).then(|| DataColor::new(background_tint(d, d.backdrops.found(doc, target).flatten()))); let pager = PanePager { shown: target + 1, count, shown_label: None, back: back.is_some(), next: next.is_some(), unit: PagerUnit::Page }; - let overlay = size.map(|size| overlay(kind, d, size, over)); + // A background, or a watermark that appears behind the page, shows where the page paints + // nothing, unless the page's own backdrop will hide it; a watermark on top covers the page. + let behind = if kind == MarkKind::Background { !backdrop_hides(d, d.backdrops.found(doc, target).flatten()) } else { d.wm.behind }; + let on_top = kind != MarkKind::Background && !d.wm.behind; + let replace_backdrops = kind == MarkKind::Background && d.bg.replace_backdrop; + // Lazy: no picture, no sheet render. + let file = match preview.file_picture(ctx, d) { + Some(p) => file_layer(on_top, behind, || preview.glass_page(ctx, doc, d.replace, replace_backdrops, target)).map(|layer| (p, layer)), + None => None, + }; + let overlay = size.map(|size| overlay(kind, d, size, over, file)); if let Some(dialog) = self.dialogs.get_mut_by_id::(id) { for (key, value) in refill.iter().flat_map(DialogFields::iter) { dialog.set_field(key, value.clone()); @@ -1619,6 +1720,22 @@ mod tests { assert_eq!(background_tint(&d, None), colour, "unticked changes nothing without a backdrop"); } + #[test] + fn a_picture_behind_a_page_whose_sheet_is_missing_shows_the_file_name_frame() { + let sheet = egui::TextureId::Managed(7); + assert!(matches!(file_layer(true, true, || None), Some(Layer::Over)), "a watermark on top needs no sheet"); + assert!(matches!(file_layer(false, true, || Some(sheet)), Some(Layer::Behind(t)) if t == sheet)); + assert!(file_layer(false, true, || None).is_none(), "a sheet rendering, or failed, leaves the name frame"); + let mut asked = false; + let hidden = file_layer(false, false, || { + asked = true; + None + }); + assert!(matches!(hidden, Some(Layer::Hidden)), "the page's own backdrop still hides the picture"); + assert!(!asked, "a hidden picture renders no sheet"); + // With no picture to place, `overlay` takes its name-frame arm. + } + #[test] fn the_watermark_edit_carries_the_offset() { let mut d = MarksDraft::default(); diff --git a/crates/ui-egui/src/dialogs/pageboxes.rs b/crates/ui-egui/src/dialogs/pageboxes.rs index 5cc0e82055..1bb84d8ad7 100644 --- a/crates/ui-egui/src/dialogs/pageboxes.rs +++ b/crates/ui-egui/src/dialogs/pageboxes.rs @@ -15,7 +15,7 @@ use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, NumberU use craft::ui::primitives::StrokeWidth; use craft::ui::runtime::env::{Env, UnitKind}; use egui::{CornerRadius, Rect, Stroke, pos2, vec2}; -use pdfcraft_engine::{BoxSpec, Edit, PageBox}; +use pdfcraft_engine::{BoxSpec, DocId, Edit, PageBox}; use crate::PdfCraftApp; use crate::units::Unit; @@ -65,15 +65,47 @@ pub struct BoxesDraft { pub range: PageRange, /// The page and box the margins were seeded from when the dialog opened. pub seeded: Option<(usize, PageBox)>, + /// The crop rectangle the dialog was opened from, if it was (#5695). `None` when it was opened from the menu or by a + /// double-click, which are for the current page. + pub drawn: Option, +} + +/// Where a crop rectangle was drawn: the dialog it opens is for that page of that document as it was then. Its margins +/// are measured on that page, so another document coming forward, or any edit to this one (pages moved, deleted or +/// inserted, the page's boxes changed), closes the dialog: OK never crops a different page to them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DrawnCrop { + pub doc: DocId, + /// The page (0-based) the rectangle was drawn on. + pub page: usize, + /// The document's edit generation when it was drawn. + pub generation: u64, } impl Default for BoxesDraft { fn default() -> Self { - Self { which: PageBox::Crop, unit: Unit::Inches, margins: [0.0; 4], range: PageRange::default(), seeded: None } + Self { which: PageBox::Crop, unit: Unit::Inches, margins: [0.0; 4], range: PageRange::default(), seeded: None, drawn: None } } } impl BoxesDraft { + /// Seeds the draft from a rectangle drawn on `page` with the Crop tool: the crop box of that page alone, its margins + /// measured in from `media` (both in user space) and kept in physical points by the page's `user_unit`, as + /// [`page_margins`] does, so they can be fine-tuned before anything is cropped (#5695). An edge of the rectangle past + /// the media box gives a zero margin, as the crop box can't reach past it, and a coordinate that is not a number + /// gives zero too, never a margin the engine refuses. + pub fn seed_crop_rect(&mut self, page: usize, media: [f64; 4], rect: [f64; 4], user_unit: f64, unit: Unit) { + let user_unit = if user_unit.is_finite() && user_unit > 0.0 { user_unit } else { 1.0 }; + let m = [media[0].min(media[2]), media[1].min(media[3]), media[0].max(media[2]), media[1].max(media[3])]; + let r = [rect[0].min(rect[2]), rect[1].min(rect[3]), rect[0].max(rect[2]), rect[1].max(rect[3])]; + self.which = PageBox::Crop; + self.unit = unit; + self.range.scope = PageScope::Current; + self.margins = [r[0] - m[0], r[1] - m[1], m[2] - r[2], m[3] - r[3]] + .map(|v| if v.is_finite() { (v.max(0.0) * user_unit * 100.0).round() / 100.0 } else { 0.0 }); + self.seeded = Some((page, PageBox::Crop)); + } + /// The edit setting the box on `pages` (0-based). `user_units` is each page's `/UserUnit` (points /// per user-space unit): the margins are physical, the page box is written in user space, so pages /// with different units get their own margins in one undo step. @@ -263,11 +295,11 @@ impl PdfCraftApp { let Some((i, id)) = self.active_ids() else { return }; let current = self.views[i].current(); let Some(doc) = self.session.get(id) else { return }; - let boxes = doc.page_boxes(); - let count = boxes.len().max(1); - let page = boxes.get(current).copied(); + let page = doc.page_boxes().get(current).copied(); let page_unit = doc.page_user_unit(current); let d = &mut self.boxes_draft; + // For the current page, not a rectangle drawn before. + d.drawn = None; // Opening the dialog starts in the unit chosen in Preferences. d.unit = self.units; if let Some(b) = page { @@ -277,6 +309,37 @@ impl PdfCraftApp { if current_only { d.range.scope = PageScope::Current; } + self.show_page_boxes(ctx, id, current); + } + + /// Opens Set Page Boxes on a rectangle drawn with the Crop tool on `page` of `doc` (`rect` in that page's user + /// space): the crop box of that page, with the margins the rectangle makes, to adjust before OK crops it (#5695). + /// The dialog is for that page of that document as it is now; [`page_boxes_pass`](Self::page_boxes_pass) closes it + /// once either changes. Nothing opens when the page is not there. + pub(crate) fn open_page_boxes_for_rect(&mut self, ctx: &egui::Context, doc: DocId, page: usize, rect: [f64; 4]) { + let Some(d) = self.session.get(doc) else { return }; + let Some(media) = d.page_boxes().get(page).map(|b| b[0]) else { return }; + let (user_unit, generation) = (d.page_user_unit(page), d.edit_generation()); + let units = self.units; + self.boxes_draft.seed_crop_rect(page, media, rect, user_unit, units); + self.boxes_draft.drawn = Some(DrawnCrop { doc, page, generation }); + self.show_page_boxes(ctx, doc, page); + } + + /// Whether a crop rectangle's dialog still has its page: its document is the active one and unedited since. + fn drawn_crop_holds(&self, drawn: DrawnCrop) -> bool { + self.active_ids().map(|(_, id)| id) == Some(drawn.doc) + && self.session.get(drawn.doc).is_some_and(|d| d.edit_generation() == drawn.generation && drawn.page < d.info.pages.len()) + } + + /// Shows the dialog for `page` of `doc` from the draft as it stands. + fn show_page_boxes(&mut self, ctx: &egui::Context, id: DocId, current: usize) { + let Some(doc) = self.session.get(id) else { return }; + let boxes = doc.page_boxes(); + let count = boxes.len().max(1); + let page = boxes.get(current).copied(); + let page_unit = doc.page_user_unit(current); + let d = &self.boxes_draft; let mut fields = DialogFields::new(); fields.set("box", BOXES.iter().find(|(b, ..)| *b == d.which).map_or("crop", |(_, id, _)| *id)); fields.set("unit", unit_id(d.unit)); @@ -297,13 +360,34 @@ impl PdfCraftApp { crate::dialogs::host::open(self, dialog); } - /// Sets the boxes when the dialog was answered with OK. + /// Sets the boxes when the dialog was answered with OK. A dialog opened from a crop rectangle closes, setting + /// nothing, once its page may no longer be the one drawn on (see [`DrawnCrop`]); it is never moved to another page. pub(crate) fn page_boxes_pass(&mut self, ctx: &egui::Context) { - let Some(answer) = self.dialogs.take_by_id::(dialog_id(KEY)) else { return }; + let key = dialog_id(KEY); + if let Some(drawn) = self.boxes_draft.drawn + && !self.drawn_crop_holds(drawn) + { + self.boxes_draft.drawn = None; + self.boxes_draft.seeded = None; + self.dialogs.cancel_by_id(ctx, key); + // An OK given in this very pass is for a page that is no longer there as it was drawn. + let _ = self.dialogs.take_by_id::(key); + return; + } + let Some(answer) = self.dialogs.take_by_id::(key) else { + if self.dialogs.get_by_id::(key).is_none() { + // Closed without an answer: opened again by any route, it is for the current page. + self.boxes_draft.drawn = None; + } + return; + }; + // However it closed, the rectangle is used up. + let drawn = self.boxes_draft.drawn.take(); let Some(result) = answer.ok() else { return }; let Some((i, id)) = self.active_ids() else { return }; let (count, user_units) = self.session.get(id).map_or((0, Vec::new()), |d| (d.info.pages.len(), d.page_user_units())); - let current = self.views[i].current(); + // The page the dialog was for: the one the rectangle was drawn on (checked above), else the current one. + let current = drawn.map_or_else(|| self.views[i].current(), |d| d.page); let f = &result.fields; let d = &mut self.boxes_draft; if let Some((b, ..)) = BOXES.iter().find(|(_, id, _)| Some(*id) == f.text("box")) { @@ -424,4 +508,26 @@ mod tests { assert_eq!(page_margins(&boxes, PageBox::Crop, 2.0), [36.0; 4], "18 user units on a UserUnit 2 page are half an inch"); assert_eq!(page_margins(&boxes, PageBox::Media, 2.0), [0.0; 4]); } + + #[test] + fn a_drawn_crop_rectangle_seeds_margins_for_its_page_alone() { + let mut d = BoxesDraft { which: PageBox::Trim, ..Default::default() }; + d.range.scope = PageScope::All; + // A rectangle drawn backwards, past the media box's left edge, on an off-origin page. + d.seed_crop_rect(3, [10.0, 20.0, 310.0, 420.0], [250.333, 380.0, -5.0, 60.0], 1.0, Unit::Millimetres); + assert_eq!(d.which, PageBox::Crop); + assert_eq!(d.unit, Unit::Millimetres); + assert_eq!(d.range.scope, PageScope::Current); + assert_eq!(d.range.pages(5, 3, &[]), [3], "the page drawn on alone"); + assert_eq!(d.margins, [0.0, 40.0, 59.67, 40.0]); + assert_eq!(d.seeded, Some((3, PageBox::Crop))); + assert_eq!(d.edit(vec![3], &[]), Edit::SetPageBox { pages: vec![3], which: PageBox::Crop, spec: BoxSpec::Margins([0.0, 40.0, 59.67, 40.0]) }); + // A coordinate that is not a number never gives a margin the engine refuses. + d.seed_crop_rect(0, [0.0, 0.0, 300.0, 400.0], [f64::NAN, 10.0, 290.0, f64::INFINITY], f64::NAN, Unit::Points); + assert!(d.margins.iter().all(|m| m.is_finite() && *m >= 0.0), "{:?}", d.margins); + // On a `/UserUnit` 2 page the margins are physical points, and the edit writes the rectangle back. + d.seed_crop_rect(1, [0.0, 0.0, 432.0, 360.0], [18.0, 18.0, 414.0, 342.0], 2.0, Unit::Points); + assert_eq!(d.margins, [36.0; 4]); + assert_eq!(d.edit(vec![1], &[1.0, 2.0]), Edit::SetPageBox { pages: vec![1], which: PageBox::Crop, spec: BoxSpec::Margins([18.0; 4]) }); + } } diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index f82e2bd572..abb406e742 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -84,6 +84,7 @@ struct PrefsDraft { always_default_view: bool, text_links: bool, units: Unit, + show_page_boxes: bool, scroll_speed: ScrollSpeed, invert_middle_drag: bool, author: String, @@ -122,6 +123,7 @@ impl PrefsDraft { always_default_view: app.always_default_view, text_links: app.text_links, units: app.units, + show_page_boxes: app.show_page_boxes, scroll_speed: app.scroll_speed, invert_middle_drag: app.invert_middle_drag, author: app.comment_prefs.author.clone(), @@ -165,6 +167,7 @@ impl PrefsDraft { always_default_view: false, text_links: true, units: Unit::default(), + show_page_boxes: false, scroll_speed: ScrollSpeed::default(), invert_middle_drag: false, author: prefs.author, @@ -208,6 +211,13 @@ impl PdfCraftApp { } } + /// Keep a control-channel page-box change in an open Preferences draft. + pub(crate) fn sync_open_show_page_boxes(&mut self) { + if let Some(prefs) = self.preferences.as_mut() { + prefs.draft.show_page_boxes = self.show_page_boxes; + } + } + /// Shows the Preferences window for this pass while it is open, and closes it when answered. pub(crate) fn show_preferences(&mut self, ui: &mut Ui) { let Some(mut session) = self.preferences.take() else { @@ -486,6 +496,7 @@ impl PreferencesModel for Prefs<'_> { } ("view.always", PrefValue::Bool(v)) => d.always_default_view = v, ("view.text_links", PrefValue::Bool(v)) => d.text_links = v, + ("view.show_page_boxes", PrefValue::Bool(on)) => d.show_page_boxes = on, ("view.units", PrefValue::Choice(id)) => d.units = lookup(&unit_table(), &id).unwrap_or(d.units), ("view.scroll_speed", PrefValue::Choice(id)) => d.scroll_speed = lookup(&speed_table(), &id).unwrap_or(d.scroll_speed), ("view.invert_middle", PrefValue::Bool(v)) => d.invert_middle_drag = v, @@ -580,6 +591,7 @@ impl PreferencesModel for Prefs<'_> { d.show_form_field_reminder = fresh.show_form_field_reminder; d.text_links = fresh.text_links; d.units = fresh.units; + d.show_page_boxes = fresh.show_page_boxes; d.scroll_speed = fresh.scroll_speed; d.invert_middle_drag = fresh.invert_middle_drag; } @@ -663,6 +675,7 @@ impl PreferencesDraft for Prefs<'_> { self.app.always_default_view = d.always_default_view; self.app.text_links = d.text_links; self.app.units = d.units; + self.app.show_page_boxes = d.show_page_boxes; self.app.scroll_speed = d.scroll_speed; self.app.invert_middle_drag = d.invert_middle_drag; self.app.comment_prefs.author = d.author; @@ -800,6 +813,8 @@ impl Prefs<'_> { RowSpec::new("view.text_links", tl!("Open web and email addresses written in the page text"), RowKind::Bool(d.text_links)) .help(tl!("Only web (http, https) and email addresses open, and PdfCraft asks first, as for other links.")), choice_row("view.units", tl!("Units"), d.units, &unit_table()).help(tl!("For page sizes and margins.")), + RowSpec::new("view.show_page_boxes", tl!("Show art, trim and bleed boxes"), RowKind::Bool(d.show_page_boxes)) + .help(tl!("Box edge marks: bleed has one tick, trim has two, and art has three.")), choice_row("view.scroll_speed", tl!("Scroll speed (mouse wheel and arrow keys)"), d.scroll_speed, &speed_table()), RowSpec::new("view.invert_middle", tl!("Invert middle-button drag"), RowKind::Bool(d.invert_middle_drag)) .help(tl!("Panning or auto-scrolling with the middle (wheel) button moves the page the other way.")), diff --git a/crates/ui-egui/src/dialogs/prompts.rs b/crates/ui-egui/src/dialogs/prompts.rs index dbda427407..5560204139 100644 --- a/crates/ui-egui/src/dialogs/prompts.rs +++ b/crates/ui-egui/src/dialogs/prompts.rs @@ -72,12 +72,14 @@ impl PdfCraftApp { tl!("Revert to the previously saved version of “{name}”? Changes since then can't be undone afterwards."), &[("name", &name)], ); - let prompt = StandardPrompt::custom(message) + let mut prompt = StandardPrompt::custom(message) .title(tl!("Revert")) .button(PromptChoice::Proceed, tl!("Revert")) .button(PromptChoice::Cancel, tl!("Cancel")) .default_choice(PromptChoice::Cancel) .instance("revert"); + // A host-side confirm remains the explicit Revert action; keyboard focus stays on Cancel. + prompt.set_choice(PromptChoice::Proceed); self.prompts.revert = Some(self.dialogs.open(prompt)); } diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 3d4f4f42f1..92f31bc679 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -1284,6 +1284,7 @@ fn comment_page(edit: &Edit) -> Option { | Edit::MoveAnnotation { page, .. } | Edit::ReshapeAnnotation { page, .. } | Edit::SetAnnotationPopup { page, .. } + | Edit::SetMarkupRange { page, .. } | Edit::ResizeAnnotation { page, .. } | Edit::StyleAnnotation { page, .. } | Edit::FillAnnotation { page, .. } @@ -1320,6 +1321,8 @@ fn is_form_edit(edit: &Edit) -> bool { | Edit::DeleteField { .. } | Edit::DeleteWidget { .. } | Edit::DuplicateField { .. } + | Edit::CopyField { .. } + | Edit::PasteField { .. } | Edit::SetFieldProps { .. } | Edit::SetFieldImage { .. } | Edit::SetFieldImageTarget { .. } diff --git a/crates/ui-egui/src/editing/save.rs b/crates/ui-egui/src/editing/save.rs index 28ca005e00..ccf5d4073a 100644 --- a/crates/ui-egui/src/editing/save.rs +++ b/crates/ui-egui/src/editing/save.rs @@ -229,6 +229,13 @@ impl PdfCraftApp { } return false; } + if let Some(saved) = self.save_to_host(ctx, id, &name, target) { + let then = if saved { pending.after.take() } else { pending.failed.take() }; + if let Some(then) = then { + then(self, ctx); + } + return saved; + } if target == SaveTarget::InPlace && let Some(path) = path { @@ -254,6 +261,22 @@ impl PdfCraftApp { false } + /// Deliver through a connected embedding page; `None` leaves an unhosted save to the picker. + #[cfg(any(target_arch = "wasm32", test))] + pub(super) fn save_to_host(&mut self, ctx: &egui::Context, id: DocId, name: &str, target: SaveTarget) -> Option { + self.host_save.as_ref()?; + let Some((_, bytes)) = self.document_bytes(ctx, id, target, None) else { return Some(false) }; + let result = self.host_save.as_ref()?(name, &bytes, target != SaveTarget::InPlace); + match result { + Ok(()) if target == SaveTarget::Copy => Some(true), + Ok(()) => Some(self.finish_save(ctx, id, bytes, None)), + Err(e) => { + self.notify_fmt("Couldn't save {name}: {e}", &[("name", name), ("e", &e)]); + Some(false) + } + } + } + /// The browser's save picker answered: where the bytes went, a failure or a cancel. #[cfg(target_arch = "wasm32")] pub(crate) fn save_flow_pass(&mut self, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/editing/tests.rs b/crates/ui-egui/src/editing/tests.rs index 0160040ddd..7c2a0eaf2c 100644 --- a/crates/ui-egui/src/editing/tests.rs +++ b/crates/ui-egui/src/editing/tests.rs @@ -74,6 +74,41 @@ fn one_page_pdf() -> Vec { out } +/// #9005: a pathless host document sends the changed PDF to the page and keeps no invented path. +#[test] +fn host_save_delivers_pathless_document_and_preserves_failures() { + use std::sync::Mutex; + let mut app = crate::PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "sample.pdf", None, one_page_pdf()).unwrap(); + let id = app.views[0].id; + app.apply_edit(&ctx, pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }); + assert!(app.session.get(id).unwrap().dirty); + assert_eq!(app.save_to_host(&ctx, id, "sample.pdf", SaveTarget::InPlace), None, "unhosted saves still use the browser picker"); + app.host_save = Some(Box::new(|_, _, _| Err("host rejected".into()))); + assert_eq!(app.save_to_host(&ctx, id, "sample.pdf", SaveTarget::InPlace), Some(false)); + assert!(app.session.get(id).unwrap().dirty, "a failed delivery does not mark the document saved"); + let received = Arc::new(Mutex::new(Vec::<(String, Vec, bool)>::new())); + let sink = received.clone(); + app.host_save = Some(Box::new(move |name, bytes, as_copy| { + sink.lock().unwrap().push((name.to_owned(), bytes.to_vec(), as_copy)); + Ok(()) + })); + assert_eq!(app.save_to_host(&ctx, id, "sample.pdf", SaveTarget::InPlace), Some(true)); + assert!(!app.session.get(id).unwrap().dirty); + assert!(app.session.get(id).unwrap().path.is_none(), "host delivery does not create a filesystem path"); + assert_eq!(app.save_to_host(&ctx, id, "sample.pdf", SaveTarget::As), Some(true)); + app.apply_edit(&ctx, pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }); + assert_eq!(app.save_to_host(&ctx, id, "sample.pdf", SaveTarget::Copy), Some(true)); + assert!(app.session.get(id).unwrap().dirty, "saving a copy does not mark the original saved"); + let saved = received.lock().unwrap(); + assert_eq!(saved.len(), 3); + assert_eq!((saved[0].0.as_str(), saved[0].2, saved[1].2, saved[2].2), ("sample.pdf", false, true, true)); + let mut reopened = pdfcraft_engine::Session::new(); + let opened = reopened.open("saved.pdf", None, Arc::new(saved[0].1.clone()), None).unwrap(); + assert_eq!(reopened.get(opened).unwrap().info.pages[0].rotation, 90); +} + /// `one_page_pdf`, opening without a password, whose permissions refuse changes. fn no_changes_pdf() -> Vec { let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(one_page_pdf())).unwrap(); diff --git a/crates/ui-egui/src/frame_guard.rs b/crates/ui-egui/src/frame_guard.rs index f63ab257ca..b0386361ee 100644 --- a/crates/ui-egui/src/frame_guard.rs +++ b/crates/ui-egui/src/frame_guard.rs @@ -193,7 +193,7 @@ mod tests { h.state_mut().panic_next = None; h.run_steps(2); assert_eq!(h.state().views.len(), 2); - h.get_by_label_contains("injected Logic panic"); + assert!(h.query_all_by_label_contains("injected Logic panic").next().is_some(), "the logic panic is reported"); assert_eq!(snapshots(&store), 1); let ctx = h.ctx.clone(); diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index 2468ffd8d9..66178dd9b2 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -141,7 +141,8 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { let pinned_tools: Vec<&'static ToolGroup> = app.pinned_tools.iter().filter_map(|id| catalog::group(id)).collect(); let recommended: Vec<&'static ToolGroup> = RECOMMENDED.iter().filter(|id| !app.is_tool_pinned(id)).filter_map(|id| catalog::group(id)).collect(); - let community_card = !app.community_card_closed; + // Embedded mode (#2490) leaves the community card out, as closing it does. + let community_card = !app.community_card_closed && !app.embedded; let asked = RefCell::new(Vec::new()); // PLAN: assumed fields `recent_view: RecentView` and `recent_sort: RecentSort` on PdfCraftApp (pdf-hub-w1). @@ -156,7 +157,7 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { // Open is in the title bar, as in production. .offers_open(false) .pinned_title(tl!("Folders").to_string()) - .drop_hint(tl!("Files you open in PdfCraft appear here").to_string()) + .drop_hint(tl!("Files you open in PdfCraft appear here. Drop a PDF anywhere to open it.").to_string()) .section(StartPlace::BeforeRecent, |ui, _| { let _ = Text::new(tl!("Welcome to PdfCraft").to_string()).role(TypeRole::Display).show(ui); let _ = Text::new(tl!("An open-source PDF workbench — local, private, and scriptable.").to_string()).show(ui); diff --git a/crates/ui-egui/src/hooks.rs b/crates/ui-egui/src/hooks.rs index e1ecfff371..4b80f087ee 100644 --- a/crates/ui-egui/src/hooks.rs +++ b/crates/ui-egui/src/hooks.rs @@ -1,3 +1,6 @@ /// Told every frame whether any tab has unsaved work, or an OCR review is not yet accepted or /// rejected, so a host page can warn before leaving. pub type HostDirtyFn = Box; + +/// Delivers a saved document to an embedding web page: name, bytes, and whether Save As was requested. +pub type HostSaveFn = Box Result<(), String>>; diff --git a/crates/ui-egui/src/hotbar.rs b/crates/ui-egui/src/hotbar.rs index 1616324c36..f55f9d957a 100644 --- a/crates/ui-egui/src/hotbar.rs +++ b/crates/ui-egui/src/hotbar.rs @@ -39,6 +39,9 @@ const SLOT_USER: SlotId = 100; #[derive(Clone, Debug, Default, Serialize, Deserialize)] #[serde(default)] pub(crate) struct Hotbar { + /// The width offered by the dock for laying out the toolbar on the last pass. + #[serde(skip)] + pub(crate) layout_width: Option, /// The commands the user put on the toolbar, in order. pub tools: Vec, /// The tool each slot showed last. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c53d47240d..3a61684869 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -51,6 +51,7 @@ pub use content_ui::TextDraft; pub use create_ui::Clip; pub use sign_ui::{DigitalIdEntry, SignDraft, SignGraphic, SignStep}; mod dialogs; +mod shown_boxes; pub use edit_text_ui::{CropMode, ImageSelection}; mod editing; mod home; @@ -122,7 +123,7 @@ use dialogs::rename_ui; use dialogs::standards_ui; use dialogs::word_count_ui; pub use home::folders_ui; -pub use hooks::HostDirtyFn; +pub use hooks::{HostDirtyFn, HostSaveFn}; use menus::tab_context; use panels::all_tools_ui; use panels::comments_panel; @@ -293,6 +294,8 @@ pub struct PdfCraftApp { pub(crate) highlight_fields: bool, /// The unit page sizes and margins are shown in (Preferences ▸ Documents and view). pub units: units::Unit, + /// Whether page-defined art, trim and bleed boxes are shown. + pub show_page_boxes: bool, /// The paper Create ▸ Blank page makes (#5644): the system region's. pub blank_paper: paper::Paper, /// Explicit CLI/control mode lasts for this session and is never persisted. @@ -306,9 +309,8 @@ pub struct PdfCraftApp { /// Whether the Tools pane was in the dock when the floating toolbar was last placed: the toolbar follows the page area's /// left edge as the pane closes and opens. pub(crate) toolbar_tools_open: bool, - /// Whether the window was narrow (under [`panels::side_panels::NARROW_WINDOW`]) when the Tools pane's width was last set: a - /// narrow window keeps the pane at production's width, a wide one gives it the width Format text needs. - pub(crate) window_narrow: bool, + /// The last automatic Tools width, for preserving a user-resized dock. + pub(crate) default_tools_width: f32, /// The right panel that was open when the user switched to Read mode, which starts with the /// panes closed; leaving Read mode brings it back unless the user opened or closed a pane in /// Read mode meanwhile. @@ -329,6 +331,8 @@ pub struct PdfCraftApp { /// closed), given back when its tab is left. portfolio_panel: Option>, pub quick_tool: QuickTool, + /// Add text or Edit text as last seen up, for [`Self::apply_text_of_put_down_tool`]. + text_tool_up: Option, /// The tool before full screen, given back on leaving it (see [`Self::apply_full_screen`]). full_screen_tool: Option, /// Comment author, per-tool colours and widths, pin. @@ -348,6 +352,8 @@ pub struct PdfCraftApp { pub reading_colors: pdfcraft_render::ReadingColors, /// App-wide page decoration only; never part of a PDF edit or render request. pub show_page_edge_shadows: bool, + /// View ▸ Show/Hide ▸ Rulers: horizontal and vertical rulers around the page area. + pub show_rulers: bool, /// How far a mouse-wheel notch scrolls. pub scroll_speed: scroll_speed::ScrollSpeed, /// Preferences ▸ Invert middle-button drag: the middle button's pan or auto-scroll moves the @@ -456,8 +462,17 @@ pub struct PdfCraftApp { pub update_check_at_start: bool, /// Optional host cleanup invoked once in `eframe::App::on_exit` (e.g. Nightly session record). pub at_exit: Option>, + /// Preserve the normal Win32 placement if eframe saved a minimized window. + #[cfg(target_os = "windows")] + pub save_window_placement: Option>, + /// Keeps the undecorated window's OS frame from offsetting its content and pointer (Windows, + /// integrated title bar). Called once per frame, before the frame's input is read. + #[cfg(target_os = "windows")] + pub window_frame: Option>, /// Native launch time, consumed after the first UI pass for startup diagnostics. pub startup_time: Option, + #[cfg(target_os = "macos")] + metal_fullscreen: app::MetalFullscreen, /// Preferences: tell the user, above the pages, that a document is secured (its security /// settings restrict changes). Off only hides that notice (#4035); kept in the settings. pub show_secured_notice: bool, @@ -540,6 +555,8 @@ pub struct PdfCraftApp { pub unlock_prompt: Option, /// Standard, full screen with the menu bar, or full screen. pub screen_mode: craft::ui::shell::ScreenMode, + /// Saves documents through a connected embedding page instead of the browser picker. + pub host_save: Option, /// Reports unsaved work, or an open OCR review, to the embedding page (web, see [`HostDirtyFn`]). pub host_dirty: Option, /// Requests from the operating system, polled at the start of every frame's logic (macOS Apple @@ -623,6 +640,8 @@ pub struct PdfCraftApp { pub space_audit: std::sync::Arc>>, /// The document and edit generation `space_audit` was measured from. pub(crate) space_audit_of: Option<(DocId, u64)>, + /// A measure is running and `space_audit` holds nothing of the active document's yet: the dialog says it is measuring. + pub(crate) space_audit_pending: std::sync::Arc, pub(crate) space_audit_jobs: optimize_ui::SpaceAuditJobs, /// Combine files: the files staged so far. pub combine_draft: Vec, @@ -772,6 +791,8 @@ pub struct PdfCraftApp { pub(crate) startup_files: Vec<(String, std::sync::Arc<[u8]>)>, /// The home screen's community card was closed; it comes back next launch (not remembered). pub community_card_closed: bool, + /// Embedded mode (web iframe with `?embedded`): hides external community links (#2490). + pub embedded: bool, /// A document asked to open this address; the user hasn't answered yet (#90, #91). pub pending_link: Option, /// A document just opened asks for its window to fit its first page or to be centred @@ -780,3 +801,7 @@ pub struct PdfCraftApp { /// An absolute GoToR target waiting for approval, before any target-file I/O (#1364). pub pending_remote_link: Option, } + +/// Host hook invoked immediately after eframe writes its native window settings. +#[cfg(target_os = "windows")] +pub type WindowPlacementSaver = dyn Fn(&mut dyn eframe::Storage); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 835bbc37a0..d1f18ddba8 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -85,6 +85,7 @@ const TITLES: &[&str] = &[ "Rotate view", "Page navigation", "Page display", + "Show/Hide", "Side panels", "Display theme", "Tools", @@ -161,6 +162,7 @@ const DISPLAY: &[&str] = &[ "view.fit_one_page", ]; const THEMES: &[&str] = &["view.theme.system", "view.theme.light", "view.theme.dark"]; +const SHOW_HIDE: &[&str] = &["view.rulers"]; const PANES: &[&str] = &["view.side_panel", "view.tools_pane", "view.split"]; const PANE_COMMANDS: &[&str] = &["comment.list", "form.fields", "ui.dock.reset"]; const MODES: &[&str] = &["view.full_screen", "view.read_mode", crate::viewer_prefs::TOGGLE]; @@ -387,6 +389,7 @@ impl PdfCraftApp { Node::submenu(tl!("Rotate view"), list(&[ROTATE_CW, ROTATE_CCW], &mut used)), Node::submenu(tl!("Page navigation"), list(NAVIGATION, &mut used)), Node::submenu(tl!("Page display"), list(DISPLAY, &mut used)), + Node::submenu(tl!("Show/Hide"), list(SHOW_HIDE, &mut used)), Node::Separator, ]; view.extend(list(PANES, &mut used)); diff --git a/crates/ui-egui/src/panels/comments_panel.rs b/crates/ui-egui/src/panels/comments_panel.rs index a2a051993c..303981acb4 100644 --- a/crates/ui-egui/src/panels/comments_panel.rs +++ b/crates/ui-egui/src/panels/comments_panel.rs @@ -5,7 +5,7 @@ //! back to engine edits, and draws the header's filter and "…" buttons for the chrome. use std::collections::HashMap; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::UNIX_EPOCH; use craft::behavior::IconId; use craft::review::ui::comments::{CommentEdit, CommentsHeader, CommentsPanel, comments_filter_menu, comments_more_menu}; @@ -241,9 +241,8 @@ fn card_rows(doc: &pdfcraft_engine::Document, map: &ThreadMap, thread: &CommentT rows } -// PLAN: the comments area has no shared clock yet (w10's note popups read one too); this is the only read here. fn now_seconds() -> i64 { - SystemTime::now().duration_since(UNIX_EPOCH).ok().and_then(|d| i64::try_from(d.as_secs()).ok()).unwrap_or(0) + crate::platform::wall_time().duration_since(UNIX_EPOCH).ok().and_then(|d| i64::try_from(d.as_secs()).ok()).unwrap_or(0) } /// Draw the panel. Returns an edit to apply (posting, replying, deleting…). diff --git a/crates/ui-egui/src/panels/format_text_ui.rs b/crates/ui-egui/src/panels/format_text_ui.rs index 775254cd20..a5a02c6fe3 100644 --- a/crates/ui-egui/src/panels/format_text_ui.rs +++ b/crates/ui-egui/src/panels/format_text_ui.rs @@ -1039,13 +1039,14 @@ mod tests { assert_eq!(item(&app).font_resource, None); assert_eq!(item(&app).family, FontFamily::Times); - // Picking a document font on an open draft with Greek text unblocks and applies it. + // Greek text on an open draft is drawn with bundled Inter by default (#9016), so it is not blocked; picking a document font + // still applies it. let mut draft = open_draft(&mut app); draft.text = "γραφή φ".into(); app.views[0].session.content.draft = Some(draft.clone()); - assert!(app.views[0].session.content.blocked().is_some(), "standard font blocks Greek phi"); + assert_eq!(app.views[0].session.content.blocked(), None, "the default font draws Greek phi with bundled Inter"); apply(&ctx, &mut app, 0, Target::Draft(Box::new(draft)), &pick); - assert_eq!(app.views[0].session.content.blocked(), None, "custom font unblocks Greek phi"); + assert_eq!(app.views[0].session.content.blocked(), None, "custom font keeps Greek phi unblocked"); assert_eq!(item(&app).text, "γραφή φ"); assert_eq!(item(&app).font_resource.as_deref(), Some(font.resource.as_str())); diff --git a/crates/ui-egui/src/panels/side_panels.rs b/crates/ui-egui/src/panels/side_panels.rs index 92a0488f00..c804f5249d 100644 --- a/crates/ui-egui/src/panels/side_panels.rs +++ b/crates/ui-egui/src/panels/side_panels.rs @@ -10,13 +10,14 @@ use std::sync::Arc; #[cfg(not(target_arch = "wasm32"))] use craft::automation::dock as dock_rpc; use craft::behavior::dock::{ - Action, Column, DockEdge, DockError, DockPlacement, Floating, Group, Layout, Node, PanelState, Permissions, SplitSize, Target, Workspace, + Action, Column, DockEdge, DockError, DockPlacement, Floating, Group, Layout, Node, PanelPlace, PanelState, Permissions, SplitSize, Target, + Workspace, node_at, }; use craft::behavior::{Axis, DockSide, IconId}; use craft::keymap::CommandRef; use craft::ui::buttons::IconButton; -use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _}; -use craft::ui::docking::{DockConfig, DockPanels, GroupAt, HidePanels, IconicMode, PanelKey, PanelSpec, PanelSpecs}; +use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, SizeLimits}; +use craft::ui::docking::{DockConfig, DockPanels, DockSizes, GroupAt, HidePanels, IconicMode, PanelKey, PanelSpec, PanelSpecs}; use craft::ui::menu::PanelRow; use craft::ui::patterns::dock::DockArea; use craft::ui::primitives::IconSpec; @@ -171,18 +172,13 @@ const PAGE_SHARE: f32 = 0.8; /// The Tools pane's default width: production's 272 points at every window width (the framework's Format text row keeps the /// size field readable in it). -const TOOLS_WIDTH: f32 = 272.0; -/// The Tools pane's width in a narrow window, as production opened it. -const TOOLS_WIDTH_NARROW: f32 = 272.0; +pub(crate) const TOOLS_WIDTH: f32 = 272.0; /// How far past the Tools pane the floating toolbar starts. Production's quick bar stood 14 points into a narrow margin /// and was 46 points wide, so its page-side edge was 60 points into the page area (which starts 3 points past the pane, /// after the splitter); the rail is 52 points wide, so it starts 10 points past the pane to end just inside that edge /// and leave the page's margin beyond it to the page. const TOOLBAR_INSET: f32 = 10.0; -/// Windows narrower than this keep the Tools pane at [`TOOLS_WIDTH_NARROW`]: a wider pane would leave the page area too little. -pub(crate) const NARROW_WINDOW: f32 = 900.0; - /// The arrangement of a new install: Tools at the start edge, the side-panel rail at the window edge, /// and the toolbar floating at the start of the page area. The side panels form one collapsed group. pub fn default_workspace(rail_side: DockSide) -> Workspace { @@ -210,7 +206,11 @@ fn keep_toolbar_in_the_margin(app: &mut PdfCraftApp) { app.toolbar_tools_open = open; let Some(rect) = toolbar_rect(&app.dock) else { return }; let x = rect.min.x; - let target = if open { (x < TOOLS_WIDTH).then_some(x + TOOLS_WIDTH) } else { (x >= TOOLS_WIDTH).then_some((x - TOOLS_WIDTH).max(0.0)) }; + let target = if open { + (x < app.default_tools_width).then_some(x + app.default_tools_width) + } else { + (x >= app.default_tools_width).then_some((x - app.default_tools_width).max(0.0)) + }; if let Some(x) = target.filter(|x| x.is_finite()) { move_toolbar(app, rect.translate(egui::vec2(x - rect.min.x, 0.0))); } @@ -226,29 +226,32 @@ fn move_toolbar(app: &mut PdfCraftApp, rect: egui::Rect) { drop(Arc::make_mut(&mut app.dock).apply(Action::move_floating(PanelId::Toolbar, rect), false, permissions)); } -/// The Tools pane's width follows the window across [`NARROW_WINDOW`]: production's narrower pane in a small window, the -/// wider default in a large one. Only the crossing changes it, so a width the user dragged to is kept. -fn fit_tools_to_window(app: &mut PdfCraftApp, window_width: f32) { - let narrow = window_width.is_finite() && window_width < NARROW_WINDOW; - if narrow == app.window_narrow { +/// Home fits the localized tool list. An open document also needs room for the editing controls +/// that share this dock, so switching tools keeps both the controls and the page in place. +fn fit_tools_to_window(app: &mut PdfCraftApp, ui: &Ui) { + let list_width = super::tools::all_tools_width(ui, app.all_tools_expanded); + let width = if app.active.is_some() { list_width.max(TOOLS_WIDTH) } else { list_width }; + let previous = app.default_tools_width; + if (width - previous).abs() < 1.0 { return; } - app.window_narrow = narrow; - if !app.dock.layout().contains(&PanelId::Tools) { + let Some(edge) = edge_of(&app.dock, PanelId::Tools) else { return }; + let column_width = dock_columns(&app.dock, edge).iter().find(|col| col.panels().any(|p| *p == PanelId::Tools)).and_then(|col| col.width); + if column_width.is_some_and(|current| (current - width).abs() < 1.0) { + app.default_tools_width = width; return; } - let width = if narrow { TOOLS_WIDTH_NARROW } else { TOOLS_WIDTH }; - // A refused resize (a locked layout) leaves the width as it is. - if Arc::make_mut(&mut app.dock).apply(Action::resize_column(PanelId::Tools, width), false, permissions).is_err() { + if column_width.is_some_and(|current| (current - previous).abs() >= 1.0) { return; } - // The floating toolbar sits in the page area's margin, which moved with the pane's edge. - let shift = if narrow { TOOLS_WIDTH_NARROW - TOOLS_WIDTH } else { TOOLS_WIDTH - TOOLS_WIDTH_NARROW }; - if app.toolbar_tools_open - && let Some(rect) = toolbar_rect(&app.dock) - && rect.min.x >= TOOLS_WIDTH_NARROW - { - move_toolbar(app, rect.translate(egui::vec2(shift, 0.0))); + if Arc::make_mut(&mut app.dock).apply(Action::resize_column(PanelId::Tools, width), false, permissions).is_ok() { + app.default_tools_width = width; + if app.toolbar_tools_open + && let Some(rect) = toolbar_rect(&app.dock) + && (rect.left() - previous - TOOLBAR_INSET).abs() <= 1.0 + { + move_toolbar(app, rect.translate(egui::vec2(width - previous, 0.0))); + } } } @@ -368,6 +371,8 @@ pub(crate) struct DockSpecs { toolbar_title: String, /// The number of cells of the toolbar's rail. toolbar_cells: usize, + /// Maximum body height for a toolbar docked across the page. The dock adds its strip allowance. + toolbar_body_height: Option, /// The page area's title. document_title: String, } @@ -395,6 +400,7 @@ impl DockSpecs { tools_footer: !calc_order && super::tools::has_footer(app), toolbar_title: tl!("Toolbar").to_string(), toolbar_cells: crate::hotbar::rail_cells(app), + toolbar_body_height: None, document_title: crate::i18n::t("Document").to_owned(), } } @@ -404,7 +410,13 @@ impl PanelSpecs for DockSpecs { fn spec(&self, panel: &PanelId) -> PanelSpec { let command = CommandRef::with_params("view.panel", json!({ "panel": panel.name() })); match panel { - PanelId::Toolbar => crate::hotbar::panel_spec(&self.toolbar_title, self.toolbar_cells), + PanelId::Toolbar => { + let spec = crate::hotbar::panel_spec(&self.toolbar_title, self.toolbar_cells); + match self.toolbar_body_height { + Some(height) => spec.limits(SizeLimits::at_most(egui::vec2(SizeLimits::BOUND, height))), + None => spec, + } + } PanelId::Document => PanelSpec::new(self.document_title.clone()).canvas(), PanelId::Tools => { let spec = PanelSpec::new(self.tools_title.clone()).command(command); @@ -433,8 +445,20 @@ impl PanelSpecs for DockSpecs { } /// Reads the specs' inputs from the app, moving the specs' revision only when one changed. -fn refresh_specs(app: &mut PdfCraftApp) { - let specs = DockSpecs::of(app); +fn refresh_specs(app: &mut PdfCraftApp, ui: &Ui) { + let mut specs = DockSpecs::of(app); + let layout = app.dock.layout(); + if let Some(PanelPlace::Node(path)) = layout.place(&PanelId::Toolbar) + && let Some((_, parent)) = path.split_last() + && let Some(Node::Split { axis: Axis::Y, .. }) = layout.root.as_ref().and_then(|root| node_at(root, parent)) + { + // A top/bottom edge drop starts with a quarter of the page. Cap that frame at the + // height of the wrapped tools, footer and grip, including for already saved layouts. + let width = app.hotbar.layout_width.unwrap_or(ui.available_width()).max(1.0); + let sizes = DockSizes::of_scope(ui); + let measured = crate::hotbar::measure_rail(app, ui, width); + specs.toolbar_body_height = Some((measured + sizes.grip - sizes.strip).max(0.0)); + } if *app.dock_specs != specs { *app.dock_specs = specs; } @@ -473,6 +497,10 @@ impl DockPanels for Panels<'_> { match at { GroupAt::Measure(width) if panels.contains(&PanelId::Toolbar) => Some(crate::hotbar::measure_rail(self.app, ui, width)), GroupAt::Show(rect) if panels.contains(&PanelId::Toolbar) => { + if self.app.hotbar.layout_width != Some(rect.width()) { + self.app.hotbar.layout_width = Some(rect.width()); + ui.ctx().request_repaint(); + } crate::hotbar::show_rail(self.app, ui); Some(rect.height()) } @@ -492,10 +520,14 @@ impl DockPanels for Panels<'_> { if self.app.left == LeftPanel::CalculationOrder { crate::calc_order_ui::header(ui); } else if crate::organize_panel::showing(self.app) { - IconButton::command(IconSpec::svg(IconId::new("chevron_left")), CommandRef::new("tools.all")).show(ui); + IconButton::command(IconSpec::svg(IconId::new("chevron_left")), CommandRef::new("tools.all")) + .label(crate::commands::control_label("tools.all")) + .show(ui); IconButton::command(IconSpec::svg(IconId::new("close")), CommandRef::new("page.organize")).label(tl!("Close panel")).show(ui); } else if self.app.left == LeftPanel::AllTools { - IconButton::command(IconSpec::svg(IconId::new("maximize_2")), CommandRef::new("tools.expand")).show(ui); + IconButton::command(IconSpec::svg(IconId::new("maximize_2")), CommandRef::new("tools.expand")) + .label(crate::commands::control_label("tools.expand")) + .show(ui); } } PanelId::Bookmarks => super::bookmarks::header(self.app, ui), @@ -587,8 +619,8 @@ pub fn dock(app: &mut PdfCraftApp, ui: &mut Ui) { let toolbar = active && !app.hotbar_hidden() && !organizing && !expanded; let anchor = rail_anchor(app); keep_toolbar_in_the_margin(app); - fit_tools_to_window(app, ui.ctx().content_rect().width()); - refresh_specs(app); + fit_tools_to_window(app, ui); + refresh_specs(app, ui); let workspace = Arc::clone(&app.dock); // The rail lists the Accessibility Checker once the document has a report, and Search and Compare only while // they show; their commands open them. @@ -1219,9 +1251,9 @@ mod tests { assert!(toolbar_x(&closed) < TOOLS_WIDTH * 0.5, "left closed: the toolbar at {}", toolbar_x(&closed)); closed.state_mut().set_left_open(true); closed.run_steps(4); - assert!(toolbar_x(&closed) > TOOLS_WIDTH, "left open again: the toolbar at {}", toolbar_x(&closed)); + assert!(toolbar_x(&closed) > closed.state().default_tools_width, "left open again: the toolbar at {}", toolbar_x(&closed)); let open = harness(|_| {}); - assert!(toolbar_x(&open) > TOOLS_WIDTH, "the default arrangement keeps the toolbar beside the Tools pane"); + assert!(toolbar_x(&open) > open.state().default_tools_width, "the default arrangement keeps the toolbar beside the Tools pane"); } fn tools_x(h: &Harness<'static, PdfCraftApp>) -> f32 { diff --git a/crates/ui-egui/src/panels/tools.rs b/crates/ui-egui/src/panels/tools.rs index ac876426a8..211b101982 100644 --- a/crates/ui-egui/src/panels/tools.rs +++ b/crates/ui-egui/src/panels/tools.rs @@ -98,17 +98,36 @@ fn tool_row(g: &'static ToolGroup, pinned: bool) -> ListRow<'static> { row.tooltip(tip) } +fn visible_tools(expanded: bool) -> &'static [ToolGroup] { + if expanded { TOOL_GROUPS } else { &TOOL_GROUPS[..COLLAPSED_TOOLS.min(TOOL_GROUPS.len())] } +} + +/// The natural sidebar width of all localized rows, including icons, badges, pins and the dock body's two insets. +pub(super) fn all_tools_width(ui: &egui::Ui, expanded: bool) -> f32 { + let env = craft::ui::runtime::env::Env::of(ui); + let cache = egui::Id::unique(("all-tools-width", crate::i18n::current().code(), expanded)); + if let Some((tokens, width)) = ui.data(|data| data.get_temp::<(std::sync::Arc<_>, f32)>(cache)) + && std::sync::Arc::ptr_eq(&tokens, &env.tokens) + { + return width; + } + let rows = visible_tools(expanded).iter().map(|group| tool_row(group, true).measure_in(ui, craft::behavior::Proposal::Ideal).x); + let width = (rows.fold(0.0, f32::max) + 2.0 * env.tokens.space.pad.regular).ceil(); + ui.data_mut(|data| data.insert_temp(cache, (std::sync::Arc::clone(&env.tokens), width))); + width +} + /// The All tools sidebar body: the tool list, the first few tools until View more shows them all. Its Expand and /// Close belong to the dock's group header. fn all_tools(app: &mut PdfCraftApp, ui: &mut egui::Ui) { - let shown = if app.all_tools_expanded { TOOL_GROUPS.len() } else { COLLAPSED_TOOLS.min(TOOL_GROUPS.len()) }; - let pins: Vec = TOOL_GROUPS[..shown].iter().map(|g| app.is_tool_pinned(g.id)).collect(); + let shown = visible_tools(app.all_tools_expanded); + let pins: Vec = shown.iter().map(|g| app.is_tool_pinned(g.id)).collect(); let out = List::::new(tl!("All tools").to_owned()) .natural_height(true) .select(SelectMode::Single) .activate(ActivateOn::Click) .selection(Bind::given(Selection::default())) - .show_items(ui, &Rows(shown), &mut |at, _| match (TOOL_GROUPS.get(*at), pins.get(*at)) { + .show_items(ui, &Rows(shown.len()), &mut |at, _| match (shown.get(*at), pins.get(*at)) { (Some(g), Some(pinned)) => tool_row(g, *pinned), _ => ListRow::spacer(), }); diff --git a/crates/ui-egui/src/platform.rs b/crates/ui-egui/src/platform.rs index 7b6b654104..b2bd2e9781 100644 --- a/crates/ui-egui/src/platform.rs +++ b/crates/ui-egui/src/platform.rs @@ -4,3 +4,16 @@ pub(super) mod macos_association; pub(super) mod open_worker; pub mod ui_scale; pub mod updates; + +/// Wall time for comparing PDF and filesystem timestamps on desktop and in the browser. +pub(super) fn wall_time() -> std::time::SystemTime { + #[cfg(not(target_arch = "wasm32"))] + return std::time::SystemTime::now(); + + #[cfg(target_arch = "wasm32")] + { + // File metadata uses std's timestamp type. Only the clock read needs the browser. + let since_epoch = web_time::UNIX_EPOCH.elapsed().unwrap_or_default(); + std::time::UNIX_EPOCH + since_epoch + } +} diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index 1e0dcba7d5..d4faa843a6 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -178,7 +178,11 @@ impl Rig { /// Whether a notice on screen says `text`. fn notice_says(&self, text: &str) -> bool { use egui_kittest::kittest::NodeT as _; - self.h.query_all_by_label_contains(text).any(|node| node.accesskit_node().role() == egui::accesskit::Role::Status) + self.h.query_all_by_label_contains(text).any(|node| { + let card = node.accesskit_node(); + matches!(card.role(), egui::accesskit::Role::Label | egui::accesskit::Role::Status | egui::accesskit::Role::Alert) + && card.children().next().is_some() + }) } fn password_dialog(&self) -> bool { diff --git a/crates/ui-egui/src/shown_boxes.rs b/crates/ui-egui/src/shown_boxes.rs new file mode 100644 index 0000000000..b7b2929f67 --- /dev/null +++ b/crates/ui-egui/src/shown_boxes.rs @@ -0,0 +1,117 @@ +use egui::{Color32, CornerRadius, Stroke}; + +/// Show art, trim and bleed boxes: the colours of Acrobat's Set Page Boxes ▸ Show All Boxes +/// (art red, trim green, bleed blue), drawn bleed, trim, art (outermost first). +const SHOWN: [(usize, Color32); 3] = + [(0, Color32::from_rgb(0x00, 0x50, 0xF0)), (1, Color32::from_rgb(0x00, 0xA0, 0x00)), (2, Color32::from_rgb(0xE0, 0x00, 0x00))]; + +/// The bleed, trim and art boxes each page sets, read once per document generation: walking +/// the page tree every frame would cost a long document its frame rate. +#[derive(Default)] +pub(crate) struct ShownBoxes { + read_at: Option, + boxes: std::sync::Arc; 3]>>, +} + +impl ShownBoxes { + pub(crate) fn get(&mut self, doc: &pdfcraft_engine::Document) -> std::sync::Arc; 3]>> { + let generation = doc.edit_generation(); + if self.read_at != Some(generation) { + self.boxes = std::sync::Arc::new(doc.defined_page_boxes()); + self.read_at = Some(generation); + } + self.boxes.clone() + } +} + +/// Outline `page`'s own boxes, clipped to the page as shown: a box past the crop box is cut at +/// the page's edge, as the rest of the page is. +pub(crate) fn paint_shown( + painter: &egui::Painter, + xf: &crate::canvas::PageXform, + info: &pdfcraft_render::DocInfo, + page: usize, + boxes: &[[Option<[f64; 4]>; 3]], +) { + let Some(own) = boxes.get(page) else { return }; + if page >= info.pages.len() { + return; + } + let painter = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect)); + for (k, color) in SHOWN { + let Some(Some(r)) = own.get(k) else { continue }; + let shown = xf.user_rect(info, page, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]); + painter.rect_stroke(shown, CornerRadius::ZERO, Stroke::new(1.0, color), egui::StrokeKind::Middle); + // Repeated tick groups identify each type even when a box edge is partly clipped. + for line in box_ticks(shown, painter.clip_rect(), k + 1) { + painter.line_segment(line, Stroke::new(1.0, color)); + } + } +} + +/// Tick groups on each edge, generated only near the visible clip to bound work for huge boxes. +fn box_ticks(rect: egui::Rect, clip: egui::Rect, count: usize) -> Vec<[egui::Pos2; 2]> { + const PERIOD: f32 = 30.0; + const SPACING: f32 = 3.0; + let mut out = Vec::new(); + let mut edge = |from: f32, to: f32, fixed: f32, other: f32, horizontal: bool| { + let (along, across) = if horizontal { (clip.x_range(), clip.y_range()) } else { (clip.y_range(), clip.x_range()) }; + let end_tick = fixed + (other - fixed).abs().min(5.0) * (other - fixed).signum(); + if fixed.min(end_tick) > across.max || fixed.max(end_tick) < across.min { + return; + } + let start = from.max(along.min - SPACING * (count - 1) as f32); + let end = to.min(along.max); + let mut at = start + (from - start).rem_euclid(PERIOD); + while at <= end && out.len() + count <= 4096 { + for i in 0..count { + let p = at + i as f32 * SPACING; + if p > end { + break; + } + if p >= along.min { + out.push(if horizontal { + [egui::pos2(p, fixed), egui::pos2(p, end_tick)] + } else { + [egui::pos2(fixed, p), egui::pos2(end_tick, p)] + }); + } + } + let next = at + PERIOD; + if next <= at { + break; + } + at = next; + } + }; + edge(rect.left(), rect.right(), rect.top(), rect.bottom(), true); + edge(rect.left(), rect.right(), rect.bottom(), rect.top(), true); + edge(rect.top(), rect.bottom(), rect.left(), rect.right(), false); + edge(rect.top(), rect.bottom(), rect.right(), rect.left(), false); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn page_box_kinds_have_distinct_inward_tick_counts() { + let rect = egui::Rect::from_min_max(egui::pos2(10.0, 20.0), egui::pos2(90.0, 60.0)); + for (kind, _) in SHOWN { + let ticks = box_ticks(rect, rect, kind + 1); + assert!(ticks.len() >= 4 * (kind + 1)); + assert!(ticks.iter().flatten().all(|p| rect.contains(*p))); + } + // A clip that shows exactly one group on the top edge still distinguishes each box. + let clip = egui::Rect::from_min_max(egui::pos2(40.0, 19.0), egui::pos2(48.0, 26.0)); + for count in 1..=3 { + let ticks = box_ticks(rect, clip, count); + assert_eq!(ticks.len(), count); + for (i, tick) in ticks.into_iter().enumerate() { + let x = 40.0 + i as f32 * 3.0; + assert_eq!(tick, [egui::pos2(x, 20.0), egui::pos2(x, 25.0)]); + } + } + } +} diff --git a/crates/ui-egui/src/tools/comments/menu.rs b/crates/ui-egui/src/tools/comments/menu.rs index d9e8941975..9a8eea8411 100644 --- a/crates/ui-egui/src/tools/comments/menu.rs +++ b/crates/ui-egui/src/tools/comments/menu.rs @@ -98,6 +98,26 @@ fn row(ui: &mut egui::Ui, label: &str, enabled: bool) -> bool { MenuItem::new(label.to_string()).enabled(enabled).show(ui).ran } +/// Mark the selected text instead, on a highlight, underline, strikethrough or squiggly underline: the +/// markup takes the text selected on its page as its range, extended or reduced, and keeps its colour, note +/// and replies (#4824). Disabled, saying why, until text on that page alone is selected. +fn mark_selection_row(ui: &mut egui::Ui, view: &mut DocView, info: &DocInfo, a: &Annotation, allowed: bool) -> Option { + if !matches!(a.subtype.as_str(), "Highlight" | "Underline" | "StrikeOut" | "Squiggly") { + return None; + } + let quads = view.selection_quads_on(info, a.page); + let mut item = MenuItem::new(tl!("Mark the selected text instead")).enabled(allowed && !a.locked && quads.is_some()); + if allowed && !a.locked && quads.is_none() { + item = item.tooltip(tl!("Select the text it should mark first")); + } + if !item.show(ui).ran { + return None; + } + let quads = quads?; + view.clear_selection(); + Some(Edit::SetMarkupRange { page: a.page, index: a.index, quads }) +} + /// Rows of the canvas context menu for the selected comment (or the page), inside `Menu::context`. pub(crate) fn context_rows(ui: &mut egui::Ui, cx: CommentMenuCx<'_>) -> Option { let CommentMenuCx { view, info, deletable, prefs, rights, recent, tool } = cx; @@ -172,6 +192,9 @@ pub(crate) fn context_rows(ui: &mut egui::Ui, cx: CommentMenuCx<'_>) -> Option, + /// What added columns are named after: the first free "TableK" (or "CopyK") when the window opened. base: String, /// The document's edit generation when the window opened: any edit since closes it. generation: u64, @@ -55,7 +57,8 @@ pub struct FieldTableDraft { /// Two drafts are the same table in the same place; what is kept for the next frame isn't part of it. impl PartialEq for FieldTableDraft { fn eq(&self, other: &Self) -> bool { - (self.doc, self.page, &self.table, &self.base, self.generation) == (other.doc, other.page, &other.table, &other.base, other.generation) + (self.doc, self.page, &self.table, &self.source, &self.base, self.generation) + == (other.doc, other.page, &other.table, &other.source, &other.base, other.generation) } } @@ -63,7 +66,7 @@ impl PartialEq for FieldTableDraft { impl Default for FieldTableDraft { fn default() -> Self { let base = "Table1".to_owned(); - FieldTableDraft { doc: DocId(0), page: 0, table: FieldTable::new([0.0, 0.0, 1.0, 1.0], &base), base, generation: 0, laid: None } + FieldTableDraft { doc: DocId(0), page: 0, table: FieldTable::new([0.0, 0.0, 1.0, 1.0], &base), source: None, base, generation: 0, laid: None } } } @@ -94,7 +97,34 @@ impl FieldTableDraft { /// the first base `form` leaves free. pub(crate) fn new(doc: DocId, page: usize, rect: [f64; 4], form: &[FormField], generation: u64) -> Self { let base = field_table::free_base(form.iter().map(|f| f.name.as_str())); - FieldTableDraft { doc, page, table: FieldTable::new(rect, &base), base, generation, laid: None } + FieldTableDraft { doc, page, table: FieldTable::new(rect, &base), source: None, base, generation, laid: None } + } + + /// A grid of copies of widget `widget` of the field `source`, starting as two copies beside it + /// ([`copy_grid`]) on its page (`info`), every column named after the first "CopyK" `form` + /// leaves free. `None` when the widget isn't on a page or there is no room beside it. + pub(crate) fn copies(doc: DocId, info: &PageInfo, form: &[FormField], source: (String, usize), generation: u64) -> Option { + let widget = form.iter().find(|f| f.name == source.0)?.widgets.get(source.1)?; + let page = widget.page?; + let (rect, rows, columns) = copy_grid(info, widget.rect)?; + let base = free_copy_base(form); + let mut table = FieldTable::new(rect, &base); + table.rows = rows; + table.set_columns(columns, &base); + Some(FieldTableDraft { doc, page, table, source: Some(source), base, generation, laid: None }) + } + + /// The edit Add fields applies: new text fields, or copies of the source. + fn edit(&self, info: &PageInfo, form: &[FormField]) -> Result { + match &self.source { + Some((name, widget)) => field_table::copy_edit(&self.table, self.page, info, form, name, *widget), + None => field_table::edit(&self.table, self.page, info, form), + } + } + + /// The window's title, and its group's. + fn title(&self) -> &'static str { + if self.source.is_some() { tl!("Copy into Grid") } else { tl!("Text Field Table") } } /// The table laid out on its page (`info`, in a form whose fields are `form`), worked out again @@ -104,8 +134,7 @@ impl FieldTableDraft { if let Some(laid) = self.laid.as_ref().filter(|l| l.table == self.table) { return Arc::clone(laid); } - let laid = - Arc::new(Laid { table: self.table.clone(), cells: self.table.cells(), edit: field_table::edit(&self.table, self.page, info, form) }); + let laid = Arc::new(Laid { table: self.table.clone(), cells: self.table.cells(), edit: self.edit(info, form) }); self.laid = Some(Arc::clone(&laid)); laid } @@ -148,7 +177,7 @@ impl StackDialog for FieldTableDialog { let refusal = held.refusal().filter(|(_, refused)| **refused == *draft).map(|(reason, _)| reason.clone()); // The layout of a table that did not change this pass is kept in the draft, so the body asks for it again for free. draft.laid(info, form); - let shown = FormDialog::new(tl!("Text Field Table").to_owned(), Bind::bound(&mut *draft)) + let shown = FormDialog::new(draft.title().to_owned(), Bind::bound(&mut *draft)) .ok_label(tl!("Add fields").to_owned()) .enter_confirms(false) .accept_stays_open(true) @@ -197,8 +226,13 @@ impl StackDialog for FieldTableDialog { /// while it can't. fn json_fields(&self) -> Option { let t = &self.draft.table; - let reason = field_table::edit(t, self.draft.page, &self.info, &self.form).err().map(|e| e.said(&i18n::words)); + let reason = self.draft.edit(&self.info, &self.form).err().map(|e| e.said(&i18n::words)); let mut map = serde_json::Map::new(); + if let Some((name, widget)) = &self.draft.source { + map.insert("source".into(), json!(name)); + map.insert("source_widget".into(), json!(widget)); + map.insert("rect".into(), json!(t.rect)); + } map.insert("rows".into(), json!(t.rows)); map.insert("columns".into(), json!(t.columns.len())); map.insert("row_gap".into(), json!(t.row_gap)); @@ -221,6 +255,19 @@ pub(crate) fn open(app: &mut PdfCraftApp, doc: DocId, page: usize, rect: [f64; 4 crate::dialogs::host::open(app, FieldTableDialog { draft, info, form: form.to_vec(), held: HeldAnswer::new() }); } +/// Opens the window for copies of widget `widget` of the field `name` of `doc` in a grid beside it (Copy into Grid), or +/// says there is no room for them. Nothing opens when the field or its page is gone. Whether it opened. +pub(crate) fn open_copies(app: &mut PdfCraftApp, doc: DocId, name: String, widget: usize, form: &[FormField], generation: u64) -> bool { + let Some(page) = form.iter().find(|f| f.name == name).and_then(|f| f.widgets.get(widget)).and_then(|w| w.page) else { return false }; + let Some(info) = app.session.get(doc).and_then(|d| d.info.pages.get(page)).cloned() else { return false }; + let Some(draft) = FieldTableDraft::copies(doc, &info, form, (name, widget), generation) else { + app.notify_tr("There is not enough space beside this field for the copies."); + return false; + }; + crate::dialogs::host::open(app, FieldTableDialog { draft, info, form: form.to_vec(), held: HeldAnswer::new() }); + true +} + /// Closes the window when its page or document is no longer what it was opened on, and adds the table when asked to; once per /// pass from the dialogs' results. pub(crate) fn pass(app: &mut PdfCraftApp, ctx: &Context) { @@ -255,7 +302,10 @@ pub(crate) fn preview(dialogs: &mut DialogHost, doc: DocId) -> Option { /// The window's controls, the names the table will have, and why it can't be added if it can't. Returns whether it can. fn body(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[FormField], refusal: Option<&Label>) -> bool { Stack::new().show(ui, |ui, _| { - FieldGroup::new(tl!("Text Field Table").to_owned()).show(ui, |ui, _| { + if d.source.is_some() { + copy_area(ui, d, info); + } + FieldGroup::new(d.title().to_owned()).show(ui, |ui, _| { whole(ui, "Rows", &mut d.table.rows, 1, MAX_ROWS); let mut columns = d.table.columns.len(); if whole(ui, "Columns", &mut columns, 1, MAX_COLUMNS) { @@ -290,6 +340,77 @@ fn body(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[FormField laid.edit.is_ok() } +/// Where the copies go, in points from the displayed page's top-left. Each box is held so the area stays on the page. +fn copy_area(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo) { + let [x0, y0, x1, y1] = d.table.rect; + let (mut left, mut top) = (x0.min(x1), y0.min(y1)); + let (mut width, mut height) = ((x1 - x0).abs(), (y1 - y0).abs()); + let (page_width, page_height) = (f64::from(info.width), f64::from(info.height)); + if ![left, top, width, height, page_width, page_height].iter().all(|v| v.is_finite()) { + return; + } + FieldGroup::new(tl!("Area").to_owned()).show(ui, |ui, _| { + length(ui, "Left", &mut left, 0.0, page_width - width); + length(ui, "Top", &mut top, 0.0, page_height - height); + length(ui, "Width", &mut width, 1.0, page_width - left); + length(ui, "Height", &mut height, 1.0, page_height - top); + }); + d.table.rect = [left, top, left + width, top + height]; +} + +/// A length in points held to `least..=most` (to `least` when `most` is under it). +fn length(ui: &mut Ui, label: &str, value: &mut f64, least: f64, most: f64) { + let most = most.max(least); + let mut typed = Some(*value); + Field::new(tl!(label).to_owned()).show(ui, |ui, _| { + NumberField::new(tl!(label).to_owned(), Bind::bound(&mut typed)).range(least..=most).unit("pt").show(ui); + }); + // An emptied field keeps the length; `max` then `min` rather than `clamp`, which panics if the bounds cross. + if let Some(v) = typed.filter(|v| v.is_finite()) { + *value = v.max(least).min(most); + } +} + +/// The first of "Copy", "Copy2", … that no field in `form` is named after (`{base}_…`), so a grid's names start free. +fn free_copy_base(form: &[FormField]) -> String { + let taken: std::collections::HashSet<&str> = form.iter().filter_map(|f| f.name.split_once('_').map(|(head, _)| head)).collect(); + // One of the first `taken.len() + 1` is always free. + (1..=taken.len().saturating_add(1)) + .map(|k| if k == 1 { "Copy".to_owned() } else { format!("Copy{k}") }) + .find(|base| !taken.contains(base.as_str())) + .unwrap_or_else(|| "Copy".to_owned()) +} + +/// Points between a field and the grid of its copies. +const COPY_GAP: f64 = 8.0; + +/// Where a grid of copies of a widget at `rect` (user space) starts: two copies below the widget, else above, else to its +/// right, else to its left, [`COPY_GAP`] from it and wholly on the displayed page. A view-space area with its rows and +/// columns; `None` when there is no room on any side. +pub(crate) fn copy_grid(info: &PageInfo, rect: [f64; 4]) -> Option<([f64; 4], usize, usize)> { + let a = info.user_to_view_f64(rect[0], rect[1]); + let b = info.user_to_view_f64(rect[2], rect[3]); + let (left, right, top, bottom) = (a[0].min(b[0]), a[0].max(b[0]), a[1].min(b[1]), a[1].max(b[1])); + let (width, height) = (right - left, bottom - top); + let (page_width, page_height) = (f64::from(info.width), f64::from(info.height)); + if ![left, right, top, bottom, page_width, page_height].iter().all(|v| v.is_finite()) || width <= 0.0 || height <= 0.0 { + return None; + } + let (tall, wide) = (COPY_GAP + height * 2.0, COPY_GAP + width * 2.0); + let (fits_across, fits_down) = (left >= 0.0 && right <= page_width, top >= 0.0 && bottom <= page_height); + if fits_across && bottom + tall <= page_height { + Some(([left, bottom + COPY_GAP, right, bottom + tall], 2, 1)) + } else if fits_across && top >= tall { + Some(([left, top - tall, right, top - COPY_GAP], 2, 1)) + } else if fits_down && right + wide <= page_width { + Some(([right + COPY_GAP, top, right + wide, bottom], 1, 2)) + } else if fits_down && left >= wide { + Some(([left - wide, top, left - COPY_GAP, bottom], 1, 2)) + } else { + None + } +} + /// A whole number field held to `least..=most`. Whether the number changed. fn whole(ui: &mut Ui, label: &str, value: &mut usize, least: usize, most: usize) -> bool { let mut typed = Some(*value as f64); @@ -455,6 +576,21 @@ fn paint_table(draw: &Draw<'_>, xf: &PageXform, visible: Rect, preview: &Preview mod tests { use super::*; + /// The copies start beside their field, on the page, and say so when there is no room. + #[test] + fn a_copy_grid_starts_on_the_page_without_covering_the_source() { + let info = PageInfo { width: 400.0, height: 300.0, label: "1".into(), crop: [0.0, 0.0, 400.0, 300.0], rotation: 0 }; + let inside = |r: [f64; 4]| r[0] >= 0.0 && r[1] >= 0.0 && r[2] <= 400.0 && r[3] <= 300.0; + let apart = |a: [f64; 4], b: [f64; 4]| a[2] <= b[0] || b[2] <= a[0] || a[3] <= b[1] || b[3] <= a[1]; + // A field near the top of the page (user y up) gets its copies under it; one near the bottom, over it. + for (user, view) in [([10.0, 270.0, 110.0, 290.0], [10.0, 10.0, 110.0, 30.0]), ([10.0, 0.0, 110.0, 20.0], [10.0, 280.0, 110.0, 300.0])] { + let (grid, rows, columns) = copy_grid(&info, user).expect("room above or below"); + assert_eq!((rows, columns), (2, 1)); + assert!(inside(grid) && apart(grid, view), "{grid:?} is on the page and clear of {view:?}"); + } + assert!(copy_grid(&info, [0.0, 0.0, 400.0, 300.0]).is_none(), "a field filling the page leaves no room"); + } + fn draft(columns: usize) -> FieldTableDraft { let mut d = FieldTableDraft::new(DocId(1), 0, [0.0, 0.0, 400.0, 200.0], &[], 0); d.table.set_columns(columns, &d.base); diff --git a/crates/ui-egui/src/tools/forms_ui.rs b/crates/ui-egui/src/tools/forms_ui.rs index 29a645b878..a04c78ad16 100644 --- a/crates/ui-egui/src/tools/forms_ui.rs +++ b/crates/ui-egui/src/tools/forms_ui.rs @@ -162,12 +162,18 @@ fn fillable(f: &FormField) -> bool { !f.read_only() && !matches!(f.kind, FormFieldKind::PushButton | FormFieldKind::Signature) } -/// The fillable widgets in the order Tab and Shift+Tab visit them. +/// Whether the field takes the focus, on a click and as a Tab stop: one that can be filled in, or a +/// push button, as another viewer gives it the focus and a Tab stop too. +fn takes_focus(f: &FormField) -> bool { + fillable(f) || (f.kind == FormFieldKind::PushButton && !f.read_only()) +} + +/// The widgets that take the focus, in the order Tab and Shift+Tab visit them. pub fn tab_order(form: &[FormField], info: &DocInfo) -> Vec<(usize, usize)> { let mut order: Vec<(usize, usize, usize)> = form .iter() .enumerate() - .filter(|(_, field)| fillable(field)) + .filter(|(_, field)| takes_focus(field)) .flat_map(|(fi, field)| { field .widgets @@ -477,6 +483,16 @@ pub(crate) fn field_press( } } +/// Presses the push button `f` (its widget `w`): queues its action, or says it has none. +fn press_button(session: &mut PageSession, f: &FormField, w: &FormWidget) { + match &f.button { + Some(a) => session.forms.button = Some((f.name.clone(), pdfcraft_engine::js::field_object_id(f.obj), a.clone())), + // Its press already ran its mouse-down action. + None if w.mouse_down => {} + None => session.forms.notice = Some(FormNotice::NoAction(f.name.clone())), + } +} + /// What a click at `at` on widget `wi` of `f` (field index `field`, widget `w`) does, with `mods` held. fn clicked( session: &mut PageSession, @@ -494,12 +510,16 @@ fn clicked( } match f.kind { _ if f.read_only() || w.read_only => session.forms.notice = Some(FormNotice::ReadOnly(f.name.clone())), - FormFieldKind::PushButton => match &f.button { - Some(a) => session.forms.button = Some((f.name.clone(), pdfcraft_engine::js::field_object_id(f.obj), a.clone())), - // Its press already ran its mouse-down action. - None if w.mouse_down => {} - None => session.forms.notice = Some(FormNotice::NoAction(f.name.clone())), - }, + FormFieldKind::PushButton => { + // The button takes the focus, as a check box does: what it leaves commits and blurs first, + // and Tab goes on from it. + if session.forms.focus.as_ref().is_none_or(|x| !x.is_on(f, wi)) { + commit(session, form); + session.forms.focus = Some(open_focus(f, wi)); + } + session.forms.refocus = true; + press_button(session, f, w); + } FormFieldKind::Text if let Some(script) = &w.mouse_up_script => { // Close the editor so the script can replace its value without a stale draft. commit(session, form); @@ -624,6 +644,13 @@ pub(crate) fn field_key(session: &mut PageSession, info: &DocInfo, form: &[FormF None } Intent::Tab => tab_to_next_field(session, info, form, f, widget, true, geo), + // Space or Enter presses the focused push button, as a click's release does. + Intent::Activate | Intent::Space if !read_only && f.kind == FormFieldKind::PushButton => { + if let Some(w) = f.widgets.get(widget) { + press_button(session, f, w); + } + None + } Intent::Activate | Intent::Space if !read_only => match f.kind { FormFieldKind::Radio => select_edit(f, widget), FormFieldKind::CheckBox => toggle_edit(f, widget), diff --git a/crates/ui-egui/src/tools/prepare.rs b/crates/ui-egui/src/tools/prepare.rs index f27231dd15..d83871d6b8 100644 --- a/crates/ui-egui/src/tools/prepare.rs +++ b/crates/ui-egui/src/tools/prepare.rs @@ -15,11 +15,13 @@ use pdfcraft_render::DocInfo; use crate::canvas::{DocView, PageBoxDrag, PageSession, PageXform}; +mod clip; pub(crate) mod dialog; mod draft; mod properties; mod tabs; pub(crate) mod tool; +pub(crate) use clip::{copy_selected, paste_copied, pastes_fields}; pub use dialog::FieldPropsDialog; pub use draft::{ACTION_KINDS, ActionDraft, FieldDraft, FieldTab}; @@ -167,6 +169,15 @@ pub struct PrepareView { pub also: Vec<(String, usize)>, /// Select the field an Add field edit creates (the form's length before it). pub select_added: Option, + /// Select every field a Paste creates (the form's length before it). + select_pasted: Option, + /// The widgets Copy took, as they were selected: field name and widget object, so a paste + /// after the field's widgets change still finds the same one. + copied: Vec<(String, Option)>, + /// The text Copy put on the clipboard. + clip: String, + /// Paste count per destination page: each paste there lands one step further. + pastes: std::collections::HashMap, gesture: Gesture, outcome: PrepareOutcome, } @@ -418,9 +429,15 @@ pub(crate) fn select_all(view: &mut DocView, form: &[FormField]) { view.session.prepare.also = selected.collect(); } -/// After an Add field edit: select the new field (the form's last). +/// After an Add field edit: select the new field (the form's last); after a Paste, every +/// widget of the pasted fields. pub(crate) fn after_refresh(session: &mut PageSession, form: &[FormField]) { session.prepare.also.retain(|(name, wi)| form.iter().any(|f| &f.name == name && *wi < f.widgets.len())); + if let Some(added) = session.prepare.select_pasted.take().and_then(|n| form.get(n..)).filter(|a| !a.is_empty()) { + let mut keys = added.iter().flat_map(|f| (0..f.widgets.len()).map(|wi| (f.name.clone(), wi))); + session.prepare.selected = keys.next(); + session.prepare.also = keys.collect(); + } if let Some(n) = session.prepare.select_added.take() { if form.len() > n && let Some(f) = form.last() diff --git a/crates/ui-egui/src/tools/prepare/clip.rs b/crates/ui-egui/src/tools/prepare/clip.rs new file mode 100644 index 0000000000..17e6aaeb9d --- /dev/null +++ b/crates/ui-egui/src/tools/prepare/clip.rs @@ -0,0 +1,118 @@ +//! Copy and paste the selected fields while preparing a form (#1571). + +use pdfcraft_engine::{Edit, FormField}; +use pdfcraft_render::PageInfo; + +use super::PrepareView; +use crate::canvas::DocView; + +/// How far a pasted field lands from the one it copies, in points right and down on the page as shown. +const PASTE_STEP: f64 = 18.0; + +/// Copy: remember the selected widgets and return the text to put on the clipboard (their +/// field names, one per line). Paste brings the fields back only while the clipboard still +/// holds that text, not after something else has been copied since. `None` with nothing selected. +pub(crate) fn copy_selected(prepare: &mut PrepareView, form: &[FormField]) -> Option { + prepare.selected.as_ref()?; + let object = |name: &str, wi: usize| form.iter().find(|f| f.name == name).and_then(|f| f.widgets.get(wi)).map(|w| w.obj); + prepare.copied = prepare.selected.iter().chain(prepare.also.iter()).map(|(n, wi)| (n.clone(), object(n, *wi))).collect(); + prepare.pastes.clear(); + prepare.clip = prepare.names().join("\n"); + Some(prepare.clip.clone()) +} + +/// Whether pasting `text` brings back the fields Copy took. +pub(crate) fn pastes_fields(prepare: &PrepareView, text: Option<&str>) -> bool { + !prepare.copied.is_empty() && text.is_some_and(|t| t.replace("\r\n", "\n").trim_end() == prepare.clip.trim_end()) +} + +/// Paste: a copy of every copied field on the current page, as one undoable step. Each copy is a +/// field of its own with the next free name. On the page they came from the copies land one step +/// right and down, and each further paste one step more; on another page the first lands in +/// place. The copies are selected once the edit is applied. +pub(crate) fn paste_copied(view: &mut DocView, form: &[FormField], pages: &[PageInfo]) -> Option { + let current = view.current(); + let rotation = view.view.rotation; + let prepare = &mut view.session.prepare; + let mut sources: Vec<(String, Vec)> = Vec::new(); + let mut from_page = None; + for (name, obj) in &prepare.copied { + // By its object: a widget deleted since is skipped, and one that moved in the list is found. + let Some(f) = form.iter().find(|f| &f.name == name) else { continue }; + let Some((wi, w)) = f.widgets.iter().enumerate().find(|(_, w)| Some(w.obj) == *obj) else { continue }; + from_page = from_page.or(w.page); + match sources.iter_mut().find(|(n, _)| n == name) { + Some((_, widgets)) => widgets.push(wi), + None => sources.push((name.clone(), vec![wi])), + } + } + if sources.is_empty() { + return None; + } + let steps = paste_steps(&mut prepare.pastes, from_page, current); + let d = PASTE_STEP * f64::from(steps); + let (dx, dy) = unturned_step(d, rotation); + let offset = match pages.get(current) { + Some(p) => { + let (o, m) = (p.view_to_user_f64(0.0, 0.0), p.view_to_user_f64(dx, dy)); + [m[0] - o[0], m[1] - o[1]] + } + None => [dx, -dy], + }; + let mut edits: Vec = sources.into_iter().map(|(name, widgets)| Edit::PasteField { name, widgets, page: current, offset }).collect(); + prepare.selected = None; + prepare.also.clear(); + prepare.select_pasted = Some(form.len()); + if edits.len() == 1 { + return edits.pop(); + } + Some(Edit::Batch { label: "Paste fields".into(), edits }) +} + +/// Count pastes independently so visiting another destination starts in place. +fn paste_steps(pastes: &mut std::collections::HashMap, from_page: Option, current: usize) -> u32 { + let count = pastes.entry(current).or_default(); + let steps = count.saturating_add(u32::from(from_page == Some(current))); + *count = count.saturating_add(1); + steps +} + +/// The step right and down by `d` on screen, in the page's unturned view, for a view turned +/// clockwise by `rotation` degrees (View ▸ Rotate View, which leaves the page's `/Rotate` alone). +fn unturned_step(d: f64, rotation: u16) -> (f64, f64) { + match rotation % 360 { + 90 => (d, -d), + 180 => (-d, -d), + 270 => (-d, d), + _ => (d, d), + } +} + +#[cfg(test)] +mod tests { + use super::{paste_steps, unturned_step}; + + #[test] + fn paste_displacement_progresses_separately_on_each_page() { + let mut pastes = Default::default(); + assert_eq!(paste_steps(&mut pastes, Some(0), 0), 1); + assert_eq!(paste_steps(&mut pastes, Some(0), 1), 0); + assert_eq!(paste_steps(&mut pastes, Some(0), 0), 2); + assert_eq!(paste_steps(&mut pastes, Some(0), 1), 1); + assert_eq!(paste_steps(&mut pastes, Some(0), 2), 0); + } + + /// Turned clockwise by the view rotation, the unturned step is right and down again. + #[test] + fn the_paste_step_turns_back_with_the_view() { + let turn = |(x, y): (f64, f64), r: u16| match r { + 90 => (-y, x), + 180 => (-x, -y), + 270 => (y, -x), + _ => (x, y), + }; + for r in [0, 90, 180, 270] { + assert_eq!(turn(unturned_step(18.0, r), r), (18.0, 18.0), "{r}°"); + } + } +} diff --git a/crates/ui-egui/src/tools/stamps_ui.rs b/crates/ui-egui/src/tools/stamps_ui.rs index 29841eb96b..728ec2cfc2 100644 --- a/crates/ui-egui/src/tools/stamps_ui.rs +++ b/crates/ui-egui/src/tools/stamps_ui.rs @@ -21,7 +21,6 @@ use egui::Pos2; use pdfcraft_engine::{Edit, MarkFile, NewAnnotation, Shape, StampGroup, StampKind, Style}; use serde::{Deserialize, Serialize}; -// PLAN: assumed `PageMap::to_user(&self, page: usize, at: Point) -> [f64; 2]` and `crate::comments::PageMap<'a>` (pdf-comments-w7, A-1) use crate::comments::PageMap; use crate::{PdfCraftApp, QuickTool}; @@ -159,7 +158,7 @@ impl<'a> StampTool<'a> { impl CanvasTool for StampTool<'_> { fn press(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) -> ToolAction { let Some(placed) = self.map.pages.iter().find(|p| p.rect.contains(pointer.pos)) else { return ToolAction::Ignored }; - let at = placed.to_page(pointer.pos); + let at = self.map.view.to_doc(pointer.pos); let user = self.map.to_user(placed.page, at); *self.press = Some(StampPress { page: placed.page, pos: pointer.pos, user }); ToolAction::Claimed diff --git a/crates/ui-egui/src/workflows/combine_ui/table.rs b/crates/ui-egui/src/workflows/combine_ui/table.rs index c55b79961d..9a6b294d70 100644 --- a/crates/ui-egui/src/workflows/combine_ui/table.rs +++ b/crates/ui-egui/src/workflows/combine_ui/table.rs @@ -1,5 +1,4 @@ use std::cell::RefCell; -use std::time::SystemTime; use craft::behavior::{ColumnKey, ColumnWidth, DisplayOrder, EditEvent, IconId, ItemSource, ReorderKeys}; use craft::theme::variant::Tone; @@ -112,7 +111,7 @@ struct RowData { fn row_data(app: &mut PdfCraftApp, checks: &[Result]) -> Vec { let conflicts = app.combine_conflicts.per_file.clone(); let twice = app.combine_tab.duplicate_warnings(&app.combine_draft); - let now = SystemTime::now(); + let now = crate::platform::wall_time(); app.combine_draft .iter() .enumerate() diff --git a/crates/ui-egui/src/workflows/optimize_ui.rs b/crates/ui-egui/src/workflows/optimize_ui.rs index 672cb66808..99da6a21ed 100644 --- a/crates/ui-egui/src/workflows/optimize_ui.rs +++ b/crates/ui-egui/src/workflows/optimize_ui.rs @@ -5,6 +5,7 @@ //! queue and shows its progress in a notice with a bar and a Cancel button; the copy is saved once //! it is done. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, PoisonError, RwLock}; use craft::behavior::{ColumnKey, ColumnWidth, DisplayOrder, ItemSource}; @@ -490,12 +491,17 @@ impl DisplayOrder for AuditRows<'_> { impl ItemSource for AuditRows<'_> {} -/// The audit's explanation over its table, read from `rows` each pass. No rows show until the measure result arrives. -fn audit_row(rows: Arc>>) -> Param { +/// The audit's explanation over its table, read from `rows` each pass. While `pending`, the table is empty and says it is measuring, +/// so no other document's or earlier edit's figures pass for the active document's. +fn audit_row(rows: Arc>>, pending: Arc) -> Param { Param::custom("space-audit", tl!("Space Audit"), move |ui, _fields, _cx| { - let lines = audit_lines(&rows.read().unwrap_or_else(PoisonError::into_inner)); + let pending = pending.load(Ordering::Acquire); + let lines = if pending { Vec::new() } else { audit_lines(&rows.read().unwrap_or_else(PoisonError::into_inner)) }; let shown = Stack::new().fill_width().show(ui, |ui, _| { Text::new(tl!("What takes up the space in this file, by kind of content.")).show(ui); + if pending { + Text::new(tl!("Measuring…")).show(ui); + } let columns = vec![ ColumnSpec::new(DESCRIPTION, tl!("Description"), ColumnWidth::Content), ColumnSpec::new(BYTES, tl!("Bytes"), ColumnWidth::Content).numeric(), @@ -525,16 +531,16 @@ fn audit_row(rows: Arc>>) -> Param { /// result each pass. It starts no measure, so a dialog may build it every pass; `properties.rs` runs `measure_space_audit` /// when Properties ▸ Space Audit opens and again after an edit. pub(crate) fn space_audit_param(app: &PdfCraftApp) -> Param { - audit_row(app.space_audit.clone()) + audit_row(app.space_audit.clone(), app.space_audit_pending.clone()) } /// Opens the audit dialog: over the Optimizer when `from_optimizer`, so its values survive, else alone. pub(crate) fn open_space_audit(app: &mut PdfCraftApp, ctx: &egui::Context, from_optimizer: bool) { app.measure_space_audit(); let key = if from_optimizer { OPTIMIZER_AUDIT_KEY } else { SPACE_AUDIT_KEY }; - let rows = app.space_audit.clone(); + let (rows, pending) = (app.space_audit.clone(), app.space_audit_pending.clone()); let dialog = HostedParamDialog::new(ctx, key, DialogFields::new(), move |fields| { - ParamDialog::new(key, tl!("Space Audit"), vec![audit_row(rows.clone())]).read_only(true).values(Bind::bound(fields)) + ParamDialog::new(key, tl!("Space Audit"), vec![audit_row(rows.clone(), pending.clone())]).read_only(true).values(Bind::bound(fields)) }); if from_optimizer { crate::dialogs::host::open_over(app, dialog.instance(AUDIT_INSTANCE)); @@ -565,9 +571,25 @@ pub(crate) fn pass(app: &mut PdfCraftApp, ctx: &egui::Context) { } #[cfg(target_arch = "wasm32")] app.space_audit_jobs.run_inline(1); + let current = app.active_ids().and_then(|(_, id)| app.session.get(id).map(|doc| (id, doc.edit_generation()))); while let Some(done) = app.space_audit_jobs.try_recv() { + // A late audit of another document, or of this one before a later edit, is not the audit to show. + if current.as_ref() != Some(&done.key) { + continue; + } *app.space_audit.write().unwrap_or_else(PoisonError::into_inner) = done.result; app.space_audit_of = Some(done.key); + app.space_audit_pending.store(false, Ordering::Release); + } + // An edit that landed before the first measure finished made that result stale and it was dropped above: nothing else starts + // the audit again for these dialogs (Properties does it for its own tab), so they would stay on "Measuring…". Start it for the + // current edit, once. + if let Some(key) = current.as_ref() + && app.space_audit_pending.load(Ordering::Acquire) + && app.space_audit_of.as_ref() != Some(key) + && !app.space_audit_jobs.contains(key) + { + app.measure_space_audit(); } } @@ -659,10 +681,17 @@ impl PdfCraftApp { let Some((_, id)) = self.active_ids() else { self.space_audit.write().unwrap_or_else(PoisonError::into_inner).clear(); self.space_audit_of = None; + self.space_audit_pending.store(false, Ordering::Release); return; }; let Some(doc) = self.session.get(id) else { return }; let key = (id, doc.edit_generation()); + // The rows held are another document's or an earlier edit's: drop them and say it is measuring until this audit arrives. + if self.space_audit_of != Some(key) { + self.space_audit.write().unwrap_or_else(PoisonError::into_inner).clear(); + self.space_audit_of = None; + self.space_audit_pending.store(true, Ordering::Release); + } let job = doc.space_audit_job(); self.space_audit_jobs.submit(key, Priority::BACKGROUND, move |_| job.run()); } diff --git a/crates/ui-egui/tests/it/bates_files.rs b/crates/ui-egui/tests/it/bates_files.rs new file mode 100644 index 0000000000..f6fc363b5a --- /dev/null +++ b/crates/ui-egui/tests/it/bates_files.rs @@ -0,0 +1,106 @@ +//! Bates numbering ▸ Add to files…: one run over several files, written as numbered copies. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use crate::support::AppHarness as _; +use craft::host::{Picked, ScriptedFiles}; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use pdfcraft_render::{PageRenderer, RenderRequest, RequestKind}; +use pdfcraft_ui_egui::PdfCraftApp; + +fn harness(files: Arc) -> Harness<'static, PdfCraftApp> { + let host = crate::support::host_with_files(files); + Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_eframe(move |cc| { + crate::support::install_runtime(&cc.egui_ctx); + let mut app = crate::support::test_app(host); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + app + }) +} + +/// The Bates number on each page of `pdf`: the run of digits in the page's text after "CASE-". +fn numbers(pdf: Vec) -> Vec { + let mut r = PageRenderer::new(Arc::new(pdf), Default::default()); + (0..r.page_count()) + .map(|p| { + let out = r.render(RenderRequest { page: p, kind: RequestKind::Text, scale: 1.0, ..Default::default() }); + let text = out.text.map(|t| t.plain_text()).unwrap_or_default(); + let at = text.find("CASE-").expect("a Bates number on every page") + "CASE-".len(); + text[at..].chars().take_while(char::is_ascii_digit).collect::().parse().unwrap() + }) + .collect() +} + +/// Opens the dialog, fills its list with `sources` through Browse, types the prefix and presses Number. +fn number(h: &mut Harness<'static, PdfCraftApp>) { + assert!(h.execute("edit.bates_files")); + h.run_steps(3); + let dialog = h.get_by_role_and_label(Role::Dialog, "Add Bates Numbering to Files"); + dialog.get_by_label("Browse…").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::TextInput, "Prefix").type_text("CASE-"); + h.run_steps(2); + h.get_by_label("Number").click(); + h.run_steps(4); +} + +fn paths() -> (PathBuf, PathBuf) { + (Path::new("case").join("b.pdf"), Path::new("case").join("a.pdf")) +} + +#[test] +fn each_copy_continues_the_numbers_of_the_one_before_and_the_originals_stay() { + let (b, a) = paths(); + let (b_bytes, a_bytes) = (crate::support::fixtures::pdf_pages(2), crate::support::fixtures::pdf_pages(3)); + let files = + Arc::new(ScriptedFiles::answering([Picked::Paths(vec![b.clone(), a.clone()])]).with_file(&b, b_bytes.clone()).with_file(&a, a_bytes.clone())); + let mut h = harness(files.clone()); + number(&mut h); + let first = numbers(files.file(&Path::new("case").join("b_Bates.pdf")).expect("the first file's copy")); + let second = numbers(files.file(&Path::new("case").join("a_Bates.pdf")).expect("the second file's copy")); + assert_eq!(first.len(), 2); + assert_eq!(second.len(), 3); + for pages in [&first, &second] { + assert!(pages.windows(2).all(|w| w[1] == w[0] + 1), "pages count up by one: {pages:?}"); + } + assert_eq!(second[0], first[1] + 1, "the list's second file starts after the first one's last page"); + assert_eq!(files.file(&b), Some(b_bytes), "the original is not changed"); + assert_eq!(files.file(&a), Some(a_bytes), "the original is not changed"); +} + +#[test] +fn a_copy_that_exists_already_means_nothing_is_written() { + let (b, a) = paths(); + let taken = Path::new("case").join("a_Bates.pdf"); + let files = Arc::new( + ScriptedFiles::answering([Picked::Paths(vec![b.clone(), a.clone()])]) + .with_file(&b, crate::support::fixtures::pdf_pages(2)) + .with_file(&a, crate::support::fixtures::pdf_pages(1)) + .with_file(&taken, b"keep".to_vec()), + ); + let mut h = harness(files.clone()); + number(&mut h); + assert!(files.written().is_empty(), "no copy is written when one can't be: {:?}", files.written()); + assert_eq!(files.file(&taken).as_deref(), Some(&b"keep"[..]), "the file there is kept"); + let notice = crate::support::shown_notice(&h).unwrap_or_default(); + assert!(notice.contains("a_Bates.pdf"), "the notice names the copy in the way: {notice}"); +} + +#[test] +fn two_copies_that_would_share_a_name_mean_nothing_is_written() { + // On a case-insensitive disk the two copies are one file, so the second would replace the first. + let (lower, upper) = (Path::new("case").join("a.pdf"), Path::new("case").join("A.pdf")); + let files = Arc::new( + ScriptedFiles::answering([Picked::Paths(vec![lower.clone(), upper.clone()])]) + .with_file(&lower, crate::support::fixtures::pdf_pages(1)) + .with_file(&upper, crate::support::fixtures::pdf_pages(1)), + ); + let mut h = harness(files.clone()); + number(&mut h); + assert!(files.written().is_empty(), "neither copy is written: {:?}", files.written()); + let notice = crate::support::shown_notice(&h).unwrap_or_default(); + assert!(notice.contains("_Bates.pdf"), "the notice names the shared copy name: {notice}"); +} diff --git a/crates/ui-egui/tests/it/buttons.rs b/crates/ui-egui/tests/it/buttons.rs index 993128dfcd..8de6f28615 100644 --- a/crates/ui-egui/tests/it/buttons.rs +++ b/crates/ui-egui/tests/it/buttons.rs @@ -154,7 +154,8 @@ fn hide_actions_hide_and_show_fields() { assert!(name_hidden(&h), "the Hide action hid the field"); // A hidden field takes no clicks: clicking where it was doesn't start editing it. click_field(&mut h, "name"); - assert!(h.state().views[0].session.forms.focus.is_none(), "a hidden field can't be focused"); + // (The push button clicked before it still has the focus, as a check box would.) + assert!(h.state().views[0].session.forms.focus.as_ref().is_none_or(|f| f.name != "name"), "a hidden field can't be focused"); click_field(&mut h, "show"); assert!(!name_hidden(&h), "the Hide action with /H false showed it again"); } diff --git a/crates/ui-egui/tests/it/comments.rs b/crates/ui-egui/tests/it/comments.rs index 19605193e4..1ac1276e08 100644 --- a/crates/ui-egui/tests/it/comments.rs +++ b/crates/ui-egui/tests/it/comments.rs @@ -501,6 +501,52 @@ fn a_selection_made_first_is_marked_when_a_tool_is_picked() { assert!(h.state().views[0].selected_text().is_none(), "the selection is consumed"); } +/// #4824: a highlight takes the text selected on its page as the text it marks, through its +/// context menu, as one undo step, and the item is off with nothing selected. +#[test] +fn a_highlights_range_is_changed_to_the_selected_text() { + let mut h = harness(|_| {}); + crate::support::settle(&mut h); + h.state_mut().views[0].select_text(0, 4, 8); + assert!(h.execute("comment.highlight")); + h.run_steps(2); + let width = |h: &Harness<'static, PdfCraftApp>| { + let r = comments(h)[0].rect; + r[2] - r[0] + }; + let before = width(&h); + assert_eq!(comments(&h).len(), 1); + h.set_option("quick", "select").unwrap(); + h.state_mut().views[0].session.comments.select_only((0, 0)); + crate::support::settle(&mut h); + let open_menu = |h: &mut Harness<'static, PdfCraftApp>| { + let p = h.state().views[0].glyph_screen_pos(0, 5).expect("text layer"); + h.hover_at(p); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + }; + // With no text selected the item is there and off. + open_menu(&mut h); + assert!(h.get_by_label("Mark the selected text instead").accesskit_node().is_disabled()); + h.key_press(egui::Key::Escape); + h.run_steps(2); + // Select more text on the page and use it. + h.state_mut().views[0].select_text(0, 4, 14); + h.state_mut().views[0].session.comments.select_only((0, 0)); + h.run_steps(2); + open_menu(&mut h); + h.get_by_label("Mark the selected text instead").click(); + h.run_steps(3); + assert_eq!(comments(&h).len(), 1, "the same highlight, not a new one"); + assert!(width(&h) > before + 1.0, "{} vs {before}", width(&h)); + assert!(h.state().views[0].selected_text().is_none(), "the selection is consumed"); + h.undo(); + h.run_steps(3); + assert!((width(&h) - before).abs() < 0.01, "one undo step puts the range back"); +} + #[test] fn selected_text_shows_actions_and_underlines_without_changing_tools() { let mut h = harness(|_| {}); @@ -669,6 +715,57 @@ fn selected_text_copy_action_closes_the_bar_and_keeps_the_selection() { h.get_by_label("Add comment"); } +#[test] +fn selecting_text_after_a_highlight_reopens_actions_without_losing_the_comment_draft() { + for draft in ["", "A note still being edited"] { + let (mut h, clipboard) = harness_copying(|app| { + app.set_option(&egui::Context::default(), "panel", "comments").unwrap(); + }); + support::wait_until(&mut h, "page text", |app| app.views[0].has_page_text(0)); + h.state_mut().views[0].select_text(0, 4, 8); + h.run_steps(3); + h.get_by_role_and_label(Role::Group, "Selection").get_by_role_and_label(Role::Button, "Highlight").click(); + h.run_steps(3); + assert_eq!(comments(&h).len(), 1, "the selection action added the highlight"); + assert!(h.state().views[0].session.comments.panel.editing.is_some(), "the highlight's note editor stays open"); + let editor = h.get_by_role_and_label(Role::MultilineTextInput, "Edit"); + editor.focus(); + if !draft.is_empty() { + editor.type_text(draft); + } + h.run_steps(2); + assert!(h.ctx.text_edit_focused(), "the note editor owns keyboard input"); + + support::wait_until(&mut h, "page text after highlighting", |app| app.views[0].has_page_text(0)); + let (from, to) = { + let view = &h.state().views[0]; + (view.glyph_screen_pos(0, 10).unwrap(), view.glyph_screen_pos(0, 14).unwrap()) + }; + drag(&mut h, from, to); + let selected = h.state().views[0].selected_text().expect("a new drag selects page text"); + assert!(!h.ctx.text_edit_focused(), "the page drag leaves the note editor"); + assert_eq!(h.state().views[0].session.comments.panel.editing.as_ref().map(|(_, _, text)| text.as_str()), Some(draft)); + let toolbar = h.get_by_role_and_label(Role::Group, "Selection"); + toolbar.get_by_role_and_label(Role::Button, "Replace text"); + h.get_by_role_and_label(Role::MultilineTextInput, "Edit").focus(); + h.run_steps(3); + assert!(h.ctx.text_edit_focused(), "the note editor owns keyboard input again"); + assert_eq!(h.state().views[0].selected_text(), Some(selected.clone()), "focusing the editor preserves the page selection"); + assert!(h.query_by_label("Replace text").is_none(), "focused comment input hides actions for an active page selection"); + + drag(&mut h, from, to); + let toolbar = h.get_by_role_and_label(Role::Group, "Selection"); + toolbar.get_by_role_and_label(Role::Button, "Copy").click(); + h.run_steps(3); + support::wait_until(&mut h, "copied page selection", |_| clipboard.copied().is_some()); + assert_eq!(clipboard.copied(), Some(selected), "Copy uses the new page selection, not the comment draft"); + + drag(&mut h, from, to); + h.get_by_role_and_label(Role::Group, "Selection").get_by_role_and_label(Role::Button, "Replace text"); + assert_eq!(h.state().views[0].session.comments.panel.editing.as_ref().map(|(_, _, text)| text.as_str()), Some(draft)); + } +} + #[test] fn dragging_over_copied_text_again_brings_the_action_bar_back() { let mut h = harness(|_| {}); diff --git a/crates/ui-egui/tests/it/content.rs b/crates/ui-egui/tests/it/content.rs index 85d0b5463b..e235e85c01 100644 --- a/crates/ui-egui/tests/it/content.rs +++ b/crates/ui-egui/tests/it/content.rs @@ -244,6 +244,65 @@ fn clicking_elsewhere_keeps_the_text_and_starts_a_new_box() { assert!(h.state().views[0].session.content.draft.is_none()); } +#[test] +fn choosing_another_tool_keeps_the_text_being_typed() { + // Picking Select from the toolbar left the box open: the document stayed unmodified, with + // nothing to undo, until a click on the page or a save applied the text. + let mut h = harness(); + assert!(h.execute("edit.text")); + h.run_steps(2); + let p = at(&h, 40.0, 100.0); + click(&mut h, p); + h.event(egui::Event::Text("Typed".into())); + h.run_steps(2); + assert!(h.execute("view.select_tool")); + h.run_steps(3); + assert_eq!(texts(&h), ["Typed"]); + assert!(h.state().views[0].session.content.draft.is_none(), "the box closed"); + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + assert!(doc.dirty, "the document is modified"); + assert!(doc.can_undo().is_some(), "the text is one undo step"); +} + +/// Text the document refuses is not lost when another tool is chosen: Add text stays up, so the +/// text stays on screen with the reason, as a click elsewhere on the page leaves it. +#[test] +fn choosing_another_tool_over_refused_text_keeps_add_text_up() { + let mut h = harness(); + assert!(h.execute("edit.text")); + h.run_steps(2); + // The document has one page, so text for a tenth page is refused. + let draft = pdfcraft_ui_egui::TextDraft::new(9, None, [20.0, 200.0, 220.0, 220.0], "Typed".into(), Default::default()); + h.state_mut().views[0].session.content.draft = Some(draft); + h.run_steps(2); + assert!(h.execute("view.select_tool")); + h.run_steps(3); + assert_eq!(h.state().quick_tool, QuickTool::AddText, "the tool stays up over text it can't apply"); + let draft = h.state().views[0].session.content.draft.as_ref().map(|d| d.text.clone()); + assert_eq!(draft.as_deref(), Some("Typed"), "the typed text is kept"); + assert!(texts(&h).is_empty(), "nothing was written to the page"); +} + +/// Entering Read mode over refused text keeps the text but not the tool: Read mode keeps every +/// tool down. +#[test] +fn read_mode_over_refused_text_keeps_the_text_and_puts_add_text_down() { + let mut h = harness(); + assert!(h.execute("edit.text")); + h.run_steps(2); + let draft = pdfcraft_ui_egui::TextDraft::new(9, None, [20.0, 200.0, 220.0, 220.0], "Typed".into(), Default::default()); + h.state_mut().views[0].session.content.draft = Some(draft); + h.run_steps(2); + assert!(h.execute("view.read_mode")); + h.run_steps(3); + assert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Read); + assert_eq!(h.state().quick_tool, QuickTool::Select, "no tool stays up in Read mode"); + let draft = h.state().views[0].session.content.draft.as_ref().map(|d| d.text.clone()); + assert_eq!(draft.as_deref(), Some("Typed"), "the typed text is kept"); + assert!(texts(&h).is_empty(), "nothing was written to the page"); +} + #[test] fn typing_moving_styling_and_deleting_added_content() { let mut h = harness(); @@ -803,7 +862,7 @@ fn format_text_sets_character_spacing_for_added_text() { h.run_steps(3); h.get_by_label("Character spacing").click(); h.run_steps(2); - h.event(egui::Event::Text("2.5".into())); + h.event(egui::Event::Text(crate::support::typed_decimal(2.5, 1))); h.run_steps(1); h.key_press(egui::Key::Enter); h.run_steps(4); diff --git a/crates/ui-egui/tests/it/control.rs b/crates/ui-egui/tests/it/control.rs index 06ca77e77e..75baad31c1 100644 --- a/crates/ui-egui/tests/it/control.rs +++ b/crates/ui-egui/tests/it/control.rs @@ -1308,6 +1308,31 @@ fn ctrl_dragging_a_thumbnail_through_the_control_channel_copies_the_page() { assert_eq!(page_texts(h.state()), ["Page 1", "Page 2", "Page 3", "Page 1"], "the copy landed at the drop gap, after page 3"); } +#[test] +fn a_docked_toolbar_opens_the_editor_from_its_gear() { + let (mut h, c) = harness(); + ok(&mut h, &c, "ui.panel", json!({"panel":"tools","open":false})); + ok(&mut h, &c, "ui.panel", json!({"panel":"toolbar","edge":"left"})); + h.run_steps(3); + let widgets = ok(&mut h, &c, "ui.inspect", json!({})); + let gear = widgets["widgets"].as_array().unwrap().iter().find(|w| w["label"] == "Edit toolbar").unwrap(); + click_center(&mut h, &c, gear); + assert!(h.query_by_role_and_label(egui::accesskit::Role::TextInput, "Search Tools").is_some(), "the editor opens beside the docked rail"); +} + +#[test] +fn the_navigation_rail_and_modes_align_with_neighboring_controls() { + use egui::accesskit::Role; + let (h, _) = harness(); + let midpoint = |role, name| h.get_by_role_and_label(role, name).rect().center(); + let menu = midpoint(Role::MenuItem, "File"); + let mode = midpoint(Role::Tab, "All tools"); + assert!((menu.y - mode.y).abs() <= 2.0, "the modes and menus share a line: {menu:?}, {mode:?}"); + let pages = midpoint(Role::Button, "Page thumbnails"); + let zoom = midpoint(Role::Button, "Zoom in"); + assert!((pages.x - zoom.x).abs() <= 1.0, "the view controls align with the panel icons: {pages:?}, {zoom:?}"); +} + #[test] fn organize_overview_is_reachable_through_the_control_channel() { let (mut h, c) = harness(); @@ -1551,6 +1576,32 @@ fn dock(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient) -> Value { ok(h, c, "ui.panel", json!({"panel": "side"}))["side_panels"].clone() } +/// Dropping the toolbar on the page's top or bottom edge reserves its controls and grip. +#[test] +fn a_horizontal_toolbar_fits_its_controls_above_or_below_the_page() { + use egui::accesskit::Role; + for edge in ["Top", "Bottom"] { + let (mut h, c) = harness(); + ok(&mut h, &c, "ui.set", json!({"key":"mode","value":"edit"})); + h.run_steps(3); + let dock_bottom = h.get_by_role_and_label(Role::Canvas, "Pages").rect().bottom(); + ok(&mut h, &c, "ui.dock.apply", json!({"action":{"Move":{"panel":"toolbar","anchor":"document","placement":{"Edge":edge}}}})); + for width in [1400.0, 820.0, 1400.0] { + h.set_size(egui::vec2(width, 900.0)); + h.run_steps(6); + let rail = h.get_by_role_and_label(Role::Toolbar, "Toolbar").rect(); + let pages = h.get_by_role_and_label(Role::Canvas, "Pages").rect(); + let grip = h.get_by_role_and_label(Role::Button, "Toolbar").rect(); + let gap = if edge == "Top" { pages.top() - rail.bottom() } else { grip.top() - pages.bottom() + dock_bottom - rail.bottom() }; + let sizes = craft::ui::docking::DockSizes::of(&h.ctx); + // The dock also enforces its theme's minimum panel body and strip height. + let floor = (sizes.least_pane + sizes.strip - grip.height() - rail.height()).max(0.0); + assert!((-1.0..=floor + sizes.gap + 1.0).contains(&gap), "{edge}, width {width}: {gap} blank points between the toolbar and the pages"); + assert!(rail.contains(h.get_by_role_and_label(Role::Button, "Edit toolbar").rect().center())); + } + } +} + #[test] fn ui_panel_opens_closes_and_sizes_panes_and_survives_restore() { let (mut h, c) = harness(); diff --git a/crates/ui-egui/tests/it/edit.rs b/crates/ui-egui/tests/it/edit.rs index e7ae037ec3..ca1f6ae0e9 100644 --- a/crates/ui-egui/tests/it/edit.rs +++ b/crates/ui-egui/tests/it/edit.rs @@ -49,9 +49,9 @@ fn add_text_with_custom_unicode_font_succeeds_and_roundtrips() { // Greek text containing phi (U+03C6) reported in issue #4978 ("γραφή"). let greek_text = "γραφή (Greek text with φ)"; - // Standard text without font_resource would be flagged as undrawable by first_undrawable. + // The default path draws Greek with bundled Inter (#9016); an explicit custom font still keeps its resource. let standard_attempt = AddedText { rect: [40.0, 195.0, 240.0, 220.0], text: greek_text.to_string(), ..Default::default() }; - assert!(pdfcraft_engine::first_undrawable(&standard_attempt).is_some(), "standard font must refuse Greek phi"); + assert_eq!(pdfcraft_engine::first_undrawable(&standard_attempt), None, "the default font draws Greek with bundled Inter"); // With custom font_resource, first_undrawable returns None. let custom_added = diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rs index ef47837693..355d6cabc1 100644 --- a/crates/ui-egui/tests/it/editing.rs +++ b/crates/ui-egui/tests/it/editing.rs @@ -470,6 +470,38 @@ fn command_click_toggles_and_rotation_applies_to_selection() { assert_eq!(rot, [90, 0, 90]); } +/// #8983: each Organize delete path removes the intended original pages, not merely the +/// thumbnail that happens to occupy their old positions after the page tree changes. +#[test] +fn organize_delete_targets_selected_range_and_the_clicked_tile() { + let expected = + |deleted: &[usize]| -> Vec { (1..=28).filter(|page| !deleted.contains(page)).map(|page| format!("Page {page}")).collect() }; + + let mut range = organize(28); + type_selection(&mut range, "19-23"); + range.key_press(Key::Enter); + range.run_steps(2); + assert_eq!(range.state().views[0].target_pages(), [18, 19, 20, 21, 22]); + range.get_by_label("Delete pages (Delete)").click(); + range.run_steps(3); + assert_eq!(page_texts(range.state()), expected(&[19, 20, 21, 22, 23]), "sidebar deletes the selected originals in order"); + + // Open the grid on page 20 so its virtualized tile is already in view; a different + // selection must not redirect that tile's own delete action. + let mut tile = harness(28, |app| { + app.views[0].go_to_page(19); + app.set_option(&egui::Context::default(), "organize", "on").unwrap(); + }); + tile.state_mut().views[0].select_pages(&[0, 1]); + tile.run_steps(2); + assert_eq!(tile.state().views[0].target_pages(), [0, 1]); + tile.get_by_label("Page 20").hover(); + tile.run_steps(2); + tile.get_by_label("Delete page 20").click(); + tile.run_steps(3); + assert_eq!(page_texts(tile.state()), expected(&[20]), "tile deletes its own original, not the selection"); +} + #[test] fn delete_is_refused_when_it_would_remove_every_page() { let mut h = organize(2); @@ -2826,7 +2858,8 @@ fn the_security_notice_wraps_beside_its_buttons_and_lines_up_with_them() { } } // Wide: one line. Narrower: wrapped. Narrowest: actions stack below the message. - for (width, wraps) in [(1700.0, false), (1550.0, true), (1250.0, false), (900.0, false)] { + let (mut single, mut wrapped, mut stacked) = (false, false, false); + for width in [1800.0, 1650.0, 1550.0, 1500.0, 1450.0, 1400.0, 1350.0, 1300.0, 1250.0, 900.0] { let mut h = Harness::builder().with_size(egui::vec2(width, 800.0)).build_eframe(|cc| { crate::support::install_runtime(&cc.egui_ctx); { @@ -2842,8 +2875,10 @@ fn the_security_notice_wraps_beside_its_buttons_and_lines_up_with_them() { h.output().shapes.iter().find_map(|shape| message_rect(&shape.shape)).expect("the security message is painted"); let button = h.get_by_label("Security settings").rect(); let dismiss = h.get_by_label("Dismiss").rect(); - if width <= 1250.0 { - assert!(button.top() >= msg.bottom(), "{width}: stacked actions stay below the message: {msg:?} vs {button:?}"); + if button.top() >= msg.bottom() { + stacked = true; + // The dismiss control stays at the end of the message line; only the action moves below it. + assert!(!msg.intersects(dismiss), "{width}: the message leaves room for dismiss: {msg:?} vs {dismiss:?}"); assert!(!button.intersects(dismiss), "{width}: the actions stay apart: {button:?} vs {dismiss:?}"); continue; } @@ -2853,8 +2888,13 @@ fn the_security_notice_wraps_beside_its_buttons_and_lines_up_with_them() { assert!(msg.top() >= button.top(), "{width}: the message stays inside the bar: {msg:?} vs {button:?}"); let first_line = msg.top() + first_line_offset; assert!((first_line - button.center().y).abs() <= 1.5, "{width}: first line centred on the buttons: {msg:?} vs {button:?}"); - assert_eq!(msg.height() > button.height(), wraps, "{width}: {msg:?}"); + if msg.height() > button.height() { + wrapped = true; + } else { + single = true; + } } + assert!(single && wrapped && stacked, "the notice handles single-line, wrapped and stacked layouts"); } /// #995, #1077: a file with only a permissions password opens without asking, restricted. Its @@ -3307,6 +3347,95 @@ fn dragging_thumbnails_reorders_pages() { assert_eq!(sel, vec![2], "the moved page stays selected"); } +/// Retain the actual textures painted by the thumbnail grid, including those replaced after an edit. +#[derive(Clone, Default)] +struct OrganizeUploads(std::sync::Arc>>>); + +impl egui_kittest::TestRenderer for OrganizeUploads { + fn handle_delta(&mut self, delta: &mut egui::TexturesDelta) { + let mut images = self.0.lock().unwrap(); + for (id, changes) in delta.set.drain() { + for change in changes.into_iter().filter(|c| c.pos.is_none()) { + let egui::ImageData::Color(image) = change.image; + images.insert(id, image); + } + } + delta.free.clear(); + } + + fn render(&mut self, _: &egui::Context, _: &egui::FullOutput) -> Result { + Err("this renderer records texture uploads".into()) + } +} + +/// The largest uploaded picture actually drawn inside a named Organize tile. +fn organize_tile_image(h: &Harness<'static, PdfCraftApp>, uploads: &OrganizeUploads, label: &str) -> Option> { + fn collect<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) { + match shape { + egui::Shape::Vec(children) => children.iter().for_each(|s| collect(s, out)), + _ => out.push(shape), + } + } + let tile = h.query_by_label(label)?.rect(); + let images = uploads.0.lock().unwrap(); + let mut shapes = Vec::new(); + h.output().shapes.iter().for_each(|s| collect(&s.shape, &mut shapes)); + shapes + .into_iter() + .filter_map(|s| { + let egui::Shape::Mesh(mesh) = s else { return None }; + let bounds = mesh.calc_bounds(); + let image = images.get(&mesh.texture_id)?; + (bounds.width() > 30.0 && bounds.height() > 30.0 && tile.contains(bounds.center()) && image.size[0] > 30 && image.size[1] > 30) + .then(|| (bounds.area(), image.clone())) + }) + .max_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, image)| image) +} + +#[test] +fn moved_organize_page_updates_the_painted_thumbnail_in_the_same_session() { + use std::sync::Arc; + let jobs = Arc::new(craft::host::ManualJobs::new()); + let uploads = OrganizeUploads::default(); + let on = jobs.clone(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).renderer(uploads.clone()).build_eframe(move |cc| { + support::install_runtime(&cc.egui_ctx); + let mut app = support::test_app(support::host_with(on.clone(), Arc::new(craft::host::ScriptedFiles::new()))); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + app.open_bytes(&egui::Context::default(), "doc.pdf", None, fixture(4)).unwrap(); + app.set_option(&egui::Context::default(), "organize", "on").unwrap(); + app + }); + let mut before_images = None; + for _ in 0..200 { + jobs.run_all(); + h.run_steps(1); + let pictures: Option> = ["Page 1", "Page 2", "Page 3"].iter().map(|label| organize_tile_image(&h, &uploads, label)).collect(); + if let Some(p) = pictures.filter(|p| p[0].pixels != p[1].pixels && p[1].pixels != p[2].pixels && p[0].pixels != p[2].pixels) { + before_images = Some(p); + break; + } + } + let before_images = before_images.expect("three visibly distinct page thumbnails are painted"); + let before = page_texts(h.state()); + let from = h.get_by_label("Page 1").rect().center(); + let to = h.get_by_label("Page 3").rect().right_center() - egui::vec2(10.0, 0.0); + page_drag(&mut h, from, to, Modifiers::NONE); + assert_eq!(page_texts(h.state()), vec![before[1].clone(), before[2].clone(), before[0].clone(), before[3].clone()]); + for _ in 0..200 { + jobs.run_all(); + h.run_steps(1); + let after: Option> = ["Page 1", "Page 2", "Page 3"].iter().map(|label| organize_tile_image(&h, &uploads, label)).collect(); + if after.is_some_and(|p| { + p[0].pixels == before_images[1].pixels && p[1].pixels == before_images[2].pixels && p[2].pixels == before_images[0].pixels + }) { + return; + } + } + panic!("the painted thumbnails did not follow the committed reorder"); +} + /// A page drag with the copy modifier held — Ctrl (Option on macOS) — instead of none. /// Modifiers are input state: `ModifiersChanged` once, as the column-select drag does. fn copy_drag(h: &mut Harness<'static, PdfCraftApp>, from: egui::Pos2, to: egui::Pos2) { @@ -4333,6 +4462,21 @@ fn the_edit_panel_back_arrow_applies_an_open_paragraph_and_puts_edit_text_down() assert_edit_text_put_down_and_the_paragraph_applied(h.state()); } +/// Choosing Select from the toolbar (or its key or command) applies the paragraph open in the +/// editor as leaving Edit does; it stayed open, with the document unmodified. +#[test] +fn choosing_select_applies_an_open_paragraph() { + let mut h = harness(1, |_| {}); + assert!(h.execute("edit.edit_text")); + h.run_steps(3); + open_the_first_line(&mut h); + assert!(h.execute("view.select_tool")); + h.run_steps(3); + assert_edit_text_put_down_and_the_paragraph_applied(h.state()); + let s = h.state(); + assert!(s.session.get(s.views[0].id).unwrap().dirty, "the document is modified"); +} + /// Organize pages, opened under the Edit tab, leaves Edit the same way through its own back arrow. #[test] fn the_organize_back_arrow_applies_an_open_paragraph_and_puts_edit_text_down() { @@ -4943,14 +5087,17 @@ fn page_context_menu_items_disabled_on_protected_pdf() { assert!(!doc.allows_assembly()); assert!(!doc.allows_annotation()); - let r = h.state().views[0].page_screen_rect(0).expect("on screen"); - let c = r.center(); - // Right click on page in Select mode - h.hover_at(c); + let view = &h.state().views[0]; + let visible_page = view.page_screen_rect(0).expect("on screen").intersect(view.viewport_rect()); + assert!(visible_page.is_positive()); + let at = visible_page.center(); + h.hover_at(at); h.run_steps(1); - h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); - h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); - h.run_steps(2); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + h.get_by_label("Take a snapshot"); let is_disabled = |h: &mut Harness<'static, PdfCraftApp>, label: &str| h.query_by(|n| n.label().as_deref() == Some(label) && n.is_disabled()).is_some(); @@ -5277,7 +5424,7 @@ fn the_format_panel_takes_any_scale_and_character_spacing() { assert_eq!(extras(&h), Some((80.0, 0.0))); type_in(&mut h, "Horizontal scale", "250"); assert_eq!(extras(&h), Some((250.0, 0.0))); - type_in(&mut h, "Character spacing", "0.25"); + type_in(&mut h, "Character spacing", &crate::support::typed_decimal(0.25, 2)); assert_eq!(extras(&h), Some((250.0, 0.25))); type_in(&mut h, "Character spacing", "-2"); assert_eq!(extras(&h), Some((250.0, -2.0))); @@ -5314,7 +5461,7 @@ fn typed_small_coloured_text_size_survives_save_and_reopen() { h.get_by_role_and_label(Role::SpinButton, "Font size").focus(); h.run_steps(2); h.key_press_modifiers(Modifiers::COMMAND, Key::A); - h.event(egui::Event::Text("6.5".into())); + h.event(egui::Event::Text(crate::support::typed_decimal(6.5, 1))); h.run_steps(1); h.key_press(Key::Enter); h.run_steps(4); diff --git a/crates/ui-egui/tests/it/fill_sign.rs b/crates/ui-egui/tests/it/fill_sign.rs index 4ea91d8e30..09904344c5 100644 --- a/crates/ui-egui/tests/it/fill_sign.rs +++ b/crates/ui-egui/tests/it/fill_sign.rs @@ -2795,10 +2795,10 @@ fn typing_a_fill_text_size_that_rounds_to_the_stored_one_adds_no_undo_step() { h.key_press(egui::Key::Enter); h.run_steps(4); }; - type_size(&mut h, "36.1234"); + type_size(&mut h, &crate::support::typed_decimal(36.1234, 4)); let resized = placed_height(&h, "Round me"); assert!(resized > height, "the first size applies: {height} -> {resized}"); - type_size(&mut h, "36.1231"); + type_size(&mut h, &crate::support::typed_decimal(36.1231, 4)); assert_eq!(h.state().fill_text_size, 36.1231); h.execute("edit.undo"); h.run_steps(3); @@ -2841,18 +2841,8 @@ fn commit_typed_text(h: &mut Harness<'static, PdfCraftApp>) { h.run_steps(3); } -fn fill_input(h: &mut Harness<'static, PdfCraftApp>, events: impl IntoIterator) { - h.input_mut().events.extend(events); - let ctx = h.ctx.clone(); - let mut raw = std::mem::take(h.input_mut()); - eframe::App::raw_input_hook(h.state_mut(), &ctx, &mut raw); - *h.input_mut() = raw; - h.step(); - h.run_steps(2); -} - fn fill_key(h: &mut Harness<'static, PdfCraftApp>, key: egui::Key) { - fill_input( + crate::support::input::native_input( h, [true, false].map(|pressed| egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: egui::Modifiers::NONE }), ); @@ -2872,10 +2862,10 @@ fn fill_sign_enter_adds_lines_outside_click_commits_and_escape_cancels() { Some("\n"), "Enter inserts a newline and keeps the editor open" ); - fill_input(&mut h, [egui::Event::Text("Ada".into())]); + crate::support::input::native_input(&mut h, [egui::Event::Text("Ada".into())]); fill_key(&mut h, egui::Key::Enter); fill_key(&mut h, egui::Key::Enter); - fill_input(&mut h, [egui::Event::Text("Lovelace".into())]); + crate::support::input::native_input(&mut h, [egui::Event::Text("Lovelace".into())]); fill_key(&mut h, egui::Key::Enter); let text = "\nAda\n\nLovelace\n"; assert_eq!(h.state().views[0].session.fill_text.as_ref().unwrap().text, text); @@ -2920,7 +2910,7 @@ fn fill_sign_enter_adds_lines_outside_click_commits_and_escape_cancels() { }; let before = unchanged(&h); click(&mut h, 50.0, 180.0); - fill_input(&mut h, [egui::Event::Text("Cancel me".into())]); + crate::support::input::native_input(&mut h, [egui::Event::Text("Cancel me".into())]); fill_key(&mut h, egui::Key::Enter); fill_key(&mut h, egui::Key::Escape); assert!(h.state().views[0].session.fill_text.is_none()); diff --git a/crates/ui-egui/tests/it/forms.rs b/crates/ui-egui/tests/it/forms.rs index a8b21726d8..b9f05c5e49 100644 --- a/crates/ui-egui/tests/it/forms.rs +++ b/crates/ui-egui/tests/it/forms.rs @@ -396,6 +396,21 @@ fn an_open_form_editor_preserves_intentional_focus_in_another_control() { h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Zoom").focus(); h.run_steps(4); assert!(h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Zoom").is_focused()); + let (area, pages) = { + let app = h.state(); + (app.views[0].viewport_rect(), app.views[0].visible_page_rects()) + }; + let blank = [area.left_center() + egui::vec2(12.0, 0.0), area.right_center() - egui::vec2(12.0, 0.0)] + .into_iter() + .find(|p| pages.iter().all(|(_, rect)| !rect.contains(*p))) + .expect("a blank point beside the page"); + click_at(&mut h, blank); + let saved = value(&h, "first"); + let draft = h.state().views[0].session.forms.focus.as_ref().map(|f| (f.name.clone(), f.text.clone())); + assert!( + saved == ["alpha"] || draft == Some(("first".into(), "alpha".into())), + "clicking the background must preserve the dirty field: saved {saved:?}, draft {draft:?}" + ); } #[test] @@ -2070,6 +2085,33 @@ fn the_field_editor_sizes_auto_size_text_as_the_page_does() { const GUIDE_INNER: &str = "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF"; +/// A push button takes the focus on a click and is a Tab stop, as another viewer treats it, so its +/// On Focus and On Blur run; Space presses the focused button. +#[test] +fn a_push_button_takes_the_focus_on_a_click_and_as_a_tab_stop() { + let bytes = pdf_from_objects(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R] >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>", + "<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (a) /Rect [20 330 120 356] /P 3 0 R /F 4 >>", + "<< /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (go) /Rect [20 280 120 306] /P 3 0 R /F 4 /A << /S /JavaScript /JS (this.getField\\(\"a\"\\).value = \"pressed\";) >> >>", + ]); + let mut h = harness_with_bytes("button-focus.pdf", bytes); + click_field(&mut h, "a", 0); + assert_eq!(focused(&h), Some(("a".into(), 0))); + h.key_press(egui::Key::Tab); + h.run_steps(4); + assert_eq!(focused(&h), Some(("go".into(), 0)), "Tab reaches the push button"); + assert_eq!(value(&h, "a"), Vec::::new(), "and does not press it"); + h.key_press(egui::Key::Space); + h.run_steps(4); + assert_eq!(value(&h, "a"), ["pressed"], "Space presses the focused button"); + click_field(&mut h, "a", 0); + assert_eq!(focused(&h), Some(("a".into(), 0))); + click_field(&mut h, "go", 0); + assert_eq!(focused(&h), Some(("go".into(), 0)), "a click focuses the push button"); +} + /// A page with a push button `go`, and three attached files: a one-page PDF filed under the key /// `Guide.pdf` (its own file name `inner.pdf`), `notes.txt`, and `fake.pdf`, which holds text. fn guide_fixture() -> Vec { diff --git a/crates/ui-egui/tests/it/javascript.rs b/crates/ui-egui/tests/it/javascript.rs index 5227f6136d..ae2bb81412 100644 --- a/crates/ui-egui/tests/it/javascript.rs +++ b/crates/ui-egui/tests/it/javascript.rs @@ -386,6 +386,9 @@ fn native_script_prompt_uses_the_german_catalog_when_available() { assert_eq!(tr(german, source), heading); let mut h = harness(); h.set_option("language", "de").unwrap(); + // The translated tools change the fitted page width. A script started before that layout + // settles would correctly be discarded when its recorded page zoom becomes stale. + h.run_steps(5); let id = h.state().active_ids().unwrap().1; h.run_button_script(id, "hello", "app.response({cQuestion:'Test',bPassword:true});"); wait_for_prompt(&mut h, heading, |h| h.query_by_role_and_label(egui::accesskit::Role::Dialog, heading).is_some()); diff --git a/crates/ui-egui/tests/it/links.rs b/crates/ui-egui/tests/it/links.rs index 953e9afbb4..57d11e7cd1 100644 --- a/crates/ui-egui/tests/it/links.rs +++ b/crates/ui-egui/tests/it/links.rs @@ -71,3 +71,39 @@ fn about_dialog_has_contributors_and_models_tabs() { h.run_steps(4); assert!(h.query_all_by_label("Anthropic").count() >= 1); } + +#[test] +fn embedded_mode_hides_community_links_and_discord_button() { + let h = harness(|app| { + app.embedded = true; + }); + assert!(h.query_by_label("Join the ArtCraft community").is_none()); + assert!(h.query_by_label("Join our Discord").is_none()); + assert!(h.query_by_label("PdfCraft web page").is_none()); + assert!(h.query_by_label("PdfCraft on GitHub").is_none()); + assert!(h.query_by_label("ArtCraft website").is_none()); + assert!(h.query_by_label("Discord").is_none()); +} + +#[test] +fn set_option_embedded_configures_flag() { + let mut app = crate::control::new_app(); + let ctx = egui::Context::default(); + assert!(!app.embedded); + app.set_option(&ctx, "embedded", "true").unwrap(); + assert!(app.embedded); + app.set_option(&ctx, "embedded", "off").unwrap(); + assert!(!app.embedded); + app.set_option(&ctx, "embedded", "1").unwrap(); + assert!(app.embedded); + app.set_option(&ctx, "embedded", "0").unwrap(); + assert!(!app.embedded); + app.set_option(&ctx, "embedded", "on").unwrap(); + assert!(app.embedded); + app.set_option(&ctx, "embedded", "false").unwrap(); + assert!(!app.embedded); + for value in ["yes", ""] { + assert!(app.set_option(&ctx, "embedded", value).is_err()); + assert!(!app.embedded, "a refused value leaves the flag unchanged"); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0026a12fc8..8c9088afb6 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -22,6 +22,7 @@ mod actions; mod animate; mod attach_picker_target; mod attachment_row; +mod bates_files; mod bookmark_position; mod bookmarks; mod bulk_fields; @@ -87,7 +88,9 @@ mod redact; mod reload; mod scan_clean; mod script_noop; +mod scrollbars; mod search_position; +mod show_boxes; mod side_panels; mod signing; mod snapshot_tabs; diff --git a/crates/ui-egui/tests/it/marks.rs b/crates/ui-egui/tests/it/marks.rs index cdf109f6ec..218e5abea1 100644 --- a/crates/ui-egui/tests/it/marks.rs +++ b/crates/ui-egui/tests/it/marks.rs @@ -715,6 +715,24 @@ fn the_preview_shows_the_page_the_range_selects_under_the_marks() { assert_eq!(tint, egui::Color32::from_rgb(red, green, blue), "the default background colour, opaque"); } +/// #9009: the page sample is large enough to inspect placement and keeps its page geometry. +#[test] +fn header_footer_preview_is_larger_and_keeps_its_overlay_and_pager() { + let mut h = harness(); + assert!(h.execute("edit.header_footer")); + h.steps(3); + type_into(&mut h, BOX_LABELS[1], "TOP"); + let Picture { at, rect: page, .. } = wait_for_preview(&mut h, "header page", |_| true); + assert!(page.height() >= 170.0, "the page is readable at the normal window size: {page:?}"); + assert!((page.width() / page.height() - 0.75).abs() < 0.02, "the whole page keeps its aspect: {page:?}"); + let (text_at, top) = painted(&h, "TOP", page); + assert!(at < text_at, "the header is drawn above the page picture"); + near(top.center().x, page.center().x, "centre header, across"); + near(top.center().y, page.top() + 36.0 * page.width() / 300.0, "centre header, down"); + show_page(&mut h, 1); + assert_eq!(pager(&h).0, 2, "the enlarged preview still steps pages"); +} + #[test] fn the_preview_steps_through_the_pages_and_starts_at_the_current_one() { let mut h = harness(); @@ -821,3 +839,231 @@ fn update_previews_the_page_without_the_marks_it_replaces() { let page = wait_for_preview(&mut h, "the page without the old header", |i| count(i, blue) == 0).image; assert!(at(&page, 0.5, 0.75) == yellow && count(&page, red) > 200, "the background and watermark stay"); } + +/// A one-page PDF of `w` × `h` points painted with `content`: a file to take a mark from. +fn picture_pdf(w: u32, h: u32, content: &str) -> Vec { + 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 {w} {h}] /Contents 4 0 R >> endobj +4 0 obj << /Length {} >> +stream +{content} +endstream +endobj +trailer << /Root 1 0 R >> +%%EOF", + content.len() + ) + .into_bytes() +} + +/// Every mesh painted last frame, with the clip it was painted under. +fn clipped_meshes(h: &Rig) -> Vec<(egui::Rect, Arc)> { + fn append(shape: &egui::Shape, clip: egui::Rect, out: &mut Vec<(egui::Rect, Arc)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| append(shape, clip, out)), + egui::Shape::Mesh(m) => out.push((clip, m.clone())), + _ => {} + } + } + let mut out = Vec::new(); + h.output().shapes.iter().for_each(|s| append(&s.shape, s.clip_rect, &mut out)); + out +} + +fn is_red(c: egui::Color32) -> bool { + c.r() > 200 && c.g() < 60 && c.b() < 60 +} + +/// The marks painted last frame from a red file: meshes whose uploaded picture is mostly red, +/// with their clip. +fn red_marks(h: &Rig) -> Vec<(egui::Rect, Arc)> { + let uploads = h.uploads.0.lock().unwrap(); + clipped_meshes(h).into_iter().filter(|(_, m)| uploads.get(&m.texture_id).is_some_and(|i| count(i, is_red) * 2 > i.pixels.len())).collect() +} + +/// Opens `command`'s dialog on `pdf` and picks `file` as its Source ▸ File. +fn open_with_file(command: &str, file: Vec, pdf: Vec) -> Rig { + let files = Arc::new(craft::host::ScriptedFiles::answering([craft::host::Picked::Contents(vec![("stamp.pdf".into(), file)])])); + let mut h = harness_with_files(pdf, files); + assert!(h.execute(command)); + // The dialog grows once it has looked at the page's backdrop; click after it settles. + h.steps(6); + h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "File").click(); + h.steps(2); + h.get_by_label("Browse…").click(); + h.steps(3); + h +} + +/// Steps until the preview shows its page and `ready` accepts what was painted on it. +fn wait_for(h: &mut Rig, what: &str, ready: impl Fn(&Rig, egui::Rect) -> Option) -> (egui::Rect, T) { + for _ in 0..200 { + h.steps(1); + if let Some(page) = preview_picture(h).map(|p| p.rect) + && let Some(found) = ready(h, page) + { + return (page, found); + } + } + panic!("the preview never showed {what}"); +} + +/// The one mark from a red file painted last frame, with its clip. +fn one_mark(h: &Rig, _: egui::Rect) -> Option<(egui::Rect, Arc)> { + match &red_marks(h)[..] { + [mark] => Some(mark.clone()), + _ => None, + } +} + +#[test] +fn a_mark_from_a_file_previews_its_picture_where_ok_puts_it() { + // A watermark from a 200 × 100 page painted red, at half the page, moved 30 pt right and + // 20 pt up, half opaque (#2817 item 14). + let mut h = open_with_file("edit.watermark", picture_pdf(200, 100, "1 0 0 rg 0 0 200 100 re f"), content_fixture()); + let settings = [("file.scale", 50.0), ("wm.rotation", 0.0), ("wm.offset.0", 30.0), ("wm.offset.1", 20.0), ("wm.opacity", 50.0)]; + for (field, value) in settings { + set_field(&mut h, MarkKind::Watermark, field, json!(value)); + } + let (page, (_, mark)) = wait_for(&mut h, "the file's picture", one_mark); + // Fitted to the 300 × 400 page: 1.5 × the picture, half of that is 150 × 75 pt. + let s = page.width() / 300.0; + let r = mark.calc_bounds(); + near(r.width(), 150.0 * s, "width"); + near(r.height(), 75.0 * s, "height"); + near(r.center().x, page.center().x + 30.0 * s, "moved right"); + near(r.center().y, page.center().y - 20.0 * s, "moved up"); + assert!(mark.vertices.iter().all(|v| v.color.a() > 50 && v.color.a() < 200), "half opaque"); + // Turned a quarter counter-clockwise: the picture's top-left corner comes to the bottom left. + set_field(&mut h, MarkKind::Watermark, "wm.rotation", json!(90.0)); + let upright = |h: &Rig, p: egui::Rect| one_mark(h, p).filter(|(_, m)| m.calc_bounds().height() > m.calc_bounds().width()); + let (page, (_, mark)) = wait_for(&mut h, "the turned picture", upright); + let r = mark.calc_bounds(); + near(r.width(), 75.0 * s, "turned, width"); + near(r.height(), 150.0 * s, "turned, height"); + near(r.center().x, page.center().x + 30.0 * s, "turned about its centre, across"); + near(r.center().y, page.center().y - 20.0 * s, "turned about its centre, down"); + let corner = mark.vertices.iter().find(|v| v.uv == egui::pos2(0.0, 0.0)).map(|v| v.pos).unwrap(); + near(corner.x, r.left(), "top-left corner, across"); + near(corner.y, r.bottom(), "top-left corner, down"); +} + +/// OK crops a mark at the page edge, so the preview keeps it to the page too, not to the pane +/// around it. +#[test] +fn a_mark_from_a_file_is_kept_to_the_page() { + let mut h = open_with_file("edit.watermark", picture_pdf(100, 100, "1 0 0 rg 0 0 100 100 re f"), content_fixture()); + // Page 2 turns landscape, so the pane around it is wider or taller than the page itself. + show_page(&mut h, 1); + // Pushed past the page's right and top edges, whichever way they face on screen. + for (field, value) in [("file.scale", 30.0), ("wm.rotation", 0.0), ("wm.offset.0", 140.0), ("wm.offset.1", 190.0)] { + set_field(&mut h, MarkKind::Watermark, field, json!(value)); + } + let (page, (clip, mark)) = wait_for(&mut h, "the file's picture", one_mark); + let mark = mark.calc_bounds(); + assert!(!page.expand(1.0).contains_rect(mark), "the mark crosses the page's edge: {mark:?} on {page:?}"); + assert!(page.expand(0.5).contains_rect(clip), "the mark is clipped at the page edge: clip {clip:?}, page {page:?}"); +} + +/// What the preview shows at `at` once last frame's meshes are painted in order: each mesh's +/// texture (white for the default one) times its vertex colours, premultiplied, inside its clip. +fn shown_at(h: &Rig, at: egui::Pos2) -> egui::Color32 { + let uploads = h.uploads.0.lock().unwrap(); + let mut out = [0.0f32; 4]; + for (clip, m) in clipped_meshes(h) { + if !clip.contains(at) { + continue; + } + for t in m.indices.as_chunks::<3>().0 { + let [a, b, c] = t.map(|i| m.vertices[i as usize]); + let cross = |u: egui::Vec2, v: egui::Vec2| u.x * v.y - u.y * v.x; + let area = cross(b.pos - a.pos, c.pos - a.pos); + if area.abs() < 1e-6 { + continue; + } + let wb = cross(at - a.pos, c.pos - a.pos) / area; + let wc = cross(b.pos - a.pos, at - a.pos) / area; + let wa = 1.0 - wb - wc; + if wa < -1e-4 || wb < -1e-4 || wc < -1e-4 { + continue; + } + let uv = a.uv.to_vec2() * wa + b.uv.to_vec2() * wb + c.uv.to_vec2() * wc; + let texel = match uploads.get(&m.texture_id) { + Some(i) if m.texture_id != egui::TextureId::default() => { + let pick = |f: f32, n: usize| ((f * n as f32) as usize).min(n - 1); + i.pixels[pick(uv.y, i.size[1]) * i.size[0] + pick(uv.x, i.size[0])] + } + _ => egui::Color32::WHITE, + }; + let tint = |k: usize| { + let ch = |v: &egui::epaint::Vertex| f32::from(v.color.to_array()[k]) / 255.0; + ch(&a) * wa + ch(&b) * wb + ch(&c) * wc + }; + let src: [f32; 4] = std::array::from_fn(|k| f32::from(texel.to_array()[k]) / 255.0 * tint(k)); + out = std::array::from_fn(|k| src[k] + out[k] * (1.0 - src[3])); + break; + } + } + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + egui::Color32::from_rgba_premultiplied(byte(out[0]), byte(out[1]), byte(out[2]), byte(out[3])) +} + +/// The point `(x, y)` points from the bottom left of the 300-point-wide page drawn as `page`. +fn on_page(page: egui::Rect, x: f32, y: f32) -> egui::Pos2 { + let s = page.width() / 300.0; + egui::pos2(page.left() + x * s, page.bottom() - y * s) +} + +/// Whether the preview of the page shown, settled, has the red picture behind it, at its middle. +fn shows_behind(h: &mut Rig) -> bool { + // Frames for the backdrop check, the picture and the page's sheet, then what the last one painted. + h.steps(8); + let (page, ()) = wait_for(h, "the page", |_, _| Some(())); + is_red(shown_at(h, page.center())) +} + +/// A background from a file shows where OK lets it show, as a colour does: through the page's +/// white, but not on a page whose own white backdrop stays (Replace unticked) or on a scan. +#[test] +fn a_background_from_a_file_previews_only_where_ok_lets_it_show() { + let mut h = open_with_file("edit.background", picture_pdf(100, 100, "1 0 0 rg 0 0 100 100 re f"), backdrop_fixture()); + set_field(&mut h, MarkKind::Background, "file.scale", json!(50.0)); + set_field(&mut h, MarkKind::Background, "bg.opacity", json!(100.0)); + // 150 × 150 pt in the middle of the 300 × 400 page. + let (page, ()) = wait_for(&mut h, "the picture behind page 1", |h, page| is_red(shown_at(h, page.center())).then_some(())); + assert!(is_red(shown_at(&h, on_page(page, 150.0, 140.0))), "inside, near the bottom edge"); + assert_eq!(shown_at(&h, on_page(page, 150.0, 110.0)), egui::Color32::WHITE, "below it"); + assert_eq!(shown_at(&h, on_page(page, 45.0, 45.0)), egui::Color32::BLACK, "the page's black square, outside it"); + // Unticked, page 1 keeps its white backdrop, which hides the background. + h.get_by_label(REPLACE).click(); + h.steps(2); + assert!(!shows_behind(&mut h), "page 1 keeps its backdrop"); + h.get_by_label(REPLACE).click(); + h.steps(2); + assert!(shows_behind(&mut h), "ticked again, it shows"); + show_page(&mut h, 1); + assert!(!shows_behind(&mut h), "a picture covers page 2"); + show_page(&mut h, 2); + assert!(shows_behind(&mut h), "page 3 is bare paper"); +} + +/// A picture behind the page shows only where the page paints nothing, as after OK: an opaque +/// blue box on the page stays blue over it, not blue times the picture (black over red), and +/// bare paper shows the picture. +#[test] +fn a_picture_behind_the_page_is_covered_where_the_page_paints() { + let page = picture_pdf(300, 400, "0 0 1 rg 100 150 100 100 re f"); + let mut h = open_with_file("edit.watermark", picture_pdf(100, 100, "1 0 0 rg 0 0 100 100 re f"), page); + // Fitted to the page's width: 300 × 300 pt from 50 pt up to 350. + let settings = [("file.scale", json!(100.0)), ("wm.rotation", json!(0.0)), ("wm.opacity", json!(100.0)), ("wm.behind", json!("behind"))]; + for (field, value) in settings { + set_field(&mut h, MarkKind::Watermark, field, value); + } + let (page, ()) = wait_for(&mut h, "the picture behind the page", |h, page| is_red(shown_at(h, on_page(page, 40.0, 320.0))).then_some(())); + let blue = shown_at(&h, on_page(page, 150.0, 200.0)); + assert!(blue.b() > 200 && blue.r() < 60 && blue.g() < 60, "the blue box stays blue over the picture: {blue:?}"); + assert_eq!(shown_at(&h, on_page(page, 150.0, 20.0)), egui::Color32::WHITE, "below the picture, white paper"); +} diff --git a/crates/ui-egui/tests/it/min_window.rs b/crates/ui-egui/tests/it/min_window.rs index 29c4c7ab6a..25ba8776c7 100644 --- a/crates/ui-egui/tests/it/min_window.rs +++ b/crates/ui-egui/tests/it/min_window.rs @@ -19,6 +19,16 @@ fn harness(size: egui::Vec2) -> Harness<'static, PdfCraftApp> { h } +#[test] +fn the_all_tools_heading_aligns_with_its_list_on_home() { + let h = harness(egui::vec2(1400.0, 900.0)); + let panel = h.get_by_role_and_label(Role::TabPanel, "All tools").rect(); + let title = h.get_by_role_and_label(Role::Label, "All tools").rect(); + let list = h.get_by_role_and_label(Role::List, "All tools").rect(); + assert!(title.left() > panel.left(), "the heading touches the panel edge: {title:?}, {panel:?}"); + assert!((title.left() - list.left()).abs() <= 1.0, "the heading and list have different insets: {title:?}, {list:?}"); +} + #[test] fn at_the_minimum_width_the_menus_the_modes_and_search_stay_reachable() { let h = harness(egui::vec2(MIN_WINDOW_SIZE[0], MIN_WINDOW_SIZE[1])); diff --git a/crates/ui-egui/tests/it/pageboxes.rs b/crates/ui-egui/tests/it/pageboxes.rs index e5439a15f2..9a6a44f13f 100644 --- a/crates/ui-egui/tests/it/pageboxes.rs +++ b/crates/ui-egui/tests/it/pageboxes.rs @@ -4,6 +4,7 @@ use crate::support::AppHarness as _; use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; +use pdfcraft_engine::{Edit, PageBox}; use pdfcraft_ui_egui::{PdfCraftApp, QuickTool}; const FIXTURE: &[u8] = b"%PDF-1.7 @@ -36,6 +37,35 @@ fn size(h: &Harness<'static, PdfCraftApp>, page: usize) -> (f32, f32) { (p.width, p.height) } +/// Whether Set Page Boxes is open. +fn boxes_open(h: &Harness<'static, PdfCraftApp>) -> bool { + h.query_by_role_and_label(Role::Dialog, "Set Page Boxes").is_some() +} + +/// Drags from `a` to `b` with the primary button, in steps. +fn drag(h: &mut Harness<'static, PdfCraftApp>, a: egui::Pos2, b: egui::Pos2) { + h.hover_at(a); + h.run_steps(1); + h.drag_at(a); + h.run_steps(1); + for k in 1..=4 { + h.hover_at(a + (b - a) * (k as f32 / 4.0)); + h.run_steps(1); + } + h.drop_at(b); + h.run_steps(4); +} + +/// Types `value` into the margin row labelled `side`. +fn type_margin(h: &mut Harness<'static, PdfCraftApp>, side: &str, value: &str) { + h.get_by_label(side).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.get_by_label(side).type_text(value); + h.key_press(egui::Key::Tab); + h.run_steps(2); +} + #[test] fn the_crop_tool_crops_to_the_dragged_rectangle_then_returns_to_select() { let mut h = harness(); @@ -59,20 +89,12 @@ fn quick_toolbar_crop_is_hidden_on_home_and_in_read_mode() { assert!(h.query_by_label("Crop pages").is_none()); } +/// Draws a rectangle over the middle half of page 0 and confirms Set Page Boxes with OK. fn crop_middle_half(h: &mut Harness<'static, PdfCraftApp>) { - let r = h.state().views[0].page_screen_rect(0).unwrap(); - // The middle half of the page in both directions. - let (a, b) = (r.min + r.size() * 0.25, r.min + r.size() * 0.75); - h.hover_at(a); - h.run_steps(1); - h.drag_at(a); - h.run_steps(1); - for k in 1..=4 { - h.hover_at(a + (b - a) * (k as f32 / 4.0)); - h.run_steps(1); - } - h.drop_at(b); + drag_middle_half(h); + h.get_by_label("OK").click(); h.run_steps(4); + assert!(!boxes_open(h), "OK closes the dialog"); let (w, hh) = size(h, 0); assert!((w - 150.0).abs() < 2.0 && (hh - 200.0).abs() < 2.0, "{w}×{hh}"); assert_eq!(size(h, 1), (300.0, 400.0)); @@ -80,6 +102,26 @@ fn crop_middle_half(h: &mut Harness<'static, PdfCraftApp>) { assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Crop page")); } +/// Drags a crop rectangle over the middle half of page 0 and checks that Set Page Boxes opens with its margins, for +/// that page alone, and that nothing is cropped yet (#5695). +fn drag_middle_half(h: &mut Harness<'static, PdfCraftApp>) { + let r = h.state().views[0].page_screen_rect(0).unwrap(); + // The middle half of the page in both directions. + let (a, b) = (r.min + r.size() * 0.25, r.min + r.size() * 0.75); + drag(h, a, b); + assert!(boxes_open(h), "a drawn rectangle opens Set Page Boxes"); + assert_eq!(size(h, 0), (300.0, 400.0), "nothing is cropped before OK"); + assert_eq!(h.state().quick_tool, QuickTool::Select, "one rectangle, then back to Select"); + let d = &h.state().boxes_draft; + assert_eq!(d.drawn.map(|d| d.page), Some(0), "the dialog is for the page drawn on"); + assert_eq!(d.which, PageBox::Crop); + assert_eq!(d.range.pages(2, 0, &[]), [0], "that page alone, of the two"); + // Left, bottom, right, top: a quarter of the 300 × 400 page in from each side. + for (m, want) in d.margins.iter().zip([75.0, 100.0, 75.0, 100.0]) { + assert!((m - want).abs() < 2.0, "{:?}", d.margins); + } +} + /// The gap the dialog keeps between its body and its footer at the app's density; the body is clipped above it. const FOOTER_GAP: f32 = 16.0; @@ -237,12 +279,7 @@ fn set_page_boxes_dialog_applies_margins_to_the_chosen_pages() { h.get_by_role_and_label(Role::Dialog, "Set Page Boxes"); // One inch off every side (the units default to inches). for side in ["Top", "Bottom", "Left", "Right"] { - h.get_by_label(side).click(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.get_by_label(side).type_text("1"); - h.key_press(egui::Key::Tab); - h.run_steps(2); + type_margin(&mut h, side, "1"); } h.get_by_label("OK").click(); h.run_steps(4); @@ -270,20 +307,187 @@ fn the_crop_tool_leaves_the_page_grid_so_a_page_can_be_cropped() { assert_eq!(h.state().quick_tool, QuickTool::Crop); assert!(!h.state().views[0].organize, "\"page.crop\" must clear view.organize"); h.run_steps(2); - let r = h.state().views[0].page_screen_rect(0).unwrap(); - // The middle half of the page in both directions. - let (a, b) = (r.min + r.size() * 0.25, r.min + r.size() * 0.75); - h.hover_at(a); - h.run_steps(1); - h.drag_at(a); - h.run_steps(1); - for k in 1..=4 { - h.hover_at(a + (b - a) * (k as f32 / 4.0)); - h.run_steps(1); - } - h.drop_at(b); + drag_middle_half(&mut h); + h.get_by_label("OK").click(); h.run_steps(4); let (w, hh) = size(&h, 0); assert!((w - 150.0).abs() < 2.0 && (hh - 200.0).abs() < 2.0, "{w}×{hh}"); assert_eq!(size(&h, 1), (300.0, 400.0)); } + +#[test] +fn a_drawn_crop_rectangle_can_be_fine_tuned_before_it_is_applied() { + let mut h = harness(); + assert!(h.execute("page.crop")); + h.run_steps(2); + drag_middle_half(&mut h); + // Keep the left edge: a zero margin leaves it at the media box (#5695). + type_margin(&mut h, "Left", "0"); + h.get_by_label("OK").click(); + h.run_steps(4); + let (w, hh) = size(&h, 0); + assert!((w - 225.0).abs() < 2.0 && (hh - 200.0).abs() < 2.0, "{w}×{hh}"); + assert_eq!(size(&h, 1), (300.0, 400.0), "only the page the rectangle was drawn on"); +} + +#[test] +fn a_crop_rectangle_drawn_on_a_page_mostly_scrolled_away_crops_that_page() { + let mut h = harness(); + assert!(h.execute("page.crop")); + h.run_steps(2); + // Scroll until only a strip of page 0's bottom is left at the top of the view, so page 1 + // fills most of it and is current. + let middle = h.state().views[0].page_screen_rect(0).unwrap().center(); + for _ in 0..60 { + let top = h.state().views[0].viewport_rect().top(); + if h.state().views[0].page_screen_rect(0).is_some_and(|r| r.max.y <= top + 150.0) { + break; + } + h.hover_at(middle); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -40.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }); + h.run_steps(3); + } + h.run_steps(6); + assert_eq!(h.state().views[0].current(), 1, "scrolled to page 1"); + // A strip across the bottom of page 0, the part of it left on screen. + let r0 = h.state().views[0].page_screen_rect(0).unwrap(); + assert!(r0.max.y - 40.0 > h.state().views[0].viewport_rect().top(), "the strip is on screen"); + let a = egui::pos2(r0.min.x + r0.width() * 0.25, r0.max.y - 40.0); + let b = egui::pos2(r0.min.x + r0.width() * 0.75, r0.max.y - 10.0); + // Pressing a page makes it current (as clicking one does); the dialog is bound to the page + // drawn on either way, not to whichever page is current when it is answered. + drag(&mut h, a, b); + assert!(boxes_open(&h)); + assert_eq!(h.state().boxes_draft.drawn.map(|d| d.page), Some(0), "the dialog is for the page the rectangle was drawn on"); + assert_eq!(h.state().boxes_draft.seeded, Some((0, PageBox::Crop)), "and keeps its margins"); + // Moving to another page edits nothing: the dialog stays open and still crops page 0. + h.state_mut().views[0].go_to_page(1); + h.run_steps(4); + assert_eq!(h.state().views[0].current(), 1); + assert!(boxes_open(&h), "navigating does not close it"); + h.get_by_label("OK").click(); + h.run_steps(4); + assert_eq!(size(&h, 1), (300.0, 400.0), "the current page is left alone"); + // The middle half across and a strip of the bottom: page 0, not the page shown most. + let (w, hh) = size(&h, 0); + assert!((w - 150.0).abs() < 2.0 && (5.0..=25.0).contains(&hh), "page 0 is cropped to the strip: {w}×{hh}"); +} + +#[test] +fn set_page_boxes_closed_with_escape_after_a_drawn_rectangle_forgets_its_page() { + let mut h = harness(); + assert!(h.execute("page.crop")); + h.run_steps(2); + drag_middle_half(&mut h); + h.key_press(egui::Key::Escape); + h.run_steps(4); + assert!(!boxes_open(&h), "Escape closes it"); + assert_eq!(h.state().boxes_draft.drawn, None, "opened again by any route, it is for the current page"); + assert_eq!(size(&h, 0), (300.0, 400.0), "and nothing is cropped"); +} + +#[test] +fn cancelling_set_page_boxes_after_a_drawn_rectangle_crops_nothing() { + let mut h = harness(); + assert!(h.execute("page.crop")); + h.run_steps(2); + drag_middle_half(&mut h); + h.get_by_label("Cancel").click(); + h.run_steps(4); + assert!(!boxes_open(&h)); + assert_eq!(size(&h, 0), (300.0, 400.0)); + assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), None); + assert_eq!(h.state().quick_tool, QuickTool::Select, "Cancel goes back to Select too"); + // Set Page Boxes opened afterwards starts from the page's own box, not the old rectangle. + assert!(h.execute("page.boxes")); + h.run_steps(3); + assert_eq!(h.state().boxes_draft.margins, [0.0; 4]); + assert_eq!(h.state().boxes_draft.drawn, None); +} + +/// A crop rectangle drawn on page 1, then the pages reordered while Set Page Boxes is still open (as an automation tool +/// or the control channel can): index 0 now names the other page, so the dialog closes rather than crop it, and OK can +/// no longer reach either page. +#[test] +fn a_crop_rectangle_draft_closes_when_its_page_moves() { + let mut h = harness(); + assert!(h.execute("page.crop")); + h.run_steps(2); + drag_middle_half(&mut h); + let ctx = h.ctx.clone(); + assert!(h.state_mut().apply_edit(&ctx, Edit::MovePages { pages: vec![0], to: 1 })); + h.run_steps(4); + assert!(!boxes_open(&h), "the draft for the page drawn on closes"); + assert_eq!(h.state().boxes_draft.drawn, None); + // Were it still open, its OK would crop whichever page is at index 0 now. + if let Some(ok) = h.query_by_label("OK") { + ok.click(); + h.run_steps(4); + } + assert_eq!(size(&h, 0), (300.0, 400.0), "the page now first is not cropped"); + assert_eq!(size(&h, 1), (300.0, 400.0), "nor the page drawn on"); + assert_ne!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Crop page")); +} + +/// A crop rectangle drawn in one document, then another document already open in a tab coming forward (the system +/// opening that file again, which focuses its tab) while Set Page Boxes is still open: the draft is the first +/// document's alone, so the dialog closes and neither document is cropped. Its margins never reach the page of the +/// same number in the other document. +#[test] +fn a_crop_rectangle_draft_closes_when_another_document_comes_forward() { + let dir = std::env::temp_dir().join(format!("pdfcraft-pageboxes-tabs-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (first, second) = (dir.join("first.pdf"), dir.join("second.pdf")); + for path in [&first, &second] { + std::fs::write(path, FIXTURE).unwrap(); + } + let (first_path, second_path) = (first.to_string_lossy().into_owned(), second.to_string_lossy().into_owned()); + let (a, b) = (first_path.clone(), second_path.clone()); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { + crate::support::install_runtime(&cc.egui_ctx); + let ctx = egui::Context::default(); + let mut app = crate::control::new_app(); + app.set_option(&ctx, "language", "en").unwrap(); + app.open_bytes(&ctx, "second.pdf", Some(b), FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "first.pdf", Some(a), FIXTURE.to_vec()).unwrap(); + app.set_option(&ctx, "left", "closed").unwrap(); + app.set_option(&ctx, "zoom", "150").unwrap(); + app + }); + h.run_steps(6); + let view_of = |h: &Harness<'static, PdfCraftApp>, name: &str| { + h.state().views.iter().position(|v| h.state().session.get(v.id).is_some_and(|d| d.name == name)).unwrap() + }; + let size_in = |h: &Harness<'static, PdfCraftApp>, name: &str| { + let s = h.state(); + let p = &s.session.get(s.views[view_of(h, name)].id).unwrap().info.pages[0]; + (p.width, p.height) + }; + let first_view = view_of(&h, "first.pdf"); + assert_eq!(h.state().active, Some(first_view), "the document opened last is in front"); + + assert!(h.execute("page.crop")); + h.run_steps(2); + let r = h.state().views[first_view].page_screen_rect(0).unwrap(); + drag(&mut h, r.min + r.size() * 0.25, r.min + r.size() * 0.75); + assert!(boxes_open(&h), "the rectangle opens Set Page Boxes"); + + // The other file, opened again from the system, comes forward with the dialog still open. + assert_eq!(h.state_mut().open_path(&second_path), pdfcraft_ui_egui::OpenOutcome::Focused); + h.run_steps(4); + assert_eq!(h.state().active, Some(view_of(&h, "second.pdf"))); + assert!(!boxes_open(&h), "the first document's draft closes"); + if let Some(ok) = h.query_by_label("OK") { + ok.click(); + h.run_steps(4); + } + assert_eq!(size_in(&h, "second.pdf"), (300.0, 400.0), "the other document's page is not cropped"); + assert_eq!(size_in(&h, "first.pdf"), (300.0, 400.0), "nothing was applied to the first either"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/tests/it/pointer.rs b/crates/ui-egui/tests/it/pointer.rs index c31755abaf..e29cf4a480 100644 --- a/crates/ui-egui/tests/it/pointer.rs +++ b/crates/ui-egui/tests/it/pointer.rs @@ -385,6 +385,32 @@ fn a_drag_from_text_onto_a_link_selects_the_text() { assert!(selected.contains("example.org"), "the drag selected across the link: {selected:?}"); } +/// A scanned page can have a page-sized image plus recognized text drawn in invisible rendering mode. +#[test] +fn dragging_across_invisible_ocr_text_selects_the_words_instead_of_the_scan() { + let image = "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\nA\nendstream"; + let content = stream("q 300 0 0 400 0 0 cm /Scan Do Q BT /F1 12 Tf 3 Tr 40 300 Td (ONE TWO SIX END) Tj ET"); + let bytes = pdf(&[ + CATALOG, + PAGES, + "<< /Type /Page /Parent 2 0 R /Resources << /XObject << /Scan 4 0 R >> /Font << /F1 5 0 R >> >> /Contents 6 0 R >>", + image, + "<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>", + &content, + ]); + let mut h = open(bytes, "150", false); + let background = at(&h, 150.0, 180.0); + mouse_click(&mut h, background); + assert!(h.state().views[0].session.picked_image.is_some(), "a click on the scan still picks its image"); + + // In 12 pt Courier each glyph is 7.2 points wide. Start inside the T and release inside the X. + let start = at(&h, 40.0 + 4.5 * 7.2, 304.0); + let end = at(&h, 40.0 + 10.5 * 7.2, 304.0); + mouse_drag(&mut h, start, end - start); + assert_eq!(h.state().views[0].selected_text().as_deref(), Some("TWO SIX")); + assert!(h.state().views[0].session.picked_image.is_none(), "the underlying image stays unselected after the drag"); +} + /// With the Select tool a click on a link over a picture follows the link and picks no picture; one /// on the picture beside the link picks it. The link's click used to pick the picture under it too. #[test] @@ -665,8 +691,10 @@ fn escape_cancels_a_crop_rectangle() { h.run_steps(1); h.drop_at(b); h.run_steps(4); + assert!(h.query_by_label("Set Page Boxes").is_none(), "an abandoned rectangle doesn't open Set Page Boxes"); let s = h.state(); assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), None, "no page box was set"); + assert_eq!(s.boxes_draft.drawn, None); } // --------------------------------------------------------------------------------------------- @@ -1391,6 +1419,27 @@ fn stamp_pages(h: &Harness<'_, PdfCraftApp>) -> Vec { s.session.get(s.views[0].id).unwrap().info.annotations.iter().filter(|a| a.subtype == "Stamp").map(|a| a.page).collect() } +/// The saved annotation stays under the click after applying both the view zoom and a second page's offset. +#[test] +fn the_saved_stamp_is_centred_on_the_click_on_zoomed_page_two() { + let mut h = open(two_pages_pdf(), "75", false); + h.state_mut().quick_tool = QuickTool::Stamp(StampKind::DynApproved); + h.run_steps(4); + let page = h.state().views[0].page_screen_rect(1).expect("page two is visible"); + // This 300 by 400 point page is unrotated: (60 %, 25 %) from its top left is PDF (180, 300). + let click = page.min + egui::vec2(page.width() * 0.6, page.height() * 0.25); + mouse_click(&mut h, click); + let app = h.state(); + let bytes = app.session.save_bytes(app.views[0].id).unwrap(); + let mut reopened = pdfcraft_engine::Session::new(); + let id = reopened.open("stamped.pdf", None, bytes, None).unwrap(); + let annotations = &reopened.get(id).unwrap().info.annotations; + let [stamp] = annotations.as_slice() else { panic!("expected exactly one saved annotation") }; + assert_eq!((stamp.page, stamp.subtype.as_str()), (1, "Stamp")); + let [left, bottom, right, top] = stamp.rect; + assert!(((left + right) * 0.5 - 180.0).abs() < 1.0 && ((bottom + top) * 0.5 - 300.0).abs() < 1.0, "saved /Rect {:?}", stamp.rect); +} + /// Where pages touch (the gaps hidden), a press on the row they share is the first page's: a stamp /// clicked there lands on page 1. The second page used to take the press over. #[test] diff --git a/crates/ui-egui/tests/it/prepare.rs b/crates/ui-egui/tests/it/prepare.rs index b8cf14885f..1e3d8e0418 100644 --- a/crates/ui-egui/tests/it/prepare.rs +++ b/crates/ui-egui/tests/it/prepare.rs @@ -1042,6 +1042,60 @@ fn duplicating_a_field_onto_every_page() { assert_eq!(doc.can_undo(), Some("Duplicate field")); } +/// Copy into Grid from a field's menu: a calendar day styled once (multi-line, no background, no +/// border) is repeated, and every copy looks and behaves as the day does. +#[test] +fn copying_a_field_into_a_grid_from_its_context_menu() { + use pdfcraft_engine::{Edit, FieldLookPatch, FieldProps}; + let mut h = harness(); + let bare = FieldLookPatch { fill: Some(None), border: Some(None), width: Some(0.0), ..Default::default() }; + let props = FieldProps { multiline: Some(true), appearance: Some(bare), ..Default::default() }; + let ctx_h = h.ctx.clone(); + assert!(h.state_mut().apply_edit(&ctx_h, Edit::SetFieldProps { name: "city".into(), props: Box::new(props) })); + h.execute("form.prepare"); + h.run_steps(3); + let before = names(&h); + let (styled, p) = { + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + let f = doc.form.iter().find(|f| f.name == "city").unwrap(); + let on_screen = pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen"); + ((f.flags, doc.field_look("city").unwrap()), on_screen.center()) + }; + h.hover_at(p); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + h.get_by_label("Copy into Grid…").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::Dialog, "Copy into Grid"); + assert!(table_open(&h)); + assert_eq!(table(&h)["source"], "city"); + assert!(table(&h).get("reason").is_none(), "the starting grid can be added: {}", table(&h)); + // A column added in the window is named as the first one is. + h.get_by_role_and_label(Role::SpinButton, "Columns").focus(); + h.run_steps(1); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + h.get_by_label("Add fields").click(); + h.run_steps(3); + let after = names(&h); + let added: Vec<&String> = after.iter().filter(|n| !before.contains(n)).collect(); + assert_eq!(added.len(), 4, "two rows of two copies: {added:?}"); + assert!(added.iter().all(|n| n.starts_with("Copy")), "every column is named as a copy: {added:?}"); + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + for name in added { + let f = doc.form.iter().find(|f| &f.name == name).unwrap(); + assert_eq!((f.flags, doc.field_look(name).unwrap()), styled, "{name} keeps the day's multi-line flag, background and border"); + } + assert_eq!(doc.can_undo(), Some("Copy field into grid")); + h.execute("edit.undo"); + h.run_steps(2); + assert_eq!(names(&h), before, "one undo takes every copy back"); +} + #[test] fn aligning_distributing_and_sizing_several_fields() { use pdfcraft_ui_egui::prepare::{Arrange, arrange}; @@ -2112,3 +2166,173 @@ fn with_prepare_open_a_double_click_on_a_field_leaves_the_polygon_unfinished() { assert_eq!(polygons, 0, "the polygon is not finished"); assert!(!s.views[0].session.comments.tool.drawing().is_empty(), "it is still being clicked out"); } + +/// The form fixture with a check box `consent` (checked) and a drop-down `shade` (green) added, +/// preparing the form, on a clipboard the test reads. +fn copy_paste_harness() -> (Harness<'static, PdfCraftApp>, crate::support::RecordingClipboard, Vec) { + copy_paste_harness_turned(0) +} + +/// [`copy_paste_harness`] with page 1 turned by `degrees`. +fn copy_paste_harness_turned(degrees: i64) -> (Harness<'static, PdfCraftApp>, crate::support::RecordingClipboard, Vec) { + use pdfcraft_engine::{Edit, FieldValue, NewField, Session}; + let mut session = Session::new(); + let id = session.open("form.pdf", None, std::sync::Arc::new(include_bytes!("../data/form.pdf").to_vec()), None).unwrap(); + let shade = NewField::Combo { options: vec!["red".to_string(), "green".to_string()], editable: false }; + for edit in [ + Edit::AddField { page: 0, rect: [20.0, 280.0, 50.0, 310.0], kind: NewField::CheckBox, name: Some("consent".into()) }, + Edit::SetFieldValue { name: "consent".into(), value: FieldValue::Check(true) }, + Edit::AddField { page: 0, rect: [80.0, 290.0, 200.0, 310.0], kind: shade, name: Some("shade".into()) }, + Edit::SetFieldValue { name: "shade".into(), value: FieldValue::Choice(vec!["green".into()]) }, + ] { + session.apply(id, edit).unwrap(); + } + if degrees != 0 { + session.apply(id, Edit::RotatePages { pages: vec![0], degrees }).unwrap(); + } + let bytes = session.save_bytes(id).unwrap().as_ref().clone(); + let clipboard = crate::support::RecordingClipboard::default(); + let mut h = harness_on(crate::support::app_with_clipboard(clipboard.clone()), "form.pdf", bytes); + assert!(h.execute("form.prepare")); + h.run_steps(2); + let before = names(&h); + (h, clipboard, before) +} + +/// Selects `consent` and `shade` and copies them with the Copy key. +fn copy_two_fields(h: &mut Harness<'static, PdfCraftApp>) { + { + let p = &mut h.state_mut().views[0].session.prepare; + p.selected = Some(("consent".into(), 0)); + p.also = vec![("shade".into(), 0)]; + } + h.event(egui::Event::Copy); + h.run_steps(2); +} + +#[test] +fn copying_and_pasting_the_selected_fields() { + use pdfcraft_engine::{Edit, FieldValue}; + let (mut h, clipboard, before) = copy_paste_harness(); + copy_two_fields(&mut h); + assert_eq!(clipboard.copied().as_deref(), Some("consent\nshade"), "Copy puts the field names on the clipboard"); + h.event(egui::Event::Paste("consent\nshade".into())); + h.run_steps(3); + let form = h.state().session.get(h.state().views[0].id).unwrap().form.as_ref().clone(); + let added: Vec<_> = form.iter().filter(|f| !before.contains(&f.name)).collect(); + assert_eq!(added.len(), 2, "one copy of each selected field, nothing else: {:?}", names(&h)); + for (source, copy) in [("consent", added[0]), ("shade", added[1])] { + let s = form.iter().find(|f| f.name == source).unwrap(); + assert_eq!((copy.kind, ©.value, ©.options), (s.kind, &s.value, &s.options), "{source} → {}", copy.name); + let (a, b) = (s.widgets[0].rect, copy.widgets[0].rect); + assert_eq!((copy.widgets.len(), copy.widgets[0].page), (1, Some(0))); + let moved = [b[0] - a[0], b[1] - a[1], b[2] - a[2], b[3] - a[3]]; + assert!(moved.iter().zip([18.0, -18.0, 18.0, -18.0]).all(|(m, e)| (m - e).abs() < 0.01), "{source}: same size, moved {moved:?}"); + } + assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Paste fields")); + let pasted: Vec<_> = added.iter().map(|f| (f.name.clone(), 0)).collect(); + let prep = &h.state().views[0].session.prepare; + assert_eq!(prep.selected.iter().chain(&prep.also).cloned().collect::>(), pasted, "the copies are selected"); + // The copies are fields of their own: changing one leaves its original alone. + let ctx = h.ctx.clone(); + assert!(h.state_mut().apply_edit(&ctx, Edit::SetFieldValue { name: added[0].name.clone(), value: FieldValue::Check(false) })); + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + let value = |name: &str| doc.form.iter().find(|f| f.name == name).unwrap().value.clone(); + assert_eq!(value("consent"), form.iter().find(|f| f.name == "consent").unwrap().value); + assert_ne!(value(&added[0].name), value("consent")); + // A second paste lands one step further. + let again = names(&h); + h.event(egui::Event::Paste("consent\nshade".into())); + h.run_steps(3); + let s = h.state(); + let form = &s.session.get(s.views[0].id).unwrap().form; + let second: Vec<_> = form.iter().filter(|f| !again.contains(&f.name)).collect(); + let consent = form.iter().find(|f| f.name == "consent").unwrap().widgets[0].rect; + assert_eq!(second.len(), 2, "{:?}", names(&h)); + assert!((second[0].widgets[0].rect[0] - consent[0] - 36.0).abs() < 0.01, "{:?}", second[0].widgets[0].rect); +} + +#[test] +fn pasting_other_text_does_not_paste_the_copied_fields() { + let (mut h, _clipboard, before) = copy_paste_harness(); + copy_two_fields(&mut h); + // Text copied in another app since: Paste brings that text, not the fields. + h.event(egui::Event::Paste("hello from another app".into())); + h.run_steps(3); + assert_eq!(names(&h), before, "stale copied fields were pasted"); +} + +#[test] +fn pasting_under_a_dialog_does_nothing() { + let (mut h, _clipboard, before) = copy_paste_harness(); + copy_two_fields(&mut h); + h.execute("help.about"); + h.run_steps(2); + assert!(crate::support::dialog_open(&h), "the About dialog is open"); + h.event(egui::Event::Paste("consent\nshade".into())); + h.run_steps(3); + assert_eq!(names(&h), before, "Paste under a dialog pasted fields behind it"); +} + +/// Review of #8604: with only the view turned (View ▸ Rotate View, the page's `/Rotate` left +/// alone), a paste still lands right and down on screen. +#[test] +fn a_paste_in_a_turned_view_moves_right_and_down_as_shown() { + let (mut h, _clipboard, before) = copy_paste_harness(); + h.state_mut().views[0].view.rotation = 180; + copy_two_fields(&mut h); + h.event(egui::Event::Paste("consent\nshade".into())); + h.run_steps(3); + let s = h.state(); + let form = &s.session.get(s.views[0].id).unwrap().form; + let copy = form.iter().find(|f| !before.contains(&f.name)).unwrap(); + let source = form.iter().find(|f| f.name == "consent").unwrap(); + let (a, b) = (source.widgets[0].rect, copy.widgets[0].rect); + let moved = [b[0] - a[0], b[1] - a[1]]; + assert!((moved[0] + 18.0).abs() < 0.01 && (moved[1] - 18.0).abs() < 0.01, "{moved:?}"); +} + +/// Review of #8604: a copied radio button deleted from its group's front still pastes as +/// itself, not as the button that took its place in the list. +#[test] +fn a_paste_after_a_widget_is_deleted_copies_the_same_button() { + use pdfcraft_engine::{Edit, NewField}; + let (mut h, _clipboard, _) = copy_paste_harness(); + let ctx = h.ctx.clone(); + for (x, export) in [(220.0, "a"), (260.0, "b"), (300.0, "c")] { + let kind = NewField::Radio { group: Some("cup".into()), export: export.into() }; + assert!(h.state_mut().apply_edit(&ctx, Edit::AddField { page: 0, rect: [x, 280.0, x + 20.0, 300.0], kind, name: Some("cup".into()) })); + } + let exports = |h: &Harness<'static, PdfCraftApp>, name: &str| -> Vec { + let s = h.state(); + let f = s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == name).cloned().unwrap(); + f.widgets.iter().filter_map(|w| w.on_state.clone()).collect() + }; + assert_eq!(exports(&h, "cup"), ["a", "b", "c"]); + h.state_mut().views[0].session.prepare.selected = Some(("cup".into(), 1)); + h.event(egui::Event::Copy); + h.run_steps(2); + assert!(h.state_mut().apply_edit(&ctx, Edit::DeleteWidget { name: "cup".into(), widget: 0 })); + let before = names(&h); + h.event(egui::Event::Paste("cup".into())); + h.run_steps(3); + let copy = names(&h).into_iter().find(|n| !before.contains(n)).expect("a copy was pasted"); + assert_eq!(exports(&h, ©), ["b"], "the copy is of the button that was copied"); +} + +#[test] +fn a_paste_on_a_turned_page_moves_right_and_down_as_shown() { + let (mut h, _clipboard, before) = copy_paste_harness_turned(180); + copy_two_fields(&mut h); + h.event(egui::Event::Paste("consent\nshade".into())); + h.run_steps(3); + let s = h.state(); + let form = &s.session.get(s.views[0].id).unwrap().form; + let copy = form.iter().find(|f| !before.contains(&f.name)).unwrap(); + let source = form.iter().find(|f| f.name == "consent").unwrap(); + let (a, b) = (source.widgets[0].rect, copy.widgets[0].rect); + // Upside down, right and down on screen is left and up in the page's own space. + let moved = [b[0] - a[0], b[1] - a[1]]; + assert!((moved[0] + 18.0).abs() < 0.01 && (moved[1] - 18.0).abs() < 0.01, "{moved:?}"); +} diff --git a/crates/ui-egui/tests/it/print.rs b/crates/ui-egui/tests/it/print.rs index 77232b8dfd..d47b8a1076 100644 --- a/crates/ui-egui/tests/it/print.rs +++ b/crates/ui-egui/tests/it/print.rs @@ -50,11 +50,19 @@ impl std::ops::DerefMut for Rig { /// An app on a scripted host, prepared by `setup`. pub(crate) fn rig_on(files: ScriptedFiles, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Rig { + rig_on_desktop(files, Arc::new(craft::window::system::NoWindows), setup) +} + +fn rig_on_desktop( + files: ScriptedFiles, + windows: Arc, + setup: impl FnOnce(&mut PdfCraftApp) + 'static, +) -> Rig { let jobs = Arc::new(ManualJobs::new()); let files = Arc::new(files); let (host_jobs, host_files) = (jobs.clone(), files.clone()); let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { - crate::support::install_runtime(&cc.egui_ctx); + crate::support::install_runtime_with(&cc.egui_ctx, windows); { let mut app = crate::support::test_app(crate::support::host_with(host_jobs, host_files)); app.set_option(&egui::Context::default(), "language", "en").unwrap(); @@ -335,6 +343,51 @@ fn current_print_page_saves_the_viewed_page_when_labels_restart() { } } +#[test] +fn file_menu_and_print_accept_clicks_on_an_offset_portrait_display() { + use craft::behavior::{Monitor, MonitorKey}; + use craft::window::system::FakeSystem; + + let windows = Arc::new(FakeSystem::new()); + windows.set_monitors(vec![ + Monitor::new(MonitorKey::new("laptop", [1920, 1080]), [0, 0], [1920, 1080], 1.0), + Monitor::new(MonitorKey::new("portrait", [1080, 1920]), [1920, -240], [1080, 1920], 1.0).with_work_px([1920, -240], [1080, 1872]), + ]); + let mut h = rig_on_desktop(saves(1), windows, |app| { + app.open_bytes(&egui::Context::default(), "form.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap(); + }); + let size = egui::vec2(1040., 1100.); + h.set_size(size); + let viewport = h.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default(); + viewport.inner_rect = Some(egui::Rect::from_min_size(egui::pos2(1920., -240.), size)); + viewport.monitor_size = Some(egui::vec2(1080., 1920.)); + h.run_steps(4); + + h.get_by_role_and_label(Role::Button, "Hand").click(); + h.run_steps(2); + assert_eq!(h.state().quick_tool, pdfcraft_ui_egui::QuickTool::Hand); + h.get_by_role_and_label(Role::Button, "Select").click(); + h.run_steps(2); + assert_eq!(h.state().quick_tool, pdfcraft_ui_egui::QuickTool::Select); + + let file = crate::support::menu_row(&h, "File").rect(); + crate::support::open_menu(&mut h, "File"); + let print = crate::support::menu_row(&h, "Print…"); + assert!(print.rect().left() <= file.right(), "File menu shifted away from its title: {:?} vs {file:?}", print.rect()); + print.click(); + h.run_steps(3); + assert!(h.is_open()); + h.settle(); + h.pick(None); + h.settle(); + h.get_by_role_and_label(Role::Button, "Save as PDF").click(); + h.run_steps(2); + h.settle(); + assert!(!h.is_open()); + let doc = pdfcraft_cos::Document::open(h.saved(0)).unwrap(); + assert_eq!(pdfcraft_model::pages(&doc).len(), 1); +} + #[test] fn print_dialog_lays_out_sheets_and_saves_a_pdf() { let mut h = harness(); diff --git a/crates/ui-egui/tests/it/redact.rs b/crates/ui-egui/tests/it/redact.rs index 06b80a76e7..4d6d2c8f4e 100644 --- a/crates/ui-egui/tests/it/redact.rs +++ b/crates/ui-egui/tests/it/redact.rs @@ -38,6 +38,8 @@ fn harness_on_file(path: String, files: Arc) -> Harness<'static, app } }); + // Opening the file runs on a worker. There is nothing to render until the document attaches. + crate::support::wait_until(&mut h, "the file to open before redaction", |app| app.active.is_some()); crate::support::settle(&mut h); h } diff --git a/crates/ui-egui/tests/it/scrollbars.rs b/crates/ui-egui/tests/it/scrollbars.rs new file mode 100644 index 0000000000..96b7640098 --- /dev/null +++ b/crates/ui-egui/tests/it/scrollbars.rs @@ -0,0 +1,42 @@ +//! The page view's scroll bar: a usable width, not a sliver the user must preempt (#9001). +//! +//! A 3-pixel floating sliver is a target the user must preempt; a scroll bar is interacted with +//! more than a button and should be a comparable, reachable size. The docked bar (18 pt) is +//! stable in every state — it does not grow when the pointer moves onto it — whereas the +//! floating bar's thumb grows from 2 pt to 6 pt on hover. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use pdfcraft_ui_egui::PdfCraftApp; + +/// The app over six 300×200 pt pages, shown continuously at 300 %: 3600 pt of content in a 900 pt +/// window, so the vertical scroll bar is always on screen (and 900 < 1400 keeps the horizontal one off). +fn harness() -> Harness<'static, PdfCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|cc| { + crate::support::install_runtime(&cc.egui_ctx); + { + let mut app = crate::control::new_app(); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + app.open_bytes(&egui::Context::default(), "pages.pdf", None, crate::support::fixtures::pdf_pages(6)).unwrap(); + app.set_option(&egui::Context::default(), "continuous", "on").unwrap(); + app.set_option(&egui::Context::default(), "zoom", "300").unwrap(); + app + } + }); + crate::support::settle(&mut h); + h.run_steps(5); + h +} + +/// The vertical scroll bar's track, from the access tree: the bar's clickable rect, whose width is +/// the bar's drawn width. +fn vertical_bar(h: &Harness<'static, PdfCraftApp>) -> egui::Rect { + h.get_by_role_and_label(egui::accesskit::Role::ScrollBar, "Vertical scroll bar").rect() +} + +#[test] +fn the_vertical_scroll_bar_is_a_usable_width() { + let h = harness(); + let track = vertical_bar(&h); + assert!(track.width() >= 16.0, "the scroll bar is a usable width ({:.1} pt), not a sliver the user must preempt", track.width()); +} diff --git a/crates/ui-egui/tests/it/show_boxes.rs b/crates/ui-egui/tests/it/show_boxes.rs new file mode 100644 index 0000000000..2120e863ea --- /dev/null +++ b/crates/ui-egui/tests/it/show_boxes.rs @@ -0,0 +1,158 @@ +//! Show art, trim and bleed boxes (Acrobat: Preferences ▸ Page Display): the boxes a page sets +//! are outlined on it, each in its colour, where the page shows them. + +use egui::{Color32, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use pdfcraft_ui_egui::PdfCraftApp; + +const ART: Color32 = Color32::from_rgb(0xE0, 0x00, 0x00); +const TRIM: Color32 = Color32::from_rgb(0x00, 0xA0, 0x00); +const BLEED: Color32 = Color32::from_rgb(0x00, 0x50, 0xF0); + +/// A 300×400 pt media box, cropped by 10 pt, with all three boxes set. +const BOXED: &[u8] = b"%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] /CropBox [10 10 290 390] /BleedBox [20 30 280 370] /TrimBox [30 40 270 360] /ArtBox [50 60 250 340] >> endobj +trailer << /Root 1 0 R >> +%%EOF"; + +/// The same crop, and no bleed, trim or art box: each one defaults to the crop box. +const PLAIN: &[u8] = b"%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] /CropBox [10 10 290 390] >> endobj +trailer << /Root 1 0 R >> +%%EOF"; + +/// Turned a quarter clockwise, with a trim box off centre so turning it shows. +const ROTATED: &[u8] = b"%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] /Rotate 90 /TrimBox [30 40 250 380] >> endobj +trailer << /Root 1 0 R >> +%%EOF"; + +fn harness(pdf: &'static [u8], show: Option<&'static str>) -> Harness<'static, PdfCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_eframe(move |cc| { + crate::support::install_runtime(&cc.egui_ctx); + let mut app = crate::control::new_app(); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + app.open_bytes(&egui::Context::default(), "boxes.pdf", None, pdf.to_vec()).expect("opens"); + app.set_option(&egui::Context::default(), "left", "closed").unwrap(); + app.set_option(&egui::Context::default(), "panel", "none").unwrap(); + app.set_option(&egui::Context::default(), "layout", "single").unwrap(); + if let Some(show) = show { + app.set_option(&egui::Context::default(), "page-boxes", show).unwrap(); + } + app + }); + h.run_steps(4); + h +} + +/// The outlines drawn in `color` this frame. +fn outlines(h: &Harness<'static, PdfCraftApp>, color: Color32) -> Vec { + h.output() + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Rect(r) if r.stroke.color == color && r.stroke.width > 0.0 => Some(r.rect), + _ => None, + }) + .collect() +} + +/// `page` scaled to the fractions `[left, top, right, bottom]` of its width and height. +fn part(page: Rect, f: [f32; 4]) -> Rect { + Rect::from_min_max( + egui::pos2(page.left() + f[0] * page.width(), page.top() + f[1] * page.height()), + egui::pos2(page.left() + f[2] * page.width(), page.top() + f[3] * page.height()), + ) +} + +fn assert_near(got: Rect, want: Rect, what: &str) { + let off = (got.min - want.min).length().max((got.max - want.max).length()); + assert!(off < 1.0, "{what}: drawn at {got:?}, expected {want:?}"); +} + +#[test] +fn a_trim_box_inside_the_crop_is_outlined_where_it_is_on_the_page() { + let h = harness(BOXED, Some("on")); + let page = h.state().views[0].page_screen_rect(0).unwrap(); + // The page shows the crop box, 280 × 380 pt from (10, 10); y runs down from its top (390). + let trim = outlines(&h, TRIM); + assert_eq!(trim.len(), 1, "one trim outline: {trim:?}"); + assert_near(trim[0], part(page, [20.0 / 280.0, 30.0 / 380.0, 260.0 / 280.0, 350.0 / 380.0]), "trim box"); + let bleed = outlines(&h, BLEED); + assert_eq!(bleed.len(), 1, "one bleed outline: {bleed:?}"); + assert_near(bleed[0], part(page, [10.0 / 280.0, 20.0 / 380.0, 270.0 / 280.0, 360.0 / 380.0]), "bleed box"); + let art = outlines(&h, ART); + assert_eq!(art.len(), 1, "one art outline: {art:?}"); + assert_near(art[0], part(page, [40.0 / 280.0, 50.0 / 380.0, 240.0 / 280.0, 330.0 / 380.0]), "art box"); +} + +#[test] +fn a_page_without_its_own_boxes_draws_none() { + let h = harness(PLAIN, Some("on")); + for (color, name) in [(TRIM, "trim"), (BLEED, "bleed"), (ART, "art")] { + assert!(outlines(&h, color).is_empty(), "the default {name} box is the crop box, not drawn"); + } +} + +#[test] +fn boxes_on_a_rotated_page_turn_with_it() { + let h = harness(ROTATED, Some("on")); + let page = h.state().views[0].page_screen_rect(0).unwrap(); + assert!(page.width() > page.height(), "the page shows turned: {page:?}"); + // Turned clockwise, the user-space left edge (x = 30) is the top and the bottom (y = 40) is + // the left, each a tenth in; the top (y = 380) is 20 pt from the right, x = 250 at 5/6 down. + let trim = outlines(&h, TRIM); + assert_eq!(trim.len(), 1, "one trim outline: {trim:?}"); + assert_near(trim[0], part(page, [40.0 / 400.0, 30.0 / 300.0, 380.0 / 400.0, 250.0 / 300.0]), "rotated trim box"); +} + +#[test] +fn boxes_are_hidden_until_the_preference_is_on() { + let h = harness(BOXED, None); + assert!(!h.state().show_page_boxes, "off by default, as in Acrobat"); + for (color, name) in [(TRIM, "trim"), (BLEED, "bleed"), (ART, "art")] { + assert!(outlines(&h, color).is_empty(), "no {name} outline with the preference off"); + } + let h = harness(BOXED, Some("off")); + assert!(outlines(&h, TRIM).is_empty(), "page-boxes off hides them"); +} + +#[test] +fn preferences_turn_the_boxes_on_and_the_choice_is_remembered() { + let mut h = harness(BOXED, None); + let ctx = h.ctx.clone(); + h.state_mut().set_option(&ctx, "dialog", "preferences").unwrap(); + h.run_steps(2); + // This category is already selected when Preferences opens; its panel and sidebar + // label share the same accessible name. + let checkbox = egui::accesskit::Role::CheckBox; + h.get_by_role_and_label(checkbox, "Show art, trim and bleed boxes").scroll_to_me(); + h.run_steps(4); + h.get_by_role_and_label(checkbox, "Show art, trim and bleed boxes").click(); + h.run_steps(2); + assert!(h.state().show_page_boxes); + let saved = h.state().settings_snapshot(); + let mut next = crate::control::new_app(); + next.apply_settings(&saved); + assert!(next.show_page_boxes, "the preference survives a restart"); +} + +#[test] +fn control_page_box_change_survives_another_open_preference_edit() { + let mut h = harness(BOXED, None); + let ctx = h.ctx.clone(); + h.state_mut().set_option(&ctx, "dialog", "preferences").unwrap(); + h.run_steps(2); + h.state_mut().set_option(&ctx, "page-boxes", "on").unwrap(); + h.run_steps(2); + h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Show form field reminder").click(); + h.run_steps(2); + assert!(h.state().show_page_boxes, "the unrelated preference must not overwrite the control change"); +} diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index a40ef1bbf7..cb548c029b 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -119,3 +119,28 @@ fn f4_toggles_the_side_panel_and_shift_f4_the_tools_panel() { h.run_steps(3); h.get_by_label("Expand all tools"); } + +/// The Open… button on the tab strip names the command by its `@id` row, in the interface +/// language (the way the menus do), not by the English command label (#8960). +#[test] +fn the_open_button_on_the_tab_strip_is_in_the_interface_language() { + if crate::support::skip_without_catalogs("the_open_button_on_the_tab_strip_is_in_the_interface_language") { + return; + } + let de = pdfcraft_ui_egui::i18n::Lang::from_code("de").unwrap(); + let expected = { + pdfcraft_ui_egui::i18n::set_current(de); + let expected = pdfcraft_ui_egui::i18n::menu_label("file.open", "Open…"); + pdfcraft_ui_egui::i18n::set_current(pdfcraft_ui_egui::i18n::Lang::EN); + expected + }; + if expected == "Open…" { + eprintln!("skipping: German has no @id row for file.open"); + return; + } + let mut h = harness(|_| {}); + h.set_option("language", "de").unwrap(); + h.run_steps(2); + assert!(h.query_by_label(&expected).is_some(), "the Open… button is in the interface language: {expected:?}"); + assert!(h.query_by_label("Open…").is_none(), "the Open… button is not in English when the translation exists"); +} diff --git a/crates/ui-egui/tests/it/signing.rs b/crates/ui-egui/tests/it/signing.rs index a3f4f75081..f6cef77759 100644 --- a/crates/ui-egui/tests/it/signing.rs +++ b/crates/ui-egui/tests/it/signing.rs @@ -557,6 +557,17 @@ fn a_signature_badge_says_its_verdict_with_any_tool() { assert_eq!(hover(&mut h, stamp, p + egui::vec2(1.0, 0.0)), (egui::CursorIcon::Crosshair, true), "so does a stamp, beside its crosshair"); } +fn open_xfa_signing_form(h: &mut Harness<'static, PdfCraftApp>) { + let bytes = pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::signing_events_template()); + let ctx = h.ctx.clone(); + h.state_mut().open_bytes(&ctx, "events.pdf", None, bytes).unwrap(); + // Only the visible tab consumes its render results. The hidden contract may still have + // a pending page, so waiting for every document here can never finish. + crate::support::wait_until(h, "the XFA page in the active tab", |app| { + app.active == Some(1) && app.views.get(1).is_some_and(|view| view.page_screen_rect(0).is_some() && !view.render_pending()) + }); +} + /// Signing a dynamic form's signature box in the app runs its XFA preSign script as signing begins, /// so its notice and the value it sets show before the signer confirms, and that value is in the /// signed file; its postSign script runs once signed, its change left to save. @@ -565,11 +576,7 @@ fn signing_an_xfa_box_runs_its_signing_scripts_in_the_app() { let dir = dir().join("xfa-events"); std::fs::create_dir_all(&dir).unwrap(); let mut h = harness(dir.clone()); - let bytes = pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::signing_events_template()); - let ctx_h = h.ctx.clone(); - h.state_mut().open_bytes(&ctx_h, "events.pdf", None, bytes).unwrap(); - h.state_mut().active = Some(1); - crate::support::settle(&mut h); + open_xfa_signing_form(&mut h); let named = |h: &Harness<'static, PdfCraftApp>, n: &str| { let s = h.state(); s.session.get(s.views[1].id).unwrap().form.iter().find(|f| f.name == n || f.name.ends_with(&format!(".{n}[0]"))).cloned().unwrap() @@ -624,11 +631,7 @@ fn cancelling_signing_takes_back_the_presign_scripts_changes() { let dir = dir().join("xfa-events-cancel"); std::fs::create_dir_all(&dir).unwrap(); let mut h = harness(dir.clone()); - let bytes = pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::signing_events_template()); - let ctx_h = h.ctx.clone(); - h.state_mut().open_bytes(&ctx_h, "events.pdf", None, bytes).unwrap(); - h.state_mut().active = Some(1); - crate::support::settle(&mut h); + open_xfa_signing_form(&mut h); let named = |h: &Harness<'static, PdfCraftApp>, n: &str| { let s = h.state(); s.session.get(s.views[1].id).unwrap().form.iter().find(|f| f.name == n || f.name.ends_with(&format!(".{n}[0]"))).cloned().unwrap() diff --git a/crates/ui-egui/tests/it/support/input.rs b/crates/ui-egui/tests/it/support/input.rs index c6862ff9d8..1c060c082f 100644 --- a/crates/ui-egui/tests/it/support/input.rs +++ b/crates/ui-egui/tests/it/support/input.rs @@ -16,6 +16,17 @@ pub fn one_frame(h: &mut Harness<'_, S>, events: impl IntoIterator, events: impl IntoIterator) { + h.input_mut().events.extend(events); + let ctx = h.ctx.clone(); + let mut raw = std::mem::take(h.input_mut()); + eframe::App::raw_input_hook(h.state_mut(), &ctx, &mut raw); + *h.input_mut() = raw; + h.step(); + h.run_steps(2); +} + fn button(pos: Pos2, pressed: bool) -> Event { Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } } diff --git a/crates/ui-egui/tests/it/support/mod.rs b/crates/ui-egui/tests/it/support/mod.rs index 14d5c3a27f..f64077f1ed 100644 --- a/crates/ui-egui/tests/it/support/mod.rs +++ b/crates/ui-egui/tests/it/support/mod.rs @@ -25,6 +25,11 @@ use std::path::PathBuf; pub mod fixtures; pub mod input; +/// Numeric fields follow the formatting region even when the interface language is English. +pub fn typed_decimal(value: f64, places: usize) -> String { + craft_i18n::Format::new(&craft_i18n::Region::system(), craft_i18n::Digits::Locale).number_ungrouped(value, places) +} + /// Step frames until `ready` holds or 30 seconds pass, and say whether it held. For background work /// (a worker-thread open, page text arriving) that a test then asserts on itself: a frame count is /// not a time, and a busy runner may not have finished the work within one. Sleeps briefly between @@ -145,7 +150,12 @@ pub fn app_with_clipboard(clipboard: RecordingClipboard) -> PdfCraftApp { /// Installs the framework runtime on a harness's context, as the app's window does, with a system /// that opens no OS windows and the interface fonts of English. Every harness creator calls it. pub fn install_runtime(ctx: &egui::Context) { - let spec = InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)); + install_runtime_with(ctx, Arc::new(NoWindows)); +} + +/// Install a runtime with the supplied desktop topology. +pub fn install_runtime_with(ctx: &egui::Context, windows: Arc) { + let spec = InstallSpec::new(ShellInfo::default(), windows); embed::install(ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(i18n::Lang::EN)).expect("the runtime installs on a fresh context"); pin_shell_os(ctx); } diff --git a/crates/ui-egui/tests/it/ui.rs b/crates/ui-egui/tests/it/ui.rs index 64d9d0c734..8c4d689c23 100644 --- a/crates/ui-egui/tests/it/ui.rs +++ b/crates/ui-egui/tests/it/ui.rs @@ -58,6 +58,22 @@ fn side(h: &mut Harness<'static, PdfCraftApp>, key: &str) -> String { pdfcraft_ui_egui::side_panels::state(h.state())[key].as_str().unwrap_or_default().to_owned() } +#[test] +fn page_controls_full_screen_button_enters_full_screen() { + let mut h = harness(|app| app.open_bytes(&egui::Context::default(), "fixture.pdf", None, FIXTURE.to_vec()).expect("fixture opens")); + h.run_steps(3); + let zoom_out = h.get_by_label("Zoom out").rect(); + let full_screen = h.get_by_label("Full screen mode"); + assert!(full_screen.rect().top() >= zoom_out.bottom(), "the full-screen button sits below Zoom out"); + // The pinned icon toggle omits the AccessKit property in its unpressed state. + assert_eq!(full_screen.accesskit_node().toggled(), None); + full_screen.click(); + h.run_steps(2); + assert!(h.state().full_screen()); + // Full-screen reading shows the document body alone, so the rail is hidden while on. + assert!(h.query_by_label("Full screen mode").is_none()); +} + /// The side panel the workspace has open, as `ui.state` reports it (`side_panel`). pub(crate) fn right(app: &PdfCraftApp) -> Option { let state = pdfcraft_ui_egui::side_panels::state(app); @@ -745,6 +761,52 @@ fn tabs_shrink_to_fit_then_arrows_step_through_them_and_open_stays_in_sight() { assert!(open.left() > 0.0 && open.right() <= discord.left(), "Open {open:?} stays in sight left of Discord {discord:?}"); } +#[test] +fn the_wheel_reveals_overflowing_document_tabs_without_switching_documents() { + use egui::accesskit::Role; + const COUNT: usize = 20; + let name = |i: usize| format!("Statement {i:02} for the office records, scanned.pdf"); + let mut h = harness(move |app| { + for i in 0..COUNT { + app.open_bytes(&egui::Context::default(), &name(i), None, FIXTURE.to_vec()).unwrap(); + } + }); + h.get_by_role_and_label(Role::Tab, &name(0)).click(); + h.run_steps(4); + let active = h.state().views[0].id; + let visible = |h: &Harness<'static, PdfCraftApp>| -> Vec { + (0..COUNT).filter(|&i| h.query_by_role_and_label(Role::Tab, &name(i)).is_some()).collect() + }; + let before = visible(&h); + assert!(before.contains(&0) && before.len() < COUNT); + assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(active)); + h.get_by_label("More tabs"); + let over = h.get_by_role_and_label(Role::Tab, &name(0)).rect().center(); + h.hover_at(over); + h.run_steps(1); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Wheel, + }); + h.run_steps(4); + let after = visible(&h); + assert!(!after.contains(&0), "the active document's tab can move out of sight"); + let revealed = after.into_iter().find(|i| !before.contains(i)).expect("a previously hidden tab is visible"); + assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(active)); + h.get_by_label("More tabs").click(); + h.run_steps(3); + h.get_by_label(&name(0)); // The active document still appears in the overflow menu. + h.key_press(egui::Key::Escape); + h.run_steps(3); + let expected = h.state().views[revealed].id; + h.get_by_role_and_label(Role::Tab, &name(revealed)).click(); + h.run_steps(3); + assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(expected)); +} + #[test] fn garbage_input_is_rejected_without_panicking() { let mut app = crate::control::new_app(); @@ -1951,6 +2013,41 @@ fn the_edit_panel_keeps_the_add_update_remove_menu() { h.get_by_label("Cancel"); } +/// #8989: the editable page label is centred in its rail field without changing navigation, +/// and the page-size hint has room for its whole text inside the document area. +#[test] +fn page_rail_value_is_centred_and_page_size_hint_fits() { + let mut h = harness(|app| { + app.open_bytes(&egui::Context::default(), "rail.pdf", None, FIXTURE.to_vec()).unwrap(); + }); + let page_field = |h: &Harness<'static, PdfCraftApp>| h.get(By::new().role(egui::accesskit::Role::TextInput).label("Current page")).rect(); + let check = |h: &Harness<'static, PdfCraftApp>, value: &str| { + let field = page_field(h); + let text = painted_text(h).into_iter().find(|(s, _, r)| s == value && field.contains_rect(*r)).expect("the page value is painted"); + assert!(!text.1 && (text.2.center().x - field.center().x).abs() <= 3.0, "{text:?} in {field:?}"); + assert!((text.2.center().y - field.center().y).abs() <= 2.0, "{text:?} in {field:?}"); + }; + check(&h, "1"); + h.get(By::new().role(egui::accesskit::Role::TextInput).label("Current page")).focus(); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.get(By::new().role(egui::accesskit::Role::TextInput).label("Current page")).type_text("2"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(h.state().views[0].current(), 1, "the centred field still navigates"); + check(&h, "2"); + + let area = h.state().views[0].viewport_rect(); + let size = { + let app = h.state(); + let p = &app.session.get(app.views[0].id).unwrap().info.pages[1]; + app.units.size(f64::from(p.width), f64::from(p.height)) + }; + h.event(egui::Event::PointerMoved(area.left_bottom() + egui::vec2(80.0, -80.0))); + h.run_steps(3); + let text = painted_text(&h).into_iter().find(|(s, _, _)| s == &size).expect("the page size is painted"); + assert!(!text.1 && area.contains_rect(text.2), "whole size {text:?} inside {area:?}"); +} + /// #3282: in a short window the rail's panel buttons scroll above the page navigation instead of /// being drawn under the page number field. #[test] @@ -2205,14 +2302,24 @@ fn home_recent_context_menu_reveals_the_target_without_opening_or_removing_it() #[test] fn unused_document_tab_space_moves_and_maximizes_the_integrated_window() { + unused_document_tab_space_moves_and_zooms_the_window(craft::window::policy::Os::Windows); +} + +#[test] +fn unused_document_tab_space_moves_and_zooms_the_macos_inset_window() { + unused_document_tab_space_moves_and_zooms_the_window(craft::window::policy::Os::Mac); +} + +fn unused_document_tab_space_moves_and_zooms_the_window(os: craft::window::policy::Os) { use craft::ui::testing::windows::set_os; - use craft::window::policy::{self, Backend, Desktop, Os, Runtime, TitleBarPref, WindowKind}; + use craft::window::policy::{self, Backend, Desktop, Runtime, TitleBarPref, WindowKind}; let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| { let desktop = Desktop { kind: Default::default(), ssd: None, gtk_theme: None, icon_theme: None }; - let frame = policy::decide(Os::Windows, Runtime::Native, Backend::X11, &desktop, WindowKind::Main, TitleBarPref::Integrated, None); + let frame = policy::decide(os, Runtime::Native, Backend::X11, &desktop, WindowKind::Main, TitleBarPref::Integrated, None); + assert!(os != policy::Os::Mac || matches!(frame.frame, policy::Frame::Inset(_)), "macOS draws an inset title bar"); let spec = craft::ui::InstallSpec::new(Default::default(), std::sync::Arc::new(craft::window::system::NoWindows)).frame(frame); craft::ui::shell::embed::install(&cc.egui_ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(pdfcraft_ui_egui::i18n::Lang::EN)).unwrap(); - set_os(&cc.egui_ctx, Os::Windows); + set_os(&cc.egui_ctx, os); crate::control::new_app() }); h.run_steps(6); @@ -2237,3 +2344,37 @@ fn unused_document_tab_space_moves_and_maximizes_the_integrated_window() { support::input::one_frame(&mut h, [egui::Event::PointerMoved(empty + egui::vec2(20.0, 0.0))]); assert!(h.output().viewport_output[&egui::ViewportId::ROOT].commands.contains(&egui::ViewportCommand::StartDrag)); } + +/// #8999: the reader, rather than the zoom spin button, gets keys after a click beside a page. +#[test] +fn clicking_blank_page_view_returns_keyboard_from_zoom() { + let mut h = harness(|app| { + app.open_bytes(&egui::Context::default(), "rail.pdf", None, FIXTURE.to_vec()).unwrap(); + app.set_option(&egui::Context::default(), "zoom", "50").unwrap(); + }); + h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Zoom").focus(); + h.run_steps(3); + assert!(h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Zoom").is_focused(), "zoom keeps intentional focus without a click"); + let (area, pages) = { + let app = h.state(); + (app.views[0].viewport_rect(), app.views[0].visible_page_rects()) + }; + let p = [area.left_center() + egui::vec2(12.0, 0.0), area.right_center() - egui::vec2(12.0, 0.0)] + .into_iter() + .find(|p| pages.iter().all(|(_, rect)| !rect.contains(*p))) + .expect("a blank point beside the page"); + h.hover_at(p); + h.run_steps(1); + h.drag_at(p); + h.run_steps(1); + h.drop_at(p); + h.run_steps(3); + assert!(!h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Zoom").is_focused(), "the pasteboard click leaves the zoom editor"); + let before = h.state().views[0].view.zoom; + h.key_press(egui::Key::ArrowDown); + h.run_steps(3); + assert_eq!(h.state().views[0].view.zoom, before, "reader keys do not edit zoom"); + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Current page").focus(); + h.run_steps(3); + assert!(h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Current page").is_focused(), "other controls retain intentional focus"); +} diff --git a/crates/ui-egui/tests/it/view.rs b/crates/ui-egui/tests/it/view.rs index be656eb3dd..c9896d84b8 100644 --- a/crates/ui-egui/tests/it/view.rs +++ b/crates/ui-egui/tests/it/view.rs @@ -604,7 +604,7 @@ fn the_rail_zoom_field_sets_a_typed_zoom() { }; type_zoom(&mut h, "150", Key::Enter); assert_eq!((h.state().views[0].fit(), h.state().views[0].zoom()), (Fit::None, 1.5)); - type_zoom(&mut h, "62.5 %", Key::Enter); + type_zoom(&mut h, &format!("{} %", crate::support::typed_decimal(62.5, 1)), Key::Enter); assert_eq!(h.state().views[0].zoom(), 0.625); for (typed, key) in [("abc", Key::Enter), ("0", Key::Enter), ("300", Key::Escape)] { type_zoom(&mut h, typed, key); @@ -618,6 +618,45 @@ fn the_rail_zoom_field_sets_a_typed_zoom() { assert_eq!(h.get_by_role_and_label(Role::SpinButton, "Zoom").value().as_deref(), Some("200")); } +/// A long document whose first twelve pages are numbered i, ii, …: the rail shows a label and a "page/count" position. +fn long_labelled_pdf(pages: usize) -> Vec { + let kids: Vec = (0..pages).map(|i| format!("{} 0 R", i + 3)).collect(); + let mut pdf = format!( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R /PageLabels << /Nums [0 << /S /r >> 12 << /S /D >>] >> >> endobj\n\ + 2 0 obj << /Type /Pages /Kids [{}] /Count {pages} >> endobj\n", + kids.join(" ") + ); + for i in 0..pages { + pdf.push_str(&format!("{} 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] >> endobj\n", i + 3)); + } + pdf.push_str("trailer << /Root 1 0 R >>\n%%EOF"); + pdf.into_bytes() +} + +#[test] +fn the_rail_page_box_and_position_fit_a_long_document() { + use egui::accesskit::Role; + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|cc| { + crate::support::install_runtime(&cc.egui_ctx); + let mut app = crate::control::new_app(); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + app.open_bytes(&egui::Context::default(), "long.pdf", None, long_labelled_pdf(1500)).expect("opens"); + app + }); + h.run_steps(8); + h.state_mut().run_command(&egui::Context::default(), "view.last_page"); + h.run_steps(8); + let page_box = h.get_by_role_and_label(Role::TextInput, "Current page"); + assert_eq!(page_box.value().as_deref(), Some("1488")); + // The box has the room of the zoom field under it, which holds "233" and its percent sign, so four digits fit. + let zoom = h.get_by_role_and_label(Role::SpinButton, "Zoom").rect(); + assert!(page_box.rect().width() >= zoom.width() - 0.5, "page box {:?} narrower than zoom {zoom:?}", page_box.rect()); + // The position under it ("1500/1500") stays inside the window rather than running past the rail. + let window = h.ctx.content_rect(); + let position = h.get_by_label_contains("1500/").rect(); + assert!(window.contains_rect(position), "{position:?} outside {window:?}"); +} + #[test] fn always_use_my_default_zoom_and_page_layout_ignores_what_the_pdf_asks_for() { use pdfcraft_ui_egui::canvas::{Fit, PageDisplay}; diff --git a/crates/ui-egui/tests/it/viewer.rs b/crates/ui-egui/tests/it/viewer.rs index e54ec52773..2c800467aa 100644 --- a/crates/ui-egui/tests/it/viewer.rs +++ b/crates/ui-egui/tests/it/viewer.rs @@ -144,6 +144,21 @@ fn revert_after_confirming() { assert_eq!((d.info.pages.len(), d.dirty), (2, false)); } +/// Host-side confirmation remains the explicit Revert action while keyboard focus defaults to Cancel. +#[test] +fn host_confirm_reverts_even_when_cancel_is_the_keyboard_default() { + let mut h = harness(); + let ctx = h.ctx.clone(); + h.state_mut().apply_edit(&ctx, pdfcraft_engine::Edit::DeletePages { pages: vec![0] }); + assert!(h.execute("file.revert")); + h.run_steps(2); + assert!(h.state_mut().dialogs.confirm::(&ctx)); + h.run_steps(3); + let s = h.state(); + let d = s.session.get(s.views[1].id).unwrap(); + assert_eq!((d.info.pages.len(), d.dirty), (2, false)); +} + /// Reverting throws the edits away, so no key alone answers it: the question opens on Cancel, and Enter or Space /// (pressing the button with the focus) keeps the edits. #[test] @@ -436,6 +451,45 @@ fn a_search_flash_preserves_following_while_an_unrelated_drag_is_held() { ); } +/// #9001: the document thumb is visibly wide at rest and can be dragged from that width. +#[test] +fn document_scrollbar_is_wide_at_rest_and_draggable() { + fn painted_thumb(shape: &egui::Shape, bar: egui::Rect) -> Option { + match shape { + egui::Shape::Vec(children) => children.iter().find_map(|child| painted_thumb(child, bar)), + egui::Shape::Rect(paint) + if paint.fill.a() > 0 + && bar.expand(1.0).contains_rect(paint.rect) + && paint.rect.width() >= bar.width() - 1.0 + && paint.rect.height() > paint.rect.width() + && paint.rect.height() < bar.height() - 1.0 => + { + Some(paint.rect) + } + _ => None, + } + } + + let mut h = harness(); + h.state_mut().active = Some(0); + h.run_steps(5); + let bar = h.get_by_role_and_label(egui::accesskit::Role::ScrollBar, "Vertical scroll bar").rect(); + assert!(bar.width() >= 14.0, "the document target is comfortably wide: {bar:?}"); + let thumb = h.output().shapes.iter().find_map(|shape| painted_thumb(&shape.shape, bar)).expect("a full-width thumb is painted before hovering"); + let start = egui::pos2(thumb.left() + 2.0, thumb.center().y); + let before = h.state().views[0].page_screen_rect(0).expect("first page visible").top(); + h.hover_at(start); + h.run_steps(2); + h.drag_at(start); + h.run_steps(2); + h.hover_at(start + egui::vec2(0.0, bar.height() * 0.3)); + h.run_steps(3); + h.drop_at(start + egui::vec2(0.0, bar.height() * 0.3)); + h.run_steps(3); + let after = h.state().views[0].page_screen_rect(0).map(|r| r.top()); + assert!(after.is_none_or(|top| top < before - 10.0), "dragging the visible thumb moves the document: {before} -> {after:?}"); +} + /// The document scroll bar is its own scroll surface: a track click moves the offset with no /// pointer motion, and dragging from that press keeps moving it. Both are the reader scrolling, /// so automatic following ends. A global "any drag is scrolling" check would miss the click. @@ -444,11 +498,9 @@ fn scroll_bar_track_click_and_drag_end_automatic_search_following() { let mut h = harness(); let view = find_one_match_per_page(&mut h); h.run_steps(4); - let vp = h.state().views[view].viewport_rect(); - // Floating bars sit in the outer few points of the document area (see theme). Aim 75% down - // the vertical track: below the handle at this scroll position, and clear of the corner - // where the horizontal bar's track overlaps. - let track = egui::pos2(vp.right() - 4.0, vp.top() + vp.height() * 0.75); + // Aim below the handle, clear of the horizontal bar and independent of the bar width. + let bar = h.get_by_role_and_label(egui::accesskit::Role::ScrollBar, "Vertical scroll bar").rect(); + let track = egui::pos2(bar.center().x, bar.top() + bar.height() * 0.75); let before = h.state().views[view].page_screen_rect(0).expect("page 1 is on screen").top(); h.event(egui::Event::PointerMoved(track)); h.run_steps(2); @@ -462,7 +514,7 @@ fn scroll_bar_track_click_and_drag_end_automatic_search_following() { } // Keep dragging from the press: the scroll bar follows the pointer, still reader scrolling. - let dragged = egui::pos2(vp.right() - 4.0, vp.top() + vp.height() * 0.4); + let dragged = egui::pos2(bar.center().x, bar.top() + bar.height() * 0.4); h.event(egui::Event::PointerMoved(dragged)); h.run_steps(2); assert!(late_match_leaves_current(&mut h, view), "the track drag is the reader scrolling"); @@ -1606,6 +1658,65 @@ fn optimizer_audits_space_usage() { assert_eq!(h.state().dialogs.open_dialogs().len(), 1, "back to the optimizer"); } +#[test] +fn audit_space_usage_opens_the_space_audit_on_its_own() { + // #8993: All tools ▸ Compress a PDF ▸ Audit space usage was still Planned and did nothing. + let mut h = harness(); + assert!(h.execute("optimize.audit")); + h.run_steps(3); + h.get_by_role_and_label(egui::accesskit::Role::Dialog, "Space Audit"); + assert_eq!(h.state().dialogs.open_dialogs().len(), 1, "the audit opens without the optimizer"); + assert!( + crate::support::step_until(&mut h, |h| h.query_by_role_and_label(egui::accesskit::Role::ListItem, "Content Streams").is_some()), + "the measure finished" + ); + h.get_by_role_and_label(egui::accesskit::Role::ListItem, "Total"); + h.get_by_role_and_label(egui::accesskit::Role::Dialog, "Space Audit").get_by_label("OK").click(); + h.run_steps(2); + assert!(h.state().dialogs.open_dialogs().is_empty(), "OK closes it"); +} + +#[test] +fn the_space_audit_measures_again_when_an_edit_lands_before_the_first_measure_finishes() { + // #9004 review: the first measure's result is stale after an edit and is dropped; the dialog must not stay on "Measuring…". + let mut h = harness(); + assert!(h.execute("optimize.audit")); + { + let s = h.state_mut(); + let id = s.views[s.active.unwrap()].id; + s.session.apply(id, pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap(); + } + assert!( + crate::support::step_until(&mut h, |h| h.query_by_role_and_label(egui::accesskit::Role::ListItem, "Content Streams").is_some()), + "the audit of the edited document arrives" + ); + assert!(h.query_by_label("Measuring…").is_none()); +} + +#[test] +fn the_space_audit_never_shows_another_documents_figures() { + let rows = |h: &Harness<'static, PdfCraftApp>| h.state().space_audit.read().map(|r| r.clone()).unwrap_or_default(); + let mut h = harness(); + assert!(h.execute("optimize.audit")); + assert!(crate::support::step_until(&mut h, |h| !rows(h).is_empty()), "the first document's audit"); + let first = rows(&h); + h.get_by_role_and_label(egui::accesskit::Role::Dialog, "Space Audit").get_by_label("OK").click(); + h.run_steps(2); + // The other document, which has fewer pages. + let other = 1 - h.state().active.unwrap(); + h.state_mut().active = Some(other); + h.run_steps(2); + assert!(h.execute("optimize.audit")); + assert!(rows(&h).is_empty(), "the first document's figures are gone as soon as the other's measure starts"); + h.run_steps(1); + if rows(&h).is_empty() { + h.get_by_label("Measuring…"); + } + assert!(crate::support::step_until(&mut h, |h| !rows(h).is_empty()), "the other document's audit"); + assert_ne!(rows(&h), first, "the audit is the active document's"); + assert!(h.query_by_label("Measuring…").is_none()); +} + #[test] fn each_document_keeps_its_own_scroll_position() { // #189: every document's page view shared one scroll position, so switching tabs showed a @@ -2302,8 +2413,14 @@ fn the_scroll_speed_preference_scales_mouse_wheel_notches() { let (slow, fast) = (scrolled(ScrollSpeed::Slow, line, 1.0), scrolled(ScrollSpeed::Fast, line, 1.0)); assert!((slow * 2.0 - normal).abs() < 1.0 && (fast - normal * 2.0).abs() < 1.0, "slow {slow}, normal {normal}, fast {fast}"); let point = egui::MouseWheelUnit::Point; - let (normal_points, fast_points) = (scrolled(ScrollSpeed::Normal, point, 30.0), scrolled(ScrollSpeed::Fast, point, 30.0)); - assert!(normal_points > 0.0 && (normal_points - fast_points).abs() < 1.0, "trackpad: {normal_points} vs {fast_points}"); + let (slow_points, fast_points) = (scrolled(ScrollSpeed::Slow, point, 30.0), scrolled(ScrollSpeed::Fast, point, 30.0)); + assert!(slow_points > 0.0, "trackpad: {slow_points}"); + // Linux touchpads (Wayland's raw finger distance) follow the choice (#1904); elsewhere the system's deltas stand. + if cfg!(target_os = "linux") { + assert!(fast_points > slow_points * 2.0, "trackpad: slow {slow_points}, fast {fast_points}"); + } else { + assert!((slow_points - fast_points).abs() < 1.0, "trackpad: slow {slow_points}, fast {fast_points}"); + } let mut app = crate::control::new_app(); app.set_option(&egui::Context::default(), "scroll_speed", "fast").unwrap(); assert!(app.set_option(&egui::Context::default(), "scroll_speed", "warp").unwrap_err().contains("slow, normal, or fast")); @@ -2693,7 +2810,9 @@ fn selection_point_scroll_is_not_applied_twice() { let held = selection_wheel_delta(egui::MouseWheelUnit::Point, 30.0, true, animated); eprintln!("Point animated={animated}: released={normal}, held={held}"); assert!(normal > 1.0, "point wheel must scroll: {normal}"); - assert!((held - 30.0).abs() < 1.0, "animated={animated}: held precision motion={held}, normal={normal}"); + // The touchpad gain (Linux, #1904) scales the delta once, in the runtime; the held drag must not scale it again. + let expected = 30.0 * pdfcraft_ui_egui::scroll_speed::ScrollSpeed::default().touchpad_gain(); + assert!((held - expected).abs() < 1.0, "animated={animated}: held precision motion={held}, expected={expected}, normal={normal}"); } } @@ -2896,3 +3015,52 @@ fn the_accessible_window_has_the_window_title_as_its_name() { assert_eq!(name(&h).as_deref(), Some("Quarterly report • — PdfCraft")); assert_eq!(name(&h), Some(h.state().window_title.clone())); } + +/// View ▸ Show/Hide ▸ Rulers (`view.rulers`, `Ctrl+R` / `⌘R`): toggles the top and left rulers, +/// reports the state through the control channel, reserves `RULER_THICKNESS` so pages are not +/// covered, and restores the full page area when turned off. +#[test] +fn rulers_toggle_reserves_space_and_reports_state() { + use pdfcraft_ui_egui::canvas::rulers::RULER_THICKNESS; + let (tx, rx) = std::sync::mpsc::channel(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { + crate::support::install_runtime(&cc.egui_ctx); + let mut app = crate::control::new_app(); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + app.attach_control(craft::automation::ControlChannel::new(rx), None); + app.open_bytes(&egui::Context::default(), "a.pdf", None, fixture(2)).unwrap(); + app + }); + h.run_steps(4); + + let initial = crate::control::ok(&mut h, &tx, "ui.state", json!({})); + assert_eq!(initial["rulers"], false); + assert_eq!(initial["active"]["rulers"], false); + let before = h.state().views[0].viewport_rect(); + + // Toggle rulers on: state reports it and page viewport shrinks by RULER_THICKNESS on top and left. + assert!(h.execute("view.rulers")); + h.run_steps(3); + let shown = crate::control::ok(&mut h, &tx, "ui.state", json!({})); + assert_eq!(shown["rulers"], true); + assert_eq!(shown["active"]["rulers"], true); + let after = h.state().views[0].viewport_rect(); + assert!((after.min.x - before.min.x - RULER_THICKNESS).abs() < 0.5, "left edge reserved: before={before:?} after={after:?}"); + assert!((after.min.y - before.min.y - RULER_THICKNESS).abs() < 0.5, "top edge reserved: before={before:?} after={after:?}"); + assert!((before.width() - after.width() - RULER_THICKNESS).abs() < 0.5, "width shrunk by ruler thickness"); + assert!((before.height() - after.height() - RULER_THICKNESS).abs() < 0.5, "height shrunk by ruler thickness"); + + // Control option rejects invalid values with an error naming the allowed ones. + let err = h.set_option("rulers", "maybe").unwrap_err(); + assert!(err.contains("on") && err.contains("off"), "unexpected error: {err}"); + + // Toggle rulers off: state reports false and viewport returns to its full area. + assert!(h.execute("view.rulers")); + h.run_steps(3); + let hidden = crate::control::ok(&mut h, &tx, "ui.state", json!({})); + assert_eq!(hidden["rulers"], false); + assert_eq!(hidden["active"]["rulers"], false); + let restored = h.state().views[0].viewport_rect(); + assert!((restored.min.x - before.min.x).abs() < 0.5 && (restored.min.y - before.min.y).abs() < 0.5); + assert!((restored.width() - before.width()).abs() < 0.5 && (restored.height() - before.height()).abs() < 0.5); +} diff --git a/crates/ui-egui/tests/it/xfa.rs b/crates/ui-egui/tests/it/xfa.rs index 0f355627ca..94a2cf6ec3 100644 --- a/crates/ui-egui/tests/it/xfa.rs +++ b/crates/ui-egui/tests/it/xfa.rs @@ -321,8 +321,10 @@ fn an_enter_script_that_changes_its_field_shows_in_the_editor() { h.run_steps(4); assert_eq!(value(&h), "", "leaving it doesn't write \"Type here\" back"); click_field(&mut h, "hint"); - h.event(egui::Event::Text("Ann".into())); - h.run_steps(2); + for c in "Ann".chars() { + crate::support::input::native_input(&mut h, [egui::Event::Text(c.to_string())]); + } + assert_eq!(h.state().views[0].session.forms.focus.as_ref().map(|f| f.text.as_str()), Some("Ann"), "native typing reaches the active field"); h.key_press_modifiers(Modifiers::NONE, Key::Tab); h.run_steps(4); assert_eq!(value(&h), "Ann"); diff --git a/crates/xfa/Cargo.toml b/crates/xfa/Cargo.toml index 967040f8f4..7b073f617f 100644 --- a/crates/xfa/Cargo.toml +++ b/crates/xfa/Cargo.toml @@ -11,7 +11,7 @@ repository.workspace = true workspace = true [dependencies] -craft-xfa = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-xfa = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" } pdfcraft-cos = { workspace = true } pdfcraft-fonts = { workspace = true } craft-xml = { workspace = true } diff --git a/crates/xfa/src/break_tests.rs b/crates/xfa/src/break_tests.rs new file mode 100644 index 0000000000..b5f8e63a2f --- /dev/null +++ b/crates/xfa/src/break_tests.rs @@ -0,0 +1,353 @@ +//! `breakBefore` and `breakAfter`: per instance, to content areas and named content areas, and +//! `startNew` (XFA 3.3, "Break Conditions", pp. 269-270; "Break to Empty pageArea or +//! contentArea", pp. 361-362). + +use super::*; + +/// A letter page area `Body` with content areas `left`, `mid` and `right` side by side, each +/// 2in wide and 10in tall, and a second page area `Other`; `body` goes in the root subform and +/// `data` in the data root. +fn form(body: &str, data: &str) -> String { + format!( + r#" + +
{data}
+
"# + ) +} + +/// A field `name`, 1in by 0.3in. +fn field(name: &str) -> String { + format!(r#""#) +} + +/// For each page, the names of its widgets in order. +fn names(form: &Form) -> Vec> { + form.pages.iter().map(|p| p.items.iter().filter_map(|i| if let Item::Widget(w) = i { Some(w.name.clone()) } else { None }).collect()).collect() +} + +/// The left edge of widget `name` on page `page`. +fn left_of(form: &Form, page: usize, name: &str) -> Option { + form.pages.get(page)?.items.iter().find_map(|i| match i { + Item::Widget(w) if w.name == name => Some(w.rect.x), + _ => None, + }) +} + +/// Every instance of a repeating subform breaks on its own: one record a page, whether the record +/// flows (`tb`) or is positioned with a fixed size. +#[test] +fn every_instance_of_a_repeating_subform_breaks() { + let data = "abc"; + for (layout, size) in [(r#"layout="tb""#, ""), ("", r#"w="2in" h="1in""#)] { + let body = format!( + r#"{}"#, + field("customer") + ); + let form = layout_xml(&form(&body, data)).unwrap(); + let pages = names(&form); + assert_eq!(pages.len(), 3, "{layout}{size}: one page a record: {pages:?}"); + assert!(pages.iter().all(|p| p.len() == 1), "{layout}{size}: {pages:?}"); + } + // breakAfter likewise: the record after each one starts a page. + let body = + format!(r#"{}"#, field("customer")); + let form = layout_xml(&form(&body, data)).unwrap(); + let with_records: Vec<_> = names(&form).into_iter().filter(|p| !p.is_empty()).collect(); + assert_eq!(with_records.len(), 3, "{with_records:?}"); +} + +/// A `contentArea` break moves to the next content area (the next column), not a new page. +#[test] +fn a_content_area_break_moves_to_the_next_column() { + let body = format!( + r#"{}{}{}"#, + field("fa"), + field("fb"), + field("fc") + ); + let form = layout_xml(&form(&body, "")).unwrap(); + assert_eq!(form.pages.len(), 1, "{:?}", names(&form)); + let [a, b, c] = ["fa", "fb", "fc"].map(|n| left_of(&form, 0, n).unwrap_or_else(|| panic!("{n} is on the page: {:?}", names(&form)))); + assert!(a < b && b < c, "each break starts the next column: {a} {b} {c}"); +} + +/// A `contentArea` break with a target goes to that content area, by name or `#id`: later on the +/// page when it is there, else on a new page. +#[test] +fn a_content_area_break_goes_to_the_named_content_area() { + let body = format!( + r##"{}{}{}"##, + field("fa"), + field("fb"), + field("fc") + ); + let form = layout_xml(&form(&body, "")).unwrap(); + assert_eq!(names(&form), vec![vec!["fa".to_string(), "fb".to_string()], vec!["fc".to_string()]]); + let right = left_of(&form, 0, "fb").unwrap_or(0.0); + let mid = left_of(&form, 1, "fc").unwrap_or(0.0); + assert!(right > 5.5 * 72.0 - 0.01, "fb is in the right column, skipping mid: {right}"); + assert!(mid > 3.0 * 72.0 - 0.01 && mid < 5.5 * 72.0, "mid is before right, so fc starts a page and goes to its mid column: {mid}"); +} + +/// Without `startNew`, a break to the page area the flow is already on keeps that page; with it, +/// the break starts a new one. +#[test] +fn a_break_to_the_current_page_area_needs_start_new_to_move() { + let body = |start_new: &str| { + format!( + r#"{}{}"#, + field("fa"), + field("fb") + ) + }; + let stay = layout_xml(&form(&body(""), "")).unwrap(); + assert_eq!(stay.pages.len(), 1, "already on Body: {:?}", names(&stay)); + let moved = layout_xml(&form(&body(r#"startNew="1""#), "")).unwrap(); + assert_eq!(moved.pages.len(), 2, "startNew asks for a new Body page: {:?}", names(&moved)); +} + +/// `startNew="1"` starts a new page even when the current one is still empty: a `breakAfter` then +/// a `startNew` break leave a blank page between (p. 362). +#[test] +fn start_new_moves_on_from_an_empty_page() { + let body = |start_new: &str| { + format!( + r#"{}{}"#, + field("fa"), + field("fb") + ) + }; + let plain = layout_xml(&form(&body(""), "")).unwrap(); + let fresh = layout_xml(&form(&body(r#"startNew="1""#), "")).unwrap(); + assert!(fresh.pages.len() > plain.pages.len(), "{:?} against {:?}", names(&fresh), names(&plain)); + assert!(names(&fresh).iter().any(Vec::is_empty), "a blank page before fb: {:?}", names(&fresh)); +} + +/// The legacy `` moves on after its subform, as `breakAfter` does: to the next +/// column for `contentArea`, to a new page for `pageArea`. +#[test] +fn a_legacy_break_after_moves_on_after_its_subform() { + let body = |to: &str| { + format!( + r#"{}{}"#, + field("fa"), + field("fb") + ) + }; + let columns = layout_xml(&form(&body("contentArea"), "")).unwrap(); + assert_eq!(columns.pages.len(), 1, "{:?}", names(&columns)); + let [a, b] = ["fa", "fb"].map(|n| left_of(&columns, 0, n).unwrap_or_else(|| panic!("{n} is on the page: {:?}", names(&columns)))); + assert!(a < b, "fb starts the next column: {a} {b}"); + let pages = layout_xml(&form(&body("pageArea"), "")).unwrap(); + assert_eq!(names(&pages), vec![vec!["fa".to_string()], vec!["fb".to_string()]]); +} + +/// A form whose page areas are `Body` (one content area, at most `body_max` pages when given) and +/// `Other`, with content areas `o1` and `o2` side by side, each 3in wide from 1in down. +fn two_masters(body: &str, body_max: &str) -> String { + format!( + r#" + +"# + ) +} + +/// The top edge of widget `name` on page `page`. +fn top_of(form: &Form, page: usize, name: &str) -> Option { + form.pages.get(page)?.items.iter().find_map(|i| match i { + Item::Widget(w) if w.name == name => Some(w.rect.y), + _ => None, + }) +} + +/// `startNew="1"` on a break to a named content area of another page area keeps the empty page +/// a `breakAfter` left, as a page-area break does, and starts one more; without it the empty +/// page is the new one. +#[test] +fn start_new_to_a_named_content_area_keeps_an_empty_page() { + let body = |start_new: &str| { + two_masters( + &format!( + r#"{}{}"#, + field("fa"), + field("fb") + ), + "", + ) + }; + let plain = layout_xml(&body("")).unwrap(); + assert_eq!(names(&plain), vec![vec!["fa".to_string()], vec!["fb".to_string()]]); + let fresh = layout_xml(&body(r#"startNew="1""#)).unwrap(); + assert_eq!(names(&fresh), vec![vec!["fa".to_string()], vec![], vec!["fb".to_string()]]); +} + +/// The first subform breaking to the second content area of another page area replaces the empty +/// first page, and the bordered subform round it opens there: its top margin is kept, and its +/// border is drawn on that page. +#[test] +fn a_first_break_to_another_page_areas_later_content_area_reopens_the_frames_there() { + let xml = two_masters( + &format!( + r#"{}"#, + field("fb") + ), + "", + ); + let form = layout_xml(&xml).unwrap(); + assert_eq!(names(&form), vec![vec!["fb".to_string()]]); + let x = left_of(&form, 0, "fb").unwrap_or_else(|| panic!("fb is on the page")); + assert!((x - 4.5 * 72.0).abs() < 0.01, "fb is in o2: {x}"); + let y = top_of(&form, 0, "fb").unwrap_or_else(|| panic!("fb is on the page")); + assert!((y - 1.5 * 72.0).abs() < 0.01, "fb sits below the top margin of w: {y}"); + let filled = form.pages.first().is_some_and(|p| p.items.iter().any(|i| matches!(i, Item::Fill { .. }))); + assert!(filled, "w's border is drawn: {:?}", form.warnings); +} + +/// A named content-area target is an explicit choice: the pages its subform overflows onto are of +/// that page area, not of the page area an enclosing subform's `overflow` names. +#[test] +fn a_named_content_area_break_is_kept_for_overflow_pages() { + let fields: String = (0..120).map(|i| field(&format!("f{i}"))).collect(); + let xml = two_masters( + &format!( + r#"{fields}"# + ), + "", + ); + let form = layout_xml(&xml).unwrap(); + let areas: Vec<_> = form.pages.iter().map(|p| p.area.clone().unwrap_or_default()).collect(); + assert!(areas.len() > 1, "the fields overflow: {areas:?}"); + assert!(areas.iter().all(|a| a == "Other"), "{areas:?}"); +} + +/// A break that needs a new page of a page area whose `occur max` is used up does not make one: +/// it moves to the next page instead, and says so. +#[test] +fn a_content_area_break_does_not_exceed_its_page_areas_max() { + let xml = two_masters( + &format!( + r#"{}{}"#, + field("fa"), + field("fb") + ), + r#""#, + ); + let form = layout_xml(&xml).unwrap(); + let areas: Vec<_> = form.pages.iter().map(|p| p.area.clone().unwrap_or_default()).collect(); + assert_eq!(areas, ["Body", "Other"], "{:?}", names(&form)); + assert!(form.warnings.iter().any(|w| w.contains("no page left")), "{:?}", form.warnings); +} + +/// A first subform whose `startNew` break names the content area the flow begins in gets a new +/// instance of it, so the first `Body` page stays blank (p. 362). +#[test] +fn a_first_start_new_break_to_the_current_content_area_leaves_it_blank() { + let xml = two_masters( + &format!(r#"{}"#, field("fb")), + "", + ); + let first = layout_xml(&xml).unwrap(); + let areas: Vec<_> = first.pages.iter().map(|p| p.area.clone().unwrap_or_default()).collect(); + assert_eq!(names(&first), [vec![], vec!["fb".to_string()]], "{areas:?}"); + assert_eq!(areas, ["Body", "Body"]); +} + +/// A first subform whose `startNew` break names the page area the flow begins in gets a new +/// instance of it, so the first `Body` page stays blank (p. 362); without `startNew` it stays. +#[test] +fn a_first_start_new_break_to_the_current_page_area_leaves_it_blank() { + for (start_new, want) in [(r#" startNew="1""#, vec![vec![], vec!["fb".to_string()]]), ("", vec![vec!["fb".to_string()]])] { + let sub = format!(r#"{}"#, field("fb")); + let laid = layout_xml(&two_masters(&sub, "")).unwrap(); + let areas: Vec<_> = laid.pages.iter().map(|p| p.area.clone().unwrap_or_default()).collect(); + assert_eq!(names(&laid), want, "{start_new:?} {areas:?}"); + assert!(areas.iter().all(|a| a == "Body"), "{areas:?}"); + } +} + +/// A first subform whose `startNew` break names a content area of another page area gets a new +/// page for it, leaving the first `Body` page blank (p. 362); without `startNew` page 1 switches. +#[test] +fn a_first_start_new_break_to_another_page_areas_content_area_leaves_page_one_blank() { + let cases = + [(r#" startNew="1""#, vec![vec![], vec!["fb".to_string()]], vec!["Body", "Other"]), ("", vec![vec!["fb".to_string()]], vec!["Other"])]; + for (start_new, want, want_areas) in cases { + let sub = format!(r#"{}"#, field("fb")); + let laid = layout_xml(&two_masters(&sub, "")).unwrap(); + let areas: Vec<_> = laid.pages.iter().map(|p| p.area.clone().unwrap_or_default()).collect(); + assert_eq!(names(&laid), want, "{start_new:?} {areas:?}"); + assert_eq!(areas, want_areas, "{start_new:?}"); + } +} + +/// A first subform whose `startNew` break to a content area names none moves to the next +/// content area, leaving the first column empty (p. 362); without `startNew` it stays. +#[test] +fn a_first_unnamed_start_new_content_area_break_moves_to_the_next_column() { + for (start_new, want) in [(r#" startNew="1""#, 3.0), ("", 0.5)] { + let sub = format!(r#"{}"#, field("fb")); + let laid = layout_xml(&form(&sub, "")).unwrap(); + let x = left_of(&laid, 0, "fb").unwrap_or_else(|| panic!("fb is on the first page: {:?}", names(&laid))); + assert!((x - want * 72.0).abs() < 0.01, "{start_new:?}: {x}"); + } +} + +/// The root subform always starts a new page and content area, so its own `startNew` adds no +/// blank one, to a page area or to the content area it begins in (p. 362). +#[test] +fn a_root_start_new_adds_no_page() { + let root = r#""#; + for brk in [r#"targetType="pageArea""#, r#"targetType="contentArea" target="left""#] { + let xml = form(&field("fa"), "").replace(root, &format!(r#"{root}"#)); + let laid = layout_xml(&xml).unwrap(); + assert_eq!(names(&laid), [vec!["fa".to_string()]], "{brk}"); + } +} + +/// `#right` names the content area whose `id` is `right`, not an earlier one named `right`. +#[test] +fn an_id_target_matches_only_an_id() { + let xml = format!( + r##" + +"##, + field("fb") + ); + let form = layout_xml(&xml).unwrap(); + let x = left_of(&form, 0, "fb").unwrap_or_else(|| panic!("fb is on the first page: {:?}", names(&form))); + assert!((x - 5.5 * 72.0).abs() < 0.01, "fb is in the area with id right: {x}"); +} + +/// A break's target and mode come from the same element: a first `breakBefore` to a page area +/// with no target, then one to the content area `#right`, is a page-area break with no target. +#[test] +fn a_break_target_is_read_from_the_element_its_mode_is() { + let body = format!( + r##"{}{}"##, + field("fa"), + field("fb") + ); + let form = layout_xml(&form(&body, "")).unwrap(); + assert_eq!(names(&form), vec![vec!["fa".to_string()], vec!["fb".to_string()]]); + let x = left_of(&form, 1, "fb").unwrap_or_else(|| panic!("fb is on the second page")); + assert!((x - 0.5 * 72.0).abs() < 0.01, "fb starts the new page's first column: {x}"); + assert!(form.warnings.is_empty(), "{:?}", form.warnings); +} diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index fb7d2228b8..f1506cbf65 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -987,6 +987,30 @@ pub fn shell(xdp: &str) -> Vec { assemble(objs) } +/// [`shell`] with bookmarks and named destinations that name the placeholder page: a +/// `/Outlines` item with a `/Dest`, one with a `GoTo` action, a `/Dests` entry, and a +/// `/Names` tree entry, all at the page. +pub fn dests_shell(xdp: &str) -> Vec { + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R /NeedsRendering true /AcroForm << /XFA 5 0 R /Fields [] >> /Outlines 6 0 R /Dests 7 0 R /Names 8 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 612 792] /Contents 4 0 R >>".to_vec(), + b"<< /Length 44 >>\nstream\nBT /F1 12 Tf 72 700 Td (Please wait...) Tj ET\nendstream".to_vec(), + format!("<< /Length {} >>\nstream\n{xdp}\nendstream", xdp.len()).into_bytes(), + b"<< /Type /Outlines /Count 2 /First 9 0 R /Last 10 0 R >>".to_vec(), + b"<< /top 11 0 R >>".to_vec(), + b"<< /Dests 12 0 R >>".to_vec(), + b"<< /Title (Top) /Parent 6 0 R /Next 10 0 R /Dest [3 0 R /Fit] >>".to_vec(), + b"<< /Title (Go) /Parent 6 0 R /Prev 9 0 R /A 13 0 R >>".to_vec(), + b"[3 0 R /Fit]".to_vec(), + b"<< /Names [(end) 14 0 R] >>".to_vec(), + b"<< /S /GoTo /D [3 0 R /Fit] >>".to_vec(), + b"[3 0 R /Fit]".to_vec(), + ]; + assemble(objs) +} + /// [`shell`] with usage rights: the catalog's `/Perms` holds a `/UR3` signature (a stand-in /// dictionary, nothing verifies it), beside `others` (`/DocMDP 6 0 R`, say: object 6 is a /// signature dictionary too). `indirect` puts `/Perms` in an object of its own. diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rs index 90abf8a41b..131a8bca27 100644 --- a/crates/xfa/src/layout.rs +++ b/crates/xfa/src/layout.rs @@ -21,6 +21,7 @@ use crate::model::{ }; use crate::text::{self, Block, Face, Span}; +mod breaks; mod common; mod draw; mod field; @@ -276,6 +277,7 @@ fn layout_inner(tpl: &Template, data: Option<&DataNode>, overrides: Option<&crat width: 612.0, height: 792.0, content: vec![Rect::new(36.0, 36.0, 540.0, 720.0)], + content_names: Vec::new(), items: Vec::new(), occur_max: None, occur_min: 0, diff --git a/crates/xfa/src/layout/breaks.rs b/crates/xfa/src/layout/breaks.rs new file mode 100644 index 0000000000..b0011b7b40 --- /dev/null +++ b/crates/xfa/src/layout/breaks.rs @@ -0,0 +1,121 @@ +//! A subform instance's `breakBefore` and `breakAfter` (XFA 3.3, "Break Conditions", pp. 269-270; +//! "Break to Empty pageArea or contentArea", pp. 361-362; "Break on Exit", p. 365). + +use super::pages::{Dest, TargetKeys}; +use super::{Layouter, Subform, XfaError}; +use crate::model::BreakMode; + +impl Layouter<'_> { + /// Move on as the `breakBefore` of an instance of `sf` says, before it is laid out. The root + /// subform (`root`) always starts a new page and content area, so its `startNew` has no + /// effect (p. 362). + pub(super) fn break_before(&mut self, sf: &Subform, root: bool) -> Result<(), XfaError> { + if !sf.break_before_page { + return Ok(()); + } + let mode = BreakMode { start_new: sf.break_before_mode.start_new && !root, ..sf.break_before_mode }; + self.apply_break(sf.break_before_target.as_deref(), mode, false) + } + + /// Move on as the `breakAfter` of an instance of `sf` says, once it is laid out. + pub(super) fn break_after(&mut self, sf: &Subform) -> Result<(), XfaError> { + if !sf.break_after_page { + return Ok(()); + } + self.apply_break(sf.break_after_target.as_deref(), sf.break_after_mode, true) + } + + /// One break. A page or content area the flow has placed nothing in yet is the new one + /// already, so the flow stays there, unless `startNew` asks for a fresh one, on the first page + /// too (p. 362). A target the flow is already in is kept unless `startNew` is set. `after`: a + /// `breakAfter`, which leaves what was just laid out behind whether or not it placed anything. + fn apply_break(&mut self, target: Option<&str>, mode: BreakMode, after: bool) -> Result<(), XfaError> { + if mode.content_area { + return self.break_to_content(target, mode.start_new, after); + } + let idx = target.and_then(|t| self.find_page_area(t)); + if let Some(t) = target + && idx.is_none() + && !self.on_page_area(t) + { + self.warn_once(format!("a break names {t}, which names no page area left to use; it moves to the next page")); + } + if let Some(idx) = idx { + self.select_break_area(idx); + } + let on_target = target.is_some_and(|t| self.on_page_area(t)); + if on_target && !mode.start_new { + return Ok(()); + } + if after || mode.start_new || self.page_has_flow() { + return self.break_frames_to(0.0, true, idx); + } + if let Some(idx) = idx + && self.cur.as_ref().is_some_and(|c| c.area != idx) + { + self.switch_empty_page(idx, 0)?; + } + Ok(()) + } + + /// A `targetType="contentArea"` break: to the content area `target` names, or the next one. + /// A named target counts as an explicit page-area choice for later pages. When reaching it + /// needs a new page and its page area has none left, another page area with a content area + /// of that name takes it, or else the flow moves to the next page, as for a page-area target. + fn break_to_content(&mut self, target: Option<&str>, start_new: bool, after: bool) -> Result<(), XfaError> { + let keys = target.and_then(TargetKeys::of); + let named = keys.and_then(|k| self.find_content_area(k)); + if let Some(t) = target + && named.is_none() + { + self.warn_once(format!("a break names {t}, which is no content area; it moves to the next one")); + } + let (Some(keys), Some((idx, i))) = (keys, named) else { + let placed = self.cur.as_ref().is_some_and(|c| c.placed); + if after || placed || start_new { + return self.break_frames(0.0, false); + } + return Ok(()); + }; + let here = self.cur.as_ref().map(|c| (c.area, c.content)); + if here == Some((idx, i)) && !start_new { + self.select_break_area(idx); + return Ok(()); + } + let later_here = here.is_some_and(|(area, content)| area == idx && i > content); + let usable = if later_here || self.area_left(idx) { Some((idx, i)) } else { self.content_area_left(keys) }; + let Some((idx, i)) = usable else { + let t = target.unwrap_or_default(); + self.warn_once(format!("a break names {t}, whose page area has no page left; it moves to the next page")); + return self.break_frames(0.0, true); + }; + self.select_break_area(idx); + if !after && !start_new && !self.page_has_flow() && here.is_some_and(|(area, _)| area != idx) { + return self.switch_empty_page(idx, i); + } + self.break_frames_into(0.0, Dest::Content(idx, i)) + } + + /// The page area and content area `keys` names: on the current page if it has one, else on + /// the first page area that may start another page. + fn find_content_area(&self, keys: TargetKeys<'_>) -> Option<(usize, usize)> { + let current = self.cur.as_ref().map(|c| c.area); + current.and_then(|idx| self.content_in(idx, keys)).or_else(|| self.content_area_left(keys)) + } + + /// The first page area that may start another page and has a content area `keys` names. + fn content_area_left(&self, keys: TargetKeys<'_>) -> Option<(usize, usize)> { + (0..self.areas.len()).filter(|&i| self.area_left(i)).find_map(|idx| self.content_in(idx, keys)) + } + + /// The content area of page area `idx` that `keys` names. + fn content_in(&self, idx: usize, keys: TargetKeys<'_>) -> Option<(usize, usize)> { + self.areas.get(idx)?.content_names.iter().position(|(name, id)| keys.names(name.as_deref(), id.as_deref())).map(|i| (idx, i)) + } + + /// Whether the current page is of the page area `target` names. + fn on_page_area(&self, target: &str) -> bool { + let Some(keys) = TargetKeys::of(target) else { return false }; + self.cur.as_ref().and_then(|c| self.areas.get(c.area)).is_some_and(|a| keys.names(a.name.as_deref(), a.id.as_deref())) + } +} diff --git a/crates/xfa/src/layout/flow.rs b/crates/xfa/src/layout/flow.rs index f2c26c955a..e7c0b8de25 100644 --- a/crates/xfa/src/layout/flow.rs +++ b/crates/xfa/src/layout/flow.rs @@ -298,7 +298,7 @@ impl Layouter<'_> { } } - fn page_has_flow(&self) -> bool { + pub(super) fn page_has_flow(&self) -> bool { self.cur.as_ref().is_some_and(|c| c.placed || c.content > 0) } @@ -324,28 +324,6 @@ impl Layouter<'_> { let Node::Subform(sf) = node else { return Ok(()) }; self.check_measures()?; let prev_rect = self.cursor().0; - let before_target = sf.break_before_target.as_deref().and_then(|t| self.find_page_area(t)); - if let Some(idx) = before_target { - self.select_break_area(idx); - } - if sf.break_before_page { - if self.page_has_flow() { - self.break_frames_to(0.0, true, before_target)?; - } else if let Some(idx) = before_target - && self.cur.as_ref().is_some_and(|c| c.area != idx) - { - self.switch_empty_page(idx)?; - } - } - // Overflow steers pages created while this subform (and its descendants) are open. - // Putting the previous selection back afterwards keeps a later sibling's untargeted - // break off this master. A descendant's explicit break bumps `preferred_epoch` and stays. - let overflow_area = sf.overflow_target.as_deref().and_then(|t| self.find_page_area(t)); - let preferred_before_overflow = self.preferred_area; - let epoch_at_overflow = self.preferred_epoch; - if let Some(idx) = overflow_area { - self.preferred_area = Some(idx); - } // Data adds instances of a repeating subform (rows added in another viewer). let instances = self.laid_out_instances(node, &ctx.som); let ctx_parent = ctx; @@ -353,83 +331,103 @@ impl Layouter<'_> { // Every instance spends budget, so nested repeats that place nothing still stop. self.measures.set(self.measures.get().saturating_add(1)); self.check_measures()?; - let ctx = ctx_parent.with_som(&sf.common, sib + i); - let (rect, _, _) = self.cursor(); - // When a break moved to a content area of a different width (such as switching from a - // portrait master to a landscape master), a width from the old content area no longer - // bounds this subform. - let (x, w) = match avail { - Some(av) if rect == prev_rect => av, - _ => self.frames.last().map_or((rect.x, rect.w), Frame::inner_width), - }; - let w = clamp_opt(sf.common.w.unwrap_or(w), sf.common.min_w, sf.common.max_w).min(w.max(1.0)); - if !matches!(sf.layout, Layout::Tb | Layout::Table) || sf.common.h.is_some() { - // Not splittable: one block. - let (_, h) = self.size_at(node, w, ctx_parent, depth, sib + i); - self.flow_block(node, x, (w, h), ctx_parent, depth, sib + i)?; - continue; + // Each instance breaks on its own. + self.break_before(sf, depth == 0)?; + // Overflow steers pages created while this instance (and its descendants) is open. + // Putting the previous selection back afterwards keeps a later sibling's untargeted + // break off this master. A descendant's explicit break bumps `preferred_epoch` and + // stays. + let overflow_area = sf.overflow_target.as_deref().and_then(|t| self.find_page_area(t)); + let preferred_before_overflow = self.preferred_area; + let epoch_at_overflow = self.preferred_epoch; + if let Some(idx) = overflow_area { + self.preferred_area = Some(idx); } - let m = sf.common.margin; - // Its border and fill go round what it takes from here, a part on each content area. - let framed = match self.flow_mark() { - Some(part) => { - self.frames.push(Frame { - x, - w, - margin: m, - border: sf.common.border.clone(), - width_limits: sf.common.w.is_none().then_some((sf.common.min_w, sf.common.max_w)), - part, - parts: Vec::new(), - lost: false, - held: false, - }); - true - } - None => false, - }; - self.advance(m.top); - let mut cur_rect = rect; - let mut inner_x = x + m.left; - let mut inner_w = (w - m.horizontal()).max(1.0); - match sf.layout { - Layout::Table => self.flow_table(sf, inner_x, inner_w, &ctx, depth)?, - _ => { - let sibs = SomIndices::of(&sf.children); - for (ci, child) in sf.children.iter().enumerate() { - if !child.common().presence.occupies() { - continue; - } - let (r, _, _) = self.cursor(); - if r != cur_rect && sf.common.w.is_none() { - cur_rect = r; - if framed && let Some(f) = self.frames.last() { - (inner_x, inner_w) = f.inner_width(); - } - } - let csib = sibs.at(ci); - if flows_as_subform(child) { - self.flow_subform(child, Some((inner_x, inner_w)), &ctx, depth + 1, csib)?; - continue; - } - self.flow_instances(child, inner_x, inner_w, &ctx, depth + 1, csib)?; + self.flow_instance(node, sf, (avail, prev_rect), ctx_parent, depth, sib + i)?; + if overflow_area.is_some() && self.preferred_epoch == epoch_at_overflow { + self.preferred_area = preferred_before_overflow; + } + self.break_after(sf)?; + } + Ok(()) + } + + /// One instance of flowed subform `sf` (`node`), at SOM sibling index `sib`. `avail`: the + /// room the parent gave, which holds while the flow is still in `prev_rect`. + fn flow_instance( + &mut self, + node: &Node, + sf: &Subform, + (avail, prev_rect): (Option<(f64, f64)>, Rect), + ctx_parent: &Ctx, + depth: usize, + sib: usize, + ) -> Result<(), XfaError> { + let ctx = ctx_parent.with_som(&sf.common, sib); + let (rect, _, _) = self.cursor(); + // When a break moved to a content area of a different width (such as switching from a + // portrait master to a landscape master), a width from the old content area no longer + // bounds this subform. + let (x, w) = match avail { + Some(av) if rect == prev_rect => av, + _ => self.frames.last().map_or((rect.x, rect.w), Frame::inner_width), + }; + let w = clamp_opt(sf.common.w.unwrap_or(w), sf.common.min_w, sf.common.max_w).min(w.max(1.0)); + if !matches!(sf.layout, Layout::Tb | Layout::Table) || sf.common.h.is_some() { + // Not splittable: one block. + let (_, h) = self.size_at(node, w, ctx_parent, depth, sib); + return self.flow_block(node, x, (w, h), ctx_parent, depth, sib); + } + let m = sf.common.margin; + // Its border and fill go round what it takes from here, a part on each content area. + let framed = match self.flow_mark() { + Some(part) => { + self.frames.push(Frame { + x, + w, + margin: m, + border: sf.common.border.clone(), + width_limits: sf.common.w.is_none().then_some((sf.common.min_w, sf.common.max_w)), + part, + parts: Vec::new(), + lost: false, + held: false, + }); + true + } + None => false, + }; + self.advance(m.top); + let mut cur_rect = rect; + let mut inner_x = x + m.left; + let mut inner_w = (w - m.horizontal()).max(1.0); + match sf.layout { + Layout::Table => self.flow_table(sf, inner_x, inner_w, &ctx, depth)?, + _ => { + let sibs = SomIndices::of(&sf.children); + for (ci, child) in sf.children.iter().enumerate() { + if !child.common().presence.occupies() { + continue; } + let (r, _, _) = self.cursor(); + if r != cur_rect && sf.common.w.is_none() { + cur_rect = r; + if framed && let Some(f) = self.frames.last() { + (inner_x, inner_w) = f.inner_width(); + } + } + let csib = sibs.at(ci); + if flows_as_subform(child) { + self.flow_subform(child, Some((inner_x, inner_w)), &ctx, depth + 1, csib)?; + continue; + } + self.flow_instances(child, inner_x, inner_w, &ctx, depth + 1, csib)?; } } - self.advance(m.bottom); - if framed && let Some(frame) = self.frames.pop() { - self.finish_frame(frame)?; - } } - if overflow_area.is_some() && self.preferred_epoch == epoch_at_overflow { - self.preferred_area = preferred_before_overflow; - } - if sf.break_after_page { - let after_target = sf.break_after_target.as_deref().and_then(|t| self.find_page_area(t)); - if let Some(idx) = after_target { - self.select_break_area(idx); - } - self.break_frames_to(0.0, true, after_target)?; + self.advance(m.bottom); + if framed && let Some(frame) = self.frames.pop() { + self.finish_frame(frame)?; } Ok(()) } diff --git a/crates/xfa/src/layout/pages.rs b/crates/xfa/src/layout/pages.rs index 8ea518fb39..9a6925e3f8 100644 --- a/crates/xfa/src/layout/pages.rs +++ b/crates/xfa/src/layout/pages.rs @@ -3,9 +3,48 @@ use super::EMBED_COPIED; use super::items::{Item, Page, UNDERLINE_DROP}; use super::{ Block, Border, Common, Ctx, Cursor, FlowMark, Font, Frame, Layouter, MAX_DRAW_CHARS, MAX_ITEMS, MAX_MEASURES, MAX_PAGES, Node, PAGE_COUNT_MARK, - PageArea, PageRole, Para, Rc, Rect, SomIndices, Views, XfaError, data_path, text, + PageRole, Para, Rc, Rect, SomIndices, Views, XfaError, data_path, text, }; +/// What a break `target` names: an `#id`, or a name or a SOM path whose last segment is one. +#[derive(Clone, Copy)] +pub(super) struct TargetKeys<'a> { + raw: &'a str, + leaf: &'a str, + /// The last part is an `#id` (`#PA1`, `pageSet.#PA1`): only an `id` matches. In + /// `#pageSet.Page3[0]` the `#` starts a SOM path and the last part is a name. + by_id: bool, +} + +impl<'a> TargetKeys<'a> { + pub(super) fn of(target: &'a str) -> Option { + let raw = target.trim().trim_start_matches('#'); + let last = target.trim().rsplit('.').next().unwrap_or(raw).trim(); + let by_id = last.starts_with('#'); + let leaf = last.split('[').next().unwrap_or(last).trim().trim_start_matches('#'); + (!leaf.is_empty()).then_some(TargetKeys { raw, leaf, by_id }) + } + + /// Whether an object with this `name` and `id` is the one named. A plain name also matches + /// an `id`, as a name-only lookup would miss an object that has only an id. + pub(super) fn names(&self, name: Option<&str>, id: Option<&str>) -> bool { + [self.leaf, self.raw].iter().any(|k| id == Some(k) || (!self.by_id && name == Some(k))) + } +} + +/// Where a break moves the flow. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Dest { + /// The next content area, or a new page after the last. + Next, + /// A new page, of the page area untargeted pages use. + Page, + /// A new page of page area `0`. + PageOf(usize), + /// Content area `1` of page area `0`: later on this page when it is one, else a new page. + Content(usize, usize), +} + impl Layouter<'_> { pub(super) fn warn_once(&mut self, msg: impl Into) { let m = msg.into(); @@ -117,20 +156,18 @@ impl Layouter<'_> { /// Find the `pageArea` index matching a `target` attribute (by `name` or `#id`, or the final /// SOM segment), preferring an area whose `occur_max` is not yet exhausted. pub(super) fn find_page_area(&self, target: &str) -> Option { - let raw = target.trim().trim_start_matches('#'); - let leaf = raw.rsplit('.').next().unwrap_or(raw).split('[').next().unwrap_or(raw).trim().trim_start_matches('#'); - if leaf.is_empty() { - return None; - } - let matches = |a: &PageArea| { - a.name.as_deref() == Some(leaf) || a.id.as_deref() == Some(leaf) || a.name.as_deref() == Some(raw) || a.id.as_deref() == Some(raw) - }; + let keys = TargetKeys::of(target)?; (0..self.areas.len()).find(|&i| { let Some(area) = self.areas.get(i) else { return false }; - matches(area) && area.occur_max.is_none_or(|m| self.uses.get(i).is_some_and(|u| *u < m)) + keys.names(area.name.as_deref(), area.id.as_deref()) && self.area_left(i) }) } + /// Whether page area `idx` may start another page (its `occur max` is not used up). + pub(super) fn area_left(&self, idx: usize) -> bool { + self.areas.get(idx).is_some_and(|a| a.occur_max.is_none_or(|m| self.uses.get(idx).is_some_and(|u| *u < m))) + } + /// Remember an explicit break target for later untargeted pages. A later explicit break /// replaces it. An `overflow` target may hide it while that subform is open; it returns /// afterwards unless a later explicit break replaced the overflow. @@ -152,8 +189,9 @@ impl Layouter<'_> { } /// Replace the current page when nothing from the flow has been placed on it yet and a - /// subform's `breakBefore` targets a different `pageArea` `idx`. - pub(super) fn switch_empty_page(&mut self, idx: usize) -> Result<(), XfaError> { + /// subform's `breakBefore` targets a different `pageArea` `idx`, entering its content area + /// `content` before the open subforms take their top margins there. + pub(super) fn switch_empty_page(&mut self, idx: usize, content: usize) -> Result<(), XfaError> { if let Some(c) = &self.cur && let Some(u) = self.uses.get_mut(c.area) { @@ -174,6 +212,9 @@ impl Layouter<'_> { } } self.new_page_of(idx)?; + if content > 0 { + self.enter_content(content); + } let (rect, y, _) = self.cursor(); let mut room = (rect.bottom() - y).max(0.0); for i in 0..self.frames.len() { @@ -249,19 +290,24 @@ impl Layouter<'_> { /// Move to the next content area, or the next page. pub(super) fn next_area(&mut self) -> Result<(), XfaError> { - if let Some(c) = &self.cur - && let Some(area) = self.areas.get(c.area) - && let Some(next) = area.content.get(c.content + 1).copied() - { - let i = c.content + 1; - let old_area = c.rect; - self.cur = Some(Cursor { area: c.area, content: i, rect: next, y: next.y, placed: false }); - self.refresh_frame_widths(old_area); + let next = self.cur.as_ref().map(|c| c.content.saturating_add(1)); + if next.is_some_and(|i| self.enter_content(i)) { return Ok(()); } self.new_page() } + /// Move to content area `i` of the current page, from its top; `false` when the page has no + /// such area. + pub(super) fn enter_content(&mut self, i: usize) -> bool { + let Some(c) = &self.cur else { return false }; + let Some(next) = self.areas.get(c.area).and_then(|a| a.content.get(i)).copied() else { return false }; + let old_area = c.rect; + self.cur = Some(Cursor { area: c.area, content: i, rect: next, y: next.y, placed: false }); + self.refresh_frame_widths(old_area); + true + } + /// Refresh outer frames before their children, preserving each parent's available width /// and margins. A fixed-width frame keeps its position. Raw area moves (a split block) keep /// their existing lost-border bookkeeping. @@ -315,6 +361,16 @@ impl Layouter<'_> { } pub(super) fn break_frames_to(&mut self, need: f64, to_page: bool, target_area: Option) -> Result<(), XfaError> { + let dest = match target_area { + Some(idx) => Dest::PageOf(idx), + None if to_page => Dest::Page, + None => Dest::Next, + }; + self.break_frames_into(need, dest) + } + + /// [`Self::break_frames`] to `dest`. + pub(super) fn break_frames_into(&mut self, need: f64, dest: Dest) -> Result<(), XfaError> { let (rect, mut y, _) = self.cursor(); let page = self.pages.len().saturating_sub(1); let here: Vec = self.frames.iter().map(|f| self.on_area(&f.part)).collect(); @@ -327,13 +383,7 @@ impl Layouter<'_> { f.parts.push((page, f.part.items, Rect::new(f.x, f.part.y, f.w, y - f.part.y))); } } - if let Some(idx) = target_area { - self.new_page_of(idx)?; - } else if to_page { - self.new_page()?; - } else { - self.next_area()?; - } + self.move_to(dest)?; let (rect, y, _) = self.cursor(); let mut room = (rect.bottom() - y - need).max(0.0); for i in 0..self.frames.len() { @@ -349,6 +399,26 @@ impl Layouter<'_> { Ok(()) } + /// Move the flow to `dest`, leaving frames as they are. + pub(super) fn move_to(&mut self, dest: Dest) -> Result<(), XfaError> { + match dest { + Dest::Next => self.next_area(), + Dest::Page => self.new_page(), + Dest::PageOf(idx) => self.new_page_of(idx), + Dest::Content(idx, i) => { + let later_here = self.cur.as_ref().is_some_and(|c| c.area == idx && i > c.content); + if !(later_here && self.enter_content(i)) { + self.new_page_of(idx)?; + // A page area's first content area is where a new page starts already. + if i > 0 { + self.enter_content(i); + } + } + Ok(()) + } + } + } + /// The bottom margins of the flowed subforms being laid out, which a break leaves below their /// content ([`Self::break_frames`]). pub(super) fn frames_bottom(&self) -> f64 { diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs index 68e94474da..601b226323 100644 --- a/crates/xfa/src/lib.rs +++ b/crates/xfa/src/lib.rs @@ -189,6 +189,9 @@ pub fn render_into(doc: &mut Document) -> Result { Ok(Report { pages: written.pages, fields: written.fields, template_bytes: packets.xdp.len(), warnings }) } +#[cfg(test)] +mod break_tests; + #[cfg(test)] mod repeat_tests; diff --git a/crates/xfa/src/model.rs b/crates/xfa/src/model.rs index f8cb94da79..e85d1b1a83 100644 --- a/crates/xfa/src/model.rs +++ b/crates/xfa/src/model.rs @@ -547,6 +547,22 @@ pub struct Subform { pub column_widths: Vec, /// ``: the named child (a header row) is repeated after a page break. pub overflow_leader: Option, + /// How `breakBefore` moves on, when [`Self::break_before_page`] is set. + pub break_before_mode: BreakMode, + /// How `breakAfter` moves on, when [`Self::break_after_page`] is set. + pub break_after_mode: BreakMode, +} + +/// How a `breakBefore` or `breakAfter` moves on (XFA 3.3, "Break to Empty pageArea or +/// contentArea", pp. 361-362). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct BreakMode { + /// `targetType="contentArea"`: to the next (or the named) content area, which on a page with + /// several is the next column, rather than to a new page. + pub content_area: bool, + /// `startNew="1"`: a new page or content area even when the current one is empty or already + /// the target. + pub start_new: bool, } /// A positioned group without a box of its own. @@ -859,6 +875,9 @@ pub struct PageArea { pub height: f64, /// Where flowed content goes, in order. pub content: Vec, + /// The `name` and `id` of each content area, in step with [`Self::content`], for breaks that + /// target one. + pub content_names: Vec<(Option, Option)>, /// Draws and fields printed on every page that uses this master. pub items: Vec, /// How many pages may use this master (`None`: unbounded). diff --git a/crates/xfa/src/parse.rs b/crates/xfa/src/parse.rs index 10ae481d94..e011a6511b 100644 --- a/crates/xfa/src/parse.rs +++ b/crates/xfa/src/parse.rs @@ -6,9 +6,9 @@ use base64::Engine; use crate::XfaError; use crate::model::{ - Access, Anchor, Area, Border, Caption, ChoiceList, Color, Common, Corner, Draw, Edge, ExclGroup, Field, FontSpec, HAlign, Layout, Margin, Node, - Occur, PageArea, PageRole, PageSet, ParaSpec, Paragraph, Placement, Presence, Prop, Props, Rect, RichText, Run, Script, Stroke, Subform, - Template, Traversal, Ui, VAlign, Value, + Access, Anchor, Area, Border, BreakMode, Caption, ChoiceList, Color, Common, Corner, Draw, Edge, ExclGroup, Field, FontSpec, HAlign, Layout, + Margin, Node, Occur, PageArea, PageRole, PageSet, ParaSpec, Paragraph, Placement, Presence, Prop, Props, Rect, RichText, Run, Script, Stroke, + Subform, Template, Traversal, Ui, VAlign, Value, }; /// Deepest element nesting followed (templates are shallow; hostile ones are not). @@ -938,6 +938,10 @@ fn parse_page_set(n: XmlNode, warnings: &mut Vec, depth: usize) -> PageS }) .take(MAX_CONTENT_AREAS + 1) .collect(); + let content_names: Vec<(Option, Option)> = children(pa, "contentArea") + .take(MAX_CONTENT_AREAS) + .map(|c| (c.attribute("name").map(str::to_string), c.attribute("id").map(str::to_string))) + .collect(); if content.len() > MAX_CONTENT_AREAS { content.truncate(MAX_CONTENT_AREAS); // Said once however many warnings came before: other warnings fill the shared cap of @@ -963,6 +967,7 @@ fn parse_page_set(n: XmlNode, warnings: &mut Vec, depth: usize) -> PageS width, height, content, + content_names, items, occur_max, occur_min, @@ -1002,11 +1007,28 @@ fn parse_subform(n: XmlNode, warnings: &mut Vec, depth: usize, set_layou // continues using the current layout container" (XFA 3.3 p. 638), so no break. let break_to_page = |name: &str| children(n, name).any(|b| b.attribute("targetType").is_some_and(|t| t == "pageArea" || t == "contentArea")); let non_empty = |s: Option<&str>| s.map(str::trim).filter(|v| !v.is_empty()).map(str::to_string); - let break_target = |name: &str, break_attr: &str, target_attr: &str| -> Option { - children(n, name) - .filter(|b| is_page_target(b.attribute("targetType"))) - .find_map(|b| non_empty(b.attribute("target"))) - .or_else(|| child(n, "break").filter(|b| is_page_target(b.attribute(break_attr))).and_then(|b| non_empty(b.attribute(target_attr)))) + // The break element of kind `name` that applies: the first to a page or content area. Its + // target and its mode are read from it together, so neither comes from another element. + let break_el = |name: &'static str| { + children(n, name).find(|b| match b.attribute("targetType") { + Some(t) => t == "pageArea" || t == "contentArea", + None => non_empty(b.attribute("target")).is_some(), + }) + }; + let break_target = |name: &'static str, break_attr: &str, target_attr: &str| -> Option { + match break_el(name) { + Some(b) => non_empty(b.attribute("target")), + None => child(n, "break").filter(|b| is_page_target(b.attribute(break_attr))).and_then(|b| non_empty(b.attribute(target_attr))), + } + }; + // How the break element the flags above read moves on. + let break_mode = |name: &'static str, legacy: &str| -> BreakMode { + let start_new = |b: XmlNode| b.attribute("startNew").map(str::trim) == Some("1"); + match break_el(name) { + Some(b) => BreakMode { content_area: b.attribute("targetType") == Some("contentArea"), start_new: start_new(b) }, + None => child(n, "break") + .map_or_else(BreakMode::default, |b| BreakMode { content_area: b.attribute(legacy) == Some("contentArea"), start_new: start_new(b) }), + } }; let break_before_target = break_target("breakBefore", "before", "beforeTarget"); let break_after_target = break_target("breakAfter", "after", "afterTarget"); @@ -1032,6 +1054,8 @@ fn parse_subform(n: XmlNode, warnings: &mut Vec, depth: usize, set_layou set: false, column_widths, overflow_leader: child(n, "overflow").and_then(|o| o.attribute("leader")).map(str::to_string).filter(|s| !s.is_empty()), + break_before_mode: break_mode("breakBefore", "before"), + break_after_mode: break_mode("breakAfter", "after"), } } diff --git a/crates/xfa/src/pdf.rs b/crates/xfa/src/pdf.rs index b597cbd85d..74627c5135 100644 --- a/crates/xfa/src/pdf.rs +++ b/crates/xfa/src/pdf.rs @@ -1121,6 +1121,41 @@ fn earlier_images(doc: &Document, pages: ObjRef) -> HashMap<[u8; 32], ObjRef> { out } +/// The pages under `pages`, in reading order: a `/Pages` node's kids, nested ones descended, +/// up to the bound the other page searches here use. A tree that lists a node twice (a cycle) +/// or holds more than [`MAX_PAGES_SEARCHED`] pages is an error: the list would be short, and a +/// destination naming a page it omits would keep a stale reference. +fn page_list(doc: &Document, pages: ObjRef) -> Result, XfaError> { + let mut out = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut stack = vec![pages]; + while let Some(r) = stack.pop() { + if !seen.insert(r) { + return Err(XfaError::Malformed("the document's page tree lists a node twice".into())); + } + let obj = doc.get(r); + let Some(d) = obj.as_dict() else { + continue; + }; + if d.name(b"Type") == Some(b"Pages") || d.get(b"Kids").is_some() { + let kids = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default(); + for k in kids.iter().filter_map(Object::as_ref).rev() { + stack.push(k); + } + } else { + // The bound counts pages accepted, so a tree of exactly the bound followed by an + // empty node is still walked. + if out.len() >= MAX_PAGES_SEARCHED { + return Err(XfaError::TooLarge(format!( + "the document's page tree holds more than {MAX_PAGES_SEARCHED} pages; its bookmarks and named destinations would not be remapped" + ))); + } + out.push(r); + } + } + Ok(out) +} + /// Write laid-out `form` into `doc`: its pages replace the document's, its widgets join the /// AcroForm's fields (a box the file holds a signature for keeps it), and the AcroForm is marked /// laid out. What was written, with any warnings, comes back. @@ -1142,6 +1177,14 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result let kept_widgets = widgets::capture(doc, &catalog, pages_ref); // Pictures embedded by earlier passes, from the pages this pass replaces. let images = earlier_images(doc, pages_ref); + // The pages this pass replaces, in order: bookmarks and named destinations that name them + // are pointed at the replacements, by page position, after the new pages are written. + // A page tree the walk cannot list (a cycle, a node listed twice, past the bound) is + // reported, not fatal: the layout is written and its destinations are left as they were. + let (old_pages, remap_skipped) = match page_list(doc, pages_ref) { + Ok(pages) => (pages, None), + Err(why) => (Vec::new(), Some(why.to_string())), + }; let (signed, taken) = existing_fields(doc, &catalog); let groups = earlier_groups(doc, &catalog); let mut em = Emitter { @@ -1191,12 +1234,25 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result catalog_changed |= register_groups(doc, &mut catalog, &groups, used)?; } let count = kids.len(); + // Bookmarks and named destinations that named the pages above are pointed at the + // replacements, by page position (one the layout dropped goes to the last page). + let new_pages: Vec = kids.iter().filter_map(Object::as_ref).collect(); doc.update_dict(pages_ref, |d| { d.set(b"Type".to_vec(), Object::name("Pages")); d.set(b"Kids".to_vec(), Object::Array(kids)); d.set(b"Count".to_vec(), Object::Int(count as i64)); d.remove(b"Parent"); })?; + let remap_skipped = match remap_destinations(doc, &mut catalog, &old_pages, &new_pages) { + Ok(changed) => { + catalog_changed |= changed; + remap_skipped + } + Err(why) => Some(why.to_string()), + }; + if let Some(why) = remap_skipped { + warnings.push(format!("bookmarks and named destinations were not all pointed at the new pages: {why}")); + } // AcroForm: keep what is there (the XFA packets above all), add our fields and fonts. let acro_ref = catalog.get(b"AcroForm").and_then(Object::as_ref); let mut acro = match catalog.get(b"AcroForm") { @@ -1252,6 +1308,285 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result Ok(Written { pages: count, fields: field_count, warnings, usage_rights }) } +/// Point bookmarks and named destinations at the pages a layout wrote: `old` (what the +/// document had) maps to `new` by page position, and a destination that named a page the +/// layout dropped is pointed at the last page written (the form shrank). A destination that +/// named a page the layout left alone, or a target that is not a page, is left alone. +/// A bookmark list or name tree past [`MAX_PAGES_SEARCHED`], or a destination or name tree +/// that refers to itself, is an error. The bookmark walk is checked before anything is written, +/// but a name or destination walk can fail after earlier ones were written, so the document may +/// be partly remapped: `write_form` reports that as a warning and keeps the layout. +/// Returns whether `catalog` itself changed (a direct `/Dests` or `/Names`). +fn remap_destinations(doc: &mut Document, catalog: &mut Dict, old: &[ObjRef], new: &[ObjRef]) -> Result { + if old.is_empty() { + return Ok(false); + } + let Some(&last) = new.last() else { + return Ok(false); + }; + let map: HashMap = old.iter().enumerate().map(|(i, o)| (*o, if i < new.len() { new[i] } else { last })).collect(); + let mut catalog_changed = false; + // /Dests: the named destinations, direct or indirect. + let dests_at = catalog.get(b"Dests").and_then(Object::as_ref); + if let Some(mut dests) = catalog.get(b"Dests").map(|d| doc.resolve(d)).and_then(|d| d.as_dict().cloned()) { + let mut updates: Vec<(Vec, Object)> = Vec::new(); + for (name, v) in dests.iter() { + let mut seen = HashSet::new(); + if let Some(new) = remap_dest(doc, v, &map, &mut seen)? { + updates.push((name.clone(), new)); + } + } + if !updates.is_empty() { + for (name, new) in updates { + dests.set(name, new); + } + match dests_at { + Some(r) => doc.set(r, Object::Dict(dests)), + None => { + catalog.set(b"Dests".to_vec(), Object::Dict(dests)); + catalog_changed = true; + } + } + } + } + // /Outlines: the bookmark items, from /First (each item's /Next, /First and /Kids too). + let first = catalog.get(b"Outlines").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().and_then(|d| d.get(b"First")).and_then(Object::as_ref)); + if let Some(first) = first { + let mut items = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut stack = vec![first]; + while let Some(r) = stack.pop() { + // Listed twice (its /Kids and /First both name it): remapped once, and not + // counted against the bound again. + if !seen.insert(r) { + continue; + } + if items.len() >= MAX_PAGES_SEARCHED { + return Err(XfaError::TooLarge(format!( + "the document's bookmarks hold more than {MAX_PAGES_SEARCHED} items; they would not all be remapped" + ))); + } + items.push(r); + if let Some(next) = doc.get(r).as_dict().and_then(|d| d.get(b"Next")).and_then(Object::as_ref) { + stack.push(next); + } + // A child, the spec's way: the item's /First. + if let Some(child) = doc.get(r).as_dict().and_then(|d| d.get(b"First")).and_then(Object::as_ref) { + stack.push(child); + } + let kids = + doc.get(r).as_dict().and_then(|d| d.get(b"Kids")).map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default(); + for k in kids.iter().filter_map(Object::as_ref).rev() { + stack.push(k); + } + } + for r in items { + let Some(mut d) = doc.get(r).as_dict().cloned() else { + continue; + }; + let mut changed = false; + if let Some(dest) = d.get(b"Dest") { + let mut seen = HashSet::new(); + if let Some(new) = remap_dest(doc, dest, &map, &mut seen)? { + d.set(b"Dest".to_vec(), new); + changed = true; + } + } + if let Some(a) = d.get(b"A") { + let mut seen = HashSet::new(); + if let Some(new) = remap_action(doc, a, &map, &mut seen)? { + d.set(b"A".to_vec(), new); + changed = true; + } + } + if changed { + doc.set(r, Object::Dict(d)); + } + } + } + // /Names: the Dests and Pages categories, a tree each: the Dests one's values are + // destinations, the Pages one's are page references. + let names_at = catalog.get(b"Names").and_then(Object::as_ref); + if let Some(mut names) = catalog.get(b"Names").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()) { + let mut updates: Vec<(Vec, Object)> = Vec::new(); + for (cat, node) in names.iter() { + let pages = cat.as_slice() == b"Pages"; + if cat.as_slice() == b"Dests" || pages { + let mut seen = HashSet::new(); + if let Some(new) = remap_name_tree(doc, node, &map, &mut seen, pages)? { + updates.push((cat.clone(), new)); + } + } + } + if !updates.is_empty() { + for (cat, new) in updates { + names.set(cat, new); + } + match names_at { + Some(r) => doc.set(r, Object::Dict(names)), + None => { + catalog.set(b"Names".to_vec(), Object::Dict(names)); + catalog_changed = true; + } + } + } + } + Ok(catalog_changed) +} + +/// Remap the page a destination value names through `map`: an array whose first element +/// names a page, a dictionary with `/D`, or an indirect reference to either. An indirect one +/// is updated where it is, so nothing comes back for the caller to put back. A string is a +/// name in the document's `/Dests` (remapped there first), so it is left alone. `seen` +/// holds the references this value's `/D` chain has followed: a repeat is a cycle, an error. +fn remap_dest(doc: &mut Document, v: &Object, map: &HashMap, seen: &mut HashSet) -> Result, XfaError> { + match v { + Object::Array(a) => { + let mut a = a.clone(); + let changed = a.first().and_then(Object::as_ref).and_then(|r| map.get(&r)).is_some_and(|t| { + a[0] = Object::Ref(*t); + true + }); + Ok(changed.then_some(Object::Array(a))) + } + Object::Dict(d) => { + let Some(dest) = d.get(b"D") else { + return Ok(None); + }; + let Some(new) = remap_dest(doc, dest, map, seen)? else { + return Ok(None); + }; + let mut d = d.clone(); + d.set(b"D".to_vec(), new); + Ok(Some(Object::Dict(d))) + } + Object::Ref(r) => { + if !seen.insert(*r) { + return Err(XfaError::Malformed("a destination's /D chain is cyclic".into())); + } + let resolved = doc.resolve(v); + match &*resolved { + Object::Array(_) | Object::Dict(_) => { + if let Some(new) = remap_dest(doc, &resolved, map, seen)? { + doc.set(*r, new); + } + } + _ => {} + } + Ok(None) + } + _ => Ok(None), + } +} + +/// Remap the page a `/Pages` name tree value names through `map`: it is a page reference, +/// remapped where it is. +fn remap_page_ref(v: &Object, map: &HashMap) -> Option { + v.as_ref().and_then(|r| map.get(&r)).map(|t| Object::Ref(*t)) +} + +/// Remap the `/D` of a `GoTo` action through `map`; an indirect action is updated where it +/// is, so nothing comes back for the caller to put back. +fn remap_action(doc: &mut Document, a: &Object, map: &HashMap, seen: &mut HashSet) -> Result, XfaError> { + let resolved = doc.resolve(a); + let Some(d) = resolved.as_dict() else { + return Ok(None); + }; + let mut d = d.clone(); + if d.name(b"S") != Some(b"GoTo") { + return Ok(None); + } + let Some(dest) = d.get(b"D") else { + return Ok(None); + }; + let Some(new) = remap_dest(doc, dest, map, seen)? else { + return Ok(None); + }; + d.set(b"D".to_vec(), new); + match a.as_ref() { + Some(r) => { + doc.set(r, Object::Dict(d)); + Ok(None) + } + None => Ok(Some(Object::Dict(d))), + } +} + +/// Remap the values in a name tree node through `map` (destinations, or page references +/// where `pages`); an indirect node is updated where it is, so nothing comes back for the +/// caller to put back. A direct one comes back for the caller (the `/Names` dictionary) to +/// put back. `seen` holds the nodes this walk has reached: a repeat is a `/Kids` cycle, an +/// error. +fn remap_name_tree( + doc: &mut Document, + node: &Object, + map: &HashMap, + seen: &mut HashSet, + pages: bool, +) -> Result, XfaError> { + if let Some(r) = node.as_ref() + && !seen.insert(r) + { + return Err(XfaError::Malformed("a name tree's /Kids chain is cyclic".into())); + } + let resolved = doc.resolve(node); + let Some(d) = resolved.as_dict() else { + return Ok(None); + }; + let mut d = d.clone(); + let mut changed = false; + if let Some(names) = d.get(b"Names").map(|n| doc.resolve(n)).and_then(|n| n.as_array().cloned()) { + let mut names = names; + for i in (0..names.len() / 2 * 2).step_by(2) { + if let Some(v) = names.get(i + 1) { + let new = if pages { + remap_page_ref(v, map) + } else { + let mut value_seen = HashSet::new(); + remap_dest(doc, v, map, &mut value_seen)? + }; + if let Some(new) = new { + names[i + 1] = new; + changed = true; + } + } + } + if changed { + match d.get(b"Names").and_then(Object::as_ref) { + Some(r) => doc.set(r, Object::Array(names)), + None => d.set(b"Names".to_vec(), Object::Array(names)), + } + } + } + if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) { + let mut kids = kids; + let mut kids_changed = false; + for k in kids.iter_mut() { + if let Some(new) = remap_name_tree(doc, k, map, seen, pages)? { + *k = new; + kids_changed = true; + } + } + if kids_changed { + match d.get(b"Kids").and_then(Object::as_ref) { + Some(r) => doc.set(r, Object::Array(kids)), + None => d.set(b"Kids".to_vec(), Object::Array(kids)), + } + changed = true; + } + } + if !changed { + return Ok(None); + } + match node.as_ref() { + Some(r) => { + doc.set(r, Object::Dict(d)); + Ok(None) + } + None => Ok(Some(Object::Dict(d))), + } +} + /// Add the screen-only and print-only `groups` this layout drew in (`used`) to the document's /// optional content properties, keeping its own layers as they are: each goes in `/OCGs`; in the /// default configuration the print-only one starts off (the screen-only one starts on when the @@ -1547,4 +1882,277 @@ mod tests { assert_eq!(em.doc.object_numbers().len(), before, "no new object for a repeated picture"); assert_eq!(em.image_xobject(&picture(last), "image/png"), Some(again)); } + + /// A document with `pages` page objects (empty dictionaries) under one `/Pages` node, + /// which also lists itself when `cyclic`. + fn page_tree(doc: &mut Document, pages: usize, cyclic: bool) -> ObjRef { + let mut kids = (0..pages).map(|_| Object::Ref(doc.add(Object::Dict(Dict::new())))).collect::>(); + let node = doc.add(Object::Null); + if cyclic { + kids.push(Object::Ref(node)); + } + let mut d = Dict::new(); + d.set(b"Type".to_vec(), Object::name("Pages")); + d.set(b"Kids".to_vec(), Object::Array(kids)); + doc.set(node, Object::Dict(d)); + node + } + + #[test] + fn a_cyclic_page_tree_terminates_with_an_error() { + // #9027: a `/Pages` node that lists itself walked forever; the search now stops with + // an error, before any destination is remapped. + let mut doc = Document::new_empty(); + let pages = page_tree(&mut doc, 1, true); + let err = page_list(&doc, pages).unwrap_err(); + assert!(matches!(err, XfaError::Malformed(_)), "{err:?}"); + } + + #[test] + fn a_page_tree_past_the_search_limit_errors_before_replacement() { + // A destination naming a page the search omits would keep a stale reference; the + // search errors instead, and exactly the bound is still walked. + let mut doc = Document::new_empty(); + let pages = page_tree(&mut doc, MAX_PAGES_SEARCHED + 1, false); + let err = page_list(&doc, pages).unwrap_err(); + assert!(matches!(err, XfaError::TooLarge(_)), "{err:?}"); + let mut doc = Document::new_empty(); + let pages = page_tree(&mut doc, MAX_PAGES_SEARCHED, false); + assert_eq!(page_list(&doc, pages).unwrap().len(), MAX_PAGES_SEARCHED); + } + + /// A document whose catalog's `/Dests` entry `cyc` is a dictionary whose `/D` is itself. + fn cyclic_dests(doc: &mut Document) -> Dict { + let dest = doc.add(Object::Null); + let mut d = Dict::new(); + d.set(b"D".to_vec(), Object::Ref(dest)); + doc.set(dest, Object::Dict(d)); + let mut dests = Dict::new(); + dests.set(b"cyc".to_vec(), Object::Ref(dest)); + let mut catalog = Dict::new(); + catalog.set(b"Dests".to_vec(), Object::Dict(dests)); + catalog + } + + #[test] + fn a_cyclic_destination_terminates_with_an_error() { + // #9027: a destination whose `/D` chain is a cycle walked forever; the remap now + // stops with an error, before any destination is replaced. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = cyclic_dests(&mut doc); + let err = remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap_err(); + assert!(matches!(err, XfaError::Malformed(_)), "{err:?}"); + } + + /// A document whose catalog's `/Names` `Dests` tree is a node whose `/Kids` is itself. + fn cyclic_name_tree(doc: &mut Document, value: Object) -> Dict { + let node = doc.add(Object::Null); + let mut d = Dict::new(); + d.set(b"Names".to_vec(), Object::Array(vec![Object::String(PdfString::literal("end")), value])); + d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(node)])); + doc.set(node, Object::Dict(d)); + let mut names = Dict::new(); + names.set(b"Dests".to_vec(), Object::Ref(node)); + let mut catalog = Dict::new(); + catalog.set(b"Names".to_vec(), Object::Dict(names)); + catalog + } + + #[test] + fn a_cyclic_name_tree_terminates_with_an_error() { + // #9027: a name tree whose `/Kids` is a cycle walked forever; the remap now stops + // with an error, before any destination is replaced. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = cyclic_name_tree(&mut doc, Object::Ref(old)); + let err = remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap_err(); + assert!(matches!(err, XfaError::Malformed(_)), "{err:?}"); + } + + /// A document whose catalog's `/Outlines` is a `/Next` chain of `count` items. + fn bookmark_chain(doc: &mut Document, count: usize) -> Dict { + let items: Vec = (0..count).map(|_| doc.add(Object::Dict(Dict::new()))).collect(); + for (a, b) in items.iter().zip(items.iter().skip(1)) { + let mut d = doc.get(*a).as_dict().cloned().unwrap(); + d.set(b"Next".to_vec(), Object::Ref(*b)); + doc.set(*a, Object::Dict(d)); + } + let mut outlines = Dict::new(); + outlines.set(b"First".to_vec(), Object::Ref(items[0])); + let mut catalog = Dict::new(); + catalog.set(b"Outlines".to_vec(), Object::Dict(outlines)); + catalog + } + + #[test] + fn a_bookmark_list_past_the_search_limit_errors_before_replacement() { + // A bookmark the search omits would not be remapped; the search errors instead, and + // exactly the bound is still walked. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = bookmark_chain(&mut doc, MAX_PAGES_SEARCHED + 1); + let err = remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap_err(); + assert!(matches!(err, XfaError::TooLarge(_)), "{err:?}"); + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = bookmark_chain(&mut doc, MAX_PAGES_SEARCHED); + assert!(!remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap()); + } + + #[test] + fn an_outline_item_reaches_its_first_child() { + // #9027: a child is the parent's /First (the spec's way); the walk follows it, so + // the child's destination is remapped too. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let child = doc.add({ + let mut d = Dict::new(); + d.set(b"Dest".to_vec(), Object::Array(vec![Object::Ref(old), Object::name("Fit")])); + d + }); + let parent = doc.add({ + let mut d = Dict::new(); + d.set(b"First".to_vec(), Object::Ref(child)); + d + }); + let mut catalog = Dict::new(); + let mut outlines = Dict::new(); + outlines.set(b"First".to_vec(), Object::Ref(parent)); + catalog.set(b"Outlines".to_vec(), Object::Dict(outlines)); + remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap(); + let obj = doc.get(child); + let dest = obj.as_dict().unwrap().get(b"Dest").unwrap(); + assert_eq!(dest.as_array().unwrap().first().and_then(Object::as_ref), Some(new), "the child's destination follows the page"); + } + + #[test] + fn a_pages_name_tree_entry_points_at_the_replacement() { + // #9027: a `/Pages` name tree value is a page reference, not a destination; it is + // remapped through the map directly. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let names = doc.add(Object::Array(vec![Object::String(PdfString::literal("end")), Object::Ref(old)])); + let node = doc.add({ + let mut d = Dict::new(); + d.set(b"Names".to_vec(), Object::Ref(names)); + d + }); + let mut catalog = Dict::new(); + let mut names_cat = Dict::new(); + names_cat.set(b"Pages".to_vec(), Object::Ref(node)); + catalog.set(b"Names".to_vec(), Object::Dict(names_cat)); + remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap(); + let obj = doc.get(names); + let arr = obj.as_array().unwrap(); + assert_eq!(arr.get(1).and_then(Object::as_ref), Some(new), "the /Pages entry follows the page"); + } + + /// `old_n` old pages mapped onto `new_n` new ones, each old page named by a bookmark, a + /// `/Dests` entry and a `/Names` `Dests` entry; returns the page each of the three ended up on. + fn remap_every_kind(old_n: usize, new_n: usize) -> (Vec, Vec<[Option; 3]>) { + let mut doc = Document::new_empty(); + let old: Vec = (0..old_n).map(|_| doc.add(Object::Dict(Dict::new()))).collect(); + let new: Vec = (0..new_n).map(|_| doc.add(Object::Dict(Dict::new()))).collect(); + let dest = |page: ObjRef| Object::Array(vec![Object::Ref(page), Object::name("Fit")]); + let items: Vec = old + .iter() + .map(|o| { + let mut d = Dict::new(); + d.set(b"Dest".to_vec(), dest(*o)); + doc.add(Object::Dict(d)) + }) + .collect(); + for (a, b) in items.iter().zip(items.iter().skip(1)) { + let mut d = doc.get(*a).as_dict().cloned().unwrap(); + d.set(b"Next".to_vec(), Object::Ref(*b)); + doc.set(*a, Object::Dict(d)); + } + let mut outlines = Dict::new(); + outlines.set(b"First".to_vec(), Object::Ref(items[0])); + let mut dests = Dict::new(); + let mut names = Vec::new(); + for (i, o) in old.iter().enumerate() { + dests.set(format!("d{i}").into_bytes(), dest(*o)); + names.push(Object::String(PdfString::literal(format!("n{i}")))); + names.push(dest(*o)); + } + let mut tree = Dict::new(); + tree.set(b"Names".to_vec(), Object::Array(names)); + let mut names_cat = Dict::new(); + names_cat.set(b"Dests".to_vec(), Object::Dict(tree)); + let mut catalog = Dict::new(); + catalog.set(b"Outlines".to_vec(), Object::Dict(outlines)); + catalog.set(b"Dests".to_vec(), Object::Dict(dests)); + catalog.set(b"Names".to_vec(), Object::Dict(names_cat)); + remap_destinations(&mut doc, &mut catalog, &old, &new).unwrap(); + let first = |o: &Object| o.as_array().and_then(|a| a.first()).and_then(Object::as_ref); + let got = (0..old_n) + .map(|i| { + let bookmark = doc.get(items[i]).as_dict().and_then(|d| d.get(b"Dest")).and_then(first); + let named = catalog.get(b"Dests").and_then(Object::as_dict).and_then(|d| d.get(format!("d{i}").as_bytes())).and_then(first); + let tree = catalog.get(b"Names").and_then(Object::as_dict).and_then(|d| d.get(b"Dests")).and_then(Object::as_dict); + let in_tree = tree.and_then(|t| t.get(b"Names")).and_then(Object::as_array).and_then(|a| a.get(i * 2 + 1)).and_then(first); + [bookmark, named, in_tree] + }) + .collect(); + (new, got) + } + + #[test] + fn a_shrinking_layout_sends_the_dropped_pages_destinations_to_the_last_page() { + // #9027: 3 old pages, 2 new: page 0 and 1 follow by position, and page 2 (dropped) + // lands on the last new page, for a bookmark, a /Dests entry and a /Names entry alike. + let (new, got) = remap_every_kind(3, 2); + assert_eq!(got[0], [Some(new[0]); 3]); + assert_eq!(got[1], [Some(new[1]); 3]); + assert_eq!(got[2], [Some(new[1]); 3]); + } + + #[test] + fn a_growing_layout_keeps_each_destination_on_its_own_position() { + // #9027: 2 old pages, 3 new: each follows its position; the extra new page is unnamed. + let (new, got) = remap_every_kind(2, 3); + assert_eq!(got[0], [Some(new[0]); 3]); + assert_eq!(got[1], [Some(new[1]); 3]); + } + + #[test] + fn a_page_tree_of_exactly_the_bound_then_an_empty_node_is_still_walked() { + // The bound counts pages accepted, not nodes popped: an empty /Pages node after a + // full tree is not a page. + let mut doc = Document::new_empty(); + let full = page_tree(&mut doc, MAX_PAGES_SEARCHED, false); + let empty = page_tree(&mut doc, 0, false); + let mut root = Dict::new(); + root.set(b"Type".to_vec(), Object::name("Pages")); + root.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(full), Object::Ref(empty)])); + let root = doc.add(Object::Dict(root)); + assert_eq!(page_list(&doc, root).unwrap().len(), MAX_PAGES_SEARCHED); + } + + #[test] + fn a_bookmark_listed_twice_at_the_bound_is_not_a_new_item() { + // The item bound is for distinct items: with exactly the bound of them, the first + // named again by the last item's /Kids is a repeat and does not make the list too large. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = bookmark_chain(&mut doc, MAX_PAGES_SEARCHED); + let first = catalog.get(b"Outlines").and_then(Object::as_dict).and_then(|o| o.get(b"First")).and_then(Object::as_ref).unwrap(); + let mut last = first; + while let Some(next) = doc.get(last).as_dict().and_then(|d| d.get(b"Next")).and_then(Object::as_ref) { + last = next; + } + let mut d = doc.get(last).as_dict().cloned().unwrap(); + d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(first)])); + doc.set(last, Object::Dict(d)); + assert!(remap_destinations(&mut doc, &mut catalog, &[old], &[new]).is_ok()); + } } diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index bc9d6911b0..fd0103ed42 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -2951,10 +2951,10 @@ fn a_buttons_box_is_the_whole_field_whatever_its_margins() { /// body page (and listed a copy of its fields per page). #[test] fn page_area_without_occur_serves_every_body_page() { + // The first section has no break: a startNew break there would open a blank first page. let section = |n: u32| { - format!( - r#""# - ) + let brk = if n == 1 { "" } else { r#""# }; + format!(r#"{brk}"#) }; let xdp = format!( r##" @@ -2991,10 +2991,10 @@ fn page_master_content_repeated_on_each_page_has_its_own_som_index() { // One page area (no occur limit) serves three body pages and carries a field in its own // master content. Each page's copy of that field gets the page area's instance index, so the // three do not share one SOM path (and one data node). + // The first section has no break: a startNew break there would open a blank first page. let section = |n: u32| { - format!( - r#""# - ) + let brk = if n == 1 { "" } else { r#""# }; + format!(r#"{brk}"#) }; let xdp = format!( r##" @@ -5887,7 +5887,7 @@ fn named_page_area_breaks_switch_between_portrait_and_landscape_masters() { .unwrap_or(0.0); assert!(pos_right > 600.0, "f_pos at x=200mm on landscape page is not clipped: {pos_right}"); - // When the very first subform targets Page3, page 1 itself uses Page3 without an extra blank page, + // When the very first subform targets Page3 without startNew, page 1 itself uses Page3, // `` directs overflow pages to a named master, and `` // switches the following page master. let first_landscape = r##"