mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-01 22:19:41 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b5bfa78bf | ||
|
|
313e14885f | ||
|
|
9a8786a3ab | ||
|
|
4b5a96163c | ||
|
|
5a68da541f | ||
|
|
7dce30c8af | ||
|
|
b4efb2fef1 | ||
|
|
30b8f025d2 | ||
|
|
27efb34a95 | ||
|
|
61c69fceca | ||
|
|
199162f96a | ||
|
|
ea7322efac | ||
|
|
3e64bba9bb | ||
|
|
5d93167fe0 | ||
|
|
6659ce4adc | ||
|
|
43632f571c | ||
|
|
0e3f5f3ea6 | ||
|
|
3c8a1eeb2d | ||
|
|
3b7779df34 | ||
|
|
e7588ff931 | ||
|
|
ba1ed225c0 | ||
|
|
36e7ee7ade | ||
|
|
b4fffa91cc | ||
|
|
5ad1c48b3e | ||
|
|
1ec6f0bb58 |
Generated
+164
-135
File diff suppressed because it is too large
Load Diff
+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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", 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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
|
||||
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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", 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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", 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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
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" }
|
||||
|
||||
|
||||
@@ -188,3 +188,34 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
Linux Wayland window decorations
|
||||
-------------------------------
|
||||
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
|
||||
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
|
||||
for vector window controls. Its title-font features are disabled: no Cantarell
|
||||
font is embedded by this dependency and no font file is added to this repo.
|
||||
|
||||
sctk-adwaita's MIT licence:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Bartłomiej Maryńczak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
+7
-2
File diff suppressed because one or more lines are too long
@@ -110,7 +110,7 @@ impl Bridge {
|
||||
fn listen(&self, intake: IntakeSender) {
|
||||
self.host.listen(move |message| {
|
||||
if let Message::Open { name, data } = message {
|
||||
deliver_open(&intake, &name, &data);
|
||||
deliver_open(&intake, name.as_deref().unwrap_or("document"), &data);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -119,7 +119,7 @@ impl Bridge {
|
||||
/// The file an open message carries, queued for the next frame like a dropped file. A host's file
|
||||
/// is untrusted input: an oversized one is refused before it is copied into the app's memory (the
|
||||
/// data's own length, not the host's claim). The crate has cleaned the name (and cut it to 255
|
||||
/// characters); a blank one comes as `document` and becomes `Document.docx`.
|
||||
/// characters); a missing one comes as `None` and becomes `Document.docx`.
|
||||
fn deliver_open(intake: &IntakeSender, name: &str, data: &FileData) {
|
||||
let name = if name == "document" { DEFAULT_NAME } else { name }.to_string();
|
||||
let FileData::Bytes(array) = data else {
|
||||
|
||||
@@ -13,14 +13,14 @@ pub fn open() -> (SharedSettings<Prefs>, craft::settings::LoadReport) {
|
||||
use std::time::Duration;
|
||||
|
||||
use craft::settings::{LegacyFile, LocalStorageFiles, Location, OpenOptions, SettingsStore};
|
||||
use wordcraft_ui_egui::prefs::legacy_ui_json;
|
||||
use wordcraft_ui_egui::prefs::legacy_ui_json_slots;
|
||||
|
||||
/// Largest stored value read back (`localStorage` holds about 5 MB per site).
|
||||
const MAX_STORED: usize = 4 << 20;
|
||||
let options = OpenOptions::new(Location::Dir("wordcraft".into()))
|
||||
.files(Arc::new(LocalStorageFiles::new(MAX_STORED)))
|
||||
.debounce(Duration::ZERO)
|
||||
.legacy(vec![LegacyFile { path: "wordcraft.ui".into(), parse: legacy_ui_json }]);
|
||||
.legacy(vec![LegacyFile { paths: vec!["wordcraft.ui".into()], parse: legacy_ui_json_slots }]);
|
||||
let (store, report) = SettingsStore::open_with(options);
|
||||
(SharedSettings::new(store), report)
|
||||
}
|
||||
|
||||
@@ -60,8 +60,14 @@ winresource = "0.1"
|
||||
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
|
||||
craft = { workspace = true, features = ["platform-apple-events", "menu"] }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts.
|
||||
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
# Check that the libraries winit's X11 backend opens are installed before choosing XWayland (see
|
||||
# `x11_libraries` in main.rs). Both are already in the build through winit's `x11` feature, at
|
||||
# these versions and with this feature.
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings, Source};
|
||||
use craft::window::restore::Store;
|
||||
use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json};
|
||||
use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json_slots};
|
||||
|
||||
/// The most of an old `ui.json` read for its window entry; the file is a few kilobytes.
|
||||
const LEGACY_LIMIT: u64 = 8 << 20;
|
||||
@@ -41,7 +41,7 @@ fn open_in(dir: Option<PathBuf>, placement: &mut Store) -> (SharedSettings<Prefs
|
||||
None => OpenOptions::new(Location::Memory),
|
||||
};
|
||||
if let Some(dir) = &dir {
|
||||
options = options.legacy(vec![LegacyFile { path: dir.join("ui.json"), parse: legacy_ui_json }]);
|
||||
options = options.legacy(vec![LegacyFile { paths: vec![dir.join("ui.json")], parse: legacy_ui_json_slots }]);
|
||||
}
|
||||
let (store, report) = SettingsStore::<Prefs>::open_with(options);
|
||||
if let Source::Legacy(path) = &report.source {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Integration test for Linux Wayland client-side window decoration controls (#5814, #5375).
|
||||
//!
|
||||
//! Ensures that on Linux, client-side window controls use font-free Adwaita vector paths
|
||||
//! so the close button is rendered as a clean vector cross rather than a square fallback,
|
||||
//! and that sctk-adwaita has proper license attribution in NOTICE without bundling font files.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// Strips an unquoted TOML `#` comment from a single line.
|
||||
fn strip_toml_comment(line: &str) -> &str {
|
||||
let mut in_double = false;
|
||||
let mut in_single = false;
|
||||
for (idx, ch) in line.char_indices() {
|
||||
match ch {
|
||||
'"' if !in_single => in_double = !in_double,
|
||||
'\'' if !in_double => in_single = !in_single,
|
||||
'#' if !in_double && !in_single => return &line[..idx],
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// Extracts the comment-stripped body of a TOML table section by exact `[header]`.
|
||||
fn toml_section(content: &str, header: &str) -> String {
|
||||
let mut in_section = false;
|
||||
let mut out = String::new();
|
||||
for raw_line in content.lines() {
|
||||
let line = strip_toml_comment(raw_line).trim();
|
||||
if line.starts_with('[') && line.ends_with(']') {
|
||||
if in_section {
|
||||
break;
|
||||
}
|
||||
in_section = line == header;
|
||||
continue;
|
||||
}
|
||||
if in_section && !line.is_empty() {
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
assert!(in_section, "expected target section {header} in apps/wordcraft/Cargo.toml");
|
||||
out
|
||||
}
|
||||
|
||||
/// Parses the `features = [...]` string array from the `winit = { ... }` dependency entry in a TOML section.
|
||||
fn winit_features(section: &str) -> Vec<&str> {
|
||||
let winit_start = section.find("winit").expect("target section must declare a winit dependency");
|
||||
let after_winit = §ion[winit_start..];
|
||||
let table_end = after_winit.find('}').expect("winit inline table must close with '}'");
|
||||
let winit_table = &after_winit[..=table_end];
|
||||
let features_start = winit_table.find("features").expect("winit dependency must declare features");
|
||||
let after_features = &winit_table[features_start..];
|
||||
let open_bracket = after_features.find('[').expect("winit features must open with '['");
|
||||
let after_open = &after_features[open_bracket + 1..];
|
||||
let close_bracket = after_open.find(']').expect("winit features must close with ']'");
|
||||
let array_body = &after_open[..close_bracket];
|
||||
array_body.split(',').map(|item| item.trim().trim_matches('"')).filter(|item| !item.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// Verifies that `apps/wordcraft/Cargo.toml` enables `wayland-csd-adwaita-notitle` for Linux.
|
||||
#[test]
|
||||
fn linux_manifest_enables_wayland_csd_adwaita_notitle() {
|
||||
let cargo_toml = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
|
||||
let content = std::fs::read_to_string(&cargo_toml).expect("read apps/wordcraft/Cargo.toml");
|
||||
|
||||
let linux_section = toml_section(&content, "[target.'cfg(target_os = \"linux\")'.dependencies]");
|
||||
let linux_features = winit_features(&linux_section);
|
||||
assert!(
|
||||
linux_features.contains(&"x11") && linux_features.contains(&"wayland-csd-adwaita-notitle"),
|
||||
"Linux winit dependency must enable x11 and wayland-csd-adwaita-notitle, got: {linux_features:?}"
|
||||
);
|
||||
|
||||
let other_unix_section = toml_section(&content, "[target.'cfg(all(unix, not(any(target_os = \"macos\", target_os = \"linux\"))))'.dependencies]");
|
||||
let other_unix_features = winit_features(&other_unix_section);
|
||||
assert!(
|
||||
other_unix_features.contains(&"x11") && !other_unix_features.contains(&"wayland-csd-adwaita-notitle"),
|
||||
"Non-Linux Unix winit dependency must enable x11 without wayland-csd-adwaita-notitle, got: {other_unix_features:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Verifies that `NOTICE` documents sctk-adwaita and its MIT licence.
|
||||
#[test]
|
||||
fn notice_documents_sctk_adwaita_attribution() {
|
||||
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
|
||||
let notice = std::fs::read_to_string(workspace_root.join("NOTICE")).expect("read NOTICE");
|
||||
assert!(notice.contains("Linux Wayland window decorations"), "NOTICE must include 'Linux Wayland window decorations'");
|
||||
assert!(notice.contains("sctk-adwaita"), "NOTICE must document sctk-adwaita");
|
||||
assert!(notice.contains("Bartłomiej Maryńczak"), "NOTICE must retain sctk-adwaita's author copyright");
|
||||
}
|
||||
|
||||
/// Parses `[[package]]` entries from `Cargo.lock` as `(name, version, dependencies)`.
|
||||
fn parse_lockfile_packages(lockfile: &str) -> Vec<(&str, &str, Vec<&str>)> {
|
||||
lockfile
|
||||
.split("[[package]]")
|
||||
.skip(1)
|
||||
.filter_map(|chunk| {
|
||||
let mut name = None;
|
||||
let mut version = None;
|
||||
let mut deps = Vec::new();
|
||||
let mut in_deps = false;
|
||||
for raw_line in chunk.lines() {
|
||||
let line = raw_line.trim();
|
||||
if in_deps {
|
||||
if line == "]" {
|
||||
in_deps = false;
|
||||
continue;
|
||||
}
|
||||
let dep = line.trim_end_matches(',').trim().trim_matches('"');
|
||||
if !dep.is_empty() {
|
||||
deps.push(dep);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("name = ") {
|
||||
name = Some(rest.trim_matches('"'));
|
||||
} else if let Some(rest) = line.strip_prefix("version = ") {
|
||||
version = Some(rest.trim_matches('"'));
|
||||
} else if line == "dependencies = [" {
|
||||
in_deps = true;
|
||||
}
|
||||
}
|
||||
Some((name?, version?, deps))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Verifies that WordCraft's resolved Linux `winit` -> `sctk-adwaita` dependency path in
|
||||
/// `Cargo.lock` does not pull in any title-font renderer crates.
|
||||
#[test]
|
||||
fn cargo_lock_contains_font_free_sctk_adwaita() {
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
|
||||
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
|
||||
let lockfile = std::fs::read_to_string(workspace_root.join("Cargo.lock")).expect("read Cargo.lock");
|
||||
let packages = parse_lockfile_packages(&lockfile);
|
||||
|
||||
let has_dep = |pkg_name: &str, target: &str| {
|
||||
packages.iter().any(|(name, _, deps)| *name == pkg_name && deps.iter().any(|spec| spec.split_whitespace().next() == Some(target)))
|
||||
};
|
||||
assert!(has_dep("winit", "sctk-adwaita"), "winit in Cargo.lock must depend on sctk-adwaita");
|
||||
|
||||
let mut queue = VecDeque::new();
|
||||
let mut visited = HashSet::new();
|
||||
for (idx, (name, _, _)) in packages.iter().enumerate() {
|
||||
if *name == "sctk-adwaita" && visited.insert(idx) {
|
||||
queue.push_back(idx);
|
||||
}
|
||||
}
|
||||
assert!(!queue.is_empty(), "Cargo.lock must include sctk-adwaita");
|
||||
|
||||
let forbidden = ["fontdue", "ab_glyph", "cosmic-text", "crossfont"];
|
||||
while let Some(idx) = queue.pop_front() {
|
||||
let (name, _, deps) = &packages[idx];
|
||||
assert!(!forbidden.contains(name), "sctk-adwaita's resolved dependency path must not include title-font renderer {name}");
|
||||
for spec in deps {
|
||||
let mut parts = spec.split_whitespace();
|
||||
let dep_name = parts.next().expect("dependency name");
|
||||
let dep_ver = parts.next();
|
||||
for (next_idx, (cand_name, cand_ver, _)) in packages.iter().enumerate() {
|
||||
if *cand_name == dep_name && dep_ver.is_none_or(|v| v == *cand_ver) && visited.insert(next_idx) {
|
||||
queue.push_back(next_idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,5 +2,7 @@
|
||||
mod appimage_env;
|
||||
mod control_arg;
|
||||
mod help;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_decorations;
|
||||
#[cfg(unix)]
|
||||
mod non_utf8_args;
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
e56d26244bbac099bfd42e23fb12f78a4be418a7
|
||||
217f4130d7d3dbb21a160f23f6b0021918906cc0
|
||||
|
||||
@@ -703,25 +703,44 @@ impl Document {
|
||||
}
|
||||
|
||||
/// A drawing id no shape uses yet (for gluing a connector to a shape that has none).
|
||||
///
|
||||
/// Returns one past the largest in-use shape id across the body, all secondary parts, and
|
||||
/// footnote/endnote separator stories (walking nested groups and tables); if `u32::MAX` is
|
||||
/// already in use, falls back via [`free_id`] to the smallest unused non-zero id (or `0` only
|
||||
/// if every non-zero `u32` id is taken).
|
||||
pub fn next_shape_id(&self) -> u32 {
|
||||
let mut max = 0u32;
|
||||
let mut largest: Option<u32> = None;
|
||||
let mut used: Vec<u32> = Vec::new();
|
||||
let mut record = |id: u32| {
|
||||
if id != 0 {
|
||||
largest = largest.max(Some(id));
|
||||
used.push(id);
|
||||
}
|
||||
};
|
||||
let mut see = |o: &InlineObject| match o {
|
||||
InlineObject::Shape { extra, .. } => max = max.max(extra.id),
|
||||
InlineObject::Shape { extra, .. } => record(extra.id),
|
||||
InlineObject::Group { children, .. } => {
|
||||
for c in children {
|
||||
if let InlineObject::Shape { extra, .. } = &c.obj {
|
||||
max = max.max(extra.id);
|
||||
let mut todo: Vec<&InlineObject> = children.iter().map(|c| &c.obj).collect();
|
||||
while let Some(obj) = todo.pop() {
|
||||
match obj {
|
||||
InlineObject::Shape { extra, .. } => record(extra.id),
|
||||
InlineObject::Group { children, .. } => todo.extend(children.iter().map(|c| &c.obj)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)) {
|
||||
let sep_stories = [&self.footnote_separators, &self.endnote_separators]
|
||||
.into_iter()
|
||||
.flat_map(|s| [&s.separator, &s.continuation_separator, &s.continuation_notice])
|
||||
.flatten();
|
||||
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)).chain(sep_stories) {
|
||||
for b in blocks {
|
||||
edit::each_para(b, 0, &mut |p| p.objects.iter().for_each(&mut see));
|
||||
}
|
||||
}
|
||||
max.saturating_add(1).max(1)
|
||||
free_id(largest, used.into_iter(), 1).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Change every inline object in every story (paragraphs inside tables too), copying only
|
||||
|
||||
@@ -291,25 +291,47 @@ impl InlineObject {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The text box stories this object shows: a text box's, or its group members'.
|
||||
/// The text box stories this object shows: a text box's, or its group members' (nested groups
|
||||
/// included, in member order).
|
||||
pub fn text_boxes(&self) -> Vec<u32> {
|
||||
match self {
|
||||
InlineObject::Shape { story: Some(id), .. } => vec![*id],
|
||||
InlineObject::Group { children, .. } => children.iter().filter_map(|c| c.obj.text_box()).collect(),
|
||||
InlineObject::Group { children, .. } => {
|
||||
let mut out = Vec::new();
|
||||
let mut todo: Vec<&InlineObject> = children.iter().rev().map(|c| &c.obj).collect();
|
||||
while let Some(obj) = todo.pop() {
|
||||
match obj {
|
||||
InlineObject::Shape { story: Some(id), .. } => out.push(*id),
|
||||
InlineObject::Group { children, .. } => {
|
||||
todo.extend(children.iter().rev().map(|c| &c.obj));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
/// The text box story slots of this object and its group members, to repoint.
|
||||
/// The text box story slots of this object and its group members (nested groups included, in
|
||||
/// member order), to repoint.
|
||||
pub fn text_box_slots(&mut self) -> Vec<&mut Option<u32>> {
|
||||
match self {
|
||||
InlineObject::Shape { story, .. } => vec![story],
|
||||
InlineObject::Group { children, .. } => children
|
||||
.iter_mut()
|
||||
.filter_map(|c| match &mut c.obj {
|
||||
InlineObject::Shape { story, .. } => Some(story),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
InlineObject::Group { children, .. } => {
|
||||
let mut out = Vec::new();
|
||||
let mut todo: Vec<&mut InlineObject> = children.iter_mut().rev().map(|c| &mut c.obj).collect();
|
||||
while let Some(obj) = todo.pop() {
|
||||
match obj {
|
||||
InlineObject::Shape { story, .. } => out.push(story),
|
||||
InlineObject::Group { children, .. } => {
|
||||
todo.extend(children.iter_mut().rev().map(|c| &mut c.obj));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,11 +42,27 @@ pub struct Revision {
|
||||
/// insertion or deletion.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub move_name: Option<String>,
|
||||
/// The change's UTC timestamp: from the file (`w16du:dateUtc`, where `date` is the local time
|
||||
/// Word writes in `w:date`), or the time WordCraft stamped the change with. `None` when the
|
||||
/// file doesn't give it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub date_utc: Option<String>,
|
||||
}
|
||||
|
||||
impl Revision {
|
||||
pub fn new(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>) -> Revision {
|
||||
Revision { kind, author: author.into(), date: date.into(), move_name: None }
|
||||
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: None }
|
||||
}
|
||||
|
||||
/// A change made here: `date` is the local wall-clock time it was made at, as Word writes
|
||||
/// `w:date`, and `date_utc` the same instant in UTC.
|
||||
pub fn made_at(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>, utc: impl Into<String>) -> Revision {
|
||||
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: Some(utc.into()) }
|
||||
}
|
||||
|
||||
/// The instant changes are grouped by: the UTC time when it is known, else `date`.
|
||||
pub fn instant(&self) -> &str {
|
||||
self.date_utc.as_deref().unwrap_or(&self.date)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -440,6 +440,116 @@ fn prune_text_boxes_drops_only_unshown_ones() {
|
||||
assert_eq!(d.prune_text_boxes(), 0);
|
||||
}
|
||||
|
||||
/// A text-box shape (`story: Some(id)`) or plain shape (`story: None`) for nested-group tests.
|
||||
fn test_shape(story: Option<u32>) -> InlineObject {
|
||||
InlineObject::Shape {
|
||||
kind: para::ShapeKind::TextBox,
|
||||
w: 50.0,
|
||||
h: 20.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A group holding `children`.
|
||||
fn test_group(children: Vec<InlineObject>) -> InlineObject {
|
||||
InlineObject::Group {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
float: Default::default(),
|
||||
ch_w: 100.0,
|
||||
ch_h: 100.0,
|
||||
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
|
||||
canvas: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `obj` wrapped inside `levels` nested [`InlineObject::Group`]s.
|
||||
fn nested_group(levels: usize, obj: InlineObject) -> InlineObject {
|
||||
(0..levels).fold(obj, |inner, _| test_group(vec![inner]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_group_text_boxes_are_collected_and_slots_repointed_in_order() {
|
||||
let mut outer = test_group(vec![
|
||||
test_shape(Some(1)),
|
||||
test_shape(None),
|
||||
nested_group(1, test_shape(Some(2))), // depth 2 from outer
|
||||
test_group(vec![nested_group(1, test_shape(Some(3))), test_shape(Some(4))]), // depth 3 and depth 2
|
||||
nested_group(39, test_shape(Some(5))), // depth 40 from outer
|
||||
]);
|
||||
assert_eq!(outer.text_boxes(), vec![1, 2, 3, 4, 5]);
|
||||
let slots = outer.text_box_slots();
|
||||
assert_eq!(slots.len(), 6);
|
||||
for id in slots.into_iter().flatten() {
|
||||
*id += 100;
|
||||
}
|
||||
assert_eq!(outer.text_boxes(), vec![101, 102, 103, 104, 105]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_text_boxes_keeps_nested_group_boxes_and_drops_unreachable() {
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let mut d = Document::from_text("body");
|
||||
let depth2 = d.add_part(PartKind::TextBox, para_of("depth 2"));
|
||||
let depth3 = d.add_part(PartKind::TextBox, para_of("depth 3"));
|
||||
let deep = d.add_part(PartKind::TextBox, para_of("depth 40"));
|
||||
let linked_live = d.add_part(PartKind::TextBox, para_of("linked follower"));
|
||||
let orphan = d.add_part(PartKind::TextBox, para_of("unreachable"));
|
||||
let orphan_nested = d.add_part(PartKind::TextBox, para_of("inside unreachable"));
|
||||
|
||||
// Live link between two nested-group boxes and a dangling link to an unreachable box.
|
||||
d.parts.get_mut(&depth2).unwrap().body.next = Some(linked_live);
|
||||
d.parts.get_mut(&depth3).unwrap().body.next = Some(orphan);
|
||||
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(depth2))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(3, test_shape(Some(depth3))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(40, test_shape(Some(deep))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(linked_live))), &CharProps::default()).unwrap();
|
||||
let at_orphan = Pos { story: StoryRef::Part(orphan), path: Path::top(0), off: 0 };
|
||||
d.insert_object(&at_orphan, nested_group(2, test_shape(Some(orphan_nested))), &CharProps::default()).unwrap();
|
||||
|
||||
assert_eq!(d.prune_text_boxes(), 2);
|
||||
let kept: Vec<u32> = d.parts.keys().copied().collect();
|
||||
assert_eq!(kept, vec![depth2, depth3, deep, linked_live]);
|
||||
assert_eq!(d.plain_text(StoryRef::Part(depth2)), "depth 2");
|
||||
assert_eq!(d.plain_text(StoryRef::Part(depth3)), "depth 3");
|
||||
assert_eq!(d.plain_text(StoryRef::Part(deep)), "depth 40");
|
||||
assert_eq!(d.parts.get(&depth2).unwrap().body.next, Some(linked_live), "live chain link stays");
|
||||
assert_eq!(d.parts.get(&depth3).unwrap().body.next, None, "dangling chain link is cleared");
|
||||
assert_eq!(d.prune_text_boxes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_text_boxes_terminates_on_cyclic_nested_group_stories() {
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let mut d = Document::from_text("body");
|
||||
let a = d.add_part(PartKind::TextBox, para_of("a"));
|
||||
let b = d.add_part(PartKind::TextBox, para_of("b"));
|
||||
let dead_c = d.add_part(PartKind::TextBox, para_of("dead c"));
|
||||
let dead_d = d.add_part(PartKind::TextBox, para_of("dead d"));
|
||||
|
||||
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
|
||||
// Reachable cycle: body -> nested group -> a -> nested group -> b -> nested group -> (a, b).
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(a))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(a), nested_group(2, test_shape(Some(b))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(b), nested_group(2, test_group(vec![test_shape(Some(a)), test_shape(Some(b))])), &CharProps::default()).unwrap();
|
||||
// Unreachable cycle: dead_c <-> dead_d through nested groups.
|
||||
d.insert_object(&at(dead_c), nested_group(2, test_shape(Some(dead_d))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(dead_d), nested_group(2, test_shape(Some(dead_c))), &CharProps::default()).unwrap();
|
||||
|
||||
assert_eq!(d.prune_text_boxes(), 2);
|
||||
let kept: Vec<u32> = d.parts.keys().copied().collect();
|
||||
assert_eq!(kept, vec![a, b]);
|
||||
assert_eq!(d.counted_stories(), vec![StoryRef::Body, StoryRef::Part(a), StoryRef::Part(b)]);
|
||||
}
|
||||
|
||||
/// `blocks` in the only cell of `levels` tables, each nested in the next.
|
||||
fn nested_tables(levels: usize, blocks: Blocks) -> Blocks {
|
||||
(0..levels).fold(blocks, |inner, _| {
|
||||
@@ -818,3 +928,165 @@ fn missing_pictures_are_capped_deduplicated_and_not_content() {
|
||||
assert!(!serde_json::to_string(&d).unwrap().contains("p0"));
|
||||
assert_eq!(MissingPictureReason::ExternalTarget.label(), "external target");
|
||||
}
|
||||
|
||||
fn shape_with_id(id: u32, story: Option<u32>) -> InlineObject {
|
||||
InlineObject::Shape {
|
||||
kind: para::ShapeKind::Rectangle,
|
||||
w: 50.0,
|
||||
h: 20.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: connector::ShapeExtra { id, ..Default::default() },
|
||||
}
|
||||
}
|
||||
|
||||
fn group_of(children: Vec<InlineObject>) -> InlineObject {
|
||||
InlineObject::Group {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
float: Default::default(),
|
||||
ch_w: 100.0,
|
||||
ch_h: 100.0,
|
||||
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
|
||||
canvas: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn nested_group_of(depth: usize, leaf: InlineObject) -> InlineObject {
|
||||
(0..depth).fold(leaf, |inner, _| group_of(vec![inner]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_accounts_for_shapes_in_nested_groups() {
|
||||
// Doubly-nested group carrying shape id 1: must not reissue id 1.
|
||||
let mut d = Document::from_text("body");
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(1, None)), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 2);
|
||||
|
||||
// Deeper nesting (5-level and 40-level groups) with mixed siblings.
|
||||
d.insert_object(
|
||||
&Pos::body(0, 0),
|
||||
nested_group_of(5, group_of(vec![shape_with_id(42, None), nested_group_of(35, shape_with_id(99, None))])),
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(d.next_shape_id(), 100);
|
||||
|
||||
// Nested group inside a secondary story (part).
|
||||
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
|
||||
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
|
||||
d.insert_object(&at_hdr, nested_group_of(3, shape_with_id(150, None)), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 151);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_preserves_flat_group_and_ungrouped_allocation() {
|
||||
let mut d = Document::from_text("body");
|
||||
assert_eq!(d.next_shape_id(), 1);
|
||||
|
||||
// Ungrouped shapes (including id 0).
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(0, None), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 1);
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(3, None), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(7, None), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 8);
|
||||
|
||||
// Flat (1-level) group.
|
||||
d.insert_object(&Pos::body(0, 0), group_of(vec![shape_with_id(12, None), shape_with_id(4, None)]), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 13);
|
||||
|
||||
// At u32::MAX, overflow falls back to an unused non-zero id rather than reissuing u32::MAX.
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
|
||||
let id = d.next_shape_id();
|
||||
assert_ne!(id, 0);
|
||||
for used in [3, 4, 7, 12, u32::MAX] {
|
||||
assert_ne!(id, used);
|
||||
}
|
||||
assert_eq!(id, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_avoids_reissuing_u32_max_on_overflow() {
|
||||
// Non-overflow boundary: u32::MAX - 1 still advances to u32::MAX.
|
||||
let mut d = Document::from_text("body");
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(u32::MAX - 1, None), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), u32::MAX);
|
||||
|
||||
// Once u32::MAX is in use inside a nested group, allocator must not reissue any in-use id.
|
||||
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
|
||||
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(1, None), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at_hdr, nested_group_of(2, shape_with_id(2, None)), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(3, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
|
||||
|
||||
let in_use = [1, 2, u32::MAX - 1, u32::MAX];
|
||||
let first = d.next_shape_id();
|
||||
assert_ne!(first, 0);
|
||||
assert!(!in_use.contains(&first), "reissued in-use shape id {first}");
|
||||
assert_eq!(first, 3);
|
||||
|
||||
// Using the returned id advances to the next unused id rather than repeating it.
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(first, None)), &CharProps::default()).unwrap();
|
||||
let second = d.next_shape_id();
|
||||
assert_ne!(second, 0);
|
||||
assert_ne!(second, first);
|
||||
assert!(!in_use.contains(&second), "reissued in-use shape id {second}");
|
||||
assert_eq!(second, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_terminates_on_cyclic_nested_group_stories() {
|
||||
// InlineObject::Group owns Vec<GroupChild> by value (and unsafe is forbidden), so a cyclic
|
||||
// in-memory Group tree cannot be constructed in safe Rust; mirror #8068 by constructing a
|
||||
// cyclic text-box story graph through nested groups instead.
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let mut d = Document::from_text("body");
|
||||
let a = d.add_part(PartKind::TextBox, para_of("a"));
|
||||
let b = d.add_part(PartKind::TextBox, para_of("b"));
|
||||
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
|
||||
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(5, Some(a))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(a), nested_group_of(2, shape_with_id(10, Some(b))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(b), nested_group_of(2, shape_with_id(25, Some(a))), &CharProps::default()).unwrap();
|
||||
|
||||
assert_eq!(d.next_shape_id(), 26);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_accounts_for_shapes_in_note_separators() {
|
||||
let blocks_with = |obj: InlineObject| -> Blocks {
|
||||
let mut p = Paragraph::with_text("sep", CharProps::default());
|
||||
p.insert_object(0, obj, &CharProps::default()).unwrap();
|
||||
vec![para_block(p)]
|
||||
};
|
||||
|
||||
// A shape ID used only in a footnote separator story must not be reissued.
|
||||
let mut d = Document::from_text("body");
|
||||
d.footnote_separators.separator = Some(blocks_with(shape_with_id(1, None)));
|
||||
assert_eq!(d.next_shape_id(), 2);
|
||||
|
||||
// Every footnote and endnote separator slot is walked, including nested groups and tables.
|
||||
d.footnote_separators.continuation_separator = Some(blocks_with(nested_group_of(2, shape_with_id(2, None))));
|
||||
d.footnote_separators.continuation_notice = Some(nested_tables(1, blocks_with(shape_with_id(5, None))));
|
||||
assert_eq!(d.next_shape_id(), 6);
|
||||
|
||||
d.endnote_separators.separator = Some(blocks_with(shape_with_id(9, None)));
|
||||
assert_eq!(d.next_shape_id(), 10);
|
||||
|
||||
d.endnote_separators.continuation_separator = Some(blocks_with(nested_group_of(3, shape_with_id(14, None))));
|
||||
assert_eq!(d.next_shape_id(), 15);
|
||||
|
||||
// Overflow fallback also respects IDs held exclusively in note-separator stories.
|
||||
d.endnote_separators.continuation_notice = Some(blocks_with(nested_group_of(2, shape_with_id(u32::MAX, None))));
|
||||
let allocated = d.next_shape_id();
|
||||
assert_ne!(allocated, 0);
|
||||
for used in [1, 2, 5, 9, 14, u32::MAX] {
|
||||
assert_ne!(allocated, used);
|
||||
}
|
||||
assert_eq!(allocated, 3);
|
||||
}
|
||||
|
||||
@@ -316,7 +316,13 @@ fn styles_and_lists_round_trip() {
|
||||
#[test]
|
||||
fn tracked_style_definition_change_round_trips() {
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Format, author: "Ana".into(), date: "2026-10-17T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Format,
|
||||
author: "Ana".into(),
|
||||
date: "2026-10-17T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
std::sync::Arc::make_mut(&mut d.styles).upsert(Style {
|
||||
id: "Mine".into(),
|
||||
name: "Mine".into(),
|
||||
@@ -1005,8 +1011,20 @@ fn toc_field_skips_nested_stories() {
|
||||
#[test]
|
||||
fn tracked_changes_round_trip() {
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Alice".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Bob".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.settings.track_changes = true;
|
||||
let ins = CharProps { ins: Some(0), ..Default::default() };
|
||||
let del = CharProps { del: Some(1), bold: Some(true), ..Default::default() };
|
||||
@@ -1034,8 +1052,20 @@ fn tracked_changes_round_trip() {
|
||||
fn tracked_equations_round_trip() {
|
||||
// Issue #6011: equations saved with tracked revision marks (w:ins / w:del) around math.
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Alice".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Bob".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.settings.track_changes = true;
|
||||
let ins = CharProps { ins: Some(0), ..Default::default() };
|
||||
let del = CharProps { del: Some(1), ..Default::default() };
|
||||
@@ -1089,8 +1119,20 @@ fn tracked_equations_round_trip() {
|
||||
fn nested_omath_para_revisions_read() {
|
||||
// Defensive reader check: w:ins and w:del nested inside m:oMathPara.
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Charles".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Ada".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Charles".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
let doc_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><w:body><w:p><m:oMathPara><w:ins w:id="1" w:author="Ada" w:date="2026-05-01T10:00:00Z"><m:oMath><m:r><m:t>x+1</m:t></m:r></m:oMath></w:ins><w:del w:id="2" w:author="Charles" w:date="2026-05-02T10:00:00Z"><m:oMath><m:r><m:t>y-1</m:t></m:r></m:oMath></w:del></m:oMathPara></w:p></w:body></w:document>"#;
|
||||
let base = wordcraft_docx::write(&d).unwrap();
|
||||
let bytes = replace_part(&base, "word/document.xml", doc_xml.as_bytes());
|
||||
@@ -1108,8 +1150,20 @@ fn tracked_paragraph_marks_round_trip() {
|
||||
// Issue #229: an inserted / deleted paragraph mark is `w:ins` / `w:del` in the mark's
|
||||
// `w:rPr` (ECMA-376 §17.13.5.16, §17.13.5.15), alone or with mark formatting.
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Alice".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Bob".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
let mut split = Paragraph::with_text("Owned ALPHA ", CharProps::default());
|
||||
split.mark.ins = Some(0);
|
||||
let mut joined = Paragraph::with_text("Owned BETA", CharProps::default());
|
||||
@@ -1863,7 +1917,7 @@ fn kitchen_sink() -> Document {
|
||||
let f = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Note", CharProps::default()))]);
|
||||
let c = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment", CharProps::default()))]);
|
||||
d.comments.insert(3, Comment { author: "X".into(), part: c, ..Default::default() });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
d.last_section.headers.default = Some(h);
|
||||
let mut blocks: Blocks = Vec::new();
|
||||
let mut p = para_runs(&[
|
||||
|
||||
@@ -41,7 +41,7 @@ fn sample() -> Document {
|
||||
let foot = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Sown in May.", CharProps::default()))]);
|
||||
let com = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Too short?", CharProps::default()))]);
|
||||
d.comments.insert(3, Comment { author: "Bo".into(), part: com, ..Default::default() });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
d.last_section.headers.default = Some(head);
|
||||
|
||||
let mut p = Paragraph::new();
|
||||
|
||||
@@ -298,6 +298,8 @@ Review|Language|Translate|review.translate
|
||||
Review|Language|Language|review.language
|
||||
Review|Comments|New Comment|review.newComment
|
||||
Review|Comments|Delete|review.deleteComment
|
||||
Review|Comments|Delete All Comments in Document|review.deleteComment
|
||||
Review|Comments|Delete All Resolved Comments|review.deleteComment
|
||||
Review|Comments|Previous|review.previousComment
|
||||
Review|Comments|Next|review.nextComment
|
||||
Review|Comments|Show Comments|review.comments
|
||||
|
||||
@@ -210,14 +210,21 @@ pub fn new_revision(s: &mut Session, kind: RevisionKind) -> u32 {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find(|(i, r)| r.kind == kind && r.author == s.author && r.date == date && r.move_name.is_none() && held != Some(*i as u32))
|
||||
.find(|(i, r)| r.kind == kind && r.author == s.author && r.instant() == date && r.move_name.is_none() && held != Some(*i as u32))
|
||||
{
|
||||
return i as u32;
|
||||
}
|
||||
s.doc.revisions.push(Revision { kind, author: s.author.clone(), date, move_name: None });
|
||||
s.doc.revisions.push(made_revision(kind, s.author.clone(), date));
|
||||
(s.doc.revisions.len() - 1) as u32
|
||||
}
|
||||
|
||||
/// A revision record for a change made at `utc` (ISO 8601, UTC): dated in local wall-clock time,
|
||||
/// as Word writes `w:date`, with the UTC time beside it, so a save writes it as it is (#6851).
|
||||
pub fn made_revision(kind: RevisionKind, author: String, utc: String) -> Revision {
|
||||
let date = crate::io_ext::word_date(&utc, local_offset_secs).unwrap_or_else(|| utc.clone());
|
||||
Revision::made_at(kind, author, date, utc)
|
||||
}
|
||||
|
||||
/// Whether the paragraph at `path` is followed by another paragraph in the same container (so
|
||||
/// its paragraph mark can be removed by joining the two).
|
||||
pub fn has_next_para(s: &Session, story: StoryRef, path: &wordcraft_doc::Path) -> bool {
|
||||
@@ -556,6 +563,10 @@ pub fn iso_from_unix_secs(secs: u64) -> String {
|
||||
|
||||
/// Seconds since the Unix epoch (UTC): the system clock, or the browser's on the web.
|
||||
pub fn now_unix() -> u64 {
|
||||
#[cfg(test)]
|
||||
if let Some(now) = TEST_NOW.with(std::cell::Cell::get) {
|
||||
return now;
|
||||
}
|
||||
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
|
||||
{
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
@@ -577,9 +588,23 @@ pub fn now_iso() -> String {
|
||||
/// The local time zone's offset from UTC in seconds (east positive) at `unix`, daylight saving
|
||||
/// included: the system's zone, or the browser's on the web. 0 (UTC) when it can't be found.
|
||||
pub fn local_offset_secs(unix: u64) -> i64 {
|
||||
#[cfg(test)]
|
||||
if let Some(zone) = TEST_ZONE.with(std::cell::Cell::get) {
|
||||
return zone(unix);
|
||||
}
|
||||
system_offset_secs(unix).clamp(-26 * 3600, 26 * 3600)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The clock [`now_unix`] reads on this thread in place of the system's, so a test can make
|
||||
/// edits at the instants it needs.
|
||||
pub static TEST_NOW: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// The zone [`local_offset_secs`] gives on this thread in place of the system's. CI runs on
|
||||
/// UTC, where local time is UTC, so a test sets a zone that isn't to tell them apart.
|
||||
pub static TEST_ZONE: std::cell::Cell<Option<fn(u64) -> i64>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn system_offset_secs(unix: u64) -> i64 {
|
||||
use chrono::Offset;
|
||||
|
||||
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("references.sources", "Manage Sources", "References › Citations & Bibliography", sources)
|
||||
.params(r#"{"add"?: Source, "remove"?: tag, "import"?: path (a Word bibliography file, `b:Sources` / `Sources.xml`)} → list"#),
|
||||
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added if new), "pages"?: string}"#),
|
||||
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added, or edited when its tag exists, and cited when no tag is given), "pages"?: string}"#),
|
||||
CommandSpec::new("references.citationStyle", "Style", "References › Citations & Bibliography", |s, v| {
|
||||
let st = p::str(v, "style").unwrap_or("APA");
|
||||
let st = find_style(st).ok_or_else(|| {
|
||||
|
||||
@@ -37,22 +37,7 @@ fn auto_tag_base(src: &Source) -> String {
|
||||
/// document's sources. `import` reads a Word bibliography file (`b:Sources`, #2640).
|
||||
pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if let Some(a) = v.get("add") {
|
||||
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
// A new source's tag is made from its author and year; an edit keeps the tag it has.
|
||||
if src.tag.is_empty() {
|
||||
src.tag = auto_tag(&s.doc, &src);
|
||||
}
|
||||
// Edit Source keeps the source's place in the list and refreshes its citations.
|
||||
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
|
||||
Some(i) => {
|
||||
if let Some(x) = s.doc.sources.get_mut(i) {
|
||||
*x = src;
|
||||
}
|
||||
update_citations(s)?;
|
||||
}
|
||||
None => s.doc.sources.push(src),
|
||||
}
|
||||
s.touch();
|
||||
add_source(s, a)?;
|
||||
}
|
||||
if let Some(t) = p::str(v, "remove") {
|
||||
s.doc.sources.retain(|x| x.tag != t);
|
||||
@@ -63,6 +48,28 @@ pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(serde_json::to_value(&s.doc.sources).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
/// Adds a source, or edits the one with its tag, and returns that tag (#7443).
|
||||
fn add_source(s: &mut Session, a: &Value) -> Result<String, CmdError> {
|
||||
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
// A new source's tag is made from its author and year; an edit keeps the tag it has.
|
||||
if src.tag.is_empty() {
|
||||
src.tag = auto_tag(&s.doc, &src);
|
||||
}
|
||||
let tag = src.tag.clone();
|
||||
// Edit Source keeps the source's place in the list and refreshes its citations.
|
||||
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
|
||||
Some(i) => {
|
||||
if let Some(x) = s.doc.sources.get_mut(i) {
|
||||
*x = src;
|
||||
}
|
||||
update_citations(s)?;
|
||||
}
|
||||
None => s.doc.sources.push(src),
|
||||
}
|
||||
s.touch();
|
||||
Ok(tag)
|
||||
}
|
||||
|
||||
/// The largest bibliography sources file imported from disk.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_SOURCES_FILE: u64 = 32 << 20;
|
||||
@@ -126,15 +133,16 @@ fn import_sources(s: &mut Session, path: &str) -> Result<(), CmdError> {
|
||||
}
|
||||
|
||||
pub(super) fn citation(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if v.get("source").is_some() {
|
||||
sources(s, &json!({"add": v.get("source")}))?;
|
||||
}
|
||||
let tag = match p::str(v, "tag") {
|
||||
Some(t) => t.to_string(),
|
||||
None => match v.get("source") {
|
||||
Some(_) => s.doc.sources.last().map(|x| x.tag.clone()).unwrap_or_default(),
|
||||
None => return Err(CmdError::Params("give `tag` or `source`".into())),
|
||||
},
|
||||
// The source just added or edited is the one cited when no `tag` is given, wherever it sits
|
||||
// in the list (#7443).
|
||||
let added = match v.get("source") {
|
||||
Some(a) => Some(add_source(s, a)?),
|
||||
None => None,
|
||||
};
|
||||
let tag = match (p::str(v, "tag"), added) {
|
||||
(Some(t), _) => t.to_string(),
|
||||
(None, Some(t)) => t,
|
||||
(None, None) => return Err(CmdError::Params("give `tag` or `source`".into())),
|
||||
};
|
||||
let src = s.doc.sources.iter().find(|x| x.tag == tag).cloned().ok_or_else(|| CmdError::Params(format!("no source `{tag}`")))?;
|
||||
let pages = p::str(v, "pages").unwrap_or("").to_string();
|
||||
|
||||
@@ -597,6 +597,22 @@ fn editing_author_and_year_keeps_the_tag_and_updates_the_citation_text() {
|
||||
assert!(f[0].1.contains("Jones") && f[0].1.contains("2021"), "{:?}", f[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn citing_an_edited_source_that_is_not_last_cites_that_source() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.sources", &json!({"add": src_of("Alice, Ann", "2000")})).unwrap();
|
||||
s.run("references.sources", &json!({"add": src_of("Bob, Ben", "2001")})).unwrap();
|
||||
let mut edited = src_of("Alice Edited, Ann", "2000");
|
||||
edited["tag"] = json!("Ali00");
|
||||
let r = s.run("references.citation", &json!({"source": edited})).unwrap();
|
||||
assert_eq!(r["tag"], "Ali00");
|
||||
let tags: Vec<_> = s.doc.sources.iter().map(|x| x.tag.as_str()).collect();
|
||||
assert_eq!(tags, ["Ali00", "Bob01"]);
|
||||
let f = fields(&s);
|
||||
assert_eq!(f[0].0, "CITATION Ali00");
|
||||
assert!(f[0].1.contains("Alice Edited") && f[0].1.contains("2000"), "{:?}", f[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_sources_tag_is_three_letters_and_two_year_digits() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
|
||||
@@ -53,11 +53,11 @@ impl Recorder<'_> {
|
||||
if let Some(r) = self.rid {
|
||||
return r;
|
||||
}
|
||||
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.date == self.date);
|
||||
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.instant() == self.date);
|
||||
let r = match found {
|
||||
Some(i) => i as u32,
|
||||
None => {
|
||||
self.revisions.push(Revision { kind: RevisionKind::Format, author: self.author.clone(), date: self.date.clone(), move_name: None });
|
||||
self.revisions.push(crate::cmd::made_revision(RevisionKind::Format, self.author.clone(), self.date.clone()));
|
||||
self.revisions.len().saturating_sub(1) as u32
|
||||
}
|
||||
};
|
||||
|
||||
@@ -27,6 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
r#"{"type"?: "indented|runIn", "columns"?: 1-4, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "headings"?: bool (letter headings)} (replaces an existing index's settings)"#,
|
||||
),
|
||||
CommandSpec::new("references.updateIndex", "Update Index", "References › Index", |s, _| {
|
||||
check_index_reachable(s)?;
|
||||
super::citations::update_generated(s)?;
|
||||
sel_result(s)
|
||||
}),
|
||||
@@ -135,8 +136,63 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an INDEX field (a plain one or a range field, as Word files hold it) sits in the main
|
||||
/// text's own paragraphs (`main`), or anywhere else a reader sees: a table cell, a text box, a
|
||||
/// header or a footer in use. Stored headers and footers no page shows (a first-page header
|
||||
/// while Different First Page is off) don't count. Only an index in the main text is rebuilt.
|
||||
fn has_index(s: &Session, main: bool) -> bool {
|
||||
s.doc.shown_stories().into_iter().any(|story| {
|
||||
s.doc
|
||||
.para_paths(story)
|
||||
.iter()
|
||||
.filter(|path| (story == StoryRef::Body && path.depth() == 0) == main)
|
||||
.filter_map(|path| s.doc.para(story, path))
|
||||
.any(|p| {
|
||||
p.objects.iter().any(|o| {
|
||||
matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Refuses Insert and Update Index when the document has an index they can't rebuild, even beside
|
||||
/// one in the main text, rather than adding a second index or reporting an update that left it
|
||||
/// unchanged.
|
||||
fn check_index_reachable(s: &Session) -> Result<(), CmdError> {
|
||||
if has_index(s, false) {
|
||||
return Err(CmdError::Failed(
|
||||
"the index is in a table, text box, header or footer, where it can't be updated; move it into the main text, then use Update Index"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
// A range-field index after text in its paragraph is not rebuilt either: Update Index only
|
||||
// takes one that starts its paragraph.
|
||||
if range_index_after_text(s) {
|
||||
return Err(CmdError::Failed(
|
||||
"the index follows text in its paragraph, where it can't be updated; put it at the start of its own paragraph in the main text".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a main-text range-field INDEX has text before it in its paragraph.
|
||||
fn range_index_after_text(s: &Session) -> bool {
|
||||
s.doc.body.iter().filter_map(|b| b.as_para()).any(|p| {
|
||||
p.objects_with_offsets().any(|(off, o)| {
|
||||
matches!(o, InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
|
||||
&& !p.text.get(..off).is_some_and(|t| t.chars().all(|c| c.is_whitespace() || c == wordcraft_doc::para::OBJ))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
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 rebuilt by Update Index; Insert Index would add a
|
||||
// second one beside it (#8034).
|
||||
if index_field(s).is_none() && has_index(s, true) {
|
||||
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
|
||||
}
|
||||
match index_field(s) {
|
||||
Some((i, _)) => {
|
||||
// Settings for the index that is there: a new field code, then rebuild it.
|
||||
@@ -484,4 +540,144 @@ mod tests {
|
||||
let (i, _) = index_field(&s).unwrap();
|
||||
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
|
||||
}
|
||||
|
||||
/// #3670: an index in a table cell or a text box (as imported documents have it) can't be
|
||||
/// rebuilt where it is, so Insert and Update Index say so, and Insert Index doesn't add a
|
||||
/// second index at the caret.
|
||||
#[test]
|
||||
fn an_index_outside_the_main_text_is_refused_not_doubled() {
|
||||
let indexes = |s: &Session| {
|
||||
std::iter::once(StoryRef::Body)
|
||||
.chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)))
|
||||
.flat_map(|story| s.doc.para_paths(story).into_iter().filter_map(move |path| s.doc.para(story, &path).cloned()))
|
||||
.flat_map(|p| p.objects)
|
||||
.filter(|o| matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX"))
|
||||
.count()
|
||||
};
|
||||
for in_box in [false, true] {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(
|
||||
"Kilns are hot.
|
||||
End.",
|
||||
));
|
||||
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
let at = if in_box {
|
||||
s.run("insert.textBox", &json!({"text": "Box"})).unwrap();
|
||||
let id = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::TextBox).map(|(id, _)| *id).unwrap();
|
||||
Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 }
|
||||
} else {
|
||||
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
|
||||
Pos { story: StoryRef::Body, path: cell, off: 0 }
|
||||
};
|
||||
// A range field, as a Word file holds its index.
|
||||
let p = s.doc.para_mut(at.story, &at.path).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
let r = s.run("references.index", &json!({"columns": 2}));
|
||||
assert!(r.is_err(), "Insert Index with the index in a {}: {r:?}", if in_box { "text box" } else { "table" });
|
||||
assert_eq!(indexes(&s), 1, "INDEX fields after Insert Index");
|
||||
assert!(s.run("references.updateIndex", &json!({})).is_err(), "Update Index reports the index it can't rebuild");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3670: an index in a table is refused even when the main text also has one, so the update
|
||||
/// can't report success and leave the table's index as it was.
|
||||
#[test]
|
||||
fn an_index_in_a_table_is_refused_beside_one_in_the_main_text() {
|
||||
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();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({})).unwrap();
|
||||
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
|
||||
let p = s.doc.para_mut(StoryRef::Body, &cell).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default()).unwrap();
|
||||
assert!(s.run("references.index", &json!({"columns": 2})).is_err());
|
||||
assert!(s.run("references.updateIndex", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// #3670: only the headers a page shows count. An INDEX in a first-page header is out of
|
||||
/// reach while Different First Page is on, and doesn't block Insert Index while it is off.
|
||||
#[test]
|
||||
fn an_index_in_a_header_blocks_insert_only_while_the_header_is_shown() {
|
||||
let with_header_index = |first: bool, title_page: bool| {
|
||||
let mut d = wordcraft_doc::Document::from_text("Kilns are hot.");
|
||||
let mut p = wordcraft_doc::Paragraph::new();
|
||||
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![std::sync::Arc::new(wordcraft_doc::Block::Para(p))]);
|
||||
if first {
|
||||
d.last_section.headers.first = Some(id);
|
||||
} else {
|
||||
d.last_section.headers.default = Some(id);
|
||||
}
|
||||
d.last_section.title_page = title_page;
|
||||
let mut s = Session::new(d);
|
||||
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s
|
||||
};
|
||||
let body_has_index = |s: &Session| index_field(s).is_some();
|
||||
// Linked (default) header: shown, so Insert Index is refused.
|
||||
let mut s = with_header_index(false, false);
|
||||
assert!(s.run("references.index", &json!({})).is_err());
|
||||
assert!(!body_has_index(&s));
|
||||
// First-page header with Different First Page off: hidden, so the body gets its index.
|
||||
let mut s = with_header_index(true, false);
|
||||
s.run("references.index", &json!({})).unwrap();
|
||||
assert!(body_has_index(&s));
|
||||
// The same header with Different First Page on is shown again.
|
||||
let mut s = with_header_index(true, true);
|
||||
assert!(s.run("references.index", &json!({})).is_err());
|
||||
assert!(!body_has_index(&s));
|
||||
}
|
||||
|
||||
/// 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_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();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
let at = s.doc.body.len();
|
||||
let mut para = wordcraft_doc::para::Paragraph::new();
|
||||
para.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
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();
|
||||
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(
|
||||
"
|
||||
",
|
||||
);
|
||||
assert!(text.contains("Kilns are hot."), "the text before the index survives: {text:?}");
|
||||
assert!(text.contains("Kilns, 1"), "Update Index generated an entry: {text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_field_index_after_text_is_refused_not_reported_updated() {
|
||||
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();
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
let end = p.len();
|
||||
p.insert_object(end, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
p.insert_object(end, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
assert!(s.run("references.updateIndex", &json!({})).is_err());
|
||||
assert!(s.run("references.index", &json!({})).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ pub fn cut_tracked(s: &mut Session) -> Result<bool, CmdError> {
|
||||
if !s.doc.settings.track_changes || !s.doc.settings.track_moves || a == b || a.story != b.story || !move_sized(&s.clipboard_text) {
|
||||
return Ok(false);
|
||||
}
|
||||
s.doc.revisions.push(Revision::new(RevisionKind::Delete, s.author.clone(), now_iso()));
|
||||
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, s.author.clone(), now_iso()));
|
||||
let rid = (s.doc.revisions.len() - 1) as u32;
|
||||
let at = track_delete_as(s, &a, &b, rid)?.at;
|
||||
s.sel = Selection::caret(at);
|
||||
@@ -75,13 +75,13 @@ pub fn take_paste(s: &mut Session, frag: &Fragment) -> Option<u32> {
|
||||
return None;
|
||||
}
|
||||
let src = s.doc.revisions.get(m.rev as usize).filter(|r| r.kind == RevisionKind::Delete && r.move_name.is_none())?;
|
||||
let date = src.date.clone();
|
||||
let (date, date_utc) = (src.date.clone(), src.date_utc.clone());
|
||||
let taken: BTreeSet<&str> = s.doc.revisions.iter().filter_map(|r| r.move_name.as_deref()).collect();
|
||||
let name = (1..).map(|n: u64| format!("move{n}")).find(|n| !taken.contains(n.as_str()))?;
|
||||
if let Some(r) = s.doc.revisions.get_mut(m.rev as usize) {
|
||||
r.move_name = Some(name.clone());
|
||||
}
|
||||
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name) });
|
||||
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name), date_utc });
|
||||
Some((s.doc.revisions.len() - 1) as u32)
|
||||
}
|
||||
|
||||
|
||||
@@ -200,7 +200,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
r#"{"color": "RRGGBB" | null, "paragraph"?: bool} (text selected inside one paragraph is shaded itself, as in Word; `paragraph: true` shades the paragraphs instead, as Borders and Shading › Apply to: Paragraph)"#,
|
||||
),
|
||||
CommandSpec::new("para.borders", "Borders", "Home › Paragraph", borders).params(
|
||||
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind`"#,
|
||||
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind` (with whole table cells selected, `kind` borders the cells as a block instead of their paragraphs)"#,
|
||||
),
|
||||
CommandSpec::new("para.sort", "Sort", "Home › Paragraph", sort).params(r#"{"descending"?: bool}"#),
|
||||
CommandSpec::new("para.keepNext", "Keep with Next", "Home › Paragraph › Line and Page Breaks", |s, v| tog(s, v, |p| p.keep_next, |p, b| p.keep_next = Some(b)))
|
||||
|
||||
@@ -102,6 +102,10 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// A paragraph with a bottom border, like Word's Horizontal Line.
|
||||
return fmt(s, &|p| p.borders = Some(Borders { bottom: Some(Border { width: 1.5, ..b }), ..Default::default() }));
|
||||
}
|
||||
// Whole table cells selected: the border goes on the cells, not their paragraphs (#7874).
|
||||
if let Some(range) = s.cell_range().cloned() {
|
||||
return crate::cmd::table::cell_block_borders(s, &range, kind, b);
|
||||
}
|
||||
fmt(s, &|p| {
|
||||
let mut cur = p.borders.unwrap_or_default();
|
||||
match kind {
|
||||
|
||||
@@ -33,7 +33,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
|
||||
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
|
||||
.when(comments_change),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool}"#),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(
|
||||
r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool (every comment), "resolved"?: bool (every resolved comment, with its replies; wins over all)}"#,
|
||||
),
|
||||
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
|
||||
validate_comment_id(v)?;
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
|
||||
|
||||
@@ -608,10 +608,11 @@ pub(super) fn list_changes(s: &mut Session, _: &Value) -> CmdResult {
|
||||
list.iter()
|
||||
.map(|c| {
|
||||
let rev = c.rev.and_then(|r| s.doc.revisions.get(r as usize));
|
||||
// The date in UTC when it is known; a file's `w:date` without it is as read.
|
||||
let mut v = json!({
|
||||
"kind": c.kind, "start": pos_json(&c.a), "end": pos_json(&c.b),
|
||||
"text": s.doc.copy_range(&c.a, &c.b).plain_text(),
|
||||
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.date.clone()),
|
||||
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.instant().to_string()),
|
||||
});
|
||||
if c.kind == "format" {
|
||||
v["description"] = json!(fmt_revisions::describe(&c.props));
|
||||
|
||||
@@ -163,17 +163,17 @@ fn remove_anchors(s: &mut Session, ids: &BTreeSet<u32>) -> Result<(), CmdError>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The comment and every reply below it, replies to replies included (#1345). A parent cycle
|
||||
/// from a hostile file ends the walk instead of looping.
|
||||
fn thread_of(s: &Session, id: u32) -> Vec<u32> {
|
||||
/// The comments and every reply below them, replies to replies included (#1345), each once. A
|
||||
/// parent cycle from a hostile file ends the walk instead of looping.
|
||||
fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
|
||||
let mut children: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
|
||||
for (k, c) in &s.doc.comments {
|
||||
if let Some(parent) = c.parent {
|
||||
children.entry(parent).or_default().push(*k);
|
||||
}
|
||||
}
|
||||
let mut seen = BTreeSet::from([id]);
|
||||
let mut ids = vec![id];
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut ids: Vec<u32> = roots.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
let mut i = 0;
|
||||
while let Some(&at) = ids.get(i) {
|
||||
for k in children.get(&at).into_iter().flatten() {
|
||||
@@ -188,11 +188,15 @@ fn thread_of(s: &Session, id: u32) -> Vec<u32> {
|
||||
|
||||
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
|
||||
validate_comment_id(v)?;
|
||||
let ids: Vec<u32> = if p::bool(v, "all").unwrap_or(false) {
|
||||
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
|
||||
// Delete All Resolved Comments (#7818): each resolved comment goes with its replies.
|
||||
let resolved: Vec<u32> = s.doc.comments.iter().filter(|(_, c)| c.resolved).map(|(k, _)| *k).collect();
|
||||
threads_of(s, resolved)
|
||||
} else if p::bool(v, "all").unwrap_or(false) {
|
||||
s.doc.comments.keys().copied().collect()
|
||||
} else {
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("no comment here".into()))?;
|
||||
thread_of(s, id)
|
||||
threads_of(s, [id])
|
||||
};
|
||||
remove_anchors(s, &ids.iter().copied().collect())?;
|
||||
for id in &ids {
|
||||
|
||||
@@ -549,6 +549,135 @@ fn selected(s: &Session) -> (usize, usize) {
|
||||
(a.off, b.off)
|
||||
}
|
||||
|
||||
/// Two edits an hour apart in the repeated hour as daylight saving time ends are two changes,
|
||||
/// though both were made at 01:30 local time: each keeps its UTC time (#6851). Rejecting one at
|
||||
/// the caret leaves the other pending. Saved as DOCX or Word XML, both are dated 01:30, as Word
|
||||
/// dates them, with their UTC times beside it (`w16du:dateUtc`), so they reopen as two changes,
|
||||
/// and a second save writes them as read.
|
||||
#[test]
|
||||
fn edits_in_the_repeated_hour_stay_separate_changes() {
|
||||
use crate::cmd::{TEST_NOW, TEST_ZONE};
|
||||
struct Reset;
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
TEST_NOW.with(|c| c.set(None));
|
||||
TEST_ZONE.with(|z| z.set(None));
|
||||
}
|
||||
}
|
||||
let _reset = Reset;
|
||||
TEST_ZONE.with(|z| z.set(Some(crate::io_ext::tests::new_york)));
|
||||
|
||||
let mut s = Session::new(Document::new());
|
||||
s.view.proofing = false;
|
||||
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
// 1 November 2026, 01:30 EDT (05:30 UTC) and then 01:30 EST (06:30 UTC).
|
||||
for (now, text) in [(1_793_511_000, " One"), (1_793_514_600, " Two")] {
|
||||
TEST_NOW.with(|c| c.set(Some(now)));
|
||||
s.run("text.insert", &json!({"text": text})).unwrap();
|
||||
}
|
||||
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10), ("insert".into(), 10, 14)]);
|
||||
let utc = ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"];
|
||||
let instants = |d: &Document| d.revisions.iter().map(|r| r.instant().to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(instants(&s.doc), utc);
|
||||
let listed = s.run("review.changes", &json!({})).unwrap();
|
||||
assert_eq!(listed.as_array().map(|l| l.iter().map(|c| c["date"].clone()).collect::<Vec<_>>()), Some(vec![json!(utc[0]), json!(utc[1])]));
|
||||
|
||||
let local = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
|
||||
for name in ["repeated.docx", "repeated.xml"] {
|
||||
let bytes = crate::io::save_bytes(name, &s.doc).unwrap();
|
||||
let read = |bytes: &[u8]| if name.ends_with(".xml") { wordcraft_docx::read_xml(bytes) } else { wordcraft_docx::read(bytes) }.unwrap();
|
||||
let written = read(&bytes);
|
||||
assert_eq!(local(&written), ["2026-11-01T01:30:00Z"; 2], "{name}");
|
||||
assert_eq!(instants(&written), utc, "{name}");
|
||||
|
||||
let mut opened = Session::new(crate::io::open_bytes(name, &bytes).unwrap());
|
||||
opened.view.proofing = false;
|
||||
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10), ("insert".into(), 10, 14)], "{name}");
|
||||
// Saved again, the changes are written as read: their local time doesn't move.
|
||||
let again = read(&crate::io::save_bytes(name, &opened.doc).unwrap());
|
||||
assert_eq!((local(&again), instants(&again)), (local(&written), instants(&written)), "{name}");
|
||||
|
||||
opened.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
|
||||
opened.run("review.reject", &json!({})).unwrap();
|
||||
assert_eq!(opened.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One", "{name}");
|
||||
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10)], "{name}: the earlier insertion is still pending");
|
||||
}
|
||||
assert_eq!(instants(&s.doc), utc, "saving leaves the session's changes as they were");
|
||||
|
||||
s.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
|
||||
s.run("review.reject", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One");
|
||||
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10)], "the earlier insertion is still pending");
|
||||
}
|
||||
|
||||
/// A change made at 08:33 UTC at UTC+8 is dated 16:33 in a Word file, as Word dates it, and 08:33
|
||||
/// UTC in an OpenDocument file, whose `dc:date` is an instant (#6851).
|
||||
#[test]
|
||||
fn a_new_change_is_dated_in_utc_in_opendocument() {
|
||||
use crate::cmd::{TEST_NOW, TEST_ZONE};
|
||||
struct Reset;
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
TEST_NOW.with(|c| c.set(None));
|
||||
TEST_ZONE.with(|z| z.set(None));
|
||||
}
|
||||
}
|
||||
let _reset = Reset;
|
||||
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
|
||||
TEST_NOW.with(|c| c.set(Some(1_794_818_004)));
|
||||
|
||||
let mut s = Session::new(Document::new());
|
||||
s.view.proofing = false;
|
||||
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("text.insert", &json!({"text": " One"})).unwrap();
|
||||
let utc = "2026-11-16T08:33:24Z";
|
||||
let dates = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
|
||||
for (name, date) in [("new.odt", utc), ("new.fodt", utc), ("new.docx", "2026-11-16T16:33:24Z"), ("new.xml", "2026-11-16T16:33:24Z")] {
|
||||
let opened = crate::io::open_bytes(name, &crate::io::save_bytes(name, &s.doc).unwrap()).unwrap();
|
||||
assert_eq!(dates(&opened), [date], "{name}");
|
||||
assert!(opened.revisions.iter().all(|r| r.instant() == utc), "{name}: {:?}", opened.revisions);
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracked change read from a file keeps its `w:date` and `w16du:dateUtc` as read through open
|
||||
/// and save in another zone (#6851): one without a UTC time (an older Word, another program), whose
|
||||
/// zone WordCraft doesn't guess, and one written in UTC, where the two are the same.
|
||||
#[test]
|
||||
fn a_file_date_is_written_as_read() {
|
||||
use crate::cmd::TEST_ZONE;
|
||||
struct Reset;
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
TEST_ZONE.with(|z| z.set(None));
|
||||
}
|
||||
}
|
||||
let _reset = Reset;
|
||||
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
|
||||
|
||||
let date = "2026-11-16T08:33:24Z";
|
||||
for utc in [None, Some(date)] {
|
||||
let mut doc = Document::from_text("Draft.");
|
||||
let mut rev = wordcraft_doc::Revision::new(wordcraft_doc::RevisionKind::Insert, "Ada", date);
|
||||
rev.date_utc = utc.map(String::from);
|
||||
doc.revisions.push(rev);
|
||||
doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
|
||||
let dates = |d: &Document| d.revisions.iter().map(|r| (r.date.clone(), r.date_utc.clone())).collect::<Vec<_>>();
|
||||
let want = vec![(date.to_string(), utc.map(String::from))];
|
||||
for name in ["file.docx", "file.xml"] {
|
||||
let bytes = crate::io::save_bytes(name, &doc).unwrap();
|
||||
let opened = crate::io::open_bytes(name, &bytes).unwrap();
|
||||
assert_eq!(dates(&opened), want, "{name} {utc:?}: opened");
|
||||
let saved = crate::io::save_bytes(name, &opened).unwrap();
|
||||
let again = if name.ends_with(".xml") { wordcraft_docx::read_xml(&saved) } else { wordcraft_docx::read(&saved) }.unwrap();
|
||||
assert_eq!(dates(&again), want, "{name} {utc:?}: saved again");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept and Move to Next, Reject and Move to Next: the change at the caret is resolved and
|
||||
/// the next one is selected; without `next` the caret stays where the change was.
|
||||
#[test]
|
||||
@@ -796,6 +925,77 @@ fn deleting_a_comment_in_a_parent_cycle_ends() {
|
||||
assert!(s.doc.comments.is_empty());
|
||||
}
|
||||
|
||||
/// Comments on "one", "two" and "three" with a reply on the first; the ids, in that order.
|
||||
fn three_commented_words(s: &mut Session) -> [u64; 4] {
|
||||
s.view.proofing = false;
|
||||
s.run("document.setText", &json!({"text": "one two three"})).unwrap();
|
||||
let on = |s: &mut Session, word: &str| {
|
||||
s.run("select.text", &json!({"text": word})).unwrap();
|
||||
s.run("review.newComment", &json!({"text": word})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let (one, two, three) = (on(s, "one"), on(s, "two"), on(s, "three"));
|
||||
let reply = s.run("review.reply", &json!({"id": one, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
|
||||
[one, reply, two, three]
|
||||
}
|
||||
|
||||
/// #7818: Review › Delete › Delete All Resolved Comments deletes each resolved comment with its
|
||||
/// replies and their text, and keeps the open ones with their anchors; Undo brings them back.
|
||||
#[test]
|
||||
fn delete_all_resolved_comments_keeps_the_open_ones() {
|
||||
let mut s = Session::new(Document::new());
|
||||
let [one, reply, two, three] = three_commented_words(&mut s);
|
||||
for id in [one, three] {
|
||||
s.run("review.resolveComment", &json!({"id": id, "value": true})).unwrap();
|
||||
}
|
||||
let part = |s: &Session, id: u64| s.doc.comments[&(id as u32)].part;
|
||||
let kept_part = part(&s, two);
|
||||
let gone_parts: Vec<u32> = [one, reply, three].iter().map(|id| part(&s, *id)).collect();
|
||||
// The caret sits in the open comment, which Delete alone would take.
|
||||
s.run("select.text", &json!({"text": "two"})).unwrap();
|
||||
let depth = s.undo_depth();
|
||||
|
||||
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
|
||||
|
||||
let mut deleted: Vec<u64> = out["deleted"].as_array().unwrap().iter().filter_map(|v| v.as_u64()).collect();
|
||||
let mut want = vec![one, reply, three];
|
||||
deleted.sort_unstable();
|
||||
want.sort_unstable();
|
||||
assert_eq!(deleted, want, "the resolved comments and the reply below one of them");
|
||||
assert_eq!(s.doc.comments.keys().map(|k| u64::from(*k)).collect::<Vec<_>>(), vec![two], "the open comment stays");
|
||||
assert!(s.doc.parts.contains_key(&kept_part));
|
||||
assert!(gone_parts.iter().all(|p| !s.doc.parts.contains_key(p)), "the deleted comments' text parts are gone");
|
||||
assert_eq!(anchors(&s), vec![(wordcraft_doc::StoryRef::Body, two as u32); 2], "only the open comment's anchors are left");
|
||||
assert_eq!(s.undo_depth(), depth + 1, "one undo step");
|
||||
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.comments.len(), 4);
|
||||
assert_eq!(anchors(&s).len(), 6);
|
||||
}
|
||||
|
||||
/// #7818: with nothing resolved, Delete All Resolved Comments leaves every comment.
|
||||
#[test]
|
||||
fn delete_all_resolved_comments_without_resolved_ones_keeps_all() {
|
||||
let mut s = Session::new(Document::new());
|
||||
three_commented_words(&mut s);
|
||||
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
|
||||
assert_eq!(out["deleted"], json!([]));
|
||||
assert_eq!(s.doc.comments.len(), 4);
|
||||
assert_eq!(anchors(&s).len(), 6);
|
||||
}
|
||||
|
||||
/// #7818: Review › Delete › Delete All Comments in Document deletes every comment, reply and
|
||||
/// anchor, resolved or not.
|
||||
#[test]
|
||||
fn delete_all_comments_in_document_deletes_every_comment() {
|
||||
let mut s = Session::new(Document::new());
|
||||
let [one, ..] = three_commented_words(&mut s);
|
||||
s.run("review.resolveComment", &json!({"id": one, "value": true})).unwrap();
|
||||
s.run("review.deleteComment", &json!({"all": true})).unwrap();
|
||||
assert!(s.doc.comments.is_empty());
|
||||
assert!(s.doc.parts.is_empty(), "no comment text is left: {:?}", s.doc.parts.keys());
|
||||
assert!(anchors(&s).is_empty());
|
||||
}
|
||||
|
||||
/// A very long reply chain (as a hostile file could hold) is deleted in one pass over the
|
||||
/// comments, not one pass per reply: 50,000 replies would otherwise freeze the app.
|
||||
#[test]
|
||||
|
||||
@@ -26,7 +26,7 @@ use clear::{cell_prefix, guard_delete, text_spans};
|
||||
use convert::{formula, from_text, quick_table, sort_table, to_text};
|
||||
pub use convert::{text_table_cells, text_table_lines};
|
||||
use layout::{autofit, borders, fix_caret, properties, set_column_widths};
|
||||
pub(crate) use layout::{sync_cell_widths, text_direction, touch_cells};
|
||||
pub(crate) use layout::{cell_block_borders, sync_cell_widths, text_direction, touch_cells};
|
||||
pub(crate) use select::{extend_selection, grow_select_all, select_cell_first, select_range};
|
||||
use select::{select_cells, select_column};
|
||||
pub use structure::split_targets;
|
||||
|
||||
@@ -279,3 +279,185 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Home › Paragraph › Borders with whole cells selected (the table, rows, columns or a block of
|
||||
/// cells): the border goes on the cells as one block, as in Word, not on the paragraphs in them
|
||||
/// (#7874). `all` borders every cell, `outside` the block's edges, `inside` the lines between its
|
||||
/// cells, `none` clears every side, and one side toggles along that edge of the block. Other kinds
|
||||
/// change nothing.
|
||||
pub(crate) fn cell_block_borders(s: &mut Session, range: &crate::CellRange, kind: &str, b: Border) -> CmdResult {
|
||||
let nil = Border { style: BorderStyle::None, width: 0.0, color: None, space: 0.0 };
|
||||
let b = Border { space: 0.0, ..b };
|
||||
let one_side = ["top", "left", "bottom", "right"].iter().position(|k| *k == kind);
|
||||
if one_side.is_none() && !matches!(kind, "all" | "none" | "outside" | "inside") {
|
||||
return sel_result(s);
|
||||
}
|
||||
let t = s.doc.table(range.story, &range.table).ok_or_else(|| CmdError::Disabled("the selection isn't in a table".into()))?;
|
||||
let (g0, g1) = range.cols;
|
||||
let picked = with_merge_runs(t, range.cells(t));
|
||||
// The selected cells' grid columns, row by row from the block's first row.
|
||||
let r0 = picked.iter().map(|&(r, _)| r).min().unwrap_or(range.rows.0);
|
||||
let mut spans: Vec<Vec<(usize, usize)>> = Vec::new();
|
||||
for &(r, c) in &picked {
|
||||
let i = r.saturating_sub(r0);
|
||||
if spans.len() <= i {
|
||||
spans.resize_with(i + 1, Vec::new);
|
||||
}
|
||||
spans[i].push(super::grid_cols(t, r, c));
|
||||
}
|
||||
// Whether a selected cell in row `r` covers any of grid columns `a..=z`.
|
||||
let picked_in = |r: Option<usize>, (a, z): (usize, usize)| {
|
||||
r.and_then(|r| r.checked_sub(r0)).and_then(|i| spans.get(i)).is_some_and(|row| row.iter().any(|&(sa, sz)| sa <= z && sz >= a))
|
||||
};
|
||||
// Each selected cell, and which of its sides (top, left, bottom, right) are on the block's edge:
|
||||
// above and below, where no selected cell lies across that side (a row that skips the selected
|
||||
// grid columns with `w:gridBefore` leaves a gap in the block). A row's first and last cells are
|
||||
// on it too when the row skips grid columns (`w:gridBefore`, `w:gridAfter`): the layout draws
|
||||
// those as the table's outer edge.
|
||||
let cells: Vec<(usize, usize, [bool; 4])> = picked
|
||||
.iter()
|
||||
.map(|&(r, c)| {
|
||||
let (a, z) = super::grid_cols(t, r, c);
|
||||
let last = t.rows.get(r).map_or(0, |row| row.cells.len().saturating_sub(1));
|
||||
(r, c, [!picked_in(r.checked_sub(1), (a, z)), a <= g0 || c == 0, !picked_in(Some(r + 1), (a, z)), z >= g1 || c >= last])
|
||||
})
|
||||
.collect();
|
||||
// Whether cell (`r`, `c`) draws a line on side `i`, its own or one the table or its style gives it.
|
||||
let resolved = wordcraft_layout::CellBorders::new(&s.doc, t);
|
||||
let draws = |r: usize, c: usize, i: usize| side(&resolved.of(r, c), i).is_some_and(|x| x.is_visible());
|
||||
// One side is taken off when a line already shows all along that edge, drawn by the cells
|
||||
// there or by cells beyond them that span the whole side, as the button toggles.
|
||||
let shown = one_side.is_some_and(|i| {
|
||||
cells.iter().filter(|(_, _, edge)| edge[i]).all(|&(r, c, _)| {
|
||||
if draws(r, c, i) {
|
||||
return true;
|
||||
}
|
||||
let across = beside(t, r, c, i, (g0, g1));
|
||||
if matches!(i, 1 | 3) {
|
||||
// The cell beside it in the row has the same height.
|
||||
return !across.is_empty() && across.into_iter().all(|(nr, nc)| draws(nr, nc, (i + 2) % 4));
|
||||
}
|
||||
// Above or below: the cells drawing the facing line must cover the side's grid
|
||||
// columns within the block, so a row that skips columns there leaves it uncovered.
|
||||
let (a, z) = super::grid_cols(t, r, c);
|
||||
let drawing = across.into_iter().filter(|&(nr, nc)| draws(nr, nc, (i + 2) % 4)).map(|(nr, nc)| super::grid_cols(t, nr, nc));
|
||||
covers(drawing.collect(), (a.max(g0), z.min(g1)))
|
||||
})
|
||||
});
|
||||
// The sides to set: (row, cell, side, border).
|
||||
let mut writes: Vec<(usize, usize, usize, Border)> = Vec::new();
|
||||
for (r, c, edge) in cells {
|
||||
for (i, on_edge) in edge.into_iter().enumerate() {
|
||||
let new = match kind {
|
||||
"all" => Some(b),
|
||||
"none" => Some(nil),
|
||||
"outside" if on_edge => Some(b),
|
||||
"inside" if !on_edge => Some(b),
|
||||
_ if one_side == Some(i) && on_edge => Some(if shown { nil } else { b }),
|
||||
_ => None,
|
||||
};
|
||||
let Some(new) = new else { continue };
|
||||
writes.push((r, c, i, new));
|
||||
// Each cell draws its own sides, so a line on the block's edge is also the facing
|
||||
// side of the cell beyond it: that gets the same border, or No Border would leave
|
||||
// the neighbour's line showing.
|
||||
if on_edge {
|
||||
writes.extend(beside(t, r, c, i, (g0, g1)).into_iter().map(|(nr, nc)| (nr, nc, (i + 2) % 4, new)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let t = s.doc.table_mut(range.story, &range.table)?;
|
||||
for (r, c, i, new) in writes {
|
||||
let Some(cl) = t.rows.get_mut(r).and_then(|row| row.cells.get_mut(c)) else { continue };
|
||||
let mut cur = cl.props.borders.unwrap_or_default();
|
||||
*side_mut(&mut cur, i) = Some(new);
|
||||
cl.props.borders = Some(cur);
|
||||
}
|
||||
touch_cells(s, &range.table)?;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Whether the grid column spans `parts` (first, last) cover every column of `a..=z`.
|
||||
fn covers(mut parts: Vec<(usize, usize)>, (a, z): (usize, usize)) -> bool {
|
||||
parts.sort_unstable();
|
||||
let mut next = a;
|
||||
for (pa, pz) in parts {
|
||||
if pa > next {
|
||||
break;
|
||||
}
|
||||
next = next.max(pz + 1);
|
||||
}
|
||||
next > z
|
||||
}
|
||||
|
||||
/// `cells` with the rest of each vertically merged cell's run: the merged cell is one cell over
|
||||
/// its rows, though selecting it from its first row takes in only that row.
|
||||
fn with_merge_runs(t: &Table, mut cells: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
|
||||
// The cell starting at grid column `g` of row `r`, when there is one.
|
||||
let at = |r: usize, g: usize| t.cell_at_grid(r, g).filter(|&c| t.grid_col(r, c) == g);
|
||||
let continues =
|
||||
|r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.props.vmerge == wordcraft_doc::props::VMerge::Continue);
|
||||
let mut seen: std::collections::HashSet<(usize, usize)> = cells.iter().copied().collect();
|
||||
let mut i = 0;
|
||||
while let Some(&(r, c)) = cells.get(i) {
|
||||
i += 1;
|
||||
let g = t.grid_col(r, c);
|
||||
let below = at(r + 1, g).filter(|&nc| continues(r + 1, nc)).map(|nc| (r + 1, nc));
|
||||
let above = r.checked_sub(1).filter(|_| continues(r, c)).and_then(|pr| at(pr, g).map(|pc| (pr, pc)));
|
||||
for next in [below, above].into_iter().flatten() {
|
||||
if seen.insert(next) {
|
||||
cells.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
cells
|
||||
}
|
||||
|
||||
/// The cells across side `i` (top, left, bottom, right) of cell (`r`, `c`) whose facing edge lies
|
||||
/// wholly on that line. Above and below, only cells within grid columns `cols` (the selected
|
||||
/// block's), so a wider cell's edge beyond the block keeps its line.
|
||||
fn beside(t: &Table, r: usize, c: usize, i: usize, (g0, g1): (usize, usize)) -> Vec<(usize, usize)> {
|
||||
let Some(row) = t.rows.get(r) else { return Vec::new() };
|
||||
match i {
|
||||
1 => c.checked_sub(1).map(|p| vec![(r, p)]).unwrap_or_default(),
|
||||
3 => {
|
||||
if c + 1 < row.cells.len() {
|
||||
vec![(r, c + 1)]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let nr = if i == 0 { r.checked_sub(1) } else { Some(r + 1) };
|
||||
let Some((nr, next)) = nr.and_then(|nr| t.rows.get(nr).map(|x| (nr, x))) else { return Vec::new() };
|
||||
let (a, z) = super::grid_cols(t, r, c);
|
||||
(0..next.cells.len())
|
||||
.filter(|&nc| {
|
||||
let (na, nz) = super::grid_cols(t, nr, nc);
|
||||
na <= z && nz >= a && na >= g0 && nz <= g1
|
||||
})
|
||||
.map(|nc| (nr, nc))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Side `i` of `b`: top, left, bottom, right.
|
||||
fn side(b: &Borders, i: usize) -> Option<Border> {
|
||||
match i {
|
||||
0 => b.top,
|
||||
1 => b.left,
|
||||
2 => b.bottom,
|
||||
_ => b.right,
|
||||
}
|
||||
}
|
||||
|
||||
/// Side `i` of `b` to set: top, left, bottom, right.
|
||||
fn side_mut(b: &mut Borders, i: usize) -> &mut Option<Border> {
|
||||
match i {
|
||||
0 => &mut b.top,
|
||||
1 => &mut b.left,
|
||||
2 => &mut b.bottom,
|
||||
_ => &mut b.right,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,9 +116,9 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
std::mem::take(&mut revised.body)
|
||||
};
|
||||
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Insert, author: author.clone(), date: date.clone(), move_name: None });
|
||||
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Insert, author.clone(), date.clone()));
|
||||
let ins = (s.doc.revisions.len() - 1) as u32;
|
||||
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Delete, author: author.clone(), date: date.clone(), move_name: None });
|
||||
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, author.clone(), date.clone()));
|
||||
let del = (s.doc.revisions.len() - 1) as u32;
|
||||
let mut char_fallbacks = 0usize;
|
||||
let mut table_fallbacks = 0usize;
|
||||
@@ -1437,10 +1437,10 @@ fn diff_table(
|
||||
|
||||
/// Find or create the formatting revision entry for `author` and `date`.
|
||||
fn format_revision(doc: &mut Document, author: &str, date: &str) -> u32 {
|
||||
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.date == date) {
|
||||
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.instant() == date) {
|
||||
return u32::try_from(i).unwrap_or(u32::MAX);
|
||||
}
|
||||
doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Format, author: author.to_string(), date: date.to_string(), move_name: None });
|
||||
doc.revisions.push(crate::cmd::made_revision(RevisionKind::Format, author.to_string(), date.to_string()));
|
||||
u32::try_from(doc.revisions.len().saturating_sub(1)).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
|
||||
@@ -2775,6 +2775,7 @@ fn compare_strips_source_revisions_from_adopted_notes() {
|
||||
author: "Other".into(),
|
||||
date: "2026-01-01T00:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
for part in rev.doc.parts.values_mut() {
|
||||
if part.kind == wordcraft_doc::PartKind::Footnote
|
||||
|
||||
@@ -98,6 +98,15 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// A UTC date and time (a `Z` or an offset) as Word writes `w:date`: the wall-clock time in the
|
||||
/// zone `zone` gives for an instant (seconds east of UTC), with a `Z` Word writes but doesn't
|
||||
/// mean. Word read the UTC dates WordCraft wrote as local time, shifted by the user's offset from
|
||||
/// UTC (#6851). None for anything else (no zone or no time of day, before 1970, unreadable).
|
||||
pub(crate) fn word_date(date: &str, zone: impl Fn(u64) -> i64) -> Option<String> {
|
||||
let utc = u64::try_from(chrono::DateTime::parse_from_rfc3339(date.trim()).ok()?.timestamp()).ok()?;
|
||||
Some(crate::cmd::iso_from_unix_secs(utc.checked_add_signed(zone(utc))?))
|
||||
}
|
||||
|
||||
/// How a page image is drawn: the printed page, headers and footers at full strength, tracked
|
||||
/// changes marked as Track Changes Options mark them. One place for `file.exportPng`,
|
||||
/// `file.strictReport`'s page check and a downloaded page image.
|
||||
@@ -134,9 +143,45 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
/// New York in 2026: daylight saving time from 8 March 07:00 UTC to 1 November 06:00 UTC.
|
||||
pub(crate) fn new_york(t: u64) -> i64 {
|
||||
if (1_772_953_200..1_793_512_800).contains(&t) { -4 * 3600 } else { -5 * 3600 }
|
||||
}
|
||||
|
||||
/// Word dates `w:date` in local wall-clock time with a `Z`; the change keeps UTC (#6851).
|
||||
#[test]
|
||||
fn word_dates_tracked_changes_in_local_time() {
|
||||
let plus8 = |_| 8 * 3600;
|
||||
// The issue's edit: 08:33:24 UTC at UTC+8, which Word showed as 8:33 AM.
|
||||
assert_eq!(word_date("2026-11-16T08:33:24Z", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
|
||||
// A date naming its offset is that instant, whatever the zone.
|
||||
assert_eq!(word_date("2026-11-16T16:33:24+08:00", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
|
||||
// West of UTC, the date can go back a day.
|
||||
assert_eq!(word_date("2026-01-01T03:00:00Z", new_york).as_deref(), Some("2025-12-31T22:00:00Z"));
|
||||
|
||||
// The repeated hour: 05:30 and 06:30 UTC are both 01:30 in New York; `dateUtc` keeps them
|
||||
// apart. Either side of a change of offset takes the offset at that instant.
|
||||
assert_eq!(word_date("2026-11-01T05:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
|
||||
assert_eq!(word_date("2026-11-01T06:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
|
||||
assert_eq!(word_date("2026-11-01T04:30:00Z", new_york).as_deref(), Some("2026-11-01T00:30:00Z"));
|
||||
assert_eq!(word_date("2026-11-01T07:30:00Z", new_york).as_deref(), Some("2026-11-01T02:30:00Z"));
|
||||
assert_eq!(word_date("2026-03-08T06:30:00Z", new_york).as_deref(), Some("2026-03-08T01:30:00Z"));
|
||||
assert_eq!(word_date("2026-03-08T07:30:00Z", new_york).as_deref(), Some("2026-03-08T03:30:00Z"));
|
||||
|
||||
// Anything else is left as it is: no zone, no time of day, before 1970, not a date.
|
||||
for date in ["", "2026-11-16T08:33:24", "2026-11-16", "1969-12-31T23:00:00Z", "yesterday", "2026-13-01T00:00:00Z"] {
|
||||
assert_eq!(word_date(date, plus8), None, "{date:?}");
|
||||
}
|
||||
// A hostile zone or a far date doesn't overflow.
|
||||
for zone in [i64::MAX, i64::MIN] {
|
||||
let _ = word_date("2026-11-16T08:33:24Z", |_| zone);
|
||||
}
|
||||
assert!(word_date("9999-12-31T23:59:59Z", plus8).is_some());
|
||||
}
|
||||
|
||||
/// A page image is the printed page: headers and footers draw at full strength (#6267).
|
||||
#[test]
|
||||
fn a_page_image_draws_headers_at_full_strength() {
|
||||
|
||||
@@ -17,6 +17,7 @@ mod find_apostrophes;
|
||||
mod fit_one_page;
|
||||
mod font_sizes;
|
||||
mod fonts;
|
||||
mod home_borders_cells;
|
||||
mod ime_noop;
|
||||
mod page_number_formats_in_lists;
|
||||
mod para_tools;
|
||||
@@ -15446,7 +15447,7 @@ fn sectioned_revision(delete: bool) -> Session {
|
||||
run(&mut s, "caret.set", json!({"pos": {"block": 2, "off": 0}}));
|
||||
run(&mut s, "para.style", json!({"style": "Heading1"}));
|
||||
let kind = if delete { RevisionKind::Delete } else { RevisionKind::Insert };
|
||||
s.doc.revisions.push(Revision { kind, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
s.doc.revisions.push(Revision { kind, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
s.doc.last_section.margin_left = 72.0;
|
||||
let mut sect = s.doc.last_section.clone();
|
||||
sect.margin_left = 144.0;
|
||||
@@ -15651,3 +15652,63 @@ fn a_range_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
|
||||
assert!(c.ins.is_some(), "Paste Formatting kept the insertion mark");
|
||||
assert_eq!(c.bold, Some(true));
|
||||
}
|
||||
|
||||
/// #8068: A text box reachable only inside nested shape groups survives mutating Session commands
|
||||
/// (which call `prune_text_boxes`) and copy/paste adoption, while an unreachable box is pruned.
|
||||
#[test]
|
||||
fn nested_group_text_box_survives_mutating_session_commands() {
|
||||
use wordcraft_doc::para::{GroupChild, InlineObject, ShapeKind};
|
||||
use wordcraft_doc::{CharProps, Document, Paragraph, PartKind, Path, para_block};
|
||||
|
||||
let mut d = Document::from_text("body");
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let nested_tb = d.add_part(PartKind::TextBox, para_of("nested group box"));
|
||||
let orphan_tb = d.add_part(PartKind::TextBox, para_of("orphan box"));
|
||||
|
||||
let shape = InlineObject::Shape {
|
||||
kind: ShapeKind::TextBox,
|
||||
w: 50.0,
|
||||
h: 20.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story: Some(nested_tb),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
};
|
||||
let group = |obj: InlineObject| InlineObject::Group {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
float: Default::default(),
|
||||
ch_w: 100.0,
|
||||
ch_h: 100.0,
|
||||
children: vec![GroupChild { x: 0.0, y: 0.0, obj }],
|
||||
canvas: None,
|
||||
};
|
||||
d.insert_object(&Pos::body(0, 0), group(group(shape)), &CharProps::default()).unwrap();
|
||||
|
||||
let mut s = Session::new(d);
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": " edited"}));
|
||||
|
||||
assert!(s.doc.parts.contains_key(&nested_tb), "nested group text box must survive prune");
|
||||
assert!(!s.doc.parts.contains_key(&orphan_tb), "unreachable text box must still be pruned");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(nested_tb)), "nested group box");
|
||||
let objs = &s.doc.para(StoryRef::Body, &Path::top(0)).unwrap().objects;
|
||||
assert_eq!(objs.len(), 1);
|
||||
assert_eq!(objs[0].text_boxes(), vec![nested_tb]);
|
||||
|
||||
// Copy/paste adopts the nested-group text box into a fresh story via text_box_slots() and survives prune.
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
let ids: Vec<u32> = s.doc.para(StoryRef::Body, &Path::top(0)).unwrap().objects.iter().flat_map(InlineObject::text_boxes).collect();
|
||||
assert_eq!(ids.len(), 2, "original and pasted nested groups each hold a text box");
|
||||
assert_ne!(ids[0], ids[1], "pasted nested group box gets its own story id");
|
||||
for id in ids {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
//! #7874: Home › Paragraph › Borders with whole table cells selected borders the cells as a
|
||||
//! block, as Word does, instead of each paragraph in them.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::props::{Border, Borders};
|
||||
use wordcraft_doc::{Block, Cell, Document, Paragraph, Path, Pos, StoryRef, Table, para_block};
|
||||
|
||||
use crate::{Selection, Session};
|
||||
|
||||
/// A document of a 3 x 3 table with text in every cell, the caret in the first cell.
|
||||
fn doc() -> Session {
|
||||
let mut t = Table::new(3, 3, 300.0);
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
cell.blocks = Cell::with_text(&format!("c{r}{c}")).blocks;
|
||||
}
|
||||
}
|
||||
let mut d = Document::new();
|
||||
d.body = vec![Arc::new(Block::Table(t)), para_block(Paragraph::new())];
|
||||
let mut s = Session::new(d);
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0));
|
||||
s
|
||||
}
|
||||
|
||||
fn table(s: &Session) -> &Table {
|
||||
s.doc.body.iter().find_map(|b| b.as_table()).unwrap()
|
||||
}
|
||||
|
||||
fn cell_borders(s: &Session, r: usize, c: usize) -> Borders {
|
||||
table(s).rows[r].cells[c].props.borders.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Which sides of cell (`r`, `c`) the layout draws a line on, the table style's lines included:
|
||||
/// top, left, bottom, right.
|
||||
fn drawn(s: &Session, r: usize, c: usize) -> [bool; 4] {
|
||||
let b = wordcraft_layout::cell_borders(&s.doc, table(s), r, c);
|
||||
[b.top, b.left, b.bottom, b.right].map(|x| x.is_some_and(|x| x.is_visible()))
|
||||
}
|
||||
|
||||
/// Which sides of cell (`r`, `c`) show a line: top, left, bottom, right.
|
||||
fn shown(s: &Session, r: usize, c: usize) -> [bool; 4] {
|
||||
let b = cell_borders(s, r, c);
|
||||
[b.top, b.left, b.bottom, b.right].map(|x| x.is_some_and(|x| x.is_visible()))
|
||||
}
|
||||
|
||||
/// Whether any paragraph in the table has borders of its own.
|
||||
fn para_borders(s: &Session) -> bool {
|
||||
table(s).rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).any(|p| p.props.borders.is_some())
|
||||
}
|
||||
|
||||
fn borders(s: &mut Session, kind: &str) {
|
||||
s.run("para.borders", &json!({"kind": kind})).unwrap();
|
||||
}
|
||||
|
||||
/// Select whole cells: rows `rows` and grid columns `cols` of the table.
|
||||
fn select(s: &mut Session, rows: (usize, usize), cols: (usize, usize)) {
|
||||
crate::cmd::table::select_range(s, StoryRef::Body, &Path(vec![0]), rows, cols).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_borders_on_a_selected_table_borders_every_cell() {
|
||||
let mut s = doc();
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "all");
|
||||
for r in 0..3 {
|
||||
for c in 0..3 {
|
||||
assert_eq!(shown(&s, r, c), [true; 4], "cell ({r}, {c}) has a line on every side");
|
||||
}
|
||||
}
|
||||
assert!(!para_borders(&s), "the paragraphs in the cells get no borders of their own");
|
||||
// The line is the one asked for, with no paragraph spacing.
|
||||
let top = cell_borders(&s, 1, 1).top.unwrap();
|
||||
assert_eq!((top.width, top.space), (0.5, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_and_inside_borders_follow_the_selected_block() {
|
||||
let mut s = doc();
|
||||
// The top-left 2 x 2 cells.
|
||||
select(&mut s, (0, 1), (0, 1));
|
||||
borders(&mut s, "outside");
|
||||
assert_eq!(shown(&s, 0, 0), [true, true, false, false]);
|
||||
assert_eq!(shown(&s, 0, 1), [true, false, false, true]);
|
||||
assert_eq!(shown(&s, 1, 0), [false, true, true, false]);
|
||||
assert_eq!(shown(&s, 1, 1), [false, false, true, true]);
|
||||
assert_eq!(table(&s).rows[2].cells[2].props.borders, None, "a cell outside the selection is left alone");
|
||||
// The cells beyond the block share its edge lines: their facing sides get the same line.
|
||||
assert_eq!(shown(&s, 0, 2), [false, true, false, false]);
|
||||
assert_eq!(shown(&s, 2, 0), [true, false, false, false]);
|
||||
borders(&mut s, "inside");
|
||||
assert_eq!(shown(&s, 0, 0), [true; 4]);
|
||||
assert_eq!(shown(&s, 1, 1), [true; 4]);
|
||||
assert_eq!(shown(&s, 0, 2), [false, true, false, false], "Inside leaves the cells beyond the block alone");
|
||||
assert!(!para_borders(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_border_on_a_row_clears_the_lines_it_shares_with_the_rows_around_it() {
|
||||
let mut s = doc();
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "all");
|
||||
select(&mut s, (1, 1), (0, 2));
|
||||
borders(&mut s, "none");
|
||||
for c in 0..3 {
|
||||
// Each cell draws its own sides, so the rows above and below must not keep the lines.
|
||||
assert_eq!(shown(&s, 0, c), [true, true, false, true], "the row above keeps its other lines, cell (0, {c})");
|
||||
assert_eq!(shown(&s, 1, c), [false; 4], "cell (1, {c})");
|
||||
assert_eq!(shown(&s, 2, c), [false, true, true, true], "the row below keeps its other lines, cell (2, {c})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_that_skips_grid_columns_has_its_first_cell_on_the_outside() {
|
||||
let mut s = doc();
|
||||
// The middle row starts at grid column 1 (`w:gridBefore`): two cells.
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[1].cells.remove(0);
|
||||
tb.rows[1].props.grid_before = 1;
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "none");
|
||||
borders(&mut s, "outside");
|
||||
assert_eq!(shown(&s, 1, 0), [false, true, false, false], "the row's first cell is on the table's left edge");
|
||||
assert_eq!(shown(&s, 1, 1), [false, false, false, true]);
|
||||
borders(&mut s, "none");
|
||||
borders(&mut s, "inside");
|
||||
assert_eq!(shown(&s, 1, 0), [true, false, true, true], "Inside leaves the row's outer edge without a line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_side_toggles_along_the_block_edge_and_no_border_clears_the_cells() {
|
||||
let mut s = doc();
|
||||
// The middle row, with no line on it or around it.
|
||||
select(&mut s, (1, 1), (0, 2));
|
||||
borders(&mut s, "none");
|
||||
borders(&mut s, "bottom");
|
||||
for c in 0..3 {
|
||||
assert_eq!(shown(&s, 1, c), [false, false, true, false], "cell (1, {c})");
|
||||
}
|
||||
borders(&mut s, "bottom");
|
||||
for c in 0..3 {
|
||||
assert_eq!(shown(&s, 1, c), [false; 4], "the second press takes the bottom line off cell (1, {c})");
|
||||
}
|
||||
borders(&mut s, "all");
|
||||
borders(&mut s, "none");
|
||||
let nil = |x: Option<Border>| x.is_some_and(|x| !x.is_visible());
|
||||
for c in 0..3 {
|
||||
let b = cell_borders(&s, 1, c);
|
||||
assert!(
|
||||
nil(b.top) && nil(b.left) && nil(b.bottom) && nil(b.right),
|
||||
"No Border writes no line on every side of cell (1, {c}), over the table's own borders"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_in_a_cell_still_borders_its_paragraph() {
|
||||
let mut s = doc();
|
||||
borders(&mut s, "all");
|
||||
assert!(para_borders(&s), "without whole cells selected, the paragraph is bordered as before");
|
||||
assert_eq!(table(&s).rows[0].cells[0].props.borders, None);
|
||||
}
|
||||
|
||||
/// A line the table's style draws counts as shown: the first press of one side takes it off,
|
||||
/// from the cells along the edge and the ones beyond it, and the second puts it back.
|
||||
#[test]
|
||||
fn one_side_takes_off_a_line_the_table_style_draws() {
|
||||
let mut s = doc();
|
||||
assert!(table(&s).rows[1].cells.iter().all(|c| c.props.borders.is_none()), "no cell has borders of its own");
|
||||
assert!((0..3).all(|c| drawn(&s, 1, c)[2]), "Table Grid draws the middle row's bottom line");
|
||||
select(&mut s, (1, 1), (0, 2));
|
||||
borders(&mut s, "bottom");
|
||||
for c in 0..3 {
|
||||
assert!(!drawn(&s, 1, c)[2] && !drawn(&s, 2, c)[0], "the first press takes the line off cell (1, {c})");
|
||||
assert!(drawn(&s, 1, c)[0], "the other sides keep the style's lines, cell (1, {c})");
|
||||
}
|
||||
borders(&mut s, "bottom");
|
||||
assert!((0..3).all(|c| drawn(&s, 1, c)[2]), "the second press puts it back");
|
||||
}
|
||||
|
||||
/// A column whose middle row skips it (`w:gridBefore`) is two blocks of cells: the cells above
|
||||
/// and below the gap face it with an outer edge, not an inside one.
|
||||
#[test]
|
||||
fn a_column_with_a_skipped_middle_cell_has_outer_edges_at_the_gap() {
|
||||
let mut s = doc();
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[1].cells.remove(0);
|
||||
tb.rows[1].props.grid_before = 1;
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "none");
|
||||
// The first grid column: cells (0, 0) and (2, 0); the middle row has no cell there.
|
||||
select(&mut s, (0, 2), (0, 0));
|
||||
borders(&mut s, "outside");
|
||||
assert_eq!(shown(&s, 0, 0), [true; 4], "Outside draws the bottom of the cell above the gap");
|
||||
assert_eq!(shown(&s, 2, 0), [true; 4], "and the top of the cell below it");
|
||||
borders(&mut s, "none");
|
||||
borders(&mut s, "inside");
|
||||
assert_eq!(shown(&s, 0, 0), [false; 4], "Inside has no line between cells that don't meet");
|
||||
assert_eq!(shown(&s, 2, 0), [false; 4]);
|
||||
}
|
||||
|
||||
/// A line drawn along only part of an edge isn't shown along it: the press completes it. Here
|
||||
/// the selected cell spans the three cells below it, and only the first of them draws its top.
|
||||
#[test]
|
||||
fn one_side_completes_a_line_drawn_along_part_of_the_edge() {
|
||||
let mut s = doc();
|
||||
let nil = Border { style: wordcraft_doc::props::BorderStyle::None, width: 0.0, color: None, space: 0.0 };
|
||||
let line = Border { style: wordcraft_doc::props::BorderStyle::Single, width: 0.5, color: None, space: 0.0 };
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[0].cells.truncate(1);
|
||||
tb.rows[0].cells[0].props.span = 3;
|
||||
tb.rows[0].cells[0].props.borders = Some(Borders { bottom: Some(nil), ..Default::default() });
|
||||
for (c, cell) in tb.rows[1].cells.iter_mut().enumerate() {
|
||||
cell.props.borders = Some(Borders { top: Some(if c == 0 { line } else { nil }), ..Default::default() });
|
||||
}
|
||||
select(&mut s, (0, 0), (0, 2));
|
||||
borders(&mut s, "bottom");
|
||||
assert!(drawn(&s, 0, 0)[2], "the line goes all along the selected cell's bottom");
|
||||
assert!((0..3).all(|c| drawn(&s, 1, c)[0]), "and along the tops of the cells below");
|
||||
}
|
||||
|
||||
/// A cell merged over two rows is one cell: selected from its first row, No Border clears its
|
||||
/// outline in the second row too.
|
||||
#[test]
|
||||
fn no_border_clears_all_of_a_vertically_merged_cell() {
|
||||
use wordcraft_doc::props::VMerge;
|
||||
let mut s = doc();
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[0].cells[1].props.vmerge = VMerge::Restart;
|
||||
tb.rows[1].cells[1].props.vmerge = VMerge::Continue;
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "all");
|
||||
// The merged cell, as selecting it from its first row selects it.
|
||||
select(&mut s, (0, 0), (1, 1));
|
||||
borders(&mut s, "none");
|
||||
assert_eq!(shown(&s, 0, 1), [false; 4]);
|
||||
assert_eq!(shown(&s, 1, 1), [false; 4], "the merged cell's second row keeps no line");
|
||||
assert!(shown(&s, 1, 0)[1] && shown(&s, 2, 1)[2], "the cells around it keep their other lines");
|
||||
}
|
||||
|
||||
/// The cells below draw a line along only part of the edge when their row skips the rest of its
|
||||
/// columns (`w:gridAfter`): the press completes it.
|
||||
#[test]
|
||||
fn one_side_completes_a_line_over_a_row_that_skips_columns() {
|
||||
let mut s = doc();
|
||||
let nil = Border { style: wordcraft_doc::props::BorderStyle::None, width: 0.0, color: None, space: 0.0 };
|
||||
let line = Border { style: wordcraft_doc::props::BorderStyle::Single, width: 0.5, color: None, space: 0.0 };
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[0].cells.truncate(1);
|
||||
tb.rows[0].cells[0].props.span = 3;
|
||||
tb.rows[0].cells[0].props.borders = Some(Borders { bottom: Some(nil), ..Default::default() });
|
||||
tb.rows[1].cells.truncate(1);
|
||||
tb.rows[1].props.grid_after = 2;
|
||||
tb.rows[1].cells[0].props.borders = Some(Borders { top: Some(line), ..Default::default() });
|
||||
select(&mut s, (0, 0), (0, 2));
|
||||
borders(&mut s, "bottom");
|
||||
assert!(drawn(&s, 0, 0)[2], "the selected cell's bottom gets the line all along it");
|
||||
}
|
||||
@@ -429,6 +429,7 @@ fn tracked_separator_session(slot: Slot) -> Session {
|
||||
author: "Alice".into(),
|
||||
date: String::new(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
let props = wordcraft_doc::CharProps { ins: Some(0), ..Default::default() };
|
||||
let p = wordcraft_doc::Paragraph::with_text("SEP", props);
|
||||
|
||||
@@ -30,17 +30,27 @@ pub fn import_flat_on(bytes: &[u8], page: &SectionProps) -> Result<Document, Str
|
||||
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`
|
||||
/// means UTC), so a tracked change is dated by its UTC time where it is known: its `date` is the
|
||||
/// local wall-clock time Word writes in `w:date` (#6851).
|
||||
fn odf_model(doc: &Document) -> Result<craft_wordmodel::Document, String> {
|
||||
let mut shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
|
||||
for r in &mut shared.revisions {
|
||||
if let Some(utc) = &r.date_utc {
|
||||
r.date = utc.clone();
|
||||
}
|
||||
}
|
||||
Ok(shared)
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> Result<Vec<u8>, String> {
|
||||
let shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
|
||||
craft_odf::text::export(&shared)
|
||||
craft_odf::text::export(&odf_model(doc)?)
|
||||
}
|
||||
|
||||
pub fn export_template(doc: &Document) -> Result<Vec<u8>, String> {
|
||||
let shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
|
||||
craft_odf::text::export_template(&shared)
|
||||
craft_odf::text::export_template(&odf_model(doc)?)
|
||||
}
|
||||
|
||||
pub fn export_flat(doc: &Document) -> Result<Vec<u8>, String> {
|
||||
let shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
|
||||
craft_odf::text::export_flat(&shared)
|
||||
craft_odf::text::export_flat(&odf_model(doc)?)
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ pub use fields::FieldCtx;
|
||||
pub use hit::VisualStep;
|
||||
pub use missing::{MetafileTextLayout, layout_metafile_text};
|
||||
pub use para::{LineEnd, ParaLayout};
|
||||
pub use table::{autofit_widths, cell_margins, measure_table_columns};
|
||||
pub use table::{CellBorders, autofit_widths, cell_borders, cell_margins, measure_table_columns};
|
||||
|
||||
mod boxes;
|
||||
mod cache;
|
||||
|
||||
+92
-39
@@ -350,6 +350,95 @@ fn region_borders(parts: &[(TablePart, Borders)], rows: (usize, usize), edges: (
|
||||
wordcraft_doc::styles::part_borders(parts, rows, edges)
|
||||
}
|
||||
|
||||
/// The table's outer and inside borders: the style's, overlaid by the table's own side by side.
|
||||
fn table_borders(t: &Table, style: Option<&TableStyleProps>) -> Borders {
|
||||
let mut tborders = style.and_then(|s| s.parts.borders).unwrap_or_default();
|
||||
if let Some(own) = t.props.borders {
|
||||
tborders.overlay(&own);
|
||||
}
|
||||
tborders
|
||||
}
|
||||
|
||||
/// The borders the layout draws for cell `ci` of row `ri`, before a right-to-left table mirrors
|
||||
/// them: the cell's own, then its row's table property exceptions, then the table style's
|
||||
/// conditional parts it is in, then the table's outer or inside borders. Home › Borders toggles
|
||||
/// on these, so a line the table style shows counts as shown (#7874). For many cells of one
|
||||
/// table, [`CellBorders`] resolves the table's part once.
|
||||
pub fn cell_borders(doc: &wordcraft_doc::Document, t: &Table, ri: usize, ci: usize) -> Borders {
|
||||
CellBorders::new(doc, t).of(ri, ci)
|
||||
}
|
||||
|
||||
/// [`cell_borders`] for the cells of one table: its style, borders and grid width resolved once.
|
||||
pub struct CellBorders<'a> {
|
||||
t: &'a Table,
|
||||
style: Option<TableStyleProps>,
|
||||
tborders: Borders,
|
||||
ncols: usize,
|
||||
}
|
||||
|
||||
impl<'a> CellBorders<'a> {
|
||||
pub fn new(doc: &wordcraft_doc::Document, t: &'a Table) -> Self {
|
||||
let style = t.props.style.as_deref().and_then(|id| doc.styles.table_style(id));
|
||||
let tborders = table_borders(t, style.as_ref());
|
||||
CellBorders { t, style, tborders, ncols: grid_cols(t).max(1) }
|
||||
}
|
||||
|
||||
/// The borders cell `ci` of row `ri` draws, as [`cell_borders`] gives them.
|
||||
pub fn of(&self, ri: usize, ci: usize) -> Borders {
|
||||
let t = self.t;
|
||||
let Some(cell) = t.rows.get(ri).and_then(|row| row.cells.get(ci)) else { return Borders::default() };
|
||||
let (g, span) = (t.grid_col(ri, ci), cell.span());
|
||||
let look = self.style.as_ref().map(|st| region_look(st, region_of(t, Some(st), ri, g, span, self.ncols)));
|
||||
resolved_cell_borders(t, ri, ci, (g, span, self.ncols), look.as_ref().map(|l| l.borders.as_slice()), self.tborders)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`cell_borders`] for cell `ci` of row `ri`, which starts at grid column `g` and is `span`
|
||||
/// columns wide in a table of `ncols`, given its style `parts` and the table borders `tb`.
|
||||
fn resolved_cell_borders(
|
||||
t: &Table,
|
||||
ri: usize,
|
||||
ci: usize,
|
||||
(g, span, ncols): (usize, usize, usize),
|
||||
parts: Option<&[(TablePart, Borders)]>,
|
||||
tb: Borders,
|
||||
) -> Borders {
|
||||
let nrows = t.rows.len();
|
||||
let Some(row) = t.rows.get(ri) else { return Borders::default() };
|
||||
// Effective borders: cell > table (outer vs inside).
|
||||
let edge = |own: Option<Border>, outer: bool, outer_b: Option<Border>, inner_b: Option<Border>| own.or(if outer { outer_b } else { inner_b });
|
||||
let cb = row.cells.get(ci).and_then(|c| c.props.borders).unwrap_or_default();
|
||||
// A row's table property exceptions (`w:tblPrEx`) override the table's borders for its cells.
|
||||
let row_borders = row.props.exceptions.as_ref().and_then(|e| e.borders).unwrap_or_default();
|
||||
// A row that skips grid columns (`w:gridBefore`/`w:gridAfter`) has its edge at its own
|
||||
// first and last cell.
|
||||
let (first_g, last_g) = (g == row.first_grid(), g + span >= ncols.saturating_sub(row.grid_after()));
|
||||
let rb = parts.map(|p| region_borders(p, (ri, nrows), (first_g, last_g))).unwrap_or_default();
|
||||
Borders {
|
||||
top: edge(cb.top.or(if ri == 0 { row_borders.top } else { row_borders.between }).or(rb.top), ri == 0, tb.top, tb.between),
|
||||
bottom: edge(
|
||||
cb.bottom.or(if ri + 1 == nrows { row_borders.bottom } else { row_borders.between }).or(rb.bottom),
|
||||
ri + 1 == nrows,
|
||||
tb.bottom,
|
||||
tb.between,
|
||||
),
|
||||
left: edge(
|
||||
cb.left.or(if first_g { row_borders.left } else { row_borders.inside_v }).or(if first_g { rb.left } else { rb.inside_v }),
|
||||
first_g,
|
||||
tb.left,
|
||||
tb.inside_v,
|
||||
),
|
||||
right: edge(
|
||||
cb.right.or(if last_g { row_borders.right } else { row_borders.inside_v }).or(if last_g { rb.right } else { rb.inside_v }),
|
||||
last_g,
|
||||
tb.right,
|
||||
tb.inside_v,
|
||||
),
|
||||
between: None,
|
||||
inside_v: None,
|
||||
}
|
||||
}
|
||||
|
||||
struct CellBox {
|
||||
items: Vec<Placed>,
|
||||
h: f32,
|
||||
@@ -464,11 +553,7 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
|
||||
// indent); earlier modes line the first cell's text up with it instead.
|
||||
let margins_def = default_margins(t, style);
|
||||
let indent = t.props.indent.unwrap_or(0.0);
|
||||
// The style's borders, overlaid by the table's own side by side.
|
||||
let mut tborders = style.and_then(|s| s.parts.borders).unwrap_or_default();
|
||||
if let Some(own) = t.props.borders {
|
||||
tborders.overlay(&own);
|
||||
}
|
||||
let tborders = table_borders(t, style);
|
||||
let first_cell = t.rows.first().and_then(|r| r.cells.first());
|
||||
// A right-to-left table (`w:bidiVisual`) mirrors: its first column stands at the right, its
|
||||
// start alignment and indent are measured from the right margin, and each cell's start
|
||||
@@ -564,40 +649,8 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
|
||||
let mut cpath = path.to_vec();
|
||||
cpath.push(ri as u32);
|
||||
cpath.push(ci as u32);
|
||||
// Effective borders: cell > table (outer vs inside).
|
||||
let tb = tborders;
|
||||
let edge =
|
||||
|own: Option<Border>, outer: bool, outer_b: Option<Border>, inner_b: Option<Border>| own.or(if outer { outer_b } else { inner_b });
|
||||
let cb = cell.props.borders.unwrap_or_default();
|
||||
// A row's table property exceptions (`w:tblPrEx`) override the table's borders for its cells.
|
||||
let row_borders = row.props.exceptions.as_ref().and_then(|e| e.borders).unwrap_or_default();
|
||||
// A row that skips grid columns (`w:gridBefore`/`w:gridAfter`) has its edge at its own
|
||||
// first and last cell.
|
||||
let (first_g, last_g) = (g == row.first_grid(), g + span >= ncols.saturating_sub(row.grid_after()));
|
||||
let rb = look.map(|l| region_borders(&l.borders, (ri, nrows), (first_g, last_g))).unwrap_or_default();
|
||||
let mut borders = Borders {
|
||||
top: edge(cb.top.or(if ri == 0 { row_borders.top } else { row_borders.between }).or(rb.top), ri == 0, tb.top, tb.between),
|
||||
bottom: edge(
|
||||
cb.bottom.or(if ri + 1 == nrows { row_borders.bottom } else { row_borders.between }).or(rb.bottom),
|
||||
ri + 1 == nrows,
|
||||
tb.bottom,
|
||||
tb.between,
|
||||
),
|
||||
left: edge(
|
||||
cb.left.or(if first_g { row_borders.left } else { row_borders.inside_v }).or(if first_g { rb.left } else { rb.inside_v }),
|
||||
first_g,
|
||||
tb.left,
|
||||
tb.inside_v,
|
||||
),
|
||||
right: edge(
|
||||
cb.right.or(if last_g { row_borders.right } else { row_borders.inside_v }).or(if last_g { rb.right } else { rb.inside_v }),
|
||||
last_g,
|
||||
tb.right,
|
||||
tb.inside_v,
|
||||
),
|
||||
between: None,
|
||||
inside_v: None,
|
||||
};
|
||||
let parts = look.map(|l| l.borders.as_slice());
|
||||
let mut borders = resolved_cell_borders(t, ri, ci, (g, span, ncols), parts, tborders);
|
||||
// The logical start (left) and end (right) borders, drawn mirrored in an RTL table.
|
||||
if rtl {
|
||||
std::mem::swap(&mut borders.left, &mut borders.right);
|
||||
|
||||
@@ -2129,6 +2129,7 @@ fn a_deleted_list_items_number_is_drawn_as_deleted_text() {
|
||||
author: "Ana".into(),
|
||||
date: String::new(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
let id = std::sync::Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
|
||||
d.format_paragraphs(&Pos::body(1, 0), &Pos::body(1, 3), &|p| p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 })).unwrap();
|
||||
@@ -3955,6 +3956,7 @@ fn a_tracked_paragraph_mark_shows_in_its_authors_colour() {
|
||||
author: "Ana".into(),
|
||||
date: String::new(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
|
||||
let l = lay(&d);
|
||||
|
||||
@@ -426,7 +426,7 @@ mod tests {
|
||||
use wordcraft_doc::props::TextDirection;
|
||||
use wordcraft_doc::{CharProps, Document, Paragraph, Revision, RevisionKind, para_block};
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
let cp = CharProps { outline: Some(true), size: Some(20.0), ins: Some(0), ..Default::default() };
|
||||
d.body = vec![para_block(Paragraph::with_text("Inserted", cp))];
|
||||
let mut opts = DisplayOptions { markup: true, ..Default::default() };
|
||||
|
||||
@@ -337,8 +337,8 @@ fn hostile_documents_export() {
|
||||
fn tracked_deletions_are_left_out_without_markup() {
|
||||
use wordcraft_doc::{Revision, RevisionKind};
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
let mut p = Paragraph::with_text("Keep ", CharProps::default());
|
||||
let n = p.len();
|
||||
p.insert_text(n, "DELETEDTEXT ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
|
||||
@@ -360,8 +360,8 @@ fn markup_takes_the_track_changes_option_colours() {
|
||||
use wordcraft_doc::props::Rgb;
|
||||
use wordcraft_doc::{Revision, RevisionKind};
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
let mut p = Paragraph::with_text("Keep ", CharProps::default());
|
||||
let n = p.len();
|
||||
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
|
||||
@@ -411,8 +411,8 @@ fn markup_takes_the_track_changes_option_colours() {
|
||||
fn hidden_deletions_stay_out_of_markup_pdf() {
|
||||
use wordcraft_doc::{Revision, RevisionKind};
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
let mut p = Paragraph::with_text("Keep ", CharProps::default());
|
||||
let n = p.len();
|
||||
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
|
||||
@@ -440,7 +440,7 @@ fn hidden_deletions_stay_out_of_markup_pdf() {
|
||||
fn deleted_heading_text_stays_out_of_bookmarks_and_tags() {
|
||||
use wordcraft_doc::{Revision, RevisionKind};
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
let del = CharProps { del: Some(0), ..Default::default() };
|
||||
// "Intro SECRET Part" with "SECRET " deleted, then a heading deleted as a whole.
|
||||
let mut h = Paragraph::with_text("Intro ", CharProps::default()).styled("Heading1");
|
||||
|
||||
@@ -16,7 +16,7 @@ craft = { workspace = true, features = [
|
||||
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
|
||||
"text-find", "web-api", "web-host", "window",
|
||||
] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -76,7 +76,7 @@ craft-ui-test-kit = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui-testing"] }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", features = ["subset"] }
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
|
||||
|
||||
@@ -62,6 +62,10 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The least width of the in-place result list, in points: v0.19.1's popup, wide enough for a row's place and
|
||||
/// shortcut beside its name (#7983). The closed field is narrower (about 130).
|
||||
const SEARCH_POPUP_MIN_WIDTH: f32 = 350.0;
|
||||
|
||||
/// Opens the search where this window shows its field (the title bar, or Immersive's screen bar). `false`
|
||||
/// when it shows none: Focus hides it, so the Search dialog takes over.
|
||||
pub(crate) fn open(app: &mut WordApp) -> bool {
|
||||
@@ -101,6 +105,7 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
|
||||
let view = env.view();
|
||||
let cache = SearchCache::for_pass(kept, commands, &view);
|
||||
let out = CommandPalette::new(name.clone(), &cache.entries, &cache.index, Bind::bound(&mut open))
|
||||
.popup_min_width(SEARCH_POPUP_MIN_WIDTH)
|
||||
.face(if compact { PaletteFace::Dialog } else { PaletteFace::InPlace })
|
||||
.look(FieldLook::Quiet)
|
||||
.placeholder(Label::from(name.clone()))
|
||||
|
||||
@@ -12,13 +12,13 @@ use craft::ui::buttons::button::ButtonStyleKey;
|
||||
use craft::ui::buttons::icon_button::IconButtonStyleKey;
|
||||
use craft::ui::buttons::{Button, IconButton};
|
||||
use craft::ui::choice::Switch;
|
||||
use craft::ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::contract::{AfterInk, Bind, BodyCx, Props as _, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::display::{Divider, Text};
|
||||
use craft::ui::list::{UndoList, UndoMark, UndoRows, UndoWords, footer_text, undo_count};
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::popover::Popover;
|
||||
use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::runtime::env::{Env, with_env};
|
||||
use craft::ui::runtime::inspect;
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost};
|
||||
use craft::ui::shell::{Title, TitleBar};
|
||||
@@ -108,7 +108,15 @@ fn autosave(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
|
||||
let on = app.autosaves() && block.is_none();
|
||||
let tip = block.as_ref().map_or_else(|| tl!("AutoSave saves every change to the file (needs a saved document)").to_string(), |b| b.reason());
|
||||
// The small switch, as the old title bar drew it.
|
||||
let out = Switch::new(Bind::given(on)).label(tl!("AutoSave").to_string()).size(ControlSize::Sm).tooltip(TooltipSpec::new(tip)).show(ui);
|
||||
// The label is muted while AutoSave is off (#7681); craft keeps the full ink where muted would fall below text contrast.
|
||||
let ink = if on { AfterInk::Normal } else { AfterInk::Muted };
|
||||
let out = with_env(
|
||||
ui,
|
||||
|o| {
|
||||
o.values.set(ink);
|
||||
},
|
||||
|ui| Switch::new(Bind::given(on)).label(tl!("AutoSave").to_string()).size(ControlSize::Sm).tooltip(TooltipSpec::new(tip)).show(ui),
|
||||
);
|
||||
if out.response.clicked() {
|
||||
match block {
|
||||
None => {
|
||||
|
||||
@@ -39,13 +39,6 @@ pub(crate) use host::close_all;
|
||||
pub(crate) use mailings::{FilterRow, RecipientDraft, RecipientFilter, RecipientListDialog, hold_rows, merge_order, visible_recipients};
|
||||
pub(crate) use page_setup::PAPER_LABELS;
|
||||
|
||||
/// `max_rows` for a `TileGrid` that shows `rows` rows of `columns` tiles. The collection counts the cap in
|
||||
/// items (the tile `rows` in, not the grid row it is in), so a cap of `rows` shows one row; a cap past the item
|
||||
/// count adds blank rows, so it stops at `len`. lean: upstream fix in craft-libs `rows_height`, then drop this.
|
||||
pub(crate) fn tile_rows_cap(len: usize, columns: usize, rows: usize) -> u16 {
|
||||
u16::try_from(len.min(columns * rows)).unwrap_or(u16::MAX)
|
||||
}
|
||||
|
||||
/// Opens the dialog `name` for a script, a button or a command, with `params`; the module of the name reads what it
|
||||
/// needs of them. Returns the dialog's id, or `None` when no dialog opened (an unknown name, nothing to show, or a
|
||||
/// pane such as Restrict Editing).
|
||||
|
||||
@@ -13,7 +13,7 @@ use craft::ui::runtime::env::{Env, Label};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use wordcraft_render::icon_lib::{self, Category};
|
||||
|
||||
use super::host::{Asks, DialogHooks, Settle, WordForm, open_form, open_with};
|
||||
use super::host::{Asks, DialogHooks, Settle, WordForm, captioned, open_form, open_with};
|
||||
use super::{Value, WordApp};
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
@@ -110,16 +110,20 @@ impl StackDialog for BookmarkDialog {
|
||||
let (by_location, hidden, name) = (&mut self.by_location, &mut self.hidden, &mut self.name);
|
||||
let mut list = ListManager::new(Label::from(tl!("Bookmark")), Label::from(tl!("Bookmark name:")), entries, Self::actions(&words))
|
||||
.empty(Label::from(tl!("The document has no bookmarks yet.")))
|
||||
.framed(true)
|
||||
.cancel_last(true)
|
||||
.name_box(Bind::bound(name))
|
||||
.name_check(|n| wordcraft_engine::cmd::insert::bookmark_name_ok(n.trim()))
|
||||
.under_list(move |ui| {
|
||||
RadioGroup::new(Label::from(tl!("Sort by:")), Bind::bound(&mut *by_location)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, cx| {
|
||||
for (at, (value, label)) in [(false, "Name"), (true, "Location")].into_iter().enumerate() {
|
||||
let side = SideLabel::new().layout(FieldLayout::After);
|
||||
cx.labelled(ui, at, Label::from(tl!(label)), side, Radio::new(value));
|
||||
}
|
||||
});
|
||||
captioned(ui, Label::from(tl!("Sort by:")), |name, ui| {
|
||||
RadioGroup::new(name, Bind::bound(&mut *by_location)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, cx| {
|
||||
for (at, (value, label)) in [(false, "Name"), (true, "Location")].into_iter().enumerate() {
|
||||
let side = SideLabel::new().layout(FieldLayout::After);
|
||||
cx.labelled(ui, at, Label::from(tl!(label)), side, Radio::new(value));
|
||||
}
|
||||
});
|
||||
})
|
||||
});
|
||||
Checkbox::new(Bind::bound(&mut *hidden)).label(Label::from(tl!("Hidden bookmarks"))).show(ui);
|
||||
});
|
||||
|
||||
@@ -39,10 +39,9 @@ pub struct RecentSymbol {
|
||||
}
|
||||
|
||||
/// Characters per row of the Symbols map (Word's grid is 16 wide).
|
||||
// lean: the cap assumes this many columns; read the laid-out count if the map becomes resizable.
|
||||
const GRID_COLUMNS: usize = 16;
|
||||
/// Rows of the Symbols map shown before it scrolls.
|
||||
const GRID_ROWS: usize = 8;
|
||||
const GRID_ROWS: u16 = 8;
|
||||
|
||||
/// How many recent symbols are kept.
|
||||
pub const RECENT_SYMBOLS: usize = 20;
|
||||
@@ -703,7 +702,7 @@ fn glyph_grid(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
|
||||
let mut grid = TileGrid::new(word("Symbols"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
.max_rows(crate::dialogs::tile_rows_cap(form.chars.len(), GRID_COLUMNS, GRID_ROWS))
|
||||
.max_rows(GRID_ROWS)
|
||||
.card_columns(GRID_COLUMNS)
|
||||
.caption(CaptionPlace::None)
|
||||
.selection(Bind::bound(&mut selection));
|
||||
|
||||
@@ -321,7 +321,7 @@ fn layout_tiles(ui: &mut Ui, theme: &[Rgb], form: &mut SmartArtForm) -> bool {
|
||||
.card_columns(3)
|
||||
// Production's picker is three tile rows high and scrolls the rest; the cap also makes the grid the one owner
|
||||
// of its scroll inside the dialog's scrolling body.
|
||||
.max_rows(crate::dialogs::tile_rows_cap(shown.len(), 3, 3))
|
||||
.max_rows(3)
|
||||
.selection(Bind::given(Selection::single(current)))
|
||||
.show_items(ui, &keyed(&positions, |i| *i), &mut |key, _| {
|
||||
let layout = shown.get(*key).copied().unwrap_or_default();
|
||||
|
||||
@@ -70,6 +70,7 @@ impl StackDialog for MacrosDialog {
|
||||
let dialog = ListManager::new(tl!("Macros").to_string(), tl!("Macro name:").to_string(), self.entries.clone(), actions)
|
||||
.empty(Label::from(tl!("There are no macros yet. Record one to add it here.").to_string()))
|
||||
.cancel_label(tl!("Close").to_string())
|
||||
.framed(true)
|
||||
// PLAN: assumed `ListManager::name_box(self, Bind<'a, String>) -> Self` (dialogs-w5, S-L310)
|
||||
.name_box(Bind::bound(&mut self.name));
|
||||
let out = dialog.show(ui);
|
||||
|
||||
@@ -203,11 +203,11 @@ fn the_table_grid_previews_the_hovered_table_until_the_click() {
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, "Table").click();
|
||||
h.run_steps(3);
|
||||
// The row 3, column 4 square: the smallest node that names a 3-row, 4-column table. The framework's picker names
|
||||
// its squares "<rows> × <columns>".
|
||||
// its squares "<columns>x<rows> Table".
|
||||
let at = h
|
||||
.query_all(egui_kittest::kittest::By::new().label_contains("3 × 4"))
|
||||
.query_all(egui_kittest::kittest::By::new().label_contains("4x3 Table"))
|
||||
.min_by(|a, b| (a.rect().width() * a.rect().height()).total_cmp(&(b.rect().width() * b.rect().height())))
|
||||
.expect("the grid's 3 × 4 square")
|
||||
.expect("the grid's 4x3 square")
|
||||
.rect()
|
||||
.center();
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
@@ -218,7 +218,7 @@ fn the_table_grid_previews_the_hovered_table_until_the_click() {
|
||||
crate::canvas::page_doc(h.state()).body.iter().find_map(|b| b.as_table()).map(|t| (t.rows.len(), t.cols()))
|
||||
};
|
||||
assert_eq!(previewed(&h), Some((3, 4)), "three rows of four columns");
|
||||
assert!(h.query_all(egui_kittest::kittest::By::new().label_contains("3 × 4")).next().is_some(), "the label reads rows × columns");
|
||||
assert!(h.query_all(egui_kittest::kittest::By::new().label_contains("4x3 Table")).next().is_some(), "the label reads columns x rows");
|
||||
assert!(h.state().session.doc.body.iter().all(|b| b.as_table().is_none()) && !h.state().session.can_undo());
|
||||
h.event(egui::Event::PointerMoved(egui::pos2(1400.0, 880.0)));
|
||||
h.run_steps(3);
|
||||
|
||||
@@ -341,7 +341,7 @@ mod tests {
|
||||
// The ribbon's stacked label breaks the line after "Switch".
|
||||
// A split button's main part runs its command; its arrow part, the inner node of the same name (the label
|
||||
// and chevron), opens the menu.
|
||||
let at = h.query_all_by_label("Switch\nWindows").last().expect("the Switch Windows arrow").rect().center();
|
||||
let at = h.query_all_by_label("Switch Windows options").next().expect("the Switch Windows arrow").rect().center();
|
||||
// Pressed the way a person does, so the framework opens the menu: the pointer rests a frame over the arrow, and
|
||||
// the press and the release are frames of their own (kittest's `click` sends all three in one).
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
|
||||
@@ -236,7 +236,7 @@ fn symbols(ui: &mut Ui, app: &mut WordApp) {
|
||||
face: GalleryFace::Paint(paint),
|
||||
})
|
||||
.collect();
|
||||
let mut sets = |ui: &mut Ui| {
|
||||
let mut sets = |ui: &mut Ui, _: &mut BodyCx| {
|
||||
let mut chosen = None;
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
for (i, (name, _)) in SYMBOL_SETS.iter().enumerate() {
|
||||
|
||||
@@ -77,7 +77,7 @@ pub struct LangInfo {
|
||||
|
||||
/// The languages WordCraft offers, when their catalogs are embedded. English first: it is the
|
||||
/// fallback and the source language.
|
||||
pub static LANGUAGES: [LangInfo; 29] = [
|
||||
pub static LANGUAGES: [LangInfo; 30] = [
|
||||
LangInfo { code: "en", prefer_hans: false, editing_lang: None },
|
||||
// Simplified Chinese; `zh`, `zh-CN`, `zh-SG` and `zh-Hans-*` resolve here (the crate's matching).
|
||||
LangInfo { code: "zh-hans", prefer_hans: true, editing_lang: None },
|
||||
@@ -139,6 +139,9 @@ pub static LANGUAGES: [LangInfo; 29] = [
|
||||
// Bosnian, Latin script; `bs`, `bs-BA`, `bs_BA.UTF-8` and `bs-Latn-BA` resolve here. Cyrillic
|
||||
// Bosnian (`bs-Cyrl-*`) has no catalog, so it stays in English.
|
||||
LangInfo { code: "bs", prefer_hans: false, editing_lang: None },
|
||||
// Hindi, Devanagari script; `hi`, `hi-IN` and `hi_IN.UTF-8` resolve here. WordCraft doesn't proof
|
||||
// Hindi yet, so it doesn't set the language of new documents.
|
||||
LangInfo { code: "hi", prefer_hans: false, editing_lang: None },
|
||||
];
|
||||
|
||||
/// Interface languages written right to left. Their catalogs are written in typing order and
|
||||
@@ -255,7 +258,7 @@ impl Lang {
|
||||
/// Every registered language in the order a picker lists them: English first (the source
|
||||
/// language and the fallback), then the rest by their own name with accents folded, so
|
||||
/// Čeština sits under C rather than after Z. Names in other scripts follow the Latin ones in
|
||||
/// code point order: Greek, Cyrillic, Arabic, then the CJK languages.
|
||||
/// code point order: Greek, Cyrillic, Arabic, Devanagari, then the CJK languages.
|
||||
pub fn for_picker() -> Vec<Lang> {
|
||||
let mut rest: Vec<Lang> = Lang::all().filter(|l| l.code() != Lang::EN.code()).collect();
|
||||
rest.sort_by_cached_key(|l| name_sort_key(l.name()));
|
||||
|
||||
@@ -84,14 +84,6 @@ fn texts(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
/// Run a frame per entry of `steps` (its events), then a few quiet ones, and return every text
|
||||
/// drawn in the last.
|
||||
fn frames(ctx: &egui::Context, app: &mut WordApp, steps: Vec<Vec<egui::Event>>) -> Vec<String> {
|
||||
let mut drawn = Vec::new();
|
||||
for shape in draw_frames(ctx, app, steps) {
|
||||
texts(&shape.shape, &mut drawn);
|
||||
}
|
||||
drawn
|
||||
}
|
||||
|
||||
fn draw_frames(ctx: &egui::Context, app: &mut WordApp, steps: Vec<Vec<egui::Event>>) -> Vec<egui::epaint::ClippedShape> {
|
||||
// Wide enough that no ribbon tab overflows behind its scroll arrows.
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2560.0, 900.0));
|
||||
let mut drawn = Vec::new();
|
||||
@@ -109,9 +101,11 @@ fn draw_frames(ctx: &egui::Context, app: &mut WordApp, steps: Vec<Vec<egui::Even
|
||||
app.ui(ui);
|
||||
});
|
||||
note_global_names();
|
||||
// The audit reads shapes without rendering textures. Discard these deltas deliberately.
|
||||
drawn.clear();
|
||||
for s in &out.shapes {
|
||||
texts(&s.shape, &mut drawn);
|
||||
}
|
||||
out.textures_delta.clear();
|
||||
drawn = out.shapes;
|
||||
}
|
||||
drawn
|
||||
}
|
||||
@@ -381,27 +375,11 @@ fn runtime_data_is_exempt_and_wording_is_not() {
|
||||
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1, "the check went through the stub, not GitHub");
|
||||
}
|
||||
|
||||
/// Locate the pointer target from the visible face, not from a fixed pixel or command dispatch.
|
||||
fn painted_control(shapes: &[egui::epaint::ClippedShape], label: &str) -> egui::Pos2 {
|
||||
fn find(shape: &egui::Shape, clip: egui::Rect, label: &str) -> Option<egui::Pos2> {
|
||||
match shape {
|
||||
egui::Shape::Text(text) if text.galley.text() == label => {
|
||||
let bounds = text.visual_bounding_rect().intersect(clip);
|
||||
bounds.is_positive().then(|| bounds.center())
|
||||
}
|
||||
egui::Shape::Vec(children) => children.iter().find_map(|s| find(s, clip, label)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
shapes.iter().find_map(|s| find(&s.shape, s.clip_rect, label)).unwrap_or_else(|| panic!("ribbon face {label:?} is not painted"))
|
||||
}
|
||||
|
||||
/// Fails on interface text drawn without going through the catalog, listed per UI state, and
|
||||
/// prints the missing-translation report (`report_catalog_gaps`). `cargo xtask i18n-report` runs it
|
||||
/// with `--nocapture`; `cargo xtask test` and `ci` run it that way instead of in the main test run.
|
||||
/// It can also run with the other tests: input is synthetic and timed by `TIME`, Read Aloud never
|
||||
/// starts a speech thread, and process-wide names other tests change are gathered every frame.
|
||||
/// The daily audit also hovers and clicks every ribbon control.
|
||||
#[test]
|
||||
fn untranslated_interface_text() {
|
||||
let ctx = crate::test_harness::context();
|
||||
@@ -518,39 +496,8 @@ fn untranslated_interface_text() {
|
||||
let _ = app.run("ui.tab", json!({"tab": "Equation"}));
|
||||
let drawn = frame(&ctx, &mut app);
|
||||
record(&app, "tab Equation", drawn);
|
||||
// A composed ribbon face, a separately translated tooltip, and menu rows reached by a real click.
|
||||
// Start clean so a preceding contextual tab or dialog can't cover the pointer target.
|
||||
let ctx = crate::test_harness::context();
|
||||
super::embedded_host(&ctx);
|
||||
let mut app = pseudo_app(&ctx);
|
||||
app.run("ui.tab", json!({"tab": "References"})).unwrap();
|
||||
let title = crate::i18n::fmt(super::tr(super::Lang::PSEUDO, "Style: {style}"), &[("style", &app.session.bib_style)]);
|
||||
let shapes = draw_frames(&ctx, &mut app, Vec::new());
|
||||
let at = painted_control(&shapes, &title);
|
||||
let mut hover = vec![vec![egui::Event::PointerMoved(at)]];
|
||||
hover.resize_with(6, Vec::new);
|
||||
let hovered = frames(&ctx, &mut app, hover);
|
||||
assert!(hovered.iter().any(|t| t == "⟦Citation Style⟧"), "Citation Style tooltip was not translated");
|
||||
record(&app, "References › Citation Style hover", hovered);
|
||||
let drawn = frames(&ctx, &mut app, click(at, egui::PointerButton::Primary));
|
||||
assert!(drawn.iter().any(|t| t == "⟦Harvard (Anglia)⟧"), "click did not open the translated Citation Style menu");
|
||||
record(&app, "References › Citation Style click", drawn);
|
||||
if crate::test_harness::full_locale_audit() {
|
||||
audit_ribbon_controls(&tabs, &mut record);
|
||||
}
|
||||
super::apply_language(super::Lang::EN);
|
||||
let mut report = String::new();
|
||||
for (text, states) in &found {
|
||||
let mut states = states.clone();
|
||||
states.sort();
|
||||
states.dedup();
|
||||
report.push_str(&format!("{:?} [{}]\n", unmarked(text), states.join(", ")));
|
||||
}
|
||||
report_catalog_gaps(super::I18N.looked_up());
|
||||
assert!(found.is_empty(), "{} interface texts skip translation (wrap them in tl!):\n{report}", found.len());
|
||||
}
|
||||
|
||||
fn audit_ribbon_controls(tabs: &[&str], mut record: impl FnMut(&WordApp, &str, Vec<String>)) {
|
||||
// Every ribbon control on every tab, and whatever menu or dialog it opens. A fresh app per
|
||||
// tab keeps one tab's commands from changing the next.
|
||||
// A fresh app per control, set up the same way, so no click changes what the next one hits
|
||||
// (Escape, for one, leaves an equation and takes the Equation tab with it).
|
||||
let contextual = ["Table Design", "Table Layout", "Equation", "Chart Design", "SmartArt Design"];
|
||||
@@ -580,6 +527,16 @@ fn audit_ribbon_controls(tabs: &[&str], mut record: impl FnMut(&WordApp, &str, V
|
||||
record(&app, &format!("{tab} › click"), drawn);
|
||||
}
|
||||
}
|
||||
super::apply_language(super::Lang::EN);
|
||||
let mut report = String::new();
|
||||
for (text, states) in &found {
|
||||
let mut states = states.clone();
|
||||
states.sort();
|
||||
states.dedup();
|
||||
report.push_str(&format!("{:?} [{}]\n", unmarked(text), states.join(", ")));
|
||||
}
|
||||
report_catalog_gaps(super::I18N.looked_up());
|
||||
assert!(found.is_empty(), "{} interface texts skip translation (wrap them in tl!):\n{report}", found.len());
|
||||
}
|
||||
|
||||
/// The missing-translation report (craft-i18n's S3; `cargo xtask i18n-report`, part of `cargo xtask
|
||||
@@ -807,15 +764,16 @@ fn frame_at(ctx: &egui::Context, app: &mut WordApp, width: f32) -> Vec<(String,
|
||||
drawn
|
||||
}
|
||||
|
||||
/// The Arabic interface is mirrored: reading starts at the right. The daily audit also renders
|
||||
/// every tab at several widths, every File page, dialog and pane, and exercises the context menu
|
||||
/// and ribbon controls right to left.
|
||||
/// The Arabic interface is mirrored: reading starts at the right. And nothing in it can panic:
|
||||
/// every tab (wide, and narrow enough to scroll), File page, dialog, pane, context menu and
|
||||
/// ribbon control is laid out right to left.
|
||||
#[test]
|
||||
fn the_arabic_interface_is_mirrored_and_never_panics() {
|
||||
let Some(ar) = crate::test_harness::locale_for_audit("ar") else {
|
||||
// Arabic comes from the craft-i18n catalogs: a build without them (English only) has nothing to mirror.
|
||||
let Some(ar) = super::Lang::from_code("ar") else {
|
||||
eprintln!("skipped: built without the craft-i18n Arabic catalog (set CRAFT_I18N_DIR to a checkout)");
|
||||
return;
|
||||
};
|
||||
let full = crate::test_harness::full_locale_audit();
|
||||
let start = |ctx: &egui::Context| {
|
||||
let mut app = fresh_app(ctx);
|
||||
app.ui.language = "ar".into();
|
||||
@@ -833,7 +791,6 @@ fn the_arabic_interface_is_mirrored_and_never_panics() {
|
||||
drawn.iter().find(|(t, _)| t == label).map(|(_, x)| *x).unwrap_or_else(|| panic!("{english} is not drawn"))
|
||||
};
|
||||
// Tabs run from the right: File, Home, Insert … and the Share button is at the far left.
|
||||
assert_ne!(super::tr(ar, "Home"), "Home", "exercise a translated tab, not just English fallback");
|
||||
let drawn = frame_at(&ctx, &mut app, 1600.0);
|
||||
let (file, home, insert, share) = (x_of(&drawn, "File"), x_of(&drawn, "Home"), x_of(&drawn, "Insert"), x_of(&drawn, "Share"));
|
||||
assert!(file > home && home > insert && insert > 800.0, "tabs: {file} {home} {insert}");
|
||||
@@ -865,20 +822,15 @@ fn the_arabic_interface_is_mirrored_and_never_panics() {
|
||||
assert_eq!(app.root_env().direction, craft::i18n::Direction::Ltr);
|
||||
super::apply_language(ar);
|
||||
}
|
||||
// #910: also exercise Layout's dense Paragraph grid at the narrowest RTL width on PRs.
|
||||
// Everything else: no panic at any width.
|
||||
let tabs: Vec<&str> = crate::ribbon::TABS.iter().copied().filter(|t| *t != "File").collect();
|
||||
if full {
|
||||
for tab in &tabs {
|
||||
app.run("ui.tab", json!({"tab": tab})).unwrap();
|
||||
for width in [2560.0, 1100.0, 420.0] {
|
||||
frame_at(&ctx, &mut app, width);
|
||||
}
|
||||
for tab in &tabs {
|
||||
let _ = app.run("ui.tab", json!({"tab": tab}));
|
||||
for width in [2560.0, 1100.0, 420.0] {
|
||||
frame_at(&ctx, &mut app, width);
|
||||
}
|
||||
} else {
|
||||
app.run("ui.tab", json!({"tab": "Layout"})).unwrap();
|
||||
frame_at(&ctx, &mut app, 420.0);
|
||||
}
|
||||
app.run("ui.tab", json!({"tab": "Home"})).unwrap();
|
||||
let _ = app.run("ui.tab", json!({"tab": "Home"}));
|
||||
// Reading Mode's toolbar is mirrored too: its far-side button ("Edit Document") is at the left.
|
||||
let _ = app.run("view.readMode", json!({}));
|
||||
let drawn = frame_at(&ctx, &mut app, 1600.0);
|
||||
@@ -896,12 +848,10 @@ fn the_arabic_interface_is_mirrored_and_never_panics() {
|
||||
assert!(preview < f32::MAX, "the preview's page indicator is drawn");
|
||||
assert!(preview + 100.0 < settings, "print page at {width}: settings {settings}, preview {preview}");
|
||||
}
|
||||
if full {
|
||||
for page in ["home", "new", "open", "info", "export", "print", "options"] {
|
||||
let _ = app.run("ui.backstage", json!({"value": true, "page": page}));
|
||||
frame(&ctx, &mut app);
|
||||
frame_at(&ctx, &mut app, 500.0);
|
||||
}
|
||||
for page in ["home", "new", "open", "info", "export", "print", "options"] {
|
||||
let _ = app.run("ui.backstage", json!({"value": true, "page": page}));
|
||||
frame(&ctx, &mut app);
|
||||
frame_at(&ctx, &mut app, 500.0);
|
||||
}
|
||||
let _ = app.run("ui.backstage", json!({"value": false}));
|
||||
// A dialog's columns start at the right too. Main's Go To set its list of targets beside its page number box; the
|
||||
@@ -912,13 +862,6 @@ fn the_arabic_interface_is_mirrored_and_never_panics() {
|
||||
let (targets, buttons) = (x_of(&drawn, "Go to what:"), x_of(&drawn, "Next"));
|
||||
assert!(targets > buttons, "Go To: targets {targets}, buttons {buttons}");
|
||||
crate::dialogs::host::close_all(&mut app, &ctx);
|
||||
if full {
|
||||
audit_arabic_states(&ctx, &mut app, &tabs, start);
|
||||
}
|
||||
super::apply_language(super::Lang::EN);
|
||||
}
|
||||
|
||||
fn audit_arabic_states(ctx: &egui::Context, app: &mut WordApp, tabs: &[&str], start: impl Fn(&egui::Context) -> WordApp) {
|
||||
let dialogs = [
|
||||
"font",
|
||||
"paragraph",
|
||||
@@ -983,28 +926,28 @@ fn audit_arabic_states(ctx: &egui::Context, app: &mut WordApp, tabs: &[&str], st
|
||||
];
|
||||
for name in dialogs {
|
||||
let _ = app.run("ui.dialog", json!({"name": name}));
|
||||
frame(ctx, app);
|
||||
crate::dialogs::host::close_all(app, ctx);
|
||||
frame(&ctx, &mut app);
|
||||
crate::dialogs::host::close_all(&mut app, &ctx);
|
||||
}
|
||||
let panes: Vec<String> =
|
||||
app.session.registry.all().iter().map(|c| c.id.to_string()).filter(|id| id.starts_with("view.") && id.ends_with("Pane")).collect();
|
||||
for pane in &panes {
|
||||
let _ = app.run(pane, json!({"value": true}));
|
||||
frame(ctx, app);
|
||||
frame_at(ctx, app, 600.0);
|
||||
frame(&ctx, &mut app);
|
||||
frame_at(&ctx, &mut app, 600.0);
|
||||
let _ = app.run(pane, json!({"value": false}));
|
||||
}
|
||||
frames(ctx, app, click(egui::pos2(1280.0, 520.0), egui::PointerButton::Secondary));
|
||||
frames(ctx, app, escape());
|
||||
frames(&ctx, &mut app, click(egui::pos2(1280.0, 520.0), egui::PointerButton::Secondary));
|
||||
frames(&ctx, &mut app, escape());
|
||||
let _ = app.run("insert.table", json!({"rows": 2, "cols": 2}));
|
||||
for tab in ["Table Design", "Table Layout"] {
|
||||
let _ = app.run("ui.tab", json!({"tab": tab}));
|
||||
frame(ctx, app);
|
||||
frame_at(ctx, app, 600.0);
|
||||
frame(&ctx, &mut app);
|
||||
frame_at(&ctx, &mut app, 600.0);
|
||||
}
|
||||
let _ = app.run("insert.equation", json!({}));
|
||||
let _ = app.run("ui.tab", json!({"tab": "Equation"}));
|
||||
frame(ctx, app);
|
||||
frame(&ctx, &mut app);
|
||||
// Every ribbon control on every tab, hovered and clicked: its tooltip, menu or dialog.
|
||||
let contextual = ["Table Design", "Table Layout", "Equation"];
|
||||
let open = |tab: &str| {
|
||||
@@ -1032,4 +975,5 @@ fn audit_arabic_states(ctx: &egui::Context, app: &mut WordApp, tabs: &[&str], st
|
||||
}
|
||||
}
|
||||
}
|
||||
super::apply_language(super::Lang::EN);
|
||||
}
|
||||
|
||||
@@ -149,6 +149,7 @@ const LOCALES: &[(&str, &[&str], Option<&str>)] = &[
|
||||
("ro", &["ro", "ro-RO", "ro-MD"], Some("Română")),
|
||||
("sl", &["sl", "sl-SI", "SL-si"], Some("Slovenščina")),
|
||||
("bs", &["bs", "bs-BA", "bs-Latn-BA"], Some("Bosanski")),
|
||||
("hi", &["hi", "hi-IN", "hi_IN.UTF-8", "hi-Deva-IN"], Some("हिन्दी")),
|
||||
("ar", &["ar", "ar-MA", "ar_EG.UTF-8", "AR-sa", "ar-Arab-AE"], None),
|
||||
];
|
||||
|
||||
|
||||
@@ -629,7 +629,8 @@ mod tests {
|
||||
let record = std::cell::RefCell::new(PaintRecord::default());
|
||||
let mut frames = Frames::new();
|
||||
let shapes = frames.frame_shapes(|ui| {
|
||||
let env = DrawEnv { tokens: &tokens, direction: craft::i18n::Direction::Ltr, ink: craft::ui::style::Ink::OnPanel };
|
||||
let env =
|
||||
DrawEnv { tokens: &tokens, direction: craft::i18n::Direction::Ltr, ink: craft::ui::style::Ink::OnPanel, mark: Default::default() };
|
||||
let icon = IconSpec::svg(IconId::new(KEY));
|
||||
Draw::new(ui.painter(), &record, env).icon(Rect::from_min_size(Pos2::ZERO, egui::vec2(20.0, 20.0)), &icon);
|
||||
});
|
||||
|
||||
@@ -581,8 +581,9 @@ fn escape_in_a_ribbon_list_does_not_open_the_context_menu() {
|
||||
.map(|n| n.rect())
|
||||
.min_by(|a, b| a.min.y.total_cmp(&b.min.y))
|
||||
.expect("the ribbon has a size field");
|
||||
// The list ends on its last whole row and scrolls the rest (craft-libs f2b9450d8), so 28 is no longer in it unscrolled.
|
||||
click_at(&mut h, pos2(size.max.x + 8.0, size.center().y));
|
||||
let list_open = |h: &H| h.query_all_by_label("28").next().is_some();
|
||||
let list_open = |h: &H| h.query_all_by_label("24").next().is_some();
|
||||
assert!(list_open(&h), "the size list is open");
|
||||
press_key(&mut h, egui::Key::Escape, Default::default());
|
||||
assert!(!list_open(&h), "Escape closes the size list");
|
||||
@@ -643,10 +644,10 @@ fn picking_from_a_ribbon_list_over_the_page_keeps_the_bar_away() {
|
||||
.expect("the ribbon has a size box");
|
||||
click_at(&mut h, pos2(size_box.max.x + 8.0, size_box.center().y));
|
||||
assert!(!bar_shown(&h), "opening the ribbon's list puts the bar away");
|
||||
let item = h.get_by_label("28").rect().center();
|
||||
assert!(canvas(&h).contains(item), "the list's 28 should hang over the page for this test");
|
||||
let item = h.get_by_label("24").rect().center();
|
||||
assert!(canvas(&h).contains(item), "the list's 24 should hang over the page for this test");
|
||||
click_at(&mut h, item);
|
||||
assert_eq!(format_state(&mut h).get("size").and_then(Value::as_f64), Some(28.0), "the ribbon's size list applied 28 pt");
|
||||
assert_eq!(format_state(&mut h).get("size").and_then(Value::as_f64), Some(24.0), "the ribbon's size list applied 24 pt");
|
||||
assert!(!visible(h.state()) && !bar_shown(&h), "the bar stays away after a pick from the ribbon's list");
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use craft::behavior::{EditEvent, MotionMode, keyed};
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show, ShowCollection, ShowContainer};
|
||||
use craft::ui::display::{Elide, Shade, Text};
|
||||
use craft::ui::form::{SliderField, SliderFieldLayout};
|
||||
use craft::ui::form::{FieldDecimals, SliderField, SliderFieldLayout};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::list::{List, ListRow};
|
||||
use craft::ui::patterns::preferences::{GroupSpec, PageSpec, PrefValue, PreferencesModel, PreferencesPage, RowKind, RowSpec};
|
||||
@@ -778,6 +778,7 @@ impl OptionsModel<'_> {
|
||||
let rate = f64::from(self.app.session.read_aloud.rate());
|
||||
let out = SliderField::new(tl!("Speed"), Bind::given(rate), f64::from(MIN_RATE)..=f64::from(MAX_RATE))
|
||||
.step(0.05)
|
||||
.field_decimals(FieldDecimals::Fixed(2))
|
||||
.layout(SliderFieldLayout::Inline)
|
||||
.short(true)
|
||||
.unit(tl!("×"))
|
||||
|
||||
@@ -290,7 +290,17 @@ fn tab_name(v: &toml_edit::Value) -> Option<String> {
|
||||
Some(name.map_or_else(|| v.to_string().trim().to_string(), str::to_lowercase))
|
||||
}
|
||||
|
||||
/// Reads the `ui.json` older builds wrote: the [`LegacyFile::parse`](craft::settings::LegacyFile) of the
|
||||
/// [`legacy_ui_json`] over the one `ui.json` slot craft-libs' legacy import hands the parse
|
||||
/// (desktop `ui.json`, web `wordcraft.ui`).
|
||||
pub fn legacy_ui_json_slots(slots: &[Result<Option<&[u8]>, &std::io::Error>]) -> Result<(Prefs, Vec<SectionError>), String> {
|
||||
match slots.first() {
|
||||
Some(Ok(Some(bytes))) => legacy_ui_json(bytes),
|
||||
Some(Ok(None)) | None => Err("ui.json is missing".to_string()),
|
||||
Some(Err(e)) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the `ui.json` older builds wrote, for [`legacy_ui_json_slots`] in the
|
||||
/// one-time import. A setting with a value of the wrong type (or a newer or older version's idea of
|
||||
/// it) falls back to its default and is reported as a [`SectionError`] with its path; unknown keys are
|
||||
/// dropped. `Err` only when the file isn't a JSON object.
|
||||
|
||||
@@ -77,7 +77,7 @@ pub(crate) fn no_ribbon() -> RibbonOutput<String> {
|
||||
/// points square and the rest 17, its menu arrows as filled triangles in 10 points, and its small
|
||||
/// rows 22 points apart (20-point buttons a tight gap apart); its tabs rest in the text colour
|
||||
/// over a 3-point underline; its body stands on its own lighter fill, ruled above and below.
|
||||
const RIBBON_LOOK: RibbonLook = RibbonLook::new(32, 17).arrow(10).row(20).tabs(3).body();
|
||||
const RIBBON_LOOK: RibbonLook = RibbonLook::new(32, 17).arrow(10).row(20).tabs(3).body(craft::menu::ribbon::RibbonBody::Band);
|
||||
|
||||
/// Draws the Read toolbar or the full ribbon, switching to and from the contextual Equation and
|
||||
/// Outlining tabs and showing the available tab strip. The output carries the record of the ribbon's
|
||||
|
||||
@@ -174,6 +174,7 @@ fn gallery_pen(ui: &mut egui::Ui, i: usize, pen: wordcraft_engine::cmd::draw::Cu
|
||||
.tooltip(tip)
|
||||
.selected(active)
|
||||
.show(ui)
|
||||
.edit
|
||||
.response;
|
||||
Menu::context(crate::tl!("Remove Pen"), &response).show(ui, |ui, _| {
|
||||
MenuItem::command(CommandRef::with_params("draw.removePen", json!({"index": i}))).label(crate::tl!("Remove Pen")).show(ui);
|
||||
|
||||
@@ -8,7 +8,7 @@ use serde_json::Value;
|
||||
use super::{Ui, WordApp, json};
|
||||
|
||||
/// The proofing languages the Language menu offers: tag and English name (translated when drawn).
|
||||
pub(crate) const PROOFING_LANGUAGES: [(&str, &str); 16] = [
|
||||
pub(crate) const PROOFING_LANGUAGES: [(&str, &str); 17] = [
|
||||
("en-US", "English (United States)"),
|
||||
("en-GB", "English (United Kingdom)"),
|
||||
("en-AU", "English (Australia)"),
|
||||
@@ -21,6 +21,7 @@ pub(crate) const PROOFING_LANGUAGES: [(&str, &str); 16] = [
|
||||
("ru-RU", "Russian"),
|
||||
("cs-CZ", "Czech"),
|
||||
("id-ID", "Indonesian"),
|
||||
("hi-IN", "Hindi"),
|
||||
("es-ES", "Spanish (Spain)"),
|
||||
("es-MX", "Spanish (Mexico)"),
|
||||
("es-419", "Spanish (Latin America)"),
|
||||
|
||||
@@ -56,11 +56,22 @@ pub(super) fn review(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
.arrangement(Arrangement::Stacked)
|
||||
.show(ui);
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Button::command(CommandRef::new("review.deleteComment"))
|
||||
.label(tl!("Delete").to_string())
|
||||
.tooltip(tl!("Delete Comment").to_string())
|
||||
.icon(IconId::new("deleteComment"))
|
||||
.show(ui);
|
||||
SplitButton::<u8>::command(
|
||||
CommandRef::new("review.deleteComment"),
|
||||
SplitMenu::Body(Box::new(|ui, _| {
|
||||
MenuItem::command(CommandRef::new("review.deleteComment")).label(tl!("Delete").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::with_params("review.deleteComment", json!({"all": true})))
|
||||
.label(tl!("Delete All Comments in Document").to_string())
|
||||
.show(ui);
|
||||
MenuItem::command(CommandRef::with_params("review.deleteComment", json!({"resolved": true})))
|
||||
.label(tl!("Delete All Resolved Comments").to_string())
|
||||
.show(ui);
|
||||
})),
|
||||
)
|
||||
.label(tl!("Delete").to_string())
|
||||
.tooltip(tl!("Delete Comment").to_string())
|
||||
.icon(IconId::new("deleteComment"))
|
||||
.show(ui);
|
||||
Button::command(CommandRef::new("review.previousComment"))
|
||||
.label(tl!("Previous").to_string())
|
||||
.tooltip(tl!("Previous Comment").to_string())
|
||||
|
||||
@@ -408,13 +408,11 @@ fn smart_art_design_layouts_are_one_strip_and_size_is_labelled() {
|
||||
}
|
||||
}
|
||||
|
||||
/// No group's content runs into its label. Keep the #910 View, Developer and Layout regressions,
|
||||
/// including long German and RTL Arabic labels; the daily run checks every tab in every locale.
|
||||
/// No group's content runs into its label: View › Show stacked four check boxes in a column
|
||||
/// made for three, so "Hide White Space" was drawn under "Show". Every tab, every language: each
|
||||
/// control lies inside its group's access node.
|
||||
#[test]
|
||||
fn ribbon_groups_fit_above_their_labels() {
|
||||
use crate::i18n::{Lang, tr};
|
||||
use egui::accesskit::Role;
|
||||
|
||||
fn rects(node: &egui_kittest::Node<'_>, out: &mut Vec<egui::Rect>) {
|
||||
for child in node.children() {
|
||||
// The framework's parts (a split button's arrow, a field's adornments) can be nodes with no
|
||||
@@ -440,53 +438,16 @@ fn ribbon_groups_fit_above_their_labels() {
|
||||
// Menu and popup bodies the framework measures in a hidden layer below the window carry access nodes under the
|
||||
// app's groups; they are never drawn, so they cannot run into a label. Only what lies on screen is checked.
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(2560.0, 900.0));
|
||||
let full = crate::test_harness::full_locale_audit();
|
||||
let german = crate::test_harness::locale_for_audit("de");
|
||||
let arabic = crate::test_harness::locale_for_audit("ar");
|
||||
let all_tabs = super::TABS.iter().copied().filter(|&t| t != "File").collect::<Vec<_>>();
|
||||
for lang in Lang::all() {
|
||||
let smoke: &[&str] = if lang == Lang::EN {
|
||||
&["View", "Developer", "Layout"]
|
||||
} else if Some(lang) == german {
|
||||
&["View", "Layout"]
|
||||
} else if Some(lang) == arabic {
|
||||
&["View", "Home"]
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
let tabs = if full || lang == Lang::EN { all_tabs.as_slice() } else { smoke };
|
||||
if tabs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for lang in crate::i18n::Lang::all() {
|
||||
h.state_mut().run("ui.language", json!({"value": lang.code()})).unwrap();
|
||||
for &tab in tabs {
|
||||
for tab in super::TABS.iter().filter(|t| **t != "File") {
|
||||
h.state_mut().run("ui.tab", json!({"tab": tab})).unwrap();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
if smoke.contains(&tab) {
|
||||
let group = match tab {
|
||||
"View" => "Show",
|
||||
"Developer" => "Controls",
|
||||
"Layout" => "Paragraph",
|
||||
"Home" => "Clipboard",
|
||||
_ => unreachable!("every smoke tab has a group witness"),
|
||||
};
|
||||
let bounds = h.get_by_role_and_label(Role::Group, tr(lang, group)).rect();
|
||||
assert!(bounds.is_positive() && screen.intersects(bounds), "{lang:?} {tab}: {group} must be on screen");
|
||||
if tab == "View" {
|
||||
let label = tr(lang, "Hide White Space");
|
||||
if lang != Lang::EN {
|
||||
assert_ne!(label, "Hide White Space", "{lang:?}: exercise translated checkbox text");
|
||||
}
|
||||
let hide = h.get_by_role_and_label(Role::CheckBox, label).rect();
|
||||
let last = h.get_by_role_and_label(Role::CheckBox, tr(lang, "Navigation Pane")).rect();
|
||||
assert!(hide.bottom() <= last.bottom() + 1.0, "{lang:?}: Hide White Space runs below the third row: {hide:?}, {last:?}");
|
||||
}
|
||||
}
|
||||
// The ribbon's groups: every labelled container is a group node (the document, its page text, the task
|
||||
// pane area), and those below the ribbon are not what this checks.
|
||||
let ribbon_bottom = h.state().canvas.canvas_rect().map_or(f32::INFINITY, |c| c.top());
|
||||
let groups = h
|
||||
.query_all(By::new().role(Role::Group))
|
||||
.query_all(By::new().role(egui::accesskit::Role::Group))
|
||||
.filter(|g| g.accesskit_node().raw_bounds().is_some() && g.rect().bottom() <= ribbon_bottom + 1.0);
|
||||
for group in groups {
|
||||
let frame = group.rect();
|
||||
@@ -967,7 +928,7 @@ fn bullets_dropdown_renders_compact_bullet_tiles() {
|
||||
h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu);
|
||||
|
||||
// The SplitButton has two button nodes: the command part and the arrow part.
|
||||
let arrow = h.query_all(By::new().role(Role::Button).label("Bullets")).nth(1).expect("Bullets split-button menu arrow");
|
||||
let arrow = h.query_all(By::new().role(Role::Button).label("Bullets options")).next().expect("Bullets split-button menu arrow");
|
||||
arrow.click();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
|
||||
|
||||
@@ -20,34 +20,6 @@ use egui_kittest::HarnessBuilder;
|
||||
|
||||
use crate::i18n::Lang;
|
||||
|
||||
/// The daily FreeBSD workspace test run opts in, as can local runs of these same tests.
|
||||
pub(crate) fn full_locale_audit() -> bool {
|
||||
match std::env::var("WORDCRAFT_FULL_LOCALE_AUDIT").as_deref() {
|
||||
Ok("1") => true,
|
||||
Ok("") | Err(std::env::VarError::NotPresent) => false,
|
||||
value => panic!("WORDCRAFT_FULL_LOCALE_AUDIT must be unset, empty or 1, got {value:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// These layout tests need real catalogs in CI. An explicitly English-only local build can
|
||||
/// still run other tests; a partial catalog set or a provisioned lane must never skip a case.
|
||||
pub(crate) fn locale_for_audit(code: &str) -> Option<Lang> {
|
||||
let required = match std::env::var("CRAFT_I18N_REQUIRED").as_deref() {
|
||||
Ok("1") => true,
|
||||
Ok("") | Err(std::env::VarError::NotPresent) => false,
|
||||
value => panic!("CRAFT_I18N_REQUIRED must be unset, empty or 1, got {value:?}"),
|
||||
};
|
||||
if let Some(lang) = Lang::from_code(code) {
|
||||
return Some(lang);
|
||||
}
|
||||
assert!(
|
||||
!required && option_env!("CRAFT_I18N_REQUIRED") != Some("1") && !full_locale_audit() && crate::i18n::CRAFT_I18N.is_empty(),
|
||||
"missing embedded {code} catalog: set CRAFT_I18N_DIR to the checkout pinned in craft-i18n.rev"
|
||||
);
|
||||
eprintln!("skipped {code} layout: this local build is English only (set CRAFT_I18N_DIR)");
|
||||
None
|
||||
}
|
||||
|
||||
/// The install spec the app's tests run on: the framework's test spec (the running build's shell, no OS windows or
|
||||
/// services) without the gallery stories' command sets. `craft::ui::testing::install_spec` loads those sets
|
||||
/// (`InstallSpec::stories`), and their default chords then hold app chords in every test window: the palette story's
|
||||
|
||||
@@ -2356,10 +2356,16 @@ fn clicks_on_ribbon_and_status_bar_chrome_keep_typing_in_the_document() {
|
||||
type_after_click(&mut h, "empty ribbon space", " blank");
|
||||
|
||||
// The status bar's view buttons.
|
||||
h.get_by_role_and_label(Role::Button, "Web Layout").click();
|
||||
// The View ribbon has buttons of the same names; the status bar's are the toggles.
|
||||
fn status_view_button<'h, S>(h: &'h egui_kittest::Harness<'_, S>, name: &'h str) -> egui_kittest::Node<'h> {
|
||||
h.query_all(egui_kittest::kittest::By::new().role(Role::Button).label(name))
|
||||
.find(|n| egui_kittest::kittest::NodeT::accesskit_node(n).toggled().is_some())
|
||||
.expect("the status bar view toggle")
|
||||
}
|
||||
status_view_button(&h, "Web Layout").click();
|
||||
type_after_click(&mut h, "Web Layout", " web");
|
||||
assert_eq!(h.state().session.view.mode, wordcraft_layout::ViewMode::Web);
|
||||
h.get_by_role_and_label(Role::Button, "Print Layout").click();
|
||||
status_view_button(&h, "Print Layout").click();
|
||||
type_after_click(&mut h, "Print Layout", " print");
|
||||
assert_eq!(h.state().session.view.mode, wordcraft_layout::ViewMode::Print);
|
||||
|
||||
|
||||
@@ -123,9 +123,9 @@ Recorded reader pairs (exact shapes in the policy):
|
||||
| lib.rs::report_dups | ID-BOOKMARK-DUP,ID-DOCPR-DUP,ID-REVISION-DUP | type.HashMap*2,type.HashSet*2 | intentional package-wide reductions for counts and document-wide duplicates, including unreached stories; definition duplicates remain per definition part | source unavailable or malformed; XML event/depth budget; category allocation cap | retain count/duplicate evidence from observed prefixes; loss remains recorded at each source; owner-local joins assemble their own scope | independent |
|
||||
| lib.rs::report_missing | ID-COMMENT-REF | access.missing*1,type.CompleteSet*1,type.HashSet*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | ID-COMMENT-REF |
|
||||
| lib.rs::report_missing_note | REF-NOTE | access.missing*1,type.CompleteSet*1,type.HashSet*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | REF-NOTE |
|
||||
| lib.rs::check_media | MEDIA-MAGIC | access.missing*1,field.bytes*1,field.content_types*1,field.entries*1,type.Vec*1 | existing media candidates and signatures; prove non-consumption from drawing-reference coverage or verify alternate raster bytes with the shared bounded decoder | incomplete relationship or reference discovery, unsupported alternate encoding, or decode budget | retain the signature Error when neither basis for a Warning is established and explain decoder budget loss, incomplete TIFF directories, or skipped assessment of a recognized encoding | independent |
|
||||
| lib.rs::check_media | MEDIA-MAGIC | access.missing*1,field.bytes*1,field.content_types*1,field.entries*1,type.Vec*6 | existing media candidates and signatures; prove non-consumption from drawing-reference coverage or verify alternate raster bytes with the shared bounded decoder | incomplete relationship or reference discovery, unsupported alternate encoding, or decode budget | retain the signature Error when neither basis for a Warning is established and explain decoder budget loss, incomplete TIFF directories, or skipped assessment of a recognized encoding | independent |
|
||||
| lib.rs::possible_drawing_targets | - | access.into_complete_set*2,access.is_complete*1,access.missing*1,access.prefix*1,field.collapsed_names*1,field.entries*1,field.parts*1,field.references*2,field.rels*2,type.CompleteSet*1,type.HashMap*2,type.HashSet*1,type.Observed*2 | package relationship targets possibly consumed by drawings; join complete per-story reference sets by owning relationship part | package relationship discovery incomplete; source missing or unexamined, duplicate owner identity, skipped markup, unmodeled relationship attributes, or reference budget | unknown owner usage leaves every internal target of its declarations possible; incomplete package discovery withholds non-consumption entirely | independent |
|
||||
| lib.rs::decode_alternate_image | - | type.Vec*1 | the admitted TIFF directory graph's main chain, within the part byte and metadata limits | directory walk incomplete, or the alternate image decode budget | leave the image unassessed | independent |
|
||||
| lib.rs::decode_alternate_image_step | - | type.Vec*1 | the admitted TIFF directory graph's main chain, within the part byte and metadata limits | directory walk incomplete, or the alternate image decode budget | leave the image unassessed | independent |
|
||||
| lib.rs::probe_alternate_tiff | - | field.first*1,type.Vec*1 | the admitted TIFF directory graph's main chain against the codec's own page listing | a main-chain directory the codec did not list | leave the image unassessed | independent |
|
||||
| lib.rs::relationship_targets | - | field.rels*2,type.HashSet*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| observed.rs::default | - | - | private Observed/CompleteSet representation provider; signature and footprint pinned in observations/representation-contracts.json | local completeness and allocation budgets carried by the typed representation | retain prefix; incomplete observations cannot construct CompleteSet; fixtures check semantics | independent |
|
||||
@@ -267,10 +267,12 @@ Recorded reader pairs (exact shapes in the policy):
|
||||
| scan.rs::parse_comments_ids | COMMENTEX-LINK | parser.parse_comments_ids*1,type.Vec*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::push_comment_id | - | type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::attrs_of | - | type.Vec*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| tiff_admission.rs::payload | - | type.HashMap*2,type.Vec*1 | the TIFF directory graph within the part byte and metadata limits | header failure, malformed directory or metadata budget | leave the image unassessed | independent |
|
||||
| tiff_admission.rs::init_walk | - | type.HashMap*6,type.HashSet*3 | the TIFF directory graph within the part byte and metadata limits | header failure, malformed directory or metadata budget | leave the image unassessed | independent |
|
||||
| tiff_admission.rs::establish_chain_role | - | field.chain_next*1,field.parsed*1,field.pending_chain_members*2 | chain edges of already-examined TIFF directories whose chain role is established | unexamined targets remain outside the established subgraph | leave unexamined targets pending for bounded examination | independent |
|
||||
| tiff_admission.rs::run_phase1 | - | field.children_of*1,field.nearest*1,field.pending_chain_members*1,field.queue*7,field.visited*1 | the TIFF directory graph within the directory, entry, depth and work bounds | directory cycle, malformed directory or metadata budget | leave the image unassessed | independent |
|
||||
| tiff_admission.rs::finish_phase2 | - | field.bytes*2,field.chain_next*2,field.children_of*1,field.parsed*1,type.HashMap*2,type.Vec*1 | the examined TIFF directory subgraph and its main chain | directory cycle, malformed directory or metadata budget | leave the image unassessed | independent |
|
||||
| tiff_admission.rs::offset | - | field.bytes*2 | one classic TIFF or BigTIFF offset field | offset bytes outside the payload | return no offset | independent |
|
||||
| tiff_admission.rs::admit | - | field.parsed*1,type.HashMap*8,type.HashSet*1,type.Vec*3 | the TIFF directory graph within the directory, entry, depth and work bounds | directory cycle, malformed directory or metadata budget | leave the image unassessed | independent |
|
||||
| tiff_admission.rs::directory | - | field.bytes*2,field.declared*5,field.entries*3,field.parsed*3,field.value_spans*1,type.BTreeMap*2 | TIFF directory table and physical value spans, bounded before directory or decoder allocations | malformed directory, incomplete value or pointer, directory cycle, work/byte budget | do not assess pixels from an incomplete preflight | independent |
|
||||
| tiff_admission.rs::directory | - | field.bytes*2,field.declared*5,field.entries*3,field.examined_dirs*2,field.failed_dirs*8,field.parsed*2,field.value_spans*1,type.BTreeMap*2 | TIFF directory table and physical value spans, bounded before directory or decoder allocations | malformed directory, incomplete value or pointer, directory cycle, work/byte budget | do not assess pixels from an incomplete preflight | independent |
|
||||
| tiff_admission.rs::record_image_data | - | type.BTreeMap*1 | ranges named by the directory’s checked offset and length tables | work budget or unreadable range | preserve decoder handling of truncated image data | independent |
|
||||
| tiff_admission.rs::children | - | type.BTreeMap*1,type.Vec*2 | SubIFD, Exif, GPS and Interop pointers under directory, depth and work bounds | unreadable child pointer or incomplete child directory | withhold the complete directory inventory | independent |
|
||||
| tiff_admission.rs::uint | - | field.bytes*1 | one checked unsigned value from a TIFF tag span | unreadable value or incompatible TIFF field type | return no value | independent |
|
||||
|
||||
+1113
-34
File diff suppressed because it is too large
Load Diff
+238
-50
@@ -858,12 +858,13 @@ fn decode_zip_name<'a>(mut raw: &'a [u8], utf8: bool, extra: &'a [u8]) -> Option
|
||||
}
|
||||
}
|
||||
|
||||
/// Reject records the reader cannot include in its central table. `by_index_raw`
|
||||
/// would parse local headers, initialize data-start caches and seek the archive;
|
||||
/// do not make directory identity depend on opening a part a second time.
|
||||
/// The walk already bounds these fields to their 16-bit lengths. Reader-rejected
|
||||
/// metadata leaves identity unknown rather than allowing a retry to invent duplicates.
|
||||
fn reader_accepts_central_record(header: &[u8], extra: &[u8], comment: &[u8], directory_start: u64) -> Option<()> {
|
||||
/// Reject records the reader cannot include in its central table, returning the resolved
|
||||
/// `(local_header_offset, compressed_size)` pair on acceptance. `by_index_raw` would parse local
|
||||
/// headers, initialize data-start caches and seek the archive; do not make directory identity
|
||||
/// depend on opening a part a second time. The walk already bounds these fields to their 16-bit
|
||||
/// lengths. Reader-rejected metadata leaves identity unknown rather than allowing a retry to
|
||||
/// invent duplicates.
|
||||
fn reader_accepts_central_record(header: &[u8], extra: &[u8], comment: &[u8], directory_start: u64) -> Option<(u64, u64)> {
|
||||
let mut local = u64::from(u32_at(header, 42)?);
|
||||
let mut compressed = u64::from(u32_at(header, 20)?);
|
||||
let mut uncompressed = u64::from(u32_at(header, 24)?);
|
||||
@@ -932,7 +933,7 @@ fn reader_accepts_central_record(header: &[u8], extra: &[u8], comment: &[u8], di
|
||||
}
|
||||
// The reader checks the final method after applying AES extra fields and the
|
||||
// final ZIP64 local offset before accepting this record into its table.
|
||||
if (method == 99 && !aes) || local >= directory_start { None } else { Some(()) }
|
||||
if (method == 99 && !aes) || local >= directory_start { None } else { Some((local, compressed)) }
|
||||
}
|
||||
|
||||
/// CP437's upper half; ASCII/control bytes in the lower half keep their byte values.
|
||||
@@ -986,15 +987,22 @@ fn reader_checked_directory<'a>(
|
||||
) -> (Option<CentralDirectory<'a>>, bool) {
|
||||
let selection = find_eocd(bytes);
|
||||
let cd = selection.as_ref().and_then(|selected| central_directory(bytes, limit, selected));
|
||||
let structural_disagreement = selection.as_ref().is_some_and(|selected| {
|
||||
let reader_matches = cd.as_ref().is_some_and(|dir| dir.consistent && directory_matches_reader(dir, zip));
|
||||
let disputed = selection.as_ref().is_some_and(|selected| {
|
||||
selected.disputed
|
||||
|| (cd.is_none()
|
||||
&& !(selected.exact_end
|
||||
&& reader_matches
|
||||
&& cd.as_ref().is_some_and(|dir| !dir.truncated && competing_footers_unreachable(bytes, selected, dir)))
|
||||
});
|
||||
let structural_disagreement = disputed
|
||||
|| selection.as_ref().is_some_and(|selected| {
|
||||
cd.is_none()
|
||||
&& selected
|
||||
.directory
|
||||
.as_ref()
|
||||
.is_some_and(|directory| usize::try_from(directory.start).ok().and_then(|start| u32_at(bytes, start)) == Some(0x0201_4B50)))
|
||||
});
|
||||
if structural_disagreement || cd.as_ref().is_some_and(|dir| !dir.consistent || !directory_matches_reader(dir, zip)) {
|
||||
.is_some_and(|directory| usize::try_from(directory.start).ok().and_then(|start| u32_at(bytes, start)) == Some(0x0201_4B50))
|
||||
});
|
||||
if structural_disagreement || cd.as_ref().is_some_and(|_| !reader_matches) {
|
||||
// A different directory or an inconsistent count can invent duplicates even when
|
||||
// decoded names and the residual agree. No finding may rely on those identities.
|
||||
acc.note("the zip central directory's selection or decoded names disagree with the reader; entry identities are unknown and dependent absence checks were skipped".to_string());
|
||||
@@ -1107,14 +1115,24 @@ impl DirectoryView {
|
||||
}
|
||||
}
|
||||
|
||||
struct EocdCandidate {
|
||||
/// Start of the footer span (the adjacent ZIP64 EOCD record when present, else the ZIP64
|
||||
/// locator 20 bytes before the EOCD when attached, else the EOCD itself).
|
||||
span_start: usize,
|
||||
/// Exclusive end of the EOCD comment (`eocd + 22 + comment_len`).
|
||||
comment_end: usize,
|
||||
directory: Option<DirectoryView>,
|
||||
}
|
||||
|
||||
struct EocdSelection {
|
||||
directory: Option<DirectoryView>,
|
||||
/// Whether the first (latest) selected candidate's comment ended at EOF.
|
||||
exact_end: bool,
|
||||
disputed: bool,
|
||||
}
|
||||
|
||||
/// The locator-targeted ZIP64 record only; never follow the reader's forward scan.
|
||||
fn zip64_directory(bytes: &[u8], eocd: usize) -> Option<DirectoryView> {
|
||||
let locator = eocd.checked_sub(20)?;
|
||||
/// Outer-file offset of an adjacent ZIP64 EOCD record referenced by `locator`.
|
||||
fn zip64_adjacent_record_start(bytes: &[u8], locator: usize) -> Option<usize> {
|
||||
if u32_at(bytes, locator)? != 0x0706_4B50 {
|
||||
return None;
|
||||
}
|
||||
@@ -1124,13 +1142,16 @@ fn zip64_directory(bytes: &[u8], eocd: usize) -> Option<DirectoryView> {
|
||||
return None;
|
||||
}
|
||||
let size = u64_at(bytes, off + 4)?;
|
||||
let count = u64_at(bytes, off + 32)?;
|
||||
let cd_off = u64_at(bytes, off + 48)?;
|
||||
// The locator is only a hint to the reader. A non-adjacent record can steer this
|
||||
// parser to a decoy; reject it rather than following the reader's forward scan.
|
||||
if size < 44
|
||||
|| size.checked_add(12)? != expected
|
||||
|| u32_at(bytes, locator + 16)? > 1
|
||||
(size >= 44 && size.checked_add(12)? == expected).then_some(off)
|
||||
}
|
||||
|
||||
/// The locator-targeted ZIP64 record only; never follow the reader's forward scan.
|
||||
fn zip64_directory(bytes: &[u8], locator: usize, off: usize) -> Option<DirectoryView> {
|
||||
let count = u64_at(bytes, off + 32)?;
|
||||
let cd_off = u64_at(bytes, off + 48)?;
|
||||
if u32_at(bytes, locator + 16)? > 1
|
||||
|| u32_at(bytes, off + 20)? != u32_at(bytes, locator + 4)?
|
||||
|| u32_at(bytes, off + 16)? != u32_at(bytes, off + 20)?
|
||||
|| u64_at(bytes, off + 24)? > count
|
||||
@@ -1142,6 +1163,198 @@ fn zip64_directory(bytes: &[u8], eocd: usize) -> Option<DirectoryView> {
|
||||
Some(DirectoryView { start: cd_off, count, zip64: true, footer_consistent: true })
|
||||
}
|
||||
|
||||
/// Inspect a single EOCD signature at `i`, advancing `last_header` backward as needed.
|
||||
/// Returns `None` when `i` is not a finder-acceptable candidate.
|
||||
fn eocd_candidate_at(bytes: &[u8], i: usize, last_header: &mut Option<usize>) -> Option<EocdCandidate> {
|
||||
const CDFH: [u8; 4] = [0x50, 0x4B, 0x01, 0x02];
|
||||
let comment_end = i.checked_add(22)?.checked_add(usize::from(u16_at(bytes, i + 20)?))?;
|
||||
if comment_end > bytes.len() {
|
||||
return None;
|
||||
}
|
||||
if last_header.is_some_and(|header| header.checked_add(4).is_none_or(|after| after > i)) {
|
||||
*last_header = bytes.get(..i)?.windows(4).rposition(|w| w == CDFH);
|
||||
}
|
||||
let total = u64::from(u16_at(bytes, i + 10)?);
|
||||
let offset = u64::from(u32_at(bytes, i + 16)?);
|
||||
let locator =
|
||||
(total == 0xFFFF || offset == 0xFFFF_FFFF).then(|| i.checked_sub(20)).flatten().filter(|&loc| u32_at(bytes, loc) == Some(0x0706_4B50));
|
||||
let (directory, span_start) = if let Some(loc) = locator {
|
||||
// An unsupported locator target is not permission to choose an earlier
|
||||
// footer: the reader may accept it by scanning. Keep identity unknown.
|
||||
match zip64_adjacent_record_start(bytes, loc) {
|
||||
Some(record_off) => (zip64_directory(bytes, loc, record_off), record_off),
|
||||
None => (None, loc),
|
||||
}
|
||||
} else {
|
||||
if total != 0
|
||||
&& (offset >= u64::try_from(i).ok()? || !last_header.is_some_and(|header| u64::try_from(header).is_ok_and(|header| header >= offset)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// read.rs uses files-on-this-disk for ZIP32, not the total field.
|
||||
let count = u64::from(u16_at(bytes, i + 8)?);
|
||||
let dir = DirectoryView {
|
||||
start: offset,
|
||||
count,
|
||||
zip64: false,
|
||||
// Disk mismatch is rejected only after spec.rs selects this footer.
|
||||
// Reject its identities rather than silently selecting an earlier one.
|
||||
footer_consistent: count == total && u16_at(bytes, i + 4)? == u16_at(bytes, i + 6)?,
|
||||
};
|
||||
(Some(dir), i)
|
||||
};
|
||||
Some(EocdCandidate { span_start, comment_end, directory })
|
||||
}
|
||||
|
||||
/// Resolve the local header's compressed size, following the local ZIP64 extra field
|
||||
/// when the 32-bit field holds the `0xFFFF_FFFF` sentinel.
|
||||
fn local_compressed_size(local_header: &[u8], local_extra: &[u8]) -> Option<u64> {
|
||||
let raw = u32_at(local_header, 18)?;
|
||||
if raw != u32::MAX {
|
||||
return Some(u64::from(raw));
|
||||
}
|
||||
let mut offset = 0usize;
|
||||
while offset < local_extra.len() {
|
||||
let tag = u16_at(local_extra, offset)?;
|
||||
let len = usize::from(u16_at(local_extra, offset + 2)?);
|
||||
offset = offset.checked_add(4)?;
|
||||
let end = offset.checked_add(len)?;
|
||||
let field = local_extra.get(offset..end)?;
|
||||
if tag == 0x0001 {
|
||||
// APPNOTE §4.5.3: local ZIP64 extra field stores uncompressed (0..8) then compressed (8..16).
|
||||
return u64_at(field, 8);
|
||||
}
|
||||
offset = end;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Verified `[data_start, data_end)` payload range for one central-directory record.
|
||||
/// Confirms local header signature, filename bytes, compression method, data-descriptor flag
|
||||
/// consistency, and compressed-size agreement (allowing zeroed local sizes when the
|
||||
/// data-descriptor flag is set), while permitting legitimate local vs central extra-field
|
||||
/// differences. Bounded strictly before the central directory.
|
||||
fn entry_payload_span(
|
||||
bytes: &[u8],
|
||||
local_offset: u64,
|
||||
compressed_size: u64,
|
||||
central_header: &[u8],
|
||||
central_name: &[u8],
|
||||
directory_start: u64,
|
||||
) -> Option<(usize, usize)> {
|
||||
let local = usize::try_from(local_offset).ok()?;
|
||||
let local_header = bytes.get(local..local.checked_add(30)?)?;
|
||||
if u32_at(local_header, 0)? != 0x0403_4B50 {
|
||||
return None;
|
||||
}
|
||||
let name_len = usize::from(u16_at(local_header, 26)?);
|
||||
let extra_len = usize::from(u16_at(local_header, 28)?);
|
||||
let name_start = local.checked_add(30)?;
|
||||
let name_end = name_start.checked_add(name_len)?;
|
||||
if bytes.get(name_start..name_end)? != central_name {
|
||||
return None;
|
||||
}
|
||||
let data_start = name_end.checked_add(extra_len)?;
|
||||
let local_extra = bytes.get(name_end..data_start)?;
|
||||
if u16_at(local_header, 8)? != u16_at(central_header, 10)? {
|
||||
return None;
|
||||
}
|
||||
let local_dd = u16_at(local_header, 6)? & 0x0008 != 0;
|
||||
let central_dd = u16_at(central_header, 8)? & 0x0008 != 0;
|
||||
if local_dd != central_dd {
|
||||
return None;
|
||||
}
|
||||
if local_dd {
|
||||
let zeroed_local = u32_at(local_header, 18)? == 0 && u32_at(local_header, 22)? == 0;
|
||||
if !zeroed_local && local_compressed_size(local_header, local_extra)? != compressed_size {
|
||||
return None;
|
||||
}
|
||||
} else if local_compressed_size(local_header, local_extra)? != compressed_size {
|
||||
return None;
|
||||
}
|
||||
let compressed = usize::try_from(compressed_size).ok()?;
|
||||
let data_end = data_start.checked_add(compressed)?;
|
||||
let cd_start = usize::try_from(directory_start).ok()?;
|
||||
(data_end <= cd_start && data_end <= bytes.len()).then_some((data_start, data_end))
|
||||
}
|
||||
|
||||
/// Verified payload interval of the final record in a complete central directory, provided it is
|
||||
/// also physically last: every preceding central record must have a verified local-header payload
|
||||
/// ending at or before this entry's local header (so no other entry extends past its payload end
|
||||
/// or overlaps it). Only that central-and-physically-last record may shield a competing earlier
|
||||
/// footer.
|
||||
fn final_entry_payload_span(bytes: &[u8], dir: &CentralDirectory) -> Option<(usize, usize)> {
|
||||
if dir.total == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut i = usize::try_from(dir.start).ok()?;
|
||||
let mut max_other_end = 0usize;
|
||||
for idx in 0..dir.total {
|
||||
if u32_at(bytes, i)? != 0x0201_4B50 {
|
||||
return None;
|
||||
}
|
||||
let name_len = usize::from(u16_at(bytes, i + 28)?);
|
||||
let extra_len = usize::from(u16_at(bytes, i + 30)?);
|
||||
let comment_len = usize::from(u16_at(bytes, i + 32)?);
|
||||
let header = bytes.get(i..i + 46)?;
|
||||
let name = bytes.get(i + 46..i + 46 + name_len)?;
|
||||
let extra = bytes.get(i + 46 + name_len..i + 46 + name_len + extra_len)?;
|
||||
let comment = bytes.get(i + 46 + name_len + extra_len..i + 46 + name_len + extra_len + comment_len)?;
|
||||
let next = i.checked_add(46 + name_len + extra_len + comment_len)?;
|
||||
bytes.get(..next)?;
|
||||
let (local, compressed) = reader_accepts_central_record(header, extra, comment, dir.start)?;
|
||||
let (data_start, data_end) = entry_payload_span(bytes, local, compressed, header, name, dir.start)?;
|
||||
if idx + 1 == dir.total {
|
||||
let local_start = usize::try_from(local).ok()?;
|
||||
return (max_other_end <= local_start).then_some((data_start, data_end));
|
||||
}
|
||||
max_other_end = max_other_end.max(data_end);
|
||||
i = next;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether every competing earlier EOCD candidate is provably unreachable: the first (latest)
|
||||
/// candidate already ends at EOF and matched the reader across its full central directory, and
|
||||
/// every disagreeing earlier candidate ends before EOF and lies entirely within the verified
|
||||
/// local-header payload of the central-and-physically-last entry (e.g. a trailing stored nested
|
||||
/// ZIP).
|
||||
fn competing_footers_unreachable(bytes: &[u8], selected: &EocdSelection, dir: &CentralDirectory) -> bool {
|
||||
const SIG: [u8; 4] = [0x50, 0x4B, 0x05, 0x06];
|
||||
const CDFH: [u8; 4] = [0x50, 0x4B, 0x01, 0x02];
|
||||
let Some(first_tuple) = selected.directory.as_ref().map(DirectoryView::tuple) else {
|
||||
return false;
|
||||
};
|
||||
let Some((payload_start, payload_end)) = final_entry_payload_span(bytes, dir) else {
|
||||
return false;
|
||||
};
|
||||
let start = bytes.len().saturating_sub(22 + 0xFFFF);
|
||||
let Some(end) = bytes.len().checked_sub(22) else {
|
||||
return false;
|
||||
};
|
||||
let mut last_header = bytes.get(..end).and_then(|prefix| prefix.windows(4).rposition(|w| w == CDFH));
|
||||
let mut seen_first = false;
|
||||
for i in (start..=end).rev() {
|
||||
if bytes.get(i..i + 4) != Some(&SIG) {
|
||||
continue;
|
||||
}
|
||||
let Some(candidate) = eocd_candidate_at(bytes, i, &mut last_header) else {
|
||||
continue;
|
||||
};
|
||||
if !seen_first {
|
||||
seen_first = true;
|
||||
continue;
|
||||
}
|
||||
if candidate.directory.as_ref().map(DirectoryView::tuple) == Some(first_tuple) {
|
||||
continue;
|
||||
}
|
||||
if candidate.comment_end >= bytes.len() || candidate.span_start < payload_start || candidate.comment_end > payload_end {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
seen_first
|
||||
}
|
||||
|
||||
/// Select in the reader's backward order, then reject competing selection tuples.
|
||||
/// Exact-comment-end remains a layout eligibility guard, never a selection rule:
|
||||
/// removing it would newly parse trailing-data archives frozen as unsupported.
|
||||
@@ -1162,44 +1375,19 @@ fn find_eocd(bytes: &[u8]) -> Option<EocdSelection> {
|
||||
}
|
||||
let comment_end = i.checked_add(22)?.checked_add(usize::from(u16_at(bytes, i + 20)?))?;
|
||||
exact_end |= comment_end == bytes.len();
|
||||
if comment_end > bytes.len() {
|
||||
let Some(candidate) = eocd_candidate_at(bytes, i, &mut last_header) else {
|
||||
continue;
|
||||
}
|
||||
if last_header.is_some_and(|header| header.checked_add(4).is_none_or(|after| after > i)) {
|
||||
last_header = bytes.get(..i)?.windows(4).rposition(|w| w == CDFH);
|
||||
}
|
||||
let total = u64::from(u16_at(bytes, i + 10)?);
|
||||
let offset = u64::from(u32_at(bytes, i + 16)?);
|
||||
let zip64 = (total == 0xFFFF || offset == 0xFFFF_FFFF) && i.checked_sub(20).and_then(|locator| u32_at(bytes, locator)) == Some(0x0706_4B50);
|
||||
let directory = if zip64 {
|
||||
// An unsupported locator target is not permission to choose an earlier
|
||||
// footer: the reader may accept it by scanning. Keep identity unknown.
|
||||
zip64_directory(bytes, i)
|
||||
} else {
|
||||
if total != 0
|
||||
&& (offset >= u64::try_from(i).ok()? || !last_header.is_some_and(|header| u64::try_from(header).is_ok_and(|header| header >= offset)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// read.rs uses files-on-this-disk for ZIP32, not the total field.
|
||||
let count = u64::from(u16_at(bytes, i + 8)?);
|
||||
Some(DirectoryView {
|
||||
start: offset,
|
||||
count,
|
||||
zip64: false,
|
||||
// Disk mismatch is rejected only after spec.rs selects this footer.
|
||||
// Reject its identities rather than silently selecting an earlier one.
|
||||
footer_consistent: count == total && u16_at(bytes, i + 4)? == u16_at(bytes, i + 6)?,
|
||||
})
|
||||
};
|
||||
if let Some(first) = selected.as_mut() {
|
||||
// No tuple can be established for an unsupported ZIP64 target. It
|
||||
// cannot certify agreement with another candidate either.
|
||||
if first.directory.as_ref().map(DirectoryView::tuple) != directory.as_ref().map(DirectoryView::tuple) || directory.is_none() {
|
||||
if first.directory.as_ref().map(DirectoryView::tuple) != candidate.directory.as_ref().map(DirectoryView::tuple)
|
||||
|| candidate.directory.is_none()
|
||||
{
|
||||
first.disputed = true;
|
||||
}
|
||||
} else {
|
||||
selected = Some(EocdSelection { directory, disputed: false });
|
||||
selected = Some(EocdSelection { directory: candidate.directory, exact_end: candidate.comment_end == bytes.len(), disputed: false });
|
||||
}
|
||||
}
|
||||
if exact_end { selected } else { None }
|
||||
|
||||
@@ -6,19 +6,92 @@ use craft_image_codecs::CodecError;
|
||||
use craft_tiff::{ByteOrder, EntrySpan, FieldType, ParseOptions, Tiff, directory_entries, entry_span, tags};
|
||||
|
||||
/// A bound of the validator's own admission (depth, directory count, entry count) was reached: the graph was not
|
||||
/// assessed, which is no evidence that it is malformed, so it is a lost assessment (`LimitExceeded`), never a grade.
|
||||
fn bound(what: &str) -> CodecError {
|
||||
CodecError::LimitExceeded(format!("TIFF directory {what} bound"))
|
||||
/// fully assessed, which is no evidence that it is malformed, so alone it is a lost assessment (`Limited`), never a grade.
|
||||
fn bound_reason(what: &str) -> String {
|
||||
format!("TIFF directory {what} bound")
|
||||
}
|
||||
|
||||
/// Outcome of bounded TIFF directory-graph admission.
|
||||
pub(crate) enum Admission<'a> {
|
||||
/// Complete acyclic directory graph within all bounds: payload slice and main-chain IFD offsets.
|
||||
Admitted(&'a [u8], Vec<u64>),
|
||||
/// A decisive defect (cycle or malformed directory/pointer) was established within the examined
|
||||
/// subgraph. If a traversal bound was also hit on an unexplored branch, the payload names it so the
|
||||
/// caller can disclose lost coverage without withdrawing the established defect.
|
||||
MalformedOrCyclic(Option<String>),
|
||||
/// No decisive defect was established within the examined subgraph, and a traversal bound
|
||||
/// stopped further exploration.
|
||||
Limited(String),
|
||||
}
|
||||
|
||||
/// Outcome of starting a bounded TIFF directory-graph admission walk.
|
||||
pub(crate) enum AdmissionStep<'a> {
|
||||
/// Admission completed within its initial pass.
|
||||
Done(Admission<'a>),
|
||||
/// The walk reached a continuation point (a malformed directory/pointer or per-branch bound)
|
||||
/// while more queued directories remain. Callers assessing a multi-part package can defer
|
||||
/// continuation until neighbouring parts finish their initial assessments so extra walk work
|
||||
/// cannot starve unaffected parts of the package-wide decode budget.
|
||||
Paused(Box<PausedWalk<'a>>),
|
||||
}
|
||||
|
||||
/// Resumable state of a TIFF directory-graph walk paused at a continuation point.
|
||||
pub(crate) struct PausedWalk<'a> {
|
||||
walk: DirectoryWalk<'a>,
|
||||
root_offset: u64,
|
||||
queue: VecDeque<(u64, bool, usize)>,
|
||||
visited: HashSet<(u64, bool)>,
|
||||
nearest: HashMap<u64, usize>,
|
||||
children_of: HashMap<u64, Vec<u64>>,
|
||||
pending_chain_members: HashSet<u64>,
|
||||
chain_next: HashMap<u64, u64>,
|
||||
malformed: bool,
|
||||
bound_hit: Option<String>,
|
||||
}
|
||||
|
||||
enum DirOutcome<T> {
|
||||
Ok(T),
|
||||
Malformed,
|
||||
/// A per-branch bound (such as one directory's entry limit) stopped this directory without
|
||||
/// exhausting the global walk budgets; other queued branches may still be examined.
|
||||
BranchBound(String),
|
||||
/// A global bound (directory count, total entries, or work/byte budget) stopped further parsing.
|
||||
GlobalBound(String),
|
||||
}
|
||||
|
||||
enum ChildrenStatus {
|
||||
Complete,
|
||||
Malformed,
|
||||
Limited(String),
|
||||
}
|
||||
|
||||
enum FailedDir {
|
||||
Malformed,
|
||||
BranchBound(String),
|
||||
}
|
||||
|
||||
/// What the codec will read for a complete TIFF: everything up to its last referenced byte (bytes after that are
|
||||
/// padding of any content and any length), with the directories of its main chain in order: the first directory and
|
||||
/// each `next` target. This is the ONE authority for which directories are main-chain pages; the page the validator
|
||||
/// assesses is chosen from it (a directory first reached as a SubIFD stays a main-chain page).
|
||||
pub(crate) fn payload(bytes: &[u8], mut reserve: impl FnMut(u64) -> Result<(), CodecError>) -> Result<Option<(&[u8], Vec<u64>)>, CodecError> {
|
||||
pub(crate) fn payload(bytes: &[u8], mut reserve: impl FnMut(u64) -> Result<(), CodecError>) -> Result<Admission<'_>, CodecError> {
|
||||
let mut state = init_walk(bytes, ParseOptions::default())?;
|
||||
state.run_phase1(&mut reserve, false)?;
|
||||
Ok(state.finish_phase2())
|
||||
}
|
||||
|
||||
/// Begin bounded TIFF directory-graph admission, pausing at the first continuation point if other
|
||||
/// queued branches remain so multi-part callers can finish initial assessments of neighbouring
|
||||
/// parts before spending shared budget on continuation work.
|
||||
pub(crate) fn start<'a>(bytes: &'a [u8], reserve: &mut impl FnMut(u64) -> Result<(), CodecError>) -> Result<AdmissionStep<'a>, CodecError> {
|
||||
let mut state = init_walk(bytes, ParseOptions::default())?;
|
||||
if state.run_phase1(reserve, true)? { Ok(AdmissionStep::Paused(Box::new(state))) } else { Ok(AdmissionStep::Done(state.finish_phase2())) }
|
||||
}
|
||||
|
||||
fn init_walk(bytes: &[u8], limits: ParseOptions) -> Result<PausedWalk<'_>, CodecError> {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "type.HashMap*2,type.Vec*1";
|
||||
collections: "type.HashMap*6,type.HashSet*3";
|
||||
scope: "the TIFF directory graph within the part byte and metadata limits";
|
||||
loss: "header failure, malformed directory or metadata budget";
|
||||
fallback: "leave the image unassessed";
|
||||
@@ -28,43 +101,249 @@ pub(crate) fn payload(bytes: &[u8], mut reserve: impl FnMut(u64) -> Result<(), C
|
||||
let Some((order, big)) = Tiff::sniff(bytes) else {
|
||||
return Err(CodecError::Malformed { format: craft_image_codecs::Format::Tiff, message: "not a TIFF or BigTIFF header".into() });
|
||||
};
|
||||
let mut walk = DirectoryWalk {
|
||||
let walk = DirectoryWalk {
|
||||
bytes,
|
||||
order,
|
||||
big,
|
||||
limits: ParseOptions::default(),
|
||||
limits,
|
||||
parsed: HashMap::new(),
|
||||
examined_dirs: HashSet::new(),
|
||||
failed_dirs: HashMap::new(),
|
||||
value_spans: HashMap::new(),
|
||||
entries: 0,
|
||||
end: if big { 16 } else { 8 },
|
||||
reserve: &mut reserve,
|
||||
};
|
||||
let malformed_root =
|
||||
|| CodecError::Malformed { format: craft_image_codecs::Format::Tiff, message: "the first TIFF directory is missing or cut off".into() };
|
||||
let first = walk.offset(if big { 8 } else { 4 }).filter(|&offset| offset != 0).ok_or_else(malformed_root)?;
|
||||
directory_entries(bytes, first, order, big, walk.limits.max_entries).map_err(|_| malformed_root())?;
|
||||
let Some(main_chain) = walk.admit(first)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
// Every range the codec reads is named by the walk, so what follows its end is padding of any content.
|
||||
let end = usize::try_from(walk.end).unwrap_or(usize::MAX).min(bytes.len());
|
||||
Ok(bytes.get(..end).map(|payload| (payload, main_chain)))
|
||||
let root_offset = walk.offset(if big { 8 } else { 4 }).filter(|&offset| offset != 0).ok_or_else(malformed_root)?;
|
||||
directory_entries(bytes, root_offset, order, big, walk.limits.max_entries).map_err(|_| malformed_root())?;
|
||||
Ok(PausedWalk {
|
||||
walk,
|
||||
root_offset,
|
||||
queue: VecDeque::from([(root_offset, true, 0usize)]),
|
||||
visited: HashSet::new(),
|
||||
nearest: HashMap::new(),
|
||||
children_of: HashMap::new(),
|
||||
pending_chain_members: HashSet::new(),
|
||||
chain_next: HashMap::new(),
|
||||
malformed: false,
|
||||
bound_hit: None,
|
||||
})
|
||||
}
|
||||
|
||||
struct DirectoryWalk<'a, R> {
|
||||
impl<'a> PausedWalk<'a> {
|
||||
/// Whether this paused walk has already established a malformed defect before pausing.
|
||||
pub(crate) fn has_established_defect(&self) -> bool {
|
||||
self.malformed
|
||||
}
|
||||
|
||||
/// Resume a paused walk to completion using the caller's remaining reservation budget.
|
||||
pub(crate) fn resume(mut self, reserve: &mut impl FnMut(u64) -> Result<(), CodecError>) -> Result<Admission<'a>, CodecError> {
|
||||
self.run_phase1(reserve, false)?;
|
||||
Ok(self.finish_phase2())
|
||||
}
|
||||
|
||||
/// Record that a decoded pointer has established `offset` as a chain member, and immediately
|
||||
/// install `chain_next` edges across any already-examined directories reachable through its
|
||||
/// cached `next` links so a later global stop cannot drop an already-established cycle.
|
||||
fn establish_chain_role(&mut self, mut offset: u64) {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "field.chain_next*1,field.parsed*1,field.pending_chain_members*2";
|
||||
scope: "chain edges of already-examined TIFF directories whose chain role is established";
|
||||
loss: "unexamined targets remain outside the established subgraph";
|
||||
fallback: "leave unexamined targets pending for bounded examination";
|
||||
package_loss: "independent";
|
||||
}
|
||||
|
||||
loop {
|
||||
let Some(&(_, next)) = self.walk.parsed.get(&offset) else {
|
||||
self.pending_chain_members.insert(offset);
|
||||
break;
|
||||
};
|
||||
self.pending_chain_members.remove(&offset);
|
||||
if next == 0 || self.chain_next.insert(offset, next).is_some() {
|
||||
break;
|
||||
}
|
||||
offset = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// Phase 1: reach every directory once per role (chain member or single), nearest first.
|
||||
/// `next` keeps the depth (a chain is one level); a pointer to a child adds one.
|
||||
/// Returns `Ok(true)` when paused at a continuation point with queued work remaining.
|
||||
fn run_phase1(&mut self, reserve: &mut impl FnMut(u64) -> Result<(), CodecError>, pause_on_continuation: bool) -> Result<bool, CodecError> {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "field.children_of*1,field.nearest*1,field.pending_chain_members*1,field.queue*7,field.visited*1";
|
||||
scope: "the TIFF directory graph within the directory, entry, depth and work bounds";
|
||||
loss: "directory cycle, malformed directory or metadata budget";
|
||||
fallback: "leave the image unassessed";
|
||||
package_loss: "independent";
|
||||
}
|
||||
|
||||
while let Some((offset, chain, depth)) = self.queue.pop_front() {
|
||||
if !self.visited.insert((offset, chain)) {
|
||||
continue;
|
||||
}
|
||||
if *self.nearest.entry(offset).or_insert(depth) > self.walk.limits.max_depth {
|
||||
self.bound_hit.get_or_insert_with(|| bound_reason("depth"));
|
||||
if pause_on_continuation && !self.queue.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (tags, next) = match self.walk.directory(offset, reserve)? {
|
||||
DirOutcome::Ok(dir) => dir,
|
||||
DirOutcome::Malformed => {
|
||||
self.malformed = true;
|
||||
if pause_on_continuation && !self.queue.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
DirOutcome::BranchBound(reason) => {
|
||||
self.bound_hit.get_or_insert(reason);
|
||||
if pause_on_continuation && !self.queue.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
DirOutcome::GlobalBound(reason) => {
|
||||
self.bound_hit.get_or_insert(reason);
|
||||
break;
|
||||
}
|
||||
};
|
||||
// Preserve any established chain edge immediately so a later budget stop cannot erase it.
|
||||
if chain || self.pending_chain_members.remove(&offset) {
|
||||
self.establish_chain_role(offset);
|
||||
}
|
||||
if chain && next != 0 {
|
||||
self.queue.push_front((next, true, depth));
|
||||
}
|
||||
if let Entry::Vacant(slot) = self.children_of.entry(offset) {
|
||||
match self.walk.record_image_data(&tags, reserve) {
|
||||
Ok(()) => {}
|
||||
Err(CodecError::LimitExceeded(reason)) => {
|
||||
self.bound_hit.get_or_insert(reason);
|
||||
break;
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
let (children, status) = self.walk.children(&tags, reserve)?;
|
||||
slot.insert(children.iter().map(|&(child, _)| child).collect());
|
||||
// A decoded SubIFD pointer establishes its target's chain role immediately; install
|
||||
// the cached `next` edge for any already-examined target before queue order or a
|
||||
// later global stop can exit the walk.
|
||||
for &(child, child_chain) in &children {
|
||||
if child_chain {
|
||||
self.establish_chain_role(child);
|
||||
}
|
||||
}
|
||||
match status {
|
||||
ChildrenStatus::Complete => {
|
||||
self.queue.extend(children.into_iter().map(|(child, chain)| (child, chain, depth + 1)));
|
||||
}
|
||||
ChildrenStatus::Malformed => {
|
||||
self.malformed = true;
|
||||
if pause_on_continuation && !self.queue.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
ChildrenStatus::Limited(reason) => {
|
||||
self.bound_hit.get_or_insert(reason);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Phase 2: a directory with a path back to itself in the examined subgraph is a cycle
|
||||
/// (depth-first, three colours). Runs even when a traversal bound stopped unexplored branches
|
||||
/// so an established cycle is never withdrawn by an unrelated bound hit.
|
||||
///
|
||||
/// This is the ONLY cycle computation. The graph's edges are every SubIFD, Exif, GPS and Interop
|
||||
/// pointer, and the `next` pointer of every directory that is read as a chain member (the first
|
||||
/// directory, a `next` target or a SubIFD target; Exif, GPS and Interop directories are single
|
||||
/// directories whose `next` nothing follows). Reaching a directory again is free whatever route
|
||||
/// it took, deeper routes included; only a directory that reaches itself rejects.
|
||||
fn finish_phase2(self) -> Admission<'a> {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "field.bytes*2,field.chain_next*2,field.children_of*1,field.parsed*1,type.HashMap*2,type.Vec*1";
|
||||
scope: "the examined TIFF directory subgraph and its main chain";
|
||||
loss: "directory cycle, malformed directory or metadata budget";
|
||||
fallback: "leave the image unassessed";
|
||||
package_loss: "independent";
|
||||
}
|
||||
|
||||
let mut cyclic = false;
|
||||
let successors = |offset: u64| -> Vec<u64> {
|
||||
self.children_of.get(&offset).into_iter().flatten().copied().chain(self.chain_next.get(&offset).copied()).collect()
|
||||
};
|
||||
// `false`: open on the current path; `true`: finished, with no path back to itself.
|
||||
let mut colour: HashMap<u64, bool> = HashMap::from([(self.root_offset, false)]);
|
||||
let mut stack = vec![(self.root_offset, successors(self.root_offset).into_iter())];
|
||||
while let Some((offset, rest)) = stack.last_mut() {
|
||||
let offset = *offset;
|
||||
match rest.next().map(|target| (target, colour.get(&target).copied())) {
|
||||
Some((_, Some(false))) => {
|
||||
cyclic = true;
|
||||
break;
|
||||
}
|
||||
Some((target, None)) => {
|
||||
colour.insert(target, false);
|
||||
stack.push((target, successors(target).into_iter()));
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
colour.insert(offset, true);
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.malformed || cyclic {
|
||||
return Admission::MalformedOrCyclic(self.bound_hit);
|
||||
}
|
||||
if let Some(reason) = self.bound_hit {
|
||||
return Admission::Limited(reason);
|
||||
}
|
||||
// The main chain: the first directory and each `next` target. The graph is acyclic here.
|
||||
let mut main_chain = vec![self.root_offset];
|
||||
while let Some(&next) = main_chain.last().and_then(|at| self.chain_next.get(at)) {
|
||||
if main_chain.len() > self.walk.parsed.len() {
|
||||
break;
|
||||
}
|
||||
main_chain.push(next);
|
||||
}
|
||||
// Every range the codec reads is named by the walk, so what follows its end is padding of any content.
|
||||
let end = usize::try_from(self.walk.end).unwrap_or(usize::MAX).min(self.walk.bytes.len());
|
||||
match self.walk.bytes.get(..end) {
|
||||
Some(payload) => Admission::Admitted(payload, main_chain),
|
||||
None => Admission::MalformedOrCyclic(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DirectoryWalk<'a> {
|
||||
bytes: &'a [u8],
|
||||
order: ByteOrder,
|
||||
big: bool,
|
||||
limits: ParseOptions,
|
||||
/// Directories already read and charged, with their tables and next pointers.
|
||||
parsed: HashMap<u64, (BTreeMap<u16, EntrySpan>, u64)>,
|
||||
/// Distinct in-range directories whose examination has started, independent of cache success.
|
||||
examined_dirs: HashSet<u64>,
|
||||
/// Cached non-Ok outcomes so revisiting an offset in another role does not re-charge budgets.
|
||||
failed_dirs: HashMap<u64, FailedDir>,
|
||||
value_spans: HashMap<u64, u64>,
|
||||
entries: usize,
|
||||
end: u64,
|
||||
reserve: &'a mut R,
|
||||
}
|
||||
|
||||
impl<R: FnMut(u64) -> Result<(), CodecError>> DirectoryWalk<'_, R> {
|
||||
impl DirectoryWalk<'_> {
|
||||
fn offset(&self, at: usize) -> Option<u64> {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
@@ -78,90 +357,14 @@ impl<R: FnMut(u64) -> Result<(), CodecError>> DirectoryWalk<'_, R> {
|
||||
if self.big { self.order.read_u64(self.bytes, at) } else { self.order.read_u32(self.bytes, at).map(u64::from) }
|
||||
}
|
||||
|
||||
/// The main chain of the directory graph reachable from `first` when it can be admitted: every directory reads,
|
||||
/// the directory, entry and depth budgets hold, and no directory is reachable from itself. `None` when the graph is
|
||||
/// malformed or cyclic; a budget that does not hold is `Err(LimitExceeded)`, a lost assessment.
|
||||
///
|
||||
/// This is the ONLY cycle computation. The graph's edges are every SubIFD, Exif, GPS and Interop
|
||||
/// pointer, and the `next` pointer of every directory that is read as a chain member (the first
|
||||
/// directory, a `next` target or a SubIFD target; Exif, GPS and Interop directories are single
|
||||
/// directories whose `next` nothing follows). Reaching a directory again is free whatever route
|
||||
/// it took, deeper routes included; only a directory that reaches itself rejects. Reachability is explored first, so
|
||||
/// the verdict depends on the graph and not on the order its edges are visited in.
|
||||
fn admit(&mut self, first: u64) -> Result<Option<Vec<u64>>, CodecError> {
|
||||
fn directory(
|
||||
&mut self,
|
||||
offset: u64,
|
||||
reserve: &mut impl FnMut(u64) -> Result<(), CodecError>,
|
||||
) -> Result<DirOutcome<(BTreeMap<u16, EntrySpan>, u64)>, CodecError> {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "field.parsed*1,type.HashMap*8,type.HashSet*1,type.Vec*3";
|
||||
scope: "the TIFF directory graph within the directory, entry, depth and work bounds";
|
||||
loss: "directory cycle, malformed directory or metadata budget";
|
||||
fallback: "leave the image unassessed";
|
||||
package_loss: "independent";
|
||||
}
|
||||
|
||||
// Phase 1: reach every directory once per role (chain member or single), nearest first.
|
||||
// `next` keeps the depth (a chain is one level); a pointer to a child adds one.
|
||||
let mut queue = VecDeque::from([(first, true, 0usize)]);
|
||||
let mut visited = HashSet::new();
|
||||
// The depth at which each directory was first reached in any role: the queue pops nearest first, so it is
|
||||
// the directory's minimum depth, and the depth bound is decided on that alone.
|
||||
let mut nearest: HashMap<u64, usize> = HashMap::new();
|
||||
let mut children_of: HashMap<u64, Vec<u64>> = HashMap::new();
|
||||
let mut chain_next: HashMap<u64, u64> = HashMap::new();
|
||||
while let Some((offset, chain, depth)) = queue.pop_front() {
|
||||
if !visited.insert((offset, chain)) {
|
||||
continue;
|
||||
}
|
||||
if *nearest.entry(offset).or_insert(depth) > self.limits.max_depth {
|
||||
return Err(bound("depth"));
|
||||
}
|
||||
let Some((tags, next)) = self.directory(offset)? else { return Ok(None) };
|
||||
if let Entry::Vacant(slot) = children_of.entry(offset) {
|
||||
self.record_image_data(&tags)?;
|
||||
let Some(children) = self.children(&tags)? else { return Ok(None) };
|
||||
slot.insert(children.iter().map(|&(child, _)| child).collect());
|
||||
queue.extend(children.into_iter().map(|(child, chain)| (child, chain, depth + 1)));
|
||||
}
|
||||
if chain && next != 0 {
|
||||
chain_next.insert(offset, next);
|
||||
queue.push_front((next, true, depth));
|
||||
}
|
||||
}
|
||||
// Phase 2: a directory with a path back to itself is a cycle (depth-first, three colours).
|
||||
let successors =
|
||||
|offset: u64| -> Vec<u64> { children_of.get(&offset).into_iter().flatten().copied().chain(chain_next.get(&offset).copied()).collect() };
|
||||
// `false`: open on the current path; `true`: finished, with no path back to itself.
|
||||
let mut colour: HashMap<u64, bool> = HashMap::from([(first, false)]);
|
||||
let mut stack = vec![(first, successors(first).into_iter())];
|
||||
while let Some((offset, rest)) = stack.last_mut() {
|
||||
let offset = *offset;
|
||||
match rest.next().map(|target| (target, colour.get(&target).copied())) {
|
||||
Some((_, Some(false))) => return Ok(None),
|
||||
Some((target, None)) => {
|
||||
colour.insert(target, false);
|
||||
stack.push((target, successors(target).into_iter()));
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
colour.insert(offset, true);
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
// The main chain: the first directory and each `next` target. The graph is acyclic here.
|
||||
let mut main_chain = vec![first];
|
||||
while let Some(&next) = main_chain.last().and_then(|at| chain_next.get(at)) {
|
||||
if main_chain.len() > self.parsed.len() {
|
||||
break;
|
||||
}
|
||||
main_chain.push(next);
|
||||
}
|
||||
Ok(Some(main_chain))
|
||||
}
|
||||
|
||||
fn directory(&mut self, offset: u64) -> Result<Option<(BTreeMap<u16, EntrySpan>, u64)>, CodecError> {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "field.bytes*2,field.declared*5,field.entries*3,field.parsed*3,field.value_spans*1,type.BTreeMap*2";
|
||||
collections: "field.bytes*2,field.declared*5,field.entries*3,field.examined_dirs*2,field.failed_dirs*8,field.parsed*2,field.value_spans*1,type.BTreeMap*2";
|
||||
scope: "TIFF directory table and physical value spans, bounded before directory or decoder allocations";
|
||||
loss: "malformed directory, incomplete value or pointer, directory cycle, work/byte budget";
|
||||
fallback: "do not assess pixels from an incomplete preflight";
|
||||
@@ -169,33 +372,65 @@ impl<R: FnMut(u64) -> Result<(), CodecError>> DirectoryWalk<'_, R> {
|
||||
}
|
||||
|
||||
if let Some(known) = self.parsed.get(&offset) {
|
||||
return Ok(Some(known.clone()));
|
||||
return Ok(DirOutcome::Ok(known.clone()));
|
||||
}
|
||||
if self.parsed.len() >= self.limits.max_ifds {
|
||||
return Err(bound("count"));
|
||||
if let Some(failed) = self.failed_dirs.get(&offset) {
|
||||
return Ok(match failed {
|
||||
FailedDir::Malformed => DirOutcome::Malformed,
|
||||
FailedDir::BranchBound(reason) => DirOutcome::BranchBound(reason.clone()),
|
||||
});
|
||||
}
|
||||
(self.reserve)(512)?;
|
||||
let Ok(dir) = directory_entries(self.bytes, offset, self.order, self.big, self.limits.max_entries) else { return Ok(None) };
|
||||
if self.examined_dirs.len() >= self.limits.max_ifds {
|
||||
return Ok(DirOutcome::GlobalBound(bound_reason("count")));
|
||||
}
|
||||
self.examined_dirs.insert(offset);
|
||||
match reserve(512) {
|
||||
Ok(()) => {}
|
||||
Err(CodecError::LimitExceeded(reason)) => return Ok(DirOutcome::GlobalBound(reason)),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
let Ok(dir) = directory_entries(self.bytes, offset, self.order, self.big, self.limits.max_entries) else {
|
||||
self.failed_dirs.insert(offset, FailedDir::Malformed);
|
||||
return Ok(DirOutcome::Malformed);
|
||||
};
|
||||
self.entries = self.entries.saturating_add(dir.read());
|
||||
if self.entries > self.limits.max_entries_total || (dir.read() >= self.limits.max_entries && dir.declared() > dir.read() as u64) {
|
||||
return Err(bound("entry"));
|
||||
if self.entries > self.limits.max_entries_total {
|
||||
return Ok(DirOutcome::GlobalBound(bound_reason("entry")));
|
||||
}
|
||||
if dir.read() >= self.limits.max_entries && dir.declared() > dir.read() as u64 {
|
||||
let reason = bound_reason("entry");
|
||||
self.failed_dirs.insert(offset, FailedDir::BranchBound(reason.clone()));
|
||||
return Ok(DirOutcome::BranchBound(reason));
|
||||
}
|
||||
if dir.declared() != dir.read() as u64 {
|
||||
return Ok(None);
|
||||
self.failed_dirs.insert(offset, FailedDir::Malformed);
|
||||
return Ok(DirOutcome::Malformed);
|
||||
}
|
||||
// Bound the indexes here and the directory inventory in the codec. Use actual
|
||||
// directory and entry counts, including overlaps, independently of payload size.
|
||||
(self.reserve)(160 * dir.declared())?;
|
||||
match reserve(160 * dir.declared()) {
|
||||
Ok(()) => {}
|
||||
Err(CodecError::LimitExceeded(reason)) => return Ok(DirOutcome::GlobalBound(reason)),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
let mut tags = BTreeMap::new();
|
||||
for pos in dir.positions() {
|
||||
let Some(value) = entry_span(self.bytes, pos, self.order, self.big, 0) else { return Ok(None) };
|
||||
let Some(value) = entry_span(self.bytes, pos, self.order, self.big, 0) else {
|
||||
self.failed_dirs.insert(offset, FailedDir::Malformed);
|
||||
return Ok(DirOutcome::Malformed);
|
||||
};
|
||||
if tags.insert(value.tag, value).is_some() {
|
||||
return Ok(None);
|
||||
self.failed_dirs.insert(offset, FailedDir::Malformed);
|
||||
return Ok(DirOutcome::Malformed);
|
||||
}
|
||||
let held = self.value_spans.entry(value.start).or_default();
|
||||
// Alias ranges with the same origin share physical bytes. A wider view
|
||||
// extends the reservation by just the bytes not seen at that offset.
|
||||
(self.reserve)(value.len.saturating_sub(*held).saturating_mul(8))?;
|
||||
match reserve(value.len.saturating_sub(*held).saturating_mul(8)) {
|
||||
Ok(()) => {}
|
||||
Err(CodecError::LimitExceeded(reason)) => return Ok(DirOutcome::GlobalBound(reason)),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
*held = (*held).max(value.len);
|
||||
self.end = self.end.max(value.start.saturating_add(value.len));
|
||||
}
|
||||
@@ -203,17 +438,31 @@ impl<R: FnMut(u64) -> Result<(), CodecError>> DirectoryWalk<'_, R> {
|
||||
// The codec describes each page separately and materializes its ExtraSamples.
|
||||
// Charge those vectors per page when several pages alias the same value bytes.
|
||||
let samples = tags.get(&tags::SAMPLES_PER_PIXEL).and_then(|span| self.uint(*span, 0)).unwrap_or(1).min(u64::from(u16::MAX));
|
||||
(self.reserve)(16 * extra.count.min(samples))?;
|
||||
match reserve(16 * extra.count.min(samples)) {
|
||||
Ok(()) => {}
|
||||
Err(CodecError::LimitExceeded(reason)) => return Ok(DirOutcome::GlobalBound(reason)),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
let table = if self.big { 8 + 20 * dir.declared() } else { 2 + 12 * dir.declared() };
|
||||
let Some(next_at) = offset.checked_add(table) else { return Ok(None) };
|
||||
let Some(next) = usize::try_from(next_at).ok().and_then(|at| self.offset(at)) else { return Ok(None) };
|
||||
let Some(next_at) = offset.checked_add(table) else {
|
||||
self.failed_dirs.insert(offset, FailedDir::Malformed);
|
||||
return Ok(DirOutcome::Malformed);
|
||||
};
|
||||
let Some(next) = usize::try_from(next_at).ok().and_then(|at| self.offset(at)) else {
|
||||
self.failed_dirs.insert(offset, FailedDir::Malformed);
|
||||
return Ok(DirOutcome::Malformed);
|
||||
};
|
||||
self.end = self.end.max(next_at.saturating_add(if self.big { 8 } else { 4 }));
|
||||
self.parsed.insert(offset, (tags.clone(), next));
|
||||
Ok(Some((tags, next)))
|
||||
Ok(DirOutcome::Ok((tags, next)))
|
||||
}
|
||||
|
||||
fn record_image_data(&mut self, tags: &BTreeMap<u16, EntrySpan>) -> Result<(), CodecError> {
|
||||
fn record_image_data(
|
||||
&mut self,
|
||||
tags: &BTreeMap<u16, EntrySpan>,
|
||||
reserve: &mut impl FnMut(u64) -> Result<(), CodecError>,
|
||||
) -> Result<(), CodecError> {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "type.BTreeMap*1";
|
||||
@@ -231,7 +480,7 @@ impl<R: FnMut(u64) -> Result<(), CodecError>> DirectoryWalk<'_, R> {
|
||||
] {
|
||||
let (Some(offsets), Some(sizes)) = (tags.get(&offsets), tags.get(&sizes)) else { continue };
|
||||
let chunks = offsets.count.min(sizes.count);
|
||||
(self.reserve)(chunks.saturating_mul(8))?;
|
||||
reserve(chunks.saturating_mul(8))?;
|
||||
for index in 0..chunks {
|
||||
if let (Some(start), Some(len)) = (self.uint(*offsets, index), self.uint(*sizes, index))
|
||||
&& len > 0
|
||||
@@ -246,8 +495,13 @@ impl<R: FnMut(u64) -> Result<(), CodecError>> DirectoryWalk<'_, R> {
|
||||
}
|
||||
|
||||
/// The directories a directory points at, each with whether it is read as a chain (SubIFD) or as a
|
||||
/// single directory (Exif, GPS, Interop). `None` when a pointer is unreadable or malformed.
|
||||
fn children(&mut self, tags: &BTreeMap<u16, EntrySpan>) -> Result<Option<Vec<(u64, bool)>>, CodecError> {
|
||||
/// single directory (Exif, GPS, Interop). Preserves any decoded prefix even if a later child tag
|
||||
/// is malformed or exceeds the reservation budget.
|
||||
fn children(
|
||||
&mut self,
|
||||
tags: &BTreeMap<u16, EntrySpan>,
|
||||
reserve: &mut impl FnMut(u64) -> Result<(), CodecError>,
|
||||
) -> Result<(Vec<(u64, bool)>, ChildrenStatus), CodecError> {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "type.BTreeMap*1,type.Vec*2";
|
||||
@@ -261,17 +515,23 @@ impl<R: FnMut(u64) -> Result<(), CodecError>> DirectoryWalk<'_, R> {
|
||||
for tag in [tags::SUB_IFDS, tags::EXIF_IFD, tags::GPS_IFD, tags::INTEROP_IFD] {
|
||||
let Some(children) = tags.get(&tag) else { continue };
|
||||
if tag != tags::SUB_IFDS && children.count != 1 {
|
||||
return Ok(None);
|
||||
return Ok((out, ChildrenStatus::Malformed));
|
||||
}
|
||||
match reserve(children.count.saturating_mul(8)) {
|
||||
Ok(()) => {}
|
||||
Err(CodecError::LimitExceeded(reason)) => return Ok((out, ChildrenStatus::Limited(reason))),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
(self.reserve)(children.count.saturating_mul(8))?;
|
||||
for index in 0..children.count {
|
||||
let Some(child) = self.uint(*children, index) else { return Ok(None) };
|
||||
let Some(child) = self.uint(*children, index) else {
|
||||
return Ok((out, ChildrenStatus::Malformed));
|
||||
};
|
||||
if child != 0 {
|
||||
out.push((child, tag == tags::SUB_IFDS));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(out))
|
||||
Ok((out, ChildrenStatus::Complete))
|
||||
}
|
||||
|
||||
fn uint(&self, span: EntrySpan, index: u64) -> Option<u64> {
|
||||
@@ -391,3 +651,259 @@ pub(crate) fn worker_open_bytes(bytes: &[u8], page: &craft_image_codecs::TiffPag
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Finding 2 (exact two-directory allowance shape): a directory that hits its per-directory
|
||||
/// entry cap counts against `max_ifds`, so a third distinct table beyond the allowance cannot
|
||||
/// be examined or change `Limited` into `MalformedOrCyclic`.
|
||||
#[test]
|
||||
fn directory_count_charges_entry_capped_directory_under_two_directory_allowance() {
|
||||
// Layout:
|
||||
// D0 at 8: 2 entries (SubIFD count=2 -> out-of-line [D1, D2], plus one dummy tag)
|
||||
// D1 at 38: 5 entries (exceeds max_entries=4 -> per-directory BranchBound)
|
||||
// D2 at 104: 2 entries (duplicate tag 40000 -> Malformed if examined)
|
||||
// SubIFD array at 134: [D1, D2]
|
||||
let d0_off = 8u32;
|
||||
let d1_off = d0_off + 2 + 2 * 12 + 4; // 38
|
||||
let d2_off = d1_off + 2 + 5 * 12 + 4; // 104
|
||||
let sub_arr_off = d2_off + 2 + 2 * 12 + 4; // 134
|
||||
|
||||
let build = |duplicate_in_third: bool| {
|
||||
let mut bytes = b"II*\0\x08\0\0\0".to_vec();
|
||||
let push_dir = |buf: &mut Vec<u8>, entries: &[(u16, u16, u32, u32)]| {
|
||||
buf.extend((entries.len() as u16).to_le_bytes());
|
||||
for &(tag, ty, count, val) in entries {
|
||||
buf.extend(tag.to_le_bytes());
|
||||
buf.extend(ty.to_le_bytes());
|
||||
buf.extend(count.to_le_bytes());
|
||||
buf.extend(val.to_le_bytes());
|
||||
}
|
||||
buf.extend(0u32.to_le_bytes());
|
||||
};
|
||||
push_dir(&mut bytes, &[(330, 4, 2, sub_arr_off), (40001, 4, 1, 0)]);
|
||||
assert_eq!(bytes.len() as u32, d1_off);
|
||||
push_dir(&mut bytes, &[(40010, 4, 1, 0), (40011, 4, 1, 1), (40012, 4, 1, 2), (40013, 4, 1, 3), (40014, 4, 1, 4)]);
|
||||
assert_eq!(bytes.len() as u32, d2_off);
|
||||
let third_tag2 = if duplicate_in_third { 40000 } else { 40002 };
|
||||
push_dir(&mut bytes, &[(40000, 4, 1, 1), (third_tag2, 4, 1, 2)]);
|
||||
assert_eq!(bytes.len() as u32, sub_arr_off);
|
||||
bytes.extend(d1_off.to_le_bytes());
|
||||
bytes.extend(d2_off.to_le_bytes());
|
||||
bytes
|
||||
};
|
||||
|
||||
fn run(bytes: &[u8], max_ifds: usize) -> Admission<'_> {
|
||||
let limits = ParseOptions { max_ifds, max_entries: 4, ..ParseOptions::default() };
|
||||
let mut state = init_walk(bytes, limits).unwrap();
|
||||
let mut reserve = |_: u64| Ok(());
|
||||
state.run_phase1(&mut reserve, false).unwrap();
|
||||
state.finish_phase2()
|
||||
}
|
||||
|
||||
// Under a 2-directory allowance, D0 + entry-capped D1 exhaust `max_ifds`; D2 must stay
|
||||
// unexamined whether or not it carries a duplicate tag.
|
||||
let malformed_third = build(true);
|
||||
let clean_third = build(false);
|
||||
assert!(matches!(run(&malformed_third, 2), Admission::Limited(_)));
|
||||
assert!(matches!(run(&clean_third, 2), Admission::Limited(_)));
|
||||
// Under a 3-directory allowance, D2 IS within budget and its duplicate tag grades MalformedOrCyclic.
|
||||
assert!(matches!(run(&malformed_third, 3), Admission::MalformedOrCyclic(Some(_))));
|
||||
assert!(matches!(run(&clean_third, 3), Admission::Limited(_)));
|
||||
}
|
||||
|
||||
/// Build a classic little-endian TIFF from `(subifds, exif, next, duplicate_tag)`.
|
||||
fn build_test_graph(nodes: &[(Vec<usize>, Option<usize>, Option<usize>, bool)]) -> Vec<u8> {
|
||||
let mut offsets = Vec::with_capacity(nodes.len());
|
||||
let mut cursor = 8u32;
|
||||
for (subs, exif, _, dup) in nodes {
|
||||
offsets.push(cursor);
|
||||
let count = 1u32 + u32::from(*dup) + u32::from(!subs.is_empty()) + u32::from(exif.is_some());
|
||||
cursor += 2 + count * 12 + 4;
|
||||
}
|
||||
let mut sub_arrays = Vec::with_capacity(nodes.len());
|
||||
for (subs, _, _, _) in nodes {
|
||||
if subs.len() > 1 {
|
||||
sub_arrays.push(Some(cursor));
|
||||
cursor += (subs.len() as u32) * 4;
|
||||
} else {
|
||||
sub_arrays.push(None);
|
||||
}
|
||||
}
|
||||
let mut bytes = b"II*\0\x08\0\0\0".to_vec();
|
||||
for (idx, (subs, exif, next, dup)) in nodes.iter().enumerate() {
|
||||
let mut entries: Vec<(u16, u16, u32, u32)> = Vec::new();
|
||||
if !subs.is_empty() {
|
||||
let val = if subs.len() == 1 { offsets[subs[0]] } else { sub_arrays[idx].unwrap() };
|
||||
entries.push((tags::SUB_IFDS, 4, subs.len() as u32, val));
|
||||
}
|
||||
if let Some(ex) = *exif {
|
||||
entries.push((tags::EXIF_IFD, 4, 1, offsets[ex]));
|
||||
}
|
||||
entries.push((40000, 4, 1, idx as u32));
|
||||
if *dup {
|
||||
entries.push((40000, 4, 1, idx as u32 + 1));
|
||||
}
|
||||
entries.sort_by_key(|e| e.0);
|
||||
bytes.extend((entries.len() as u16).to_le_bytes());
|
||||
for (tag, ty, cnt, val) in entries {
|
||||
bytes.extend(tag.to_le_bytes());
|
||||
bytes.extend(ty.to_le_bytes());
|
||||
bytes.extend(cnt.to_le_bytes());
|
||||
bytes.extend(val.to_le_bytes());
|
||||
}
|
||||
bytes.extend(next.map_or(0u32, |n| offsets[n]).to_le_bytes());
|
||||
}
|
||||
for (subs, _, _, _) in nodes {
|
||||
if subs.len() > 1 {
|
||||
for &child in subs {
|
||||
bytes.extend(offsets[child].to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(bytes.len() as u32, cursor);
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Round-2 Item 1 (Astra's Exif-to-SubIFD graph under global stops): when a decoded SubIFD
|
||||
/// pointer establishes a chain role for an already-examined Exif directory, its cached `next`
|
||||
/// edge must be installed immediately so a subsequent global stop (directory count or byte
|
||||
/// reservation) on an independent sibling cannot drop the established cycle in either sibling
|
||||
/// order — while an unexamined malformed sibling still stays outside the allowance.
|
||||
#[test]
|
||||
fn cached_chain_role_installs_edge_before_global_stop_in_both_sibling_orders() {
|
||||
// Astra's exact Exif/SubIFD graph:
|
||||
// 0 = D0: SubIFD [B1], Exif X
|
||||
// 1 = X: next -> D0 (when cyclic) or None (acyclic control)
|
||||
// 2..=11 = B1..B10 (chain of SubIFDs); B10 has SubIFD [X, B11] or [B11, X]
|
||||
// 12 = B11: independent sibling (duplicate tag in acyclic control to prove it stays unexamined)
|
||||
let build_astra_graph = |x_first: bool, cyclic: bool, b11_malformed: bool| -> Vec<u8> {
|
||||
let mut nodes = vec![(vec![2], Some(1), None, false), (vec![], None, cyclic.then_some(0), false)];
|
||||
for step in 0..10 {
|
||||
let subs = if step < 9 {
|
||||
vec![3 + step]
|
||||
} else if x_first {
|
||||
vec![1, 12]
|
||||
} else {
|
||||
vec![12, 1]
|
||||
};
|
||||
nodes.push((subs, None, None, false));
|
||||
}
|
||||
nodes.push((vec![], None, None, b11_malformed));
|
||||
build_test_graph(&nodes)
|
||||
};
|
||||
|
||||
// Measure the exact byte reservation right before B11's examination begins (12 tables cached).
|
||||
let probe_bytes = build_astra_graph(false, false, false);
|
||||
let mut reservations = Vec::new();
|
||||
{
|
||||
let limits = ParseOptions { max_depth: 11, max_ifds: 12, ..ParseOptions::default() };
|
||||
let mut state = init_walk(&probe_bytes, limits).unwrap();
|
||||
let mut reserve = |cost: u64| {
|
||||
reservations.push(cost);
|
||||
Ok(())
|
||||
};
|
||||
state.run_phase1(&mut reserve, false).unwrap();
|
||||
assert_eq!(state.walk.parsed.len(), 12);
|
||||
assert!(matches!(state.finish_phase2(), Admission::Limited(_)));
|
||||
}
|
||||
let exact_12_tables_budget: u64 = reservations.iter().sum();
|
||||
|
||||
fn run_count(bytes: &[u8]) -> (usize, Admission<'_>) {
|
||||
let limits = ParseOptions { max_depth: 11, max_ifds: 12, ..ParseOptions::default() };
|
||||
let mut state = init_walk(bytes, limits).unwrap();
|
||||
let mut reserve = |_: u64| Ok(());
|
||||
state.run_phase1(&mut reserve, false).unwrap();
|
||||
let cached = state.walk.parsed.len();
|
||||
(cached, state.finish_phase2())
|
||||
}
|
||||
fn run_bytes(bytes: &[u8], budget: u64) -> (usize, Admission<'_>) {
|
||||
let limits = ParseOptions { max_depth: 11, ..ParseOptions::default() };
|
||||
let mut state = init_walk(bytes, limits).unwrap();
|
||||
let mut rem = budget;
|
||||
let mut reserve = |cost: u64| {
|
||||
if cost > rem {
|
||||
return Err(CodecError::LimitExceeded("alternate image decode budget".into()));
|
||||
}
|
||||
rem -= cost;
|
||||
Ok(())
|
||||
};
|
||||
state.run_phase1(&mut reserve, false).unwrap();
|
||||
let cached = state.walk.parsed.len();
|
||||
(cached, state.finish_phase2())
|
||||
}
|
||||
|
||||
for x_first in [false, true] {
|
||||
let cyclic = build_astra_graph(x_first, true, false);
|
||||
let acyclic_malformed_sibling = build_astra_graph(x_first, false, true);
|
||||
|
||||
let (cached, outcome) = run_count(&cyclic);
|
||||
assert_eq!(cached, 12, "x_first={x_first}");
|
||||
assert!(
|
||||
matches!(outcome, Admission::MalformedOrCyclic(Some(ref r)) if r.contains("TIFF directory count bound")),
|
||||
"count stop cyclic x_first={x_first}"
|
||||
);
|
||||
let (cached, outcome) = run_count(&acyclic_malformed_sibling);
|
||||
assert_eq!(cached, 12, "x_first={x_first}");
|
||||
assert!(
|
||||
matches!(outcome, Admission::Limited(ref r) if r.contains("TIFF directory count bound")),
|
||||
"count stop acyclic x_first={x_first}: B11 must stay unexamined"
|
||||
);
|
||||
|
||||
let (cached, outcome) = run_bytes(&cyclic, exact_12_tables_budget);
|
||||
assert_eq!(cached, 12, "x_first={x_first}");
|
||||
assert!(
|
||||
matches!(outcome, Admission::MalformedOrCyclic(Some(ref r)) if r.contains("alternate image decode budget")),
|
||||
"byte stop cyclic x_first={x_first}"
|
||||
);
|
||||
let (cached, outcome) = run_bytes(&acyclic_malformed_sibling, exact_12_tables_budget);
|
||||
assert_eq!(cached, 12, "x_first={x_first}");
|
||||
assert!(
|
||||
matches!(outcome, Admission::Limited(ref r) if r.contains("alternate image decode budget")),
|
||||
"byte stop acyclic x_first={x_first}: B11 must stay unexamined"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reversed discovery order: a SubIFD pointer to X is decoded (from A at depth 1) BEFORE X is
|
||||
/// examined as Exif (depth 1), and sibling B hits `max_ifds = 3` before `(X, true, 2)` is popped.
|
||||
#[test]
|
||||
fn cached_chain_role_installs_edge_in_reversed_discovery_order() {
|
||||
for x_first in [false, true] {
|
||||
let subs_a = if x_first { vec![2, 3] } else { vec![3, 2] };
|
||||
// 0 = D0 (SubIFD A, Exif X), 1 = A (SubIFD [X, B] or [B, X]), 2 = X (next D0), 3 = B
|
||||
let cyclic = build_test_graph(&[
|
||||
(vec![1], Some(2), None, false),
|
||||
(subs_a.clone(), None, None, false),
|
||||
(vec![], None, Some(0), false),
|
||||
(vec![], None, None, false),
|
||||
]);
|
||||
let acyclic = build_test_graph(&[
|
||||
(vec![1], Some(2), None, false),
|
||||
(subs_a, None, None, false),
|
||||
(vec![], None, None, false),
|
||||
(vec![], None, None, true),
|
||||
]);
|
||||
for (is_cyclic, bytes) in [(true, &cyclic), (false, &acyclic)] {
|
||||
let limits = ParseOptions { max_ifds: 3, ..ParseOptions::default() };
|
||||
let mut state = init_walk(bytes, limits).unwrap();
|
||||
let mut reserve = |_: u64| Ok(());
|
||||
state.run_phase1(&mut reserve, false).unwrap();
|
||||
let outcome = state.finish_phase2();
|
||||
if is_cyclic {
|
||||
assert!(
|
||||
matches!(outcome, Admission::MalformedOrCyclic(Some(ref r)) if r.contains("TIFF directory count bound")),
|
||||
"reversed discovery cyclic x_first={x_first}"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
matches!(outcome, Admission::Limited(ref r) if r.contains("TIFF directory count bound")),
|
||||
"reversed discovery acyclic x_first={x_first}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,6 +140,42 @@ fn le16(v: &mut Vec<u8>, x: u16) {
|
||||
fn le32(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
fn le64(v: &mut Vec<u8>, x: u64) {
|
||||
v.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
fn write_zip64_eocd(out: &mut Vec<u8>, count: u64, cd_size: u64, cd_off: u64) -> usize {
|
||||
let off = out.len();
|
||||
le32(out, 0x0606_4B50);
|
||||
le64(out, 44);
|
||||
le16(out, 45);
|
||||
le16(out, 45);
|
||||
le32(out, 0);
|
||||
le32(out, 0);
|
||||
le64(out, count);
|
||||
le64(out, count);
|
||||
le64(out, cd_size);
|
||||
le64(out, cd_off);
|
||||
off
|
||||
}
|
||||
fn write_zip64_locator(out: &mut Vec<u8>, z64_off: u64, total_disks: u32) -> usize {
|
||||
let off = out.len();
|
||||
le32(out, 0x0706_4B50);
|
||||
le32(out, 0);
|
||||
le64(out, z64_off);
|
||||
le32(out, total_disks);
|
||||
off
|
||||
}
|
||||
fn plain_zip64(recs: &[Rec]) -> (Vec<u8>, usize, usize) {
|
||||
let mut out = Vec::new();
|
||||
let offs = write_locals(&mut out, recs);
|
||||
let cd = out.len() as u64;
|
||||
write_cd(&mut out, recs, &offs, &all(recs.len()), 0);
|
||||
let size = out.len() as u64 - cd;
|
||||
let z64_off = write_zip64_eocd(&mut out, recs.len() as u64, size, cd);
|
||||
let loc_off = write_zip64_locator(&mut out, z64_off as u64, 1);
|
||||
write_eocd(&mut out, 0xFFFF, 0xFFFF_FFFF, 0xFFFF_FFFF);
|
||||
(out, z64_off, loc_off)
|
||||
}
|
||||
fn write_locals(out: &mut Vec<u8>, recs: &[Rec]) -> Vec<u64> {
|
||||
let mut offs = Vec::new();
|
||||
for r in recs {
|
||||
@@ -366,13 +402,7 @@ fn stored_nested_case(nested: bool) {
|
||||
assert_eq!(a.offset(), 0);
|
||||
assert_eq!(a.central_directory_start(), 4044);
|
||||
let r = run(&format!("stored nested={nested}"), &z);
|
||||
if nested {
|
||||
// The measured ambiguity-retirement run breaks frozen round21/22
|
||||
// outcomes. Keep this disclosed section-5 residual while it still binds.
|
||||
disputed("stored nested residual", &r).unwrap();
|
||||
} else {
|
||||
assert_clean(&r);
|
||||
}
|
||||
assert_clean(&r);
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip() {
|
||||
@@ -382,6 +412,353 @@ fn stored_nested_zip() {
|
||||
fn stored_no_signature_control() {
|
||||
stored_nested_case(false);
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_non_final_entry_stays_disputed() {
|
||||
// High 1: identical in shape to stored_nested_zip, but with one further ordinary part after
|
||||
// the embedded-zip entry so the embedded zip is NOT the final central-directory record.
|
||||
let inner = plain(&clean_recs(false));
|
||||
for (nested, label) in [(false, "non-final control"), (true, "non-final stored nested zip")] {
|
||||
let body = if nested { inner.clone() } else { vec![b'z'; inner.len()] };
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", body));
|
||||
recs.push(rec(b"word/extra.xml", r#"<?xml version="1.0" encoding="UTF-8"?><x/>"#));
|
||||
let z = plain(&recs);
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(z.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 7);
|
||||
assert_eq!(a.offset(), 0);
|
||||
for i in 0..a.len() {
|
||||
let mut f = a.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
}
|
||||
let r = run(label, &z);
|
||||
if nested {
|
||||
disputed(label, &r).unwrap();
|
||||
assert!(r.coverage_notes.iter().any(|n| n.contains("selection or decoded names disagree")));
|
||||
} else {
|
||||
assert_clean(&r);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_cd_last_not_physically_last_stays_disputed() {
|
||||
// Central directory lists the embedded-zip entry last while another entry's data sits
|
||||
// physically after it in the file. Clearance requires the central-last entry to also be
|
||||
// physically last, so the dispute must stay standing.
|
||||
let inner = plain(&clean_recs(false));
|
||||
for (nested, label) in [(false, "cd-last non-physical control"), (true, "cd-last not physically last stored nested zip")] {
|
||||
let body = if nested { inner.clone() } else { vec![b'z'; inner.len()] };
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", body));
|
||||
recs.push(rec(b"word/extra.xml", r#"<?xml version="1.0" encoding="UTF-8"?><x/>"#));
|
||||
let mut z = Vec::new();
|
||||
let offs = write_locals(&mut z, &recs);
|
||||
assert!(offs[6] > offs[5]);
|
||||
let cd = z.len() as u64;
|
||||
write_cd(&mut z, &recs, &offs, &[0, 1, 2, 3, 4, 6, 5], 0);
|
||||
let size = z.len() as u64 - cd;
|
||||
write_eocd(&mut z, recs.len() as u16, size as u32, cd as u32);
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(z.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 7, "{label}");
|
||||
assert_eq!(a.offset(), 0, "{label}");
|
||||
for i in 0..a.len() {
|
||||
let mut f = a.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
}
|
||||
let r = run(label, &z);
|
||||
if nested {
|
||||
disputed(label, &r).unwrap();
|
||||
assert!(r.coverage_notes.iter().any(|n| n.contains("selection or decoded names disagree")), "{label}");
|
||||
} else {
|
||||
assert_clean(&r);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_inconsistent_local_header_stays_disputed() {
|
||||
// High 2: stored_nested_zip shape with the final containing entry's local header made
|
||||
// inconsistent with its central record must keep the dispute standing (Incomplete).
|
||||
let inner = plain(&clean_recs(false));
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner.clone()));
|
||||
let base = plain(&recs);
|
||||
let local = {
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(base.as_slice())).unwrap();
|
||||
a.by_name("word/embeddings/pkg.bin").unwrap().header_start() as usize
|
||||
};
|
||||
assert_eq!(&base[local..local + 4], &[0x50, 0x4B, 0x03, 0x04]);
|
||||
|
||||
// 1. Local compressed size disagrees with central compressed size (no data-descriptor flag).
|
||||
let mut bad_size = base.clone();
|
||||
let wrong_size = (inner.len() as u32).saturating_sub(1);
|
||||
bad_size[local + 18..local + 22].copy_from_slice(&wrong_size.to_le_bytes());
|
||||
|
||||
// 2. Local filename bytes disagree with central record's name (same length, same data_start).
|
||||
let mut bad_name = base.clone();
|
||||
let name_len = u16::from_le_bytes(bad_name[local + 26..local + 28].try_into().unwrap()) as usize;
|
||||
bad_name[local + 30 + name_len - 1] = b'x';
|
||||
|
||||
// 3. Data-descriptor bit set only in local header (central flag remains 0) with zeroed local sizes.
|
||||
let mut bad_dd = base.clone();
|
||||
bad_dd[local + 6..local + 8].copy_from_slice(&0x0008u16.to_le_bytes());
|
||||
bad_dd[local + 18..local + 22].copy_from_slice(&0u32.to_le_bytes());
|
||||
bad_dd[local + 22..local + 26].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
for (label, z) in [
|
||||
("inconsistent local compressed size", bad_size),
|
||||
("inconsistent local filename", bad_name),
|
||||
("inconsistent local data-descriptor flag", bad_dd),
|
||||
] {
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(z.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 6, "{label}");
|
||||
assert_eq!(a.offset(), 0, "{label}");
|
||||
for i in 0..a.len() {
|
||||
let mut f = a.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
}
|
||||
let r = run(label, &z);
|
||||
disputed(label, &r).unwrap();
|
||||
assert!(r.coverage_notes.iter().any(|n| n.contains("selection or decoded names disagree")), "{label}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_legitimate_local_header_variants_pass() {
|
||||
// High 2 positive boundaries: data-descriptor flag with zeroed local sizes and legitimate
|
||||
// local-vs-central extra-field differences must remain accepted for the final entry.
|
||||
let inner = plain(&clean_recs(false));
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner.clone()));
|
||||
|
||||
// Variant 1: data-descriptor flag set in both local and central headers, zeroed local sizes,
|
||||
// trailing 16-byte data descriptor before the central directory.
|
||||
{
|
||||
let mut out = Vec::new();
|
||||
let mut offs = write_locals(&mut out, &recs[..recs.len() - 1]);
|
||||
let last = recs.last().unwrap();
|
||||
offs.push(out.len() as u64);
|
||||
let crc = crc32(&last.body);
|
||||
let len = last.body.len() as u32;
|
||||
le32(&mut out, 0x0403_4B50);
|
||||
le16(&mut out, 20);
|
||||
le16(&mut out, last.flags | 0x0008);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0x21);
|
||||
le32(&mut out, 0);
|
||||
le32(&mut out, 0);
|
||||
le32(&mut out, 0);
|
||||
le16(&mut out, last.name.len() as u16);
|
||||
le16(&mut out, 0);
|
||||
out.extend_from_slice(&last.name);
|
||||
out.extend_from_slice(&last.body);
|
||||
le32(&mut out, 0x0807_4B50);
|
||||
le32(&mut out, crc);
|
||||
le32(&mut out, len);
|
||||
le32(&mut out, len);
|
||||
let cd = out.len() as u64;
|
||||
let mut cd_recs = recs.clone();
|
||||
cd_recs.last_mut().unwrap().flags |= 0x0008;
|
||||
write_cd(&mut out, &cd_recs, &offs, &all(cd_recs.len()), 0);
|
||||
let size = out.len() as u64 - cd;
|
||||
write_eocd(&mut out, cd_recs.len() as u16, size as u32, cd as u32);
|
||||
assert_clean(&run("stored nested zip with data descriptor", &out));
|
||||
}
|
||||
|
||||
// Variant 2: local header carries an extra field absent from the central directory record.
|
||||
{
|
||||
let mut out = Vec::new();
|
||||
let mut offs = write_locals(&mut out, &recs[..recs.len() - 1]);
|
||||
let last = recs.last().unwrap();
|
||||
offs.push(out.len() as u64);
|
||||
let local_extra = [0xFE, 0xCA, 0x04, 0x00, 1, 2, 3, 4];
|
||||
le32(&mut out, 0x0403_4B50);
|
||||
le16(&mut out, 20);
|
||||
le16(&mut out, last.flags);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0x21);
|
||||
le32(&mut out, crc32(&last.body));
|
||||
le32(&mut out, last.body.len() as u32);
|
||||
le32(&mut out, last.body.len() as u32);
|
||||
le16(&mut out, last.name.len() as u16);
|
||||
le16(&mut out, local_extra.len() as u16);
|
||||
out.extend_from_slice(&last.name);
|
||||
out.extend_from_slice(&local_extra);
|
||||
out.extend_from_slice(&last.body);
|
||||
let cd = out.len() as u64;
|
||||
write_cd(&mut out, &recs, &offs, &all(recs.len()), 0);
|
||||
let size = out.len() as u64 - cd;
|
||||
write_eocd(&mut out, recs.len() as u16, size as u32, cd as u32);
|
||||
assert_clean(&run("stored nested zip with local-only extra field", &out));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip64_embedded_final_entry_passes() {
|
||||
// An embedded ZIP64 archive as the central-and-physically-last entry clears cleanly whether
|
||||
// its locator holds an inner-relative offset or an outer-file offset inside the payload.
|
||||
let (inner_rel, inner_z64, inner_loc) = plain_zip64(&clean_recs(false));
|
||||
assert_eq!(zip::ZipArchive::new(Cursor::new(inner_rel.as_slice())).unwrap().len(), 5);
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner_rel.clone()));
|
||||
let z_rel = plain(&recs);
|
||||
let payload_start = {
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(z_rel.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 6);
|
||||
assert_eq!(a.offset(), 0);
|
||||
a.by_name("word/embeddings/pkg.bin").unwrap().data_start() as usize
|
||||
};
|
||||
assert_clean(&run("stored nested zip64 (inner-relative locator)", &z_rel));
|
||||
|
||||
let mut inner_outer = inner_rel;
|
||||
let outer_z64 = (payload_start + inner_z64) as u64;
|
||||
inner_outer[inner_loc + 8..inner_loc + 16].copy_from_slice(&outer_z64.to_le_bytes());
|
||||
recs.pop();
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner_outer));
|
||||
let z_outer = plain(&recs);
|
||||
assert_clean(&run("stored nested zip64 (outer-adjusted record inside payload)", &z_outer));
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip64_record_outside_payload_stays_disputed() {
|
||||
// Comment B: a competing ZIP64 footer whose adjacent ZIP64 EOCD record lies outside the final
|
||||
// entry's payload (in its local-header extra field) while the locator+EOCD start at
|
||||
// payload_start must NOT clear the dispute.
|
||||
for (label, total_disks) in
|
||||
[("straddling zip64 record outside payload (valid metadata)", 1u32), ("straddling zip64 record outside payload (multi-disk locator)", 2u32)]
|
||||
{
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
let mut out = Vec::new();
|
||||
let mut offs = write_locals(&mut out, &recs);
|
||||
let pkg_local = out.len();
|
||||
offs.push(pkg_local as u64);
|
||||
let pkg_name = b"word/embeddings/pkg.bin";
|
||||
let mut local_extra = Vec::new();
|
||||
le16(&mut local_extra, 0xCAFE);
|
||||
le16(&mut local_extra, 56);
|
||||
let z64_rel_in_extra = write_zip64_eocd(&mut local_extra, 1, 46, 0);
|
||||
assert_eq!(local_extra.len(), 60);
|
||||
let payload_start = pkg_local + 30 + pkg_name.len() + local_extra.len();
|
||||
let z64_outer_off = pkg_local + 30 + pkg_name.len() + z64_rel_in_extra;
|
||||
assert_eq!(z64_outer_off + 56, payload_start);
|
||||
|
||||
let mut payload = Vec::new();
|
||||
write_zip64_locator(&mut payload, z64_outer_off as u64, total_disks);
|
||||
write_eocd(&mut payload, 0xFFFF, 0xFFFF_FFFF, 0xFFFF_FFFF);
|
||||
assert_eq!(payload.len(), 42);
|
||||
|
||||
le32(&mut out, 0x0403_4B50);
|
||||
le16(&mut out, 20);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0x21);
|
||||
le32(&mut out, crc32(&payload));
|
||||
le32(&mut out, payload.len() as u32);
|
||||
le32(&mut out, payload.len() as u32);
|
||||
le16(&mut out, pkg_name.len() as u16);
|
||||
le16(&mut out, local_extra.len() as u16);
|
||||
out.extend_from_slice(pkg_name);
|
||||
out.extend_from_slice(&local_extra);
|
||||
assert_eq!(out.len(), payload_start);
|
||||
out.extend_from_slice(&payload);
|
||||
|
||||
recs.push(rec(pkg_name, payload));
|
||||
let cd = out.len() as u64;
|
||||
write_cd(&mut out, &recs, &offs, &all(recs.len()), 0);
|
||||
let size = out.len() as u64 - cd;
|
||||
write_eocd(&mut out, recs.len() as u16, size as u32, cd as u32);
|
||||
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(out.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 6, "{label}");
|
||||
assert_eq!(a.offset(), 0, "{label}");
|
||||
for i in 0..a.len() {
|
||||
let mut f = a.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
}
|
||||
let r = run(label, &out);
|
||||
disputed(label, &r).unwrap();
|
||||
assert!(r.coverage_notes.iter().any(|n| n.contains("selection or decoded names disagree")), "{label}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_preserves_outer_defects() {
|
||||
let inner = plain(&clean_recs(false));
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs[2] = rec(b"word/document.xml", doc(&fnref("5")));
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner));
|
||||
let z = plain(&recs);
|
||||
let r = run("stored nested outer defect", &z);
|
||||
assert_eq!(r.verdict, Verdict::Fail);
|
||||
assert_eq!(rules(&r), ["REF-NOTE@word/document.xml"]);
|
||||
assert!(r.checks_run.contains(&"PKG-DUP-ENTRY"));
|
||||
}
|
||||
#[test]
|
||||
fn stored_payload_forged_eof_eocd_stays_disputed() {
|
||||
// An inner EOCD whose comment length is forged to reach the outer EOF extends beyond
|
||||
// the entry's verified payload span and remains reachable by an exact-EOF reader.
|
||||
let mut inner = plain(&clean_recs(false));
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner.clone()));
|
||||
let outer = plain(&recs);
|
||||
let inner_eocd_in_outer = 4044 - 22;
|
||||
let forged_comment = u16::try_from(outer.len() - inner_eocd_in_outer - 22).unwrap();
|
||||
let inner_eocd = inner.len() - 22;
|
||||
inner[inner_eocd + 20..inner_eocd + 22].copy_from_slice(&forged_comment.to_le_bytes());
|
||||
recs.pop();
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner));
|
||||
let z = plain(&recs);
|
||||
let r = run("stored payload forged eof eocd", &z);
|
||||
disputed("forged eof eocd inside stored payload", &r).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn gap_eocd_outside_payload_stays_disputed() {
|
||||
// A competing EOCD placed in an unreferenced gap after the central directory is not inside
|
||||
// any entry's verified payload span, so it must keep disputing the outer footer.
|
||||
let recs = clean_recs(false);
|
||||
let mut z = Vec::new();
|
||||
let offs = write_locals(&mut z, &recs);
|
||||
let start = z.len() as u32;
|
||||
write_cd(&mut z, &recs, &offs, &all(recs.len()), 0);
|
||||
let size = z.len() as u32 - start;
|
||||
write_eocd(&mut z, (recs.len() - 1) as u16, size, start);
|
||||
write_eocd(&mut z, recs.len() as u16, size, start);
|
||||
let r = run("gap eocd outside payload", &z);
|
||||
disputed("gap eocd outside payload", &r).unwrap();
|
||||
}
|
||||
fn untyped_case(reverse: bool) {
|
||||
let mut p = with_footnotes(&["1"], &fnref("5"));
|
||||
p.put("[Content_Types].xml", ct(&[("/word/footnotes.xml", CT_FN)]));
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
# Localization parity with Microsoft Word
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Bosnian interface: `bs` in the language list, `bs-BA` system locales, catalog in storytold/craft-i18n); previously trivial (Arabic: the Home tab's Styles gallery reads from the right, its arrows at the left (#5566); readiness unchanged); previously trivial (table sort and formulas read the Panamanian balboa's `B/.` around a number (`B/. 1,250.50`, `1,250.50 B/.`), as Word does, matched only at the ends of the text so `1/.5` stays a fraction); previously trivial (Arabic: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously minor (Options › Language redesign: Your languages, Add a language…, Set as default; the Dictionaries folder moved from Proofing); previously trivial (Language packs: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (Language lists: every installed and available Language pack's language can be chosen in Set Proofing Language, installed ones in Review › Language and the status bar; craft-i18n.rev at 9d6d54d: region names and the Language (Region) template in 35 locales, craft-i18n#145); previously trivial (craft-i18n.rev at cde4900: rows for Options › Language, the missing-pack bar and 28 Language pack language names in 35 locales, craft-i18n#136); previously trivial (craft-proof pin: French elision suggestions first, ca-ES-valencia reads the ca-valencia pack); previously minor (Arabic `ar` interface: craft-i18n catalog, mirrored shell, font fallback, #1195; 28 languages); previously trivial (Language packs: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland)); previously trivial (Language packs: language-packs-1 is published and pinned, 61 packs; the language requests it covers); previously minor (Language packs: languages beyond English install their spelling dictionary and hyphenation as a pack from File › Options › Language or the missing-pack bar; the default build embeds English Language data only) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-01 · **Change:** minor (Hindi interface: `hi` in the language list, `hi-IN` system locales, Devanagari interface face, catalog in storytold/craft-i18n); previously minor (Bosnian interface: `bs` in the language list, `bs-BA` system locales, catalog in storytold/craft-i18n); previously trivial (Arabic: the Home tab's Styles gallery reads from the right, its arrows at the left (#5566); readiness unchanged); previously trivial (table sort and formulas read the Panamanian balboa's `B/.` around a number (`B/. 1,250.50`, `1,250.50 B/.`), as Word does, matched only at the ends of the text so `1/.5` stays a fraction); previously trivial (Arabic: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously minor (Options › Language redesign: Your languages, Add a language…, Set as default; the Dictionaries folder moved from Proofing); previously trivial (Language packs: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (Language lists: every installed and available Language pack's language can be chosen in Set Proofing Language, installed ones in Review › Language and the status bar; craft-i18n.rev at 9d6d54d: region names and the Language (Region) template in 35 locales, craft-i18n#145); previously trivial (craft-i18n.rev at cde4900: rows for Options › Language, the missing-pack bar and 28 Language pack language names in 35 locales, craft-i18n#136); previously trivial (craft-proof pin: French elision suggestions first, ca-ES-valencia reads the ca-valencia pack); previously minor (Arabic `ar` interface: craft-i18n catalog, mirrored shell, font fallback, #1195; 28 languages); previously trivial (Language packs: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland)); previously trivial (Language packs: language-packs-1 is published and pinned, 61 packs; the language requests it covers); previously minor (Language packs: languages beyond English install their spelling dictionary and hyphenation as a pack from File › Options › Language or the missing-pack bar; the default build embeds English Language data only) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
|
||||
Interface languages, script support and proofing per language. How translation works (adding a
|
||||
language, the embedded catalogs): `crates/ui-egui/src/i18n.rs`. The catalogs, their format and
|
||||
@@ -21,8 +21,8 @@ native-speaker review (human).
|
||||
|
||||
## What WordCraft ships (measured)
|
||||
|
||||
- **29 interface languages**: English plus `zh-hans`, `zh-hant`, `ja`, Korean `ko` (#1216), `uk`, `es`, `pt-br`,
|
||||
Serbian `sr`/`sr-latn` (#250), Estonian `et`, Turkish `tr`, Russian `ru`, Italian `it` (#594), German `de` (#574), Polish `pl`, Czech `cs`, Hungarian `hu`, French `fr`, Bulgarian `bg`, Vietnamese `vi` (#1434), Swedish `sv` (#1219), Croatian `hr` (#1271), Romanian `ro`, Slovenian `sl`, Dutch `nl`, Danish `da` (#2722) Arabic `ar` (#1195) and Bosnian `bs`. Catalogs have 2,061–2,730 entries
|
||||
- **30 interface languages**: English plus `zh-hans`, `zh-hant`, `ja`, Korean `ko` (#1216), `uk`, `es`, `pt-br`,
|
||||
Serbian `sr`/`sr-latn` (#250), Estonian `et`, Turkish `tr`, Russian `ru`, Italian `it` (#594), German `de` (#574), Polish `pl`, Czech `cs`, Hungarian `hu`, French `fr`, Bulgarian `bg`, Vietnamese `vi` (#1434), Swedish `sv` (#1219), Croatian `hr` (#1271), Romanian `ro`, Slovenian `sl`, Dutch `nl`, Danish `da` (#2722) Arabic `ar` (#1195), Bosnian `bs` and Hindi `hi`. Catalogs have 2,061–2,800 entries
|
||||
each; Polish has every key of every other catalog, including the built-in style names and the equation gallery, except the citation style names only Hungarian, Bulgarian, Swedish, Romanian and Slovenian translate so far. A missing translation falls back to English and never fails a test or
|
||||
build. `cargo xtask i18n-report`, part of `cargo xtask ci`, prints per language the interface
|
||||
strings its catalog lacks: everything the interface audit saw looked up, the ribbon tabs, command
|
||||
@@ -61,7 +61,7 @@ shared items below.
|
||||
| English | en | source (100%) | ✅ | Latin ✅ | yes | **full** | 0 |
|
||||
| Simplified Chinese (Mandarin) | zh-hans | 929 entries; 98% of extracted, ~95% of visible | most; newer panes English | CJK ✅, IME ✅; Windows UI font fixed (#248); interface font chain covers every catalog character, installed CJK font after the embedded ones when it doesn't, PingFang found on macOS 12 (#486); font list by Chinese names (宋体, 微软雅黑, #505); word count counts each Han ideograph and kana as a word, not punctuation (#4547); no vertical text | no | partial | 3–5 |
|
||||
| Spanish | es | ~930; 98% / ~95% | most | Latin ✅ | no | partial | 1–2 |
|
||||
| Hindi | hi | 0 | ❌ | Devanagari shaping via HarfRust, untested; no hyphenation | no | none | 4–6 |
|
||||
| Hindi | hi | 2,800 entries (craft-i18n `locales/hi/wordcraft.tsv`) | most; newer panes English | Devanagari interface face (craft-fonts Noto Sans Devanagari); document shaping via HarfRust; no hyphenation; no proofing | yes | partial | 2–4 (proofing, hyphenation) |
|
||||
| Arabic | ar | ~2,730 entries (craft-i18n `locales/ar/wordcraft.tsv`); 98% / ~95% | most; newer panes English | shaping, joining, lam-alef, bidi ✅ (#207); letters join across a change of formatting and past hidden or deleted text ✅ (#4093); mirrored UI ✅ (#1195; dialogs, tables and galleries read right to left); Arabic UI font fallback; no kashida; no proofing | no | partial | 2–4 (review + kashida/proofing elsewhere) |
|
||||
| French | fr | 2,615 entries (complete catalog) | all | Latin ✅ | no | partial (spelling and suggestions from the French Language pack, elided forms first: `Jadore` → `J'adore`; no grammar marks) | 1–2 (grammar) |
|
||||
| Portuguese | pt-br (pt-PT none) | ~930; 98% / ~95% (pt-BR) | most | Latin ✅ | no | partial | 2–4 (pt-BR finish + pt-PT) |
|
||||
@@ -98,6 +98,7 @@ Slovenian (`sl-SI` system locales, `{"value":"sl"}`) has 2,614 entries: every ke
|
||||
catalog. Counts use count-neutral wording (`Besede: 21`); terminology: [`localization-sl.md`](localization-sl.md).
|
||||
Slovenian proofing is not included.
|
||||
Bosnian (`bs-BA` system locales, `{"value":"bs"}`) is Latin script; Cyrillic Bosnian stays in English. Its craft-i18n catalog has 2,508 WordCraft entries plus the shared catalog, with `one|few|other` plural rows. The catalog is an AI-assisted draft not yet reviewed by a native speaker; Bosnian proofing is not included; terminology: [`localization-bs.md`](localization-bs.md).
|
||||
Hindi (`hi-IN` system locales, `{"value":"hi"}`) is Devanagari script, drawn by the craft-fonts Noto Sans Devanagari interface face. Its craft-i18n catalog has 2,800 WordCraft entries plus the shared catalog, an AI-assisted draft reviewed by a native speaker. Hindi proofing is not included, so the Hindi interface doesn't set the language of new documents.
|
||||
Hungarian follows `hu-HU` system locales and `{"value":"hu"}`, with a complete catalog of 2,419 entries: every key of
|
||||
the Russian catalog, built-in style names shown translated, plus the citation style names. Hungarian proofing is not included; terminology and conventions:
|
||||
[`localization-hu.md`](localization-hu.md).
|
||||
@@ -114,14 +115,9 @@ region's language is Spanish (`es-UY` on a Uruguayan system, `es-MX` on a Mexica
|
||||
Spain's `es-ES` (#3360).
|
||||
|
||||
**Interface audit (runs in CI).** `cargo xtask i18n-report` runs `untranslated_interface_text`,
|
||||
which lays the app out in a pseudo-language (tabs, File pages, dialogs, panes, the right-click
|
||||
menu, and a real hover and click on the Citation Style ribbon menu) and fails on visible text that
|
||||
skipped the catalog. It then prints the missing-translation report described above, which never fails.
|
||||
PR checks also retain the Arabic placement checks and the ribbon overlap cases in English, German and
|
||||
Arabic. The daily FreeBSD x86_64 workspace test run sets `WORDCRAFT_FULL_LOCALE_AUDIT=1` to also
|
||||
crawl every ribbon control in the original audit, run the full Arabic width/state sweep and check every
|
||||
offered locale on every ordinary ribbon tab. Set that same variable with the pinned catalogs to run
|
||||
the full sweep locally. Proper names (citation styles such as APA or
|
||||
which lays the app out in a pseudo-language (every tab, File page, dialog, pane, the right-click
|
||||
menu, and a hover and a click on every ribbon control) and fails on visible text that skipped the
|
||||
catalog. It then prints the missing-translation report described above, which never fails. Proper names (citation styles such as APA or
|
||||
GOST, LaTeX, Unicode) and `bad parameters:` errors, which name a command's JSON parameters for
|
||||
scripts and MCP, stay English. Size labels (Envelopes, Labels, Layout › Size) are translated
|
||||
patterns (`{name} {height} × {width} in`) with the region's decimal separator; paper names
|
||||
@@ -281,6 +277,7 @@ WordCraft keeps 2,54 cm).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-01 | minor | Hindi interface (`hi`, Devanagari): listed in `LANGUAGES`, `hi-IN` system locales, saved preference and bundled-font tests; catalog in storytold/craft-i18n (`locales/hi/wordcraft.tsv`), `craft-i18n.rev` at 217f413; no Hindi proofing |
|
||||
| 2026-10-29 | minor | Bosnian interface (`bs`, Latin script): listed in `LANGUAGES`, `bs-BA` system locales, saved preference and bundled-font tests; catalog in storytold/craft-i18n (`locales/bs/wordcraft.tsv`); no Bosnian proofing |
|
||||
| 2026-11-06 | trivial | Arabic: the Home tab's Styles gallery reads from the right: Normal is the rightmost tile and the scroll arrows and More sit at the gallery's left end, as the rest of the mirrored ribbon (#5566); left to right is unchanged; regression test `the_styles_gallery_reads_from_the_right_in_a_right_to_left_interface` |
|
||||
| 2026-11-05 | trivial | Arabic letters join across a change of formatting and past hidden or deleted text (#4093) |
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry.
|
||||
|
||||
**510 of 522 catalog features have commands (97.7%).**
|
||||
**512 of 524 catalog features have commands (97.7%).**
|
||||
|
||||
| Tab | Live | Total |
|
||||
|---|---|---|
|
||||
@@ -16,7 +16,7 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-
|
||||
| Layout | 23 | 23 |
|
||||
| References | 25 | 25 |
|
||||
| Mailings | 23 | 23 |
|
||||
| Review | 29 | 31 |
|
||||
| Review | 31 | 33 |
|
||||
| View | 29 | 29 |
|
||||
| Read Mode | 2 | 3 |
|
||||
| Developer | 11 | 11 |
|
||||
@@ -32,7 +32,7 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-
|
||||
| Editing | 41 | 41 |
|
||||
| Tools | 7 | 7 |
|
||||
|
||||
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 510 yes, 12 no (window 3, os 8, engine-gap 1), 0 partial, 0 unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.
|
||||
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 512 yes, 12 no (window 3, os 8, engine-gap 1), 0 partial, 0 unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.
|
||||
|
||||
## Missing
|
||||
|
||||
|
||||
+2
-1
File diff suppressed because one or more lines are too long
@@ -128,6 +128,6 @@ modules:
|
||||
# the two equal).
|
||||
- type: git
|
||||
url: https://github.com/storytold/craft-i18n
|
||||
commit: e56d26244bbac099bfd42e23fb12f78a4be418a7
|
||||
commit: 217f4130d7d3dbb21a160f23f6b0021918906cc0
|
||||
dest: craft-i18n
|
||||
- cargo-sources.json
|
||||
|
||||
Reference in New Issue
Block a user