mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-04 22:49:54 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8199f45fa2 | ||
|
|
6e2b519b3e |
+1
-4
@@ -2,10 +2,7 @@
|
||||
plan/
|
||||
/target
|
||||
/dist
|
||||
/corpus/*
|
||||
!/corpus/docx/
|
||||
/corpus/docx/*
|
||||
!/corpus/docx/README.md
|
||||
/corpus
|
||||
/log
|
||||
.DS_Store
|
||||
/.claude/
|
||||
|
||||
Generated
+125
-112
@@ -1173,7 +1173,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1214,7 +1214,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1226,7 +1226,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1234,7 +1234,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1259,7 +1259,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1277,7 +1277,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1295,12 +1295,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1308,7 +1308,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1317,12 +1317,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1330,7 +1330,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1350,7 +1350,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-control-protocol",
|
||||
"craft-platform",
|
||||
@@ -1361,7 +1361,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1371,7 +1371,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1379,7 +1379,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1405,7 +1405,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc-binary"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-cfb",
|
||||
@@ -1422,7 +1422,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1430,7 +1430,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
@@ -1450,7 +1450,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1469,7 +1469,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-xml",
|
||||
@@ -1481,7 +1481,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-wordmodel",
|
||||
"image",
|
||||
@@ -1491,7 +1491,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1506,7 +1506,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1525,7 +1525,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1534,7 +1534,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1557,7 +1557,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-subset"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"harfbuzz-subset-sys",
|
||||
@@ -1570,7 +1570,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-font-subset",
|
||||
]
|
||||
@@ -1578,7 +1578,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gpu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"egui-wgpu",
|
||||
"log",
|
||||
@@ -1590,7 +1590,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1603,7 +1603,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-html"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -1616,7 +1616,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.1",
|
||||
@@ -1646,7 +1646,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1673,7 +1673,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1691,7 +1691,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1699,7 +1699,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1714,7 +1714,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-latex"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
@@ -1725,7 +1725,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-markdown"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
@@ -1735,7 +1735,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"roxmltree",
|
||||
@@ -1745,7 +1745,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mcp-server"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1753,7 +1753,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1771,7 +1771,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
@@ -1783,7 +1783,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1794,7 +1794,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"chrono",
|
||||
@@ -1805,7 +1805,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1814,7 +1814,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1840,7 +1840,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ods"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-odf",
|
||||
"craft-sheet",
|
||||
@@ -1851,7 +1851,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1868,7 +1868,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
@@ -1879,7 +1879,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1895,7 +1895,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"krilla",
|
||||
"serde",
|
||||
@@ -1905,7 +1905,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"async-channel",
|
||||
@@ -1943,7 +1943,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1967,7 +1967,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1978,7 +1978,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1991,7 +1991,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -2010,7 +2010,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -2023,7 +2023,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2040,17 +2040,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ssip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
@@ -2067,7 +2067,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2079,7 +2079,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2103,7 +2103,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2118,7 +2118,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2133,7 +2133,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2143,7 +2143,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2152,7 +2152,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2167,12 +2167,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2186,7 +2186,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2203,7 +2203,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2241,7 +2241,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2252,7 +2252,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2270,7 +2270,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2291,7 +2291,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2312,7 +2312,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-test-kit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2323,7 +2323,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2342,7 +2342,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2374,7 +2374,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2385,7 +2385,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-platform",
|
||||
@@ -2397,7 +2397,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2405,7 +2405,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2437,7 +2437,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math",
|
||||
@@ -2451,7 +2451,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xls"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
@@ -2464,7 +2464,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
@@ -2476,7 +2476,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2486,7 +2486,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2842,7 +2842,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -2875,7 +2875,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2910,7 +2910,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -2929,7 +2929,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2948,7 +2948,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"accesskit_winit",
|
||||
"arboard",
|
||||
@@ -2974,7 +2974,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"egui",
|
||||
@@ -2987,7 +2987,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -3000,7 +3000,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"dify",
|
||||
"eframe",
|
||||
@@ -3026,7 +3026,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -3107,7 +3107,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -3133,7 +3133,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.1",
|
||||
@@ -3866,7 +3866,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3875,7 +3875,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3893,7 +3893,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3911,12 +3911,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4645,7 +4645,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4784,7 +4784,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo",
|
||||
@@ -8454,6 +8454,19 @@ dependencies = [
|
||||
"wayland-scanner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-protocols-plasma"
|
||||
version = "0.3.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"wayland-scanner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-protocols-wlr"
|
||||
version = "0.3.12"
|
||||
@@ -8978,7 +8991,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
[[package]]
|
||||
name = "winit"
|
||||
version = "0.30.13"
|
||||
source = "git+https://github.com/storytold/winit.git?rev=3fd7ae64762f82a73b78bd24f453f82c4291067d#3fd7ae64762f82a73b78bd24f453f82c4291067d"
|
||||
source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"android-activity",
|
||||
@@ -9017,6 +9030,7 @@ dependencies = [
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"wayland-protocols-plasma",
|
||||
"web-sys",
|
||||
"web-time",
|
||||
"windows-sys 0.52.0",
|
||||
@@ -9664,7 +9678,6 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
name = "xtask"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -10037,19 +10050,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "hayro"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
|
||||
+54
-54
@@ -37,22 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
wordcraft-validate = { path = "crates/validate" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -85,28 +85,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -174,27 +174,27 @@ debug = 0
|
||||
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
|
||||
# and the egui and winit forks it builds with.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
|
||||
|
||||
+1
-14
@@ -60,9 +60,7 @@ discounts and the user evidence (120 issues from outside users, 4 praise, 0 "swi
|
||||
|
||||
**Why alpha:** the core workflows (write, format, styles, lists, tables, references, review, mail
|
||||
merge, open and save .docx) work end to end and ship as signed builds on every desktop platform
|
||||
and the web. **Why not beta:** DOCX has not been tested on a real-world corpus yet (the opt-in
|
||||
`cargo xtask docx-corpus` harness can now run one locally, but no corpus or Word comparison is
|
||||
checked in); charts, SmartArt and
|
||||
and the web. **Why not beta:** DOCX has never been tested on real-world files; charts, SmartArt and
|
||||
OLE objects are dropped silently; pagination differs from Word (no Aptos-metric font, no column
|
||||
balancing or footnote continuation); content controls are lost; there is open field evidence of
|
||||
a startup crash and several hangs; no native printing. Gaps #1–#7 in [`docs/gaps.md`](docs/gaps.md)
|
||||
@@ -409,7 +407,6 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
- 2026-10-24: AutoCorrect: a word typed after a no-break space or an ideographic space is corrected as after a plain space (replacements, sentence capitals, ordinals and links). AutoCorrect left such a word as typed.
|
||||
- 2026-10-24: MCP `type_text` with `paragraphs: true` is one command (#3973): it was a `text.newParagraph` and a `text.insert` per line, each snapshotting the whole document for Undo, so 10,000 lines took 2.8 s (doubling the lines cost 2.4–3.2×) and left an Undo step per line; now they take ~10 ms (linear) and one Undo takes them all back. A CRLF is one break, not two, and the breaks no longer run AutoCorrect (the per-line way capitalised every line but the last). Typed line breaks are the Enter key, so in a one-line content control, where Enter does nothing, they no longer split it into paragraphs.
|
||||
- 2026-10-24: Track Changes: the border-line (`---` and the others) and `+---+` table AutoFormats mark the typed characters deleted instead of removing them, so Reject All brings them back. Characters the same author typed with tracking on are removed, as a tracked Backspace removes them. A border at the top of a story is a tracked formatting change too, as the border on the paragraph above already was. The table is inserted untracked, as Insert › Table inserts one. A line that holds a tracked deletion no longer triggers either AutoFormat.
|
||||
- 2026-10-23: Headers and footers: with the caret in a later section's header or footer, Link to Previous, Header/Footer Position, Insert › Header/Footer and Page Borders change that section. They counted the header's paragraphs as body paragraphs, so section 2's header changed section 1 (#3639).
|
||||
- 2026-10-23: cu20we: DrawingML flat, square and round line caps are imported, saved, displayed and exported to PDF; absent or unknown caps default to flat. VML end caps (including shapetype inheritance) are preserved through DOCX save. Ink and metafile stroke handling remain separate. Synthetic DOCX, raster and PDF regressions cover the change; no new native Word comparison.
|
||||
- 2026-10-23: cu20we: paragraph-relative box floats start above effective space before; header, footer, cell and text-box layout regressions pass. Framed paragraph positioning is unchanged; no new native Word comparison.
|
||||
- 2026-10-23: AutoFormat As You Type: `*Bold* and _italic_ as real formatting`. With the option on, `*word*` typed and finished becomes bold and `_word_` italic, without the marks. It is off by default (`tools.autocorrect {"boldItalic"}`).
|
||||
@@ -453,7 +450,6 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target
|
||||
- 2026-10-20: Restrict Editing: with Filling in forms enforced, the Developer tab's content-control buttons and Properties grey out in the ribbon, their tooltips saying why, as in Word; before, they looked live and only refused when clicked.
|
||||
- 2026-10-20: The page tip shown while dragging the vertical scrollbar stays on one line; it broke into two or three lines ("Page 10 of" / "40") as the page number grew during the drag (#3341).
|
||||
- 2026-10-20: Layout: text in Apple's Times and Courier takes Times New Roman's and Courier New's single-line spacing, as in Word for Mac; in a corpus of 180 real manuscripts, the five set in Times no longer gain a page.
|
||||
- 2026-10-19: The empty window (no document, as after Esc on the Start screen or File › Close) says no document is open in the page area and offers Blank document, Browse… and Home; Home returns to the Start screen without making a document (#3126).
|
||||
- 2026-10-19: Restrict Editing: with Filling in forms enforced, inserting content controls, their Properties and Remove Content Control are refused, as in Word (it greys them out), so a form's fields stay as they are and only their content is filled in.
|
||||
- 2026-10-19: Content controls: text typed over a placeholder takes the control's own run properties (`w:sdtPr/w:rPr`, ECMA-376 §17.5.2.27), as in Word, and the placeholder style is recognised by its built-in name "Placeholder Text" whatever its localized id (German Word: `Platzhaltertext`), so entries in forms from localized Word no longer stay grey.
|
||||
|
||||
@@ -497,7 +493,6 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target
|
||||
| 2026-10-25 | Custom document properties (#2982, split from #1798): File › Info › Properties › Advanced Properties… opens a Custom Document Properties dialog that lists the document's custom properties and adds, modifies and deletes them through the name/value form (text properties only; Word's number/date/yes-no types not offered). OK is one undoable `file.properties` step and marks the document changed; Cancel discards everything; names and values are validated against the engine's limits with the error shown in the dialog. Saved properties survive a DOCX round trip. |
|
||||
| 2026-10-24 | #4085: Ctrl+Alt+H toggles the last chosen highlight colour; explicit colour setters remain idempotent. Mixed, inherited and pending formatting and Undo/Redo covered by command/key regressions. |
|
||||
| 2026-10-23 | File > Print: N-up physical sheets and left/right-bound booklets, shared preview/PDF geometry and padded copies (#641); printer jobs keep upstream’s link-annotation fix. |
|
||||
| 2026-10-23 | Header and footer commands change the section of the header the caret is in (#3639) |
|
||||
| 2026-10-23 | A command that changes nothing is not an edit: it adds no undo step, marks no unsaved changes and forces no relayout, so the redo stack survives it and five hundred of them can no longer push the user's own edits out of the undo history. |
|
||||
| 2026-10-23 | Interface translations come from storytold/craft-i18n, shared with the other Crafting Apps: the catalogs are embedded at build time from the commit in `craft-i18n.rev` and looked up through craft-libs' `craft-i18n` crate; `crates/ui-egui/src/i18n/*.tsv` are gone (translations now go to craft-i18n). Strings other apps already translate show translated; a build without `CRAFT_I18N_DIR` is English only |
|
||||
| 2026-10-23 | Comment times show in the user's own time zone, as in Word: the Comments pane converts them (it showed the file's UTC time) and the balloons show them under each author (they showed none). The file's UTC time (Word's `w16cex:dateUtc`) wins over `w:date`, a time naming its zone is converted, and one without a zone shows as written (#2322, #2337) |
|
||||
@@ -605,7 +600,6 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target
|
||||
| 2026-10-15 | Rulers: the numbers thin out as the page shrinks on screen (every 1, 2, 4… units, at least 30 px apart, the small ticks at least 4 px apart), give way to the indent, tab and column markers, and the margins get ticks only; both rulers span the caret's page at its own scale in One Page and Multiple Pages and follow the caret to another page (#1878) |
|
||||
| 2026-10-15 | Spelling as you type no longer flags the word being typed; the squiggle comes when the word ends or the caret leaves it, as in Word (#1552) |
|
||||
| 2026-10-15 | Text Highlight Color: No Color becomes the Highlight button's choice, as in Word, so the next click on the button removes highlighting instead of applying the colour picked before; the ribbon and the mini toolbar share one menu (#2105) |
|
||||
| 2026-10-15 | Design › Paragraph Spacing presets update built-in paragraph styles, so existing styled paragraphs follow the preset; custom paragraph styles keep their own spacing (#1913) |
|
||||
| 2026-10-14 | Insert › Date & Time and DATE, TIME and other date fields show the computer's local date, time and weekday, daylight saving included, as Word does (#1707); they showed UTC, so a user in New Zealand at noon on 31 October got 30 October 23:00. Timestamps saved in files (revisions, comments, document properties) stay UTC. Backstage's greeting follows the local hour too |
|
||||
| 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. |
|
||||
| 2026-10-14 | Tab stops edited on the ruler: the corner selector picks Left/Center/Right/Decimal/Bar, a click sets a stop (Alt skips the snap), dragging moves it with a guide line and position tooltip, dragging off the ruler clears it; markers draw per kind and mirror for RTL; one `para.tabs` call and one undo step per gesture |
|
||||
@@ -627,7 +621,6 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target
|
||||
| 2026-11-07 | Page Setup also bounds the unfocused margin display after a long numeric paste; the accepted value is retained (#5650). |
|
||||
| 2026-11-05 | Page Setup's margin, paper-size and document-grid number boxes scroll long text inside the field instead of enlarging the dialog (#5650). Readiness estimates unchanged. |
|
||||
| 2026-10-29 | Print Markup discovers comment balloon anchors in one forward paragraph-object walk; anchor positions, filtering and the existing cap stay unchanged (#3614) |
|
||||
| 2026-10-29 | PDF figure tagging reuses requested paragraph prefixes within each export (#3614); alternative text, decorative roles and drawing/page order stay unchanged. Synthetic export scaling and tag/persistence controls; readiness estimates unchanged. |
|
||||
| 2026-10-26 | Spelling & Grammar opens a right-side Proofing task pane observed in Word for Windows: sentence context, directly clickable suggestion cards and ignore/dictionary actions. Current-story traversal and stale-target checks are retained. Right-click keeps its compact menu. |
|
||||
| 2026-10-26 | View › Window across the native windows (#322): Arrange All, View Side by Side, Synchronous Scrolling |
|
||||
| 2026-10-22 | Documents that keep content in another format (`w:altChunk`: a web page, RTF, text or another Word document, as generators and mail-merge tools write them) show it where it stands, as Word does, instead of leaving it out; one such file in the docxide-pdf corpus opened as an empty page and now matches Word's 8 pages. `.mht` web archives open, and web pages open the way Word opens them (style sheets, paragraph margins, Times New Roman, single lines, automatic spacing). Insert › Text from File keeps the inserted file's pictures |
|
||||
@@ -961,8 +954,6 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target
|
||||
| 2026-10-07 | v0.1.0 released; contributor credits in About (#6) |
|
||||
| 2026-10-06 | Layout arc: wrap around floats, text boxes, page borders, line numbers, row splitting, drop caps, hyphenation, comment balloons; release pipeline for every platform; first estimate (~62% real feature parity, 120–150 h to 100%) |
|
||||
| 2026-10-05 | M0–M12 first versions: model, layout, render, engine with 200+ commands, Word-style UI, DOCX I/O, PDF and other formats, references, review, mailings, CLI, MCP, web |
|
||||
| 2026-10-19 | Mixed-direction lines: Latin text with digits, hyphens, spaces, full stops and commas after a Persian or Arabic word reads as typed ("2-naphthol", "Windows 11"), as in Word, in right-to-left and left-to-right paragraphs; a combining mark at the end of the Persian or Arabic word stays with its letter (#2150). |
|
||||
| 2026-10-23 | A recipient list over what it keeps is refused while it is read: 1,000 columns, 2 M cells (its records times its widest record) and 64 MiB of cell text, so a hostile file is never built and then cut. |
|
||||
|
||||
Footer page-table height and body wrapping are corrected. Other pagination gaps remain open.
|
||||
|
||||
@@ -971,7 +962,6 @@ Quoted field escapes are interpreted like Word, and body `PAGE` fields use their
|
||||
Section page-numbering settings preserve `w:chapStyle` values across the full unsigned-byte range.
|
||||
MATH glyphs that reference the same construction now share its immutable variants and assembly data (#3630). Glyph mappings, values and the existing partial-record fallback stay unchanged. Repeated glyph IDs keep their last valid reference without retaining superseded constructions. Distinct overlapping constructions and assembly-only sharing remain separate.
|
||||
|
||||
- 2026-10-15: Design › Paragraph Spacing presets update built-in paragraph styles, so existing styled paragraphs follow the preset; custom paragraph styles keep their own spacing (#1913). Readiness unchanged.
|
||||
- 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096).
|
||||
|
||||
## Revision history
|
||||
@@ -1232,7 +1222,6 @@ MATH glyphs that reference the same construction now share its immutable variant
|
||||
| 2026-10-20 | trivial | Progress log: the scrollbar page tip stays on one line (#3341) |
|
||||
| 2026-10-20 | trivial | Progress log: Times and Courier take their Windows counterparts' line spacing |
|
||||
| 2026-10-20 | trivial | Progress log: saving to a NAS share mounted by GVFS (#3003) |
|
||||
| 2026-10-19 | trivial | Empty window (#3126): with no document open (Esc on the Start screen, File › Close), the page area says no document is open and offers Blank document, Browse… and Home; Home goes back to the Start screen without making a document |
|
||||
| 2026-10-19 | trivial | Progress log: Linux display server setting (#2184) |
|
||||
| 2026-10-19 | trivial | Progress log: the status bar's count can be words, characters or characters without spaces (#2797) |
|
||||
| 2026-10-19 | trivial | Text context menus include the existing formatting mini toolbar (#2959); paste options remain in PR #2599. Readiness estimates unchanged. |
|
||||
@@ -1557,8 +1546,6 @@ MATH glyphs that reference the same construction now share its immutable variant
|
||||
> 2026-10-23 · cu20we review follow-up: Only paragraph-relative box floats use the pre-spacing origin. Line-relative floats and page/margin fallbacks in cells and text boxes keep the text-top origin. Synthetic controls compare zero and 24 pt space-before across all four box contexts. New cap conversion helpers and regression tests document their contracts; readiness estimates unchanged.
|
||||
| 2026-11-12 | minor | Progress log: layout.fitOnePage condenses a multi-page document by one page while preserving typography hierarchy (#6433) |
|
||||
| 2026-11-03 | trivial | Progress log: a line breaks after a hyphen before a slash (#3408) |
|
||||
| 2026-10-19 | trivial | Progress log: Latin text in right-to-left lines keeps its order (#2150) |
|
||||
| 2026-10-30 | trivial | Progress log: Left and Right step into an equation next to the caret (#4138); readiness estimates unchanged |
|
||||
|
||||
### Format Painter integration refresh, 2026-10-30
|
||||
|
||||
|
||||
@@ -36,11 +36,9 @@ USAGE:
|
||||
page can't be drawn or a picture is missing or undecodable
|
||||
(report on stderr, as for convert --strict)
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
|
||||
[--save OUT …] [--page N] [--scale S] [--print] [--author NAME]
|
||||
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
|
||||
run commands headlessly, then save (--author names
|
||||
who tracked changes and comments are by).
|
||||
Repeat --save OUT to write multiple outputs in order,
|
||||
after any outputs from --script.
|
||||
PNG saves use --page (1-based, default 1) and --scale (default 2).
|
||||
--script runs a JSON file (- is stdin) first:
|
||||
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
|
||||
@@ -634,13 +632,6 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
validate_options("run", &rest, RUN_OPTIONS)?;
|
||||
let mut cli_outputs = Vec::new();
|
||||
for (i, arg) in rest.iter().enumerate() {
|
||||
if arg == "--save" {
|
||||
let path = rest.get(i + 1).filter(|value| !value.is_empty() && !value.starts_with("--")).ok_or("run: --save requires a path")?;
|
||||
cli_outputs.push(path.clone());
|
||||
}
|
||||
}
|
||||
let page = parse_page_arg("run", &rest)?;
|
||||
let scale = parse_scale_arg("run", &rest)?;
|
||||
let password = password_from(&rest)?;
|
||||
@@ -689,7 +680,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(cli_outputs).collect();
|
||||
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).collect();
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
@@ -1057,7 +1048,6 @@ fn launcher_profile_flag(args: &[OsString]) -> bool {
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
wordcraft_engine::malloc_tuning::apply();
|
||||
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
|
||||
if launcher_profile_flag(&args) {
|
||||
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
|
||||
@@ -564,64 +564,6 @@ fn script_builds_a_document_and_saves_docx_and_pdf_relative_to_the_script() {
|
||||
assert!(json.contains("Hello script") && json.contains("\"bold\":true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_each_cli_output_and_still_accepts_a_single_save() {
|
||||
let dir = script_dir("cli-saves");
|
||||
let input = dir.join("in.docx");
|
||||
let docx = dir.join("out.docx");
|
||||
let pdf = dir.join("out.pdf");
|
||||
run(&args(&["run", "--template", "sample", "--save", &input.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--file", &input.to_string_lossy(), "--save", &docx.to_string_lossy(), "--save", &pdf.to_string_lossy()])).unwrap();
|
||||
assert_eq!(listed_text(&open(&docx, None).unwrap().doc).unwrap(), listed_text(&open(&input, None).unwrap().doc).unwrap());
|
||||
assert!(std::fs::read(pdf).unwrap().starts_with(b"%PDF"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_script_and_cli_outputs() {
|
||||
let dir = script_dir("mixed-saves");
|
||||
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.txt","script.docx"]}"#);
|
||||
let first = dir.join("cli.txt");
|
||||
let second = dir.join("cli.docx");
|
||||
run(&args(&["run", "--save", &first.to_string_lossy(), "--script", &script, "--save", &second.to_string_lossy()])).unwrap();
|
||||
for path in [dir.join("script.txt"), dir.join("script.docx"), first, second] {
|
||||
assert!(path.is_file(), "{} was not written", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_a_missing_second_save_path_before_writing() {
|
||||
let dir = script_dir("missing-save");
|
||||
let first = dir.join("first.docx");
|
||||
let first_path = first.to_string_lossy();
|
||||
for tail in [vec!["--save"], vec!["--save", "--print"], vec!["--save", ""]] {
|
||||
let mut argv: Vec<&str> = vec!["run", "--save", &first_path];
|
||||
argv.extend(tail);
|
||||
assert_eq!(run(&args(&argv)), Err("run: --save requires a path".into()));
|
||||
assert!(!first.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_preflights_script_and_cli_outputs_in_order_before_writing() {
|
||||
let dir = script_dir("preflight-saves");
|
||||
let first = dir.join("first.docx");
|
||||
let invalid = dir.join("missing/later.docx");
|
||||
let last = dir.join("missing-too/last.docx");
|
||||
let mut script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["missing-script/script.docx"]}"#);
|
||||
let first_path = first.to_string_lossy();
|
||||
let invalid_path = invalid.to_string_lossy();
|
||||
let last_path = last.to_string_lossy();
|
||||
let argv = |script: &str| args(&["run", "--save", &first_path, "--save", &invalid_path, "--script", script, "--save", &last_path]);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("script.docx"), "{err}");
|
||||
assert!(!first.exists());
|
||||
|
||||
script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.docx"]}"#);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("later.docx"), "{err}");
|
||||
assert!(!first.exists() && !dir.join("script.docx").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_with_a_bad_output_writes_no_output() {
|
||||
let dir = script_dir("badout");
|
||||
|
||||
@@ -3,8 +3,6 @@ mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_region;
|
||||
mod help;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
mod malloc_tuning;
|
||||
mod mcp_roots;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod non_utf8_args;
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
//! The CLI binary re-executes itself on Linux glibc with `MALLOC_TRIM_THRESHOLD_` fixed so freed
|
||||
//! page/render buffers are returned to the OS while respecting caller-supplied values.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use wordcraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR};
|
||||
|
||||
struct TempDirs(PathBuf);
|
||||
|
||||
impl TempDirs {
|
||||
fn new(tag: &str) -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let root = loop {
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-malloc-{tag}-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => break dir,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => panic!("temp dir {}: {e}", dir.display()),
|
||||
}
|
||||
};
|
||||
std::fs::create_dir_all(root.join("in")).unwrap();
|
||||
std::fs::create_dir_all(root.join("out")).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDirs {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn mcp_environ(tag: &str, set: Option<&str>) -> Vec<String> {
|
||||
let dirs = TempDirs::new(tag);
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] {
|
||||
cmd.env_remove(var);
|
||||
}
|
||||
if let Some(v) = set {
|
||||
cmd.env(TRIM_THRESHOLD_VAR, v);
|
||||
}
|
||||
let mut child = cmd
|
||||
.args(["mcp", "--automation-read-root", &s(&dirs.0.join("in")), "--automation-write-root", &s(&dirs.0.join("out"))])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"ping"}}"#).unwrap();
|
||||
let mut reply = String::new();
|
||||
BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap();
|
||||
assert!(reply.contains(r#""id":1"#), "mcp answered after re-exec: {reply}");
|
||||
let environ = std::fs::read(format!("/proc/{}/environ", child.id())).unwrap();
|
||||
drop(stdin);
|
||||
assert!(child.wait().unwrap().success());
|
||||
environ.split(|&b| b == 0).map(|e| String::from_utf8_lossy(e).into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_the_trim_threshold() {
|
||||
let env = mcp_environ("default", None);
|
||||
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}={TRIM_THRESHOLD}")), "{env:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_a_value_the_user_set() {
|
||||
let env = mcp_environ("explicit", Some("999999"));
|
||||
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}=999999")), "{env:?}");
|
||||
}
|
||||
@@ -74,10 +74,6 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan
|
||||
x11-dl = "2.21"
|
||||
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
|
||||
|
||||
# Name the window supplied by eframe's attachment hook on targets that otherwise use winit indirectly.
|
||||
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# The update helper: a copy of this program started with `--finish-update`
|
||||
# (`craft::update::self_update::finish`).
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
//! Native parent windows for document-owned file pickers in windowless mode.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
use craft::dialogs::service::FilePanels;
|
||||
use craft::platform::open::IntakeSender;
|
||||
use craft::ui::dialog::DialogHost;
|
||||
use eframe::{ViewportHooks, ViewportWindowKey};
|
||||
use egui::{Context, RawInput, ViewportId};
|
||||
use winit::window::Window;
|
||||
use wordcraft_ui_egui::file_dialogs::{NativeWindowLookup, OwnerPanels, ParentLease};
|
||||
|
||||
use crate::drop_intake::ChildDrops;
|
||||
|
||||
/// The latest successful attachment for each viewport. The registry does not keep windows alive.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct DocumentWindows(Arc<Mutex<HashMap<ViewportId, (ViewportWindowKey, Weak<Window>)>>>);
|
||||
|
||||
impl DocumentWindows {
|
||||
pub(crate) fn hooks(&self, drops: IntakeSender) -> Arc<dyn ViewportHooks> {
|
||||
Arc::new(DocumentHooks { windows: self.clone(), drops: ChildDrops(drops) })
|
||||
}
|
||||
}
|
||||
|
||||
struct DocumentHooks {
|
||||
windows: DocumentWindows,
|
||||
drops: ChildDrops,
|
||||
}
|
||||
|
||||
impl ViewportHooks for DocumentHooks {
|
||||
fn window_attached(&self, key: ViewportWindowKey, window: Weak<Window>) {
|
||||
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
attached.insert(key.viewport_id(), (key, window));
|
||||
}
|
||||
|
||||
fn window_detached(&self, key: ViewportWindowKey) {
|
||||
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if attached.get(&key.viewport_id()).is_some_and(|(current, _)| *current == key) {
|
||||
attached.remove(&key.viewport_id());
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_input(&self, ctx: &Context, raw: &mut RawInput) {
|
||||
self.drops.raw_input(ctx, raw);
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeWindowLookup for DocumentWindows {
|
||||
fn incarnation(&self, viewport: ViewportId) -> Option<NonZeroU64> {
|
||||
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (key, weak) = attached.get(&viewport)?;
|
||||
(weak.strong_count() > 0).then(|| key.incarnation())
|
||||
}
|
||||
}
|
||||
|
||||
impl OwnerPanels for DocumentWindows {
|
||||
fn pump_parented(
|
||||
&mut self,
|
||||
viewport: ViewportId,
|
||||
incarnation: NonZeroU64,
|
||||
panels: &mut FilePanels,
|
||||
host: &mut DialogHost,
|
||||
) -> Option<ParentLease> {
|
||||
// Upgrade only the exact live incarnation, on the event-loop thread. Never hold the
|
||||
// registry lock across the pump (macOS can enter native dialog code here).
|
||||
let parent = {
|
||||
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (key, weak) = attached.get(&viewport)?;
|
||||
if key.incarnation() != incarnation {
|
||||
return None;
|
||||
}
|
||||
weak.upgrade()?
|
||||
};
|
||||
panels.pump_with(host, Some(parent.as_ref()));
|
||||
// rfd can use the copied handles on a later worker callback. The router retains this
|
||||
// lease through backend completion even if the initiating document detached meanwhile.
|
||||
Some(ParentLease::new(parent))
|
||||
}
|
||||
|
||||
fn pump_unparented(&mut self, panels: &mut FilePanels, host: &mut DialogHost) {
|
||||
// The router allows this only for an explicitly in-app request or an already launched
|
||||
// operation with an empty native queue. It cannot open an unowned system dialog here.
|
||||
panels.pump_with::<eframe::Frame>(host, None);
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
//! Route desktop drop events to WordCraft's existing file intake.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::platform::open::{DroppedFile, IntakeSender};
|
||||
use eframe::ViewportHooks;
|
||||
use egui::{Context, RawInput, ViewportId};
|
||||
|
||||
/// The ordinary app input hook leaves files in `raw` for the runtime's own reading.
|
||||
pub(crate) fn forward_app_input(sender: &IntakeSender, raw: &RawInput) {
|
||||
sender.dropped(
|
||||
raw.dropped_files
|
||||
.iter()
|
||||
.map(|file| {
|
||||
dropped_path(file.path()).unwrap_or_else(|| DroppedFile { path: None, name: String::new(), bytes: file.bytes().ok().map(Arc::from) })
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
|
||||
fn dropped_path(path: &Path) -> Option<DroppedFile> {
|
||||
if path.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
Some(DroppedFile { path: Some(path.to_path_buf()), name, bytes: None })
|
||||
}
|
||||
|
||||
/// Immediate child input in the windowless trial.
|
||||
pub(crate) struct ChildDrops(pub(crate) IntakeSender);
|
||||
|
||||
impl ViewportHooks for ChildDrops {
|
||||
fn raw_input(&self, _ctx: &Context, raw: &mut RawInput) {
|
||||
// Immediate viewports skip App::raw_input_hook. The regular ROOT input still goes there.
|
||||
// Consume this child batch so no later hook or pass feeds it again. Native OS drops carry
|
||||
// paths: pass those through without reading the files on the event loop.
|
||||
if raw.viewport_id != ViewportId::ROOT && !raw.dropped_files.is_empty() {
|
||||
self.0.dropped(raw.dropped_files.drain(..).filter_map(|file| dropped_path(file.path())).collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft::host::Wake;
|
||||
use craft::platform::open::{FileIntake, Intake};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NativeDrop(PathBuf);
|
||||
|
||||
impl egui::DroppedFile for NativeDrop {
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
fn bytes(&self) -> Result<Vec<u8>, String> {
|
||||
panic!("the raw-input hook must not read native dropped files");
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_drops(viewport_id: ViewportId, paths: &[PathBuf]) -> RawInput {
|
||||
RawInput {
|
||||
viewport_id,
|
||||
dropped_files: paths.iter().map(|path| Arc::new(NativeDrop(path.clone())) as egui::DroppedFileHandle).collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_drop_enters_intake_once_in_drop_order() {
|
||||
let (intake, sender) = FileIntake::new(Wake::none());
|
||||
let hooks = ChildDrops(sender.clone());
|
||||
let ctx = Context::default();
|
||||
let child = ViewportId::from_hash_of("document");
|
||||
let paths = [std::env::temp_dir().join("second.docx"), std::env::temp_dir().join("first.docx")];
|
||||
let mut raw = raw_drops(child, &paths);
|
||||
|
||||
// The immediate child goes through the viewport hook, not the App hook.
|
||||
hooks.raw_input(&ctx, &mut raw);
|
||||
let batches = intake.take();
|
||||
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one child drop batch, got {batches:?}") };
|
||||
assert!(files.iter().map(|file| file.path.as_ref()).eq(paths.iter().map(Some)));
|
||||
|
||||
// A replay of this input, or another input path seeing it, cannot send it again.
|
||||
hooks.raw_input(&ctx, &mut raw);
|
||||
forward_app_input(&sender, &raw);
|
||||
assert!(intake.take().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_drop_still_reaches_intake_only_from_app_input() {
|
||||
let (intake, sender) = FileIntake::new(Wake::none());
|
||||
let hooks = ChildDrops(sender.clone());
|
||||
let ctx = Context::default();
|
||||
let path = std::env::temp_dir().join("document.docx");
|
||||
let mut raw = raw_drops(ViewportId::ROOT, std::slice::from_ref(&path));
|
||||
|
||||
// Pinned eframe calls both hooks on ROOT, in this order.
|
||||
hooks.raw_input(&ctx, &mut raw);
|
||||
assert!(intake.take().is_empty());
|
||||
forward_app_input(&sender, &raw);
|
||||
let batches = intake.take();
|
||||
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one root drop batch, got {batches:?}") };
|
||||
assert!(matches!(files.as_slice(), [file] if file.path.as_ref() == Some(&path)));
|
||||
assert!(matches!(raw.dropped_files.as_slice(), [file] if file.path() == path.as_path()));
|
||||
}
|
||||
}
|
||||
+178
-237
@@ -19,8 +19,6 @@ mod build_channel;
|
||||
mod build_flavor;
|
||||
mod control_server;
|
||||
mod default_apps;
|
||||
mod document_panels;
|
||||
mod drop_intake;
|
||||
mod launch_profile;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
@@ -29,7 +27,6 @@ mod prefs;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod region;
|
||||
mod startup_mode;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
@@ -43,12 +40,12 @@ use craft::platform::appearance::SystemReader;
|
||||
use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard};
|
||||
use craft::platform::default_app::{DefaultApp, DefaultAppError};
|
||||
use craft::platform::logs::{self, LogNames, crash};
|
||||
use craft::platform::open::{FileIntake, IntakeSender};
|
||||
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
|
||||
use craft::print::spool::Spool;
|
||||
use craft::settings::SharedSettings;
|
||||
use craft::ui::InstallSpec;
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost};
|
||||
use craft::ui::shell::embed::{self, CloseDecision};
|
||||
use craft::ui::shell::embed;
|
||||
use craft::window::restore::{self, Store};
|
||||
use craft::window::system::SystemWindows;
|
||||
use wordcraft_engine::Session;
|
||||
@@ -63,8 +60,6 @@ struct App {
|
||||
native_menu: Option<craft::menu::NativeMenu>,
|
||||
/// The native panels behind the file service the app reaches through `Host::files`.
|
||||
panels: FilePanels,
|
||||
/// Native parent windows for the owned picker route, populated only in windowless mode.
|
||||
document_windows: document_panels::DocumentWindows,
|
||||
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
|
||||
/// queue the OS's requests are read from.
|
||||
drops: IntakeSender,
|
||||
@@ -91,35 +86,19 @@ impl App {
|
||||
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
|
||||
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
|
||||
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
|
||||
// Validate native incarnations before WordApp logic can settle an available answer.
|
||||
// A final Quit from a previous pass takes priority over launching any new pick.
|
||||
if self.app.quit_requested {
|
||||
self.app.quiesce_native_file_panels();
|
||||
}
|
||||
self.app.pump_owned_picks(ctx, &mut self.document_windows);
|
||||
self.app.logic(ctx);
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(menu) = &mut self.native_menu {
|
||||
native_menu::update(menu, &mut self.app, ctx);
|
||||
}
|
||||
// Once the document guards have settled Quit, not even this pass's last pump can open
|
||||
// another picker. Keep the event loop and display alive for handles already in use.
|
||||
if self.app.quit_requested {
|
||||
self.app.quiesce_native_file_panels();
|
||||
}
|
||||
self.pump_file_panels(ctx, frame);
|
||||
if self.app.quit_requested && !self.app.printing.busy() && !self.app.native_file_panels_open() {
|
||||
self.panels.pump_with(self.app.dialog_host_mut(), frame);
|
||||
// A quit that waits for nothing (the documents are answered for) closes the root window.
|
||||
if self.app.quit_requested && !self.app.printing.busy() {
|
||||
WindowHost::of(ctx).act(egui::ViewportId::ROOT, WindowAction::Close);
|
||||
}
|
||||
// A platform close can be accepted without setting quit_requested (e.g. no unsaved work).
|
||||
// Shut off new launches only when that final close is accepted, not before a Save prompt.
|
||||
embed::logic(ctx, || {
|
||||
let decision = self.app.close_decision();
|
||||
if matches!(decision, CloseDecision::Close) {
|
||||
self.app.quiesce_native_file_panels();
|
||||
}
|
||||
decision
|
||||
});
|
||||
// The decision holds the close while a Save Changes prompt is open; a closure over
|
||||
// `close_requested` would ask again on every frame of the prompt.
|
||||
embed::logic(ctx, || self.app.close_decision());
|
||||
}
|
||||
|
||||
/// One pass of the root window's UI.
|
||||
@@ -128,12 +107,7 @@ impl App {
|
||||
embed::before_ui(ui.ctx(), frame);
|
||||
}
|
||||
self.app.ui(ui);
|
||||
self.pump_file_panels(ui.ctx(), frame);
|
||||
}
|
||||
|
||||
fn pump_file_panels(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
|
||||
self.panels.pump_with(self.app.dialog_host_mut(), frame);
|
||||
self.app.pump_owned_picks(ctx, &mut self.document_windows);
|
||||
}
|
||||
|
||||
/// Everything that must happen before the process ends, whichever way the window closes.
|
||||
@@ -160,7 +134,11 @@ impl eframe::App for App {
|
||||
/// Hands the app what the runtime gathered since the last frame (fired commands) and the
|
||||
/// runtime the input the app gives back, before any pass of the frame runs.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
drop_intake::forward_app_input(&self.drops, raw);
|
||||
// Once per frame, before any pass; the files stay in `raw` for the runtime's own reading.
|
||||
let files = dropped_files(raw);
|
||||
if !files.is_empty() {
|
||||
self.drops.dropped(files);
|
||||
}
|
||||
self.before_input(ctx);
|
||||
}
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
@@ -174,6 +152,21 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The files dropped in this frame's input, as the intake carries them: a file with a path by its
|
||||
/// path, a file without one by its bytes.
|
||||
fn dropped_files(raw: &egui::RawInput) -> Vec<DroppedFile> {
|
||||
raw.dropped_files
|
||||
.iter()
|
||||
.map(|file| {
|
||||
let path = Some(file.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty());
|
||||
let name = path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
// A file without a path (the web) carries its bytes; one that cannot be read is dropped as empty.
|
||||
let bytes = if path.is_none() { file.bytes().ok().map(std::sync::Arc::from) } else { None };
|
||||
DroppedFile { path, name, bytes }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the window runs through XWayland (X11) rather than native Wayland, and the log line
|
||||
/// saying why. `WORDCRAFT_WAYLAND` wins (`0`, `false`, `no` or `off` asks for X11, any other value
|
||||
/// for Wayland), then File › Options › Advanced › Linux display server (#2184). Automatic is X11
|
||||
@@ -499,9 +492,6 @@ fn main() -> eframe::Result {
|
||||
let updates_unsafe = start_over_failed.is_some();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let updates_unsafe = false;
|
||||
// Before any thread or logger starts: re-exec on Linux glibc with MALLOC_TRIM_THRESHOLD_
|
||||
// fixed so large freed document/render buffers return to the OS.
|
||||
wordcraft_engine::malloc_tuning::apply();
|
||||
// First, so the panic hook (set once, by this call; the later one only gives it the crash-log
|
||||
// folder) and every start-up warning are recorded.
|
||||
let logger = logs::install(LogNames::new("wordcraft"));
|
||||
@@ -623,17 +613,25 @@ fn main() -> eframe::Result {
|
||||
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
|
||||
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
|
||||
};
|
||||
let mut viewport = egui::ViewportBuilder::default()
|
||||
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
|
||||
.with_app_id(app_id)
|
||||
.with_inner_size([1440.0, 920.0])
|
||||
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false);
|
||||
let mut options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
|
||||
.with_app_id(app_id)
|
||||
.with_inner_size([1440.0, 920.0])
|
||||
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(icon) = app_icon() {
|
||||
viewport = viewport.with_icon(icon);
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
}
|
||||
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler and
|
||||
// the GPU that drives the screen (#603, #2652, #5199).
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
|
||||
craft::gpu::configure(setup);
|
||||
}
|
||||
prefs::load_user_fonts();
|
||||
// Where the root window was last, kept beside the settings; in memory when preferences are off.
|
||||
@@ -652,18 +650,16 @@ fn main() -> eframe::Result {
|
||||
let display_server = settings.lock().get().display_server;
|
||||
let (x11, why) = uses_x11(display_server, |name| std::env::var_os(name), x11_libraries);
|
||||
log::info!("{why}");
|
||||
if x11 {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
x11
|
||||
};
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let x11 = false;
|
||||
// The windowless root by default; windowed when rolled back, or when winit will open X11 or
|
||||
// XWayland, which its bootstrap doesn't support (`startup_mode`).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let winit_x11 = startup_mode::winit_picks_x11(x11, |name| std::env::var_os(name));
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let winit_x11 = false;
|
||||
let first_mode = startup_mode::first_mode(std::env::var_os(startup_mode::ROLLBACK_VAR).as_deref(), winit_x11);
|
||||
log::info!("root: {first_mode:?} first");
|
||||
// What the OS asks of a running app arrives here; its wake repaints once the window exists.
|
||||
let repaint: Arc<OnceLock<egui::Context>> = Arc::new(OnceLock::new());
|
||||
let (intake, sender) = FileIntake::new(Wake::new({
|
||||
@@ -674,39 +670,9 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
}
|
||||
}));
|
||||
let drops = intake.sender();
|
||||
// Each start's options, from scratch: a fallback start gets the plain windowed ones.
|
||||
let hook_drops = drops.clone();
|
||||
let document_windows = document_panels::DocumentWindows::default();
|
||||
let hook_windows = document_windows.clone();
|
||||
let native_options = move |mode: eframe::RootViewportMode| {
|
||||
let mut options = eframe::NativeOptions {
|
||||
root_viewport_mode: mode,
|
||||
// A refused start must return here, on the thread whose event loop the fallback reuses.
|
||||
run_and_return: true,
|
||||
viewport: viewport.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler
|
||||
// and the GPU that drives the screen (#603, #2652, #5199).
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
|
||||
craft::gpu::configure(setup);
|
||||
}
|
||||
// Read only when the first start builds the event loop; a fallback reuses that loop.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if x11 {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
if mode == eframe::RootViewportMode::Windowless {
|
||||
options.viewport_hooks = Some(hook_windows.hooks(hook_drops.clone()));
|
||||
}
|
||||
options
|
||||
};
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns.
|
||||
let drops = intake.sender();
|
||||
#[cfg(target_os = "macos")]
|
||||
let _apple_events = craft::platform::open::apple_events::install(sender);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -736,161 +702,138 @@ fn main() -> eframe::Result {
|
||||
let noticed_for_exit = unclean_notice_shown.clone();
|
||||
let noticed_in_window = unclean_notice_shown.clone();
|
||||
let exit_settings = settings.clone();
|
||||
// Everything a start hands the app, used by the one creator that runs (`startup_mode::run`).
|
||||
let create_app = move |cc: &eframe::CreationContext<'_>,
|
||||
mode: eframe::RootViewportMode|
|
||||
-> Result<Box<dyn eframe::App>, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let _ = repaint.set(ctx.clone());
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
};
|
||||
// The interface language: the saved choice, else the system's.
|
||||
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
|
||||
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
|
||||
let host = Arc::new(
|
||||
Host::builder(wordcraft_ui_egui::APP)
|
||||
.i18n(wordcraft_ui_egui::i18n::catalogs())
|
||||
.files(Arc::new(file_service))
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.lang(lang.craft_lang())
|
||||
.build(),
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
|
||||
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
|
||||
// The system region picks the new document's paper, the units and the decimal
|
||||
// separator (#838).
|
||||
let region = region::system();
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
// The custom dictionary's words (#40) count as loaded settings.
|
||||
if prefs::enabled()
|
||||
&& let Some(path) = prefs::user_dict_path()
|
||||
{
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
}
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
let windowless = mode == eframe::RootViewportMode::Windowless;
|
||||
app.enable_windowless_trial(windowless);
|
||||
if windowless {
|
||||
app.set_native_window_lookup(Some(Arc::new(document_windows.clone())));
|
||||
}
|
||||
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
|
||||
if let Some(state) = &cc.wgpu_render_state {
|
||||
let info = state.adapter.get_info();
|
||||
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
|
||||
if software {
|
||||
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
|
||||
let result = eframe::run_native(
|
||||
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let _ = repaint.set(ctx.clone());
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
};
|
||||
// The interface language: the saved choice, else the system's.
|
||||
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
|
||||
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
|
||||
let host = Arc::new(
|
||||
Host::builder(wordcraft_ui_egui::APP)
|
||||
.i18n(wordcraft_ui_egui::i18n::catalogs())
|
||||
.files(Arc::new(file_service))
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.lang(lang.craft_lang())
|
||||
.build(),
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
|
||||
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
|
||||
// The system region picks the new document's paper, the units and the decimal
|
||||
// separator (#838).
|
||||
let region = region::system();
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
// The custom dictionary's words (#40) count as loaded settings.
|
||||
if prefs::enabled()
|
||||
&& let Some(path) = prefs::user_dict_path()
|
||||
{
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
}
|
||||
app.set_software_drawing(software);
|
||||
}
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
}
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
}
|
||||
}
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
}
|
||||
}
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.replace_startup_document(doc);
|
||||
}
|
||||
app.tell_about_font_downloads();
|
||||
if prefs::enabled()
|
||||
&& let Some(dir) = wordcraft_control_key::settings_dir()
|
||||
{
|
||||
let ctx = ctx.clone();
|
||||
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut control_server = None;
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// the OS hands over later open on top of it and close it.
|
||||
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
|
||||
app.start_screen();
|
||||
}
|
||||
// A Word template named here starts a new document based on it (#3433).
|
||||
for f in files {
|
||||
if let Err(e) = app.open_from_platform(&f, None) {
|
||||
app.report_open_failure(&f, &e);
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.replace_startup_document(doc);
|
||||
}
|
||||
}
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
app.tell_about_font_downloads();
|
||||
if prefs::enabled()
|
||||
&& let Some(dir) = wordcraft_control_key::settings_dir()
|
||||
{
|
||||
let ctx = ctx.clone();
|
||||
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
}
|
||||
let mut control_server = None;
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) =
|
||||
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// the OS hands over later open on top of it and close it.
|
||||
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
|
||||
app.start_screen();
|
||||
}
|
||||
// A Word template named here starts a new document based on it (#3433).
|
||||
for f in files {
|
||||
if let Err(e) = app.open_from_platform(&f, None) {
|
||||
app.report_open_failure(&f, &e);
|
||||
}
|
||||
}
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
|
||||
);
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
document_windows,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
};
|
||||
let result = startup_mode::run(first_mode, create_app, |mode, inputs| {
|
||||
eframe::run_native(
|
||||
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
|
||||
native_options(mode),
|
||||
Box::new(move |cc| {
|
||||
let create = inputs.take().ok_or("the app was already created")?;
|
||||
create(cc, mode)
|
||||
}),
|
||||
)
|
||||
});
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
}),
|
||||
);
|
||||
// The exit hook has run; this is the no-op fallback for a start that created no window.
|
||||
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
// The app is dropped by now: whatever it saved on the way out is in the store.
|
||||
@@ -1054,7 +997,6 @@ mod launch_arg_tests {
|
||||
#[cfg(test)]
|
||||
mod smoke {
|
||||
use super::*;
|
||||
use craft::platform::open::DroppedFile;
|
||||
use craft::ui::testing::Frames;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -1102,7 +1044,6 @@ mod smoke {
|
||||
native_menu: None,
|
||||
app,
|
||||
panels,
|
||||
document_windows: Default::default(),
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
//! Which root WordCraft starts with, and the one fallback to normal windows.
|
||||
//!
|
||||
//! The windowless root is the default. `WORDCRAFT_WINDOWLESS_TRIAL=0` (exactly `0`) rolls back to
|
||||
//! a windowed root; any other value, or none, keeps the default. On Linux and the BSDs the
|
||||
//! windowless bootstrap supports only native Wayland, so a start whose event loop winit will open
|
||||
//! on X11 or XWayland starts windowed from the outset and never retries ([`winit_picks_x11`]).
|
||||
//!
|
||||
//! Everything else is decided by eframe, from the display it actually connected to: its windowless
|
||||
//! bootstrap returns [`eframe::Error::UnsupportedConfiguration`] for an X11 display handle (and,
|
||||
//! on macOS and Windows, for a renderer bootstrap it cannot use) before it calls the app creator
|
||||
//! and before any root window exists. With `run_and_return` that error comes back out of
|
||||
//! `run_native`, the thread's event loop stays cached, and a second `run_native` on this thread
|
||||
//! reuses it. [`run`] then starts once more with normal windows, only when the creator has not
|
||||
//! started. Every other error, a second `UnsupportedConfiguration`, and any error after the
|
||||
//! creator started (including a document window whose surface cannot be attached later, which
|
||||
//! eframe reports per document) is returned unchanged.
|
||||
//!
|
||||
//! Source-only caveat: on a native Wayland display eframe's logical root takes the launcher's
|
||||
//! activation token before the renderer starts, so a fallback window there may open without it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use eframe::RootViewportMode;
|
||||
|
||||
/// The variable that rolls the windowless root back to a windowed one, with the value `0`.
|
||||
pub(crate) const ROLLBACK_VAR: &str = "WORDCRAFT_WINDOWLESS_TRIAL";
|
||||
|
||||
/// The root mode of the first start: windowed when rolled back or when winit opens X11.
|
||||
pub(crate) fn first_mode(rollback: Option<&std::ffi::OsStr>, x11: bool) -> RootViewportMode {
|
||||
if x11 || rollback.is_some_and(|v| v == "0") { RootViewportMode::Windowed } else { RootViewportMode::Windowless }
|
||||
}
|
||||
|
||||
/// Whether winit's event loop opens on X11 (XWayland included): forced by the app, or unforced
|
||||
/// with no Wayland display and an X server. Mirrors the pinned winit's choice exactly: empty and
|
||||
/// non-Unicode values count as unset, and Wayland wins over `DISPLAY` when unforced. Neither set
|
||||
/// means winit fails to start at all, which no mode changes.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub(crate) fn winit_picks_x11(forced_x11: bool, env: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
|
||||
let set = |name: &str| env(name).is_some_and(|v| v.to_str().is_some_and(|v| !v.is_empty()));
|
||||
forced_x11 || (!set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") && set("DISPLAY"))
|
||||
}
|
||||
|
||||
/// The app's one-shot startup inputs, shared by every start but taken by one app creator only.
|
||||
pub(crate) struct OneShot<T>(Rc<RefCell<Option<T>>>);
|
||||
|
||||
impl<T> Clone for OneShot<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(Rc::clone(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> OneShot<T> {
|
||||
/// The inputs, for the app creator that runs; `None` once any creator has taken them.
|
||||
pub(crate) fn take(&self) -> Option<T> {
|
||||
self.0.borrow_mut().take()
|
||||
}
|
||||
|
||||
fn untouched(&self) -> bool {
|
||||
self.0.borrow().is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the app in `first` mode through `launch`, and once more with normal windows when a
|
||||
/// windowless start was refused as unsupported before its app creator took `inputs`.
|
||||
pub(crate) fn run<T>(first: RootViewportMode, inputs: T, mut launch: impl FnMut(RootViewportMode, OneShot<T>) -> eframe::Result) -> eframe::Result {
|
||||
let inputs = OneShot(Rc::new(RefCell::new(Some(inputs))));
|
||||
match launch(first, inputs.clone()) {
|
||||
Err(eframe::Error::UnsupportedConfiguration(reason)) if first == RootViewportMode::Windowless && inputs.untouched() => {
|
||||
log::warn!("windowless start unsupported here ({reason}); opening normal windows instead");
|
||||
launch(RootViewportMode::Windowed, inputs)
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use RootViewportMode::{Windowed, Windowless};
|
||||
|
||||
fn unsupported() -> eframe::Result {
|
||||
Err(eframe::Error::UnsupportedConfiguration("windowless root: X11".into()))
|
||||
}
|
||||
|
||||
/// Runs the real policy with scripted starts; each step sees whether it may create the app and
|
||||
/// returns that start's result. Returns the modes started, the modes that created the app, and
|
||||
/// the result.
|
||||
fn script(first: RootViewportMode, mut steps: Vec<(bool, eframe::Result)>) -> (Vec<RootViewportMode>, Vec<RootViewportMode>, eframe::Result) {
|
||||
steps.reverse();
|
||||
let mut started = Vec::new();
|
||||
let mut created = Vec::new();
|
||||
let result = run(first, "inputs", |mode, inputs| {
|
||||
started.push(mode);
|
||||
let (creates, result) = steps.pop().unwrap_or((false, Ok(())));
|
||||
if creates && inputs.take().is_some() {
|
||||
created.push(mode);
|
||||
}
|
||||
result
|
||||
});
|
||||
(started, created, result)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsupported_windowless_bootstrap_starts_once_more_with_windows() {
|
||||
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (true, Ok(()))]);
|
||||
assert_eq!(started, [Windowless, Windowed]);
|
||||
assert_eq!(created, [Windowed], "the inputs reach the windowed start's creator, once");
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_windowed_start_is_the_last_one() {
|
||||
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (false, unsupported())]);
|
||||
assert_eq!(started, [Windowless, Windowed]);
|
||||
assert!(created.is_empty());
|
||||
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windowed_start_is_never_retried() {
|
||||
let (started, _, result) = script(first_mode(None, true), vec![(false, unsupported())]);
|
||||
assert_eq!(started, [Windowed], "X11 starts windowed, once");
|
||||
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_errors_come_back_unchanged() {
|
||||
let (started, _, result) = script(Windowless, vec![(false, Err(eframe::Error::AppCreation("no runtime".into())))]);
|
||||
assert_eq!(started, [Windowless]);
|
||||
assert!(matches!(result, Err(eframe::Error::AppCreation(e)) if e.to_string() == "no runtime"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_starts_again_once_the_app_creator_ran() {
|
||||
let (started, created, result) = script(Windowless, vec![(true, unsupported())]);
|
||||
assert_eq!((started, created), (vec![Windowless], vec![Windowless]));
|
||||
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_exactly_zero_rolls_back() {
|
||||
let var = |v: &str| Some(std::ffi::OsString::from(v));
|
||||
assert_eq!(first_mode(var("0").as_deref(), false), Windowed);
|
||||
for value in [None, var("1"), var(""), var("off"), var(" 0")] {
|
||||
assert_eq!(first_mode(value.as_deref(), false), Windowless, "{value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The pinned winit opens Wayland whenever a Wayland display is named and the app forces
|
||||
/// nothing, even with `DISPLAY` set; X11 only when forced or with no Wayland display.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[test]
|
||||
fn x11_is_what_winit_opens_not_what_the_session_says() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let picks = |forced, vars: &[(&str, &str)]| {
|
||||
winit_picks_x11(forced, |name| vars.iter().find(|(k, _)| *k == name).map(|(_, v)| std::ffi::OsString::from(v)))
|
||||
};
|
||||
let both = [("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "wayland-0")];
|
||||
assert!(picks(true, &both), "forced XWayland");
|
||||
assert!(!picks(false, &both), "unforced, Wayland wins");
|
||||
assert!(!picks(false, &[("DISPLAY", ":0"), ("WAYLAND_SOCKET", "3")]));
|
||||
assert!(picks(false, &[("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "")]), "an empty Wayland display is unset");
|
||||
assert!(!picks(false, &[]));
|
||||
let non_unicode = |name: &str| match name {
|
||||
"DISPLAY" => Some(":0".into()),
|
||||
"WAYLAND_DISPLAY" => Some(std::ffi::OsString::from_vec(b"w\xe9".to_vec())),
|
||||
_ => None,
|
||||
};
|
||||
assert!(winit_picks_x11(false, non_unicode), "winit reads a non-Unicode Wayland display as unset");
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
# DOCX corpus (local only)
|
||||
|
||||
This directory is where a local, real-world DOCX corpus can live for the opt-in
|
||||
`cargo xtask docx-corpus` harness. **The corpus is never committed.** `/corpus` is
|
||||
git-ignored; only this README is tracked. Never commit Word-produced files, documents
|
||||
you do not have the right to redistribute, or any proprietary template, theme, font
|
||||
or image. Word-produced documents are useful locally, including ones you made
|
||||
yourself, but they must stay untracked.
|
||||
|
||||
## Populate it
|
||||
|
||||
Put `.docx` files anywhere under this directory (subfolders are walked, symlinks are
|
||||
skipped):
|
||||
|
||||
```sh
|
||||
mkdir -p corpus/docx/mine
|
||||
cp ~/Documents/report.docx corpus/docx/mine/
|
||||
```
|
||||
|
||||
Useful sources for a local corpus:
|
||||
|
||||
- documents you wrote yourself, exported from Word, Google Docs, LibreOffice or Pages;
|
||||
- public-domain or openly licensed DOCX samples whose licence allows local testing;
|
||||
- synthetic files generated by WordCraft (`wordcraft-cli run --template sample --save …`);
|
||||
- deliberately broken files for the failure path (a text file renamed `.docx`, a
|
||||
truncated ZIP, a package missing `word/document.xml`).
|
||||
|
||||
Keep a note of where each file came from. If a corpus must be shared, share the
|
||||
manifest and the harness report, not the documents.
|
||||
|
||||
## Run it
|
||||
|
||||
```sh
|
||||
# The runner builds wordcraft-cli before every run (a no-op when it is current).
|
||||
cargo xtask docx-corpus --dir corpus/docx
|
||||
cargo xtask docx-corpus --dir corpus/docx --out target/docx-corpus/report.json
|
||||
cargo xtask docx-corpus --dir corpus/docx --all-pages
|
||||
cargo xtask docx-corpus --dir corpus/docx --timeout 120 --cli target/debug/wordcraft-cli
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
| Option | Meaning |
|
||||
|---|---|
|
||||
| `--dir <path>` | corpus directory (required) |
|
||||
| `--out <path>` | JSON report path (default `target/docx-corpus/report.json`); the Markdown summary is written beside it with an `.md` extension |
|
||||
| `--all-pages` | render every page instead of only page 1 (capped at 2,000 pages per file) |
|
||||
| `--timeout <secs>` | per-child-process timeout, default 60, maximum 3,600 |
|
||||
| `--cli <path>` | use a specific `wordcraft-cli` binary |
|
||||
| `-h`, `--help` | usage |
|
||||
|
||||
A missing or empty corpus directory is not an error: the command explains what is
|
||||
missing and exits successfully.
|
||||
|
||||
## What each file goes through
|
||||
|
||||
Every `.docx` is handled in child `wordcraft-cli` processes, each with the timeout
|
||||
above, so one hostile or hanging file cannot stop the run:
|
||||
|
||||
1. **Open + inspect** — `wordcraft-cli info` gives page and word counts; `wordcraft-cli text`
|
||||
gives the plain text baseline.
|
||||
2. **Render** — page 1 to PNG (`--all-pages` renders every page). Images go to
|
||||
`<report-stem>-artifacts/<index>-<file>/page-NNNN.png` beside the report.
|
||||
3. **Save** — `wordcraft-cli convert` writes a temporary `.docx` copy under the system
|
||||
temporary directory.
|
||||
4. **Reopen + compare** — the copy is opened again for page count and plain text. The
|
||||
temporary copy is then deleted.
|
||||
|
||||
The report records file name, bytes, open time, page count, word count, render time,
|
||||
round-trip time, rendered images, and every failure. Failures are classified as:
|
||||
|
||||
| Kind | Meaning |
|
||||
|---|---|
|
||||
| `open` | the file could not be opened or inspected (invalid package, encrypted, timeout, oversized, …) |
|
||||
| `render` | page rendering failed |
|
||||
| `save` | saving the temporary copy failed |
|
||||
| `reopen` | the saved copy could not be opened or its text read |
|
||||
| `text_mismatch` | reopened plain text differs from the original |
|
||||
| `page_count_delta` | reopened page count differs from the original |
|
||||
|
||||
The JSON report is deterministic for the same corpus and arguments apart from the
|
||||
timing fields: files are sorted by relative path, failure counts are always present,
|
||||
and there is no timestamp. The Markdown summary is a short human-readable table.
|
||||
|
||||
## Limits
|
||||
|
||||
- This harness measures open/render/save/reopen and text/page stability. It does **not**
|
||||
compare with Word's own rendering or page count, and it does not fix document bugs.
|
||||
A Word-vs-WordCraft visual comparison is a separate task.
|
||||
- PNG rendering is a smoke test that the page can be produced, not a fidelity score.
|
||||
- Files are treated as hostile: recursion depth, file count, file size, render pages and
|
||||
child output are capped, and symlinks are skipped. The caps are deliberately generous
|
||||
for normal documents; a file above them is reported as a failure rather than skipped
|
||||
silently.
|
||||
- The corpus and its reports stay local. `target/` is git-ignored too, so reports do not
|
||||
enter commits.
|
||||
@@ -21,32 +21,26 @@ pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
|
||||
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
|
||||
/// overrides the entire folder for isolated runs otherwise.
|
||||
pub fn settings_dir() -> Option<PathBuf> {
|
||||
settings_dir_with(CHOSEN.get(), |k| std::env::var_os(k))
|
||||
}
|
||||
|
||||
fn settings_dir_with(chosen: Option<&PathBuf>, mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
|
||||
if let Some(path) = chosen {
|
||||
if let Some(path) = CHOSEN.get() {
|
||||
return Some(path.clone());
|
||||
}
|
||||
if let Some(path) = env("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
platform_settings_dir_for(env)
|
||||
platform_settings_dir()
|
||||
}
|
||||
|
||||
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
|
||||
#[cfg(test)]
|
||||
fn platform_settings_dir() -> Option<PathBuf> {
|
||||
platform_settings_dir_for(|k| std::env::var_os(k))
|
||||
}
|
||||
|
||||
fn platform_settings_dir_for(mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
} else if cfg!(windows) {
|
||||
env("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
|
||||
std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
|
||||
} else {
|
||||
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("wordcraft"))
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.map(|c| c.join("wordcraft"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,26 +109,4 @@ mod tests {
|
||||
assert_eq!(key_path(dir, 7981), dir.join("control-key.local-7981"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_dir_is_the_apps_folder() {
|
||||
let default_dir = settings_dir_with(None, |key| match key {
|
||||
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("settings_dir should return Some when platform env var is set");
|
||||
let default_name = default_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||
assert!(default_name == "wordcraft" || default_name == "WordCraft", "{}", default_dir.display());
|
||||
assert_eq!(settings_dir_with(None, |_| None), None);
|
||||
|
||||
let override_dir = settings_dir_with(None, |key| (key == "WORDCRAFT_PROFILE_DIR").then(|| "/tmp/profile".into()));
|
||||
assert_eq!(override_dir.as_deref(), Some(Path::new("/tmp/profile")));
|
||||
|
||||
let empty_override = settings_dir_with(None, |key| match key {
|
||||
"WORDCRAFT_PROFILE_DIR" => Some("".into()),
|
||||
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(empty_override, Some(default_dir));
|
||||
}
|
||||
}
|
||||
|
||||
+3
-52
@@ -230,26 +230,10 @@ impl ChartAxis {
|
||||
pub const MAX_FMT: usize = 128;
|
||||
|
||||
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
|
||||
/// characters. A trailing space stays when it is part of the code: the character after `_`,
|
||||
/// `*` or `\`, or text inside quotes.
|
||||
/// characters.
|
||||
pub fn clean_fmt(s: &str) -> String {
|
||||
let chars: Vec<char> = s.chars().take(MAX_FMT * 4).skip_while(|c| c.is_whitespace() || c.is_control()).take(MAX_FMT).collect();
|
||||
let mut keep = 0;
|
||||
let mut quoted = false;
|
||||
let mut operand = false;
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
if !c.is_control() && (!c.is_whitespace() || operand || quoted) {
|
||||
keep = i + 1;
|
||||
}
|
||||
if operand {
|
||||
operand = false;
|
||||
} else if c == '"' {
|
||||
quoted = !quoted;
|
||||
} else if !quoted && matches!(c, '_' | '*' | '\\') {
|
||||
operand = true;
|
||||
}
|
||||
}
|
||||
chars[..keep].iter().map(|&c| if c.is_control() { ' ' } else { c }).collect()
|
||||
let s: String = s.chars().take(MAX_FMT * 4).map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
s.trim().chars().take(MAX_FMT).collect::<String>().trim_end().to_string()
|
||||
}
|
||||
|
||||
/// A chart WordCraft can edit.
|
||||
@@ -528,37 +512,4 @@ mod tests {
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_keeps_a_trailing_space_that_is_an_operand() {
|
||||
// `_`, `*` and `\` take the next character, so a final space after one is part of the code.
|
||||
assert_eq!(clean_fmt("0_ "), "0_ ");
|
||||
assert_eq!(clean_fmt("#,##0_ "), "#,##0_ ");
|
||||
assert_eq!(clean_fmt("0* "), "0* ");
|
||||
assert_eq!(clean_fmt("0\\ "), "0\\ ");
|
||||
assert_eq!(clean_fmt("0_ \n "), "0_ ");
|
||||
assert_eq!(clean_fmt("0\"a "), "0\"a ", "a space inside quotes is text");
|
||||
// Other spaces at the ends, and control characters, still go.
|
||||
assert_eq!(clean_fmt(" 0.00 \t"), "0.00");
|
||||
assert_eq!(clean_fmt("0_\n"), "0_");
|
||||
assert_eq!(clean_fmt("0\"a\" "), "0\"a\"");
|
||||
assert_eq!(clean_fmt("\\_ "), "\\_", "an escaped `_` takes no operand");
|
||||
assert_eq!(clean_fmt("0\u{1}0"), "0 0");
|
||||
assert_eq!(clean_fmt("_\u{1}"), "_");
|
||||
assert_eq!(clean_fmt(" \n "), "");
|
||||
let long = format!("{}_ ", "0".repeat(MAX_FMT - 2));
|
||||
assert_eq!(clean_fmt(&long), long, "a code of exactly MAX_FMT characters keeps its operand");
|
||||
|
||||
// Axis and series formats both go through the cleaner.
|
||||
let mut a = ChartAxis { fmt: Some("0_ ".into()), ..Default::default() };
|
||||
a.sanitize();
|
||||
assert_eq!(a.fmt.as_deref(), Some("0_ "));
|
||||
let mut spec = ChartSpec {
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], fmt: Some("#,##0_ ".into()), ..Default::default() }],
|
||||
categories: vec!["a".into()],
|
||||
..Default::default()
|
||||
};
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].fmt.as_deref(), Some("#,##0_ "));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -817,10 +817,7 @@ impl Document {
|
||||
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
|
||||
for blocks in stories {
|
||||
for b in blocks.iter_mut() {
|
||||
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
|
||||
p.normalize();
|
||||
p.reconcile_objects();
|
||||
});
|
||||
edit::each_para_mut(Arc::make_mut(b), 0, &mut Paragraph::normalize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-83
@@ -340,72 +340,6 @@ impl Paragraph {
|
||||
self.runs = out;
|
||||
}
|
||||
|
||||
/// Make the objects match the U+FFFC markers one to one (files lie): drop surplus objects,
|
||||
/// and remove markers past the last object. Runs must already cover the text.
|
||||
///
|
||||
/// One scan finds the unmatched markers, one pass removes them and the runs and objects are
|
||||
/// fixed up once, so the cost is linear in the paragraph however many markers are unmatched.
|
||||
/// There is no cap on the markers: stopping early would leave markers without objects.
|
||||
pub fn reconcile_objects(&mut self) {
|
||||
let keep = self.objects.len();
|
||||
// Byte offsets of the unmatched markers (every marker after the first `keep`), ascending.
|
||||
let mut seen = 0usize;
|
||||
let mut drop: Vec<usize> = Vec::new();
|
||||
for (i, _) in self.text.match_indices(OBJ) {
|
||||
crate::work::steps(1);
|
||||
if seen >= keep {
|
||||
drop.push(i);
|
||||
}
|
||||
seen += 1;
|
||||
}
|
||||
if self.objects.len() > seen {
|
||||
self.objects.truncate(seen);
|
||||
self.touch();
|
||||
}
|
||||
if drop.is_empty() {
|
||||
return;
|
||||
}
|
||||
let w = OBJ.len_utf8();
|
||||
if self.text.len() == drop.len() * w {
|
||||
// Emptying: the mark keeps the formatting of what was deleted (as `delete` does).
|
||||
let revisions = (self.mark.ins, self.mark.del, self.mark.fmt_change.clone());
|
||||
let mut mark = self.props_of_char(0).clone();
|
||||
(mark.ins, mark.del, mark.fmt_change) = revisions;
|
||||
self.mark = mark;
|
||||
}
|
||||
// Shrink the runs: each removed marker takes `w` bytes off the run that holds it.
|
||||
let mut d = 0usize;
|
||||
let mut start = 0usize;
|
||||
for r in &mut self.runs {
|
||||
crate::work::steps(1);
|
||||
let re = start + r.len;
|
||||
let mut cut = 0usize;
|
||||
while let Some(&off) = drop.get(d) {
|
||||
crate::work::steps(1);
|
||||
if off >= re {
|
||||
break;
|
||||
}
|
||||
if off >= start {
|
||||
cut += w;
|
||||
}
|
||||
d += 1;
|
||||
}
|
||||
start = re;
|
||||
r.len -= cut.min(r.len);
|
||||
}
|
||||
let mut out = String::with_capacity(self.text.len() - drop.len() * w);
|
||||
// The pieces between markers; marker `k` sits before piece `k + 1` and stays if matched.
|
||||
for (k, piece) in self.text.split(OBJ).enumerate() {
|
||||
if k > 0 && k <= keep {
|
||||
out.push(OBJ);
|
||||
}
|
||||
out.push_str(piece);
|
||||
}
|
||||
self.text = out;
|
||||
self.normalize();
|
||||
self.touch();
|
||||
}
|
||||
|
||||
/// Delete `a..b` (bytes). Objects inside are removed.
|
||||
pub fn delete(&mut self, a: usize, b: usize) -> Result<()> {
|
||||
let (a, b) = (a.min(b), a.max(b));
|
||||
@@ -619,8 +553,7 @@ impl Paragraph {
|
||||
/// The word around `off` (double-click): (start, end) without trailing space.
|
||||
pub fn word_at(&self, off: usize) -> (usize, usize) {
|
||||
let off = self.clamp(off);
|
||||
// Word's word unit takes a typographic apostrophe (’) like `'`, at either end too (#6517).
|
||||
let is_w = |c: char| crate::bidi::is_word_char(c) || c == '’';
|
||||
let is_w = |c: char| crate::bidi::is_word_char(c);
|
||||
let mut a = off;
|
||||
for (i, c) in self.text.get(..off).unwrap_or("").char_indices().rev() {
|
||||
if !is_w(c) {
|
||||
@@ -853,21 +786,6 @@ mod tests {
|
||||
assert_eq!(p.prev_boundary(0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_at_takes_a_typographic_apostrophe_like_a_straight_one() {
|
||||
// Byte offsets: `’` is three bytes. Word: `don’t ` (#6517).
|
||||
let p = Paragraph::with_text("don’t stop", CharProps::default());
|
||||
assert_eq!(p.word_at(1), (0, 8));
|
||||
assert_eq!(p.word_at(2), (0, 8));
|
||||
let p = Paragraph::with_text("the dogs’ bone", CharProps::default());
|
||||
assert_eq!(p.word_at(5), (4, 12));
|
||||
let p = Paragraph::with_text("’tis here", CharProps::default());
|
||||
assert_eq!(p.word_at(3), (0, 7));
|
||||
assert_eq!(p.word_at(4), (0, 7));
|
||||
let p = Paragraph::with_text("well-known", CharProps::default());
|
||||
assert_eq!(p.word_at(1), (0, 4));
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#[test]
|
||||
fn edits_keep_runs_consistent(ops in proptest::collection::vec((0u8..4, 0usize..40, 0usize..40, "[a-zé ]{0,5}"), 0..40)) {
|
||||
|
||||
@@ -929,143 +929,6 @@ fn missing_pictures_are_capped_deduplicated_and_not_content() {
|
||||
assert_eq!(MissingPictureReason::ExternalTarget.label(), "external target");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_runs_reconciles_objects_with_markers() {
|
||||
let c = CharProps::default();
|
||||
let markers = |p: &Paragraph| p.text.chars().filter(|ch| *ch == '\u{FFFC}').count();
|
||||
let build = || {
|
||||
let mut d = Document::from_text("abc");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.insert_object(1, fs("A"), &c).unwrap();
|
||||
p.insert_object(5, fs("B"), &c).unwrap();
|
||||
d
|
||||
};
|
||||
// More objects than markers (as a hand-edited .json can say): the surplus goes.
|
||||
let mut d = build();
|
||||
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().objects.push(fs("C"));
|
||||
d.normalize_runs();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!((markers(p), p.objects.len()), (2, 2));
|
||||
assert_eq!(p.objects, vec![fs("A"), fs("B")]);
|
||||
// More markers than objects: the unmatched marker goes, runs still cover the text.
|
||||
let mut d = build();
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.text.push('\u{FFFC}');
|
||||
p.runs[0].len += 3;
|
||||
d.normalize_runs();
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!((markers(p), p.objects.len()), (2, 2));
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
|
||||
// Deleting the first marker keeps B on the second.
|
||||
p.delete(1, 4).unwrap();
|
||||
assert_eq!(p.objects, vec![fs("B")]);
|
||||
// The cost is linear: the markers and runs `reconcile_objects` walks (`crate::work`), not a
|
||||
// timing. 8x the unmatched markers cost about 8x the steps, far more if each removal rescans.
|
||||
let reconcile = |extra: usize| {
|
||||
let mut p = Paragraph::default();
|
||||
p.objects = vec![fs("A")];
|
||||
p.text = format!("\u{FFFC}{}x", "\u{FFFC}".repeat(extra));
|
||||
p.runs = vec![Run { len: p.text.len(), props: c.clone() }];
|
||||
crate::work::count(|| {
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "\u{FFFC}x");
|
||||
std::hint::black_box(&p);
|
||||
})
|
||||
};
|
||||
let (s1, s8) = (reconcile(2_000), reconcile(16_000));
|
||||
assert!(s1 > 0, "no steps counted, so the walk this test watches no longer counts them (crate::work)");
|
||||
let ratio = s8 as f64 / s1 as f64;
|
||||
assert!(ratio <= 12.0, "8x the markers cost {ratio:.1}x the steps ({s1} -> {s8})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_drops_many_unmatched_markers_in_one_pass() {
|
||||
let c = CharProps::default();
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.insert_object(0, fs("A"), &c).unwrap();
|
||||
p.insert_object(p.text.len(), fs("B"), &c).unwrap();
|
||||
let extra = 50_000;
|
||||
// "<A>x<B>" followed by many unmatched markers around more text, in one run.
|
||||
p.text = format!("\u{FFFC}x\u{FFFC}{}y{}z", "\u{FFFC}".repeat(extra), "\u{FFFC}".repeat(extra));
|
||||
p.runs = vec![Run { len: p.text.len(), props: c.clone() }];
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "\u{FFFC}x\u{FFFC}yz");
|
||||
assert_eq!(p.objects, vec![fs("A"), fs("B")]);
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_keeps_every_matched_object() {
|
||||
let c = CharProps::default();
|
||||
let n = 100_050;
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.text = "\u{FFFC}".repeat(n);
|
||||
p.objects = (0..n).map(|_| fs("A")).collect();
|
||||
p.runs = vec![Run { len: p.text.len(), props: c }];
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.objects.len(), n);
|
||||
assert_eq!(p.text.matches('\u{FFFC}').count(), n);
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_keeps_run_props_across_several_runs() {
|
||||
let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() });
|
||||
let italic = CharProps { italic: Some(true), ..CharProps::default() };
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.objects = vec![fs("A")];
|
||||
// Runs: plain "a<A>b<X>" | bold "<X><X>" (only unmatched, becomes empty) | italic "<X>c<X>" | plain "d".
|
||||
let x = "\u{FFFC}";
|
||||
let parts = [
|
||||
(format!("a\u{FFFC}b{x}"), plain.clone()),
|
||||
(format!("{x}{x}"), bold),
|
||||
(format!("{x}c{x}"), italic.clone()),
|
||||
("d".to_string(), plain.clone()),
|
||||
];
|
||||
p.text = parts.iter().map(|(t, _)| t.as_str()).collect();
|
||||
p.runs = parts.iter().map(|(t, c)| Run { len: t.len(), props: c.clone() }).collect();
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "a\u{FFFC}bcd");
|
||||
assert_eq!(p.objects, vec![fs("A")]);
|
||||
let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect();
|
||||
// "a<A>b" plain (5 bytes: 1 + 3 + 1), "c" italic, "d" plain.
|
||||
assert_eq!(got, vec![(5, plain.clone()), (1, italic), (1, plain)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_marker_on_run_boundary_shrinks_the_right_run() {
|
||||
let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() });
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
let x = "\u{FFFC}";
|
||||
// plain "ab" | bold "<X>cd" : the marker is the first byte of the second run.
|
||||
p.text = format!("ab{x}cd");
|
||||
p.runs = vec![Run { len: 2, props: plain.clone() }, Run { len: 2 + x.len(), props: bold.clone() }];
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "abcd");
|
||||
let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect();
|
||||
assert_eq!(got, vec![(2, plain), (2, bold)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_all_unmatched_markers_empties_the_paragraph() {
|
||||
let bold = CharProps { bold: Some(true), ..CharProps::default() };
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.text = "\u{FFFC}".repeat(3);
|
||||
p.runs = vec![Run { len: p.text.len(), props: bold.clone() }];
|
||||
p.mark = CharProps { ins: Some(7), ..CharProps::default() };
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "");
|
||||
assert!(p.objects.is_empty());
|
||||
assert!(p.runs.is_empty());
|
||||
// The mark takes the deleted formatting but keeps its own revision.
|
||||
assert_eq!(p.mark, CharProps { bold: Some(true), ins: Some(7), ..CharProps::default() });
|
||||
}
|
||||
|
||||
fn shape_with_id(id: u32, story: Option<u32>) -> InlineObject {
|
||||
InlineObject::Shape {
|
||||
kind: para::ShapeKind::Rectangle,
|
||||
|
||||
@@ -177,19 +177,6 @@ fn glossary_value_from_shared(
|
||||
})
|
||||
}
|
||||
|
||||
fn note_separators_from_shared(
|
||||
source: craft_wordmodel::NoteSeparators,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::NoteSeparators, DocxError> {
|
||||
let craft_wordmodel::NoteSeparators { separator, continuation_separator, continuation_notice } = source;
|
||||
let mut blocks = |b: Option<craft_wordmodel::Blocks>| b.map(|b| blocks_from_shared(b, graphics)).transpose();
|
||||
Ok(wordcraft_doc::NoteSeparators {
|
||||
separator: blocks(separator)?,
|
||||
continuation_separator: blocks(continuation_separator)?,
|
||||
continuation_notice: blocks(continuation_notice)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Result<wordcraft_doc::MissingPictures, DocxError> {
|
||||
let mut target = wordcraft_doc::MissingPictures::default();
|
||||
target.truncated = source.truncated;
|
||||
@@ -252,8 +239,8 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
|
||||
document.core = convert(core)?;
|
||||
document.sources = convert(sources)?;
|
||||
document.custom_props = convert(custom_props)?;
|
||||
document.footnote_separators = note_separators_from_shared(footnote_separators, &mut graphics)?;
|
||||
document.endnote_separators = note_separators_from_shared(endnote_separators, &mut graphics)?;
|
||||
document.footnote_separators = convert(footnote_separators)?;
|
||||
document.endnote_separators = convert(endnote_separators)?;
|
||||
document.media = media;
|
||||
document.passthrough = passthrough;
|
||||
document.glossary = glossary.into_iter().map(|g| glossary_value_from_shared(g, &mut graphics)).collect::<Result<_, _>>()?;
|
||||
|
||||
@@ -2444,36 +2444,6 @@ fn note_separators_and_continuation_notice_round_trip() {
|
||||
check(&wordcraft_docx::read(&out).unwrap());
|
||||
}
|
||||
|
||||
/// A picture frame shape in a footnote or endnote separator opens as the same shape kind as it does
|
||||
/// in the body, instead of failing the whole document. (The test name dates from when the body
|
||||
/// opened this shape as a rectangle.)
|
||||
#[test]
|
||||
fn a_frame_shape_in_a_note_separator_reads_as_a_rectangle() {
|
||||
let frame = r#"<w:r><w:drawing><wp:inline><wp:extent cx="508000" cy="381000"/><wp:docPr id="1" name="F"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#;
|
||||
let notes = |root: &str, item: &str| {
|
||||
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{frame}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
|
||||
};
|
||||
let footnotes = notes("footnotes", "footnote");
|
||||
let endnotes = notes("endnotes", "endnote");
|
||||
let bytes = docx(
|
||||
&format!("<w:p>{frame}</w:p>"),
|
||||
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml")],
|
||||
&[("word/footnotes.xml", &footnotes), ("word/endnotes.xml", &endnotes)],
|
||||
);
|
||||
let d = wordcraft_docx::read(&bytes).unwrap();
|
||||
let shapes = |p: &Paragraph| -> Vec<(ShapeKind, f32)> {
|
||||
p.objects.iter().filter_map(|o| if let InlineObject::Shape { kind, w, .. } = o { Some((*kind, *w)) } else { None }).collect()
|
||||
};
|
||||
let in_body = shapes(d.body[0].as_para().unwrap());
|
||||
assert_eq!(in_body.len(), 1, "{in_body:?}");
|
||||
assert_eq!(in_body[0].1, 40.0);
|
||||
assert_eq!(in_body[0].0, ShapeKind::Frame);
|
||||
for separators in [&d.footnote_separators, &d.endnote_separators] {
|
||||
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
|
||||
assert_eq!(shapes(sep), in_body);
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #534: East Asian number formats are read, labelled and written back as they were; a
|
||||
/// value the format doesn't define is decimal, and a level without `w:ind` has no indent.
|
||||
#[test]
|
||||
|
||||
@@ -362,10 +362,10 @@ fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
|
||||
if !copied {
|
||||
return Err(CmdError::Failed("the member vanished".into()));
|
||||
}
|
||||
let text = f.clipboard_text();
|
||||
let r = super::edit::copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
Ok(r)
|
||||
s.clipboard_text = f.clipboard_text();
|
||||
s.clip_history.push(&f, &s.clipboard_text);
|
||||
s.clipboard = Some(f);
|
||||
Ok(super::edit::copy_result(s))
|
||||
}
|
||||
|
||||
/// Take member `index` out of the canvas at `pos`; the canvas stays selected.
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
//! Caret movement and selection.
|
||||
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::math_edit::MathPos;
|
||||
use wordcraft_doc::para::OBJ;
|
||||
use wordcraft_doc::{InlineObject, Pos, StoryRef};
|
||||
use wordcraft_doc::{Pos, StoryRef};
|
||||
use wordcraft_layout::ViewMode;
|
||||
|
||||
use super::{parse_pos, sel_result};
|
||||
@@ -121,31 +119,9 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
if bidi_para(s) {
|
||||
return visual_lr(s, v, is_left);
|
||||
}
|
||||
if !extend(v)
|
||||
&& !s.math_left
|
||||
&& let Some(r) = into_equation(s, is_left)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
mv(s, v, if is_left { left } else { right })
|
||||
}
|
||||
|
||||
/// Left/Right onto an equation opens it, at its end from the right and at its start from the
|
||||
/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then
|
||||
/// moves on instead of going back in. A caret.left/right that itself left an equation (sent
|
||||
/// while editing one) moves on too.
|
||||
fn into_equation(s: &mut Session, is_left: bool) -> Option<CmdResult> {
|
||||
let f = s.sel.focus.clone();
|
||||
let off = if is_left { f.off.checked_sub(OBJ.len_utf8())? } else { f.off };
|
||||
if !matches!(s.doc.para_at(&f)?.object_at(off), Some(InlineObject::Equation { .. })) {
|
||||
return None;
|
||||
}
|
||||
s.sel = Selection::caret(Pos { off, ..f });
|
||||
s.goal_x = None;
|
||||
s.pending = None;
|
||||
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
|
||||
}
|
||||
|
||||
/// Left/Right in bidirectional text: one caret position to the left or right on the screen.
|
||||
/// Past the line's visual end the caret goes to the neighbouring line in reading order (the
|
||||
/// previous line when moving toward the paragraph's start edge).
|
||||
@@ -300,11 +276,7 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
}
|
||||
let Some(c) = l.caret_on(&from, s.page_hint) else { return sel_result(s) };
|
||||
let np = if dir < 0 { c.page.saturating_sub(1) } else { (c.page + 1).min(l.pages.len().saturating_sub(1)) };
|
||||
let to = if np == c.page {
|
||||
if dir < 0 { s.doc.start_of(from.story) } else { s.doc.end_of(from.story) }
|
||||
} else {
|
||||
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
|
||||
};
|
||||
let to = l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from);
|
||||
s.page_hint = np;
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
|
||||
@@ -244,10 +244,10 @@ fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
|
||||
rows.push(row_text(s, &a, &b));
|
||||
blocks.push(Block::Para(para));
|
||||
}
|
||||
let text = rows.join("\n");
|
||||
s.clipboard_text = rows.join("\n");
|
||||
let media = s.doc.media_of_blocks(&blocks);
|
||||
let f = Fragment { blocks, parts, media };
|
||||
super::edit::copy_result(s, &f, &text)
|
||||
s.clipboard = Some(Fragment { blocks, parts, media });
|
||||
Ok(super::edit::copy_result(s))
|
||||
}
|
||||
|
||||
/// Delete each row's piece (bottom up, so earlier positions stay valid) and leave the caret at
|
||||
|
||||
@@ -279,22 +279,6 @@ fn content_base(s: &Session, r: &ControlRange) -> CharProps {
|
||||
content_props(&s.doc, &props)
|
||||
}
|
||||
|
||||
/// The formatting of what replaces a control's content: typed text, a list entry, a date or a
|
||||
/// check box's mark. In place of the placeholder, that is the control's own run properties
|
||||
/// (ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style: the
|
||||
/// showing placeholder's own character style is that style, whatever a producer called it (Word
|
||||
/// localizes only the id; another program may localize the name too). In place of a value, it is
|
||||
/// that value's formatting.
|
||||
fn replacement_props(s: &Session, r: &ControlRange) -> CharProps {
|
||||
if !r.control.showing_placeholder {
|
||||
return content_base(s, r);
|
||||
}
|
||||
match &r.control.run_props {
|
||||
Some(rp) => content_props(&s.doc, rp),
|
||||
None => CharProps { style: None, ..content_base(s, r) },
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Rules for typing and deleting
|
||||
|
||||
@@ -343,8 +327,14 @@ pub fn prepare_edit(s: &mut Session) -> Result<Option<CharProps>, CmdError> {
|
||||
if !r.control.showing_placeholder || !r.contains(&b) {
|
||||
return Ok(None);
|
||||
}
|
||||
// Text typed in place of the placeholder takes the control's own run properties, as in Word.
|
||||
let props = replacement_props(s, &r);
|
||||
// Text typed in place of the placeholder takes the control's own run properties (Word, and
|
||||
// ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style. The
|
||||
// showing placeholder's own character style is that style, whatever a producer called it
|
||||
// (Word localizes only the id; another program may localize the name too).
|
||||
let props = match &r.control.run_props {
|
||||
Some(rp) => content_props(&s.doc, rp),
|
||||
None => CharProps { style: None, ..content_base(s, &r) },
|
||||
};
|
||||
s.sel = Selection { anchor: r.content_start(), focus: r.end.clone() };
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
c.showing_placeholder = false;
|
||||
@@ -676,7 +666,7 @@ fn toggle_check_box(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
let now = p::bool(v, "value").unwrap_or(!checked);
|
||||
let (ch, font) = if now { (*checked_char, checked_font) } else { (*unchecked_char, unchecked_font) };
|
||||
let mut props = replacement_props(s, &r);
|
||||
let mut props = content_base(s, &r);
|
||||
if !font.is_empty() {
|
||||
props.font = Some(font.clone());
|
||||
}
|
||||
@@ -706,7 +696,7 @@ fn choose_item(s: &mut Session, v: &Value) -> CmdResult {
|
||||
return Err(CmdError::Params("give index, value or text".into()));
|
||||
};
|
||||
let Some(item) = item.cloned() else { return Err(CmdError::Params("no such entry".into())) };
|
||||
let props = replacement_props(s, &r);
|
||||
let props = content_base(s, &r);
|
||||
let end = set_content(s, &r, &item.display, &props)?;
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
if let ControlKind::ComboBox { last_value, .. } | ControlKind::DropDown { last_value, .. } = &mut c.kind {
|
||||
@@ -726,7 +716,7 @@ fn set_date(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
let (y, m, d) = p::str(v, "date").and_then(parse_date).ok_or_else(|| CmdError::Params("date: YYYY-MM-DD".into()))?;
|
||||
let text = format_date_value(format, y, m, d);
|
||||
let props = replacement_props(s, &r);
|
||||
let props = content_base(s, &r);
|
||||
let end = set_content(s, &r, &text, &props)?;
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
if let ControlKind::Date { full_date, .. } = &mut c.kind {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::{Border, BorderStyle, Borders, CharProps, LineSpacing, Rgb, TextColor};
|
||||
use wordcraft_doc::{StyleKind, Watermark, styles};
|
||||
use wordcraft_doc::{Watermark, styles};
|
||||
|
||||
use super::sel_result;
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
|
||||
@@ -209,16 +209,9 @@ fn para_spacing(s: &mut Session, v: &Value) -> CmdResult {
|
||||
"double" => (0.0, 8.0, 2.0),
|
||||
_ => (0.0, 8.0, 1.15),
|
||||
};
|
||||
let st = Arc::make_mut(&mut s.doc.styles);
|
||||
let apply = |p: &mut wordcraft_doc::props::ParaProps| {
|
||||
p.space_before = Some(before);
|
||||
p.space_after = Some(after);
|
||||
p.line_spacing = Some(LineSpacing::Multiple(line));
|
||||
};
|
||||
apply(&mut st.default_para);
|
||||
for style in st.styles.iter_mut().filter(|style| style.builtin && style.kind == StyleKind::Paragraph) {
|
||||
apply(&mut style.para);
|
||||
}
|
||||
Arc::make_mut(&mut s.doc.styles).default_para.space_before = Some(before);
|
||||
Arc::make_mut(&mut s.doc.styles).default_para.space_after = Some(after);
|
||||
Arc::make_mut(&mut s.doc.styles).default_para.line_spacing = Some(LineSpacing::Multiple(line));
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -294,7 +287,7 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult {
|
||||
};
|
||||
let blocks: Vec<usize> = match p::str(v, "applyTo") {
|
||||
Some("document") => s.doc.sections().iter().map(|(end, _)| *end).collect(),
|
||||
Some("section") | None => vec![super::page::section_end_of_focus(s)],
|
||||
Some("section") | None => vec![s.sel.focus.path.0.first().copied().unwrap_or(0) as usize],
|
||||
Some(x) => return Err(CmdError::Params(format!("unknown `applyTo` `{x}`"))),
|
||||
};
|
||||
for block in blocks {
|
||||
@@ -302,34 +295,3 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::{Document, Style};
|
||||
|
||||
#[test]
|
||||
fn paragraph_spacing_preset_updates_builtin_styles_and_keeps_custom_styles() {
|
||||
let mut s = Session::new(Document::new());
|
||||
Arc::make_mut(&mut s.doc.styles).styles.push(Style {
|
||||
id: "CustomSpacing".into(),
|
||||
name: "Custom Spacing".into(),
|
||||
kind: StyleKind::Paragraph,
|
||||
builtin: false,
|
||||
para: wordcraft_doc::props::ParaProps { space_after: Some(24.0), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
s.run("design.paragraphSpacing", &json!({"value": "double"})).unwrap();
|
||||
|
||||
let normal = s.doc.styles.get("Normal").unwrap();
|
||||
assert_eq!(normal.para.line_spacing, Some(LineSpacing::Multiple(2.0)));
|
||||
let heading = s.doc.styles.get("Heading1").unwrap();
|
||||
assert_eq!((heading.para.space_before, heading.para.space_after), (Some(0.0), Some(8.0)));
|
||||
assert_eq!(heading.para.line_spacing, Some(LineSpacing::Multiple(2.0)));
|
||||
let custom = s.doc.styles.get("CustomSpacing").unwrap();
|
||||
assert_eq!(custom.para.space_after, Some(24.0));
|
||||
assert_eq!(custom.para.line_spacing, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,28 +208,29 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
|
||||
None if a == b => return Ok(json!({"text": ""})),
|
||||
None => s.doc.copy_range(&a, &b),
|
||||
};
|
||||
let text = f.clipboard_text();
|
||||
let r = copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
Ok(r)
|
||||
s.clipboard_text = f.clipboard_text();
|
||||
s.clip_history.push(&f, &s.clipboard_text);
|
||||
s.clipboard = Some(f);
|
||||
Ok(copy_result(s))
|
||||
}
|
||||
|
||||
/// What Copy and Cut return: the clipboard's text, and the copy as HTML (equations as MathML,
|
||||
/// #816) and as RTF for the host to put on the system clipboard too, so other programs keep the
|
||||
/// formatting; and for a copy of one equation alone, its MathML (#1297).
|
||||
///
|
||||
/// The copy goes on the clipboard whole or not at all: a copy whose HTML or RTF cannot be made
|
||||
/// is refused, and the clipboard keeps what it held.
|
||||
pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResult {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
d.media = s.doc.media.clone();
|
||||
}
|
||||
let html = wordcraft_formats::html::export_fragment(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as HTML: {e}")))?;
|
||||
let rtf = wordcraft_formats::rtf::export(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as RTF: {e}")))?;
|
||||
let mut r = json!({"text": text});
|
||||
for (k, v) in [("html", &html), ("rtf", &rtf)] {
|
||||
pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
|
||||
Some(f) => {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
d.media = s.doc.media.clone();
|
||||
}
|
||||
(wordcraft_formats::html::export_fragment(&d), wordcraft_formats::rtf::export(&d))
|
||||
}
|
||||
None => (String::new(), String::new()),
|
||||
};
|
||||
let mut r = json!({"text": s.clipboard_text});
|
||||
for (k, v) in [("html", &s.clipboard_html), ("rtf", &s.clipboard_rtf)] {
|
||||
if !v.is_empty() {
|
||||
r[k] = json!(v);
|
||||
}
|
||||
@@ -238,16 +239,10 @@ pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResul
|
||||
// ("MathML" on Windows, `public.mathml.presentation` on macOS; #1297). Word looks for them
|
||||
// before anything else when it pastes; a copy with text around the equation doesn't offer
|
||||
// them, so pasting it keeps the text.
|
||||
if let Some((linear, display)) = f.sole_equation() {
|
||||
if let Some((linear, display)) = s.clipboard.as_ref().and_then(|f| f.sole_equation()) {
|
||||
r["mathml"] = json!(wordcraft_formats::mathml::linear_to_mathml(linear, display));
|
||||
}
|
||||
// The copy is on the clipboard now: its text, its fragment and its HTML and RTF flavours,
|
||||
// all at once.
|
||||
s.clipboard_text = text.to_string();
|
||||
s.clipboard = Some(f.clone());
|
||||
s.clipboard_html = html;
|
||||
s.clipboard_rtf = rtf;
|
||||
Ok(r)
|
||||
r
|
||||
}
|
||||
|
||||
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
|
||||
|
||||
@@ -261,11 +261,6 @@ fn insert_nodes_as_equation(s: &mut Session, nodes: Arg, v: &Value) -> CmdResult
|
||||
/// Starts editing the equation at the caret, materializing lazy nodes and clamping the requested
|
||||
/// position, and returns the equation and caret.
|
||||
fn edit(s: &mut Session, v: &Value) -> CmdResult {
|
||||
edit_at(s, v.get("pos").and_then(|p| serde_json::from_value::<MathPos>(p.clone()).ok()))
|
||||
}
|
||||
|
||||
/// [`edit`] at `pos` in the equation, or at its end without one.
|
||||
pub(super) fn edit_at(s: &mut Session, pos: Option<MathPos>) -> CmdResult {
|
||||
let at = equation_at_caret(s).ok_or_else(|| CmdError::Disabled("no equation at the caret".into()))?;
|
||||
let nodes = match s.doc.para_at(&at).and_then(|p| p.object_at(at.off)) {
|
||||
Some(InlineObject::Equation { math, linear, .. }) => {
|
||||
@@ -277,7 +272,8 @@ pub(super) fn edit_at(s: &mut Session, pos: Option<MathPos>) -> CmdResult {
|
||||
}
|
||||
_ => return Err(CmdError::Failed("no equation there".into())),
|
||||
};
|
||||
let pos = pos.unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes)));
|
||||
let pos =
|
||||
v.get("pos").and_then(|p| serde_json::from_value::<MathPos>(p.clone()).ok()).unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes)));
|
||||
let Some(session) = crate::next_math_session() else {
|
||||
return Err(CmdError::Failed("no equation editing session available".into()));
|
||||
};
|
||||
|
||||
@@ -59,74 +59,6 @@ fn structures_symbols_and_navigation() {
|
||||
assert!(s.math.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn left_and_right_step_into_an_equation_next_to_the_caret() {
|
||||
let mut s = session();
|
||||
s.run("document.setText", &json!({"text": "ab\ncd"})).unwrap();
|
||||
let p0 = s.doc.start_of(s.sel.focus.story);
|
||||
let p1 = Pos { path: s.doc.next_para(p0.story, &p0.path).unwrap(), ..p0.clone() };
|
||||
// An equation between "a" and "b", and another one between "c" and "d".
|
||||
for p in [&p0, &p1] {
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p.clone() }})).unwrap();
|
||||
s.run("insert.equation", &json!({"linear": "x+y", "edit": false})).unwrap();
|
||||
}
|
||||
let after = 1 + OBJ.len_utf8();
|
||||
let editing = |s: &Session| s.math.as_ref().map(|m| (m.at.path.clone(), m.at.off, m.pos.clone()));
|
||||
|
||||
// Right from "a|" enters the equation at its start.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
|
||||
s.run("caret.right", &json!({})).unwrap();
|
||||
assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default())));
|
||||
// Leaving it to the right, the next Right goes on to the text, not back in.
|
||||
for _ in 0..10 {
|
||||
if s.math.is_none() {
|
||||
break;
|
||||
}
|
||||
s.run("equation.move", &json!({"dir": "right"})).unwrap();
|
||||
}
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after));
|
||||
s.run("caret.right", &json!({})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + 1));
|
||||
|
||||
// Left from just after the equation in the second paragraph enters it at its end.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap();
|
||||
s.run("caret.left", &json!({})).unwrap();
|
||||
let end = MathPos::new(Vec::new(), me::units(&nodes_of(&s, &Pos { off: 1, ..p1.clone() }).unwrap()));
|
||||
assert_eq!(editing(&s), Some((p1.path.clone(), 1, end)));
|
||||
for _ in 0..10 {
|
||||
if s.math.is_none() {
|
||||
break;
|
||||
}
|
||||
s.run("equation.move", &json!({"dir": "left"})).unwrap();
|
||||
}
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1));
|
||||
s.run("caret.left", &json!({})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 0));
|
||||
|
||||
// Shift+Right selects over the equation, as before.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
|
||||
s.run("caret.right", &json!({"extend": true})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.anchor.off, s.sel.focus.off), (true, 1, after));
|
||||
|
||||
// caret.left/right sent while editing (the arrow keys go to equation.move instead) leave
|
||||
// the equation and move on, as before, rather than opening the equation they land next to.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: after, ..p0.clone() }})).unwrap();
|
||||
s.run("equation.edit", &json!({})).unwrap();
|
||||
s.run("caret.left", &json!({})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1));
|
||||
// With two equations side by side, Right from the first goes on past the second.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap();
|
||||
s.run("insert.equation", &json!({"linear": "z", "edit": false})).unwrap();
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p1.clone() }})).unwrap();
|
||||
s.run("equation.edit", &json!({})).unwrap();
|
||||
s.run("caret.right", &json!({})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + OBJ.len_utf8()));
|
||||
// That holds only for the command that left the equation: the next Right opens one again.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
|
||||
s.run("caret.right", &json!({})).unwrap();
|
||||
assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbering_conversion_and_display() {
|
||||
let mut s = session();
|
||||
@@ -703,24 +635,3 @@ fn a_math_name_is_corrected_by_any_character_that_cannot_continue_it() {
|
||||
s.run("equation.type", &json!({"text": r"\alpha+"})).unwrap();
|
||||
assert_eq!(linear(&s), r"\alpha+");
|
||||
}
|
||||
|
||||
/// Paste Formatting keeps an open equation open (matching other formatting commands and
|
||||
/// `cmd::column`), whereas content-pasting commands leave the equation first.
|
||||
#[test]
|
||||
fn paste_formatting_keeps_an_open_equation_open() {
|
||||
let mut s = session();
|
||||
s.run("text.insert", &json!({"text": "source "})).unwrap();
|
||||
s.run("select.text", &json!({"text": "source"})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("edit.copyFormat", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.equation", &json!({"linear": "x"})).unwrap();
|
||||
let before = s.math.clone();
|
||||
assert!(before.is_some());
|
||||
|
||||
s.run("edit.pasteFormat", &json!({})).unwrap();
|
||||
assert_eq!(s.math, before, "edit.pasteFormat keeps the open equation open");
|
||||
|
||||
s.run("edit.pasteText", &json!({"text": "y"})).unwrap();
|
||||
assert!(s.math.is_none(), "edit.pasteText closes the open equation");
|
||||
}
|
||||
|
||||
@@ -94,9 +94,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("file.save", "Save", "File", save)
|
||||
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
|
||||
.params(r#"{"path"?: string (required with `copy`), "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy at `path`, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`)}"#)
|
||||
.params(r#"{"path"?: string, "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save), "copy"?: bool (as file.save)}"#).pure(),
|
||||
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save)}"#).pure(),
|
||||
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
|
||||
// to undo; it marks the document as changed itself.
|
||||
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
|
||||
@@ -342,8 +342,6 @@ pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let path = p::req_str(v, "path")?;
|
||||
let (mut doc, _) = read_document(s, path, v)?;
|
||||
doc.settings.attached_template = Some(path.to_string());
|
||||
// A new document: not created when the template was. Saving stamps its creation date.
|
||||
doc.core.created.clear();
|
||||
if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() {
|
||||
s.set_document(doc);
|
||||
} else {
|
||||
@@ -395,14 +393,6 @@ fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Executes `file.save`: writes the document or text to disk, preserving exact file text for
|
||||
/// unedited Markdown files, and updating session path and dirty state.
|
||||
fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// A copy (File › Export, #6131) is written and nothing else: the document keeps its own file,
|
||||
// its unsaved changes and its save stamps, so the next Save still goes to the original.
|
||||
// It never falls back to the document's own file or opens the Save As picker (whose answer is
|
||||
// an ordinary save that adopts the file).
|
||||
let as_copy = p::bool(v, "copy") == Some(true);
|
||||
if as_copy && p::str(v, "path").is_none() {
|
||||
return Err(CmdError::Params("`copy` needs a `path`: the copy has to go somewhere".into()));
|
||||
}
|
||||
let path = match p::str(v, "path").map(std::path::PathBuf::from).or_else(|| s.path.clone()) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
@@ -411,9 +401,6 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
};
|
||||
check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?;
|
||||
if as_copy && v.get("password").is_some_and(|pw| !pw.is_null()) {
|
||||
return Err(CmdError::Params("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into()));
|
||||
}
|
||||
if let Some(pw) = v.get("password").filter(|pw| !pw.is_null()) {
|
||||
let Some(pw) = pw.as_str().filter(|pw| !pw.is_empty()) else {
|
||||
return Err(CmdError::Params("`password` must be a non-empty string (file.encrypt removes a password)".into()));
|
||||
@@ -456,14 +443,11 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Some(text) => crate::io::save_text_path(&path, text),
|
||||
None => crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts),
|
||||
};
|
||||
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
|
||||
if written.is_err() || as_copy {
|
||||
if let Err(e) = written {
|
||||
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
|
||||
return Err(CmdError::Failed(e));
|
||||
}
|
||||
written.map_err(CmdError::Failed)?;
|
||||
if as_copy {
|
||||
return Ok(json!({"saved": true, "path": path.to_string_lossy(), "encrypted": encrypted, "copy": true}));
|
||||
}
|
||||
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
|
||||
// A save in a format that doesn't keep everything (plain text, Markdown, a page image) is a
|
||||
// copy, except over the document's own file: a note.txt opened and saved is saved (#2376).
|
||||
// A Markdown file saved as another one loses nothing its own save wouldn't: it moves there.
|
||||
|
||||
@@ -209,8 +209,7 @@ fn target(s: &Session) -> Option<(Pos, Pos)> {
|
||||
return Some((a, b));
|
||||
}
|
||||
let p = s.doc.para_at(&a)?;
|
||||
// Word takes a typographic apostrophe (’) like `'` here (#6517).
|
||||
let is_w = |c: char| c.is_alphanumeric() || matches!(c, '\'' | '’' | '_');
|
||||
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '_';
|
||||
let before = p.text.get(..a.off)?.chars().next_back();
|
||||
let after = p.text.get(a.off..)?.chars().next();
|
||||
if before.is_some_and(is_w) && after.is_some_and(is_w) {
|
||||
@@ -352,16 +351,6 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
|
||||
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
|
||||
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
|
||||
let chars = resolved(s);
|
||||
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
|
||||
return !chars.first().is_some_and(has);
|
||||
}
|
||||
!chars.iter().all(has)
|
||||
}
|
||||
|
||||
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
|
||||
/// complex-script bold.
|
||||
fn shown_bold(r: &ResolvedChar) -> bool {
|
||||
@@ -377,7 +366,7 @@ fn shown_italic(r: &ResolvedChar) -> bool {
|
||||
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
|
||||
let on = match p::bool(v, "value") {
|
||||
Some(b) => b,
|
||||
None => turns_on(s, get),
|
||||
None => !resolved(s).iter().all(get),
|
||||
};
|
||||
apply(s, &|c| set(c, on))
|
||||
}
|
||||
@@ -387,7 +376,7 @@ fn underline(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let on = match (p::bool(v, "value"), style) {
|
||||
(Some(b), _) => b,
|
||||
(None, Some(_)) => true,
|
||||
(None, None) => turns_on(s, |r| r.underline != Underline::None),
|
||||
(None, None) => !resolved(s).iter().all(|r| r.underline != Underline::None),
|
||||
};
|
||||
let u = if on { style.unwrap_or(Underline::Single) } else { Underline::None };
|
||||
apply(s, &|c| c.underline = Some(u))
|
||||
|
||||
@@ -188,14 +188,10 @@ fn range_index_after_text(s: &Session) -> bool {
|
||||
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let instr = index_instr(v);
|
||||
check_index_reachable(s)?;
|
||||
// An index Word wrote as a range field is first made a plain field in its own paragraph, as
|
||||
// Update Index makes it, so it takes the new settings rather than a second index being added
|
||||
// beside it (#8034).
|
||||
// An index Word wrote as a range field is rebuilt by Update Index; Insert Index would add a
|
||||
// second one beside it (#8034).
|
||||
if index_field(s).is_none() && has_index(s, true) {
|
||||
super::citations::update_generated(s)?;
|
||||
if index_field(s).is_none() {
|
||||
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
|
||||
}
|
||||
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
|
||||
}
|
||||
match index_field(s) {
|
||||
Some((i, _)) => {
|
||||
@@ -644,10 +640,10 @@ End.",
|
||||
assert!(!body_has_index(&s));
|
||||
}
|
||||
|
||||
/// An index Word wrote as a range field in the main text takes Insert Index's settings and is
|
||||
/// rebuilt, rather than a second index being added at the caret (#8034).
|
||||
/// An index Word wrote as a range field in the main text is rebuilt by Update Index; Insert
|
||||
/// Index says so instead of adding a second one (#8034).
|
||||
#[test]
|
||||
fn insert_index_gives_a_range_field_index_in_the_main_text_its_settings() {
|
||||
fn insert_index_leaves_a_range_field_index_in_the_main_text_to_update_index() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
|
||||
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &json!({})).unwrap();
|
||||
@@ -658,23 +654,10 @@ End.",
|
||||
para.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(at), wordcraft_doc::Block::Para(para)).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({"columns": 2})).unwrap();
|
||||
let instrs: Vec<String> = s
|
||||
.doc
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| b.as_para())
|
||||
.flat_map(|p| p.objects.iter())
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX" => {
|
||||
Some(instr.clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(instrs.len(), 1, "one index, not a second beside it: {instrs:?}");
|
||||
assert!(FieldCode::parse(&instrs[0]).arg('c').is_some(), "the index took the new columns setting: {instrs:?}");
|
||||
let before = s.doc.body.len();
|
||||
assert!(s.run("references.index", &json!({})).is_err());
|
||||
assert_eq!(s.doc.body.len(), before, "no second index was added");
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
let text: String =
|
||||
s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.replace(wordcraft_doc::para::OBJ, "")).collect::<Vec<_>>().join(
|
||||
"
|
||||
|
||||
@@ -21,8 +21,8 @@ pub use items::{
|
||||
};
|
||||
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
|
||||
use links::{bookmark, delete_bookmark, link, link_targets};
|
||||
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span, selection_is_one_line};
|
||||
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
|
||||
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
|
||||
pub use objects::{base64_decode, base64_encode};
|
||||
use objects::{icon, shape, table, text_box};
|
||||
pub(crate) use objects::{image_ext, picture};
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::{
|
||||
/// even page or the default), made when there is none: with Different First Page on, a header
|
||||
/// inserted on page 1 is the one page 1 shows (#2826).
|
||||
pub(super) fn hf_part(s: &mut Session, header: bool) -> u32 {
|
||||
let block = crate::cmd::page::section_end_of_focus(s);
|
||||
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let layout = s.layout();
|
||||
let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) };
|
||||
let slot = page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default();
|
||||
@@ -98,12 +98,15 @@ pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
let shown = match page {
|
||||
Some(page) => shown_hf(s, page, header)?,
|
||||
None => {
|
||||
// The caret's section's own, else the one it is linked to from a section before it, as
|
||||
// layout shows it (#3639): editing that one keeps the link.
|
||||
let section = crate::cmd::page::hf_section_of_focus(s);
|
||||
let sections = s.doc.sections();
|
||||
let set = sections.iter().take(section + 1).rev().find_map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default });
|
||||
set.filter(|id| s.doc.parts.contains_key(id))
|
||||
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let set = s
|
||||
.doc
|
||||
.sections()
|
||||
.into_iter()
|
||||
.find(|(end, _)| block <= *end)
|
||||
.or_else(|| s.doc.sections().pop())
|
||||
.map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default });
|
||||
set.flatten().filter(|id| s.doc.parts.contains_key(id))
|
||||
}
|
||||
};
|
||||
let Some(id) = shown else {
|
||||
|
||||
@@ -205,26 +205,21 @@ pub fn format_date_at_in(fmt: &str, lang: Option<&str>, unix: u64, offset_secs:
|
||||
format_date_parts_in(fmt, lang, y, m as usize, d, hms, days)
|
||||
}
|
||||
|
||||
/// Month and weekday names of a language, as Word writes them in date fields: full names and the
|
||||
/// abbreviations used by `MMM` and `ddd`. Weekdays start on Thursday (1970-01-01).
|
||||
/// Month and weekday names of a language, as Word writes them in date fields: full names, the
|
||||
/// three-letter forms (`MMM`, `ddd`) being their first three letters, without a full stop.
|
||||
/// Weekdays start on Thursday (1970-01-01).
|
||||
struct DateNames {
|
||||
/// Full month names (January through December).
|
||||
months: [&'static str; 12],
|
||||
/// Abbreviated month names for `MMM` (January through December).
|
||||
months_short: [&'static str; 12],
|
||||
/// Weekday names starting on Thursday (1970-01-01).
|
||||
days: [&'static str; 7],
|
||||
/// Abbreviated weekday names for `ddd`, starting on Thursday (1970-01-01).
|
||||
days_short: [&'static str; 7],
|
||||
/// The picture of a `DATE` field without `\@`.
|
||||
default: &'static str,
|
||||
}
|
||||
|
||||
const ENGLISH: DateNames = DateNames {
|
||||
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
|
||||
months_short: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
|
||||
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
|
||||
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
|
||||
default: "M/d/yyyy",
|
||||
};
|
||||
|
||||
@@ -232,46 +227,14 @@ const ENGLISH: DateNames = DateNames {
|
||||
/// `ddd` = `qui`, and `dd/MM/yyyy` for a field without a picture.
|
||||
const PORTUGUESE: DateNames = DateNames {
|
||||
months: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
|
||||
months_short: ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"],
|
||||
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
|
||||
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
|
||||
default: "dd/MM/yyyy",
|
||||
};
|
||||
|
||||
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
|
||||
/// letters), and `dd.MM.yyyy` for a field without a picture. Covers de-DE, de-CH and bare `de`.
|
||||
const GERMAN: DateNames = DateNames {
|
||||
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
|
||||
months_short: ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
|
||||
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
|
||||
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
|
||||
default: "dd.MM.yyyy",
|
||||
};
|
||||
|
||||
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
|
||||
/// Wörterbuch; Windows NLS `de-AT`). Every other month and weekday matches [`GERMAN`].
|
||||
const GERMAN_AUSTRIA: DateNames = DateNames {
|
||||
months: ["Jänner", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
|
||||
months_short: ["Jän", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
|
||||
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
|
||||
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
|
||||
default: "dd.MM.yyyy",
|
||||
};
|
||||
|
||||
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
|
||||
/// and a region subtag refines it (`de-AT` writes `Jänner`). Tags compare case-insensitively, as
|
||||
/// `w:lang` values do.
|
||||
/// Choose month and weekday names according to the primary language subtag.
|
||||
fn date_names(lang: Option<&str>) -> &'static DateNames {
|
||||
let mut subtags = lang.unwrap_or("").trim().split(['-', '_']);
|
||||
let primary = subtags.next().unwrap_or("");
|
||||
if primary.eq_ignore_ascii_case("pt") {
|
||||
&PORTUGUESE
|
||||
} else if primary.eq_ignore_ascii_case("de") {
|
||||
// Austria keeps `Jänner` / `Jän`; Germany and Switzerland keep `Januar` / `Jan`.
|
||||
if subtags.any(|region| region.eq_ignore_ascii_case("AT")) { &GERMAN_AUSTRIA } else { &GERMAN }
|
||||
} else {
|
||||
&ENGLISH
|
||||
}
|
||||
let primary = lang.and_then(|l| l.trim().split(['-', '_']).next()).unwrap_or("");
|
||||
if primary.eq_ignore_ascii_case("pt") { &PORTUGUESE } else { &ENGLISH }
|
||||
}
|
||||
|
||||
/// The picture Word gives a `DATE` field that has no `\@` switch, in the field's language.
|
||||
@@ -289,12 +252,9 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u3
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d: u32, (hh, mm, ss): (u32, u32, u32), days_since: i64) -> String {
|
||||
let names = date_names(lang);
|
||||
let mi = m.saturating_sub(1);
|
||||
let di = days_since.rem_euclid(7) as usize;
|
||||
let month = names.months.get(mi).copied().unwrap_or(names.months[0]);
|
||||
let month_short = names.months_short.get(mi).copied().unwrap_or(names.months_short[0]);
|
||||
let day = names.days.get(di).copied().unwrap_or(names.days[0]);
|
||||
let day_short = names.days_short.get(di).copied().unwrap_or(names.days_short[0]);
|
||||
let month = names.months.get(m.saturating_sub(1)).copied().unwrap_or(names.months[0]);
|
||||
let day = names.days.get(days_since.rem_euclid(7) as usize).copied().unwrap_or(names.days[0]);
|
||||
let three = |s: &str| -> String { s.chars().take(3).collect() };
|
||||
let mut out = String::new();
|
||||
let chars: Vec<char> = fmt.chars().collect();
|
||||
let mut i = 0;
|
||||
@@ -336,11 +296,11 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
|
||||
('y' | 'Y', 4..) => out.push_str(&format!("{y:04}")),
|
||||
('y' | 'Y', _) => out.push_str(&format!("{:02}", y % 100)),
|
||||
('M', 4..) => out.push_str(month),
|
||||
('M', 3) => out.push_str(month_short),
|
||||
('M', 3) => out.push_str(&three(month)),
|
||||
('M', 2) => out.push_str(&format!("{m:02}")),
|
||||
('M', 1) => out.push_str(&m.to_string()),
|
||||
('d' | 'D', 4..) => out.push_str(day),
|
||||
('d' | 'D', 3) => out.push_str(day_short),
|
||||
('d' | 'D', 3) => out.push_str(&three(day)),
|
||||
('d' | 'D', 2) => out.push_str(&format!("{d:02}")),
|
||||
('d' | 'D', 1) => out.push_str(&d.to_string()),
|
||||
('H', 2..) => out.push_str(&format!("{hh:02}")),
|
||||
@@ -351,7 +311,7 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
|
||||
('m', _) => out.push_str(&mm.to_string()),
|
||||
('s', 2..) => out.push_str(&format!("{ss:02}")),
|
||||
('s', _) => out.push_str(&ss.to_string()),
|
||||
// Bare `a`/`A` is literal; AM/PM is the `am/pm` token (#3488).
|
||||
('a' | 'A', _) => out.push_str(if hh < 12 { "AM" } else { "PM" }),
|
||||
_ => {
|
||||
for _ in 0..n {
|
||||
out.push(c);
|
||||
@@ -614,43 +574,6 @@ mod date_time_locale_tests {
|
||||
assert_eq!(format("MMMM", 20), "outubro");
|
||||
}
|
||||
|
||||
/// German month and weekday names, and the default picture, are chosen by the language tag
|
||||
/// (de-DE, de-AT, de-CH), as in Word (#7146).
|
||||
#[test]
|
||||
fn german_date_names_render_for_de() {
|
||||
assert_eq!(format_date_parts_in("dddd, d. MMMM yyyy", Some("de-DE"), 2026, 11, 21, (12, 0, 0), 2), "Samstag, 21. November 2026");
|
||||
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
|
||||
}
|
||||
|
||||
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
|
||||
/// trailing full stop (#7146).
|
||||
#[test]
|
||||
fn german_short_names_match_windows_nls() {
|
||||
let format = |pic| format_date_parts_in(pic, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3);
|
||||
assert_eq!(format("ddd, d. MMM yyyy"), "So, 15. Mrz 2026");
|
||||
assert_eq!(format("dddd"), "Sonntag");
|
||||
assert_eq!(format("MMM"), "Mrz");
|
||||
}
|
||||
|
||||
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland
|
||||
/// and bare `de` keep `Januar` (`Jan`); every other name is shared (#7146).
|
||||
#[test]
|
||||
fn austrian_german_january_is_jaenner() {
|
||||
let january = |lang, pic| format_date_parts_in(pic, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
|
||||
assert_eq!(january("de-AT", "MMMM"), "Jänner");
|
||||
assert_eq!(january("de-AT", "MMM"), "Jän");
|
||||
assert_eq!(january("de_at", "MMMM"), "Jänner", "region subtags compare case-insensitively");
|
||||
for lang in ["de-DE", "de-CH", "de"] {
|
||||
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
|
||||
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
|
||||
}
|
||||
// Only January differs: February and March read the same in Austria and Germany.
|
||||
for month in [2, 3] {
|
||||
let names = |lang| format_date_parts_in("MMMM MMM", Some(lang), 2026, month, 1, (12, 0, 0), 0);
|
||||
assert_eq!(names("de-AT"), names("de-DE"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pt-BR dynamic field keeps its result after DOCX round-trip and refresh.
|
||||
#[test]
|
||||
fn pt_br_date_time_dialog_inserts_dynamic_field() {
|
||||
|
||||
@@ -84,45 +84,25 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// What can't stand in one line of text: breaks, and pictures or fields.
|
||||
const NOT_ONE_LINE: [char; 7] = {
|
||||
/// The `text` to retype a selection with before linking it: only when it differs from the selected
|
||||
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
|
||||
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
|
||||
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
|
||||
use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, OBJ, PAGE_BREAK};
|
||||
[LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ]
|
||||
};
|
||||
|
||||
/// The raw text of the selection when it is one run of one paragraph without breaks, pictures or fields.
|
||||
fn one_line_selection(s: &Session) -> Option<&str> {
|
||||
// A column (block) selection has both ends in one paragraph but holds a piece of each line it
|
||||
// covers: it isn't one line of text (#8581).
|
||||
if s.column_segments().is_some_and(|segs| !segs.is_empty()) {
|
||||
/// What can't stand in one line of text: breaks, and pictures or fields.
|
||||
const NOT_ONE_LINE: [char; 7] = [LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ];
|
||||
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
|
||||
if text.contains(NOT_ONE_LINE) {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a.story != b.story || a.path != b.path {
|
||||
return None;
|
||||
}
|
||||
s.doc.para(a.story, &a.path)?.text.get(a.off..b.off).filter(|t| !t.contains(NOT_ONE_LINE))
|
||||
}
|
||||
|
||||
/// Whether the selection is plain text in one line of one paragraph: otherwise (as Word shows
|
||||
/// `<<Selection in Document>>`) Text to display can't show it and linking keeps its content (#8286).
|
||||
pub fn selection_is_one_line(s: &Session) -> bool {
|
||||
one_line_selection(s).is_some()
|
||||
}
|
||||
|
||||
/// The `text` to retype a selection with before linking it: only when it differs from the selected
|
||||
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
|
||||
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
|
||||
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
|
||||
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
|
||||
if text.contains(NOT_ONE_LINE) {
|
||||
let shown = s.doc.para(a.story, &a.path)?.text.get(a.off..b.off)?;
|
||||
if shown.contains(NOT_ONE_LINE) || shown == text {
|
||||
return None;
|
||||
}
|
||||
let shown = one_line_selection(s)?;
|
||||
if shown == text {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = s.sel.ordered();
|
||||
// A selection in a field's result (between its markers, which it doesn't hold) is retyped by
|
||||
// the next update of the field, not here.
|
||||
if s.doc.field_ranges(a.story).iter().any(|r| r.start < b && a <= r.end) {
|
||||
|
||||
@@ -23,13 +23,8 @@ fn insert_block_at_caret(s: &mut Session, block: Block) -> Result<Path, CmdError
|
||||
Ok(insert_at)
|
||||
}
|
||||
|
||||
/// Most rows an inserted table has. The table model holds more, but an inserted table starts
|
||||
/// small: the command that inserts one clamps to this, so the others read it rather than
|
||||
/// repeating the number.
|
||||
pub const MAX_TABLE_ROWS: usize = 1_000;
|
||||
|
||||
pub(super) fn table(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, MAX_TABLE_ROWS as u64) as usize;
|
||||
let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, 1000) as usize;
|
||||
let cols = p::u64(v, "cols").unwrap_or(2).clamp(1, 63) as usize;
|
||||
let width = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0);
|
||||
let mut t = Table::new(rows, cols, width);
|
||||
|
||||
@@ -358,8 +358,6 @@ fn date_pictures_keep_quoted_text() {
|
||||
// Two quotes outside quoted text are one too (an apostrophe), not an empty quoted text.
|
||||
assert_eq!(format_date_parts("yyyy '' MM", 2026, 10, 21, (0, 0, 0), 0), "2026 ' 10");
|
||||
assert_eq!(format_date_parts("d''MM", 2026, 10, 21, (0, 0, 0), 0), "21'10");
|
||||
// Bare `a` is literal, not AM/PM (#3488).
|
||||
assert_eq!(format_date_parts("yyyy a", 2026, 10, 21, (14, 30, 0), 0), "2026 a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -27,7 +27,7 @@ pub use merge::{merge_range, refresh};
|
||||
#[cfg(test)]
|
||||
use merge::{mergefield_name, placeholder};
|
||||
use recipients::recipients;
|
||||
pub use recipients::{CsvLimits, MAX_CELLS, MAX_FIELDS, MAX_TEXT_BYTES, RECIPIENT_EXTENSIONS, RECIPIENT_LIMITS, is_spreadsheet_name, parse_csv};
|
||||
pub use recipients::{RECIPIENT_EXTENSIONS, is_spreadsheet_name, parse_csv};
|
||||
|
||||
/// The mail-merge data source and preview state (lives in the session, not the document).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
|
||||
@@ -19,32 +19,22 @@ fn csv_separator(text: &str) -> char {
|
||||
[',', ';', '\t'].into_iter().max_by_key(|c| unquoted.matches(*c).count()).unwrap_or(',')
|
||||
}
|
||||
|
||||
/// What a CSV may hold while it is read: the parser refuses a list that is over these, so a
|
||||
/// hostile file is never built and then cut.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CsvLimits {
|
||||
/// Most columns in a record.
|
||||
pub fields: usize,
|
||||
/// Most cells in the list: its records times its widest record.
|
||||
pub cells: usize,
|
||||
/// Most bytes of cell text in all.
|
||||
pub text: usize,
|
||||
/// Ends the current row: kept when it has any non-empty field, otherwise dropped.
|
||||
fn push_csv_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>) {
|
||||
if row.iter().any(|x| !x.is_empty()) {
|
||||
rows.push(std::mem::take(row));
|
||||
} else {
|
||||
row.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse CSV (RFC 4180-ish: quotes, doubled quotes, commas/semicolons/tabs).
|
||||
///
|
||||
/// The limits are kept while the list is read, not after it: a record wider than
|
||||
/// `limits.fields`, a list of more than `limits.cells` cells, or more than `limits.text` bytes
|
||||
/// of cell text is refused, rather than built and then cut.
|
||||
pub fn parse_csv(text: &str, limits: &CsvLimits) -> Result<Vec<Vec<String>>, CmdError> {
|
||||
pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
|
||||
let sep = csv_separator(text);
|
||||
let mut rows = Vec::new();
|
||||
let mut row = Vec::new();
|
||||
let mut cell = String::new();
|
||||
let mut q = false;
|
||||
// The widest record read so far, and the bytes of cell text read so far.
|
||||
let mut widest = 0usize;
|
||||
let mut text_bytes = 0usize;
|
||||
let mut chars = text.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if q {
|
||||
@@ -61,75 +51,29 @@ pub fn parse_csv(text: &str, limits: &CsvLimits) -> Result<Vec<Vec<String>>, Cmd
|
||||
} else if c == '"' {
|
||||
q = true;
|
||||
} else if c == sep {
|
||||
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
|
||||
row.push(std::mem::take(&mut cell));
|
||||
} else if c == '\n' || c == '\r' {
|
||||
if c == '\r' && chars.peek() == Some(&'\n') {
|
||||
chars.next();
|
||||
}
|
||||
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
|
||||
end_row(&mut rows, &mut row, &mut widest, limits)?;
|
||||
row.push(std::mem::take(&mut cell));
|
||||
push_csv_row(&mut rows, &mut row);
|
||||
} else {
|
||||
cell.push(c);
|
||||
}
|
||||
// The text read so far: the finished cells and the one being read.
|
||||
if text_bytes.saturating_add(cell.len()) > limits.text {
|
||||
return Err(CmdError::Failed(format!("the CSV can't have more than {} of text", text_size(limits.text))));
|
||||
}
|
||||
if rows.len() > 100_000 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The last cell, when the file doesn't end with a line break.
|
||||
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
|
||||
end_row(&mut rows, &mut row, &mut widest, limits)?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// A finished cell joins the record: the record's width stays inside the limit.
|
||||
fn end_cell(row: &mut Vec<String>, cell: &mut String, text_bytes: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
|
||||
*text_bytes = text_bytes.saturating_add(cell.len());
|
||||
row.push(std::mem::take(cell));
|
||||
if row.len() > limits.fields {
|
||||
return Err(CmdError::Failed(format!("the CSV can't have more than {} columns", limits.fields)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A finished record joins the list (an empty one is dropped). The list costs its records times
|
||||
/// its widest record — a recipient list pads every record to the header's width — so a list
|
||||
/// over the limit is refused here, while it is read.
|
||||
fn end_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>, widest: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
|
||||
if row.iter().any(|x| !x.is_empty()) {
|
||||
*widest = (*widest).max(row.len());
|
||||
rows.push(std::mem::take(row));
|
||||
} else {
|
||||
row.clear();
|
||||
}
|
||||
if rows.len().saturating_mul(*widest) > limits.cells {
|
||||
return Err(CmdError::Failed(format!("the CSV can't have more than {} cells (its records times its widest record)", limits.cells)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A byte budget, said the way a reader says it.
|
||||
fn text_size(bytes: usize) -> String {
|
||||
if bytes >= 1 << 20 { format!("{} MB", bytes >> 20) } else { format!("{bytes} bytes") }
|
||||
row.push(cell);
|
||||
push_csv_row(&mut rows, &mut row);
|
||||
rows
|
||||
}
|
||||
|
||||
/// Most records and fields a recipient list keeps.
|
||||
const MAX_RECORDS: usize = 100_000;
|
||||
|
||||
pub const MAX_FIELDS: usize = 1_000;
|
||||
|
||||
/// Most cells a recipient list keeps: its records times its fields. A recipient list pads every
|
||||
/// record to the header's width, so this is what a list costs, not how many values it says.
|
||||
pub const MAX_CELLS: usize = 2_000_000;
|
||||
|
||||
/// Most bytes of cell text a recipient list keeps. The table path keeps the same budget.
|
||||
pub const MAX_TEXT_BYTES: usize = 64 << 20;
|
||||
|
||||
/// The limits a recipient list keeps.
|
||||
pub const RECIPIENT_LIMITS: CsvLimits = CsvLimits { fields: MAX_FIELDS, cells: MAX_CELLS, text: MAX_TEXT_BYTES };
|
||||
const MAX_FIELDS: usize = 1_000;
|
||||
|
||||
pub(super) fn cell(x: &Value) -> String {
|
||||
match x {
|
||||
@@ -173,12 +117,12 @@ fn table_from_rows(fields: Option<&Vec<Value>>, arr: &[Value]) -> Result<(Vec<St
|
||||
|
||||
/// Skip unquoted blank prefix lines only when a text recipient list has a header.
|
||||
/// Headerless lists and the shared CSV reader keep whitespace records.
|
||||
fn recipient_csv(text: &str, headers: bool) -> Result<Vec<Vec<String>>, CmdError> {
|
||||
fn recipient_csv(text: &str, headers: bool) -> Vec<Vec<String>> {
|
||||
let prefix = text
|
||||
.split_inclusive(['\n', '\r'])
|
||||
.take_while(|line| headers && line.trim().is_empty())
|
||||
.fold(0_usize, |bytes, line| bytes.saturating_add(line.len()));
|
||||
parse_csv(text.get(prefix..).unwrap_or_default(), &RECIPIENT_LIMITS)
|
||||
parse_csv(text.get(prefix..).unwrap_or_default())
|
||||
}
|
||||
|
||||
pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
|
||||
@@ -187,7 +131,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
|
||||
table_from_rows(v.get("fields").and_then(Value::as_array), arr)?
|
||||
} else {
|
||||
let all = if let Some(c) = p::str(v, "csv") {
|
||||
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))?
|
||||
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))
|
||||
} else {
|
||||
let (bytes, ext) = if let Some(d) = p::str(v, "data") {
|
||||
let b = crate::cmd::insert::base64_decode(d.trim()).ok_or_else(|| CmdError::Params("`data` isn't valid base64".into()))?;
|
||||
@@ -244,7 +188,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sheet = json!(chosen);
|
||||
rows
|
||||
} else {
|
||||
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))?
|
||||
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))
|
||||
}
|
||||
};
|
||||
header_split(all, p::bool(v, "headers").unwrap_or(true))?
|
||||
|
||||
@@ -2,54 +2,9 @@ use super::*;
|
||||
|
||||
#[test]
|
||||
fn csv_parsing() {
|
||||
let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n", &RECIPIENT_LIMITS).unwrap();
|
||||
let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n");
|
||||
assert_eq!(r, vec![vec!["Name", "City"], vec!["Smith, Ann", "Paris"], vec!["Bo", "Oslo \"N\""]]);
|
||||
assert_eq!(parse_csv("a;b\n1;2", &RECIPIENT_LIMITS).unwrap()[1], vec!["1", "2"]);
|
||||
}
|
||||
|
||||
/// The parser keeps its limits while it reads the list, so a hostile list is refused
|
||||
/// instead of being built and then cut.
|
||||
#[test]
|
||||
fn csv_parsing_refuses_a_list_over_its_limits() {
|
||||
// A record wider than the limit.
|
||||
let e = parse_csv("a,b,c,d,e", &CsvLimits { fields: 4, cells: 100, text: 1_000 }).unwrap_err();
|
||||
assert!(e.to_string().contains("4 columns"), "{e}");
|
||||
// More cells than the list keeps.
|
||||
let e = parse_csv("a,b\nc,d\ne,f\ng,h\ni,j\nk,l", &CsvLimits { fields: 10, cells: 10, text: 1_000 }).unwrap_err();
|
||||
assert!(e.to_string().contains("10 cells"), "{e}");
|
||||
// More text than the list keeps.
|
||||
let e = parse_csv("abcdefghij", &CsvLimits { fields: 10, cells: 100, text: 8 }).unwrap_err();
|
||||
assert!(e.to_string().contains("of text"), "{e}");
|
||||
// A list inside the limits still parses.
|
||||
let limits = CsvLimits { fields: 4, cells: 10, text: 1_000 };
|
||||
assert_eq!(parse_csv("a,b\nc,d", &limits).unwrap(), vec![vec!["a", "b"], vec!["c", "d"]]);
|
||||
}
|
||||
|
||||
/// A recipient list over its limits is refused, not built.
|
||||
#[test]
|
||||
fn a_recipient_list_over_its_limits_is_refused() {
|
||||
// A record wider than the list's fields.
|
||||
let wide = format!("{}\nvalue", "f,".repeat(MAX_FIELDS + 1));
|
||||
let e = parse_csv(&wide, &RECIPIENT_LIMITS).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_FIELDS} columns")), "{e}");
|
||||
|
||||
// A record of exactly the limit's width is kept.
|
||||
let exact = format!("{}\nvalue", "f,".repeat(MAX_FIELDS - 1));
|
||||
assert_eq!(parse_csv(&exact, &RECIPIENT_LIMITS).unwrap()[0].len(), MAX_FIELDS);
|
||||
|
||||
// A wide header over many records: the list would cost more cells than it keeps, and
|
||||
// every record is padded to the header's width.
|
||||
let mut csv = format!("{}\n", (0..MAX_FIELDS).map(|i| format!("f{i}")).collect::<Vec<_>>().join(","));
|
||||
for _ in 0..=MAX_CELLS / MAX_FIELDS {
|
||||
csv.push_str("value\n");
|
||||
}
|
||||
let e = parse_csv(&csv, &RECIPIENT_LIMITS).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_CELLS} cells")), "{e}");
|
||||
|
||||
// The command refuses it too, with a message of its own.
|
||||
let mut s = Session::new(Document::new());
|
||||
let e = s.run("mailings.recipients", &json!({"csv": wide})).unwrap_err();
|
||||
assert!(e.to_string().contains("columns"), "{e}");
|
||||
assert_eq!(parse_csv("a;b\n1;2")[1], vec!["1", "2"]);
|
||||
}
|
||||
|
||||
/// #4001: finishing a merge opens a new document, with a new undo history. It is not an
|
||||
@@ -101,16 +56,13 @@ fn csv_delimiter_reads_complete_header_record() {
|
||||
let quoted = header.replace('"', "\"\"");
|
||||
let text = format!("\"{quoted}\"{sep}City{sep}{sep}\r\nAda{sep}Paris{sep}{sep}\nBo{sep}Oslo{sep}{sep}");
|
||||
assert_eq!(
|
||||
parse_csv(&text, &RECIPIENT_LIMITS).unwrap(),
|
||||
parse_csv(&text),
|
||||
vec![vec![header.as_str(), "City", "", ""], vec!["Ada", "Paris", "", ""], vec!["Bo", "Oslo", "", ""]],
|
||||
"separator {sep:?}, embedded newline {newline:?}"
|
||||
);
|
||||
// A multiline field after an ordinary column must not end detection either.
|
||||
let text = format!("ID{sep}\"{quoted}\"{sep}City\n1{sep}Ada{sep}Paris\n2{sep}Bo{sep}Oslo");
|
||||
assert_eq!(
|
||||
parse_csv(&text, &RECIPIENT_LIMITS).unwrap(),
|
||||
vec![vec!["ID", header.as_str(), "City"], vec!["1", "Ada", "Paris"], vec!["2", "Bo", "Oslo"]]
|
||||
);
|
||||
assert_eq!(parse_csv(&text), vec![vec!["ID", header.as_str(), "City"], vec!["1", "Ada", "Paris"], vec!["2", "Bo", "Oslo"]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,7 +74,7 @@ fn csv_delimiter_reads_multiline_headers_after_blank_lines() {
|
||||
let header = format!("Given{newline}Family");
|
||||
for prefix in ["\n\r\n", "\r", "\r\r"] {
|
||||
let text = format!("{prefix}\"{header}\"{sep}City\rAda{sep}Paris");
|
||||
assert_eq!(parse_csv(&text, &RECIPIENT_LIMITS).unwrap(), vec![vec![header.as_str(), "City"], vec!["Ada", "Paris"]]);
|
||||
assert_eq!(parse_csv(&text), vec![vec![header.as_str(), "City"], vec!["Ada", "Paris"]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,41 +99,34 @@ fn recipient_csv_blank_prefix_keeps_columns_without_dropping_literal_records() {
|
||||
let rows = s.merge.rows.clone();
|
||||
assert!(s.run("mailings.recipients", &json!({"csv": " \t\r\n \r"})).is_err());
|
||||
assert_eq!(s.merge.rows, rows, "an empty headered list must not replace existing recipients");
|
||||
assert_eq!(
|
||||
parse_csv(" \nName,Email\nAda,[email protected]", &RECIPIENT_LIMITS).unwrap()[0],
|
||||
vec![" "],
|
||||
"the shared CSV reader keeps literal whitespace rows"
|
||||
);
|
||||
assert_eq!(parse_csv(" \nName,Email\nAda,[email protected]")[0], vec![" "], "the shared CSV reader keeps literal whitespace rows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_delimiter_keeps_record_boundaries_and_ties() {
|
||||
// Later records cannot choose the header's delimiter.
|
||||
assert_eq!(
|
||||
parse_csv("Name;City\rAda;Paris,,,,\rBo;Oslo", &RECIPIENT_LIMITS).unwrap(),
|
||||
vec![vec!["Name", "City"], vec!["Ada", "Paris,,,,"], vec!["Bo", "Oslo"]]
|
||||
);
|
||||
assert_eq!(parse_csv("Name;City\rAda;Paris,,,,\rBo;Oslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris,,,,"], vec!["Bo", "Oslo"]]);
|
||||
// Existing ties prefer tab, then semicolon, then comma.
|
||||
assert_eq!(parse_csv("A,B;C\n1,2;3", &RECIPIENT_LIMITS).unwrap(), vec![vec!["A,B", "C"], vec!["1,2", "3"]]);
|
||||
assert_eq!(parse_csv("A;B\tC\n1;2\t3", &RECIPIENT_LIMITS).unwrap(), vec![vec!["A;B", "C"], vec!["1;2", "3"]]);
|
||||
assert_eq!(parse_csv("Name\nAda,Paris;Oslo", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name"], vec!["Ada,Paris;Oslo"]]);
|
||||
assert!(parse_csv("", &RECIPIENT_LIMITS).unwrap().is_empty());
|
||||
assert_eq!(parse_csv("\nName\nAda", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name"], vec!["Ada"]]);
|
||||
assert_eq!(parse_csv("A,B;C\n1,2;3"), vec![vec!["A,B", "C"], vec!["1,2", "3"]]);
|
||||
assert_eq!(parse_csv("A;B\tC\n1;2\t3"), vec![vec!["A;B", "C"], vec!["1;2", "3"]]);
|
||||
assert_eq!(parse_csv("Name\nAda,Paris;Oslo"), vec![vec!["Name"], vec!["Ada,Paris;Oslo"]]);
|
||||
assert!(parse_csv("").is_empty());
|
||||
assert_eq!(parse_csv("\nName\nAda"), vec![vec!["Name"], vec!["Ada"]]);
|
||||
// The reader remains permissive about an unterminated quoted cell.
|
||||
assert_eq!(parse_csv("Name,City\nAda,\"Paris\nOslo", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name", "City"], vec!["Ada", "Paris\nOslo"]]);
|
||||
assert_eq!(parse_csv("Name,City\nAda,\"Paris\nOslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris\nOslo"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_delimiter_ignores_quoted_text() {
|
||||
let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n", &RECIPIENT_LIMITS).unwrap();
|
||||
let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n");
|
||||
assert_eq!(r, vec![vec!["Name, first, last", "City"], vec!["Ann", "Paris"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_delimiter_skips_leading_blank_lines() {
|
||||
let want = vec![vec!["Name", "Email"], vec!["Ann", "[email protected]"]];
|
||||
assert_eq!(parse_csv("\nName,Email\nAnn,[email protected]\n", &RECIPIENT_LIMITS).unwrap(), want);
|
||||
assert_eq!(parse_csv("\r\n\r\nName;Email\r\nAnn;[email protected]", &RECIPIENT_LIMITS).unwrap(), want);
|
||||
assert_eq!(parse_csv("\nName,Email\nAnn,[email protected]\n"), want);
|
||||
assert_eq!(parse_csv("\r\n\r\nName;Email\r\nAnn;[email protected]"), want);
|
||||
}
|
||||
|
||||
/// Field types ignore case (ECMA-376 Part 1, 17.16.1), and `MERGEFIELDX` is another field.
|
||||
|
||||
@@ -103,7 +103,7 @@ fn exact_text(s: &Session) -> Option<String> {
|
||||
return res.clone();
|
||||
}
|
||||
let kept = [s.md_file.latest.as_deref(), s.md_file.saved.as_deref()];
|
||||
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).is_ok_and(|d| d.same_content(&s.doc))).map(str::to_string);
|
||||
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).same_content(&s.doc)).map(str::to_string);
|
||||
*s.md_file.cached_exact.borrow_mut() = Some((s.rev(), res.clone()));
|
||||
res
|
||||
}
|
||||
@@ -216,16 +216,15 @@ fn enter(s: &mut Session) -> Result<(), CmdError> {
|
||||
// The file's own text when it still says what the document holds, so nothing is lost.
|
||||
let (text, loses_content, block_lines) = match exact_text(s) {
|
||||
Some(text) => {
|
||||
let (_, lines) = parse_with_lines(&s.doc, &text)?;
|
||||
let (_, lines) = parse_with_lines(&s.doc, &text);
|
||||
(text, false, lines)
|
||||
}
|
||||
None => {
|
||||
let text = wordcraft_formats::markdown::export(&s.doc)
|
||||
.map_err(|e| CmdError::Failed(format!("the document cannot be written as Markdown: {e}")))?;
|
||||
let text = wordcraft_formats::markdown::export(&s.doc);
|
||||
if text.len() > MAX_SOURCE_BYTES {
|
||||
return Err(CmdError::Failed(too_long()));
|
||||
}
|
||||
let (doc, lines) = parse_with_lines(&s.doc, &text)?;
|
||||
let (doc, lines) = parse_with_lines(&s.doc, &text);
|
||||
let loses_content = !doc.same_content(&s.doc);
|
||||
(text, loses_content, lines)
|
||||
}
|
||||
@@ -290,19 +289,7 @@ pub fn apply(s: &mut Session) {
|
||||
}
|
||||
(src.text.clone(), src.entry_text.clone(), src.entry_doc.clone(), src.has_step, src.entry_lines.clone())
|
||||
};
|
||||
let (doc, lines) = if text == *entry_text {
|
||||
((*entry_doc).clone(), entry_lines)
|
||||
} else {
|
||||
// The text cannot be read as Markdown: the document stays as it is, rather than
|
||||
// becoming an empty one.
|
||||
match parse_with_lines(&s.doc, &text) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
s.status = e.to_string();
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
let (doc, lines) = if text == *entry_text { ((*entry_doc).clone(), entry_lines) } else { parse_with_lines(&s.doc, &text) };
|
||||
let step = if !has_step {
|
||||
s.checkpoint(LABEL);
|
||||
Some(s.undo_mark())
|
||||
@@ -326,20 +313,19 @@ pub fn apply(s: &mut Session) {
|
||||
|
||||
/// `text` as a document and block lines, with what isn't in Markdown from `current`: its page, settings,
|
||||
/// properties and language, as opening the file gave it.
|
||||
fn parse_with_lines(current: &Document, text: &str) -> Result<(Document, Vec<usize>), CmdError> {
|
||||
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, ¤t.last_section)
|
||||
.map_err(|e| CmdError::Failed(format!("the Markdown cannot be read: {e}")))?;
|
||||
fn parse_with_lines(current: &Document, text: &str) -> (Document, Vec<usize>) {
|
||||
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, ¤t.last_section);
|
||||
doc.ensure_nonempty();
|
||||
doc.settings = current.settings.clone();
|
||||
doc.core = current.core.clone();
|
||||
Arc::make_mut(&mut doc.styles).default_chr.lang = current.styles.default_chr.lang.clone();
|
||||
Ok((doc, lines))
|
||||
(doc, lines)
|
||||
}
|
||||
|
||||
/// `text` as a document, with what isn't in Markdown from `current`: its page, settings,
|
||||
/// properties and language, as opening the file gave it.
|
||||
fn parse(current: &Document, text: &str) -> Result<Document, CmdError> {
|
||||
parse_with_lines(current, text).map(|(doc, _)| doc)
|
||||
fn parse(current: &Document, text: &str) -> Document {
|
||||
parse_with_lines(current, text).0
|
||||
}
|
||||
|
||||
/// The byte offset where `line` starts, or the end of a text with fewer lines.
|
||||
|
||||
@@ -278,23 +278,4 @@ mod tests {
|
||||
assert_eq!(texts(&s), ["First one.", "Second one.", "Third one."]);
|
||||
assert!(kinds(&mut s).is_empty());
|
||||
}
|
||||
|
||||
/// A command that fails between a tracked cut and its paste changed nothing, so the move
|
||||
/// the cut recorded is still there: the paste is a move, as it was before the command.
|
||||
#[test]
|
||||
fn a_failed_command_between_a_tracked_cut_and_its_paste_leaves_the_move() {
|
||||
let mut s = Session::new(Document::new());
|
||||
s.run("document.setText", &json!({"text": "First one.\nSecond one.\nThird one."})).unwrap();
|
||||
s.run("file.setAuthor", &json!({"name": "Ana"})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 2, "off": 0}})).unwrap();
|
||||
s.run("edit.cut", &json!({})).unwrap();
|
||||
// A command that fails: there is no such character style.
|
||||
assert!(s.run("format.charStyle", &json!({"style": "NoSuchStyle"})).is_err());
|
||||
s.run("caret.set", &json!({"pos": {"block": 0, "off": 0}})).unwrap();
|
||||
s.run("edit.paste", &json!({})).unwrap();
|
||||
let k = kinds(&mut s);
|
||||
assert!(k.iter().any(|(k, m)| k == "moveTo" && m == "move1"), "{k:?}");
|
||||
assert!(k.iter().any(|(k, m)| k == "moveFrom" && m == "move1"), "{k:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,6 @@ pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, or
|
||||
use picture::{clear_background, grown, picture_style};
|
||||
#[cfg(test)]
|
||||
pub(crate) use select::all_objects;
|
||||
pub(crate) use select::select_object;
|
||||
pub(crate) use select::{edit_obj, has_shape_or_canvas};
|
||||
#[cfg(test)]
|
||||
use select::{has_group, holds_ink, obj_size, with_obj};
|
||||
|
||||
@@ -176,7 +176,7 @@ pub fn min_size(o: &InlineObject) -> f32 {
|
||||
}
|
||||
|
||||
/// Select the object whose character is at `pos`.
|
||||
pub(crate) fn select_object(s: &mut Session, pos: &Pos) {
|
||||
pub(super) fn select_object(s: &mut Session, pos: &Pos) {
|
||||
s.sel = Selection { anchor: pos.clone(), focus: Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos.clone() } };
|
||||
}
|
||||
|
||||
|
||||
@@ -250,26 +250,6 @@ pub fn section_index_of_focus(s: &Session) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
/// The caret's section, for the header and footer commands. In a header or footer it is the
|
||||
/// section of the caret's page when that page shows it: a section linked to the previous one
|
||||
/// shows that section's header, so the header alone names the earlier section (#3639).
|
||||
pub fn hf_section_of_focus(s: &mut Session) -> usize {
|
||||
let wordcraft_doc::StoryRef::Part(id) = s.sel.focus.story else { return section_index_of_focus(s) };
|
||||
let layout = s.layout();
|
||||
match layout.pages.get(s.page_hint) {
|
||||
Some(pg) if pg.header_story == Some(id) || pg.footer_story == Some(id) => pg.section,
|
||||
_ => section_of_part(s, id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The last body block of the caret's section ([`hf_section_of_focus`]), the block
|
||||
/// [`wordcraft_doc::Document::section_mut`] takes. In a header or footer the caret's block index
|
||||
/// counts that story's paragraphs, not the body's, so it would name another section (#3639).
|
||||
pub fn section_end_of_focus(s: &mut Session) -> usize {
|
||||
let i = hf_section_of_focus(s);
|
||||
s.doc.sections().get(i).map(|(end, _)| *end).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn sect(s: &Session) -> SectionProps {
|
||||
let i = section_index_of_focus(s);
|
||||
s.doc.sections().get(i).map(|(_, x)| (*x).clone()).unwrap_or_default()
|
||||
|
||||
@@ -187,7 +187,7 @@ fn paste_special(s: &mut Session, v: &Value) -> CmdResult {
|
||||
return Ok(r);
|
||||
}
|
||||
"formatted" => s.clipboard.clone().ok_or_else(|| CmdError::Failed("the clipboard is empty".into()))?,
|
||||
"html" => adopt(s, import_html(&src).map_err(|e| CmdError::Failed(format!("bad HTML: {e}")))?),
|
||||
"html" => adopt(s, import_html(&src)),
|
||||
_ => adopt(s, wordcraft_formats::rtf::import(src.as_bytes()).map_err(|e| CmdError::Failed(format!("bad RTF: {e}")))?),
|
||||
};
|
||||
insert(s, frag)?;
|
||||
@@ -204,8 +204,8 @@ const BLOCKQUOTE_INDENT: f32 = 36.0;
|
||||
/// (#1270): it pastes as a Normal paragraph indented by the page's `blockquote` margins, else half
|
||||
/// an inch each side, rather than in the (centred, italic) Quote style. Opening an .html file keeps
|
||||
/// `<blockquote>` as Quote, so HTML round-trips.
|
||||
fn import_html(html: &str) -> Result<Document, String> {
|
||||
let mut doc = wordcraft_formats::html::import(html_fragment(html))?;
|
||||
fn import_html(html: &str) -> Document {
|
||||
let mut doc = wordcraft_formats::html::import(html_fragment(html));
|
||||
let (left, right) = blockquote_margins(html);
|
||||
for b in &mut doc.body {
|
||||
each_para(Arc::make_mut(b), 0, &mut |p| {
|
||||
@@ -217,7 +217,7 @@ fn import_html(html: &str) -> Result<Document, String> {
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(doc)
|
||||
doc
|
||||
}
|
||||
|
||||
/// The left and right margins (points) the payload's `<style>` sheets give `blockquote` — LibreOffice
|
||||
@@ -294,7 +294,7 @@ fn has_content(d: &Document) -> bool {
|
||||
/// [`MAX_PASTE_BYTES`], or it holds nothing to paste (the caller pastes the text then).
|
||||
pub fn rich_fragment(s: &mut Session, v: &Value) -> Option<Fragment> {
|
||||
let fits = |k: &str| p::str(v, k).filter(|t| !t.trim().is_empty() && t.len() <= MAX_PASTE_BYTES);
|
||||
let doc = fits("html").and_then(|html| import_html(html).ok());
|
||||
let doc = fits("html").map(import_html);
|
||||
let doc = match doc.filter(has_content) {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
@@ -373,22 +373,21 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
|
||||
p.props = para.clone();
|
||||
for run in &mut p.runs {
|
||||
let src = std::mem::replace(&mut run.props, base.clone());
|
||||
let e = emphasis_of(s, &src);
|
||||
// Emphasis the source shows in either script is kept for both, as the Bold and
|
||||
// Italic buttons set it: text pasted into a run marked `w:cs` (Thai from a WPS or
|
||||
// Word file) is drawn with the complex-script bold and italic.
|
||||
if shown(e.bold, e.bold_cs, &e) {
|
||||
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
|
||||
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
|
||||
// with the complex-script bold and italic.
|
||||
if src.bold == Some(true) || src.bold_cs == Some(true) {
|
||||
run.props.bold = Some(true);
|
||||
run.props.bold_cs = Some(true);
|
||||
}
|
||||
if shown(e.italic, e.italic_cs, &e) {
|
||||
if src.italic == Some(true) || src.italic_cs == Some(true) {
|
||||
run.props.italic = Some(true);
|
||||
run.props.italic_cs = Some(true);
|
||||
}
|
||||
if e.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
|
||||
run.props.underline = e.underline;
|
||||
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
|
||||
run.props.underline = src.underline;
|
||||
}
|
||||
if e.strike == Some(true) {
|
||||
if src.strike == Some(true) {
|
||||
run.props.strike = Some(true);
|
||||
}
|
||||
run.props.link = src.link;
|
||||
@@ -401,34 +400,6 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The formatting a pasted run's emphasis is judged by: its own, over its character style
|
||||
/// chain's. Word keeps the bold, italic, underline and strikethrough a character style gives the
|
||||
/// source, as direct formatting, but not a paragraph style's (measured in Word for Windows), so
|
||||
/// the paragraph style isn't consulted.
|
||||
fn emphasis_of(s: &Session, src: &wordcraft_doc::CharProps) -> wordcraft_doc::CharProps {
|
||||
use wordcraft_doc::styles::StyleKind;
|
||||
let mut e = wordcraft_doc::CharProps::default();
|
||||
if let Some(id) = src.style.as_deref() {
|
||||
for st in s.doc.styles.chain(id) {
|
||||
if st.kind == StyleKind::Character || st.kind == StyleKind::Paragraph {
|
||||
e.overlay(&st.chr);
|
||||
}
|
||||
}
|
||||
}
|
||||
e.overlay(&wordcraft_doc::CharProps { style: None, ..src.clone() });
|
||||
e
|
||||
}
|
||||
|
||||
/// Whether a run with these Latin and complex-script values of a toggle (bold or italic) shows
|
||||
/// it anywhere, as the resolved formatting draws it: a run marked `w:cs` or `w:rtl` draws all
|
||||
/// its text with the complex-script value, which borrows the Latin one unless the run is marked
|
||||
/// `w:cs`; other runs draw their Latin text with the Latin value.
|
||||
fn shown(latin: Option<bool>, complex: Option<bool>, run: &wordcraft_doc::CharProps) -> bool {
|
||||
let complex_shown = complex.or(latin.filter(|_| run.cs != Some(true))) == Some(true);
|
||||
let all_complex = run.cs == Some(true) || run.rtl == Some(true);
|
||||
complex_shown || (!all_complex && latin == Some(true))
|
||||
}
|
||||
|
||||
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
|
||||
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
|
||||
/// anything else is [`insert_as_is`].
|
||||
|
||||
@@ -305,16 +305,7 @@ pub(crate) fn greyed_out(s: &Session, id: &str, facts: impl FnOnce() -> Facts) -
|
||||
}
|
||||
}
|
||||
let comment_ok = id.starts_with("review.") && (id.contains("Comment") || id == "review.reply");
|
||||
let tracked = matches!(
|
||||
id,
|
||||
"review.accept"
|
||||
| "review.reject"
|
||||
| "review.acceptAndNext"
|
||||
| "review.rejectAndNext"
|
||||
| "review.acceptAll"
|
||||
| "review.rejectAll"
|
||||
| "review.trackChanges"
|
||||
);
|
||||
let tracked = matches!(id, "review.accept" | "review.reject" | "review.acceptAll" | "review.rejectAll" | "review.trackChanges");
|
||||
match mode {
|
||||
"readOnly" => (!facts().exceptions).then_some("the document is protected (read only)"),
|
||||
"forms" => (facts().fillable == 0).then_some("the document is protected (read only)"),
|
||||
|
||||
@@ -213,15 +213,7 @@ fn tracked_changes_protection_keeps_revisions() {
|
||||
select(&mut s, "text");
|
||||
s.run("text.insert", &json!({"text": "words"})).unwrap();
|
||||
let before = s.doc.clone();
|
||||
for id in [
|
||||
"review.acceptAll",
|
||||
"review.rejectAll",
|
||||
"review.accept",
|
||||
"review.reject",
|
||||
"review.acceptAndNext",
|
||||
"review.rejectAndNext",
|
||||
"review.trackChanges",
|
||||
] {
|
||||
for id in ["review.acceptAll", "review.rejectAll", "review.accept", "review.reject", "review.trackChanges"] {
|
||||
assert!(s.run(id, &json!({})).is_err(), "{id}");
|
||||
}
|
||||
assert_eq!(s.doc, before);
|
||||
|
||||
@@ -422,19 +422,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
"DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => {
|
||||
let lang = field_lang(&s.doc, p, k);
|
||||
let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref()));
|
||||
let created = s.doc.core.created.trim();
|
||||
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
|
||||
// document, never saved, has no creation date yet and saving stamps now. A
|
||||
// file opened without one, or with one that can't be read, keeps the result
|
||||
// it has.
|
||||
let text = if name != "CREATEDATE" || (created.is_empty() && s.path.is_none()) {
|
||||
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
|
||||
} else if let Some((unix, offset)) = created_at(created) {
|
||||
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
updates.push((k, text_result(instr, text)));
|
||||
updates.push((k, text_result(instr, crate::cmd::insert::format_date_in(&pic, lang.as_deref()))));
|
||||
}
|
||||
"REF" | "PAGEREF" => {
|
||||
let f = FieldCode::parse(instr);
|
||||
@@ -584,24 +572,6 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us
|
||||
doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang
|
||||
}
|
||||
|
||||
/// A core-properties creation date as seconds since the epoch and the UTC offset to show it at:
|
||||
/// an instant (`2019-05-05T12:00:00Z`, any offset or fraction, or without the seconds,
|
||||
/// `2019-05-05T12:00Z`, as W3CDTF allows) at the local offset, or a calendar date (`2019-05-05`)
|
||||
/// at its own midnight, whatever the time zone. `None` for another form or a date before 1970.
|
||||
fn created_at(stamp: &str) -> Option<(u64, i64)> {
|
||||
let instant = chrono::DateTime::parse_from_rfc3339(stamp).ok().or_else(|| {
|
||||
// `%:z` takes `+01:00` but not `Z`.
|
||||
let utc = stamp.strip_suffix(['Z', 'z']).map(|t| format!("{t}+00:00"));
|
||||
chrono::DateTime::parse_from_str(utc.as_deref().unwrap_or(stamp), "%Y-%m-%dT%H:%M%:z").ok()
|
||||
});
|
||||
if let Some(t) = instant {
|
||||
let unix = u64::try_from(t.timestamp()).ok()?;
|
||||
return Some((unix, crate::cmd::local_offset_secs(unix)));
|
||||
}
|
||||
let day = chrono::NaiveDate::parse_from_str(stamp, "%Y-%m-%d").ok()?;
|
||||
Some((u64::try_from(day.and_hms_opt(0, 0, 0)?.and_utc().timestamp()).ok()?, 0))
|
||||
}
|
||||
|
||||
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
|
||||
fn default_picture(name: &str, lang: Option<&str>) -> String {
|
||||
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
|
||||
|
||||
@@ -506,56 +506,6 @@ fn update_fields_all_covers_every_story() {
|
||||
s.run("references.updateFields", &json!({"all": "yes"})).unwrap();
|
||||
}
|
||||
|
||||
/// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11), not today's date.
|
||||
#[test]
|
||||
fn createdate_keeps_the_creation_date_on_update() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.doc.core.created = "2019-05-05T12:00:00Z".into();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
// 12:00 UTC is 5 May from UTC-12 to UTC+11:59, the next day east of that.
|
||||
let unix = 1_557_057_600;
|
||||
let (_, _, day, _, _) = crate::cmd::local_civil(unix, crate::cmd::local_offset_secs(unix));
|
||||
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")]);
|
||||
assert!(day == 5 || day == 6, "{day}");
|
||||
// W3CDTF may leave out the seconds; that is the same instant.
|
||||
for minutes in ["2019-05-05T12:00Z", "2019-05-05T14:00+02:00", "2019-05-05T07:00-05:00"] {
|
||||
// From another date first, so an unread stamp, which keeps the result, shows.
|
||||
s.doc.core.created = "2001-02-03".into();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert_eq!(fields(&s)[1].1, "2/3/2001");
|
||||
s.doc.core.created = minutes.into();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")], "{minutes}");
|
||||
}
|
||||
// A date without a time is that calendar day in every time zone.
|
||||
s.doc.core.created = "2019-06-07".into();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-06", "6/7/2019"]);
|
||||
}
|
||||
|
||||
/// A creation date that can't be read leaves the field's result as it was; a document that has
|
||||
/// never been saved is created now (saving stamps that time as its creation date).
|
||||
#[test]
|
||||
fn createdate_without_a_readable_creation_date() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.doc.core.created = "sometime in May".into();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
|
||||
assert_eq!(fields(&s)[0].1, "2019-05");
|
||||
// A file opened without a creation date keeps the result too.
|
||||
s.doc.core.created.clear();
|
||||
s.path = Some(std::env::temp_dir().join("opened.docx"));
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert_eq!(fields(&s)[0].1, "2019-05");
|
||||
s.path = None;
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_tabs_ignore_nonentries() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
|
||||
@@ -610,73 +560,6 @@ fn caption_for_an_object_in_a_cell_stays_in_the_cell() {
|
||||
assert_eq!(texts.get(1).map(String::as_str), Some("Figure 1"), "{texts:?}");
|
||||
}
|
||||
|
||||
/// A TOC inserted before a heading leaves the caret at the heading's first character, past the
|
||||
/// `_Toc` bookmark its entry links to: Delete then deletes that character, and the entry still
|
||||
/// finds its heading (Delete at offset zero took the bookmark).
|
||||
#[test]
|
||||
fn the_caret_after_a_toc_sits_past_the_headings_bookmark() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns\nBody text."));
|
||||
s.run("para.style", &json!({"style": "Heading 1"})).unwrap();
|
||||
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(0), off: 0 });
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
let heading = s.doc.para_at(&s.sel.focus).cloned().unwrap();
|
||||
assert_eq!(heading.plain_text(), "Kilns");
|
||||
let marks = |p: &Paragraph| p.objects.iter().filter(|o| matches!(o, InlineObject::BookmarkStart { .. })).count();
|
||||
assert_eq!(marks(&heading), 1, "the heading has its bookmark");
|
||||
s.run("text.delete", &json!({})).unwrap();
|
||||
let heading = s.doc.para_at(&s.sel.focus).cloned().unwrap();
|
||||
assert_eq!(heading.plain_text(), "ilns", "Delete took the first character");
|
||||
assert_eq!(marks(&heading), 1, "the bookmark stays");
|
||||
}
|
||||
|
||||
/// Inserting a table of contents (Word itself warns when there's no heading yet, but still
|
||||
/// creates an empty one) must leave the caret in a fresh paragraph just after it, like Word
|
||||
/// does — not inside the table's own title, where typing the rest of the document (and later
|
||||
/// updating the table) would splice stray text into unrelated paragraphs and blank the title.
|
||||
#[test]
|
||||
fn a_toc_inserted_before_any_headings_exist_leaves_the_caret_after_it() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
assert_eq!(s.sel.focus.path, Path::top(1), "the caret must land right after the table, not inside it");
|
||||
s.run("text.insert", &json!({"text": "\r"})).unwrap();
|
||||
s.run("para.style", &json!({"style": "Heading 1"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Kilns\r"})).unwrap();
|
||||
s.run("para.style", &json!({"style": "Normal"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Body text."})).unwrap();
|
||||
s.run("references.updateToc", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
s.doc.plain_text(StoryRef::Body).matches("Contents").count(),
|
||||
1,
|
||||
"the title stays where it was, it doesn't vanish and reappear elsewhere"
|
||||
);
|
||||
assert!(s.doc.plain_text(StoryRef::Body).contains("Body text."), "typed body content survives untouched");
|
||||
let heading = s.doc.body.iter().filter_map(|b| b.as_para()).find(|p| p.props.style.as_deref() == Some("Heading1"));
|
||||
assert_eq!(heading.map(|p| p.plain_text()), Some("Kilns".to_string()));
|
||||
}
|
||||
|
||||
/// A settings-based replacement of a table whose last entry is directly followed by a table
|
||||
/// (nothing paragraph-shaped in between) must still land the caret in a real paragraph: the
|
||||
/// block "after" the table isn't always a paragraph just because it exists.
|
||||
#[test]
|
||||
fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_paragraph() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
let (_, end) = toc_range(&s).unwrap();
|
||||
while s.doc.body.get(end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())) {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
|
||||
}
|
||||
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)), "test setup: a table must directly follow the table's entries");
|
||||
// Replacing the table's settings must still land the caret in a fresh paragraph right
|
||||
// after the table, not snap back into the table's own entries (a bogus position pointing
|
||||
// at the table gets silently corrected by `clamp_selection` to the nearest *preceding*
|
||||
// paragraph, so a weaker "is this some paragraph" check wouldn't catch the regression).
|
||||
s.run("references.toc", &json!({"levels": 3})).unwrap();
|
||||
let (_, new_end) = toc_range(&s).unwrap();
|
||||
assert_eq!(s.sel.focus.path, Path::top(new_end + 1), "the caret must land right after the table, not snap back into the table");
|
||||
assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_)));
|
||||
}
|
||||
|
||||
/// A fresh scratch directory for the file-name tests below.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn filename_scratch_dir(tag: &str) -> std::path::PathBuf {
|
||||
|
||||
@@ -412,7 +412,6 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// its paragraph ending the title's section, and the new entries follow in their columns.
|
||||
Some((start, _)) if title_above_break(s, start).is_some() => {
|
||||
replace_toc_above_break(s, v, start, &tabs)?;
|
||||
caret_after_toc(s)?;
|
||||
return sel_result(s);
|
||||
}
|
||||
Some((start, end)) => {
|
||||
@@ -445,41 +444,8 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i), Block::Para(head))?;
|
||||
let leader = leader(p::str(v, "tabLeader").unwrap_or("dot"));
|
||||
regenerate_toc(s, Some(leader), &tabs)?;
|
||||
caret_after_toc(s)?;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Like Word, the caret lands in the paragraph right after the table, ready to keep typing — not
|
||||
/// inside the table's own title or entries, where typing (or Enter) would corrupt them. When a
|
||||
/// table (or nothing) follows, a paragraph is added there first, and the entries are rebuilt so
|
||||
/// their page numbers count it.
|
||||
fn caret_after_toc(s: &mut Session) -> Result<(), CmdError> {
|
||||
if let Some((_, end)) = toc_range(s) {
|
||||
let after = end + 1;
|
||||
if !s.doc.body.get(after).is_some_and(|b| b.as_para().is_some()) {
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(after), Block::Para(Paragraph::new()))?;
|
||||
// Rebuilt as they now are (their leader and tabs), only the page numbers can change.
|
||||
let tabs = cached_toc_tabs(s);
|
||||
regenerate_toc(s, None, &tabs)?;
|
||||
}
|
||||
if let Some((_, end)) = toc_range(s) {
|
||||
// Past the markers the paragraph starts with (a heading's `_Toc` bookmark, which its
|
||||
// entry links to): Delete there takes the first character, not the bookmark.
|
||||
let off = s.doc.body.get(end + 1).and_then(|b| b.as_para()).map_or(0, |p| {
|
||||
let mut off = 0;
|
||||
for (at, o) in p.objects_with_offsets() {
|
||||
if at != off || !o.is_marker() {
|
||||
break;
|
||||
}
|
||||
off += OBJ.len_utf8();
|
||||
}
|
||||
off
|
||||
});
|
||||
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(end + 1), off });
|
||||
}
|
||||
}
|
||||
s.clamp_selection();
|
||||
Ok(())
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Replaces a TOC whose title sits above the section break its field's paragraph ends
|
||||
|
||||
@@ -12,7 +12,6 @@ use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
mod changes;
|
||||
mod comments;
|
||||
mod proofing;
|
||||
pub use proofing::thesaurus_word;
|
||||
|
||||
pub(crate) use changes::StyleTarget;
|
||||
pub use changes::{
|
||||
@@ -62,12 +61,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"next"?: bool (then select the next change)}"#),
|
||||
CommandSpec::new("review.reject", "Reject", "Review › Changes", |s, v| resolve_sel_then(s, v, false))
|
||||
.params(r#"{"next"?: bool (then select the next change)}"#),
|
||||
CommandSpec::new("review.acceptAndNext", "Accept and Move to Next", "Review › Changes", |s, _| {
|
||||
resolve_sel_then(s, &json!({"next": true}), true)
|
||||
}),
|
||||
CommandSpec::new("review.rejectAndNext", "Reject and Move to Next", "Review › Changes", |s, _| {
|
||||
resolve_sel_then(s, &json!({"next": true}), false)
|
||||
}),
|
||||
CommandSpec::new("review.nextChange", "Next Change", "Review › Changes", |s, _| nav_change(s, 1)).pure(),
|
||||
CommandSpec::new("review.previousChange", "Previous Change", "Review › Changes", |s, _| nav_change(s, -1)).pure(),
|
||||
CommandSpec::new("review.markup", "Display for Review", "Review › Tracking", |s, v| {
|
||||
|
||||
@@ -53,11 +53,10 @@ fn resolve_para(
|
||||
}
|
||||
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
|
||||
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
|
||||
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
|
||||
// story or cell has no follower to join here; `resolve_all` removes the whole paragraph
|
||||
// instead when one is left over (see `remove_trailing_para`). An empty paragraph whose mark
|
||||
// carries a section break goes whole too: its section joins the following one, as when the
|
||||
// break is deleted (#5667). Joining instead gave the next paragraph its properties.
|
||||
// whole, so the next one keeps its own style and numbering, as in Word. The mark at the end
|
||||
// of a story or cell can't go, so it just stops being a revision. An empty paragraph whose
|
||||
// mark carries a section break goes whole too: its section joins the following one, as when
|
||||
// the break is deleted (#5667). Joining instead gave the next paragraph its properties.
|
||||
if (del.is_some() && accept) || (ins.is_some() && !accept) {
|
||||
let sectioned = story == StoryRef::Body
|
||||
&& path.0.len() == 1
|
||||
@@ -77,23 +76,6 @@ fn resolve_para(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
|
||||
/// removal and it is the last paragraph in its container and carries no section break: it goes
|
||||
/// away, as long as the container keeps another paragraph (a story or cell must never end up
|
||||
/// with none). `false`, changing nothing, otherwise.
|
||||
fn remove_trailing_para(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path) -> Result<bool, CmdError> {
|
||||
let Some(p) = s.doc.para(story, path) else { return Ok(false) };
|
||||
if !p.is_empty() || p.section.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(container) = s.doc.container(story, path) else { return Ok(false) };
|
||||
if container.iter().filter(|b| b.as_para().is_some()).count() <= 1 {
|
||||
return Ok(false);
|
||||
}
|
||||
s.doc.remove_block(story, path)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Accept or reject the changes of the table cell `path` is in: the table's, its row's and the
|
||||
/// cell's own. Returns whether there were any.
|
||||
fn resolve_cell(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, accept: bool) -> Result<bool, CmdError> {
|
||||
@@ -263,16 +245,8 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st).into_iter().rev() {
|
||||
// A whole-paragraph mark that resolves to removal at the end of its container takes
|
||||
// the paragraph with it (there is no follower for `resolve_para` to join). A paragraph
|
||||
// followed by a table is not the end: removing it could make two tables adjacent.
|
||||
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
|
||||
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
|
||||
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
|
||||
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
|
||||
if trailing {
|
||||
remove_trailing_para(s, st, &path)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Tables, rows, cells, sections and style definitions.
|
||||
@@ -293,564 +267,11 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
resolve_loose_blocks(blocks, accept)?;
|
||||
}
|
||||
}
|
||||
// Keep revision entries still referenced by surviving stories or metadata (e.g., Ruby or
|
||||
// content-control run properties) and compact/remap the table; clear it directly when none
|
||||
// survive.
|
||||
retain_referenced_revisions(&mut s.doc);
|
||||
s.doc.revisions.clear();
|
||||
s.clamp_selection();
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn lookup_rev(idx: u32, remap: &[Option<u32>]) -> Option<u32> {
|
||||
remap.get(idx as usize).copied().flatten()
|
||||
}
|
||||
|
||||
fn remap_opt_rev(slot: &mut Option<u32>, remap: &[Option<u32>]) -> bool {
|
||||
let Some(old) = *slot else { return false };
|
||||
let next = lookup_rev(old, remap);
|
||||
if next != *slot {
|
||||
*slot = next;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn step_prop_change<'a, T>(
|
||||
slot: &'a mut Option<Box<wordcraft_doc::props::PropChange<T>>>,
|
||||
remap: &[Option<u32>],
|
||||
changed: &mut bool,
|
||||
) -> Option<&'a mut T> {
|
||||
let old = slot.as_ref()?.rev;
|
||||
let Some(new) = lookup_rev(old, remap) else {
|
||||
*slot = None;
|
||||
*changed = true;
|
||||
return None;
|
||||
};
|
||||
let ch = slot.as_deref_mut()?;
|
||||
if ch.rev != new {
|
||||
ch.rev = new;
|
||||
*changed = true;
|
||||
}
|
||||
Some(&mut ch.old)
|
||||
}
|
||||
|
||||
fn collect_char(mut c: &wordcraft_doc::CharProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
loop {
|
||||
if let Some(i) = c.ins {
|
||||
f(i);
|
||||
}
|
||||
if let Some(i) = c.del {
|
||||
f(i);
|
||||
}
|
||||
let Some(ch) = c.fmt_change.as_deref() else { break };
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
c = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_char(mut c: &mut wordcraft_doc::CharProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
loop {
|
||||
changed |= remap_opt_rev(&mut c.ins, remap);
|
||||
changed |= remap_opt_rev(&mut c.del, remap);
|
||||
let Some(old) = step_prop_change(&mut c.fmt_change, remap, &mut changed) else { break };
|
||||
c = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_para_props(mut p: &wordcraft_doc::ParaProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
loop {
|
||||
if let Some(nc) = p.num_change.as_deref() {
|
||||
f(nc.rev);
|
||||
}
|
||||
let Some(ch) = p.fmt_change.as_deref() else { break };
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
p = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_para_props(mut p: &mut wordcraft_doc::ParaProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
loop {
|
||||
if let Some(old) = p.num_change.as_deref().map(|nc| nc.rev) {
|
||||
match lookup_rev(old, remap) {
|
||||
Some(new) => {
|
||||
if let Some(nc) = p.num_change.as_deref_mut()
|
||||
&& nc.rev != new
|
||||
{
|
||||
nc.rev = new;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
p.num_change = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(old) = step_prop_change(&mut p.fmt_change, remap, &mut changed) else { break };
|
||||
p = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_section(mut s: &wordcraft_doc::SectionProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
while let Some(ch) = s.fmt_change.as_deref() {
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
s = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_section(mut s: &mut wordcraft_doc::SectionProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
while let Some(old) = step_prop_change(&mut s.fmt_change, remap, &mut changed) {
|
||||
s = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_table_props(mut t: &wordcraft_doc::props::TableProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
while let Some(ch) = t.fmt_change.as_deref() {
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
t = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_table_props(mut t: &mut wordcraft_doc::props::TableProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
while let Some(old) = step_prop_change(&mut t.fmt_change, remap, &mut changed) {
|
||||
t = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_row_props(mut r: &wordcraft_doc::props::RowProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
loop {
|
||||
if let Some(ex) = r.exceptions.as_deref() {
|
||||
collect_table_props(ex, f);
|
||||
}
|
||||
let Some(ch) = r.fmt_change.as_deref() else { break };
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
r = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_row_props(mut r: &mut wordcraft_doc::props::RowProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
loop {
|
||||
if let Some(ex) = r.exceptions.as_deref_mut() {
|
||||
changed |= remap_table_props(ex, remap);
|
||||
}
|
||||
let Some(old) = step_prop_change(&mut r.fmt_change, remap, &mut changed) else { break };
|
||||
r = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_cell_props(mut c: &wordcraft_doc::props::CellProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
while let Some(ch) = c.fmt_change.as_deref() {
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
c = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_cell_props(mut c: &mut wordcraft_doc::props::CellProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
while let Some(old) = step_prop_change(&mut c.fmt_change, remap, &mut changed) {
|
||||
c = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_leaf_object(obj: &InlineObject, f: &mut impl FnMut(u32) -> bool) {
|
||||
match obj {
|
||||
InlineObject::Ruby { props, .. } => collect_char(props, f),
|
||||
InlineObject::ControlStart { control } => {
|
||||
if let Some(rp) = &control.run_props {
|
||||
collect_char(rp, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_object(obj: &InlineObject, f: &mut impl FnMut(u32) -> bool) {
|
||||
let InlineObject::Group { children, .. } = obj else {
|
||||
collect_leaf_object(obj, f);
|
||||
return;
|
||||
};
|
||||
let mut stack = Vec::new();
|
||||
let mut cur = children.as_slice();
|
||||
loop {
|
||||
for ch in cur {
|
||||
match &ch.obj {
|
||||
InlineObject::Group { children: inner, .. } => {
|
||||
if !inner.is_empty() {
|
||||
stack.push(inner.as_slice());
|
||||
}
|
||||
}
|
||||
other => collect_leaf_object(other, f),
|
||||
}
|
||||
}
|
||||
let Some(next) = stack.pop() else { break };
|
||||
cur = next;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_leaf_object(obj: &mut InlineObject, remap: &[Option<u32>]) -> bool {
|
||||
match obj {
|
||||
InlineObject::Ruby { props, .. } => remap_char(props, remap),
|
||||
InlineObject::ControlStart { control } => control.run_props.as_mut().is_some_and(|rp| remap_char(rp, remap)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_object(obj: &mut InlineObject, remap: &[Option<u32>]) -> bool {
|
||||
let InlineObject::Group { children, .. } = obj else {
|
||||
return remap_leaf_object(obj, remap);
|
||||
};
|
||||
let mut changed = false;
|
||||
let mut stack = Vec::new();
|
||||
let mut cur = children.as_mut_slice();
|
||||
loop {
|
||||
for ch in cur {
|
||||
match &mut ch.obj {
|
||||
InlineObject::Group { children: inner, .. } => {
|
||||
if !inner.is_empty() {
|
||||
stack.push(inner.as_mut_slice());
|
||||
}
|
||||
}
|
||||
other => changed |= remap_leaf_object(other, remap),
|
||||
}
|
||||
}
|
||||
let Some(next) = stack.pop() else { break };
|
||||
cur = next;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_controls(wrap: &wordcraft_doc::ControlWrap, f: &mut impl FnMut(u32) -> bool) {
|
||||
for c in &wrap.open {
|
||||
if let Some(rp) = &c.run_props {
|
||||
collect_char(rp, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_controls(wrap: &mut wordcraft_doc::ControlWrap, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
for c in &mut wrap.open {
|
||||
if let Some(rp) = &mut c.run_props {
|
||||
changed |= remap_char(rp, remap);
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_para(p: &Paragraph, f: &mut impl FnMut(u32) -> bool) {
|
||||
collect_para_props(&p.props, f);
|
||||
for r in &p.runs {
|
||||
collect_char(&r.props, f);
|
||||
}
|
||||
collect_char(&p.mark, f);
|
||||
if let Some(sec) = p.section.as_deref() {
|
||||
collect_section(sec, f);
|
||||
}
|
||||
for obj in &p.objects {
|
||||
collect_object(obj, f);
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_table(table: &wordcraft_doc::table::Table, f: &mut impl FnMut(u32) -> bool) {
|
||||
let mut stack = Vec::new();
|
||||
let mut cur = table;
|
||||
loop {
|
||||
collect_table_props(&cur.props, f);
|
||||
collect_controls(&cur.controls, f);
|
||||
for row in &cur.rows {
|
||||
collect_row_props(&row.props, f);
|
||||
collect_controls(&row.controls, f);
|
||||
for cell in &row.cells {
|
||||
collect_cell_props(&cell.props, f);
|
||||
collect_controls(&cell.controls, f);
|
||||
for b in &cell.blocks {
|
||||
match b.as_ref() {
|
||||
wordcraft_doc::Block::Para(p) => collect_para(p, f),
|
||||
wordcraft_doc::Block::Table(nested) => stack.push(nested),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(next) = stack.pop() else { break };
|
||||
cur = next;
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_block(block: &wordcraft_doc::Block, f: &mut impl FnMut(u32) -> bool) {
|
||||
match block {
|
||||
wordcraft_doc::Block::Para(p) => collect_para(p, f),
|
||||
wordcraft_doc::Block::Table(t) => collect_table(t, f),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_blocks(blocks: &wordcraft_doc::Blocks, f: &mut impl FnMut(u32) -> bool) {
|
||||
for b in blocks {
|
||||
collect_block(b, f);
|
||||
}
|
||||
}
|
||||
|
||||
fn block_needs_rewrite(block: &wordcraft_doc::Block, remap: &[Option<u32>]) -> bool {
|
||||
let mut needs = false;
|
||||
collect_block(block, &mut |idx| {
|
||||
let next = lookup_rev(idx, remap);
|
||||
if next != Some(idx) {
|
||||
needs = true;
|
||||
}
|
||||
next.is_some()
|
||||
});
|
||||
needs
|
||||
}
|
||||
|
||||
fn remap_blocks(blocks: &mut wordcraft_doc::Blocks, remap: &[Option<u32>]) {
|
||||
let mut stack: Vec<&mut std::sync::Arc<wordcraft_doc::Block>> = blocks.iter_mut().collect();
|
||||
while let Some(arc_b) = stack.pop() {
|
||||
if !block_needs_rewrite(arc_b, remap) {
|
||||
continue;
|
||||
}
|
||||
match std::sync::Arc::make_mut(arc_b) {
|
||||
wordcraft_doc::Block::Para(p) => {
|
||||
let mut changed = remap_para_props(&mut p.props, remap);
|
||||
for r in &mut p.runs {
|
||||
changed |= remap_char(&mut r.props, remap);
|
||||
}
|
||||
changed |= remap_char(&mut p.mark, remap);
|
||||
if let Some(sec) = p.section.as_deref_mut() {
|
||||
changed |= remap_section(sec, remap);
|
||||
}
|
||||
for obj in &mut p.objects {
|
||||
changed |= remap_object(obj, remap);
|
||||
}
|
||||
if changed {
|
||||
p.touch();
|
||||
}
|
||||
}
|
||||
wordcraft_doc::Block::Table(t) => {
|
||||
remap_table_props(&mut t.props, remap);
|
||||
remap_controls(&mut t.controls, remap);
|
||||
for row in &mut t.rows {
|
||||
remap_row_props(&mut row.props, remap);
|
||||
remap_controls(&mut row.controls, remap);
|
||||
for cell in &mut row.cells {
|
||||
remap_cell_props(&mut cell.props, remap);
|
||||
remap_controls(&mut cell.controls, remap);
|
||||
stack.extend(cell.blocks.iter_mut());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_styles(styles: &wordcraft_doc::styles::StyleSheet, f: &mut impl FnMut(u32) -> bool) {
|
||||
collect_char(&styles.default_chr, f);
|
||||
collect_para_props(&styles.default_para, f);
|
||||
for st in &styles.styles {
|
||||
collect_para_props(&st.para, f);
|
||||
collect_char(&st.chr, f);
|
||||
if let Some(ch) = st.para_change.as_deref()
|
||||
&& f(ch.rev)
|
||||
{
|
||||
collect_para_props(&ch.old, f);
|
||||
}
|
||||
if let Some(ch) = st.chr_change.as_deref()
|
||||
&& f(ch.rev)
|
||||
{
|
||||
collect_char(&ch.old, f);
|
||||
}
|
||||
if let Some(tbl) = &st.table {
|
||||
for c in [&tbl.header_chr, &tbl.band_chr, &tbl.first_col_chr, &tbl.total_chr, &tbl.last_col_chr, &tbl.col_band_chr] {
|
||||
collect_char(c, f);
|
||||
}
|
||||
for pf in tbl.regions.values() {
|
||||
collect_char(&pf.chr, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_styles(styles: &mut std::sync::Arc<wordcraft_doc::styles::StyleSheet>, remap: &[Option<u32>]) {
|
||||
let mut needs = false;
|
||||
collect_styles(styles, &mut |idx| {
|
||||
let next = lookup_rev(idx, remap);
|
||||
if next != Some(idx) {
|
||||
needs = true;
|
||||
}
|
||||
next.is_some()
|
||||
});
|
||||
if !needs {
|
||||
return;
|
||||
}
|
||||
let styles = std::sync::Arc::make_mut(styles);
|
||||
remap_char(&mut styles.default_chr, remap);
|
||||
remap_para_props(&mut styles.default_para, remap);
|
||||
for st in &mut styles.styles {
|
||||
remap_para_props(&mut st.para, remap);
|
||||
remap_char(&mut st.chr, remap);
|
||||
let mut dummy = false;
|
||||
if let Some(old) = step_prop_change(&mut st.para_change, remap, &mut dummy) {
|
||||
remap_para_props(old, remap);
|
||||
}
|
||||
if let Some(old) = step_prop_change(&mut st.chr_change, remap, &mut dummy) {
|
||||
remap_char(old, remap);
|
||||
}
|
||||
if let Some(tbl) = &mut st.table {
|
||||
for c in
|
||||
[&mut tbl.header_chr, &mut tbl.band_chr, &mut tbl.first_col_chr, &mut tbl.total_chr, &mut tbl.last_col_chr, &mut tbl.col_band_chr]
|
||||
{
|
||||
remap_char(c, remap);
|
||||
}
|
||||
for pf in tbl.regions.values_mut() {
|
||||
remap_char(&mut pf.chr, remap);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_numbering(numbering: &wordcraft_doc::numbering::Numbering, f: &mut impl FnMut(u32) -> bool) {
|
||||
for abs in &numbering.abstracts {
|
||||
for lvl in &abs.levels {
|
||||
collect_char(&lvl.chr, f);
|
||||
}
|
||||
}
|
||||
for num in &numbering.nums {
|
||||
for (_, lvl) in &num.level_overrides {
|
||||
collect_char(&lvl.chr, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_numbering(numbering: &mut std::sync::Arc<wordcraft_doc::numbering::Numbering>, remap: &[Option<u32>]) {
|
||||
let mut needs = false;
|
||||
collect_numbering(numbering, &mut |idx| {
|
||||
let next = lookup_rev(idx, remap);
|
||||
if next != Some(idx) {
|
||||
needs = true;
|
||||
}
|
||||
next.is_some()
|
||||
});
|
||||
if !needs {
|
||||
return;
|
||||
}
|
||||
let numbering = std::sync::Arc::make_mut(numbering);
|
||||
for abs in &mut numbering.abstracts {
|
||||
for lvl in &mut abs.levels {
|
||||
remap_char(&mut lvl.chr, remap);
|
||||
}
|
||||
}
|
||||
for num in &mut numbering.nums {
|
||||
for (_, lvl) in &mut num.level_overrides {
|
||||
remap_char(&mut lvl.chr, remap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_doc_revisions(doc: &wordcraft_doc::Document, f: &mut impl FnMut(u32) -> bool) {
|
||||
collect_blocks(&doc.body, f);
|
||||
collect_section(&doc.last_section, f);
|
||||
for part in doc.parts.values() {
|
||||
collect_blocks(&part.blocks, f);
|
||||
}
|
||||
for sep in [&doc.footnote_separators, &doc.endnote_separators] {
|
||||
for blocks in [&sep.separator, &sep.continuation_separator, &sep.continuation_notice].into_iter().flatten() {
|
||||
collect_blocks(blocks, f);
|
||||
}
|
||||
}
|
||||
for bb in &doc.glossary {
|
||||
collect_blocks(&bb.blocks, f);
|
||||
}
|
||||
collect_styles(&doc.styles, f);
|
||||
collect_numbering(&doc.numbering, f);
|
||||
}
|
||||
|
||||
fn rewrite_doc_revisions(doc: &mut wordcraft_doc::Document, remap: &[Option<u32>]) {
|
||||
remap_blocks(&mut doc.body, remap);
|
||||
remap_section(&mut doc.last_section, remap);
|
||||
for part in doc.parts.values_mut() {
|
||||
remap_blocks(&mut part.blocks, remap);
|
||||
}
|
||||
for sep in [&mut doc.footnote_separators, &mut doc.endnote_separators] {
|
||||
for blocks in [&mut sep.separator, &mut sep.continuation_separator, &mut sep.continuation_notice].into_iter().flatten() {
|
||||
remap_blocks(blocks, remap);
|
||||
}
|
||||
}
|
||||
for bb in &mut doc.glossary {
|
||||
remap_blocks(&mut bb.blocks, remap);
|
||||
}
|
||||
remap_styles(&mut doc.styles, remap);
|
||||
remap_numbering(&mut doc.numbering, remap);
|
||||
}
|
||||
|
||||
/// Retain only revision entries still referenced by `doc`, compacting `doc.revisions` and remapping
|
||||
/// surviving references (or clearing invalid out-of-bounds ones). On the common path with no
|
||||
/// surviving references, the walk avoids heap allocation for paragraphs, non-nested tables, and
|
||||
/// non-nested inline objects (an iterative stack allocates only for tables inside tables or groups
|
||||
/// inside groups), `BTreeSet::new()` never allocates, and `doc.revisions.clear()` runs directly
|
||||
/// without allocating `remap`/`kept` or running the rewrite pass.
|
||||
fn retain_referenced_revisions(doc: &mut wordcraft_doc::Document) {
|
||||
let old_len = doc.revisions.len();
|
||||
let mut used = std::collections::BTreeSet::new();
|
||||
let mut has_invalid = false;
|
||||
// The callback returns whether the visited index is valid; PropChange walkers stop descending
|
||||
// into `ch.old` when an outer `ch.rev` is out of bounds because `step_prop_change` discards the
|
||||
// whole outer PropChange (including any nested indices buried inside it). That keeps the table
|
||||
// at its exact fixed point in a single pass.
|
||||
collect_doc_revisions(doc, &mut |idx| {
|
||||
if (idx as usize) < old_len {
|
||||
used.insert(idx);
|
||||
true
|
||||
} else {
|
||||
has_invalid = true;
|
||||
false
|
||||
}
|
||||
});
|
||||
if used.is_empty() && !has_invalid {
|
||||
doc.revisions.clear();
|
||||
return;
|
||||
}
|
||||
if !has_invalid && used.len() == old_len {
|
||||
return;
|
||||
}
|
||||
let mut remap = vec![None; old_len];
|
||||
let mut kept = Vec::with_capacity(used.len());
|
||||
let mut needs_rewrite = has_invalid;
|
||||
for old in used {
|
||||
let new = kept.len() as u32;
|
||||
remap[old as usize] = Some(new);
|
||||
if new != old {
|
||||
needs_rewrite = true;
|
||||
}
|
||||
kept.push(doc.revisions[old as usize].clone());
|
||||
}
|
||||
doc.revisions = kept;
|
||||
if needs_rewrite {
|
||||
rewrite_doc_revisions(doc, &remap);
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept or Reject All; with `stopTracking`, Track Changes is turned off as well.
|
||||
pub(super) fn resolve_all_then(s: &mut Session, v: &Value, accept: bool) -> CmdResult {
|
||||
let out = resolve_all(s, accept)?;
|
||||
|
||||
@@ -128,20 +128,6 @@ pub(super) fn suggestions(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
}
|
||||
|
||||
/// The word at the caret that the thesaurus looks up and a chosen synonym replaces: the word unit
|
||||
/// without the spaces after it or the quotes around it, so `‘good’` is `good` and its quotes stay
|
||||
/// when it is replaced; an apostrophe inside a word (`don’t`) is kept (#6517).
|
||||
pub fn thesaurus_word(s: &Session) -> Option<(Pos, Pos)> {
|
||||
let f = &s.sel.focus;
|
||||
let p = s.doc.para_at(f)?;
|
||||
let (a, b) = p.word_at(f.off);
|
||||
let w = p.text.get(a..b)?;
|
||||
let edge = |c: char| c.is_whitespace() || matches!(c, '’' | '‘' | '\'');
|
||||
let start = a + (w.len() - w.trim_start_matches(edge).len());
|
||||
let end = (a + w.trim_end_matches(edge).len()).max(start);
|
||||
Some((Pos { off: start, ..f.clone() }, Pos { off: end, ..f.clone() }))
|
||||
}
|
||||
|
||||
/// A tiny built-in thesaurus of common words (our own list).
|
||||
pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
|
||||
const T: &[(&str, &[&str])] = &[
|
||||
@@ -178,8 +164,10 @@ pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let word = match p::str(v, "word") {
|
||||
Some(w) => w.to_lowercase(),
|
||||
None => {
|
||||
let (a, b) = thesaurus_word(s).ok_or_else(|| CmdError::Failed("no word".into()))?;
|
||||
s.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).unwrap_or("").to_lowercase()
|
||||
let f = s.sel.focus.clone();
|
||||
let p = s.doc.para_at(&f).ok_or_else(|| CmdError::Failed("no word".into()))?;
|
||||
let (a, b) = p.word_at(f.off);
|
||||
p.text.get(a..b).unwrap_or("").trim().to_lowercase()
|
||||
}
|
||||
};
|
||||
let syn = T.iter().find(|(w, _)| *w == word).map(|(_, l)| l.to_vec()).unwrap_or_default();
|
||||
|
||||
@@ -703,20 +703,6 @@ fn accept_and_reject_can_move_to_the_next_change() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_shortcut_commands_resolve_and_select_the_next_change_without_parameters() {
|
||||
for (command, accept) in [("review.acceptAndNext", true), ("review.rejectAndNext", false)] {
|
||||
let mut s = three_changes();
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
s.run(command, &serde_json::Value::Null).unwrap();
|
||||
let remaining = change_spans(&mut s);
|
||||
assert_eq!(remaining.iter().map(|change| change.0.as_str()).collect::<Vec<_>>(), ["delete", "insert"], "{command}");
|
||||
let (_, start, end) = remaining[0];
|
||||
assert_eq!(selected(&s), (start as usize, end as usize), "{command}: the deletion is selected next");
|
||||
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).starts_with("new "), accept, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With the caret on no change, Accept and Move to Next selects the next change without
|
||||
/// resolving it, as Accept and Next Change do.
|
||||
#[test]
|
||||
@@ -1262,7 +1248,7 @@ fn rtf_tracked_changes_accept_and_reject_after_opening_and_round_trip() {
|
||||
let rtf: &[u8] = br"{\rtf1\ansi\deff0{\fonttbl{\f0 Arial;}}{\*\revtbl {Unknown;}{Alice;}{Bob;}}
|
||||
\pard Keep {\revised\revauth1\revdttm-1480361314 added }text{\deleted\revauthdel2\revdttmdel-2016341499 gone} end{\revised\revauth1\revdttm-1480361314\deleted\revauthdel2\revdttmdel-2016341499 both}.\par}";
|
||||
let opened = wordcraft_formats::rtf::import(rtf).unwrap();
|
||||
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).unwrap().as_bytes()).unwrap();
|
||||
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).as_bytes()).unwrap();
|
||||
for doc in [opened, again] {
|
||||
for (cmd, want) in [("review.acceptAll", "Keep added text end."), ("review.rejectAll", "Keep text gone end.")] {
|
||||
let mut s = Session::new(doc.clone());
|
||||
@@ -1420,533 +1406,3 @@ fn preexisting_table_with_redlined_cell_content_preserves_table_shell() {
|
||||
assert!(s_rt.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect every revision reference `(location, idx, expected_kind)` surviving anywhere in `doc`
|
||||
/// and assert that each resolves to an existing entry in `doc.revisions` of the expected kind.
|
||||
fn assert_all_revision_refs_valid(doc: &Document, label: &str) -> usize {
|
||||
use wordcraft_doc::{
|
||||
Block, Blocks, CharProps, InlineObject, ParaProps, RevisionKind, SectionProps,
|
||||
props::{CellProps, RowProps, TableProps},
|
||||
};
|
||||
|
||||
fn check_idx(doc: &Document, label: &str, loc: &str, idx: u32, expected: RevisionKind, count: &mut usize) {
|
||||
*count += 1;
|
||||
let rev = doc.revisions.get(idx as usize).unwrap_or_else(|| {
|
||||
panic!("{label}: dangling revision index {idx} at {loc} (revisions.len() == {})", doc.revisions.len());
|
||||
});
|
||||
assert_eq!(rev.kind, expected, "{label}: revision index {idx} at {loc} has kind {:?}, expected {expected:?}", rev.kind);
|
||||
}
|
||||
|
||||
fn walk_char(doc: &Document, label: &str, loc: &str, c: &CharProps, count: &mut usize) {
|
||||
if let Some(i) = c.ins {
|
||||
check_idx(doc, label, &format!("{loc}.ins"), i, RevisionKind::Insert, count);
|
||||
}
|
||||
if let Some(i) = c.del {
|
||||
check_idx(doc, label, &format!("{loc}.del"), i, RevisionKind::Delete, count);
|
||||
}
|
||||
if let Some(ch) = &c.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_char(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_para_props(doc: &Document, label: &str, loc: &str, p: &ParaProps, count: &mut usize) {
|
||||
if let Some(nc) = &p.num_change {
|
||||
check_idx(doc, label, &format!("{loc}.num_change"), nc.rev, RevisionKind::Format, count);
|
||||
}
|
||||
if let Some(ch) = &p.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_para_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_section(doc: &Document, label: &str, loc: &str, s: &SectionProps, count: &mut usize) {
|
||||
if let Some(ch) = &s.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_section(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_table_props(doc: &Document, label: &str, loc: &str, t: &TableProps, count: &mut usize) {
|
||||
if let Some(ch) = &t.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_table_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_row_props(doc: &Document, label: &str, loc: &str, r: &RowProps, count: &mut usize) {
|
||||
if let Some(ex) = r.exceptions.as_deref() {
|
||||
walk_table_props(doc, label, &format!("{loc}.exceptions"), ex, count);
|
||||
}
|
||||
if let Some(ch) = &r.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_row_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_cell_props(doc: &Document, label: &str, loc: &str, c: &CellProps, count: &mut usize) {
|
||||
if let Some(ch) = &c.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_cell_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_object(doc: &Document, label: &str, loc: &str, obj: &InlineObject, count: &mut usize) {
|
||||
match obj {
|
||||
InlineObject::Ruby { props, .. } => walk_char(doc, label, &format!("{loc}.ruby.props"), props, count),
|
||||
InlineObject::ControlStart { control } => {
|
||||
if let Some(rp) = &control.run_props {
|
||||
walk_char(doc, label, &format!("{loc}.control.run_props"), rp, count);
|
||||
}
|
||||
}
|
||||
InlineObject::Group { children, .. } => {
|
||||
for (i, ch) in children.iter().enumerate() {
|
||||
walk_object(doc, label, &format!("{loc}.group[{i}]"), &ch.obj, count);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_blocks(doc: &Document, label: &str, loc: &str, blocks: &Blocks, count: &mut usize) {
|
||||
for (bi, b) in blocks.iter().enumerate() {
|
||||
match &**b {
|
||||
Block::Para(p) => {
|
||||
let ploc = format!("{loc}[{bi}]");
|
||||
walk_para_props(doc, label, &format!("{ploc}.props"), &p.props, count);
|
||||
for (ri, r) in p.runs.iter().enumerate() {
|
||||
walk_char(doc, label, &format!("{ploc}.runs[{ri}]"), &r.props, count);
|
||||
}
|
||||
walk_char(doc, label, &format!("{ploc}.mark"), &p.mark, count);
|
||||
if let Some(sec) = p.section.as_deref() {
|
||||
walk_section(doc, label, &format!("{ploc}.section"), sec, count);
|
||||
}
|
||||
for (oi, obj) in p.objects.iter().enumerate() {
|
||||
walk_object(doc, label, &format!("{ploc}.objects[{oi}]"), obj, count);
|
||||
}
|
||||
}
|
||||
Block::Table(t) => {
|
||||
let tloc = format!("{loc}[{bi}]");
|
||||
walk_table_props(doc, label, &format!("{tloc}.props"), &t.props, count);
|
||||
for (ci, ctl) in t.controls.open.iter().enumerate() {
|
||||
if let Some(rp) = &ctl.run_props {
|
||||
walk_char(doc, label, &format!("{tloc}.controls[{ci}].run_props"), rp, count);
|
||||
}
|
||||
}
|
||||
for (ri, row) in t.rows.iter().enumerate() {
|
||||
walk_row_props(doc, label, &format!("{tloc}.rows[{ri}].props"), &row.props, count);
|
||||
for (ci, ctl) in row.controls.open.iter().enumerate() {
|
||||
if let Some(rp) = &ctl.run_props {
|
||||
walk_char(doc, label, &format!("{tloc}.rows[{ri}].controls[{ci}].run_props"), rp, count);
|
||||
}
|
||||
}
|
||||
for (ci, cell) in row.cells.iter().enumerate() {
|
||||
walk_cell_props(doc, label, &format!("{tloc}.rows[{ri}].cells[{ci}].props"), &cell.props, count);
|
||||
for (ki, ctl) in cell.controls.open.iter().enumerate() {
|
||||
if let Some(rp) = &ctl.run_props {
|
||||
walk_char(doc, label, &format!("{tloc}.rows[{ri}].cells[{ci}].controls[{ki}].run_props"), rp, count);
|
||||
}
|
||||
}
|
||||
walk_blocks(doc, label, &format!("{tloc}.rows[{ri}].cells[{ci}].blocks"), &cell.blocks, count);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut count = 0;
|
||||
walk_blocks(doc, label, "body", &doc.body, &mut count);
|
||||
walk_section(doc, label, "last_section", &doc.last_section, &mut count);
|
||||
for (id, part) in &doc.parts {
|
||||
walk_blocks(doc, label, &format!("part({:?}#{id})", part.kind), &part.blocks, &mut count);
|
||||
}
|
||||
for (sname, sep) in [("footnote_separators", &doc.footnote_separators), ("endnote_separators", &doc.endnote_separators)] {
|
||||
for (fname, blocks) in [
|
||||
("separator", &sep.separator),
|
||||
("continuation_separator", &sep.continuation_separator),
|
||||
("continuation_notice", &sep.continuation_notice),
|
||||
] {
|
||||
if let Some(bl) = blocks {
|
||||
walk_blocks(doc, label, &format!("{sname}.{fname}"), bl, &mut count);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (gi, bb) in doc.glossary.iter().enumerate() {
|
||||
walk_blocks(doc, label, &format!("glossary[{gi}]"), &bb.blocks, &mut count);
|
||||
}
|
||||
walk_char(doc, label, "styles.default_chr", &doc.styles.default_chr, &mut count);
|
||||
walk_para_props(doc, label, "styles.default_para", &doc.styles.default_para, &mut count);
|
||||
for st in &doc.styles.styles {
|
||||
walk_para_props(doc, label, &format!("styles[{}].para", st.id), &st.para, &mut count);
|
||||
walk_char(doc, label, &format!("styles[{}].chr", st.id), &st.chr, &mut count);
|
||||
if let Some(ch) = &st.para_change {
|
||||
check_idx(doc, label, &format!("styles[{}].para_change", st.id), ch.rev, RevisionKind::Format, &mut count);
|
||||
walk_para_props(doc, label, &format!("styles[{}].para_change.old", st.id), &ch.old, &mut count);
|
||||
}
|
||||
if let Some(ch) = &st.chr_change {
|
||||
check_idx(doc, label, &format!("styles[{}].chr_change", st.id), ch.rev, RevisionKind::Format, &mut count);
|
||||
walk_char(doc, label, &format!("styles[{}].chr_change.old", st.id), &ch.old, &mut count);
|
||||
}
|
||||
if let Some(tbl) = &st.table {
|
||||
for (k, c) in [
|
||||
("header_chr", &tbl.header_chr),
|
||||
("band_chr", &tbl.band_chr),
|
||||
("first_col_chr", &tbl.first_col_chr),
|
||||
("total_chr", &tbl.total_chr),
|
||||
("last_col_chr", &tbl.last_col_chr),
|
||||
("col_band_chr", &tbl.col_band_chr),
|
||||
] {
|
||||
walk_char(doc, label, &format!("styles[{}].table.{k}", st.id), c, &mut count);
|
||||
}
|
||||
for (rk, pf) in &tbl.regions {
|
||||
walk_char(doc, label, &format!("styles[{}].table.regions[{rk:?}].chr", st.id), &pf.chr, &mut count);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (ai, abs) in doc.numbering.abstracts.iter().enumerate() {
|
||||
for (li, lvl) in abs.levels.iter().enumerate() {
|
||||
walk_char(doc, label, &format!("numbering.abstracts[{ai}].levels[{li}].chr"), &lvl.chr, &mut count);
|
||||
}
|
||||
}
|
||||
for (ni, num) in doc.numbering.nums.iter().enumerate() {
|
||||
for (li, (_, lvl)) in num.level_overrides.iter().enumerate() {
|
||||
walk_char(doc, label, &format!("numbering.nums[{ni}].level_overrides[{li}].chr"), &lvl.chr, &mut count);
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// #8129: Accept All / Reject All must not invalidate revision references that survive in
|
||||
/// preserved annotation properties (e.g., a Ruby guide in a header story carrying a Format record
|
||||
/// into the document's own revision table).
|
||||
#[test]
|
||||
fn accept_and_reject_all_keep_surviving_header_ruby_revision_valid() {
|
||||
use wordcraft_doc::{
|
||||
CharProps, InlineObject, Paragraph, PartKind, Revision, RevisionKind, StoryRef, para::RubyAlign, para_block, props::PropChange,
|
||||
};
|
||||
|
||||
let mut orig = Document::from_text("Original body text.");
|
||||
// Populate indices 0..=4 so the header Ruby guide owns Format revision at index 4.
|
||||
for i in 0..4 {
|
||||
orig.revisions.push(Revision::new(RevisionKind::Insert, format!("Prior {i}"), "2026-11-28T00:00:00Z"));
|
||||
}
|
||||
orig.revisions.push(Revision::new(RevisionKind::Format, "HeaderOwner", "2026-11-29T00:00:00Z"));
|
||||
|
||||
let mut header_para = Paragraph::new();
|
||||
let ruby = InlineObject::Ruby {
|
||||
base: "漢字".into(),
|
||||
ruby: "かんじ".into(),
|
||||
align: RubyAlign::Center,
|
||||
size: 6.0,
|
||||
raise: 10.0,
|
||||
base_size: 12.0,
|
||||
lang: "ja-JP".into(),
|
||||
props: Box::new(CharProps { bold: Some(true), fmt_change: PropChange::boxed(4, CharProps::default()), ..Default::default() }),
|
||||
};
|
||||
header_para.insert_object(0, ruby, &CharProps::default()).unwrap();
|
||||
let header_id = orig.add_part(PartKind::Header, vec![para_block(header_para)]);
|
||||
orig.last_section.headers.default = Some(header_id);
|
||||
|
||||
// Body-only edit compared against `orig`: compare preserves the header and its index-4 record.
|
||||
let mut compared = Session::new(orig);
|
||||
compared.run("review.compare", &json!({"text": "Revised body text.", "author": "Reviewer"})).unwrap();
|
||||
assert!(assert_all_revision_refs_valid(&compared.doc, "after compare") >= 3);
|
||||
|
||||
for (cmd, want_body) in [("review.acceptAll", "Revised body text."), ("review.rejectAll", "Original body text.")] {
|
||||
let mut s = Session::new(compared.doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd}: body endpoint");
|
||||
let surviving = assert_all_revision_refs_valid(&s.doc, cmd);
|
||||
assert_eq!(surviving, 1, "{cmd}: header Ruby revision reference survives");
|
||||
let header = s.doc.parts.get(&header_id).expect("header preserved");
|
||||
let hp = header.blocks[0].as_para().expect("header paragraph");
|
||||
let InlineObject::Ruby { props, .. } = &hp.objects[0] else { panic!("expected Ruby") };
|
||||
let rev_idx = props.fmt_change.as_ref().expect("Ruby fmt_change preserved").rev;
|
||||
let rev = &s.doc.revisions[rev_idx as usize];
|
||||
assert_eq!(rev.kind, RevisionKind::Format);
|
||||
assert_eq!(rev.author, "HeaderOwner");
|
||||
assert_eq!(rev.date, "2026-11-29T00:00:00Z");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8129: Surviving revision references across footer, footnote, comment, and text-box stories
|
||||
/// (including shared indices and ContentControl run_props) remain valid and compacted after both
|
||||
/// Accept All and Reject All, and repeated resolution is idempotent.
|
||||
#[test]
|
||||
fn accept_and_reject_all_keep_surviving_refs_across_other_stories() {
|
||||
use wordcraft_doc::{
|
||||
CharProps, Comment, ContentControl, ControlKind, InlineObject, Paragraph, PartKind, Revision, RevisionKind, StoryRef,
|
||||
para::{NoteKind, RubyAlign, ShapeKind},
|
||||
para_block,
|
||||
props::PropChange,
|
||||
};
|
||||
|
||||
let make_ruby = |rev: u32| InlineObject::Ruby {
|
||||
base: "漢".into(),
|
||||
ruby: "かん".into(),
|
||||
align: RubyAlign::Center,
|
||||
size: 6.0,
|
||||
raise: 10.0,
|
||||
base_size: 12.0,
|
||||
lang: "ja-JP".into(),
|
||||
props: Box::new(CharProps { bold: Some(true), fmt_change: PropChange::boxed(rev, CharProps::default()), ..Default::default() }),
|
||||
};
|
||||
|
||||
let mut doc = Document::from_text("");
|
||||
// Indices 0..=7; only 2 (Footer/TextBox) and 5 (Footnote/Comment) survive resolution.
|
||||
doc.revisions.push(Revision::new(RevisionKind::Insert, "Unused0", "2026-11-20T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Delete, "Unused1", "2026-11-21T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Format, "FooterOwner", "2026-11-22T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Insert, "Unused3", "2026-11-23T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Delete, "Unused4", "2026-11-24T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Format, "FootnoteOwner", "2026-11-25T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Insert, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Delete, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
|
||||
let mut footer_para = Paragraph::new();
|
||||
footer_para.insert_object(0, make_ruby(2), &CharProps::default()).unwrap();
|
||||
let footer_id = doc.add_part(PartKind::Footer, vec![para_block(footer_para)]);
|
||||
doc.last_section.footers.default = Some(footer_id);
|
||||
|
||||
let mut footnote_para = Paragraph::new();
|
||||
let mut ctl = ContentControl::new(ControlKind::RichText);
|
||||
ctl.run_props = Some(CharProps { italic: Some(true), fmt_change: PropChange::boxed(5, CharProps::default()), ..Default::default() });
|
||||
footnote_para.insert_object(0, InlineObject::ControlStart { control: Box::new(ctl) }, &CharProps::default()).unwrap();
|
||||
footnote_para.insert_object(footnote_para.len(), InlineObject::ControlEnd, &CharProps::default()).unwrap();
|
||||
let footnote_id = doc.add_part(PartKind::Footnote, vec![para_block(footnote_para)]);
|
||||
|
||||
let mut textbox_para = Paragraph::new();
|
||||
textbox_para.insert_object(0, make_ruby(2), &CharProps::default()).unwrap();
|
||||
let textbox_id = doc.add_part(PartKind::TextBox, vec![para_block(textbox_para)]);
|
||||
|
||||
let mut comment_para = Paragraph::new();
|
||||
comment_para.insert_object(0, make_ruby(5), &CharProps::default()).unwrap();
|
||||
let comment_id = doc.add_part(PartKind::Comment, vec![para_block(comment_para)]);
|
||||
doc.comments.insert(1, Comment { author: "Alice".into(), part: comment_id, ..Default::default() });
|
||||
|
||||
let body_p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
|
||||
body_p.insert_text(body_p.len(), "Revised", &CharProps { ins: Some(6), ..Default::default() }).unwrap();
|
||||
body_p.insert_text(body_p.len(), "Original", &CharProps { del: Some(7), ..Default::default() }).unwrap();
|
||||
body_p.insert_text(body_p.len(), " body.", &CharProps::default()).unwrap();
|
||||
body_p
|
||||
.insert_object(
|
||||
body_p.len(),
|
||||
InlineObject::NoteRef { kind: NoteKind::Footnote, id: footnote_id, custom: String::new() },
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
body_p
|
||||
.insert_object(
|
||||
body_p.len(),
|
||||
InlineObject::Shape {
|
||||
kind: ShapeKind::Rectangle,
|
||||
w: 72.0,
|
||||
h: 36.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story: Some(textbox_id),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
},
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
body_p.insert_object(0, InlineObject::CommentStart { id: 1 }, &CharProps::default()).unwrap();
|
||||
body_p.insert_object(body_p.len(), InlineObject::CommentEnd { id: 1 }, &CharProps::default()).unwrap();
|
||||
assert_eq!(assert_all_revision_refs_valid(&doc, "before resolution"), 6);
|
||||
|
||||
for (cmd, want_body) in [("review.acceptAll", "Revised body."), ("review.rejectAll", "Original body.")] {
|
||||
let mut s = Session::new(doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd}: body endpoint");
|
||||
assert_eq!(assert_all_revision_refs_valid(&s.doc, cmd), 4, "{cmd}: 4 surviving references");
|
||||
assert_eq!(s.doc.revisions.len(), 2, "{cmd}: compacted to 2 distinct referenced revisions");
|
||||
|
||||
let InlineObject::Ruby { props: footer_props, .. } = &s.doc.parts[&footer_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected footer Ruby");
|
||||
};
|
||||
let InlineObject::ControlStart { control: fn_ctl } = &s.doc.parts[&footnote_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected footnote ControlStart");
|
||||
};
|
||||
let InlineObject::Ruby { props: tb_props, .. } = &s.doc.parts[&textbox_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected textbox Ruby");
|
||||
};
|
||||
let InlineObject::Ruby { props: cm_props, .. } = &s.doc.parts[&comment_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected comment Ruby");
|
||||
};
|
||||
|
||||
let footer_rev = footer_props.fmt_change.as_ref().unwrap().rev;
|
||||
let tb_rev = tb_props.fmt_change.as_ref().unwrap().rev;
|
||||
let fn_rev = fn_ctl.run_props.as_ref().unwrap().fmt_change.as_ref().unwrap().rev;
|
||||
let cm_rev = cm_props.fmt_change.as_ref().unwrap().rev;
|
||||
|
||||
assert_eq!(footer_rev, tb_rev, "{cmd}: shared index preserved across footer and textbox");
|
||||
assert_eq!(fn_rev, cm_rev, "{cmd}: shared index preserved across footnote and comment");
|
||||
assert_eq!(s.doc.revisions[footer_rev as usize].author, "FooterOwner");
|
||||
assert_eq!(s.doc.revisions[fn_rev as usize].author, "FootnoteOwner");
|
||||
|
||||
// Second pass must be idempotent.
|
||||
let after_first = s.doc.clone();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc, after_first, "{cmd}: second pass must be a no-op");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8129: Common path — when Accept All or Reject All leaves no surviving revision references
|
||||
/// anywhere in the document, the revision table is cleared completely as before.
|
||||
#[test]
|
||||
fn accept_and_reject_all_clear_revision_table_when_no_refs_survive() {
|
||||
use wordcraft_doc::{CharProps, Paragraph, PartKind, Revision, RevisionKind, StoryRef, para_block};
|
||||
|
||||
let mut doc = Document::from_text("Body ");
|
||||
doc.revisions.push(Revision::new(RevisionKind::Insert, "Alice", "2026-11-29T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Delete, "Bob", "2026-11-29T00:00:00Z"));
|
||||
let body_p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
|
||||
body_p.insert_text(body_p.len(), "new", &CharProps { ins: Some(0), ..Default::default() }).unwrap();
|
||||
body_p.insert_text(body_p.len(), "old", &CharProps { del: Some(1), ..Default::default() }).unwrap();
|
||||
|
||||
let mut header_p = Paragraph::with_text("Hdr ", CharProps::default());
|
||||
header_p.insert_text(header_p.len(), "ins", &CharProps { ins: Some(0), ..Default::default() }).unwrap();
|
||||
let header_id = doc.add_part(PartKind::Header, vec![para_block(header_p)]);
|
||||
doc.last_section.headers.default = Some(header_id);
|
||||
|
||||
for (cmd, want_body, want_hdr) in [("review.acceptAll", "Body new", "Hdr ins"), ("review.rejectAll", "Body old", "Hdr ")] {
|
||||
let mut s = Session::new(doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd}: body endpoint");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(header_id)), want_hdr, "{cmd}: header endpoint");
|
||||
assert_eq!(assert_all_revision_refs_valid(&s.doc, cmd), 0);
|
||||
assert!(s.doc.revisions.is_empty(), "{cmd}: revision table cleared when no references survive");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8129: Malformed input — an out-of-bounds outer `PropChange` burying a valid inner revision
|
||||
/// index must reach its fixed point in a single Accept All / Reject All pass: the buried record
|
||||
/// is discarded along with its invalid outer change, the table contains only records still
|
||||
/// referenced, and a second resolution pass leaves the document identical.
|
||||
#[test]
|
||||
fn accept_and_reject_all_reach_fixed_point_with_buried_rev_in_invalid_outer_change() {
|
||||
use wordcraft_doc::{
|
||||
CharProps, InlineObject, Paragraph, PartKind, Revision, RevisionKind, StoryRef, para::RubyAlign, para_block, props::PropChange,
|
||||
};
|
||||
|
||||
let make_ruby = |props: CharProps| InlineObject::Ruby {
|
||||
base: "漢".into(),
|
||||
ruby: "かん".into(),
|
||||
align: RubyAlign::Center,
|
||||
size: 6.0,
|
||||
raise: 10.0,
|
||||
base_size: 12.0,
|
||||
lang: "ja-JP".into(),
|
||||
props: Box::new(props),
|
||||
};
|
||||
|
||||
// Case 1: Only surviving reference carrier is malformed (invalid outer rev 99 burying valid
|
||||
// inner rev 0). One pass must clear both the malformed PropChange and the revision table.
|
||||
let mut sole_doc = Document::from_text("");
|
||||
sole_doc.revisions.push(Revision::new(RevisionKind::Format, "BuriedInner", "2026-11-28T00:00:00Z"));
|
||||
sole_doc.revisions.push(Revision::new(RevisionKind::Insert, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
sole_doc.revisions.push(Revision::new(RevisionKind::Delete, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
|
||||
let mut hdr_para = Paragraph::new();
|
||||
let buried_props = CharProps {
|
||||
bold: Some(true),
|
||||
fmt_change: PropChange::boxed(99, CharProps { fmt_change: PropChange::boxed(0, CharProps::default()), ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
hdr_para.insert_object(0, make_ruby(buried_props), &CharProps::default()).unwrap();
|
||||
let hdr_id = sole_doc.add_part(PartKind::Header, vec![para_block(hdr_para)]);
|
||||
sole_doc.last_section.headers.default = Some(hdr_id);
|
||||
|
||||
let body_p = sole_doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
|
||||
body_p.insert_text(body_p.len(), "New", &CharProps { ins: Some(1), ..Default::default() }).unwrap();
|
||||
body_p.insert_text(body_p.len(), "Old", &CharProps { del: Some(2), ..Default::default() }).unwrap();
|
||||
|
||||
for (cmd, want_body) in [("review.acceptAll", "New"), ("review.rejectAll", "Old")] {
|
||||
let mut s = Session::new(sole_doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd} sole: body endpoint");
|
||||
assert_eq!(assert_all_revision_refs_valid(&s.doc, &format!("{cmd} sole")), 0);
|
||||
assert!(s.doc.revisions.is_empty(), "{cmd} sole: buried revision must not linger after pass 1");
|
||||
let InlineObject::Ruby { props, .. } = &s.doc.parts[&hdr_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected Ruby");
|
||||
};
|
||||
assert!(props.fmt_change.is_none(), "{cmd} sole: invalid outer fmt_change discarded");
|
||||
|
||||
let after_first = s.doc.clone();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc, after_first, "{cmd} sole: second pass must be a no-op");
|
||||
}
|
||||
|
||||
// Case 2: Mixed malformed and valid surviving carriers, including a valid -> invalid -> valid
|
||||
// chain. After one pass, only the genuinely surviving records remain and pass 2 is a no-op.
|
||||
let mut mixed_doc = Document::from_text("");
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "BuriedInOuter", "2026-11-20T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "KeptOuter", "2026-11-21T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "BuriedInMid", "2026-11-22T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "KeptOther", "2026-11-23T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Insert, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Delete, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
|
||||
let mut hdr_mixed = Paragraph::new();
|
||||
// Ruby 0: invalid outer (99) burying valid rev 0.
|
||||
let outer_invalid = CharProps {
|
||||
fmt_change: PropChange::boxed(99, CharProps { ins: Some(0), fmt_change: PropChange::boxed(0, CharProps::default()), ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
// Ruby 1: valid outer (1) containing invalid middle (88) burying valid rev 2.
|
||||
let nested_invalid = CharProps {
|
||||
fmt_change: PropChange::boxed(
|
||||
1,
|
||||
CharProps {
|
||||
fmt_change: PropChange::boxed(88, CharProps { fmt_change: PropChange::boxed(2, CharProps::default()), ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
..Default::default()
|
||||
};
|
||||
hdr_mixed.insert_object(0, make_ruby(outer_invalid), &CharProps::default()).unwrap();
|
||||
hdr_mixed.insert_object(hdr_mixed.len(), make_ruby(nested_invalid), &CharProps::default()).unwrap();
|
||||
let hdr_mixed_id = mixed_doc.add_part(PartKind::Header, vec![para_block(hdr_mixed)]);
|
||||
mixed_doc.last_section.headers.default = Some(hdr_mixed_id);
|
||||
|
||||
let mut ftr_mixed = Paragraph::new();
|
||||
let valid_other = CharProps { fmt_change: PropChange::boxed(3, CharProps::default()), ..Default::default() };
|
||||
ftr_mixed.insert_object(0, make_ruby(valid_other), &CharProps::default()).unwrap();
|
||||
let ftr_mixed_id = mixed_doc.add_part(PartKind::Footer, vec![para_block(ftr_mixed)]);
|
||||
mixed_doc.last_section.footers.default = Some(ftr_mixed_id);
|
||||
|
||||
let body_m = mixed_doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
|
||||
body_m.insert_text(body_m.len(), "New", &CharProps { ins: Some(4), ..Default::default() }).unwrap();
|
||||
body_m.insert_text(body_m.len(), "Old", &CharProps { del: Some(5), ..Default::default() }).unwrap();
|
||||
|
||||
for (cmd, want_body) in [("review.acceptAll", "New"), ("review.rejectAll", "Old")] {
|
||||
let mut s = Session::new(mixed_doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd} mixed: body endpoint");
|
||||
assert_eq!(assert_all_revision_refs_valid(&s.doc, &format!("{cmd} mixed")), 2);
|
||||
let authors: Vec<&str> = s.doc.revisions.iter().map(|r| r.author.as_str()).collect();
|
||||
assert_eq!(authors, vec!["KeptOuter", "KeptOther"], "{cmd} mixed: only genuinely referenced records retained");
|
||||
|
||||
let hdr_objs = &s.doc.parts[&hdr_mixed_id].blocks[0].as_para().unwrap().objects;
|
||||
let InlineObject::Ruby { props: p0, .. } = &hdr_objs[0] else { panic!("expected Ruby 0") };
|
||||
let InlineObject::Ruby { props: p1, .. } = &hdr_objs[1] else { panic!("expected Ruby 1") };
|
||||
let InlineObject::Ruby { props: pf, .. } = &s.doc.parts[&ftr_mixed_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected footer Ruby");
|
||||
};
|
||||
assert!(p0.fmt_change.is_none(), "{cmd} mixed: invalid outer discarded");
|
||||
let p1_outer = p1.fmt_change.as_ref().expect("valid outer retained");
|
||||
assert_eq!(s.doc.revisions[p1_outer.rev as usize].author, "KeptOuter");
|
||||
assert!(p1_outer.old.fmt_change.is_none(), "{cmd} mixed: invalid middle and buried inner discarded");
|
||||
let pf_outer = pf.fmt_change.as_ref().expect("valid footer ref retained");
|
||||
assert_eq!(s.doc.revisions[pf_outer.rev as usize].author, "KeptOther");
|
||||
|
||||
let after_first = s.doc.clone();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc, after_first, "{cmd} mixed: second pass must be a no-op");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(crate) use autoformat::smart_quote;
|
||||
use delete::{backspace, delete, delete_sentence_back, delete_word_back, delete_word_fwd};
|
||||
pub use enter_tab::MAX_TYPED_PARAGRAPHS;
|
||||
use enter_tab::{back_tab, new_paragraph, tab};
|
||||
use unicode::{ins_char, insert_break, insert_code, toggle_unicode};
|
||||
use unicode::{ins_char, insert_code, toggle_unicode};
|
||||
pub use unicode::{oem_code_page, system_code_pages, system_oem_code_page};
|
||||
|
||||
/// The text-entry commands: typing, Enter, breaks, Tab, deleting and typed symbols.
|
||||
@@ -26,9 +26,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("text.insert", "Type Text", "Editing", insert).params(r#"{"text": string, "raw"?: bool, "paragraphs"?: bool} (paragraphs: each line a paragraph, one undo step, at most 10000 lines)"#),
|
||||
CommandSpec::new("text.newParagraph", "New Paragraph", "Editing", new_paragraph).key("Enter"),
|
||||
CommandSpec::new("text.lineBreak", "Line Break", "Editing", |s, _| insert_break(s, '\n')).key("Shift+Enter"),
|
||||
CommandSpec::new("text.pageBreak", "Page Break", "Insert › Pages", |s, _| insert_break(s, PAGE_BREAK)).key("Mod+Enter"),
|
||||
CommandSpec::new("text.columnBreak", "Column Break", "Layout › Breaks", |s, _| insert_break(s, COLUMN_BREAK)).key("Mod+Shift+Enter"),
|
||||
CommandSpec::new("text.lineBreak", "Line Break", "Editing", |s, _| ins_char(s, '\n')).key("Shift+Enter"),
|
||||
CommandSpec::new("text.pageBreak", "Page Break", "Insert › Pages", |s, _| ins_char(s, PAGE_BREAK)).key("Mod+Enter"),
|
||||
CommandSpec::new("text.columnBreak", "Column Break", "Layout › Breaks", |s, _| ins_char(s, COLUMN_BREAK)).key("Mod+Shift+Enter"),
|
||||
CommandSpec::new("text.tab", "Tab", "Editing", tab).key("Tab"),
|
||||
CommandSpec::new("text.backTab", "Shift+Tab", "Editing", back_tab).key("Shift+Tab"),
|
||||
// A tab character even in a table cell, where Tab moves to the next cell (#3137); ⌥Tab on macOS.
|
||||
|
||||
@@ -58,9 +58,8 @@ fn sample_text(s: &Session) -> Option<String> {
|
||||
|
||||
/// `text.newParagraph`: Enter, unless the selection is in a control that takes no paragraph break.
|
||||
pub(super) fn new_paragraph(s: &mut Session, _: &Value) -> CmdResult {
|
||||
// Enter in a one-line plain text control (or a check box or list), or on a selected picture or
|
||||
// shape, does nothing, as in Word (#4126).
|
||||
if crate::cmd::controls::refuses_paragraph(s) || crate::cmd::objects::object_selection(s).is_some() {
|
||||
// Enter in a one-line plain text control (or a check box or list) does nothing, as in Word.
|
||||
if crate::cmd::controls::refuses_paragraph(s) {
|
||||
return sel_result(s);
|
||||
}
|
||||
enter(s, true)?;
|
||||
|
||||
@@ -110,17 +110,3 @@ pub(super) fn ins_char(s: &mut Session, c: char) -> CmdResult {
|
||||
type_text(s, c.encode_utf8(&mut b))?;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// A line, page or column break. On a selected picture or shape, Word puts the break in front of
|
||||
/// it and keeps it selected, rather than replacing it (#4126).
|
||||
pub(super) fn insert_break(s: &mut Session, c: char) -> CmdResult {
|
||||
let Some(at) = crate::cmd::objects::object_selection(s).map(|(p, _)| p) else { return ins_char(s, c) };
|
||||
s.sel = Selection::caret(at.clone());
|
||||
ins_char(s, c)?;
|
||||
// The break goes in front of the object, or of the content control around it.
|
||||
let at = Pos { off: at.off + c.len_utf8(), ..at };
|
||||
if s.doc.para_at(&at).and_then(|p| p.object_at(at.off)).is_some_and(|o| o.is_drawing()) {
|
||||
crate::cmd::objects::select_object(s, &at);
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
use super::{Arc, CmdError, CmdResult, Document, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p, sel_result};
|
||||
use crate::cmd::insert::MAX_TABLE_ROWS;
|
||||
use crate::cmd::mailings::{CsvLimits, MAX_TEXT_BYTES};
|
||||
use wordcraft_doc::CharProps;
|
||||
use wordcraft_doc::table::MAX_COLS;
|
||||
|
||||
const TABLE_LIMITS: CsvLimits = CsvLimits { fields: MAX_COLS, cells: MAX_TABLE_ROWS * MAX_COLS, text: MAX_TEXT_BYTES };
|
||||
|
||||
/// Options › Language › Set as default: only the saved default proofing language (what future
|
||||
/// blank documents are written in), as Word's Set as Preferred. A setting, like `file.options`: the
|
||||
@@ -463,14 +458,7 @@ pub(super) fn customize_ribbon(s: &mut Session, v: &Value) -> CmdResult {
|
||||
pub(super) fn spreadsheet_rows(v: &Value) -> Result<Vec<Vec<String>>, CmdError> {
|
||||
// The CSV fallback is for an absent `values`; an explicit null is a malformed argument.
|
||||
let Some(values) = v.get("values") else {
|
||||
let rows = crate::cmd::mailings::parse_csv(p::str(v, "csv").unwrap_or("A,B,C\n1,2,3\n4,5,6"), &TABLE_LIMITS)
|
||||
.map_err(|e| CmdError::Failed(format!("{e}; a table holds at most {MAX_TABLE_ROWS} rows of {MAX_COLS} columns")))?;
|
||||
// A table holds so many rows: a longer list would lose its records quietly, because
|
||||
// the table the command inserts is shorter than the list.
|
||||
if rows.len() > MAX_TABLE_ROWS {
|
||||
return Err(CmdError::Failed(format!("a table holds at most {MAX_TABLE_ROWS} rows")));
|
||||
}
|
||||
return Ok(rows);
|
||||
return Ok(crate::cmd::mailings::parse_csv(p::str(v, "csv").unwrap_or("A,B,C\n1,2,3\n4,5,6")));
|
||||
};
|
||||
let list = values.as_array().ok_or_else(|| CmdError::Params("`values` must be an array of rows".into()))?;
|
||||
if list.is_empty() || list.len() > 1000 {
|
||||
|
||||
@@ -443,11 +443,7 @@ fn diff_blocks(doc: &mut Document, old: &[Arc<Block>], new: &[Arc<Block>], ctx:
|
||||
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(doc, pa, pb, ctx))),
|
||||
_ => {
|
||||
if let Some(x) = a {
|
||||
out.push(Arc::new(mark_block(x, &|c| {
|
||||
// An existing deletion is another author's: keep their revision
|
||||
// stamp instead of re-attributing the paragraph to this compare.
|
||||
c.del.get_or_insert(ctx.del);
|
||||
})));
|
||||
out.push(Arc::new(mark_block(x, &|c| c.del = Some(ctx.del))));
|
||||
}
|
||||
if let Some(x) = b {
|
||||
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins))));
|
||||
@@ -1617,16 +1613,8 @@ fn block_text(b: &Block, depth: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy of the block with every run (in tables, every cell's) changed by `f`, and a paragraph's
|
||||
/// mark along with them, so a whole inserted or deleted paragraph carries the revision even when
|
||||
/// the paragraph is empty (`format` returns early for a length-0 range). Walks nested tables
|
||||
/// iteratively, without recursion or depth truncation.
|
||||
///
|
||||
/// A whole-paragraph revision on the last paragraph of a story or cell is removed together with
|
||||
/// the paragraph on Accept/Reject All (see `remove_trailing_para` in `review::changes`), except
|
||||
/// where the paragraph carries a section break or is the container's only paragraph. A
|
||||
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
|
||||
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
|
||||
/// Returns a copy of `b` with all text runs and paragraph marks across all nested table cells
|
||||
/// updated by `f` iteratively, without recursion or depth truncation.
|
||||
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
|
||||
let mut out = b.clone();
|
||||
let mut todo = vec![&mut out];
|
||||
|
||||
@@ -237,7 +237,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"csv"?: string, "values"?: [[cell, …], …] (rows of equal length, at most 1000 rows × 63 columns; wins over csv), "header"?: bool (first row repeats on each page), "style"?: table style name (default GridTable1Light)}"#),
|
||||
CommandSpec::new("layout.linkToPrevious", "Link to Previous", "Header & Footer › Navigation", |s, v| {
|
||||
let header = p::bool(v, "footer").map(|f| !f).unwrap_or(true);
|
||||
let block = crate::cmd::page::section_end_of_focus(s);
|
||||
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let sect = s.doc.section_mut(block);
|
||||
if header {
|
||||
sect.headers = Default::default();
|
||||
@@ -252,7 +252,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("hf.previous", "Previous Section", "Header & Footer › Navigation", |s, _| hf_nav(s, -1)).pure(),
|
||||
CommandSpec::new("hf.position", "Header/Footer Position", "Header & Footer › Position", |s, v| {
|
||||
let (h, f) = (p::f32(v, "header"), p::f32(v, "footer"));
|
||||
let block = crate::cmd::page::section_end_of_focus(s);
|
||||
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let sect = s.doc.section_mut(block);
|
||||
if let Some(h) = h {
|
||||
sect.header = h.clamp(0.0, 300.0);
|
||||
|
||||
@@ -11,259 +11,6 @@ fn compare_marks_changes() {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "The dog sat.\nKeep this.\nNew line here.");
|
||||
}
|
||||
|
||||
/// Top-level body blocks that are empty paragraphs.
|
||||
fn empty_paras(s: &Session) -> usize {
|
||||
s.doc.body.iter().filter(|b| matches!(b.as_para(), Some(p) if p.is_empty())).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_a_whole_paragraph_and_its_mark() {
|
||||
// A whole inserted paragraph carries the insertion on its mark, not just on its runs.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "NEW");
|
||||
assert!(mid.mark.ins.is_some(), "the inserted paragraph's mark is not marked inserted");
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting an inserted paragraph left an empty paragraph behind");
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nNEW\nB");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting an inserted paragraph left an empty paragraph behind");
|
||||
|
||||
// A whole deleted paragraph carries the deletion on its mark.
|
||||
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.mark.del.is_some(), "the deleted paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting a deleted paragraph left an empty paragraph behind");
|
||||
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nOLD\nB");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_an_empty_paragraphs_mark() {
|
||||
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\n\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let empty = s.doc.body[1].as_para().unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert!(empty.mark.ins.is_some(), "the empty inserted paragraph's mark is not marked inserted");
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting an empty inserted paragraph left it behind");
|
||||
|
||||
// An empty deleted paragraph is stamped on its mark too.
|
||||
let mut s = Session::new(Document::from_text("A\n\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let empty = s.doc.body[1].as_para().unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert!(empty.mark.del.is_some(), "the empty deleted paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_keeps_another_authors_deletion_stamp() {
|
||||
// A paragraph the original already carries as a tracked deletion by another author: Compare
|
||||
// must keep that author's revision on its runs and on its paragraph mark, not re-attribute
|
||||
// the block to its own deletion revision.
|
||||
let mut doc = Document::from_text("A\nOLD\nB");
|
||||
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Delete, "Alice", ""));
|
||||
let p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
for r in &mut p.runs {
|
||||
r.props.del = Some(0);
|
||||
}
|
||||
p.mark.del = Some(0);
|
||||
let mut s = Session::new(doc);
|
||||
s.run("review.compare", &json!({"text": "A\nB", "author": "Bob"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.runs.iter().all(|r| r.props.del == Some(0)), "the runs' deletion was re-stamped: {:?}", mid.runs);
|
||||
assert_eq!(mid.mark.del, Some(0), "the paragraph mark's deletion was re-stamped");
|
||||
assert_eq!(s.doc.revisions.first().map(|r| (r.kind, r.author.as_str())), Some((RevisionKind::Delete, "Alice")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_terminal_inserted_paragraph_resolves_fully() {
|
||||
// A paragraph inserted at the very end is removed whole when rejected, leaving no empty
|
||||
// paragraph behind.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nC"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting a terminal inserted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_terminal_deleted_paragraph_resolves_fully() {
|
||||
// The mirror of `compare_terminal_inserted_paragraph_resolves_fully`: a paragraph deleted
|
||||
// from the very end is removed whole when accepted, leaving no empty paragraph behind.
|
||||
let mut s = Session::new(Document::from_text("A\nB\nC"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reject_all_keeps_an_empty_inserted_paragraph_between_tables() {
|
||||
// An empty paragraph between two tables is not the container's last block: removing it
|
||||
// would make the tables adjacent, and they would join into one on reopen. Reject All only
|
||||
// clears its mark.
|
||||
use wordcraft_doc::{Block, Paragraph, para_block};
|
||||
let mut doc = Document::from_text("");
|
||||
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, "Alice", ""));
|
||||
let table = || std::sync::Arc::new(Block::Table(wordcraft_doc::table::Table::new(1, 1, 100.0)));
|
||||
let mut between = Paragraph::default();
|
||||
between.mark.ins = Some(0);
|
||||
doc.body = vec![table(), para_block(between), table(), para_block(Paragraph::with_text("end", Default::default()))];
|
||||
let mut s = Session::new(doc);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
let kinds: Vec<bool> = s.doc.body.iter().map(|b| matches!(**b, Block::Table(_))).collect();
|
||||
assert_eq!(kinds, [true, false, true, false]);
|
||||
let kept = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
assert!(kept.is_empty() && kept.mark.ins.is_none(), "{kept:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_pins_rejecting_an_inserted_section_keeps_the_next_paragraphs_style() {
|
||||
// Pins the fixed behaviour for rejecting an inserted paragraph that carries a section
|
||||
// break. This was a known limitation recorded on `mark_block` (compare.rs): `resolve`'s
|
||||
// `remove_empty_para` refused paragraphs carrying a section, so once the inserted
|
||||
// paragraph's text was rejected the empty paragraph was joined into the next one, which
|
||||
// took its properties ("Body" came back Normal instead of its original Heading 1). Fixed
|
||||
// on main by #5734 (issue #5667): `resolve_para` now removes the section break first, so
|
||||
// the empty paragraph goes whole and the following paragraph keeps its own properties.
|
||||
// After Reject All the original is restored exactly.
|
||||
let mut original = Document::from_text("Intro\nBody");
|
||||
original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into());
|
||||
let mut s = Session::new(original);
|
||||
|
||||
let mut rev = Document::from_text("Intro\nAppendix\nBody");
|
||||
{
|
||||
let p = rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
p.props.style = Some("Normal".into());
|
||||
p.section = Some(Box::new(wordcraft_doc::section::SectionProps::default()));
|
||||
}
|
||||
rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap().props.style = Some("Heading1".into());
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-section-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev).unwrap();
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Intro\nBody");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
let body = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(body.plain_text(), "Body");
|
||||
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
|
||||
// The Accept-side mirror of `compare_pins_rejecting_an_inserted_section_keeps_the_next_paragraphs_style`:
|
||||
// compare deletes a paragraph that carries a section break whole (original `A`, `OLD`
|
||||
// with a section break, `B`; revised `A`, `B`). Accept All goes through the same #5734
|
||||
// branch in `resolve_para` as the reject case: the section break is removed first, so
|
||||
// the emptied paragraph goes whole instead of being joined into the next one. After
|
||||
// Accept All the revised text stands exactly and `B` keeps its own properties.
|
||||
let mut original = Document::from_text("A\nOLD\nB");
|
||||
{
|
||||
let p = original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
p.props.style = Some("Normal".into());
|
||||
p.section = Some(Box::new(wordcraft_doc::section::SectionProps::default()));
|
||||
}
|
||||
original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap().props.style = Some("Heading1".into());
|
||||
let mut s = Session::new(original);
|
||||
|
||||
let mut rev = Document::from_text("A\nB");
|
||||
rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into());
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-section-accept-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev).unwrap();
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.mark.del.is_some(), "the deleted sectioned paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting the deleted sectioned paragraph left it behind");
|
||||
let body = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(body.plain_text(), "B");
|
||||
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_the_last_paragraphs_mark() {
|
||||
// Inserted last paragraph: rejecting removes it whole.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert!(s.doc.body[2].as_para().unwrap().mark.ins.is_some());
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nNEW");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
|
||||
// Deleted last paragraph: accepting removes it whole.
|
||||
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert!(s.doc.body[2].as_para().unwrap().mark.del.is_some());
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nOLD");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_keeps_the_only_paragraphs_mark() {
|
||||
let mut s = Session::new(Document::from_text(""));
|
||||
s.doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, s.author.clone(), ""));
|
||||
s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 1);
|
||||
assert!(s.doc.body[0].as_para().unwrap().mark.ins.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_options_ignore_case_and_white_space() {
|
||||
let original = "The Cat sat.\nTwo spaces here.";
|
||||
@@ -1914,32 +1661,10 @@ fn spreadsheet_rejects_hostile_values() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A CSV too wide or too long for a table is refused, not cut.
|
||||
#[test]
|
||||
fn insert_spreadsheet_refuses_a_csv_a_table_cannot_hold() {
|
||||
use crate::cmd::insert::MAX_TABLE_ROWS;
|
||||
use wordcraft_doc::table::MAX_COLS;
|
||||
let mut s = Session::new(Document::new());
|
||||
// Wider than a table's columns.
|
||||
let wide = format!("{}\nvalue", "c,".repeat(MAX_COLS));
|
||||
let e = s.run("insert.spreadsheet", &json!({"csv": wide})).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_COLS} columns")), "{e}");
|
||||
// Longer than a table's rows: the records above the limit would be lost quietly.
|
||||
let long = format!("value\n{}", "value\n".repeat(MAX_TABLE_ROWS));
|
||||
let e = s.run("insert.spreadsheet", &json!({"csv": long})).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_TABLE_ROWS} rows")), "{e}");
|
||||
// A table's own width and length are fine.
|
||||
let ok = format!("{}\nvalue", "c,".repeat(MAX_COLS - 1));
|
||||
s.run("insert.spreadsheet", &json!({"csv": ok})).unwrap();
|
||||
let ok = "value\n".repeat(MAX_TABLE_ROWS);
|
||||
s.run("insert.spreadsheet", &json!({"csv": ok})).unwrap();
|
||||
}
|
||||
|
||||
/// The inspector's removals delete straight from the document, so they aren't tracked: on a
|
||||
/// document that tracks changes the text would go with no revision to show for it, and the
|
||||
/// revision trail would be broken behind the user's back. The removal is refused instead,
|
||||
/// and the document is left as it was.
|
||||
|
||||
#[test]
|
||||
fn inspect_removals_are_refused_while_the_document_tracks_changes() {
|
||||
let mut s = Session::new(Document::from_text("Visible text.\nHidden text."));
|
||||
|
||||
@@ -337,29 +337,6 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A document made from a template is created now, not when the template was: it has no
|
||||
/// creation date until it is saved, so CREATEDATE in it shows today.
|
||||
#[test]
|
||||
fn new_from_template_has_no_creation_date_of_its_own_yet() {
|
||||
let d = scratch("created");
|
||||
let path = d.join("Dated.dotx");
|
||||
let mut t = Session::new(wordcraft_doc::Document::new());
|
||||
t.run("document.setText", &json!({"text": "Dated"})).unwrap();
|
||||
t.doc.core.created = "2019-05-05T12:00:00Z".into();
|
||||
crate::io::save_path(&path, &t.doc).unwrap();
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.doc.core.created, "");
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy")));
|
||||
// The template itself keeps its date.
|
||||
let mut again = Session::new(wordcraft_doc::Document::new());
|
||||
again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// #3433: a template the platform hands the app takes an untouched blank document's place
|
||||
/// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the
|
||||
/// new document opens beside the others, as File › New's does. Either way the template on
|
||||
|
||||
@@ -284,17 +284,14 @@ fn import_chunk(c: &wordcraft_docx::AltChunk) -> Option<Document> {
|
||||
|| matches!(ext.as_str(), "mht" | "mhtml")
|
||||
|| mht::is_mht(b)
|
||||
{
|
||||
mht::import(b).map_err(|e| log::warn!("altChunk {}: the MHT cannot be read: {e}", c.part)).ok()?
|
||||
mht::import(b)
|
||||
} else if ct.contains("rtf") || ext == "rtf" || b.starts_with(b"{\\rtf") {
|
||||
rtf::import(b).map_err(|e| log::warn!("altChunk {}: the RTF cannot be read: {e}", c.part)).ok()?
|
||||
rtf::import(b).ok()?
|
||||
} else if ct.contains("html") || matches!(ext.as_str(), "html" | "htm" | "xhtml") {
|
||||
html::import_page(&html::decode_as(b, charset), &|_| None)
|
||||
.map_err(|e| log::warn!("altChunk {}: the HTML cannot be read: {e}", c.part))
|
||||
.ok()?
|
||||
} else if ct == "text/plain" || ext == "txt" {
|
||||
txt::import(b)
|
||||
} else {
|
||||
log::warn!("altChunk {}: its type ({ct}) is not one WordCraft reads", c.part);
|
||||
return None;
|
||||
};
|
||||
// shortcut: pictures fit the chunk's default page, not the section it lands in; fit them there if wide pictures in chunks overflow narrow sections.
|
||||
@@ -499,7 +496,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
|
||||
// Pictures referenced by a relative path load from beside the HTML file.
|
||||
let images = LocalImages::new(path.parent().unwrap_or(std::path::Path::new("")));
|
||||
let html = wordcraft_formats::html::decode(&bytes);
|
||||
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), ®ion_page(region))?;
|
||||
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), ®ion_page(region));
|
||||
fit_pictures(&mut doc);
|
||||
opened(&mut doc);
|
||||
return Ok((doc, false));
|
||||
|
||||
@@ -16,7 +16,6 @@ pub mod io;
|
||||
mod io_ext;
|
||||
pub mod keymap;
|
||||
pub(crate) mod locale;
|
||||
pub mod malloc_tuning;
|
||||
pub mod math_gallery;
|
||||
pub mod packs;
|
||||
pub(crate) mod prefs;
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
//! glibc malloc tuning for native binaries (adapted from Storytold's `photocraft` #8743).
|
||||
//!
|
||||
//! With glibc's defaults, transient large buffers (page render targets, autofit tables, decoded
|
||||
//! images) raise glibc's dynamic `mmap` and `trim` thresholds (up to 32 MiB on 64-bit), so later
|
||||
//! heap allocations stay in glibc arenas instead of returning freed pages to the OS. Fixing
|
||||
//! `MALLOC_TRIM_THRESHOLD_` at 128 KiB (`131072`) disables dynamic threshold growth so freed
|
||||
//! pages above 128 KiB are returned cleanly while preserving multi-arena allocation throughput.
|
||||
//!
|
||||
//! Because glibc reads its malloc environment variables once at process start and mutating the
|
||||
//! process environment in Rust requires `unsafe` (forbidden workspace-wide) and happens after glibc
|
||||
//! initialization, [`apply`] re-executes the current executable via `exec` when no malloc tuning
|
||||
//! variable is already set (keeping PID, argv, `argv[0]`, and environment). Setting any `MALLOC_*`
|
||||
//! variable or `glibc.malloc.*` tunable opts out.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// The glibc environment variable [`apply`] sets.
|
||||
pub const TRIM_THRESHOLD_VAR: &str = "MALLOC_TRIM_THRESHOLD_";
|
||||
|
||||
/// Fixed trim threshold (128 KiB, glibc's initial default) to disable dynamic threshold escalation.
|
||||
pub const TRIM_THRESHOLD: &str = "131072";
|
||||
|
||||
/// glibc malloc variables that indicate callers or wrappers already configured malloc tuning.
|
||||
const MALLOC_VARS: [&str; 5] = [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX"];
|
||||
|
||||
/// Whether startup should re-execute with [`TRIM_THRESHOLD_VAR`] set, given an environment reader:
|
||||
/// true only when no malloc variable or `glibc.malloc.*` tunable is present.
|
||||
pub fn needs_restart(var: impl Fn(&str) -> Option<OsString>) -> bool {
|
||||
if MALLOC_VARS.iter().any(|v| var(v).is_some()) {
|
||||
return false;
|
||||
}
|
||||
!var("GLIBC_TUNABLES").is_some_and(|t| t.to_string_lossy().contains("glibc.malloc."))
|
||||
}
|
||||
|
||||
/// Re-execute this binary with [`TRIM_THRESHOLD_VAR`] set when [`needs_restart`] is true.
|
||||
///
|
||||
/// Must be called early in `main()` before worker threads start or logs/crash hooks initialize.
|
||||
/// Returns immediately if tuning variables are already present or if `exec` fails.
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
pub fn apply() {
|
||||
use std::io::Write;
|
||||
use std::os::unix::process::CommandExt;
|
||||
|
||||
if !needs_restart(|k| std::env::var_os(k)) {
|
||||
return;
|
||||
}
|
||||
let Ok(exe) = std::env::current_exe() else { return };
|
||||
let mut args = std::env::args_os();
|
||||
let mut cmd = std::process::Command::new(exe);
|
||||
if let Some(argv0) = args.next() {
|
||||
cmd.arg0(argv0);
|
||||
}
|
||||
// `exec` replaces the current process in place and only returns on error.
|
||||
let err = cmd.args(args).env(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD).exec();
|
||||
let _ = writeln!(std::io::stderr(), "wordcraft: could not restart with {TRIM_THRESHOLD_VAR} set ({err})");
|
||||
}
|
||||
|
||||
/// No-op on platforms without Linux glibc.
|
||||
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
|
||||
pub fn apply() {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
|
||||
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restarts_only_without_malloc_tuning() {
|
||||
assert!(needs_restart(env(&[])));
|
||||
assert!(needs_restart(env(&[("HOME", "/home/a"), ("GLIBC_TUNABLES", "glibc.cpu.hwcaps=-AVX2")])));
|
||||
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD)])), "re-executed process stops");
|
||||
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, "")])), "any explicit value opts out");
|
||||
assert!(!needs_restart(env(&[("MALLOC_MMAP_THRESHOLD_", "1048576")])));
|
||||
assert!(!needs_restart(env(&[("MALLOC_ARENA_MAX", "2")])));
|
||||
assert!(!needs_restart(env(&[("GLIBC_TUNABLES", "glibc.malloc.trim_threshold=0")])));
|
||||
}
|
||||
}
|
||||
@@ -230,9 +230,6 @@ pub struct Session {
|
||||
pub editing_lang: Option<String>,
|
||||
/// Editing inside an equation: which one and the caret in it.
|
||||
pub math: Option<MathEdit>,
|
||||
/// The running command left the equation being edited before it ran (see [`Session::run`]),
|
||||
/// so Left/Right don't open the equation the caret now sits next to (#4138).
|
||||
pub(crate) math_left: bool,
|
||||
/// Equations are typed in LaTeX rather than the linear format.
|
||||
pub math_latex: bool,
|
||||
/// Text typed into equations is normal (non-math) text.
|
||||
|
||||
@@ -280,7 +280,6 @@ impl Session {
|
||||
findings: _,
|
||||
ribbon: _,
|
||||
editing_lang: _,
|
||||
math_left: _,
|
||||
math_latex: _,
|
||||
math_normal_text: _,
|
||||
last_highlight: _,
|
||||
|
||||
@@ -80,12 +80,8 @@ impl Session {
|
||||
};
|
||||
let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts));
|
||||
let [newest, _] = std::mem::take(&mut self.layout);
|
||||
// Only preserve the alternate layout slot for the current document revision (e.g. Print vs
|
||||
// Web/Draft toggling); a superseded revision can never hit `fits()` again and would keep an
|
||||
// obsolete DocLayout live in memory.
|
||||
let prev = newest.filter(|e| e.0 == rev);
|
||||
self.layout =
|
||||
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), prev];
|
||||
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), newest];
|
||||
l
|
||||
}
|
||||
|
||||
@@ -279,31 +275,3 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
|
||||
let mut session = Session::new(Document::new());
|
||||
let first = session.layout();
|
||||
let first_weak = Arc::downgrade(&first);
|
||||
drop(first);
|
||||
|
||||
// Switching view mode at the same revision keeps the prior layout in `layout[1]`.
|
||||
session.view.mode = ViewMode::Draft;
|
||||
let same_rev_other_mode = session.layout();
|
||||
assert!(first_weak.upgrade().is_some(), "same-revision alternate view mode stays cached");
|
||||
|
||||
let draft_weak = Arc::downgrade(&same_rev_other_mode);
|
||||
drop(same_rev_other_mode);
|
||||
|
||||
// Advancing `rev` makes earlier layouts unreachable: building the new layout must drop them.
|
||||
session.run("text.insert", &serde_json::json!({"text": "hello"})).expect("insert");
|
||||
let after_edit = session.layout();
|
||||
assert!(draft_weak.upgrade().is_none(), "superseded revision layout must be dropped");
|
||||
assert!(first_weak.upgrade().is_none(), "older revision layout must not remain live");
|
||||
drop(after_edit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +157,6 @@ impl Session {
|
||||
merge,
|
||||
ui_requests: Vec::new(),
|
||||
math,
|
||||
math_left: false,
|
||||
math_latex: false,
|
||||
math_normal_text: false,
|
||||
also_selected,
|
||||
|
||||
@@ -27,23 +27,16 @@ struct ElsewhereContext {
|
||||
blocks_before: Option<std::collections::BTreeMap<String, Fragment>>,
|
||||
default_language_before: Option<String>,
|
||||
pending_application_change_before: bool,
|
||||
/// The tracked move the command would have dropped, put back when it fails.
|
||||
move_before: Option<crate::cmd::moves::PendingMove>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn leave_math_for_command(&mut self, id: &str) {
|
||||
self.math_left = false;
|
||||
if self.math.is_some()
|
||||
&& (id.starts_with("text.")
|
||||
|| id.starts_with("caret.")
|
||||
|| id.starts_with("select.")
|
||||
|| (id.starts_with("edit.paste") && id != "edit.pasteFormat"))
|
||||
&& (id.starts_with("text.") || id.starts_with("caret.") || id.starts_with("select.") || id.starts_with("edit.paste"))
|
||||
&& let Some(m) = self.math.take()
|
||||
{
|
||||
let off = m.at.off + wordcraft_doc::para::OBJ.len_utf8();
|
||||
self.sel = Selection::caret(Pos { off, ..m.at });
|
||||
self.math_left = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,9 +211,7 @@ impl Session {
|
||||
} else if spec.id.starts_with("caret.") {
|
||||
self.typing_open = false;
|
||||
}
|
||||
// Only the paste right after a tracked cut makes it a move. A command that fails
|
||||
// changed nothing, so the move it would have dropped is put back (below).
|
||||
let move_before = self.pending_move.clone();
|
||||
// Only the paste right after a tracked cut makes it a move.
|
||||
if (spec.mutates || matches!(id, "edit.undo" | "edit.undoTo" | "edit.redo")) && !matches!(id, "edit.cut" | "edit.paste" | "edit.pasteSpecial")
|
||||
{
|
||||
self.pending_move = None;
|
||||
@@ -246,7 +237,7 @@ impl Session {
|
||||
};
|
||||
if self.document_id != home || (result.is_err() && self.order.iter().any(|d| *d >= mark)) {
|
||||
return self.finish_elsewhere(
|
||||
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before },
|
||||
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before },
|
||||
result,
|
||||
);
|
||||
}
|
||||
@@ -311,9 +302,6 @@ impl Session {
|
||||
self.join_anchor = false;
|
||||
}
|
||||
}
|
||||
// The command failed, so the tracked move it would have dropped is still there:
|
||||
// the paste after it is a move, as it was before the command.
|
||||
self.pending_move = move_before;
|
||||
if let Some(dirty) = dirty_before {
|
||||
self.dirty = dirty;
|
||||
}
|
||||
@@ -492,8 +480,7 @@ impl Session {
|
||||
/// as it was (opening a document is no edit to undo there). Failed: the documents the command opened close again and the first document is
|
||||
/// active and as it was.
|
||||
fn finish_elsewhere(&mut self, context: ElsewhereContext, result: Result<Value, CmdError>) -> Result<Value, CmdError> {
|
||||
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before } =
|
||||
context;
|
||||
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before } = context;
|
||||
// Another document is a state change the input method has to see, never an IME edit.
|
||||
self.ime_edit_outcome = ImeEditOutcome::default();
|
||||
match &result {
|
||||
@@ -525,9 +512,6 @@ impl Session {
|
||||
self.undo_evicted = ev;
|
||||
self.column = c;
|
||||
}
|
||||
// The command failed, so the tracked move it would have dropped is still
|
||||
// there: the paste after it is a move, as it was before the command.
|
||||
self.pending_move = move_before;
|
||||
}
|
||||
if let Some(b) = blocks_before {
|
||||
self.building_blocks = b;
|
||||
|
||||
@@ -162,7 +162,6 @@ impl Session {
|
||||
editing_lang: _,
|
||||
// Equation editing mode, like `view`: not part of the document or its history.
|
||||
math: _,
|
||||
math_left: _,
|
||||
math_latex: _,
|
||||
math_normal_text: _,
|
||||
// The save password, like the file path: not an edit to the document.
|
||||
|
||||
+2
-456
@@ -293,15 +293,6 @@ fn custom_dictionary_words_persist_through_their_file() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confined_sessions_test_is_native_only() {
|
||||
let source = include_str!("tests.rs");
|
||||
assert!(source.contains(
|
||||
"#[cfg(not(target_arch = \"wasm32\"))]\n#[test]\nfn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots()"
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
|
||||
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
@@ -1052,128 +1043,6 @@ fn bold_toggles_selection_and_caret_word() {
|
||||
assert_eq!(p.props_of_char(9).italic, None);
|
||||
}
|
||||
|
||||
/// A partly formatted selection toggles by its first character, as Word does (#6516).
|
||||
#[test]
|
||||
fn toggles_on_mixed_selection_follow_first_character() {
|
||||
// `Abc abc` with `fmt` set by `cmd`, then `cmd` with `v` on the selection `from` → `to`.
|
||||
let toggled = |cmd: &str, fmt: (usize, usize), from: usize, to: usize, v: serde_json::Value| -> String {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "Abc abc"}));
|
||||
let sel = |s: &mut Session, a: usize, b: usize| {
|
||||
run(s, "select.range", json!({"anchor": {"block": 0, "off": a}, "focus": {"block": 0, "off": b}}));
|
||||
};
|
||||
sel(&mut s, fmt.0, fmt.1);
|
||||
run(&mut s, cmd, json!({"value": true}));
|
||||
sel(&mut s, from, to);
|
||||
run(&mut s, cmd, v);
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
|
||||
(0..7)
|
||||
.map(|i| {
|
||||
let c = p.props_of_char(i);
|
||||
match cmd {
|
||||
"format.italic" => c.italic == Some(true),
|
||||
"format.underline" => c.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None),
|
||||
_ => c.bold == Some(true),
|
||||
}
|
||||
})
|
||||
.map(|on| if on { 'F' } else { '.' })
|
||||
.collect()
|
||||
};
|
||||
let t = || json!({});
|
||||
for cmd in ["format.bold", "format.italic", "format.underline"] {
|
||||
// `FFF....`: a selection starting on formatted text removes the format from all of it.
|
||||
assert_eq!(toggled(cmd, (0, 3), 2, 5, t()), "FF.....", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 0, 7, t()), ".......", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 1, 7, t()), "F......", "{cmd}");
|
||||
// Made right to left: still the first character in document order.
|
||||
assert_eq!(toggled(cmd, (0, 3), 5, 2, t()), "FF.....", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 7, 0, t()), ".......", "{cmd}");
|
||||
// `....FFF`: a selection starting on plain text applies it to all of it.
|
||||
assert_eq!(toggled(cmd, (4, 7), 0, 7, t()), "FFFFFFF", "{cmd}");
|
||||
// An explicit value still sets.
|
||||
assert_eq!(toggled(cmd, (0, 3), 0, 7, json!({"value": true})), "FFFFFFF", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (4, 7), 0, 7, json!({"value": false})), ".......", "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection that starts in an empty paragraph: Word decides from the first text character, not
|
||||
/// from the empty paragraph's mark (observed in Word for Windows, #6516 review).
|
||||
#[test]
|
||||
fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
|
||||
let toggled = |mark_bold: bool, text_bold: bool| -> Option<bool> {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "abc"}));
|
||||
let first = Pos::body(0, 0);
|
||||
s.doc.para_mut(first.story, &first.path).unwrap().mark.bold = Some(mark_bold);
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
|
||||
run(&mut s, "format.bold", json!({"value": text_bold}));
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 1, "off": 3}}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold
|
||||
};
|
||||
// A bold empty paragraph before plain text: Bold goes on.
|
||||
assert_eq!(toggled(true, false), Some(true));
|
||||
// A plain empty paragraph before bold text: Bold comes off.
|
||||
assert_eq!(toggled(false, true), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
|
||||
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
|
||||
let bold_word = |text: &str, caret: usize| {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": text}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap().clone();
|
||||
p.text.char_indices().filter(|&(i, _)| p.props_of_char(i).bold == Some(true)).map(|(_, c)| c).collect::<String>()
|
||||
};
|
||||
assert_eq!(bold_word("don’t stop", 1), "don’t");
|
||||
assert_eq!(bold_word("the dogs’ bone", 5), "dogs’");
|
||||
assert_eq!(bold_word("’tis here", 3), "’tis");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_word_takes_a_typographic_apostrophe() {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "don’t stop"}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 1}}));
|
||||
run(&mut s, "select.word", json!({}));
|
||||
let (a, b) = s.sel.ordered();
|
||||
assert_eq!((a.off, b.off), (0, 8), "`don’t ` with its trailing space, as Word selects it (#6517)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thesaurus_at_a_caret_looks_up_a_quoted_word_without_its_quotes() {
|
||||
// The word unit now takes `’`, so `‘good’` gives `good’`; the lookup drops enclosing quotes.
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "a ‘good’ day"}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}}));
|
||||
let r = run(&mut s, "review.thesaurus", json!({}));
|
||||
assert_eq!(r["word"], json!("good"));
|
||||
assert!(r["synonyms"].as_array().is_some_and(|a| !a.is_empty()), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_synonym_replaces_the_word_and_keeps_its_quotes() {
|
||||
// The range a chosen synonym replaces (the context menu's): the word without its quotes or the
|
||||
// space after it, while an apostrophe inside a word stays part of it (#6517).
|
||||
let word = |text: &str, caret: usize| {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": text, "raw": true}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
|
||||
let (a, b) = crate::cmd::review::thesaurus_word(&s).unwrap();
|
||||
s.set_selection(crate::Selection { anchor: a, focus: b });
|
||||
run(&mut s, "text.insert", json!({"text": "fine", "raw": true}));
|
||||
s.doc.plain_text(StoryRef::Body)
|
||||
};
|
||||
assert_eq!(word("a ‘good’ day", 6), "a ‘fine’ day");
|
||||
assert_eq!(word("a 'good' day", 4), "a 'fine' day");
|
||||
assert_eq!(word("a good day", 3), "a fine day");
|
||||
assert_eq!(word("don’t go", 1), "fine go");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn border_toggles_and_saves() {
|
||||
use wordcraft_doc::props::Border;
|
||||
@@ -2185,88 +2054,6 @@ fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
|
||||
assert!(r.bold_cs, "drawn bold as complex script");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_merge_formatting_leaves_plain_what_the_source_draws_plain() {
|
||||
// #4852 review: a run marked `w:cs` is bold and italic only by `w:bCs` and `w:iCs`, so one
|
||||
// with `w:b` and `w:i` alone is drawn plain and pastes plain; one with `w:bCs` pastes bold.
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "x"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
let pasted = |s: &Session, props: wordcraft_doc::CharProps| {
|
||||
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย");
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| p.runs.iter_mut().for_each(|r| r.props = props.clone()));
|
||||
}
|
||||
crate::cmd::paste::merge_formatting(s, &mut frag);
|
||||
let mut out = Vec::new();
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(None, &r.props))));
|
||||
}
|
||||
out
|
||||
};
|
||||
let cs = wordcraft_doc::CharProps { cs: Some(true), bold: Some(true), italic: Some(true), ..Default::default() };
|
||||
for r in pasted(&s, cs.clone()) {
|
||||
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs, "{r:?}");
|
||||
}
|
||||
for r in pasted(&s, wordcraft_doc::CharProps { bold_cs: Some(true), ..cs }) {
|
||||
assert!(r.bold && r.bold_cs && !r.italic_cs, "{r:?}");
|
||||
}
|
||||
// An unmarked run shows `w:b` in both scripts.
|
||||
for r in pasted(&s, wordcraft_doc::CharProps { bold: Some(true), ..Default::default() }) {
|
||||
assert!(r.bold && r.bold_cs, "{r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_merge_formatting_keeps_a_character_styles_emphasis_not_a_paragraph_styles() {
|
||||
// #7177 review, measured in Word for Windows: Merge Formatting keeps the bold, italic,
|
||||
// underline and strikethrough a character style gives the source, as direct formatting, but
|
||||
// drops a paragraph style's.
|
||||
use wordcraft_doc::props::Underline;
|
||||
use wordcraft_doc::styles::{Style, StyleKind};
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "x"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
let on = wordcraft_doc::CharProps {
|
||||
bold: Some(true),
|
||||
bold_cs: Some(true),
|
||||
italic: Some(true),
|
||||
italic_cs: Some(true),
|
||||
underline: Some(Underline::Single),
|
||||
strike: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
let sheet = Arc::make_mut(&mut s.doc.styles);
|
||||
sheet.upsert(Style { id: "ChEmph".into(), name: "ChEmph".into(), kind: StyleKind::Character, chr: on.clone(), ..Default::default() });
|
||||
sheet.upsert(Style { id: "PEmph".into(), name: "PEmph".into(), kind: StyleKind::Paragraph, chr: on, ..Default::default() });
|
||||
let pasted = |s: &Session, para_style: Option<&str>, props: wordcraft_doc::CharProps| {
|
||||
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย Thai");
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| {
|
||||
p.props.style = para_style.map(str::to_string);
|
||||
p.runs.iter_mut().for_each(|r| r.props = props.clone());
|
||||
});
|
||||
}
|
||||
crate::cmd::paste::merge_formatting(s, &mut frag);
|
||||
let mut out = Vec::new();
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| {
|
||||
out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(p.props.style.as_deref(), &r.props)));
|
||||
});
|
||||
}
|
||||
out
|
||||
};
|
||||
for cs in [None, Some(true)] {
|
||||
for r in pasted(&s, None, wordcraft_doc::CharProps { style: Some("ChEmph".into()), cs, ..Default::default() }) {
|
||||
assert!(r.bold && r.bold_cs && r.italic && r.italic_cs && r.strike, "character style, cs {cs:?}: {r:?}");
|
||||
assert_eq!(r.underline, Underline::Single, "character style, cs {cs:?}");
|
||||
}
|
||||
for r in pasted(&s, Some("PEmph"), wordcraft_doc::CharProps { cs, ..Default::default() }) {
|
||||
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs && !r.strike, "paragraph style, cs {cs:?}: {r:?}");
|
||||
assert_eq!(r.underline, Underline::None, "paragraph style, cs {cs:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
|
||||
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
|
||||
@@ -4306,74 +4093,6 @@ fn layout_size_when_focus_is_in_header_updates_correct_section() {
|
||||
assert_eq!((s0.page_w, s0.page_h), (612.0, 792.0));
|
||||
}
|
||||
|
||||
/// #3639: with the caret in section 2's header, the header and footer commands change section 2.
|
||||
/// The caret's block index counts the header's paragraphs, and block 0 of the body is in section 1.
|
||||
#[test]
|
||||
fn header_and_footer_commands_change_the_section_of_the_header_the_caret_is_in() {
|
||||
use wordcraft_doc::{Block, Paragraph, PartKind, StoryRef};
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "section 1"}));
|
||||
run(&mut s, "layout.break", json!({"kind": "nextPage"}));
|
||||
run(&mut s, "text.insert", json!({"text": "section 2"}));
|
||||
assert_eq!(s.doc.sections().len(), 2);
|
||||
let header = |s: &mut Session, text: &str| {
|
||||
s.doc.add_part(PartKind::Header, vec![std::sync::Arc::new(Block::Para(Paragraph::with_text(text, Default::default())))])
|
||||
};
|
||||
let (h1, h2) = (header(&mut s, "H1"), header(&mut s, "H2"));
|
||||
let f1 = s.doc.add_part(PartKind::Footer, vec![std::sync::Arc::new(Block::Para(Paragraph::with_text("F1", Default::default())))]);
|
||||
s.doc.section_mut(0).headers.default = Some(h1);
|
||||
s.doc.section_mut(0).footers.default = Some(f1);
|
||||
s.doc.last_section.headers.default = Some(h2);
|
||||
let first = s.doc.sections()[0].1.clone();
|
||||
let in_h2 = |s: &mut Session| s.sel = crate::Selection::caret(s.doc.start_of(StoryRef::Part(h2)));
|
||||
|
||||
in_h2(&mut s);
|
||||
run(&mut s, "hf.position", json!({"header": 50}));
|
||||
assert_eq!(s.doc.last_section.header, 50.0);
|
||||
in_h2(&mut s);
|
||||
run(&mut s, "design.pageBorders", json!({"kind": "box"}));
|
||||
assert!(s.doc.last_section.page_borders.is_some());
|
||||
// Section 2 has no footer of its own and shows section 1's: Edit Footer opens that one and
|
||||
// keeps the link.
|
||||
in_h2(&mut s);
|
||||
assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f1);
|
||||
assert_eq!(s.doc.last_section.footers.default, None, "section 2 stays linked");
|
||||
in_h2(&mut s);
|
||||
run(&mut s, "insert.footer", json!({"text": "F2"}));
|
||||
let f2 = s.doc.last_section.footers.default.expect("section 2 has the new footer");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(f2)), "F2");
|
||||
in_h2(&mut s);
|
||||
assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f2, "Edit Footer opens section 2's footer");
|
||||
in_h2(&mut s);
|
||||
run(&mut s, "layout.linkToPrevious", json!({}));
|
||||
assert_eq!(s.doc.last_section.headers.default, None, "section 2 is linked to section 1");
|
||||
|
||||
assert_eq!(*s.doc.sections()[0].1, first, "section 1 is untouched");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(h1)), "H1");
|
||||
|
||||
// Section 2 now shows section 1's header and has its own footer. With the caret in that
|
||||
// header on section 2's page, the commands change section 2, not section 1 that owns it.
|
||||
let page2 = s.layout().pages.iter().position(|pg| pg.section == 1).expect("section 2 has a page");
|
||||
assert_eq!(s.layout().pages[page2].header_story, Some(h1));
|
||||
let in_h1 = |s: &mut Session, page: usize| {
|
||||
s.sel = crate::Selection::caret(s.doc.start_of(StoryRef::Part(h1)));
|
||||
s.page_hint = page;
|
||||
};
|
||||
in_h1(&mut s, page2);
|
||||
assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f2, "Edit Footer opens the footer section 2 shows");
|
||||
in_h1(&mut s, page2);
|
||||
run(&mut s, "hf.position", json!({"header": 40}));
|
||||
assert_eq!(s.doc.last_section.header, 40.0);
|
||||
assert_eq!(*s.doc.sections()[0].1, first, "section 1 is untouched");
|
||||
// On section 1's own page the same header is section 1's.
|
||||
in_h1(&mut s, 0);
|
||||
assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f1);
|
||||
in_h1(&mut s, 0);
|
||||
run(&mut s, "hf.position", json!({"header": 30}));
|
||||
assert_eq!(s.doc.sections()[0].1.header, 30.0);
|
||||
assert_eq!(s.doc.last_section.header, 40.0);
|
||||
}
|
||||
|
||||
/// #1433: the smallest page there can be (0.1" wide, no margins, set straight through Page
|
||||
/// Setup's section) still lays out and exports text, a table and two columns.
|
||||
#[test]
|
||||
@@ -5689,22 +5408,6 @@ fn replacing_a_toc_keeps_its_title_above_the_section_break() {
|
||||
assert_eq!(toc_layout(&s), before, "{}", text(&s));
|
||||
}
|
||||
|
||||
/// Replacing Word's TOC whose title sits above a section break leaves the caret after the table,
|
||||
/// as a plain replacement does: with the caret in the title, typing went into the title.
|
||||
#[test]
|
||||
fn replacing_a_toc_above_a_section_break_leaves_the_caret_after_it() {
|
||||
let mut s = word_toc_above_a_section_break("TOCHeading");
|
||||
s.sel = crate::Selection::caret(Pos { story: StoryRef::Body, path: wordcraft_doc::Path::top(0), off: 2 });
|
||||
run(&mut s, "references.toc", json!({"levels": 1}));
|
||||
// Past the last entry, not in the title or the entries.
|
||||
let last_entry = s.doc.body.iter().rposition(|b| b.as_para().is_some_and(|p| p.props.style.as_deref().is_some_and(|st| st.starts_with("TOC"))));
|
||||
assert!(last_entry.is_some_and(|e| s.sel.focus.path.last() > e), "{:?}: {}", s.sel.focus, text(&s));
|
||||
run(&mut s, "text.insert", json!({"text": "typed"}));
|
||||
let (paras, _) = toc_layout(&s);
|
||||
assert_eq!(paras.first().map(|(_, _, t)| t.as_str()), Some("Contents"), "the title is untouched: {paras:?}");
|
||||
assert!(paras.iter().any(|(st, _, t)| t == "typed" && !st.starts_with("TOC")), "{paras:?}");
|
||||
}
|
||||
|
||||
/// #4041: removing Word's TOC whose title sits above a section break takes the title, the blank
|
||||
/// paragraph ending its section and that break with the entries, as Word's Remove Table of
|
||||
/// Contents does (observed in Word for Mac): the empty paragraph after the table, ending the
|
||||
@@ -7514,64 +7217,6 @@ fn saving_a_text_file_over_itself_saves_the_document() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #6131: File › Export to DOCX, ODT or RTF writes a copy (`copy: true`). It made the copy the
|
||||
/// document's file and cleared its unsaved changes, so the next Save went to the copy and the
|
||||
/// original kept its old text. The copy has the edits; the document keeps its file, its changes
|
||||
/// and its save stamps.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn exporting_a_copy_keeps_the_documents_file() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-engine-export-copy-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let body = |p: &std::path::Path| crate::io::open_path(p).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
|
||||
for ext in ["docx", "odt", "rtf"] {
|
||||
let original = dir.join(format!("a-{ext}.docx"));
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "first"}));
|
||||
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
|
||||
run(&mut s, "text.insert", json!({"text": " edited"}));
|
||||
let stamps = (s.doc.core.revision, s.doc.core.modified.clone());
|
||||
let copy = dir.join(format!("copy.{ext}"));
|
||||
let r = run(&mut s, "file.saveAs", json!({"path": copy.to_string_lossy(), "copy": true}));
|
||||
assert_eq!(r["saved"], true, "{ext}");
|
||||
assert_eq!(body(©), "first edited", "{ext}: the copy has the edits");
|
||||
assert_eq!(s.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file");
|
||||
assert!(s.dirty, "{ext}: the document keeps its unsaved changes");
|
||||
assert_eq!((s.doc.core.revision, s.doc.core.modified.clone()), stamps, "{ext}: the document's save stamps are untouched");
|
||||
run(&mut s, "file.save", json!({}));
|
||||
assert_eq!(body(&original), "first edited", "{ext}: Save still writes the original");
|
||||
assert!(!s.dirty);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A copy with no path would open the Save As picker on an untitled document (whose answer is an
|
||||
/// ordinary save that adopts the file) or fall back to the open file's path and overwrite it while
|
||||
/// leaving the document dirty: refused in both cases (#6131 review).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_copy_without_a_path_is_refused() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "first"}));
|
||||
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("copy"), "{e}");
|
||||
assert!(s.ui_requests.is_empty(), "no picker opens");
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-engine-copy-no-path-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("doc.docx");
|
||||
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
|
||||
run(&mut s, "text.insert", json!({"text": " edited"}));
|
||||
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("copy"), "{e}");
|
||||
assert!(s.dirty, "the document keeps its unsaved changes");
|
||||
let on_disk = crate::io::open_path(&original).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(on_disk, "first", "the original file on disk was not overwritten");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A Markdown file saved as another Markdown file is that file from now on: the next save goes
|
||||
/// there and the first file stays as it was. Other formats keep the #2376 rule.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -7678,7 +7323,8 @@ fn scratch_dir(name: &str) -> std::path::PathBuf {
|
||||
dir
|
||||
}
|
||||
|
||||
pub(crate) fn tiny_png() -> Vec<u8> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn tiny_png() -> Vec<u8> {
|
||||
wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 30, 30, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
@@ -10004,77 +9650,6 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
|
||||
assert_eq!(text(&s), "Q");
|
||||
}
|
||||
|
||||
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
|
||||
#[test]
|
||||
fn change_case_follows_turkic_language_mapping() {
|
||||
// 1. Turkish (tr-TR): all 5 modes
|
||||
// Capitalize Each Word (title)
|
||||
let mut s = s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Işık");
|
||||
|
||||
// UPPERCASE
|
||||
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
|
||||
assert_eq!(text(&s), "İSTANBUL IŞIK");
|
||||
|
||||
// lowercase
|
||||
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
|
||||
assert_eq!(text(&s), "istanbul ışık");
|
||||
|
||||
// sentence case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
|
||||
assert_eq!(text(&s), "İstanbul. Işık.");
|
||||
|
||||
// toggle case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
|
||||
assert_eq!(text(&s), "iSTANBUL ıŞIK");
|
||||
|
||||
// 2. Azerbaijani (az-AZ)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 3. Crimean Tatar (crh)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 4. English control (en-US): unchanged Unicode default
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "Istanbul");
|
||||
|
||||
// 5. Mixed-language selection: Turkish run followed by English run
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Istanbul");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_case_sentence_ignores_decimal_points() {
|
||||
// #3485: Sentence case should not capitalize after decimal points.
|
||||
@@ -10147,9 +9722,6 @@ fn insert_icon_places_a_picture_of_the_requested_size_that_saves_and_recolours()
|
||||
#[test]
|
||||
fn markup_pdf_takes_the_track_changes_option_colours() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
|
||||
// A fixed creation date: without one each PDF is stamped with the current time, and the
|
||||
// exports compared below differ when a clock second ticks over between them.
|
||||
s.doc.core.created = "2026-01-01T00:00:00Z".into();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
|
||||
@@ -15685,32 +15257,6 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
|
||||
let mut s = s();
|
||||
for i in 0..80 {
|
||||
if i > 0 {
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
}
|
||||
run(&mut s, "text.insert", json!({"text": format!("Paragraph {i}")}));
|
||||
}
|
||||
let pages = s.layout().pages.len();
|
||||
assert!(pages >= 2, "expected a multi-page document, got {pages}");
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
let start = s.sel.focus.clone();
|
||||
// Advance page by page until the last page, then one more PageDown must reach the end.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageDown", json!({}));
|
||||
}
|
||||
let end = s.doc.end_of(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(s.sel.focus, end, "PageDown on the last page reaches the end of the document");
|
||||
// Step back page by page until page 0, then one more PageUp must reach the start.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageUp", json!({}));
|
||||
}
|
||||
assert_eq!(s.sel.focus, start, "PageUp on the first page reaches the start of the document");
|
||||
}
|
||||
|
||||
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
|
||||
/// (a nested cell's too), a column's, not the whole page's text width.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -41,41 +41,6 @@ fn assert_fixture_font(s: &mut Session) {
|
||||
assert!(runs > 0, "the font check must inspect laid-out body text");
|
||||
}
|
||||
|
||||
/// A document that just spills onto a second page: the most lines `make` can put on one page,
|
||||
/// then space before the last paragraph until it moves to page 2 ([`spill_last_paragraph`]).
|
||||
/// The fixtures are set in the bundled [`FIXTURE_FONT`], but a fixed line count still depends on
|
||||
/// that font's exact metrics and the page setup, so the tests find the spill point instead.
|
||||
fn just_spilling(make: impl Fn(usize) -> Session) -> Session {
|
||||
let mut lines = 10;
|
||||
while make(lines + 1).layout().pages.len() < 2 {
|
||||
lines += 1;
|
||||
assert!(lines < 120, "{lines} lines still fit on one page");
|
||||
}
|
||||
let mut s = make(lines);
|
||||
assert_eq!(s.layout().pages.len(), 1, "{lines} lines must fit on one page");
|
||||
spill_last_paragraph(&mut s);
|
||||
s
|
||||
}
|
||||
|
||||
/// Adds space before the last paragraph, half a point at a time, until it moves to page 2. The
|
||||
/// document then overflows by less than half a point, which any font reduction it is fitted with
|
||||
/// brings back.
|
||||
fn spill_last_paragraph(s: &mut Session) {
|
||||
let mut before = match s.doc.body.last().map(|b| &**b) {
|
||||
Some(wordcraft_doc::Block::Para(p)) => p.props.space_before.unwrap_or(0.0),
|
||||
_ => 0.0,
|
||||
};
|
||||
while s.layout().pages.len() < 2 {
|
||||
before += 0.5;
|
||||
assert!(before <= 200.0, "space before the last paragraph never moved it to page 2");
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = s.doc.body.last_mut().map(std::sync::Arc::make_mut) {
|
||||
p.props.space_before = Some(before);
|
||||
}
|
||||
s.touch();
|
||||
s.relayout();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_fails_on_single_page() {
|
||||
let mut s = create_multiline_doc(5);
|
||||
@@ -179,20 +144,15 @@ fn fit_one_page_respects_max_delta() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_respects_step_pt() {
|
||||
let at_11_4 = |lines: usize| {
|
||||
let mut s = create_multiline_doc(lines);
|
||||
for b in &mut s.doc.body {
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
p.mark.size = Some(11.4);
|
||||
for r in &mut p.runs {
|
||||
r.props.size = Some(11.4);
|
||||
}
|
||||
let mut s = create_multiline_doc(27);
|
||||
for b in &mut s.doc.body {
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
p.mark.size = Some(11.4);
|
||||
for r in &mut p.runs {
|
||||
r.props.size = Some(11.4);
|
||||
}
|
||||
}
|
||||
s.touch();
|
||||
s
|
||||
};
|
||||
let mut s = just_spilling(at_11_4);
|
||||
}
|
||||
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
@@ -202,7 +162,7 @@ fn fit_one_page_respects_step_pt() {
|
||||
let default_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "adjustSpacing": false}));
|
||||
assert!(default_res.is_err(), "default step 0.5 must skip all candidates when maxDelta is 0.4");
|
||||
|
||||
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, a fine-grained step (0.1 to 0.4 pt) succeeds.
|
||||
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, fine-grained steps (0.1..0.4) succeed (11.4 -> 11.0 pt).
|
||||
s.doc = doc_backup;
|
||||
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "stepPt": 0.1, "adjustSpacing": false}));
|
||||
assert!(res.is_ok(), "stepPt=0.1 must generate fine-grained candidates under maxDelta 0.4: {res:?}");
|
||||
@@ -917,7 +877,7 @@ fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_preserves_budget_across_document_serialization() {
|
||||
let mut s = just_spilling(create_multiline_doc);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
@@ -934,10 +894,12 @@ fn fit_one_page_preserves_budget_across_document_serialization() {
|
||||
assert_eq!(reopened_doc.fit_state.as_ref().map(|f| f.cum_delta), Some(0.5));
|
||||
assert!(reopened_doc.custom_props.is_empty(), "custom_props must remain empty");
|
||||
|
||||
// Reopen into a new session with additional spill: the last paragraph moves to page 2 again
|
||||
// Reopen into a new session with additional spill
|
||||
let mut s2 = Session::new(reopened_doc);
|
||||
assert_eq!(s2.layout().pages.len(), 1);
|
||||
spill_last_paragraph(&mut s2);
|
||||
let extra_p = wordcraft_doc::Paragraph::with_text("Extra overflow paragraph.", CharProps::default());
|
||||
s2.doc.body.push(wordcraft_doc::para_block(extra_p));
|
||||
s2.touch();
|
||||
s2.relayout();
|
||||
|
||||
// Second fit on reopened document preserves previous 0.5 delta, allowing only remaining 0.5 pt up to 1.0 cap
|
||||
let res2 = s2.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
|
||||
|
||||
@@ -1653,38 +1653,6 @@ fn a_link_keeps_a_selection_it_cannot_retype() {
|
||||
assert_eq!(s.doc.field_ranges(StoryRef::Body).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_selection_in_one_paragraph_is_not_one_line() {
|
||||
// A column (block) selection over the wrapped lines of one paragraph: both its ends are in
|
||||
// that paragraph, but it holds a piece of each line, so Word shows <<Selection in Document>>
|
||||
// for it and the text to display can't retype it (#8581).
|
||||
let mut s = typed("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau");
|
||||
let (first, second) = {
|
||||
let l = s.layout();
|
||||
let len = s.doc.para_at(&Pos::body(0, 0)).unwrap().text.len();
|
||||
let mut top = None;
|
||||
let mut first = None;
|
||||
let mut second = None;
|
||||
for off in 0..=len {
|
||||
let Some(c) = l.caret_on(&Pos::body(0, off), 0) else { continue };
|
||||
if top.is_some_and(|t| t != c.top) && second.is_none() {
|
||||
second = Some(off + 10);
|
||||
break;
|
||||
}
|
||||
if top.is_none() {
|
||||
top = Some(c.top);
|
||||
first = Some(off);
|
||||
}
|
||||
}
|
||||
(first.expect("the paragraph is laid out"), second.expect("the paragraph wraps"))
|
||||
};
|
||||
run(&mut s, "select.column", json!({"anchor": Pos::body(0, first), "focus": Pos::body(0, second)}));
|
||||
let segs = s.column_segments().expect("the block is one paragraph's lines").to_vec();
|
||||
assert_eq!(segs.len(), 2, "the block holds a piece of each of the paragraph's two lines");
|
||||
assert!(segs.iter().all(|(a, b)| a.path == segs[0].0.path && b.path == segs[0].0.path), "both pieces are in one paragraph");
|
||||
assert!(!crate::cmd::insert::selection_is_one_line(&s), "a column selection is not one line of text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_then_selecting_then_typing_are_two_undo_steps() {
|
||||
// #419: a selection that moves the insertion point ends the typing group, like a caret move.
|
||||
@@ -2394,102 +2362,6 @@ fn shift_right_at_the_end_of_a_cell_selects_the_cell_first() {
|
||||
assert_eq!(shift_right(&mut s), Some(((1, 1), (0, 0))));
|
||||
}
|
||||
|
||||
/// Left or Right as the canvas sends it: while an equation is edited the arrows move inside it
|
||||
/// (`equation.move`, as ui-egui's `equation_key` does); otherwise they run the command bound to the
|
||||
/// key, with Shift extending the selection.
|
||||
fn arrow(s: &mut Session, key: &str) {
|
||||
if s.math.is_some() {
|
||||
run(s, "equation.move", json!({"dir": if key == "Left" { "left" } else { "right" }}));
|
||||
return;
|
||||
}
|
||||
let (key, extend) = key.strip_prefix("Shift+").map_or((key, false), |k| (k, true));
|
||||
let id = s.registry.by_shortcut(key).map(|c| c.id).unwrap_or_else(|| panic!("nothing bound to {key}"));
|
||||
run(s, id, if extend { json!({"extend": true}) } else { json!({}) });
|
||||
}
|
||||
|
||||
/// The equation being edited and the caret in it.
|
||||
fn editing(s: &Session) -> Option<(Pos, wordcraft_doc::math_edit::MathPos)> {
|
||||
s.math.as_ref().map(|m| (m.at.clone(), m.pos.clone()))
|
||||
}
|
||||
|
||||
/// Presses `key` until the caret is out of the equation (at most 10 times).
|
||||
fn arrow_out(s: &mut Session, key: &str) {
|
||||
for _ in 0..10 {
|
||||
if s.math.is_none() {
|
||||
return;
|
||||
}
|
||||
arrow(s, key);
|
||||
}
|
||||
panic!("{key} didn't leave the equation");
|
||||
}
|
||||
|
||||
/// "a", an equation `x+y`, "b"; or with `n` equations side by side.
|
||||
fn equations_between_a_and_b(n: usize) -> Session {
|
||||
let mut s = typed("ab");
|
||||
for _ in 0..n {
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)}));
|
||||
run(&mut s, "insert.equation", json!({"linear": "x+y", "edit": false}));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn left_and_right_keys_step_into_and_out_of_an_equation() {
|
||||
use wordcraft_doc::math_edit::{MathPos, units};
|
||||
let e = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let end = MathPos::new(Vec::new(), units(&wordcraft_doc::math::parse_linear("x+y")));
|
||||
let mut s = equations_between_a_and_b(1);
|
||||
// Right from "a|" opens the equation at its start; leaving it past its end puts the caret
|
||||
// after it, so the next Right goes on over "b".
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)}));
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!(editing(&s), Some((Pos::body(0, 1), MathPos::default())));
|
||||
arrow_out(&mut s, "Right");
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 1 + e));
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!((editing(&s), s.sel.focus.clone()), (None, Pos::body(0, 2 + e)));
|
||||
// Left over "b", then into the equation at its end; out past its start, then on over "a".
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!((editing(&s), s.sel.focus.clone()), (None, Pos::body(0, 1 + e)));
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!(editing(&s), Some((Pos::body(0, 1), end)));
|
||||
arrow_out(&mut s, "Left");
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 1));
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!((editing(&s), s.sel.focus.clone()), (None, Pos::body(0, 0)));
|
||||
// Shift+Right selects over the equation as one character, as before.
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)}));
|
||||
arrow(&mut s, "Shift+Right");
|
||||
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1 + e)));
|
||||
// With text selected, Left and Right only collapse the selection, even when its moving end is
|
||||
// next to the equation.
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1)));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
|
||||
arrow(&mut s, "Shift+Right");
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_out_of_an_equation_steps_into_the_one_beside_it() {
|
||||
let e = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let mut s = equations_between_a_and_b(2);
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)}));
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!(editing(&s).map(|(at, _)| at), Some(Pos::body(0, 1)), "into the first one");
|
||||
arrow_out(&mut s, "Right");
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 1 + e), "between the two equations");
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!(editing(&s), Some((Pos::body(0, 1 + e), wordcraft_doc::math_edit::MathPos::default())), "into the second one");
|
||||
arrow_out(&mut s, "Right");
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!(editing(&s).map(|(at, _)| at), Some(Pos::body(0, 1 + e)), "Left goes back into the second one");
|
||||
arrow_out(&mut s, "Left");
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!(editing(&s).map(|(at, _)| at), Some(Pos::body(0, 1)), "then into the first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_initial_capitals_are_corrected() {
|
||||
let s = typed("the WOrd and THe end, not IDs or CDs. TV is fine ");
|
||||
@@ -3448,22 +3320,13 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "İNgilizce ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "İngilizce ", "no combining dot in any language");
|
||||
// #3503: two initial capitals and caps-lock with a stray İ in English.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "Wİrd ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "two initial capitals lowercases İ to i in English");
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "wİRD ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "caps-lock slip fixes wİRD to Wird in English");
|
||||
}
|
||||
|
||||
/// #3479: Format > Change Case follows the same Turkic case mapping as AutoCorrect, using
|
||||
/// each run's own language; other languages keep the Unicode default.
|
||||
#[test]
|
||||
fn change_case_follows_turkic_case_mapping() {
|
||||
for tag in ["tr-TR", "az-AZ", "crh"] {
|
||||
for tag in ["tr-TR", "az-AZ"] {
|
||||
for (mode, input, want) in [
|
||||
("upper", "istanbul", "İSTANBUL"),
|
||||
("lower", "IŞIK", "ışık"),
|
||||
@@ -3676,77 +3539,6 @@ fn typing_over_backward_selection_keeps_its_font() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `One`, a picture (floating with Square wrapping when `floating`), `Two`; the picture selected,
|
||||
/// right to left when floating.
|
||||
fn picture_between_paragraphs(floating: bool) -> Session {
|
||||
let mut s = s();
|
||||
typ(&mut s, "One\n");
|
||||
run(&mut s, "insert.picture", json!({"data": crate::cmd::insert::base64_encode(&crate::tests::tiny_png()), "width": 50}));
|
||||
typ(&mut s, "\nTwo");
|
||||
let pic = Pos::body(1, 0);
|
||||
let end = Pos { off: pic.off + wordcraft_doc::para::OBJ.len_utf8(), ..pic.clone() };
|
||||
run(&mut s, "select.range", json!({"anchor": pic, "focus": end}));
|
||||
if floating {
|
||||
run(&mut s, "arrange.wrap", json!({"wrap": "square"}));
|
||||
s.sel = crate::Selection { anchor: s.sel.focus.clone(), focus: s.sel.anchor.clone() };
|
||||
}
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_some_and(|(_, o)| o.is_floating() == floating));
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_on_a_selected_picture_does_nothing() {
|
||||
// Word for Mac: with a picture selected, inline or floating, Enter (any number of times)
|
||||
// leaves it alone (#4126).
|
||||
for floating in [false, true] {
|
||||
let mut s = picture_between_paragraphs(floating);
|
||||
let (doc, sel) = (s.doc.clone(), s.sel.clone());
|
||||
typ(&mut s, "\n\n\n");
|
||||
assert_eq!(s.doc, doc, "the picture and the paragraphs stay as they were (floating: {floating})");
|
||||
assert_eq!(s.sel, sel, "the picture stays selected (floating: {floating})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_break_on_a_selected_picture_goes_in_front_of_it() {
|
||||
// Word for Mac: Shift+Enter or a page break on a selected picture puts the break in front of
|
||||
// it (an inline picture moves down a line or to the next page; a floating one's anchor does)
|
||||
// and keeps it selected (#4126). A column break is treated the same way.
|
||||
use wordcraft_doc::para::{COLUMN_BREAK, OBJ, PAGE_BREAK};
|
||||
for (id, c) in [("text.lineBreak", '\n'), ("text.pageBreak", PAGE_BREAK), ("text.columnBreak", COLUMN_BREAK)] {
|
||||
for floating in [false, true] {
|
||||
let mut s = picture_between_paragraphs(floating);
|
||||
let (doc, sel) = (s.doc.clone(), s.sel.clone());
|
||||
let (at, before) = crate::cmd::objects::object_selection(&s).map(|(p, o)| (p, o.clone())).unwrap();
|
||||
run(&mut s, id, json!({}));
|
||||
run(&mut s, id, json!({}));
|
||||
let text: Vec<_> = paras(&s).into_iter().map(|p| p.0).collect();
|
||||
assert_eq!(text, ["One".to_string(), format!("{c}{c}{OBJ}"), "Two".to_string()], "{id}, floating: {floating}");
|
||||
let (pos, o) = crate::cmd::objects::object_selection(&s).expect("the picture stays selected");
|
||||
assert_eq!((pos.off, o), (at.off + 2 * c.len_utf8(), &before), "{id}, floating: {floating}");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!((&s.doc, &s.sel), (&doc, &sel), "{id}, floating: {floating}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_break_on_a_picture_in_a_picture_control_keeps_the_picture_selected() {
|
||||
// The break goes in front of the control, and the picture (not the control's start) stays
|
||||
// selected (#4126).
|
||||
let mut s = picture_between_paragraphs(false);
|
||||
run(&mut s, "developer.picture", json!({}));
|
||||
let obj = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let pic = Pos::body(1, obj);
|
||||
run(&mut s, "select.range", json!({"anchor": pic, "focus": Pos { off: obj * 2, ..pic.clone() }}));
|
||||
let before = crate::cmd::objects::object_selection(&s).map(|(_, o)| o.clone()).expect("the picture is selected");
|
||||
run(&mut s, "text.lineBreak", json!({}));
|
||||
assert!(paras(&s)[1].0.starts_with('\n'), "{:?}", paras(&s)[1].0);
|
||||
let (_, o) = crate::cmd::objects::object_selection(&s).expect("the picture stays selected");
|
||||
assert_eq!(o, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_arrow_moves_through_a_ligature_one_letter_at_a_time() {
|
||||
// A font that draws "ffi" as one glyph (bundled, so the test doesn't depend on the installed
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
//! A value chosen in a content control in place of its placeholder (a list entry, a date, a check
|
||||
//! box's mark) takes the control's own run properties (`w:sdtPr/w:rPr`, ECMA-376 Part 1
|
||||
//! §17.5.2.27), as typed text does (#3116). Packages are hand-written: the controls WordCraft
|
||||
//! inserts carry no run properties.
|
||||
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::StoryRef;
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_engine::Session;
|
||||
use wordcraft_engine::io::{open_bytes, save_bytes};
|
||||
|
||||
const W: &str =
|
||||
r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml""#;
|
||||
const RELS: &str = r#"xmlns="http://schemas.openxmlformats.org/package/2006/relationships""#;
|
||||
const TYPE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
|
||||
/// Opens a package with `body` and a grey Placeholder Text character style.
|
||||
fn open(body: &str) -> wordcraft_doc::Document {
|
||||
let styles = r#"<w:style w:type="character" w:styleId="PlaceholderText"><w:name w:val="Placeholder Text"/><w:rPr><w:color w:val="808080"/></w:rPr></w:style>"#;
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for (name, value) in [
|
||||
(
|
||||
"_rels/.rels",
|
||||
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/officeDocument" Target="word/document.xml"/></Relationships>"#),
|
||||
),
|
||||
(
|
||||
"word/_rels/document.xml.rels",
|
||||
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/styles" Target="styles.xml"/></Relationships>"#),
|
||||
),
|
||||
("word/document.xml", format!(r#"<w:document {W}><w:body>{body}</w:body></w:document>"#)),
|
||||
("word/styles.xml", format!(r#"<w:styles {W}>{styles}</w:styles>"#)),
|
||||
] {
|
||||
zip.add(name, value.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
open_bytes("form.docx", &zip.finish().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// A paragraph holding a control of `kind` (its `w:sdtPr` type element) tagged `tag`. Its
|
||||
/// placeholder is grey and boxed; its run properties ask for blue Source Serif 4 at 14 pt.
|
||||
fn control(tag: &str, kind: &str) -> String {
|
||||
let own = r#"<w:rPr><w:rFonts w:ascii="Source Serif 4" w:hAnsi="Source Serif 4"/><w:color w:val="1F4E79"/><w:sz w:val="28"/></w:rPr>"#;
|
||||
let shown =
|
||||
r#"<w:rPr><w:rStyle w:val="PlaceholderText"/><w:color w:val="808080"/><w:bdr w:val="single" w:sz="4" w:space="0" w:color="808080"/></w:rPr>"#;
|
||||
format!(
|
||||
r#"<w:p><w:sdt><w:sdtPr>{own}<w:tag w:val="{tag}"/><w:showingPlcHdr/>{kind}</w:sdtPr><w:sdtContent><w:r>{shown}<w:t>Choose</w:t></w:r></w:sdtContent></w:sdt></w:p>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// The formatting of the control's first character, and the control's own run properties.
|
||||
fn formatting(d: &wordcraft_doc::Document, tag: &str) -> (CharProps, CharProps) {
|
||||
let r = d.control_ranges(StoryRef::Body).into_iter().find(|r| r.control.tag == tag).unwrap();
|
||||
let at = r.content_start();
|
||||
(d.para_at(&at).unwrap().props_of_char(at.off).clone(), r.control.run_props.clone().unwrap())
|
||||
}
|
||||
|
||||
/// What shows of a run's formatting here: colour, font, size and box.
|
||||
fn look(p: &CharProps) -> impl PartialEq + std::fmt::Debug {
|
||||
(p.color, p.font.clone(), p.size, p.border)
|
||||
}
|
||||
|
||||
/// A list entry, a date or a check box's mark chosen in place of the placeholder takes the
|
||||
/// control's run properties, as typed text does; it kept the placeholder's grey and box. A saved
|
||||
/// file keeps the value's formatting.
|
||||
#[test]
|
||||
fn choosing_over_a_placeholder_takes_the_controls_formatting() {
|
||||
let entries = r#"<w:listItem w:displayText="Small" w:value="S"/><w:listItem w:displayText="Large" w:value="L"/>"#;
|
||||
let choices = [
|
||||
("size", format!("<w:dropDownList>{entries}</w:dropDownList>"), "developer.chooseItem", json!({"control": "size", "index": 1})),
|
||||
(
|
||||
"due",
|
||||
r#"<w:date><w:dateFormat w:val="d MMMM yyyy"/></w:date>"#.into(),
|
||||
"developer.setDate",
|
||||
json!({"control": "due", "date": "2026-12-01"}),
|
||||
),
|
||||
("ok", r#"<w14:checkbox><w14:checked w14:val="0"/></w14:checkbox>"#.into(), "developer.toggleCheckBox", json!({"control": "ok"})),
|
||||
];
|
||||
let body: String = choices.iter().map(|(tag, kind, ..)| control(tag, kind)).collect();
|
||||
let mut s = Session::new(open(&body));
|
||||
for (tag, _, command, params) in &choices {
|
||||
let (placeholder, own) = formatting(&s.doc, tag);
|
||||
assert_ne!(look(&placeholder), look(&own), "{tag}: the placeholder is formatted apart from its control");
|
||||
s.run(command, params).unwrap_or_else(|e| panic!("{command}: {e}"));
|
||||
assert_eq!(look(&formatting(&s.doc, tag).0), look(&own), "{tag}: {command} gives the control's run properties");
|
||||
}
|
||||
let saved = open_bytes("form.docx", &save_bytes("form.docx", &s.doc).unwrap()).unwrap();
|
||||
for (tag, ..) in &choices {
|
||||
let (value, own) = formatting(&saved, tag);
|
||||
assert_eq!(look(&value), look(&own), "{tag}: the saved value keeps the control's run properties");
|
||||
}
|
||||
}
|
||||
@@ -129,105 +129,6 @@ fn a_date_field_in_a_header_is_refreshed_too() {
|
||||
assert_eq!(found, [today], "the header's field is refreshed as well as the body's");
|
||||
}
|
||||
|
||||
/// A document whose `docDefaults` set `lang`, so a field run that names no language inherits it,
|
||||
/// as a German Word document does.
|
||||
fn open_body_in_lang(lang: &str, body: &str) -> wordcraft_doc::Document {
|
||||
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let styles = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:lang w:val="{lang}"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style></w:styles>"#
|
||||
);
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
wordcraft_engine::io::open_bytes(
|
||||
"d.docx",
|
||||
&zip(&[("_rels/.rels", rels), ("word/document.xml", &doc), ("word/_rels/document.xml.rels", doc_rels), ("word/styles.xml", &styles)]),
|
||||
)
|
||||
.expect("opens")
|
||||
}
|
||||
|
||||
/// German documents carry their language in `docDefaults`, not on each field run. A `DATE` field
|
||||
/// without `\@` therefore uses `dd.MM.yyyy`, and `MMMM`/`dddd` name the day in German, on open
|
||||
/// and on an explicit refresh, for `de-DE`, `de-AT` and `de-CH` (#7146).
|
||||
#[test]
|
||||
fn german_date_fields_inherit_the_document_default_language() {
|
||||
const PICTURE: &str = "dddd, d. MMMM yyyy";
|
||||
for lang in ["de-DE", "de-AT", "de-CH"] {
|
||||
let d = open_body_in_lang(
|
||||
lang,
|
||||
&format!(
|
||||
"<w:p>{}</w:p><w:p>{}</w:p>",
|
||||
field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false),
|
||||
field("DATE", "1/1/2020", false)
|
||||
),
|
||||
);
|
||||
let expected = wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some(lang));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got.len(), 2, "{lang}");
|
||||
assert_eq!(got[0].1, expected, "{lang}: weekday and month names come from docDefaults");
|
||||
assert_ne!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, None), "{lang}: not the English names");
|
||||
assert_eq!(
|
||||
got[1].1,
|
||||
wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)),
|
||||
"{lang}: a DATE field without a picture uses the German default"
|
||||
);
|
||||
// Saving and reopening keeps the inherited language, and an explicit refresh does not
|
||||
// fall back to English.
|
||||
let written = wordcraft_docx::write(&d).unwrap();
|
||||
let mut reopened = wordcraft_engine::io::open_bytes("reopened.docx", &written).unwrap();
|
||||
wordcraft_engine::cmd::references::refresh_date_fields(&mut reopened);
|
||||
let got = fields(&reopened);
|
||||
assert_eq!(got[0].1, expected, "{lang}: after round-trip");
|
||||
assert_eq!(got[1].1, wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)), "{lang}: after round-trip");
|
||||
}
|
||||
}
|
||||
|
||||
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
|
||||
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
|
||||
#[test]
|
||||
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
|
||||
const PICTURE: &str = "ddd, d. MMM yyyy";
|
||||
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
|
||||
// The abbreviations at a fixed date, independent of when the test runs.
|
||||
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
|
||||
}
|
||||
|
||||
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
|
||||
/// English result cached in the fixture is replaced with German weekday and month names.
|
||||
#[test]
|
||||
fn a_german_time_field_uses_german_names() {
|
||||
const PICTURE: &str = "dddd, d. MMMM yyyy 'um' HH:mm";
|
||||
let d =
|
||||
open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"TIME \@ "{PICTURE}""#), "Wednesday, 1 January 2020 um 00:00", false)));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got[0].0, format!(r#"TIME \@ "{PICTURE}""#));
|
||||
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
|
||||
}
|
||||
|
||||
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
|
||||
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
|
||||
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
|
||||
/// of the same formatter at a fixed January instant.
|
||||
#[test]
|
||||
fn austrian_german_documents_use_jaenner() {
|
||||
const PICTURE: &str = "dddd, d. MMMM yyyy";
|
||||
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
|
||||
|
||||
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
|
||||
assert_eq!(january("de-AT", "MMMM"), "Jänner");
|
||||
assert_eq!(january("de-AT", "MMM"), "Jän");
|
||||
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
|
||||
for lang in ["de-DE", "de-CH", "de"] {
|
||||
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
|
||||
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
|
||||
/// FIB, one compressed text piece, and the Clx that points at it.
|
||||
fn binary_doc_with_stale_date() -> Vec<u8> {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
mod comment_ids;
|
||||
mod content_controls;
|
||||
mod date_fields;
|
||||
mod macro_packages;
|
||||
mod odt_charts;
|
||||
|
||||
@@ -25,7 +25,7 @@ mod lookup;
|
||||
mod names;
|
||||
|
||||
use face::{BUNDLED, FontBytes};
|
||||
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled, bundled_inter};
|
||||
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
|
||||
#[cfg(test)]
|
||||
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -42,52 +42,14 @@ pub(crate) use names::{last_resort_face, legacy_family};
|
||||
|
||||
static GLOBAL: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
|
||||
|
||||
/// Fixed-capacity FIFO cache shared by outline and hinting tables so old zoom/script entries evict
|
||||
/// incrementally instead of wiping the whole table at once.
|
||||
pub(super) struct BoundedCache<K, V> {
|
||||
map: HashMap<K, V>,
|
||||
order: std::collections::VecDeque<K>,
|
||||
cap: usize,
|
||||
}
|
||||
|
||||
impl<K: Eq + std::hash::Hash + Clone, V> BoundedCache<K, V> {
|
||||
pub(super) fn new(cap: usize) -> Self {
|
||||
Self { map: HashMap::new(), order: std::collections::VecDeque::new(), cap: cap.max(1) }
|
||||
}
|
||||
|
||||
pub(super) fn get(&self, key: &K) -> Option<&V> {
|
||||
self.map.get(key)
|
||||
}
|
||||
|
||||
pub(super) fn insert(&mut self, key: K, val: V) {
|
||||
if let Some(existing) = self.map.get_mut(&key) {
|
||||
*existing = val;
|
||||
return;
|
||||
}
|
||||
while self.map.len() >= self.cap {
|
||||
let Some(oldest) = self.order.pop_front() else {
|
||||
break;
|
||||
};
|
||||
self.map.remove(&oldest);
|
||||
}
|
||||
self.order.push_back(key.clone());
|
||||
self.map.insert(key, val);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Process-wide font database.
|
||||
pub struct FontDb {
|
||||
faces: RwLock<Vec<Arc<FontFace>>>,
|
||||
outlines: Mutex<BoundedCache<(u32, u32), Arc<BezPath>>>,
|
||||
outlines: Mutex<HashMap<(u32, u32), Arc<BezPath>>>,
|
||||
/// Screen-hinted outlines per (face, glyph, ppem bits); `None` where the face can't be hinted.
|
||||
hinted: Mutex<BoundedCache<(u32, u32, u32), Option<Arc<BezPath>>>>,
|
||||
hinted: Mutex<HashMap<(u32, u32, u32), Option<Arc<BezPath>>>>,
|
||||
/// Light hinting instances per (face, ppem bits); `None` where the face can't be hinted.
|
||||
hinters: Mutex<BoundedCache<(u32, u32), Option<Arc<HintingInstance>>>>,
|
||||
hinters: Mutex<HashMap<(u32, u32), Option<Arc<HintingInstance>>>>,
|
||||
/// Fallback faces found per (character, excluded face), valid while the face count is the
|
||||
/// one stored (faces are only ever added). Layout asks once per uncovered character, and the
|
||||
/// search sorts every loaded face, so without this text in a script the requested font lacks
|
||||
@@ -101,8 +63,6 @@ pub struct FontDb {
|
||||
diagram_search_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(test)]
|
||||
diagram_publish_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(test)]
|
||||
run_style_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock<Vec<CatalogEntry>>,
|
||||
/// Fonts the user added at run time, and the folder they are stored in (#582).
|
||||
@@ -161,9 +121,9 @@ impl FontDb {
|
||||
}
|
||||
Self {
|
||||
faces: RwLock::new(faces),
|
||||
outlines: Mutex::new(BoundedCache::new(face::OUTLINE_CACHE_MAX)),
|
||||
hinted: Mutex::new(BoundedCache::new(face::HINTED_CACHE_MAX)),
|
||||
hinters: Mutex::new(BoundedCache::new(face::HINTER_CACHE_MAX)),
|
||||
outlines: Mutex::new(HashMap::new()),
|
||||
hinted: Mutex::new(HashMap::new()),
|
||||
hinters: Mutex::new(HashMap::new()),
|
||||
fallbacks: RwLock::new(FallbackCache::default()),
|
||||
run_fallbacks: RwLock::new(RunFallbackCache::default()),
|
||||
diagram_fallbacks: RwLock::new(DiagramFallbackCache::default()),
|
||||
@@ -173,8 +133,6 @@ impl FontDb {
|
||||
diagram_search_hook: Mutex::new(None),
|
||||
#[cfg(test)]
|
||||
diagram_publish_hook: Mutex::new(None),
|
||||
#[cfg(test)]
|
||||
run_style_hook: Mutex::new(None),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock::new(Vec::new()),
|
||||
user: RwLock::new(user::UserFonts::default()),
|
||||
|
||||
@@ -13,16 +13,6 @@ pub fn bundled() -> &'static [&'static [u8]] {
|
||||
BUNDLED
|
||||
}
|
||||
|
||||
/// The bundled Inter Regular and SemiBold, each with its style name: the same bytes as in [`bundled`], so a caller
|
||||
/// adds no second copy to the binary. The interface draws with them behind the suite's Inter, which is cut to Latin,
|
||||
/// Greek and Cyrillic.
|
||||
pub fn bundled_inter() -> [(&'static str, &'static [u8]); 2] {
|
||||
[("Regular", INTER_REGULAR), ("SemiBold", INTER_SEMIBOLD)]
|
||||
}
|
||||
|
||||
static INTER_REGULAR: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
|
||||
static INTER_SEMIBOLD: &[u8] = include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf");
|
||||
|
||||
pub(super) static BUNDLED: &[&[u8]] = &[
|
||||
include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/SourceSans3-Semibold.ttf"),
|
||||
@@ -33,9 +23,9 @@ pub(super) static BUNDLED: &[&[u8]] = &[
|
||||
include_bytes!("../../../../assets/fonts/SourceSerif4-Semibold.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/SourceSerif4-Bold.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/SourceSerif4-BoldIt.ttf"),
|
||||
INTER_REGULAR,
|
||||
include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/Inter-Medium.ttf"),
|
||||
INTER_SEMIBOLD,
|
||||
include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"),
|
||||
];
|
||||
|
||||
@@ -551,13 +541,9 @@ fn is_explicit_serif(name: &str) -> bool {
|
||||
|
||||
pub(super) static NEXT_ID: AtomicU32 = AtomicU32::new(1);
|
||||
|
||||
/// Unhinted glyph outlines kept per (face, glyph).
|
||||
pub(super) const OUTLINE_CACHE_MAX: usize = 16_384;
|
||||
/// Screen-hinted outlines kept per (face, glyph, ppem bits); narrower than [`OUTLINE_CACHE_MAX`]
|
||||
/// because zoom changes create entries per size.
|
||||
pub(super) const HINTED_CACHE_MAX: usize = 8_192;
|
||||
pub(super) const OUTLINE_CACHE_MAX: usize = 50_000;
|
||||
/// Hinting instances kept (one per face and text size on screen).
|
||||
pub(super) const HINTER_CACHE_MAX: usize = 128;
|
||||
pub(super) const HINTER_CACHE_MAX: usize = 256;
|
||||
/// Sizes hinted, in device pixels per em: below, text is too small to read anyway; above, the
|
||||
/// half-pixel hinting moves is invisible (and each size would cost a cache entry).
|
||||
pub(super) const HINT_PPEM: std::ops::RangeInclusive<f32> = 4.0..=96.0;
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
use super::face::{FALLBACK_FAMILY, FontFace};
|
||||
use super::fallback_data::{
|
||||
BALLOT_BOXES, DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block,
|
||||
fallback_order,
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, file_stamp, ranges_hold, read_fallback_file};
|
||||
use super::fallback_data::{
|
||||
DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order,
|
||||
};
|
||||
use super::{Arc, FontDb};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::{HashMap, Ordering};
|
||||
@@ -29,11 +28,7 @@ impl FontDb {
|
||||
_ => "Italic",
|
||||
};
|
||||
let styled = self.face(&base.family, style);
|
||||
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, &[c]) && styled.id != exclude {
|
||||
styled
|
||||
} else {
|
||||
base
|
||||
})
|
||||
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled.covers(c) && styled.id != exclude { styled } else { base })
|
||||
}
|
||||
|
||||
/// The fallback search, cached per (character, excluded face) until loaded faces or font
|
||||
@@ -75,9 +70,6 @@ impl FontDb {
|
||||
if let Some(face) = self.circle_fallback(c, exclude) {
|
||||
return (Some(face), self.read_faces().len());
|
||||
}
|
||||
if let Some((face, n)) = self.ballot_box_fallback(c, exclude) {
|
||||
return (Some(face), n);
|
||||
}
|
||||
let (found, n) = self.loaded_fallback(c, exclude);
|
||||
if found.is_some() {
|
||||
return (found, n);
|
||||
@@ -105,38 +97,6 @@ impl FontDb {
|
||||
find()
|
||||
}
|
||||
|
||||
/// A ballot box (☐ ☑ ☒, a check box's symbols) the face lacks: the first of the symbol faces
|
||||
/// ([`crate::word::SYMBOL`], in that order) that has all three, so a check box looks the same
|
||||
/// ticked and unticked (#7863). The UI fallback has ☐, drawn with a drop shadow, and ☑ but no
|
||||
/// ☒, which put a box's two states in different fonts. `None` when no listed face has all
|
||||
/// three: the ordinary fallback then. With the face, the number of loaded faces before the
|
||||
/// search: a face loaded during it (by it, or by another thread for a family it had passed)
|
||||
/// leaves that number behind, so the answer isn't cached for the new face list.
|
||||
fn ballot_box_fallback(&self, c: char, exclude: u32) -> Option<(Arc<FontFace>, usize)> {
|
||||
if !BALLOT_BOXES.contains(&c) {
|
||||
return None;
|
||||
}
|
||||
let n = self.read_faces().len();
|
||||
let all = |f: &Arc<FontFace>| f.id != exclude && BALLOT_BOXES.iter().all(|b| f.covers(*b));
|
||||
for family in crate::word::SYMBOL {
|
||||
if let Some(face) = self.find(family, "Regular").filter(all) {
|
||||
return Some((face, n));
|
||||
}
|
||||
// An installed family is loaded only when its files map all three.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let enabled = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled;
|
||||
if enabled && !self.is_loaded(family) && BALLOT_BOXES.iter().all(|b| self.family_maps(family, *b)) {
|
||||
self.load_cataloged(family);
|
||||
if let Some(face) = self.find(family, "Regular").filter(all) {
|
||||
return Some((face, n));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// [`Self::search_fallback`] when no loaded face covers `c`: load a system font that does,
|
||||
/// one search at a time.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -239,13 +199,8 @@ impl FontDb {
|
||||
|
||||
/// The face for a run, and the number of loaded faces the search last chose from.
|
||||
fn search_run(&self, chars: &[char], exclude: u32, bold: bool, italic: bool) -> (Option<Arc<FontFace>>, usize) {
|
||||
// A run of ballot boxes draws in their one face, as each of them alone does (#7863).
|
||||
let ballot = chars.first().filter(|_| chars.iter().all(|c| BALLOT_BOXES.contains(c))).and_then(|c| self.ballot_box_fallback(*c, exclude));
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
|
||||
let (mut base, mut checked) = match ballot {
|
||||
Some((face, n)) => (Some(face), n),
|
||||
None => self.loaded_covering(chars, exclude),
|
||||
};
|
||||
let (mut base, mut checked) = self.loaded_covering(chars, exclude);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if base.is_none() {
|
||||
// A character no loaded face covers: load a system font for it, then retry (the run's
|
||||
@@ -280,16 +235,12 @@ impl FontDb {
|
||||
(true, false) => "Bold",
|
||||
_ => "Italic",
|
||||
};
|
||||
// The count stays the one `base` was chosen from. `base` is loaded, so the style lookup
|
||||
// only picks among the family's loaded faces and loads nothing: a later count could only
|
||||
// take in a face another thread loaded meanwhile, and cache this answer for faces it never
|
||||
// saw (#7863).
|
||||
let before_style = self.read_faces().len();
|
||||
let styled = self.face(&base.family, style);
|
||||
#[cfg(test)]
|
||||
if let Some(hook) = self.run_style_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
|
||||
hook(self);
|
||||
if before_style == checked {
|
||||
checked = self.read_faces().len();
|
||||
}
|
||||
let face = if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, chars) && styled.id != exclude {
|
||||
let face = if styled.family.eq_ignore_ascii_case(&base.family) && chars.iter().all(|c| styled.covers(*c)) && styled.id != exclude {
|
||||
styled
|
||||
} else {
|
||||
base
|
||||
@@ -606,11 +557,3 @@ impl FontDb {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Can `styled`, a bold or italic face of `base`'s family, draw `chars` in its place? It must map
|
||||
/// them all, and all three ballot boxes when they are ballot boxes and `base` has all three, so a
|
||||
/// check box's states stay in one face in bold or italic text too (#7863).
|
||||
fn styled_covers(styled: &FontFace, base: &FontFace, chars: &[char]) -> bool {
|
||||
let boxes = chars.iter().all(|c| BALLOT_BOXES.contains(c)) && BALLOT_BOXES.iter().all(|b| base.covers(*b));
|
||||
chars.iter().chain(BALLOT_BOXES.iter().filter(|_| boxes)).all(|c| styled.covers(*c))
|
||||
}
|
||||
|
||||
@@ -242,9 +242,6 @@ pub const RTL_FALLBACKS: &[&str] = &[
|
||||
pub const RTL_FALLBACKS: &[&str] =
|
||||
&["Noto Naskh Arabic", "Noto Sans Arabic", "Noto Sans Hebrew", "Vazirmatn", "Segoe UI", "Arial", "Tahoma", "DejaVu Sans"];
|
||||
|
||||
/// The ballot boxes ☐ ☑ ☒: a check box's unchecked symbol and its two usual checked ones.
|
||||
pub(super) const BALLOT_BOXES: [char; 3] = ['\u{2610}', '\u{2611}', '\u{2612}'];
|
||||
|
||||
/// Families tried (when installed) for characters the loaded fonts lack: CJK, symbols, emoji.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) const SYSTEM_FALLBACKS: &[&str] = &[
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM};
|
||||
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM, HINTER_CACHE_MAX, OUTLINE_CACHE_MAX};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::fallback_data::read_fallback_file;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -220,7 +220,11 @@ impl FontDb {
|
||||
return p.clone();
|
||||
}
|
||||
let p = Arc::new(face.glyph_outline(gid));
|
||||
self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
|
||||
let mut cache = self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.len() >= OUTLINE_CACHE_MAX {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(key, p.clone());
|
||||
p
|
||||
}
|
||||
|
||||
@@ -243,13 +247,21 @@ impl FontDb {
|
||||
None => {
|
||||
// Built outside the lock: running a font's hinting programs takes a while.
|
||||
let h = face.screen_hinter(ppem).map(Arc::new);
|
||||
self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(hkey, h.clone());
|
||||
let mut cache = self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.len() >= HINTER_CACHE_MAX {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(hkey, h.clone());
|
||||
h
|
||||
}
|
||||
}
|
||||
};
|
||||
let p = hinter.and_then(|h| face.hinted_glyph_outline(gid, &h)).map(Arc::new);
|
||||
self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
|
||||
let mut cache = self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.len() >= OUTLINE_CACHE_MAX {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(key, p.clone());
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,18 +154,6 @@ fn screen_hinting_refuses_hostile_sizes() {
|
||||
assert!(db.hinted_outline(&face, u32::MAX, 20.0).is_none_or(|o| o.elements().is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_outline_cache_evicts_oldest_incrementally() {
|
||||
let mut c = BoundedCache::new(2);
|
||||
c.insert(1u32, "a");
|
||||
c.insert(2u32, "b");
|
||||
c.insert(3u32, "c");
|
||||
assert_eq!(c.len(), 2);
|
||||
assert!(c.get(&1).is_none(), "oldest entry evicted");
|
||||
assert_eq!(c.get(&2), Some(&"b"), "newer entry retained");
|
||||
assert_eq!(c.get(&3), Some(&"c"));
|
||||
}
|
||||
|
||||
/// The issue's run (#1549): Thai letters and digits, Latin letters, digits and the baht sign.
|
||||
const THAI_RUN: &str = "[D] น้ำ ค่ำ ปั้น ฝั่ง ปู่ ๑๒๓๔๕๖๗๘๙๐ ฿1,250.50";
|
||||
|
||||
|
||||
@@ -866,130 +866,6 @@ fn circle_checks_face_coverage() {
|
||||
assert_eq!(db.fallback_for('●', primary.id()).unwrap().family, FALLBACK_FAMILY);
|
||||
}
|
||||
|
||||
/// A bundled Source Sans 3 Regular named `family` that maps ☒ (U+2612) too: its ☐–☑ cmap group
|
||||
/// runs on one character further (the next group starts at U+2615, so the groups stay sorted).
|
||||
fn with_every_ballot_box(family: &str) -> Vec<u8> {
|
||||
let mut data = named_face("SourceSans3-Regular.ttf", family);
|
||||
let (from, to) = ([0x2610_u32, 0x2611].map(u32::to_be_bytes).concat(), [0x2610_u32, 0x2612].map(u32::to_be_bytes).concat());
|
||||
let mut patched = 0;
|
||||
while let Some(at) = data.windows(from.len()).position(|w| w == from) {
|
||||
data[at..at + to.len()].copy_from_slice(&to);
|
||||
patched += 1;
|
||||
}
|
||||
assert!(patched > 0);
|
||||
data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_check_box_draws_every_state_in_one_face() {
|
||||
// #7863: with the check box's font missing, ☐ and ☑ came from the UI fallback, which has no
|
||||
// ☒, and ☒ from another face, so ticking a box changed how it looked.
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
assert!(!primary.covers('☐'), "the requested face lacks the boxes");
|
||||
// A listed symbol face with ☐ and ☑ only, then a later one with all three.
|
||||
db.add_document_fonts(vec![
|
||||
(named_face("SourceSerif4-Regular.ttf", "Apple Symbols"), "Apple Symbols".to_string()),
|
||||
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
|
||||
]);
|
||||
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").id()).collect();
|
||||
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
|
||||
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), false, false).expect("a face has them");
|
||||
assert_eq!(run.id(), faces[0], "a run of them takes the same face");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_check_box_draws_every_state_in_one_face() {
|
||||
// The listed family's Regular face has all three boxes and its Bold face only ☐ and ☑: bold ☐
|
||||
// and ☑ took the Bold face, and ☒ the Regular one.
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
db.add_document_fonts(vec![
|
||||
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
|
||||
(named_face("SourceSans3-Bold.ttf", "DejaVu Sans"), "DejaVu Sans".to_string()),
|
||||
]);
|
||||
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").id()).collect();
|
||||
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
|
||||
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), true, false).expect("a face has them");
|
||||
assert_eq!(run.id(), faces[0], "a bold run of them takes the same face");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ballot_boxes_load_an_installed_symbol_face() {
|
||||
let dir = font_dir("ballot-boxes");
|
||||
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("DejaVu Sans")).unwrap();
|
||||
// An earlier listed family with only two of the boxes: never loaded for them.
|
||||
std::fs::write(dir.join("TwoBoxes-Regular.ttf"), named_face("SourceSerif4-Regular.ttf", "Apple Symbols")).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
db.set_system_fallback(false);
|
||||
assert!(db.fallback_for('☐', primary.id()).is_some());
|
||||
assert!(!db.is_loaded("DejaVu Sans"), "nothing is loaded with the system fallback off");
|
||||
db.set_system_fallback(true);
|
||||
let found = db.fallback_for('☐', primary.id()).unwrap();
|
||||
assert_eq!(found.family, "DejaVu Sans", "the installed face with all three");
|
||||
assert_eq!(db.fallback_for('☒', primary.id()).unwrap().id(), found.id());
|
||||
assert!(!db.is_loaded("Apple Symbols"), "a listed family without all three is not loaded");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_check_box_keeps_one_face_when_a_symbol_face_loads_during_its_search() {
|
||||
// A search for ☐ passed Apple Symbols, not loaded yet, and was loading the installed Segoe UI
|
||||
// Symbol when another thread loaded Apple Symbols. Its answer was remembered for the face count
|
||||
// after both loads, so ☐ kept Segoe UI Symbol while ☑ and ☒ took Apple Symbols, the first
|
||||
// listed face with all three.
|
||||
let dir = font_dir("ballot-box-race");
|
||||
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("Segoe UI Symbol")).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
let reads = || db.coverage.lock().unwrap().reads;
|
||||
let unread = reads();
|
||||
let loading = db.loading.lock().unwrap();
|
||||
std::thread::scope(|s| {
|
||||
let search = s.spawn(|| db.fallback_for('☐', primary.id()));
|
||||
// Past Apple Symbols, the search reads the installed file's character map, then waits for
|
||||
// `loading` to load the file. (A search that finishes without reading it ends the wait too.)
|
||||
while reads() == unread && !search.is_finished() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Another thread loads Apple Symbols meanwhile, as a font load adds faces (`loading` is
|
||||
// held here).
|
||||
db.add_fonts(vec![(with_every_ballot_box("Apple Symbols"), None)]);
|
||||
drop(loading);
|
||||
assert!(search.join().unwrap().is_some());
|
||||
});
|
||||
let faces: Vec<String> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").family.clone()).collect();
|
||||
assert_eq!(faces, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_run_of_check_boxes_keeps_one_face_when_a_symbol_face_loads_during_its_style_lookup() {
|
||||
// A bold run of boxes chose DejaVu Sans, the first listed face loaded with all three, and
|
||||
// looked up its bold face while another thread loaded Apple Symbols, listed earlier. The run's
|
||||
// answer was remembered for the face count after that load, so the run kept DejaVu Sans while
|
||||
// each box alone took Apple Symbols.
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
db.add_document_fonts(vec![(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string())]);
|
||||
let apple = with_every_ballot_box("Apple Symbols");
|
||||
*db.run_style_hook.lock().unwrap() = Some(Box::new(move |db| {
|
||||
// A font load adds faces and leaves the generation as it is.
|
||||
db.add_fonts(vec![(apple, None)]);
|
||||
}));
|
||||
let run = ['☐', '☑', '☒'];
|
||||
assert!(db.fallback_for_run(&run, primary.id(), true, false).is_some());
|
||||
assert!(db.run_style_hook.lock().unwrap().is_none(), "Apple Symbols loaded during the run's style lookup");
|
||||
let boxes: Vec<String> = run.iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").family.clone()).collect();
|
||||
assert_eq!(boxes, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
|
||||
let again = db.fallback_for_run(&run, primary.id(), true, false).expect("a face has them");
|
||||
assert_eq!(again.family, "Apple Symbols", "the run takes the face each box takes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_postscript_names() {
|
||||
let dir = font_dir("postscript");
|
||||
|
||||
@@ -17,7 +17,7 @@ pub mod word;
|
||||
|
||||
pub use fontdb::{
|
||||
FALLBACK_FAMILY, FONT_FILE_EXTS, FaceRef, FontDb, FontFace, FontFormat, Installed, LocalName, MAX_FONT_FILE_BYTES, UserFont, UserFontError,
|
||||
base_style, bundled, bundled_inter, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
|
||||
base_style, bundled, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
|
||||
};
|
||||
pub use harfrust::Feature;
|
||||
use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer};
|
||||
|
||||
@@ -40,11 +40,6 @@ pub fn has_named_substitutes(family: &str) -> bool {
|
||||
|
||||
const SANS: &[&str] = &["Carlito", "Helvetica Neue", "Arial", "Liberation Sans", "Noto Sans", "DejaVu Sans", "Source Sans 3"];
|
||||
|
||||
/// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
|
||||
/// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
|
||||
/// A check box's ballot boxes take their face from this list too (`FontDb::fallback_for`, #7863).
|
||||
pub(crate) const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
|
||||
|
||||
/// Serif faces known by name with no open clone of their own (lowercase): they take the generic
|
||||
/// serif list, but as fonts we know, not by a guess from the name ([`has_own_substitutes`]).
|
||||
const KNOWN_SERIFS: &[&str] = &[
|
||||
@@ -80,6 +75,9 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) {
|
||||
const ARIAL: &[&str] = &["Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
|
||||
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
|
||||
const TIMES: &[&str] = &["Liberation Serif", "Times", "Tinos", "Source Serif 4"];
|
||||
// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
|
||||
// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
|
||||
const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
|
||||
// Persian / Arabic document fonts. Naskh (book) faces such as B Nazanin, B Lotus, B Zar and
|
||||
// Traditional Arabic, then the sans faces (B Yekan, B Titr, IRANSans) people use for
|
||||
// headings and screens. Open fonts with full Persian coverage first.
|
||||
|
||||
+24
-14
@@ -4,28 +4,38 @@ use wordcraft_doc::{Document, SectionProps};
|
||||
|
||||
pub use craft_html::doc::{ImageLoader, PAGE_FONT, css_len_pt, decode, decode_as, decode_entity, esc, export_flow, parse, parse_with, unescape};
|
||||
|
||||
use crate::{from_shared, shared_section, to_shared};
|
||||
|
||||
pub fn import(html: &str) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import(html))
|
||||
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import_page(html, images))
|
||||
pub fn import(html: &str) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import(html)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import_with(html, images))
|
||||
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import_page(html, images)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import_on(html, images, &shared_section(page)?))
|
||||
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import_with(html, images)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_html::doc::export(&to_shared(doc)?))
|
||||
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import_on(html, images, &shared_section(page))).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn export_fragment(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_html::doc::export_fragment(&to_shared(doc)?))
|
||||
pub fn export(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_html::doc::export(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn export_fragment(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_html::doc::export_fragment(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,22 +4,23 @@ use wordcraft_doc::{Document, SectionProps};
|
||||
|
||||
pub use craft_latex::{escape_text, latex_to_linear, linear_to_latex};
|
||||
|
||||
use crate::{from_shared, to_shared};
|
||||
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
from_shared(craft_latex::import(bytes))
|
||||
pub fn import(bytes: &[u8]) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_latex::import(bytes)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
let mut d = import(bytes)?;
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
|
||||
let mut d = import(bytes);
|
||||
d.last_section = page.clone();
|
||||
Ok(d)
|
||||
d
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> craft_flow::Flow {
|
||||
craft_latex::parse(text)
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_latex::export(&to_shared(doc)?))
|
||||
pub fn export(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_latex::export(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
+15
-39
@@ -28,27 +28,6 @@ use wordcraft_doc::Document;
|
||||
/// (`wordcraft_docx::package::MAX_ENTRIES`); checked before `zip` parses them (#3660).
|
||||
pub const MAX_ZIP_ENTRIES: u64 = 20_000;
|
||||
|
||||
/// The document as the shared model the format crates read and write.
|
||||
///
|
||||
/// A conversion that fails is an error, never an empty document or an empty file: the caller
|
||||
/// says so instead of writing a file with nothing in it.
|
||||
pub(crate) fn to_shared(doc: &Document) -> Result<craft_wordmodel::Document, String> {
|
||||
wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The shared model as the app's document model. A conversion that fails is an error, never
|
||||
/// an empty document.
|
||||
pub(crate) fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The page a file that gives no page size starts on, as the shared model.
|
||||
pub(crate) fn shared_section(page: &wordcraft_doc::SectionProps) -> Result<craft_wordmodel::SectionProps, String> {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
Ok(to_shared(&d)?.last_section)
|
||||
}
|
||||
|
||||
/// Extensions this crate handles.
|
||||
pub const EXTENSIONS: &[&str] =
|
||||
&["txt", "text", "md", "markdown", "html", "htm", "xhtml", "mht", "mhtml", "rtf", "odt", "ott", "fodt", "tex", "latex", "ltx"];
|
||||
@@ -56,15 +35,15 @@ pub const EXTENSIONS: &[&str] =
|
||||
/// Import `bytes` in the format named by `ext` (no dot, any case). `None` = not our format.
|
||||
pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let r: Result<Document, String> = match ext.as_str() {
|
||||
let r = match ext.as_str() {
|
||||
"txt" | "text" => Ok(txt::import(bytes)),
|
||||
"md" | "markdown" => markdown::import(&txt::decode(bytes)),
|
||||
"html" | "htm" | "xhtml" => html::import_page(&html::decode(bytes), &|_| None),
|
||||
"mht" | "mhtml" => mht::import(bytes),
|
||||
"md" | "markdown" => Ok(markdown::import(&txt::decode(bytes))),
|
||||
"html" | "htm" | "xhtml" => Ok(html::import_page(&html::decode(bytes), &|_| None)),
|
||||
"mht" | "mhtml" => Ok(mht::import(bytes)),
|
||||
"rtf" => rtf::import(bytes),
|
||||
"odt" | "ott" => odt::import(bytes),
|
||||
"fodt" => odt::import_flat(bytes),
|
||||
"tex" | "latex" | "ltx" => latex::import(bytes),
|
||||
"tex" | "latex" | "ltx" => Ok(latex::import(bytes)),
|
||||
_ => return None,
|
||||
};
|
||||
Some(r.map(|mut d| {
|
||||
@@ -78,36 +57,33 @@ pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
|
||||
/// formats keep the page their file gives.
|
||||
pub fn import_on(ext: &str, bytes: &[u8], page: &wordcraft_doc::SectionProps) -> Option<Result<Document, String>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let mut doc: Result<Document, String> = match ext.as_str() {
|
||||
let mut doc = match ext.as_str() {
|
||||
"odt" | "ott" => return Some(odt::import_on(bytes, page)),
|
||||
"fodt" => return Some(odt::import_flat_on(bytes, page)),
|
||||
"txt" | "text" => Ok(txt::import_on(bytes, page)),
|
||||
"txt" | "text" => txt::import_on(bytes, page),
|
||||
"md" | "markdown" => markdown::import_on(&txt::decode(bytes), page),
|
||||
"html" | "htm" | "xhtml" => html::import_on(&html::decode(bytes), &|_| None, page),
|
||||
"mht" | "mhtml" => mht::import_on(bytes, page),
|
||||
_ => return import(&ext, bytes),
|
||||
};
|
||||
if let Ok(d) = doc.as_mut() {
|
||||
d.ensure_nonempty();
|
||||
}
|
||||
Some(doc)
|
||||
doc.ensure_nonempty();
|
||||
Some(Ok(doc))
|
||||
}
|
||||
|
||||
/// Export `doc` in the format named by `ext`. `None` = not our format.
|
||||
pub fn export(ext: &str, doc: &Document) -> Option<Result<Vec<u8>, String>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let out: Result<Vec<u8>, String> = match ext.as_str() {
|
||||
Some(match ext.as_str() {
|
||||
"txt" | "text" => Ok(txt::export(doc)),
|
||||
"md" | "markdown" => markdown::export(doc).map(String::into_bytes),
|
||||
"html" | "htm" | "xhtml" => html::export(doc).map(String::into_bytes),
|
||||
"rtf" => rtf::export(doc).map(String::into_bytes),
|
||||
"md" | "markdown" => Ok(markdown::export(doc).into_bytes()),
|
||||
"html" | "htm" | "xhtml" => Ok(html::export(doc).into_bytes()),
|
||||
"rtf" => Ok(rtf::export(doc).into_bytes()),
|
||||
"odt" => odt::export(doc),
|
||||
"ott" => odt::export_template(doc),
|
||||
"fodt" => odt::export_flat(doc),
|
||||
"tex" | "latex" | "ltx" => latex::export(doc).map(String::into_bytes),
|
||||
"tex" | "latex" | "ltx" => Ok(latex::export(doc).into_bytes()),
|
||||
_ => return None,
|
||||
};
|
||||
Some(out)
|
||||
})
|
||||
}
|
||||
|
||||
/// How [`export_with`] writes a copy.
|
||||
|
||||
@@ -4,19 +4,23 @@ use wordcraft_doc::{Block, Document, SectionProps};
|
||||
|
||||
pub use craft_markdown::{Refs, escape, parse, parse_inlines};
|
||||
|
||||
use crate::{from_shared, shared_section, to_shared};
|
||||
|
||||
pub fn import(text: &str) -> Result<Document, String> {
|
||||
from_shared(craft_markdown::import(text))
|
||||
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn import_on(text: &str, page: &SectionProps) -> Result<Document, String> {
|
||||
from_shared(craft_markdown::import_on(text, &shared_section(page)?))
|
||||
pub fn import(text: &str) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_markdown::import(text)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn import_on(text: &str, page: &SectionProps) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_markdown::import_on(text, &shared_section(page))).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`import_on`] returning the document and the 0-based starting line of each top-level block.
|
||||
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> Result<(Document, Vec<usize>), String> {
|
||||
let doc = import_on(text, page)?;
|
||||
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> (Document, Vec<usize>) {
|
||||
let doc = import_on(text, page);
|
||||
let src_lines: Vec<&str> = text.strip_prefix('\u{FEFF}').unwrap_or(text).lines().collect();
|
||||
let mut out = Vec::with_capacity(doc.body.len());
|
||||
let mut cursor = 0usize;
|
||||
@@ -53,9 +57,12 @@ pub fn import_on_with_lines(text: &str, page: &SectionProps) -> Result<(Document
|
||||
}
|
||||
out.push(found.min(src_lines.len()));
|
||||
}
|
||||
Ok((doc, out))
|
||||
(doc, out)
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_markdown::export(&to_shared(doc)?))
|
||||
pub fn export(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_markdown::export(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ pub fn is_mht(bytes: &[u8]) -> bool {
|
||||
}
|
||||
|
||||
/// Import an MHT file.
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
pub fn import(bytes: &[u8]) -> Document {
|
||||
import_on(bytes, &SectionProps::default())
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ fn part_bytes(part: &Part) -> &[u8] {
|
||||
}
|
||||
|
||||
/// [`import`] onto `page`.
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
|
||||
let msg = craft_mime::parse(bytes, &craft_mime::Limits::DEFAULT);
|
||||
let mut leaves = Vec::new();
|
||||
collect_leaves(&msg.root, &mut leaves);
|
||||
@@ -46,7 +46,7 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String>
|
||||
.or_else(|| leaves.iter().copied().find(|p| matches!(p.declared_media_type(), Some("text/html" | "application/xhtml+xml"))));
|
||||
let Some(root) = root else {
|
||||
let text = leaves.iter().copied().find(|p| p.declared_media_type().unwrap_or("text/plain") == "text/plain").map(part_bytes).unwrap_or(&[]);
|
||||
return Ok(crate::txt::import_on(text, page));
|
||||
return crate::txt::import_on(text, page);
|
||||
};
|
||||
let html = crate::html::decode_as(part_bytes(root), root.content_type.get("charset"));
|
||||
let base = root.content_location().unwrap_or("");
|
||||
|
||||
@@ -1,83 +1,33 @@
|
||||
//! OpenDocument Text (`.odt`, `.ott`, `.fodt`) import and export via `craft-odf`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::{Block, Document, SectionProps};
|
||||
use wordcraft_doc::{Document, SectionProps};
|
||||
|
||||
pub use craft_odf::text::{CryptError, TEMPLATE_MIME, TEXT_MIME, decrypt, encrypt, is_encrypted};
|
||||
|
||||
/// Text room, points, that header and footer bands leave on a page (as Page Setup's margins must).
|
||||
const MIN_TEXT_ROOM: f32 = 36.0;
|
||||
|
||||
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A shared document opened as a WordCraft one, its pages keeping the text room the header and
|
||||
/// footer bands leave ([`keep_text_room`]).
|
||||
fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
|
||||
let mut doc = wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())?;
|
||||
keep_text_room(&mut doc);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// A page's header and footer bands grow its margins, and a band as tall as the page (to fit a
|
||||
/// full-page picture, #5806) takes all the text's room: every page then draws one line below the
|
||||
/// paper and the rest of the body is missing from the render and PDF. The bands grow the margins
|
||||
/// only while the text keeps half an inch (Page Setup's rule for margins): the larger margin, the
|
||||
/// larger band with it, gives up the excess first, so the smaller band is kept whole. The band's
|
||||
/// own height is untouched: the header still draws as tall as its content.
|
||||
///
|
||||
/// `craft-odf` caps a band at the page's longer side rather than at the room left for text; this
|
||||
/// is the guard that keeps the text on the page until the shared reader makes the same one.
|
||||
fn keep_text_room(doc: &mut Document) {
|
||||
for b in &mut doc.body {
|
||||
if let Block::Para(p) = &mut *Arc::make_mut(b)
|
||||
&& let Some(sec) = p.section.as_mut()
|
||||
{
|
||||
keep_section_room(sec);
|
||||
}
|
||||
}
|
||||
keep_section_room(&mut doc.last_section);
|
||||
}
|
||||
|
||||
fn keep_section_room(sec: &mut SectionProps) {
|
||||
if !(sec.page_h.is_finite() && sec.margin_top.is_finite() && sec.margin_bottom.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let mut excess = sec.margin_top + sec.margin_bottom - (sec.page_h - MIN_TEXT_ROOM);
|
||||
if excess <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let (first, second) = if sec.margin_top >= sec.margin_bottom {
|
||||
(&mut sec.margin_top, &mut sec.margin_bottom)
|
||||
} else {
|
||||
(&mut sec.margin_bottom, &mut sec.margin_top)
|
||||
};
|
||||
let cut = excess.min(first.max(0.0));
|
||||
*first -= cut;
|
||||
excess -= cut;
|
||||
if excess > 0.0 {
|
||||
*second = (*second - excess).max(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
from_shared(craft_odf::text::import(bytes)?)
|
||||
let shared = craft_odf::text::import(bytes)?;
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
from_shared(craft_odf::text::import_on(bytes, &shared_section(page))?)
|
||||
let shared = craft_odf::text::import_on(bytes, &shared_section(page))?;
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn import_flat(bytes: &[u8]) -> Result<Document, String> {
|
||||
from_shared(craft_odf::text::import_flat(bytes)?)
|
||||
let shared = craft_odf::text::import_flat(bytes)?;
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn import_flat_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
from_shared(craft_odf::text::import_flat_on(bytes, &shared_section(page))?)
|
||||
let shared = craft_odf::text::import_flat_on(bytes, &shared_section(page))?;
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The shared model an OpenDocument file is written from. ODF's `dc:date` is an instant (a `Z`
|
||||
|
||||
@@ -2,11 +2,9 @@
|
||||
|
||||
use wordcraft_doc::Document;
|
||||
|
||||
use crate::{from_shared, to_shared};
|
||||
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
let shared = craft_rtf::doc::import(bytes)?;
|
||||
from_shared(shared)
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn parse(bytes: &[u8]) -> Result<crate::model::Flow, String> {
|
||||
@@ -14,6 +12,9 @@ pub fn parse(bytes: &[u8]) -> Result<crate::model::Flow, String> {
|
||||
Ok(craft_flow::from_doc(&shared))
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_rtf::doc::export(&to_shared(doc)?))
|
||||
pub fn export(doc: &Document) -> String {
|
||||
let Ok(shared) = wordcraft_docx::to_shared_model(doc) else {
|
||||
return String::new();
|
||||
};
|
||||
craft_rtf::doc::export(&shared)
|
||||
}
|
||||
|
||||
+9
-337
@@ -95,7 +95,15 @@ pub fn read_rows(bytes: &[u8], pick: Pick<'_>) -> Result<(Vec<String>, Vec<Vec<S
|
||||
let names: Vec<String> = book.sheets.iter().map(|s| s.name.clone()).collect();
|
||||
let i = resolve(&names, pick)?;
|
||||
let sheet = &book.sheets[i];
|
||||
let rows = cells_to_rows(&sheet.cells, ods_value);
|
||||
let rows = cells_to_rows(&sheet.cells, |c| {
|
||||
if !c.text.is_empty() {
|
||||
clamp_cell(c.text.clone())
|
||||
} else if let Some(v) = c.value() {
|
||||
format_value(&v)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
});
|
||||
return Ok((names, rows));
|
||||
}
|
||||
Err("not an Excel or OpenDocument spreadsheet".into())
|
||||
@@ -170,187 +178,6 @@ fn format_value(v: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// An OpenDocument cell's display string, from `office:value-type`: floats from `office:value`,
|
||||
/// dates and times from `office:date-value` / `office:time-value` in ISO 8601 form (`yyyy-mm-dd`,
|
||||
/// `yyyy-mm-dd hh:mm[:ss]`, `hh:mm[:ss]`), booleans as `TRUE`/`FALSE`, and strings, percentages
|
||||
/// and currencies as the cell's text (their value when the text is blank). A value that does not
|
||||
/// parse falls back to the text. A covered cell under a merged cell is blank.
|
||||
///
|
||||
/// A float merges its value, not the text its number format shows: a ZIP code `01234` shown
|
||||
/// through the format `00000` merges as `1234`, and `1,234` shown with a thousands separator
|
||||
/// merges as `1234`.
|
||||
fn ods_value(c: &craft_ods::Cell) -> String {
|
||||
use craft_ods::ValueType as T;
|
||||
if c.covered {
|
||||
return String::new();
|
||||
}
|
||||
let typed = match (c.value_type, c.raw.as_deref().map(str::trim)) {
|
||||
(Some(T::Float | T::Boolean), Some(_)) => c.value().map(|v| format_value(&v)),
|
||||
(Some(T::Date), Some(v)) => iso_datetime(v),
|
||||
(Some(T::Time), Some(v)) => iso_time(v),
|
||||
(Some(T::Percentage | T::Currency | T::String), Some(_)) if c.text.is_empty() => c.value().map(|v| format_value(&v)),
|
||||
_ => None,
|
||||
};
|
||||
typed.map(clamp_cell).unwrap_or_else(|| clamp_cell(c.text.clone()))
|
||||
}
|
||||
|
||||
/// An ISO 8601 date or date-time (`2024-03-05`, `2024-03-05T13:45:00.000`) as `yyyy-mm-dd`,
|
||||
/// with ` hh:mm[:ss]` when the time isn't midnight. `None` unless the whole value is a valid
|
||||
/// calendar date and clock time.
|
||||
fn iso_datetime(v: &str) -> Option<String> {
|
||||
use chrono::Datelike;
|
||||
let v = v.trim();
|
||||
let (date, time) = match v.split_once('T') {
|
||||
Some((date, time)) => (date, Some(time)),
|
||||
None => (v, None),
|
||||
};
|
||||
// A date alone may carry a zone (`Z` or `±hh:mm`), which is left out.
|
||||
let date = match (time, date.strip_suffix('Z')) {
|
||||
(None, Some(d)) => d,
|
||||
(None, None) if date.len() > 6 && date.get(date.len() - 6..).is_some_and(|z| z.starts_with(['+', '-']) && z.get(3..4) == Some(":")) => {
|
||||
zone_offset(date.get(date.len() - 5..)?)?;
|
||||
date.get(..date.len() - 6)?
|
||||
}
|
||||
_ => date,
|
||||
};
|
||||
let date = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
|
||||
let mut out = format!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day());
|
||||
if let Some(time) = time {
|
||||
let (clock, fraction) = clock_time(time)?;
|
||||
if clock != chrono::NaiveTime::MIN || !fraction.is_empty() {
|
||||
out.push(' ');
|
||||
out.push_str(&hh_mm((clock, fraction)));
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A clock time `hh:mm[:ss[.s…]]` with an optional `Z` or `±hh:mm` zone (one, not both), which is
|
||||
/// left out. The seconds' fraction comes back as its digits as written, trailing zeros dropped,
|
||||
/// so a fraction finer than a nanosecond is kept.
|
||||
fn clock_time(t: &str) -> Option<(chrono::NaiveTime, String)> {
|
||||
let t = match (t.strip_suffix('Z'), t.rfind(['+', '-'])) {
|
||||
(Some(t), _) => t,
|
||||
(None, Some(i)) => {
|
||||
zone_offset(t.get(i + 1..)?)?;
|
||||
t.get(..i)?
|
||||
}
|
||||
(None, None) => t,
|
||||
};
|
||||
let (clock, fraction) = match t.split_once('.') {
|
||||
// A fraction needs whole seconds before it.
|
||||
Some((t, frac)) => {
|
||||
if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
(chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").ok()?, frac.trim_end_matches('0'))
|
||||
}
|
||||
None => (chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").or_else(|_| chrono::NaiveTime::parse_from_str(t, "%H:%M")).ok()?, ""),
|
||||
};
|
||||
// A leap second (`23:59:60`) is not a time a cell holds.
|
||||
(chrono::Timelike::nanosecond(&clock) < 1_000_000_000).then(|| (clock, fraction.to_string()))
|
||||
}
|
||||
|
||||
/// A zone offset's `hh:mm`, two digits each and at most `14:00` as XML Schema allows.
|
||||
fn zone_offset(z: &str) -> Option<()> {
|
||||
use chrono::Timelike;
|
||||
let two_digit = z.len() == 5 && z.bytes().enumerate().all(|(i, b)| if i == 2 { b == b':' } else { b.is_ascii_digit() });
|
||||
if !two_digit {
|
||||
return None;
|
||||
}
|
||||
let z = chrono::NaiveTime::parse_from_str(z, "%H:%M").ok()?;
|
||||
(z.hour() < 14 || (z.hour() == 14 && z.minute() == 0)).then_some(())
|
||||
}
|
||||
|
||||
/// `hh:mm`, with `:ss` when the seconds aren't zero and their fraction when it isn't.
|
||||
fn hh_mm((t, fraction): (chrono::NaiveTime, String)) -> String {
|
||||
use chrono::Timelike;
|
||||
let (h, m, s) = (t.hour(), t.minute(), t.second());
|
||||
if !fraction.is_empty() {
|
||||
format!("{h:02}:{m:02}:{s:02}.{fraction}")
|
||||
} else if s == 0 {
|
||||
format!("{h:02}:{m:02}")
|
||||
} else {
|
||||
format!("{h:02}:{m:02}:{s:02}")
|
||||
}
|
||||
}
|
||||
|
||||
/// An ISO 8601 duration (`PT13H45M00S`, `P1DT2H`, `-PT1H`) or clock time (`13:45[:00]`) as
|
||||
/// `hh:mm[:ss]`, a duration's days counted as hours and a negative one with a leading `-`.
|
||||
/// `None` for anything else, years and months included.
|
||||
fn iso_time(v: &str) -> Option<String> {
|
||||
let t = v.trim();
|
||||
let (negative, t) = match t.strip_prefix('-') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, t),
|
||||
};
|
||||
let Some(t) = t.strip_prefix('P') else {
|
||||
return if negative { None } else { clock_time(t).map(hh_mm) };
|
||||
};
|
||||
let (days, t, has_t) = match t.split_once('T') {
|
||||
Some((days, time)) => (days, time, true),
|
||||
None => (t, "", false),
|
||||
};
|
||||
// A `T` needs a time after it.
|
||||
if has_t && t.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut any = !days.is_empty();
|
||||
let days: u64 = if days.is_empty() { 0 } else { days.strip_suffix('D')?.parse().ok()? };
|
||||
let (mut h, mut m, mut s) = (0u64, 0u64, 0u64);
|
||||
// The seconds' fraction digits, kept as written.
|
||||
let mut fraction = String::new();
|
||||
let mut num = String::new();
|
||||
// Units come in the order H, M, S, each at most once.
|
||||
let mut next_unit = 0;
|
||||
for c in t.chars() {
|
||||
let unit = match c {
|
||||
'H' => 1,
|
||||
'M' => 2,
|
||||
'S' => 3,
|
||||
'0'..='9' | '.' if num.len() < 20 => {
|
||||
num.push(c);
|
||||
continue;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
if unit <= next_unit {
|
||||
return None;
|
||||
}
|
||||
next_unit = unit;
|
||||
let n = std::mem::take(&mut num);
|
||||
match unit {
|
||||
1 => h = n.parse().ok()?,
|
||||
2 => m = n.parse().ok()?,
|
||||
_ => {
|
||||
let (whole, frac) = n.split_once('.').unwrap_or((&n, ""));
|
||||
if whole.is_empty() || (n.contains('.') && frac.is_empty()) || !frac.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
s = whole.parse().ok()?;
|
||||
fraction = frac.trim_end_matches('0').to_string();
|
||||
}
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
if !any || !num.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// A duration too long to count in hours is not a time.
|
||||
m = m.checked_add(s / 60)?;
|
||||
s %= 60;
|
||||
h = h.checked_add(m / 60)?.checked_add(days.checked_mul(24)?)?;
|
||||
m %= 60;
|
||||
let sign = if negative && ((h, m, s) != (0, 0, 0) || !fraction.is_empty()) { "-" } else { "" };
|
||||
Some(if !fraction.is_empty() {
|
||||
format!("{sign}{h:02}:{m:02}:{s:02}.{fraction}")
|
||||
} else if s == 0 {
|
||||
format!("{sign}{h:02}:{m:02}")
|
||||
} else {
|
||||
format!("{sign}{h:02}:{m:02}:{s:02}")
|
||||
})
|
||||
}
|
||||
|
||||
fn cells_to_rows<C>(cells: &BTreeMap<CellRef, C>, fmt: impl Fn(&C) -> String) -> Vec<Vec<String>> {
|
||||
let mut grid: BTreeMap<(u32, u32), String> = BTreeMap::new();
|
||||
for (r, c) in cells {
|
||||
@@ -381,158 +208,3 @@ fn grid_to_rows(grid: &BTreeMap<(u32, u32), String>) -> Vec<Vec<String>> {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An `.ods` package whose body is `tables` (`table:table` elements).
|
||||
fn spreadsheet(tables: &str) -> Result<Vec<u8>, craft_odf::Error> {
|
||||
let content = format!(
|
||||
r#"<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet>{tables}</office:spreadsheet></office:body></office:document-content>"#
|
||||
);
|
||||
let mut w = craft_odf::PackageWriter::new(craft_odf::mime::SPREADSHEET);
|
||||
w.file("content.xml", "text/xml", content.as_bytes());
|
||||
w.finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_cells_read_their_typed_values() {
|
||||
let book = spreadsheet(
|
||||
r#"<table:table table:name="Guests">
|
||||
<table:table-row><table:table-cell office:value-type="string"><text:p>Name</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="string"><text:p>When</text:p></table:table-cell><table:table-cell office:value-type="string" table:number-columns-repeated="2"><text:p>Tag</text:p></table:table-cell></table:table-row>
|
||||
<table:table-row table:number-rows-repeated="2"><table:table-cell office:value-type="string" table:number-columns-spanned="2"><text:p>Ada<text:s text:c="2"/>L</text:p><text:p>x</text:p><office:annotation><text:p>note</text:p></office:annotation></table:table-cell><table:covered-table-cell office:value-type="string"><text:p>hidden</text:p></table:covered-table-cell><table:table-cell office:value-type="float" office:value="3.50"><text:p>3,5</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T00:00:00"><text:p>05/03/24</text:p></table:table-cell><table:table-cell office:value-type="boolean" office:boolean-value="false"><text:p>NO</text:p></table:table-cell><table:table-cell office:value-type="time" office:time-value="PT13H45M00S"><text:p>01:45 PM</text:p></table:table-cell></table:table-row>
|
||||
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:30"><text:p>Tue</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="not a date"><text:p>someday</text:p></table:table-cell><table:table-cell office:value-type="percentage" office:value="0.25"><text:p>25%</text:p></table:table-cell><table:table-cell office:value-type="currency" office:value="9"/></table:table-row>
|
||||
</table:table>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (_, rows) = read_rows(&book, Pick::Name("Guests")).unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
assert_eq!(rows[0], ["Name", "", "", "When", "Tag", "Tag"]);
|
||||
assert_eq!(rows[1], ["Ada L\nx", "", "3.5", "2024-03-05", "FALSE", "13:45"]);
|
||||
assert_eq!(rows[1], rows[2]);
|
||||
assert_eq!(rows[3], ["2024-03-05 13:45:30", "someday", "25%", "9"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ods_date_with_two_zones_reads_its_text() {
|
||||
let book = spreadsheet(
|
||||
r#"<table:table table:name="Dates">
|
||||
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00Z"><text:p>offset then Z</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00Z+02:00"><text:p>Z then offset</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00"><text:p>one zone</text:p></table:table-cell></table:table-row>
|
||||
</table:table>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (_, rows) = read_rows(&book, Pick::Name("Dates")).unwrap();
|
||||
assert_eq!(rows, [["offset then Z", "Z then offset", "2024-03-05 13:45"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_dates_and_durations() {
|
||||
assert_eq!(iso_time("PT1H59M59.6S").as_deref(), Some("01:59:59.6"));
|
||||
assert_eq!(iso_time("PT0.25S").as_deref(), Some("00:00:00.25"));
|
||||
assert_eq!(iso_time("PT59M60.50S").as_deref(), Some("01:00:00.5"));
|
||||
assert_eq!(iso_time("PT0H0M59S").as_deref(), Some("00:00:59"));
|
||||
assert_eq!(iso_time("PT1H2M3S").as_deref(), Some("01:02:03"));
|
||||
assert_eq!(iso_time("PT1.S"), None);
|
||||
assert_eq!(iso_time("P1000000000000000000D"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_time_keeps_its_seconds_fraction_as_written() {
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.0000000001").as_deref(), Some("2024-03-05 00:00:00.0000000001"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:30.1234567891Z").as_deref(), Some("2024-03-05 13:45:30.1234567891"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:30.500+02:00").as_deref(), Some("2024-03-05 13:45:30.5"));
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_time("13:45:00.1234567891").as_deref(), Some("13:45:00.1234567891"));
|
||||
assert_eq!(iso_time("PT13H45M0.1234567891S").as_deref(), Some("13:45:00.1234567891"));
|
||||
assert_eq!(iso_time("13:45:00."), None);
|
||||
assert_eq!(iso_time("13:45:00.5x"), None);
|
||||
assert_eq!(iso_time("13:45.5"), None);
|
||||
assert_eq!(iso_time("23:59:60.5"), None);
|
||||
assert_eq!(iso_time("13: 45.5"), None);
|
||||
assert_eq!(iso_time("1:45:30.5").as_deref(), Some("01:45:30.5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_ods_value_keeps_to_the_cell_limit() {
|
||||
let long = format!("2024-03-05T13:45:30.{}", "1".repeat(MAX_CELL_CHARS));
|
||||
let book = spreadsheet(&format!(
|
||||
r#"<table:table table:name="Long"><table:table-row><table:table-cell office:value-type="date" office:date-value="{long}"><text:p>x</text:p></table:table-cell></table:table-row></table:table>"#
|
||||
))
|
||||
.unwrap();
|
||||
let (_, rows) = read_rows(&book, Pick::Name("Long")).unwrap();
|
||||
assert_eq!(rows[0][0].chars().count(), MAX_CELL_CHARS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_date_alone_drops_its_zone() {
|
||||
assert_eq!(iso_datetime("2024-03-05Z").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05+02:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05-05:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05+02:99"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_is_at_most_fourteen_hours() {
|
||||
assert_eq!(iso_datetime("2024-03-05+14:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05-14:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05+14:01"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05-15:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:00").as_deref(), Some("2024-03-05 13:45"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:01"), None);
|
||||
assert_eq!(iso_time("13:45:00-15:00"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_is_z_or_an_offset_not_both() {
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+02:00Z"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00Z+02:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05+02:00Z"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05Z+02:00"), None);
|
||||
assert_eq!(iso_time("13:45:00+02:00Z"), None);
|
||||
assert_eq!(iso_time("13:45:00Z+02:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00Z").as_deref(), Some("2024-03-05 13:45"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00-05:00").as_deref(), Some("2024-03-05 13:45"));
|
||||
assert_eq!(iso_time("13:45:00+02:00").as_deref(), Some("13:45"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_offset_has_two_digit_hours_and_minutes() {
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+2:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+ 2:00"), None);
|
||||
assert_eq!(iso_time("13:45:00-5:00"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leap_second_is_not_a_time() {
|
||||
assert_eq!(iso_datetime("2024-03-05T23:59:60Z"), None);
|
||||
assert_eq!(iso_time("23:59:60"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_duration_with_t_needs_a_time() {
|
||||
assert_eq!(iso_time("P1DT"), None);
|
||||
assert_eq!(iso_time("P0DT"), None);
|
||||
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
|
||||
assert_eq!(iso_time("PT.S"), None);
|
||||
assert_eq!(iso_time("13:45:00Z").as_deref(), Some("13:45"));
|
||||
assert_eq!(iso_time("-PT1H").as_deref(), Some("-01:00"));
|
||||
assert_eq!(iso_time("P2DT1H30M").as_deref(), Some("49:30"));
|
||||
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
|
||||
assert_eq!(iso_time("P1Y2M"), None);
|
||||
assert_eq!(iso_time("PT"), None);
|
||||
assert_eq!(iso_time("PT5"), None);
|
||||
assert_eq!(iso_time("PT1H2H"), None);
|
||||
assert_eq!(iso_time("PT1S2H"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.500").as_deref(), Some("2024-03-05 00:00:00.5"));
|
||||
assert_eq!(iso_time("00:00:00.250").as_deref(), Some("00:00:00.25"));
|
||||
assert_eq!(iso_time("25:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:30+02:00").as_deref(), Some("2024-03-05 13:45:30"));
|
||||
assert_eq!(iso_datetime("2024-13-05"), None);
|
||||
assert_eq!(iso_datetime("2023-02-29"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05junk"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:99"), None);
|
||||
}
|
||||
}
|
||||
|
||||
+14
-65
@@ -330,14 +330,6 @@ fn rtf_round_trip() {
|
||||
assert_eq!(back.core.creator, "Ada Writer");
|
||||
}
|
||||
|
||||
/// A file the format cannot read is an error, not a blank document: the reader says what it
|
||||
/// could not read, so the caller can say so too.
|
||||
#[test]
|
||||
fn a_format_that_cannot_be_read_is_an_error_not_a_blank_document() {
|
||||
let e = import("rtf", b"not an RTF document").unwrap().unwrap_err();
|
||||
assert!(e.contains("RTF"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odt_round_trip() {
|
||||
check_round_trip("odt", true);
|
||||
@@ -350,47 +342,6 @@ fn odt_round_trip() {
|
||||
assert_eq!(back.core.creator, "Ada Writer");
|
||||
}
|
||||
|
||||
/// A flat ODT on A4 with a header and a footer, their bands' minimum heights (`fo:min-height`)
|
||||
/// stated, and two body paragraphs.
|
||||
fn flat_odt_with_bands(header: &str, footer: &str) -> Vec<u8> {
|
||||
format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
|
||||
<office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="21cm" fo:page-height="29.7cm" fo:margin-top="2cm" fo:margin-bottom="1.5cm" fo:margin-left="2cm" fo:margin-right="2cm"/><style:header-style><style:header-footer-properties fo:min-height="{header}" fo:margin-bottom="0.25cm"/></style:header-style><style:footer-style><style:header-footer-properties fo:min-height="{footer}" fo:margin-top="0.5cm"/></style:footer-style></style:page-layout></office:automatic-styles>
|
||||
<office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"><style:header><text:p>H</text:p></style:header><style:footer><text:p>F</text:p></style:footer></style:master-page></office:master-styles>
|
||||
<office:body><office:text><text:p>a</text:p><text:p>b</text:p></office:text></office:body>
|
||||
</office:document>"#
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_band_as_tall_as_the_page_leaves_the_text_room() {
|
||||
// #5806: a header's min-height raised to the page height (to fit a full-page picture) made the
|
||||
// text's top margin the page's bottom edge, so each page drew one line off the paper and the
|
||||
// rest of the text was lost. The bands grow the margins only while the text keeps half an
|
||||
// inch, as Page Setup's margins must.
|
||||
let cm = |v: f32| v * 72.0 / 2.54;
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 0.05;
|
||||
let room = |header: &str, footer: &str| {
|
||||
let doc = import("fodt", &flat_odt_with_bands(header, footer)).unwrap().unwrap();
|
||||
let s = doc.last_section.clone();
|
||||
(s.page_h - s.margin_top - s.margin_bottom, s)
|
||||
};
|
||||
let (left, s) = room("29.7cm", "1cm");
|
||||
assert!(left >= 36.0 - 0.05, "text room {left}: {s:?}");
|
||||
// The header still starts at the page margin; the text right after as much band as fits.
|
||||
assert!(near(s.header, cm(2.0)) && near(s.margin_top, s.page_h - cm(3.0) - 36.0), "{s:?}");
|
||||
// A footer as tall as the page leaves it too, and so do both at once.
|
||||
let (left, s) = room("0.5cm", "29.7cm");
|
||||
assert!(left >= 36.0 - 0.05 && near(s.margin_top, cm(2.75)), "text room {left}: {s:?}");
|
||||
let (left, s) = room("29.7cm", "29.7cm");
|
||||
assert!(left >= 36.0 - 0.05, "text room {left}: {s:?}");
|
||||
// Bands that fit are as stated.
|
||||
let (_, s) = room("0.5cm", "1cm");
|
||||
assert!(near(s.margin_top, cm(2.75)) && near(s.margin_bottom, cm(3.0)), "{s:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latex_round_trip() {
|
||||
check_round_trip("tex", true);
|
||||
@@ -607,7 +558,7 @@ fn latex_export_carries_no_commands_from_the_document() {
|
||||
assert_eq!(crate::latex::linear_to_latex("\\alpha+\\sin x+\\mathbb R"), "\\alpha+\\sin x+\\mathbb R");
|
||||
assert_eq!(crate::latex::linear_to_latex("x^2^3"), "x^2^3");
|
||||
// The same through a whole file, and for a bookmark name.
|
||||
let d = crate::latex::import("Text $\\input secret.txt $ and \\hypertarget{^^5cinput secret.txt ^^5c}{here}.".as_bytes()).unwrap();
|
||||
let d = crate::latex::import("Text $\\input secret.txt $ and \\hypertarget{^^5cinput secret.txt ^^5c}{here}.".as_bytes());
|
||||
let out = String::from_utf8(export("tex", &d).unwrap().unwrap()).unwrap();
|
||||
assert!(!out.contains("\\input") && !out.contains("^^"), "{out}");
|
||||
}
|
||||
@@ -620,11 +571,11 @@ fn latex_export_carries_no_commands_from_the_document() {
|
||||
fn latex_labels_in_a_row_are_read_in_linear_time() {
|
||||
let started = std::time::Instant::now();
|
||||
for src in ["\\label{a} ".repeat(100_000) + "x", "\\label{a}".repeat(100_000) + "x", "\\hypertarget{a}{} ".repeat(100_000)] {
|
||||
let d = crate::latex::import(src.as_bytes()).unwrap();
|
||||
let d = crate::latex::import(src.as_bytes());
|
||||
assert!(d.body.len() <= 2);
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
|
||||
let d = crate::latex::import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()).unwrap();
|
||||
let d = crate::latex::import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes());
|
||||
let p = d.para_at(&wordcraft_doc::Pos::body(0, 0)).unwrap();
|
||||
let names: Vec<&str> = p
|
||||
.objects
|
||||
@@ -741,8 +692,7 @@ fn html_img_sources_go_through_the_loader() {
|
||||
let d = crate::html::import_with(html, &|src| {
|
||||
seen.borrow_mut().push(src.to_string());
|
||||
(src == "logo.png").then(|| std::sync::Arc::new(pic.clone()))
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
assert_eq!(*seen.borrow(), ["logo.png", "gone.png"]);
|
||||
assert_eq!(d.media.len(), 1);
|
||||
let text = d.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
@@ -1130,7 +1080,7 @@ fn hidden_drawings_are_left_out_of_exports() {
|
||||
d.insert_object(&wordcraft_doc::Pos::body(0, 0), image, &Default::default()).unwrap();
|
||||
}
|
||||
// Two pictures, one hidden: one comes out.
|
||||
assert_eq!(crate::html::export(&d).unwrap().matches("<img").count(), 1);
|
||||
assert_eq!(crate::html::export(&d).matches("<img").count(), 1);
|
||||
}
|
||||
|
||||
/// Every text span of the flow, with its formatting.
|
||||
@@ -1218,17 +1168,16 @@ fn dropped_names_and_links_are_logged_once_per_document() {
|
||||
let count = |w: &[String], what: &str| w.iter().filter(|l| l.contains(what)).count();
|
||||
for _ in 0..2 {
|
||||
// Each import is its own document: the second is reported too.
|
||||
let (doc, warned) = crate::test_log::warnings(|| crate::html::import(&html).unwrap());
|
||||
let (doc, warned) = crate::test_log::warnings(|| crate::html::import(&html));
|
||||
assert!(doc.body.len() == 1, "the text is kept");
|
||||
assert_eq!(count(&warned, "font names longer"), 1, "{warned:?}");
|
||||
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
|
||||
}
|
||||
let (_, warned) =
|
||||
crate::test_log::warnings(|| crate::html::import("<p><a href=\"https://e.com\" style=\"font-family:Georgia\">fine</a></p>").unwrap());
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::html::import("<p><a href=\"https://e.com\" style=\"font-family:Georgia\">fine</a></p>"));
|
||||
assert!(warned.is_empty(), "nothing left out, nothing said: {warned:?}");
|
||||
|
||||
let md = format!("[a](https://e.com/{long}) [b](https://e.com/{long})");
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::markdown::import(&md).unwrap());
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::markdown::import(&md));
|
||||
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
|
||||
|
||||
let rtf =
|
||||
@@ -1238,14 +1187,14 @@ fn dropped_names_and_links_are_logged_once_per_document() {
|
||||
assert_eq!(count(&warned, "style names longer"), 1, "{warned:?}");
|
||||
|
||||
let tex = format!("\\href{{https://e.com/{long}}}{{a}} \\url{{https://e.com/{long}}}");
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::latex::import(tex.as_bytes()).unwrap());
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::latex::import(tex.as_bytes()));
|
||||
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_title_outside_head_is_metadata_not_body() {
|
||||
for html in ["<title>T</title><p>b</p>", "<html><title>T</title><body>b</body></html>"] {
|
||||
let d = crate::html::import(html).unwrap();
|
||||
let d = crate::html::import(html);
|
||||
assert_eq!(para_texts(&d), vec!["b".to_string()], "{html}");
|
||||
assert_eq!(d.core.title, "T", "{html}");
|
||||
}
|
||||
@@ -1271,7 +1220,7 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
|
||||
r#"<div style="background-color:#1e1e1e"><p>text <code style="background-color:#eeeeee">x</code></p></div>"#,
|
||||
r#"<div style="background-color:#1e1e1e"><div>a</div><div> </div><div>b</div></div>"#,
|
||||
);
|
||||
let doc = crate::html::import(html).unwrap();
|
||||
let doc = crate::html::import(html);
|
||||
assert_eq!(doc.body.len(), 7);
|
||||
|
||||
let Block::Para(code) = &*doc.body[0] else { panic!("expected code paragraph") };
|
||||
@@ -1296,8 +1245,8 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
|
||||
assert_eq!(line.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "line {idx} (blank included) keeps container shading");
|
||||
}
|
||||
|
||||
for exported in [crate::html::export(&doc).unwrap(), crate::html::export_fragment(&doc).unwrap()] {
|
||||
let back = crate::html::import(&exported).unwrap();
|
||||
for exported in [crate::html::export(&doc), crate::html::export_fragment(&doc)] {
|
||||
let back = crate::html::import(&exported);
|
||||
let Block::Para(p0) = &*back.body[0] else { panic!("expected paragraph 0") };
|
||||
let Block::Para(p1) = &*back.body[1] else { panic!("expected paragraph 1") };
|
||||
let Block::Para(p2) = &*back.body[2] else { panic!("expected paragraph 2") };
|
||||
@@ -1316,7 +1265,7 @@ fn odt_list_item_later_paragraphs_stay_in_the_item() {
|
||||
let fodt = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text"><office:automatic-styles><text:list-style style:name="L1"><text:list-level-style-number text:level="1" style:num-format="1"/></text:list-style></office:automatic-styles><office:body><office:text><text:list text:style-name="L1"><text:list-item><text:p>One</text:p><text:p>Still one</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document>"#;
|
||||
let doc = crate::odt::import_flat(fodt.as_bytes()).unwrap();
|
||||
let html = crate::html::export(&doc).unwrap();
|
||||
let html = crate::html::export(&doc);
|
||||
assert_eq!(html.matches("<ol").count(), 1, "one list, not restarted: {html}");
|
||||
let (one, still, two) = (html.find("One").unwrap(), html.find("Still one").unwrap(), html.find("Two").unwrap());
|
||||
assert!(one < still && still < two, "{html}");
|
||||
|
||||
@@ -152,7 +152,7 @@ pub(crate) fn add(ctx: &mut Ctx, lay: &mut DocLayout) {
|
||||
author_name(&cm.author),
|
||||
CharProps { bold: Some(true), size: Some(9.0), color: Some(TextColor::Rgb(color)), ..Default::default() },
|
||||
);
|
||||
let pl = ctx.para_labelled(&head, inner, None, &[], 0.0, None);
|
||||
let pl = ctx.para_labelled(&head, inner, None, &[], None);
|
||||
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
|
||||
push_para(&mut items, (story, &[HEADER_PATH]), &pl, (0, pl.lines.len()), (x, y + lead), inner, Edges::own(&pl, 0, pl.lines.len()));
|
||||
y += pl.height + 2.0;
|
||||
|
||||
+11
-22
@@ -261,8 +261,6 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
// Word has no frames in a text box: a framed paragraph there (its style's frame, usually)
|
||||
// runs with the box's text (#2357).
|
||||
let frames = !matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox));
|
||||
// Nor in a table cell for a frame placed on the page: Word keeps its text in the cell.
|
||||
let cell_frame = |fr: &wordcraft_doc::props::TextFrame| !in_cell || fr.v_anchor == "text";
|
||||
// The bottom of the last paragraph's lines.
|
||||
let mut prev_end = 0.0f32;
|
||||
// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
|
||||
@@ -276,17 +274,17 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
Block::Para(p) => {
|
||||
// A paragraph after one whose mark is hidden goes on from that one's last line
|
||||
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
|
||||
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table, cell_frame);
|
||||
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table);
|
||||
let p = taken.as_ref().map_or(p, |t| &t.para);
|
||||
let label = ctx.next_label(p);
|
||||
let listed = label.is_some();
|
||||
let mut pl = ctx.para_labelled(p, width, table, &[], 0.0, label.clone());
|
||||
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
|
||||
// A text frame (a footer's page number in a frame, say) is placed apart, like a
|
||||
// floating object, and the text after it wraps around it; it takes no room in
|
||||
// the flow.
|
||||
if let Some(fr) = pl.rp.frame.clone().filter(|fr| frames && cell_frame(fr)) {
|
||||
if let Some(fr) = pl.rp.frame.clone().filter(|_| frames) {
|
||||
let fw = fr.w.unwrap_or_else(|| natural_width(&pl)).clamp(1.0, 1584.0);
|
||||
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], 0.0, label) } else { pl };
|
||||
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], label) } else { pl };
|
||||
let h = match fr.h {
|
||||
Some(h) if fr.h_exact => h,
|
||||
Some(h) => h.max(pf.height),
|
||||
@@ -318,8 +316,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
// body path. Keep text and wrap exclusions relative to the text's actual top.
|
||||
// A paragraph going on from a shared line has its origin at that line's top.
|
||||
let para_top = taken.as_ref().map_or(y, |t| t.joint.top);
|
||||
let applied = if i == 0 { before } else { before.max(0.0) };
|
||||
y += applied;
|
||||
y += if i == 0 { before } else { before.max(0.0) };
|
||||
TakenUp::start(taken.as_ref(), &mut y, &mut excl);
|
||||
// Floating objects anchored here: place them, then wrap the text around them.
|
||||
// One left out of the layout (hidden, or deleted in the final text) takes no room.
|
||||
@@ -365,7 +362,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
}
|
||||
let rel = rel_exclusions(&excl, 0.0, y);
|
||||
if !rel.is_empty() {
|
||||
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
|
||||
pl = ctx.para_labelled(p, width, table, &rel, label);
|
||||
}
|
||||
TakenUp::clear(taken.as_ref(), &mut excl);
|
||||
// Bordered paragraphs: room for their borders, those of a group joined in one box.
|
||||
@@ -478,7 +475,7 @@ fn natural_width(pl: &ParaLayout) -> f32 {
|
||||
}
|
||||
|
||||
/// A text frame's placement as a floating object's (`w:framePr` → anchors, alignment, wrap).
|
||||
pub(crate) fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
|
||||
fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
|
||||
let anchor = |a: &str, text: Anchor| match a {
|
||||
"page" => Anchor::Page,
|
||||
"margin" => Anchor::Margin,
|
||||
@@ -778,14 +775,13 @@ impl Joint {
|
||||
(i, p): (usize, &Paragraph),
|
||||
(width, frames): (f32, bool),
|
||||
table: Option<¶::CellText>,
|
||||
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
|
||||
) -> (bool, bool, Option<TakenUp>) {
|
||||
let chr = table.map(|t| &t.chr);
|
||||
let mark_hidden = ctx.mark_hidden(p, chr);
|
||||
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
|
||||
let came = joint.take().filter(|j| j.next == i);
|
||||
*joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
|
||||
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table, cell_frame));
|
||||
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table));
|
||||
(mark_hidden, shows_nothing, taken)
|
||||
}
|
||||
|
||||
@@ -801,7 +797,7 @@ impl Joint {
|
||||
/// taller than the text going on from it), with the room for its bottom border (Word).
|
||||
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<¶::CellText>) -> (f32, Vec<WrapArea>) {
|
||||
let eq = ctx.eq_count;
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
|
||||
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
|
||||
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
|
||||
@@ -829,16 +825,9 @@ impl Joint {
|
||||
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
|
||||
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
|
||||
/// without its space before, as [`Joint::fit`] lays it out.
|
||||
fn take_up(
|
||||
self,
|
||||
ctx: &mut Ctx,
|
||||
p: &Paragraph,
|
||||
(width, frames): (f32, bool),
|
||||
table: Option<¶::CellText>,
|
||||
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
|
||||
) -> Option<TakenUp> {
|
||||
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<¶::CellText>) -> Option<TakenUp> {
|
||||
let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para));
|
||||
if own.page_break_before || own.bidi || own.frame.as_ref().is_some_and(|fr| frames && cell_frame(fr)) {
|
||||
if own.page_break_before || own.bidi || (frames && own.frame.is_some()) {
|
||||
return None;
|
||||
}
|
||||
let mut para = p.clone();
|
||||
|
||||
@@ -16,9 +16,6 @@ pub(crate) struct Key {
|
||||
pub(crate) table: u64,
|
||||
pub(crate) notes: u64,
|
||||
pub(crate) excl: u64,
|
||||
/// The space before the paragraph layout applied above it, which a Top-and-Bottom object in
|
||||
/// it is laid out again below ([`para::ParaEnv::space_before`]).
|
||||
pub(crate) space_before: u32,
|
||||
pub(crate) eq: u32,
|
||||
pub(crate) read_spacing: Option<u32>,
|
||||
pub(crate) grid: (u32, u32, u32, bool),
|
||||
@@ -35,14 +32,6 @@ pub(crate) struct Key {
|
||||
pub(crate) joined: Option<(u32, bool)>,
|
||||
}
|
||||
|
||||
pub(crate) struct StylesEnv {
|
||||
styles: std::sync::Weak<wordcraft_doc::styles::StyleSheet>,
|
||||
numbering: std::sync::Weak<wordcraft_doc::numbering::Numbering>,
|
||||
default_tab: u32,
|
||||
footnote_format: wordcraft_doc::section::NumFormat,
|
||||
hash: u64,
|
||||
}
|
||||
|
||||
/// Memoised paragraph layouts.
|
||||
#[derive(Default)]
|
||||
pub struct LayoutCache {
|
||||
@@ -55,7 +44,6 @@ pub struct LayoutCache {
|
||||
/// kept, so no other picture's bytes can come to have its address ([`Outlines`]).
|
||||
pub(crate) outlines: Outlines,
|
||||
pub(crate) env: u64,
|
||||
pub(crate) styles_env: Option<StylesEnv>,
|
||||
pub(crate) used: HashSet<Key>,
|
||||
/// The STYLEREF style index of the last pass and what it was built from: the body blocks
|
||||
/// (shared, so an edited block is a different pointer) and `env` (styles and numbering). Kept
|
||||
@@ -79,7 +67,6 @@ impl LayoutCache {
|
||||
self.paras.clear();
|
||||
self.measures.clear();
|
||||
self.outlines.clear();
|
||||
self.styles_env = None;
|
||||
self.styleref = None;
|
||||
}
|
||||
|
||||
@@ -104,56 +91,12 @@ pub(crate) fn hash_of<T: Hash>(t: &T) -> u64 {
|
||||
h.finish()
|
||||
}
|
||||
|
||||
struct HashWriter<'a>(&'a mut std::collections::hash_map::DefaultHasher);
|
||||
|
||||
impl std::io::Write for HashWriter<'_> {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.write(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Fingerprint of stylesheet, numbering, default tab, and footnote format, memoised on
|
||||
/// [`LayoutCache::styles_env`] via `Weak` pointers so unchanged passes skip JSON serialisation.
|
||||
/// Holding live `Weak` references keeps the underlying `ArcInner` allocations reserved, ensuring a
|
||||
/// fresh `Arc` allocation cannot reuse a still-cached address.
|
||||
fn styles_env_hash(doc: &Document, cache: &mut LayoutCache) -> u64 {
|
||||
let tab = doc.settings.default_tab.to_bits();
|
||||
if let Some(cached) = &cache.styles_env
|
||||
&& cached.styles.as_ptr() == Arc::as_ptr(&doc.styles)
|
||||
&& cached.styles.strong_count() > 0
|
||||
&& cached.numbering.as_ptr() == Arc::as_ptr(&doc.numbering)
|
||||
&& cached.numbering.strong_count() > 0
|
||||
&& cached.default_tab == tab
|
||||
&& cached.footnote_format == doc.settings.footnote_format
|
||||
{
|
||||
return cached.hash;
|
||||
}
|
||||
let mut sh = std::collections::hash_map::DefaultHasher::new();
|
||||
let _ = serde_json::to_writer(HashWriter(&mut sh), &(&doc.styles, &doc.numbering, doc.settings.default_tab, &doc.settings.footnote_format));
|
||||
let hash = sh.finish();
|
||||
cache.styles_env = Some(StylesEnv {
|
||||
styles: Arc::downgrade(&doc.styles),
|
||||
numbering: Arc::downgrade(&doc.numbering),
|
||||
default_tab: tab,
|
||||
footnote_format: doc.settings.footnote_format,
|
||||
hash,
|
||||
});
|
||||
hash
|
||||
}
|
||||
|
||||
pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) -> u64 {
|
||||
let styles = styles_env_hash(doc, cache);
|
||||
pub(crate) fn env_hash(doc: &Document, opts: &LayoutOptions) -> u64 {
|
||||
let s = serde_json::to_string(&(&doc.styles, &doc.numbering, doc.settings.default_tab, &doc.settings.footnote_format)).unwrap_or_default();
|
||||
// Outline view lays paragraphs out changed (no indents; plain without text formatting).
|
||||
let outline = (opts.view == ViewMode::Outline).then(|| opts.outline.as_ref().is_some_and(|o| o.plain));
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
styles.hash(&mut h);
|
||||
// The compatibility mode changes paragraph layout too (widow control in table cells).
|
||||
doc.settings.compat_mode.hash(&mut h);
|
||||
s.hash(&mut h);
|
||||
opts.show_hidden.hash(&mut h);
|
||||
opts.hide_deleted.hash(&mut h);
|
||||
opts.hide_marked.hash(&mut h);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user