mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-01 22:19:41 +00:00
Compare commits
55
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 | ||
|
|
14112e7137 | ||
|
|
b4fffa91cc | ||
|
|
5ad1c48b3e | ||
|
|
4daed0b5ad | ||
|
|
d22500664d | ||
|
|
effb736735 | ||
|
|
d7aac19341 | ||
|
|
055a9065f5 | ||
|
|
5265924f29 | ||
|
|
0f241aef67 | ||
|
|
6478152244 | ||
|
|
1ec6f0bb58 | ||
|
|
aaaeff2b94 | ||
|
|
e1f261501c | ||
|
|
837999196a | ||
|
|
13f5e9702c | ||
|
|
0eace8de49 | ||
|
|
63863ec62d | ||
|
|
b4f0a3abad | ||
|
|
ff98927ea6 | ||
|
|
fff580d8f0 | ||
|
|
4b3e5d52df | ||
|
|
53bbaa8978 | ||
|
|
813f069712 | ||
|
|
43c38dfb56 | ||
|
|
6d6ab5f4dc | ||
|
|
54f6709a97 | ||
|
|
c6d71b829a | ||
|
|
af26131063 | ||
|
|
9b13180006 | ||
|
|
2ca5bf5dfa | ||
|
|
1f6cf16029 | ||
|
|
18bbf00090 |
@@ -83,7 +83,9 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
@@ -95,7 +97,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -11,9 +11,9 @@ permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
|
||||
# Automatic Stage 2 signer dispatch for completed scheduled nightly producer runs.
|
||||
if: >-
|
||||
false && github.repository == 'storytold/wordcraft' &&
|
||||
github.repository == 'storytold/wordcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
name: WordCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
# Automated daily unsigned nightly build at 07:00 UTC plus supervised manual runs.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 7 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
@@ -258,6 +258,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `crates/ui-egui/icons/pageNumber.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/pageWidth.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/painter.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/painter-fill.svg` | WordCraft contributors | original: the Format Painter's yellow bar, split out as the fill drawn under `painter.svg` | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/paraSpacing.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/pastCitation.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/paste.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
|
||||
Generated
+172
-134
File diff suppressed because it is too large
Load Diff
+54
-53
@@ -37,21 +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-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"] }
|
||||
@@ -84,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"
|
||||
@@ -173,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)
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ craft = { workspace = true, features = [
|
||||
"platform-appearance",
|
||||
"platform-clipboard-system",
|
||||
] }
|
||||
craft-nightly = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Temporary settings folders for the `prefs` tests.
|
||||
@@ -59,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.
|
||||
|
||||
@@ -1,23 +1,11 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
use crate::launch_profile::Profile;
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(wordcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open WordCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable WordCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
@@ -37,7 +25,10 @@ pub fn version_query(args: &[OsString]) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{BuildFlavor, needs_native_error, version, version_query};
|
||||
use craft_nightly::{Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
@@ -47,19 +38,22 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let expected_root = canonical_profile_root(spec.app_id).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("letter.docx")], &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(launch.passthrough_args, vec![OsString::from("letter.docx")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
fn stable_build_refuses_nightly_launch_flags() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let args = craft_nightly::launch_arguments(std::path::Path::new(crate::launch_profile::launcher_root()), &[]);
|
||||
let err = parse_startup(BuildFlavor::Stable, &spec, args, &StartupOptions::new()).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
|
||||
|
||||
@@ -1,174 +1,132 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, preferences, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy. No environment mutation.
|
||||
//! Nightly-v1 bootstrap backed by `craft-nightly`. Selected before logging, preferences, fonts or
|
||||
//! saved state. Stable launches retain their original arguments and directory policy.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
pub use craft_nightly::Profile;
|
||||
|
||||
/// Returns the active launch profile for this process, defaulting to [`Profile::Stable`] before
|
||||
/// `craft_nightly::prepare_launch` installs one.
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
static STABLE: Profile = Profile::Stable;
|
||||
craft_nightly::current().unwrap_or(&STABLE)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
fn is_nightly_flag_token(arg: &OsStr) -> bool {
|
||||
arg.to_str().is_some_and(|s| {
|
||||
s == craft_nightly::LAUNCH_PROFILE_FLAG
|
||||
|| s == craft_nightly::PROFILE_ROOT_FLAG
|
||||
|| s.starts_with("--launch-profile=")
|
||||
|| s.starts_with("--profile-root=")
|
||||
})
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
|
||||
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
/// Returns `true` when `args` starts with nightly launch protocol flags followed by `--`.
|
||||
/// `craft_nightly::parse_startup` consumes that `--`; preserving it lets `main.rs`'s
|
||||
/// `split_at_delimiter` treat every argument after `--` as a document path.
|
||||
pub fn had_launcher_separator(args: &[OsString]) -> bool {
|
||||
if !args.first().is_some_and(|arg| is_nightly_flag_token(arg)) {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
let mut idx = 0;
|
||||
while let Some(arg) = args.get(idx) {
|
||||
if arg == "--" {
|
||||
return true;
|
||||
}
|
||||
if arg == craft_nightly::LAUNCH_PROFILE_FLAG || arg == craft_nightly::PROFILE_ROOT_FLAG {
|
||||
idx += 2;
|
||||
} else if arg.to_str().is_some_and(|s| s.starts_with("--launch-profile=") || s.starts_with("--profile-root=")) {
|
||||
idx += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old settings-folder resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
/// Re-attaches the `--` separator when `craft_nightly` stripped one from an explicit launcher
|
||||
/// header, leaving direct-launch arguments untouched.
|
||||
pub fn passthrough_args(args: Vec<OsString>, had_separator: bool) -> Vec<OsString> {
|
||||
if had_separator { std::iter::once(OsString::from("--")).chain(args).collect() } else { args }
|
||||
}
|
||||
|
||||
/// The root the Launcher hands a nightly on this platform, in that platform's own spelling: `C:\NightlyData\profiles\wordcraft`
|
||||
/// on Windows, `/nightly-data/profiles/wordcraft` elsewhere. A test that fixtures the hand-off uses this rather than a
|
||||
/// literal, because a root literal in the other platform's spelling is not absolute here and `parse` refuses it (#7849).
|
||||
/// literal, because a root literal in the other platform's spelling is not absolute here and validation refuses it (#7849).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn launcher_root() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref(), crate::profile_root::probe_writable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use super::{had_launcher_separator, launcher_root, passthrough_args};
|
||||
use craft_nightly::{
|
||||
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup, validate_and_prepare_root,
|
||||
};
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
|
||||
fn absolute() -> &'static str {
|
||||
super::launcher_root()
|
||||
launcher_root()
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
let spec = crate::profile_root::spec();
|
||||
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
let had_sep = had_launcher_separator(&argv);
|
||||
assert!(!had_sep);
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "letter with spaces.docx"]));
|
||||
fn direct_nightly_launch_resolves_canonical_root_and_preserves_user_arguments() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let expected_root = canonical_profile_root(spec.app_id).unwrap();
|
||||
let argv = args(&["--sample", "letter.docx"]);
|
||||
let had_sep = had_launcher_separator(&argv);
|
||||
assert!(!had_sep);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
|
||||
let had_sep = had_launcher_separator(&argv);
|
||||
assert!(had_sep);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), args(&["--", "--profile-root", "letter with spaces.docx"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_and_unknown_profile_arguments_are_refused() {
|
||||
let spec = crate::profile_root::spec();
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,53 +135,36 @@ mod tests {
|
||||
/// instead of run against a directory this platform never meant.
|
||||
#[test]
|
||||
fn a_root_absolute_only_in_the_other_platforms_spelling_is_refused() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let foreign = if cfg!(windows) { "/nightly-data/profiles/wordcraft" } else { r"C:\NightlyData\profiles\wordcraft" };
|
||||
let argv = args(&["--launch-profile", VERSION, "--profile-root", foreign, "--"]);
|
||||
assert!(parse(argv).is_err(), "the other platform's root spelling must not stand in: {foreign}");
|
||||
let err = validate_and_prepare_root(std::path::Path::new(foreign), &spec).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::RelativeProfileRoot(_)), "the other platform's root spelling must not stand in: {foreign}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
fn launcher_and_plain_version_queries_are_recognized() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let pair = &["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT];
|
||||
for flag in ["--version", "-V"] {
|
||||
let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
|
||||
assert!(plain.is_version_query());
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
let direct = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert!(direct.is_version_query());
|
||||
argv.push("letter with spaces.docx".into());
|
||||
let with_document = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
|
||||
assert!(!with_document.is_version_query());
|
||||
assert_eq!(with_document.passthrough_args, args(&[flag, "letter with spaces.docx"]));
|
||||
|
||||
let mut with_sep = args(form);
|
||||
with_sep.push("--".into());
|
||||
with_sep.push(flag.into());
|
||||
let separated = parse_startup(BuildFlavor::NightlyV1, &spec, with_sep, &StartupOptions::new()).unwrap();
|
||||
assert!(separated.is_version_query());
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
}
|
||||
|
||||
+31
-17
@@ -415,34 +415,40 @@ fn report_launch_profile_error(error: &str) {
|
||||
|
||||
/// Select the immutable launch profile before any startup service or side effect.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before logging, crash handling, the update helper,
|
||||
// The launch profile is decided before logging, crash handling, the update helper,
|
||||
// fonts, preferences or the settings folder.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
// Plain `--version` / `-V` on nightly: answered before root resolution, validation,
|
||||
// process identity, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
|
||||
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| launch_profile::prepare(launch, launch_profile::validate_root))
|
||||
let had_separator = launch_profile::had_launcher_separator(&argv);
|
||||
let early = craft_nightly::prepare_launch(build_flavor::COMPILED, &profile_root::spec(), argv, &craft_nightly::StartupOptions::new())
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Launcher `--launch-profile nightly-v1 --profile-root <dir> [--] --version` / `-V`:
|
||||
// `craft_nightly::prepare_launch` skips root validation and profile installation for
|
||||
// version queries, so answer and exit before any startup side effect.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
|
||||
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
|
||||
return None;
|
||||
}
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2);
|
||||
}
|
||||
let identity = if early.profile.is_nightly() {
|
||||
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
|
||||
} else {
|
||||
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
|
||||
};
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
|
||||
if let Err(error) = wordcraft_ui_egui::os_window::select_identity(identity) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
@@ -454,7 +460,7 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.args)
|
||||
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
|
||||
}
|
||||
|
||||
/// Parses the command line, installs logging and the panic hook, restores preferences and window
|
||||
@@ -1199,14 +1205,22 @@ mod command_line_tests {
|
||||
use super::{documents_to_open, split_at_delimiter};
|
||||
|
||||
/// The argv the Launcher starts a nightly with, as `prepare_launch` hands it on. The root is the one this
|
||||
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows `parse` rightly refuses it.
|
||||
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows validation rightly refuses it.
|
||||
fn launcher_argv(tail: &[&str]) -> Vec<String> {
|
||||
let mut argv: Vec<std::ffi::OsString> = ["--launch-profile", "nightly-v1", "--profile-root", super::launch_profile::launcher_root(), "--"]
|
||||
.iter()
|
||||
.map(std::ffi::OsString::from)
|
||||
.collect();
|
||||
argv.extend(tail.iter().map(std::ffi::OsString::from));
|
||||
super::launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
let had_separator = super::launch_profile::had_launcher_separator(&argv);
|
||||
let launch = craft_nightly::parse_startup(
|
||||
crate::build_flavor::BuildFlavor::NightlyV1,
|
||||
&crate::profile_root::spec(),
|
||||
argv,
|
||||
&craft_nightly::StartupOptions::new(),
|
||||
)
|
||||
.unwrap();
|
||||
super::launch_profile::passthrough_args(launch.passthrough_args, had_separator).iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+160
-553
@@ -1,4 +1,5 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
//! App-owned nightly profile specification for `craft-nightly`; no stable fallback, migration or
|
||||
//! process environment changes.
|
||||
//!
|
||||
//! WordCraft keeps all of its user state in one settings folder (`wordcraft_control_key::settings_dir`):
|
||||
//! `config.toml`, `window.json`, `logs/`, `recovery/`, `fonts/`, `Templates/`,
|
||||
@@ -8,603 +9,209 @@
|
||||
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use craft_nightly::AppProfileSpec;
|
||||
|
||||
/// The app id of the nightly Flatpak this build ships in (`packaging/linux/flatpak-bundle.sh`).
|
||||
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.wordcraft.nightly";
|
||||
pub const APP_ID: &str = "wordcraft";
|
||||
pub const DISPLAY_NAME: &str = "WordCraft";
|
||||
pub const STABLE_PACKAGE_ID: &str = "ai.storyteller.wordcraft";
|
||||
pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.wordcraft.nightly";
|
||||
pub const STABLE_DIR_NAMES: &[&str] = &["wordcraft", "WordCraft", "craft-fonts", "Craft Fonts"];
|
||||
pub const FORBIDDEN_ENV_VARS: &[&str] = &["WORDCRAFT_PROFILE_DIR"];
|
||||
pub const FOLDER_ONLY_ENTRIES: &[&str] = &["recovery", "logs", "fonts", "Templates", "FontStore"];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
/// Returns WordCraft's `craft-nightly` isolation specification, including OS-specific installation
|
||||
/// and sandbox roots that must never overlap a nightly profile.
|
||||
pub fn spec() -> AppProfileSpec {
|
||||
spec_with(|key| std::env::var_os(key))
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
fn spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: APP_ID,
|
||||
display_name: DISPLAY_NAME,
|
||||
stable_dir_names: STABLE_DIR_NAMES,
|
||||
stable_package_id: STABLE_PACKAGE_ID,
|
||||
nightly_package_id: NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: FORBIDDEN_ENV_VARS,
|
||||
portable_markers: &[],
|
||||
folder_only_entries: FOLDER_ONLY_ENTRIES,
|
||||
extra_forbidden_roots: extra_forbidden_roots_with(env),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(unix, target_os = "windows"))]
|
||||
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
if path.is_absolute() { Some(path) } else { None }
|
||||
}
|
||||
|
||||
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// Per-user and per-machine MSI install locations.
|
||||
if let Some(local) =
|
||||
non_empty_abs(&env, "LOCALAPPDATA").or_else(|| non_empty_abs(&env, "USERPROFILE").map(|p| p.join("AppData").join("Local")))
|
||||
{
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("WordCraft"));
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("WordCraft"));
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
// Native packages' locations and the stable Flatpak's per-app data folder.
|
||||
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.wordcraft"));
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("WordCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The suite's shared font store and the MSI's default per-user and per-machine folders.
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Craft Fonts"));
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("WordCraft"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("WordCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("wordcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The shared font store (fonts and Language packs) and the native packages' locations.
|
||||
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("craft-fonts"));
|
||||
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.wordcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
roots.push(PathBuf::from("/Applications/WordCraft.app"));
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/WordCraft"),
|
||||
library.join("Caches/WordCraft"),
|
||||
library.join("Caches/ai.storyteller.wordcraft"),
|
||||
library.join("Preferences/WordCraft"),
|
||||
library.join("Preferences/ai.storyteller.wordcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.wordcraft.savedState"),
|
||||
library.join("Application Support/Craft Fonts"),
|
||||
home.join("Applications/WordCraft.app"),
|
||||
PathBuf::from("/Applications/WordCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
if std::fs::metadata(&child).is_ok_and(|meta| !meta.is_dir()) {
|
||||
return Err(format!("the nightly {label} must be a directory"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (`config.toml`, `logs`, `recovery`, `fonts`,
|
||||
/// `Templates`, `window.json` and so on) must resolve inside it, so a link there cannot point
|
||||
/// Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
roots.push(library.join("Preferences/ai.storyteller.wordcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.wordcraft.savedState"));
|
||||
roots.push(home.join("Applications/WordCraft.app"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
#[cfg(not(any(unix, target_os = "windows")))]
|
||||
let _ = env;
|
||||
roots
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The app's exclusive create probe: a file only this process can have made, created and removed.
|
||||
pub fn probe_writable(dir: &Path) -> std::io::Result<()> {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let probe = dir.join(format!(".nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
}
|
||||
|
||||
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
|
||||
/// starting the app or creating the profile of the person running them.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
// The developer switch that points a run at any folder: Nightly's folder comes from the Launcher.
|
||||
if env("WORDCRAFT_PROFILE_DIR").is_some_and(|v| !v.is_empty()) {
|
||||
return Err("nightly-v1 cannot be combined with WORDCRAFT_PROFILE_DIR".into());
|
||||
}
|
||||
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting a Flatpak
|
||||
// runtime could point another profile at the stable app's token files; the nightly Flatpak
|
||||
// itself (`packaging/linux/flatpak-bundle.sh`) is the one sandbox this build ships in.
|
||||
if platform != Platform::Windows
|
||||
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
|
||||
&& id != NIGHTLY_FLATPAK_ID
|
||||
{
|
||||
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
// Existing aliases under the profile must not redirect its own subfolders elsewhere.
|
||||
entries_stay_inside(&chosen)?;
|
||||
// Recovery can read, adopt and sweep entries; a link there must never leave the profile.
|
||||
private_subdirectory(&chosen, "recovery", "recovery folder")?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
private_subdirectory(&confirmed, "recovery", "recovery folder")?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 5] = ["recovery", "logs", "fonts", "Templates", "FontStore"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{
|
||||
APP_ID, DISPLAY_NAME, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, STABLE_DIR_NAMES, STABLE_PACKAGE_ID,
|
||||
extra_forbidden_roots_with, spec_with,
|
||||
};
|
||||
use craft_nightly::{ProfileError, validate_and_prepare_root};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
struct TempRoot(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
impl TempRoot {
|
||||
fn new(label: &str) -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("wordcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let candidate = std::env::temp_dir().join(format!(
|
||||
"wordcraft-profile-spec-{label}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/wordcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
|dir| {
|
||||
let probe = dir.join("exclusive-test-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
Self(root)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
impl Drop for TempRoot {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_settings_folders_font_store_and_packages_but_allows_the_launcher_sibling() {
|
||||
let mut fixture = Fixture::new();
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("wordcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
}
|
||||
let fonts = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()).join("craft-fonts");
|
||||
std::fs::create_dir_all(fonts.join("language-packs")).unwrap();
|
||||
for candidate in [fonts.clone(), fonts.join("nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
for package in ["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"] {
|
||||
assert!(fixture.check(Platform::Linux, &PathBuf::from(package)).is_err());
|
||||
}
|
||||
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
|
||||
let nightly = data.join("ArtCraftLauncher/nightly/profiles/wordcraft");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
fn spec_preserves_wordcraft_isolation_contract() {
|
||||
let spec = spec_with(|_| None);
|
||||
assert_eq!(spec.app_id, APP_ID);
|
||||
assert_eq!(spec.display_name, DISPLAY_NAME);
|
||||
assert_eq!(spec.stable_dir_names, STABLE_DIR_NAMES);
|
||||
assert_eq!(spec.stable_package_id, STABLE_PACKAGE_ID);
|
||||
assert_eq!(spec.nightly_package_id, NIGHTLY_PACKAGE_ID);
|
||||
assert_eq!(spec.profile_root_env, None);
|
||||
assert_eq!(spec.forbidden_env_vars, FORBIDDEN_ENV_VARS);
|
||||
assert!(spec.portable_markers.is_empty());
|
||||
assert_eq!(spec.folder_only_entries, FOLDER_ONLY_ENTRIES);
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[test]
|
||||
fn linux_extra_forbidden_roots_cover_native_packages_and_stable_flatpak() {
|
||||
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/home/tester"))]);
|
||||
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
|
||||
assert!(roots.contains(&PathBuf::from("/usr/bin/wordcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/usr/local/bin/wordcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/opt/wordcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.wordcraft")));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_extra_forbidden_roots_cover_bundles_plist_and_saved_state() {
|
||||
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/Users/tester"))]);
|
||||
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
|
||||
assert!(roots.contains(&PathBuf::from("/Applications/WordCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/Users/tester/Applications/WordCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Preferences/ai.storyteller.wordcraft.plist")));
|
||||
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Saved Application State/ai.storyteller.wordcraft.savedState")));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn windows_extra_forbidden_roots_cover_per_user_and_machine_installs() {
|
||||
let env = BTreeMap::from([
|
||||
(String::from("LOCALAPPDATA"), OsString::from(r"C:\Users\tester\AppData\Local")),
|
||||
(String::from("ProgramFiles"), OsString::from(r"C:\Program Files")),
|
||||
(String::from("ProgramFiles(x86)"), OsString::from(r"C:\Program Files (x86)")),
|
||||
]);
|
||||
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
|
||||
assert!(roots.contains(&PathBuf::from(r"C:\Users\tester\AppData\Local\Programs\ArtCraft\WordCraft")));
|
||||
assert!(roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\WordCraft")));
|
||||
assert!(roots.contains(&PathBuf::from(r"C:\Program Files (x86)\ArtCraft\WordCraft")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
fn nightly_profile_reopens_and_enforces_folder_only_entries_and_extra_fences() {
|
||||
let temp = TempRoot::new("reopen");
|
||||
let fenced = temp.0.join("fenced-stable");
|
||||
let mut spec = spec_with(|_| None);
|
||||
spec.extra_forbidden_roots.push(fenced.clone());
|
||||
|
||||
let overlap = validate_and_prepare_root(&fenced.join("nightly"), &spec).unwrap_err();
|
||||
assert!(matches!(overlap, ProfileError::ForbiddenRootOverlap { .. }));
|
||||
assert!(!fenced.exists());
|
||||
|
||||
let private = temp.0.join("nightly-private");
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
let flatpak = fixture.home().join(".var/app/ai.storyteller.wordcraft");
|
||||
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert!(!flatpak.exists());
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
// Inside the Nightly Flatpak, XDG_DATA_HOME is this app's own persistent data folder, so
|
||||
// the launcher's profile lands there rather than on the discarded sandbox home.
|
||||
let nightly = fixture.home().join(".var/app/ai.storyteller.wordcraft.nightly/data/wordcraft-nightly");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_the_app_library_subtrees_the_shared_font_store_and_the_whole_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/WordCraft Nightly.app/Contents/MacOS/WordCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let library = fixture.home().join("Library");
|
||||
for suffix in [
|
||||
"Application Support/WordCraft",
|
||||
"Caches/WordCraft",
|
||||
"Caches/ai.storyteller.wordcraft",
|
||||
"Preferences/WordCraft",
|
||||
"Saved Application State/ai.storyteller.wordcraft.savedState",
|
||||
"Application Support/Craft Fonts",
|
||||
] {
|
||||
let stable = library.join(suffix);
|
||||
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen");
|
||||
}
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/wordcraft");
|
||||
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_roaming_local_font_store_and_install_fences_remain_active() {
|
||||
let fixture = Fixture::new();
|
||||
let mut fixture = fixture;
|
||||
for key in ["APPDATA", "LOCALAPPDATA"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("WordCraft");
|
||||
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
let err = validate_and_prepare_root(&private, &spec).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::ExpectedDirectoryEntry(_)), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
let fonts = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Craft Fonts");
|
||||
assert!(fixture.check(Platform::Windows, &fonts.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
|
||||
let per_user = local.join("Programs").join("ArtCraft").join("WordCraft");
|
||||
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
let machine = base.join("ArtCraft").join("WordCraft");
|
||||
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!machine.exists());
|
||||
}
|
||||
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("wordcraft");
|
||||
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not WordCraft's install");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/wordcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("recovery"), platform));
|
||||
assert!(overlaps(&root.join("recovery"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("wordcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_and_entry_aliases_cannot_leave_the_profile_and_stable_bytes_stay_untouched() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/wordcraft/recovery");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
|
||||
let private = fixture.root.join(format!("nightly-{index}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&target, private.join("recovery")).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "recovery must not escape the private profile or follow a dangling alias");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
for name in ["logs", "fonts", "config.toml"] {
|
||||
let private = fixture.root.join(format!("nightly-entry-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err(), "{name} must not lead outside the profile");
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_recovery_alias_inside_the_profile_keeps_it_usable() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-private");
|
||||
let recovery = private.join("private-recovery");
|
||||
std::fs::create_dir_all(&recovery).unwrap();
|
||||
std::os::unix::fs::symlink(&recovery, private.join("recovery")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
assert_eq!(std::fs::canonicalize(private.join("recovery")).unwrap(), recovery);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/wordcraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
fixture.env.insert("WORDCRAFT_PROFILE_DIR".into(), fixture.home().join("custom-stable").into_os_string());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("WORDCRAFT_PROFILE_DIR"));
|
||||
fixture.env.remove("WORDCRAFT_PROFILE_DIR");
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.wordcraft".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
// The nightly Flatpak is the one sandbox this build ships in, so its own id is accepted.
|
||||
let flatpak_profile = fixture.home().join("nightly/flatpak-profile");
|
||||
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
|
||||
assert_eq!(fixture.check(Platform::Linux, &flatpak_profile).unwrap(), flatpak_profile);
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let file = fixture.home().join("not-a-directory");
|
||||
std::fs::write(&file, b"do not replace me").unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &file).is_err());
|
||||
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
|
||||
let candidate = fixture.home().join("nightly");
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert_eq!(calls.get(), 1);
|
||||
assert!(!fixture.home().join(".config/wordcraft").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/wordcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
|
||||
let alias = fixture.home().join("alias");
|
||||
symlink(&stable, &alias).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
|
||||
let missing = fixture.home().join("missing-target");
|
||||
let dangling = fixture.home().join("dangling");
|
||||
symlink(&missing, &dangling).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
|
||||
assert!(!missing.exists());
|
||||
assert!(!stable.join("nightly").exists());
|
||||
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,6 +506,11 @@ pub struct ParaProps {
|
||||
/// file (not laid out yet); Word sizes a line by it, so dropping it changes Word's pages.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text_alignment: Option<TextAlignment>,
|
||||
/// A list item's paragraph after its first (or a list header's), with no number of its own,
|
||||
/// at this list level (0..=8): formats with list items (ODT, HTML, Markdown) keep it in the
|
||||
/// item. Set only directly, never by a style.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub list_item: Option<u8>,
|
||||
}
|
||||
|
||||
impl ParaProps {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -100,18 +100,35 @@ fn object_value_from_shared(
|
||||
float: convert(float)?,
|
||||
ch_w,
|
||||
ch_h,
|
||||
children: children.into_iter().map(|c| group_child_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
|
||||
children: group_children_from_shared(children, graphics)?,
|
||||
canvas: canvas.map(convert).transpose()?,
|
||||
}),
|
||||
other => convert(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn group_child_value_from_shared(
|
||||
source: craft_wordmodel::para::GroupChild,
|
||||
/// A group's members. The shared reader keeps a hyperlinked nested group whole; WordCraft's
|
||||
/// text box, layout and edit code looks one level deep, so lift its members into this group
|
||||
/// (their offsets composed, scaled from the nested group's child space), as the reader does for
|
||||
/// an unlinked one. The nested group's own link is dropped.
|
||||
// lean: nested groups are flattened until WordCraft supports them (follow-up issue).
|
||||
fn group_children_from_shared(
|
||||
children: Vec<craft_wordmodel::para::GroupChild>,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
|
||||
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj, graphics)? })
|
||||
) -> Result<Vec<wordcraft_doc::para::GroupChild>, DocxError> {
|
||||
let mut out = Vec::with_capacity(children.len());
|
||||
for c in children {
|
||||
let (x, y) = (c.x, c.y);
|
||||
match object_value_from_shared(c.obj, graphics)? {
|
||||
wordcraft_doc::para::InlineObject::Group { w, h, ch_w, ch_h, children, .. } => {
|
||||
let (kx, ky) = (if ch_w > 0.0 { w / ch_w } else { 1.0 }, if ch_h > 0.0 { h / ch_h } else { 1.0 });
|
||||
// `children` is already flat: the recursion converted the nested group first.
|
||||
out.extend(children.into_iter().map(|m| wordcraft_doc::para::GroupChild { x: x + m.x * kx, y: y + m.y * ky, obj: m.obj }));
|
||||
}
|
||||
obj => out.push(wordcraft_doc::para::GroupChild { x, y, obj }),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn table_value_from_shared(source: craft_wordmodel::table::Table, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Table, DocxError> {
|
||||
|
||||
@@ -229,6 +229,7 @@ fn every_para_prop_round_trips() {
|
||||
fmt_change: None,
|
||||
snap_to_grid: Some(false),
|
||||
text_alignment: Some(TextAlignment::Top),
|
||||
list_item: None, // not a DOCX property
|
||||
};
|
||||
let variants = [
|
||||
ParaProps { line_spacing: Some(LineSpacing::AtLeast(14.0)), indent_first: Some(24.0), align: Some(Align::Center), ..Default::default() },
|
||||
@@ -315,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(),
|
||||
@@ -1004,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() };
|
||||
@@ -1033,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() };
|
||||
@@ -1088,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());
|
||||
@@ -1107,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());
|
||||
@@ -1862,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(&[
|
||||
|
||||
@@ -265,3 +265,23 @@ fn story_shared_by_many_shapes_is_written_once() {
|
||||
// fallback. The other shapes do not repeat it.
|
||||
assert_eq!(xml.matches(text.as_str()).count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_box_in_a_linked_nested_group_survives_pruning() {
|
||||
// The shared reader keeps a hyperlinked nested group whole; the box inside must still be
|
||||
// reachable (`text_boxes` looks one level deep), or the first edit's prune deletes its story.
|
||||
let inner = r#"<wpg:grpSp><wpg:cNvPr id="3" name="Inner"><a:hlinkClick r:id="rId9"/></wpg:cNvPr><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="635000" y="0"/><a:ext cx="635000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="635000" cy="635000"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:cNvPr id="4" name="Box"/><wps:cNvSpPr txBox="1"/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="rect"/></wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>Inside</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></wpg:grpSp>"#;
|
||||
let doc = format!(
|
||||
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><w:body><w:p><w:r><w:drawing><wp:inline><wp:extent cx="1270000" cy="635000"/><wp:docPr id="1" name="Outer"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="1270000" cy="635000"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:wgp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p></w:body></w:document>"#
|
||||
);
|
||||
let rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc_rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/" TargetMode="External"/></Relationships>"#;
|
||||
let bytes = zip(&[("_rels/.rels", rels), ("word/document.xml", doc.as_bytes()), ("word/_rels/document.xml.rels", doc_rels)]);
|
||||
let mut d = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(boxes(&d).len(), 1);
|
||||
// What every mutating command does after it runs.
|
||||
d.prune_text_boxes();
|
||||
assert_eq!(boxes(&d).len(), 1, "the nested box lost its story");
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.contains("Inside"), "{xml}");
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Character formatting (Home › Font).
|
||||
|
||||
use std::sync::{Arc, PoisonError};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::eq::{EncloseShape, EncloseStyle, Enclosure};
|
||||
use wordcraft_doc::props::{Border, CharProps, Highlight, Rgb, TextColor, Underline, VertAlign};
|
||||
@@ -8,8 +10,44 @@ use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
|
||||
|
||||
use super::sel_result;
|
||||
use super::tools::{is_turkic, lower_char, upper_char};
|
||||
use crate::doc_state::{ColumnBlock, Selection};
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct StateKey {
|
||||
document_id: u64,
|
||||
rev: u64,
|
||||
sel: Selection,
|
||||
pending: Option<CharProps>,
|
||||
pending_at: Option<Pos>,
|
||||
column: Option<ColumnBlock>,
|
||||
font_gen: u64,
|
||||
}
|
||||
|
||||
/// Cached result of [`cached_state`] and the session inputs it depends on.
|
||||
pub(crate) struct StateCache {
|
||||
key: StateKey,
|
||||
value: Arc<Value>,
|
||||
}
|
||||
|
||||
impl StateCache {
|
||||
pub(crate) fn rev(&self) -> u64 {
|
||||
self.key.rev
|
||||
}
|
||||
}
|
||||
|
||||
fn state_key(s: &Session) -> StateKey {
|
||||
StateKey {
|
||||
document_id: s.document_id(),
|
||||
rev: s.rev(),
|
||||
sel: s.sel.clone(),
|
||||
pending: s.pending.clone(),
|
||||
pending_at: s.pending_at.clone(),
|
||||
column: s.column.clone(),
|
||||
font_gen: wordcraft_fonts::FontDb::global().generation(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Word's font size list.
|
||||
pub const SIZES: [f32; 17] = [8.0, 9.0, 10.0, 10.5, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 36.0, 48.0, 72.0];
|
||||
|
||||
@@ -879,8 +917,30 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
|
||||
apply(s, &|c| c.overlay(&props))
|
||||
}
|
||||
|
||||
/// What the ribbon shows: the formatting at the selection (mixed values are null), cached per
|
||||
/// document revision, selection, pending caret state, column selection, and font generation.
|
||||
pub fn cached_state(s: &Session) -> Arc<Value> {
|
||||
let key = state_key(s);
|
||||
{
|
||||
let cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(cached) = cache.as_ref()
|
||||
&& cached.key == key
|
||||
{
|
||||
return Arc::clone(&cached.value);
|
||||
}
|
||||
}
|
||||
let value = Arc::new(compute_state(s));
|
||||
let mut cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
*cache = Some(StateCache { key, value: Arc::clone(&value) });
|
||||
value
|
||||
}
|
||||
|
||||
/// What the ribbon shows: the formatting at the selection (mixed values are null).
|
||||
pub fn state(s: &Session) -> Value {
|
||||
(*cached_state(s)).clone()
|
||||
}
|
||||
|
||||
fn compute_state(s: &Session) -> Value {
|
||||
let all = resolved(s);
|
||||
let first = all.first().cloned();
|
||||
let same = |f: &dyn Fn(&ResolvedChar) -> Value| -> Value {
|
||||
@@ -906,6 +966,7 @@ pub fn state(s: &Session) -> Value {
|
||||
"italic": all.iter().all(shown_italic),
|
||||
"underline": all.iter().all(|r| r.underline != Underline::None),
|
||||
"underlineColor": same(&|r| json!(r.underline_color.map_or_else(|| "auto".to_string(), |c| c.hex()))),
|
||||
"shading": same(&|r| json!(r.shading.map(|c| c.hex()))),
|
||||
"strike": all.iter().all(|r| r.strike),
|
||||
"border": all.iter().all(|r| r.border.is_some()),
|
||||
"subscript": all.iter().all(|r| r.vert_align == VertAlign::Subscript),
|
||||
@@ -927,6 +988,14 @@ pub fn state(s: &Session) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// The selection's uniform highlight colour (`Some(None)` when uniformly unhighlighted), or `None`
|
||||
/// when the selection is mixed or empty.
|
||||
pub fn uniform_highlight(s: &Session) -> Option<Option<Rgb>> {
|
||||
let all = resolved(s);
|
||||
let first = all.first()?.highlight;
|
||||
all.iter().all(|r| r.highlight == first).then_some(first)
|
||||
}
|
||||
|
||||
/// What Enclose Characters works on: the selected text (one full-width or up to two half-width
|
||||
/// characters), or enclosed characters already there (selected, or beside the caret).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -1054,4 +1123,30 @@ mod tests {
|
||||
assert_eq!(convert("one 3.14 apples and two 2.5 pears.", "sentence", true), "One 3.14 apples and two 2.5 pears.");
|
||||
assert_eq!(convert("pi is 3.14. next sentence.", "sentence", true), "Pi is 3.14. Next sentence.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_state_hits_until_selection_format_or_pending_changes() {
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut s = crate::Session::new(wordcraft_doc::Document::new());
|
||||
let a = super::cached_state(&s);
|
||||
let b = super::cached_state(&s);
|
||||
assert!(Arc::ptr_eq(&a, &b), "unchanged session should reuse cached format state Arc");
|
||||
|
||||
s.run("text.insert", &json!({"text": "hello world"})).unwrap();
|
||||
let c = super::cached_state(&s);
|
||||
assert!(!Arc::ptr_eq(&b, &c), "text edit bumps rev and invalidates cache");
|
||||
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
let d = super::cached_state(&s);
|
||||
assert!(!Arc::ptr_eq(&c, &d), "pending bold changes caret formatting");
|
||||
assert_eq!(d["bold"], json!(true));
|
||||
assert!(Arc::ptr_eq(&d, &super::cached_state(&s)));
|
||||
|
||||
s.run("select.text", &json!({"text": "hello"})).unwrap();
|
||||
let e = super::cached_state(&s);
|
||||
assert!(!Arc::ptr_eq(&d, &e), "selection change updates format state");
|
||||
assert_eq!(e["bold"], json!(false));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)))
|
||||
@@ -304,7 +304,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// start, so all of a paragraph's text is still text, except in the last paragraph of its story,
|
||||
/// cell or box, where it stands for the paragraph with its mark. A selected picture, shape or text
|
||||
/// box is its object character, not text (a field's object character is).
|
||||
fn shades_text(s: &Session) -> bool {
|
||||
pub fn shades_text(s: &Session) -> bool {
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a == b || a.story != b.story || a.path != b.path {
|
||||
return false;
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -149,6 +149,8 @@ pub struct Session {
|
||||
/// ([`Session::why_disabled`]): computed once per document, revision and author instead of
|
||||
/// for every button on every frame.
|
||||
protect_facts: std::sync::Mutex<Option<((u64, u64, String), crate::cmd::protect::Facts)>>,
|
||||
/// Cached result of [`crate::cmd::format::cached_state`] and the state key it was made for.
|
||||
pub(crate) format_state: std::sync::Mutex<Option<crate::cmd::format::StateCache>>,
|
||||
/// How many times the document's body was replaced under the same [`Self::document_id`]
|
||||
/// (`document.setText`, version restore, compare, Undo/Redo). It is the body's IME
|
||||
/// replacement epoch: a composition must not survive the swap, even when the new body has
|
||||
|
||||
@@ -285,6 +285,7 @@ impl Session {
|
||||
last_highlight: _,
|
||||
// Keyed by document id and revision, so one cache serves every document.
|
||||
protect_facts: _,
|
||||
format_state: _,
|
||||
// The input method talks to the window, whichever document it shows; the IME
|
||||
// context is keyed by `document_id`.
|
||||
ime_state_revision: _,
|
||||
|
||||
@@ -131,6 +131,7 @@ impl Session {
|
||||
untitled,
|
||||
made_rev,
|
||||
protect_facts: std::sync::Mutex::new(None),
|
||||
format_state: std::sync::Mutex::new(None),
|
||||
ime_body_epoch,
|
||||
ime_state_revision: None,
|
||||
ime_state_seen: None,
|
||||
|
||||
@@ -113,6 +113,7 @@ impl Session {
|
||||
autocap: _,
|
||||
rev: _,
|
||||
protect_facts: _,
|
||||
format_state: _,
|
||||
cache: _,
|
||||
layout: _,
|
||||
// The word being typed, like `column`: valid only while `sel` is where typing left it.
|
||||
@@ -296,6 +297,10 @@ impl Session {
|
||||
if facts.as_ref().is_some_and(|((_, r, _), _)| *r != rev) {
|
||||
*facts = None;
|
||||
}
|
||||
let format_state = self.format_state.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if format_state.as_ref().is_some_and(|c| c.rev() != rev) {
|
||||
*format_state = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// [`crate::cmd::protect::Facts`] for the document as it is now, cached per revision.
|
||||
|
||||
@@ -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)?)
|
||||
}
|
||||
|
||||
@@ -1258,3 +1258,16 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
|
||||
assert_eq!(p2.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odt_list_item_later_paragraphs_stay_in_the_item() {
|
||||
// "One" has two paragraphs. The second must stay inside item 1, so HTML's "Two" is item 2.
|
||||
let fodt = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text"><office:automatic-styles><text:list-style style:name="L1"><text:list-level-style-number text:level="1" style:num-format="1"/></text:list-style></office:automatic-styles><office:body><office:text><text:list text:style-name="L1"><text:list-item><text:p>One</text:p><text:p>Still one</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document>"#;
|
||||
let doc = crate::odt::import_flat(fodt.as_bytes()).unwrap();
|
||||
let html = crate::html::export(&doc);
|
||||
assert_eq!(html.matches("<ol").count(), 1, "one list, not restarted: {html}");
|
||||
let (one, still, two) = (html.find("One").unwrap(), html.find("Still one").unwrap(), html.find("Two").unwrap());
|
||||
assert!(one < still && still < two, "{html}");
|
||||
assert!(html[one..still].matches("</li>").count() == 0, "later paragraph left item 1: {html}");
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<rect x="4" y="3" width="12" height="5" rx="1" fill="#F2C811"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 157 B |
@@ -1,5 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<rect x="4" y="3" width="12" height="5" rx="1" fill="#F2C811" class="fixed"/>
|
||||
<rect x="4" y="3" width="12" height="5" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M16 5.5 L17.5 5.5 L17.5 10 L10 10 L10 12" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<rect x="8.8" y="12" width="2.4" height="6" rx="1" fill="currentColor"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 460 B After Width: | Height: | Size: 380 B |
@@ -107,6 +107,7 @@ impl WordApp {
|
||||
command_states: Default::default(),
|
||||
command_states_cache: None,
|
||||
keytip_cache: None,
|
||||
search_cache: None,
|
||||
fonts_frames: 0,
|
||||
clipboard_published: false,
|
||||
printing: Default::default(),
|
||||
|
||||
@@ -147,6 +147,12 @@ const LINKED_EDIT: [craft::ui::runtime::commands::EditCommands; 5] = {
|
||||
[Cut, Copy, Paste, Undo, Redo]
|
||||
};
|
||||
|
||||
/// The English parts of a registry `location` (`Home › Font`, split as `i18n::location` does); `None` for no place.
|
||||
pub(crate) fn location_path(location: &str) -> Option<Vec<&str>> {
|
||||
let path: Vec<&str> = location.split(" › ").filter(|part| !part.is_empty()).collect();
|
||||
(!path.is_empty()).then_some(path)
|
||||
}
|
||||
|
||||
impl WordApp {
|
||||
/// The app's commands as the keymap knows them: every engine command with its default
|
||||
/// chords, then the interface commands. The interface commands come last because a tie in the
|
||||
@@ -183,6 +189,11 @@ impl WordApp {
|
||||
// warned about), so their chords go in as the set's replaced defaults (the `LINKED_EDIT` fold below).
|
||||
for spec in registry.all().iter().filter(|spec| seen.insert(spec.id) && !LINKED_EDIT.iter().any(|c| c.id() == spec.id)) {
|
||||
let mut def = CommandDef::new(CommandRef::new(spec.id), tl!(spec.label), Scope::app());
|
||||
// Its ribbon place is its menu path, in English: Customize Keyboard files it under the tab by name,
|
||||
// and the framework translates each segment where it shows it.
|
||||
if let Some(path) = location_path(spec.location) {
|
||||
def = def.with_path(path.into_iter().map(str::to_owned).collect());
|
||||
}
|
||||
for binding in default_bindings(spec.shortcut) {
|
||||
def = def.with_default(binding);
|
||||
}
|
||||
|
||||
@@ -255,7 +255,16 @@ fn side_menu(ui: &mut Ui, band: f32, current: &str, has_document: bool, show_dis
|
||||
.scroll(Scroll::vertical())
|
||||
.header(move |ui, _| {
|
||||
ui.add_space(band);
|
||||
let _ = IconButton::command(IconSpec::svg(IconId::new("chevronLeft")), BackstagePageCommand::Back).show(ui);
|
||||
// The side menu place, so the arrow reads in the rail's white ink, not a panel button's dark ink (#7707).
|
||||
with_env(
|
||||
ui,
|
||||
|overrides| {
|
||||
overrides.values.set(ControlPlace::SideMenu);
|
||||
},
|
||||
|ui| {
|
||||
let _ = IconButton::command(IconSpec::svg(IconId::new("chevronLeft")), BackstagePageCommand::Back).show(ui);
|
||||
},
|
||||
);
|
||||
})
|
||||
// The community link above About, both at the reading start, as production's bottom links: rows of the side
|
||||
// menu place too, so they read in the rail's white ink over the brand colour, not a panel button's dark ink.
|
||||
|
||||
@@ -146,6 +146,9 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
let ctx = ui.ctx().clone();
|
||||
let focused = app.canvas.focused(&ctx);
|
||||
crate::dialogs_smart_art::end_typing_run(app, focused);
|
||||
// The page keeps the keyboard focus while another window is active, but the caret shows and blinks only in the
|
||||
// active window: a window in the background asks for no frames to blink it (#7674).
|
||||
let active = focused && ctx.input(|input| input.focused);
|
||||
let doc = app.session.layout();
|
||||
let Some(pl) = place(app, &doc, body.pages) else { return };
|
||||
|
||||
@@ -184,7 +187,7 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
};
|
||||
let ink = |app: &mut WordApp| caret_color_at(app, &doc, pl.page, pl.probe.0, pl.probe.1, zoom_key, dim_body);
|
||||
|
||||
let shown = pl.collapsed && focused;
|
||||
let shown = pl.collapsed && active;
|
||||
let mut bars: Vec<(Bar, Color32)> = Vec::new();
|
||||
let mut composition = None;
|
||||
if focused && !pl.in_equation && !app.canvas.ime_preedit.is_empty() {
|
||||
@@ -211,7 +214,7 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
ctx.request_repaint();
|
||||
} else if shown && blink_fading(since_ms / 1000.0, app.canvas.glide.secs()) {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(16));
|
||||
} else if focused {
|
||||
} else if active {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(530 - (since_ms as u64 % 530)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2484,3 +2484,63 @@ fn hostile_numbers_are_ignored() {
|
||||
assert!(h.state().canvas.view.zoom.is_finite() && h.state().canvas.view.zoom > 0.0);
|
||||
assert!(h.state().canvas.view.offset.0.is_finite() && h.state().canvas.view.offset.1.is_finite());
|
||||
}
|
||||
|
||||
/// A window in the background shows no caret and asks for no frames to blink one (#7674). The page keeps the keyboard
|
||||
/// focus, so the caret blinks again once the window is active again.
|
||||
#[test]
|
||||
fn the_caret_blinks_only_while_the_window_is_active() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "Some text"})).unwrap();
|
||||
// No glide or fade: the caret's frames are the blink's alone.
|
||||
a.ui.animations = crate::theme::Animations::Off;
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().canvas.focus_page(&ctx);
|
||||
for _ in 0..6 {
|
||||
h.app_frame();
|
||||
}
|
||||
assert!(h.state().canvas.focused(&ctx), "the page has the keyboard focus");
|
||||
let blink = std::time::Duration::from_millis(530);
|
||||
let next_frame =
|
||||
|h: &H| h.output().viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |viewport| viewport.repaint_delay);
|
||||
assert!(next_frame(&h) <= blink, "an active window asks for a frame within a blink");
|
||||
// The caret is a stroke from its top to its bottom where the layout puts it. The blink runs on the wall clock:
|
||||
// restarted, it is in its on half for the next 530 ms, so a caret the window draws at all is in the frame after.
|
||||
let (top, bottom) = {
|
||||
let app = h.state_mut();
|
||||
let focus = app.session.sel.focus.clone();
|
||||
let c = app.session.layout().caret(&focus).expect("the caret has a place");
|
||||
let mut at = |y| crate::canvas::page_to_screen(app, c.page, c.x, y).expect("the caret's page is on screen");
|
||||
(at(c.top), at(c.top + c.height))
|
||||
};
|
||||
let caret_drawn = |h: &mut H| {
|
||||
h.state_mut().canvas.glide.restart(craft::platform::clock::monotonic_ms());
|
||||
h.app_frame();
|
||||
h.output().shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Path(path) => path.points.len() == 2 && path.points[0].distance(top) < 1.5 && path.points[1].distance(bottom) < 1.5,
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
assert!(caret_drawn(&mut h), "an active window draws the caret");
|
||||
|
||||
h.input_mut().focused = false;
|
||||
h.event(egui::Event::WindowFocused(false));
|
||||
for _ in 0..3 {
|
||||
h.app_frame();
|
||||
}
|
||||
assert!(h.state().canvas.focused(&ctx), "the page keeps the keyboard focus");
|
||||
assert!(next_frame(&h) > blink, "a window in the background asks for no frame to blink the caret");
|
||||
assert!(!caret_drawn(&mut h), "a window in the background draws no caret");
|
||||
|
||||
h.input_mut().focused = true;
|
||||
h.event(egui::Event::WindowFocused(true));
|
||||
h.app_frame();
|
||||
assert!(next_frame(&h) <= blink, "active again, the caret blinks again");
|
||||
}
|
||||
|
||||
@@ -18,12 +18,18 @@ pub(crate) struct ChromeOpen {
|
||||
pub(crate) undo: bool,
|
||||
/// The actions marked in the open Undo drop-down; back to none whenever the drop-down is closed.
|
||||
pub(crate) undo_mark: craft::ui::list::UndoMark,
|
||||
/// The rows and mark the Undo drop-down had when it closed, drawn through its exit fade: a pick has already
|
||||
/// undone those steps, so the live history would empty the list as it fades (#8141).
|
||||
pub(crate) undo_closing: Option<(Vec<String>, craft::ui::list::UndoMark)>,
|
||||
/// The command search.
|
||||
pub(crate) search: bool,
|
||||
/// How the title bar's controls at the end fit the room the leading controls leave them.
|
||||
pub(crate) title_fit: Fit,
|
||||
/// How the status bar's controls fit the room the page leaves them.
|
||||
pub(crate) status_fit: Fit,
|
||||
/// Cached word count `(document_id, count_key, words)` for [`StatusCount::Words`] so typing
|
||||
/// avoids full-document text extraction and character scans.
|
||||
pub(crate) status_words: Option<(u64, u64, usize)>,
|
||||
}
|
||||
|
||||
/// The steps a bar's group of controls takes in a narrow window, from the fullest to the most compact.
|
||||
@@ -244,6 +250,28 @@ impl WordApp {
|
||||
wordcraft_engine::cmd::font::warns(font, &shown).then_some(shown)
|
||||
}
|
||||
|
||||
/// The count in `unit` for the status bar, computing only word count when `unit` is
|
||||
/// [`StatusCount::Words`] and the full [`StatusCounts`] has not already been cached.
|
||||
pub fn cached_status_count(&mut self, unit: StatusCount) -> usize {
|
||||
let key = self.session.rev().wrapping_mul(2) | u64::from(self.session.prefs.count_notes);
|
||||
if self.status_counts.0 == key {
|
||||
return self.status_counts.1.in_unit(unit);
|
||||
}
|
||||
if unit == StatusCount::Words {
|
||||
let doc_id = self.session.document_id();
|
||||
if let Some((cached_doc, cached_key, words)) = self.chrome.status_words
|
||||
&& cached_doc == doc_id
|
||||
&& cached_key == key
|
||||
{
|
||||
return words;
|
||||
}
|
||||
let words = self.session.word_count();
|
||||
self.chrome.status_words = Some((doc_id, key, words));
|
||||
return words;
|
||||
}
|
||||
self.cached_status_counts().in_unit(unit)
|
||||
}
|
||||
|
||||
/// The document's counts, recomputed only when the document (or the count option) changes:
|
||||
/// words as the status bar and the Word Count dialog count them, and characters with and
|
||||
/// without spaces as the dialog does (#2797).
|
||||
@@ -252,14 +280,10 @@ impl WordApp {
|
||||
let key = self.session.rev().wrapping_mul(2) | u64::from(self.session.prefs.count_notes);
|
||||
if self.status_counts.0 != key {
|
||||
let text = self.session.counted_text();
|
||||
self.status_counts = (
|
||||
key,
|
||||
StatusCounts {
|
||||
words: self.session.word_count(),
|
||||
chars: wordcraft_doc::count_chars(&text),
|
||||
chars_no_spaces: wordcraft_doc::count_chars_no_spaces(&text),
|
||||
},
|
||||
);
|
||||
let words = self.session.word_count();
|
||||
self.chrome.status_words = Some((self.session.document_id(), key, words));
|
||||
self.status_counts =
|
||||
(key, StatusCounts { words, chars: wordcraft_doc::count_chars(&text), chars_no_spaces: wordcraft_doc::count_chars_no_spaces(&text) });
|
||||
}
|
||||
self.status_counts.1
|
||||
}
|
||||
|
||||
@@ -1,18 +1,46 @@
|
||||
//! Command search: a `CommandPalette` in its in-place face, over the registry's commands.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::behavior::IconId;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, TooltipSpec};
|
||||
use craft::ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms};
|
||||
use craft::ui::patterns::panels::{CommandPalette, PaletteFace};
|
||||
use craft::ui::runtime::env::{Env, Label, WordTemplate};
|
||||
use craft::ui::runtime::env::{Env, EnvView, Label, WordTemplate};
|
||||
use craft::ui::runtime::inspect;
|
||||
use craft::ui::style::FieldLook;
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::WordApp;
|
||||
|
||||
/// The search's entries and their index, kept between passes. Building the index folds every command's labels, so it
|
||||
/// is built again only when the commands or the interface language change, not in every pass the field shows.
|
||||
pub(crate) struct SearchCache {
|
||||
registry: Arc<wordcraft_engine::Registry>,
|
||||
lang: &'static str,
|
||||
entries: Vec<HelpEntry>,
|
||||
pub(crate) index: Arc<SearchIndex>,
|
||||
}
|
||||
|
||||
impl SearchCache {
|
||||
/// `kept` while it was built from `app`'s registry in the current language, else the entries and index built
|
||||
/// again, their labels resolved and folded as `view` reads them.
|
||||
fn for_pass(kept: Option<SearchCache>, app: &WordApp, view: &EnvView<'_>) -> SearchCache {
|
||||
let lang = crate::i18n::current().code();
|
||||
match kept {
|
||||
Some(cache) if cache.lang == lang && Arc::ptr_eq(&cache.registry, &app.session.registry) => cache,
|
||||
_ => {
|
||||
let entries = help_entries(app);
|
||||
let index = Arc::new(SearchIndex::new(view, &entries, &Synonyms::of(&view.words::<SearchWords>())));
|
||||
SearchCache { registry: Arc::clone(&app.session.registry), lang, entries, index }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One help entry for each registry command Search offers: its label, with the English label so a search in
|
||||
/// English finds it in any language. Paper Color opens the selector in Options instead of running with no
|
||||
/// value, since Search is an interactive entry point.
|
||||
@@ -25,11 +53,19 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
|
||||
.map(|c| {
|
||||
let command =
|
||||
if c.id == "view.paperColor" { CommandRef::with_params("file.options", json!({"pane": "general"})) } else { CommandRef::new(c.id) };
|
||||
HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string())
|
||||
let entry = HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string());
|
||||
match crate::app::command_board::location_path(c.location) {
|
||||
Some(path) => entry.with_path(path.into_iter().map(|part| tl!(part).to_string())),
|
||||
None => entry,
|
||||
}
|
||||
})
|
||||
.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 {
|
||||
@@ -49,13 +85,14 @@ pub(crate) fn is_open(app: &WordApp) -> bool {
|
||||
/// rect it took. `compact` (a narrow window, #5886) shows the magnifier alone, and the search opens as a box over
|
||||
/// the window, since the bar has no room for the field.
|
||||
pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect {
|
||||
// Built in every pass the field runs: the palette opens inside its own `show`, so the entries are there before
|
||||
// it knows. The list lives for the pass only.
|
||||
let entries = help_entries(app);
|
||||
// There in every pass the field runs: the palette opens inside its own `show`, so the entries are there before
|
||||
// it knows. They and their index are kept between passes ([`SearchCache`]).
|
||||
let kept = app.search_cache.take();
|
||||
let suggested: Vec<CommandRef> = crate::dialogs::SEARCH_SUGGESTIONS.iter().map(|id| CommandRef::new(*id)).collect();
|
||||
let mut open = app.chrome.search;
|
||||
let name = tl!("Search commands and help").to_string();
|
||||
let ((rect, out), _) = inspect::record(ui, crate::keytips::search_region(), |ui| {
|
||||
let commands: &WordApp = app;
|
||||
let ((rect, out, cache), _) = inspect::record(ui, crate::keytips::search_region(), |ui| {
|
||||
let mut rect = None;
|
||||
if compact {
|
||||
let button = IconButton::new(IconId::new("wordcraft.search")).label(name.clone()).tooltip(TooltipSpec::new(name.clone())).show(ui);
|
||||
@@ -66,18 +103,35 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
|
||||
}
|
||||
let env = Env::of(ui);
|
||||
let view = env.view();
|
||||
let index = SearchIndex::new(&view, &entries, &Synonyms::of(&view.words::<SearchWords>()));
|
||||
let out = CommandPalette::new(name.clone(), &entries, &index, Bind::bound(&mut open))
|
||||
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()))
|
||||
.suggested((Label::from(tl!("Suggested").to_string()), suggested))
|
||||
.fallback(WordTemplate::new(tl!("Find “{text}” in the document")))
|
||||
.show(ui);
|
||||
(rect.unwrap_or(out.response.rect), out)
|
||||
(rect.unwrap_or(out.response.rect), out, cache)
|
||||
});
|
||||
app.search_cache = Some(cache);
|
||||
app.chrome.search = open;
|
||||
if let Some(text) = out.fallback {
|
||||
crate::dialogs::find_in_navigation_pane(app, ui.ctx(), &text);
|
||||
}
|
||||
rect
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{Services, WordApp};
|
||||
|
||||
/// #7983: a search result names the ribbon place of its command.
|
||||
#[test]
|
||||
fn search_entries_show_the_ribbon_location() {
|
||||
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
let entries = super::help_entries(&app);
|
||||
let bold = entries.iter().find(|e| e.command().id == "format.bold").expect("format.bold is searchable");
|
||||
assert!(!bold.path().is_empty(), "the entry has a path");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,13 +121,13 @@ fn readouts(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
|
||||
/// without spaces, whichever was chosen (#2797). A click opens Word Count; a right click the choice.
|
||||
fn count(app: &mut WordApp, ui: &mut Ui) {
|
||||
let unit = app.ui.status_count;
|
||||
let counts = app.cached_status_counts();
|
||||
let total = app.cached_status_count(unit);
|
||||
// A selected picture/shape/text box isn't a text selection: show the total.
|
||||
let text = if app.session.sel.is_collapsed() || crate::objects::selected(app).is_some() {
|
||||
status_count_text(unit, counts.in_unit(unit), None)
|
||||
status_count_text(unit, total, None)
|
||||
} else {
|
||||
let selected = crate::count_in_unit(&app.session.selected_text(), unit);
|
||||
status_count_text(unit, counts.in_unit(unit), Some(selected))
|
||||
status_count_text(unit, total, Some(selected))
|
||||
};
|
||||
let out = item(ui, text, None);
|
||||
if out.clicked() {
|
||||
|
||||
@@ -249,6 +249,37 @@ fn the_status_bar_totals_are_the_word_count_dialogs_numbers() {
|
||||
assert_eq!(line(StatusCount::CharactersNoSpaces), "6 of 21 characters (no spaces)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_status_count_words_matches_full_counts_across_edits() {
|
||||
let mut a = new_app();
|
||||
a.run("text.insert", json!({"text": "one two"})).unwrap();
|
||||
assert_eq!(a.cached_status_count(StatusCount::Words), 2);
|
||||
|
||||
a.run("text.insert", json!({"text": " three four"})).unwrap();
|
||||
assert_eq!(a.cached_status_count(StatusCount::Words), 4);
|
||||
assert_eq!(a.cached_status_count(StatusCount::Words), a.cached_status_counts().words);
|
||||
assert_eq!(a.cached_status_count(StatusCount::Characters), a.cached_status_counts().chars);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_style_gallery_reuses_arc_until_styles_change() {
|
||||
let mut a = new_app();
|
||||
let rev = a.session.rev();
|
||||
let first = a.previews.style_gallery(&a.session.doc, rev);
|
||||
let second = a.previews.style_gallery(&a.session.doc, rev);
|
||||
assert!(std::sync::Arc::ptr_eq(&first, &second), "same rev should reuse cached style gallery Arc");
|
||||
assert!(!first.is_empty());
|
||||
|
||||
a.run("text.insert", json!({"text": "changed"})).unwrap();
|
||||
let typed = a.previews.style_gallery(&a.session.doc, a.session.rev());
|
||||
assert!(std::sync::Arc::ptr_eq(&second, &typed), "text edit with identical style sheet reuses gallery Arc");
|
||||
|
||||
a.run("styles.create", json!({"name": "Stage7TestStyle", "fromSelection": false})).unwrap();
|
||||
let updated = a.previews.style_gallery(&a.session.doc, a.session.rev());
|
||||
assert!(!std::sync::Arc::ptr_eq(&typed, &updated), "changing styles refreshes style gallery");
|
||||
assert!(updated.iter().any(|(_, name)| name == "Stage7TestStyle"));
|
||||
}
|
||||
|
||||
/// The status bar's actions, through its menus by name: the count row sets the unit and is kept between
|
||||
/// runs, Overtype switches back to inserting.
|
||||
#[test]
|
||||
@@ -1126,3 +1157,38 @@ fn status_bar_view_mode_toggles_and_zoom_slider_proportions() {
|
||||
});
|
||||
assert!(has_14pt_knob, "Zoom slider should paint a {glyph_md} pt thumb (ControlSize::Md) matching 14 pt IconButton icons inside {slider:?}");
|
||||
}
|
||||
|
||||
/// The title bar's command search keeps its entries and their index between passes: building the index folds every
|
||||
/// command's labels, and an idle window repaints for its caret (#7674). New commands, or another interface language,
|
||||
/// build it again.
|
||||
#[test]
|
||||
fn the_title_bar_search_keeps_its_index_until_the_commands_or_the_language_change() {
|
||||
struct ResetLang;
|
||||
impl Drop for ResetLang {
|
||||
fn drop(&mut self) {
|
||||
crate::i18n::apply_language(crate::i18n::Lang::EN);
|
||||
}
|
||||
}
|
||||
let _reset = ResetLang;
|
||||
let index = |h: &egui_kittest::Harness<'static, WordApp>| {
|
||||
h.state().search_cache.as_ref().map(|cache| std::sync::Arc::clone(&cache.index)).expect("the title bar's search has its index")
|
||||
};
|
||||
|
||||
let mut h = harness(new_app());
|
||||
let built = index(&h);
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
assert!(std::sync::Arc::ptr_eq(&built, &index(&h)), "idle passes keep the index");
|
||||
|
||||
let same_commands = wordcraft_engine::Registry::new(h.state().session.registry.all().to_vec());
|
||||
h.state_mut().session.registry = std::sync::Arc::new(same_commands);
|
||||
crate::test_harness::frames(&mut h, 1);
|
||||
let rebuilt = index(&h);
|
||||
assert!(!std::sync::Arc::ptr_eq(&built, &rebuilt), "a new command registry builds it again");
|
||||
|
||||
if crate::i18n::catalogs_embedded() {
|
||||
h.state_mut().run("ui.language", json!({"value": "de"})).unwrap();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert_eq!(crate::i18n::current().code(), "de");
|
||||
assert!(!std::sync::Arc::ptr_eq(&rebuilt, &index(&h)), "another interface language builds it again");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 => {
|
||||
@@ -163,14 +171,19 @@ const UNDO_ROWS_SHOWN: u16 = 8;
|
||||
fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
|
||||
// The small filled triangle of the old toolbar.
|
||||
let out = IconButton::new(IconSpec::glyph(&crate::ribbon::common::MENU_ARROW)).label(tl!("Undo History").to_string()).enabled(enabled).show(ui);
|
||||
let labels = undo_list_rows(app);
|
||||
let mut open = app.chrome.undo;
|
||||
if out.response.clicked() {
|
||||
open = !open;
|
||||
}
|
||||
let mut mark = app.chrome.undo_mark;
|
||||
let was_open = app.chrome.undo;
|
||||
// Through the exit fade the list draws what it had when it closed.
|
||||
let closing = if open { None } else { app.chrome.undo_closing.take() };
|
||||
let mut mark = closing.as_ref().map_or(app.chrome.undo_mark, |(_, m)| *m);
|
||||
let mut picked = None;
|
||||
let mut drawn = None;
|
||||
Popover::new(tl!("Undo History").to_string(), Bind::bound(&mut open)).opened_by(&out.response).show(ui, |ui, cx| {
|
||||
// Built inside the body, which runs only while the popover shows or fades.
|
||||
let labels = closing.as_ref().map_or_else(|| undo_list_rows(app), |(l, _)| l.clone());
|
||||
let rows = UndoRows::new(&labels);
|
||||
// A collection owns its scroll: the popover's body scrolls, so the list caps its rows and scrolls the rest.
|
||||
let events = UndoList::new(tl!("Undo History").to_string())
|
||||
@@ -178,6 +191,7 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
|
||||
.selection(Bind::bound(&mut mark))
|
||||
.show_items(ui, &rows, &mut |key, _| rows.row(*key))
|
||||
.events;
|
||||
drawn = Some(labels.clone());
|
||||
if let Some(count) = undo_count(&events) {
|
||||
picked = Some(count);
|
||||
cx.request_close();
|
||||
@@ -198,6 +212,11 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
|
||||
});
|
||||
app.chrome.undo = open;
|
||||
app.chrome.undo_mark = if open { mark } else { UndoMark::default() };
|
||||
app.chrome.undo_closing = match (open, was_open) {
|
||||
(true, _) => None,
|
||||
(false, true) => drawn.map(|l| (l, mark)),
|
||||
(false, false) => closing,
|
||||
};
|
||||
if let Some(count) = picked {
|
||||
let _ = app.run("edit.undoTo", json!({"count": count}));
|
||||
// Picking a row closes the Undo History popover on its foreground layer; return keyboard
|
||||
@@ -213,19 +232,17 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
|
||||
fn qat_menu(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
|
||||
let out =
|
||||
IconButton::new(IconId::new("wordcraft.more")).label(tl!("Customize Quick Access Toolbar").to_string()).glyphs(GlyphRole::Tool).show(ui);
|
||||
let shown: Vec<(&'static str, String, bool)> = QAT_MENU
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let label = app.session.registry.get(id).map(|s| tl!(s.label).to_string())?;
|
||||
Some((*id, label, app.session.ribbon.qat().contains(id)))
|
||||
})
|
||||
.collect();
|
||||
// No `open` binding: with one the framework leaves the opening to the app, without it the opener opens the menu.
|
||||
Menu::new(tl!("Customize Quick Access Toolbar").to_string()).opened_by(&out.response, Trigger::Click).show(ui, |ui, _| {
|
||||
MenuItem::heading(tl!("Customize Quick Access Toolbar").to_string()).show(ui);
|
||||
for (id, label, on) in &shown {
|
||||
let key = if *on { "qatRemove" } else { "qatAdd" };
|
||||
MenuItem::command(CommandRef::with_params("tools.customizeRibbon", json!({ key: *id }))).label(label.clone()).check(*on).show(ui);
|
||||
for &id in &QAT_MENU {
|
||||
let Some(spec) = app.session.registry.get(id) else { continue };
|
||||
let on = app.session.ribbon.qat().contains(&id);
|
||||
let key = if on { "qatRemove" } else { "qatAdd" };
|
||||
MenuItem::command(CommandRef::with_params("tools.customizeRibbon", json!({ key: id })))
|
||||
.label(tl!(spec.label).to_string())
|
||||
.check(on)
|
||||
.show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
MenuItem::command(CommandRef::with_params("ui.dialog", json!({"name": "customizeQuickAccess"})))
|
||||
|
||||
+207
-36
@@ -17,10 +17,10 @@ use craft::ui::choice::{CellMarks, SwatchTable};
|
||||
use craft::ui::contract::{BodyCx, Hover, NoValue, Props as _, Show as _, clicked};
|
||||
use craft::ui::dialog::{DialogId, DialogResult};
|
||||
use craft::ui::menu::{MenuItem, MenuItemOutput};
|
||||
use craft::ui::primitives::{IconMark, IconSpec};
|
||||
use craft::ui::primitives::{Glyph, IconMark, IconSpec, StrokeWidth};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::style::DataColor;
|
||||
use egui::{Color32, Ui};
|
||||
use craft::ui::style::{DataColor, UiTokens};
|
||||
use egui::{Color32, Painter, Rect, Stroke, StrokeKind, Ui, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::Rgb;
|
||||
|
||||
@@ -241,18 +241,76 @@ pub fn apply(app: &mut WordApp, target: &Target, hex: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour a target has now (the dialog's Current swatch).
|
||||
/// The colour every item has, `None` for no items, no colour, or items that differ.
|
||||
fn agree(mut colors: impl Iterator<Item = Option<Rgb>>) -> Option<Rgb> {
|
||||
let first = colors.next()??;
|
||||
colors.all(|c| c == Some(first)).then_some(first)
|
||||
}
|
||||
|
||||
/// The shading the given cells share; cells a ragged table lacks are skipped, not read as unshaded.
|
||||
fn cell_shading(table: &wordcraft_doc::Table, cells: impl IntoIterator<Item = (usize, usize)>) -> Option<Rgb> {
|
||||
agree(cells.into_iter().filter_map(|(r, c)| table.rows.get(r)?.cells.get(c).map(|cell| cell.props.shading)))
|
||||
}
|
||||
|
||||
/// The colour a target has now (the dialog's Current swatch), read from what its command changes:
|
||||
/// `para.shading` reads the selected text's shading when the selection is text within one paragraph,
|
||||
/// else the paragraphs'; `shape.effects` reads shapes only. `None` when it has none, is Automatic,
|
||||
/// differs across the selection, or cannot be read (a picture's icon colour is not stored).
|
||||
fn current_of(app: &mut WordApp, target: &Target) -> Option<Rgb> {
|
||||
use wordcraft_doc::InlineObject;
|
||||
let Target::Run { cmd, .. } = target else { return None };
|
||||
let s = &app.session;
|
||||
let shapes = |o: &InlineObject| matches!(o, InlineObject::Shape { .. }) || o.is_canvas();
|
||||
let objects = || wordcraft_engine::cmd::objects::target_objects(s, shapes).into_iter().map(|(_, o)| o);
|
||||
match cmd.as_str() {
|
||||
"format.color" => {
|
||||
let st = wordcraft_engine::cmd::format::state(&app.session);
|
||||
st.get("color").and_then(Value::as_str).and_then(parse)
|
||||
"format.color" | "format.underlineColor" => {
|
||||
let st = wordcraft_engine::cmd::format::cached_state(s);
|
||||
let key = if cmd == "format.color" { "color" } else { "underlineColor" };
|
||||
st.get(key).and_then(Value::as_str).and_then(parse)
|
||||
}
|
||||
// The command shades the selected text, not its paragraph, when the selection is text within one.
|
||||
"para.shading" if wordcraft_engine::cmd::para::shades_text(s) => {
|
||||
wordcraft_engine::cmd::format::cached_state(s).get("shading").and_then(Value::as_str).and_then(parse)
|
||||
}
|
||||
"para.shading" => agree(
|
||||
wordcraft_engine::cmd::selected_paths(s)
|
||||
.iter()
|
||||
.map(|path| s.doc.para(s.sel.focus.story, path).and_then(|p| s.doc.styles.resolve_para(&p.props).shading)),
|
||||
),
|
||||
"table.shading" => {
|
||||
let (tp, _, _) = s.sel.focus.path.cell()?;
|
||||
let table = s.doc.table(s.sel.focus.story, &tp)?;
|
||||
cell_shading(table, wordcraft_engine::cmd::table::selected_cells(s))
|
||||
}
|
||||
"design.pageColor" => s.doc.settings.page_color,
|
||||
"shape.fill" => agree(objects().map(|o| {
|
||||
let fill = match &o {
|
||||
InlineObject::Shape { fill, .. } => fill.as_ref(),
|
||||
o => o.canvas_style().and_then(|c| c.fill.as_ref()),
|
||||
};
|
||||
match fill {
|
||||
Some(wordcraft_doc::fill::Fill::Solid { color, .. }) => Some(*color),
|
||||
_ => None,
|
||||
}
|
||||
})),
|
||||
"shape.outline" => agree(objects().map(|o| match &o {
|
||||
InlineObject::Shape { stroke, .. } => *stroke,
|
||||
o => o.canvas_style().and_then(|c| c.stroke),
|
||||
})),
|
||||
// Glow is applied to shapes only, so a canvas in the selection is not read.
|
||||
"shape.effects" => agree(objects().filter(|o| matches!(o, InlineObject::Shape { .. })).map(|o| match &o {
|
||||
InlineObject::Shape { effects, .. } => effects.glow.as_ref().map(|g| g.color),
|
||||
_ => None,
|
||||
})),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the selection's font colour is uniformly Automatic.
|
||||
fn current_is_auto(app: &WordApp) -> bool {
|
||||
wordcraft_engine::cmd::format::state(&app.session).get("color").and_then(Value::as_str) == Some("auto")
|
||||
}
|
||||
|
||||
/// The colour a split button's main part applies: what its target remembers, else what is in effect.
|
||||
fn remembered(app: &mut WordApp, target: &Target) -> Option<Rgb> {
|
||||
match target {
|
||||
@@ -287,9 +345,9 @@ pub struct ColorPick {
|
||||
pub response: egui::Response,
|
||||
/// The colour picked in this pass.
|
||||
pub picked: Option<Rgb>,
|
||||
/// What the pointer over a swatch did to the live preview: it shows while the pointer is over a
|
||||
/// swatch and ends when it leaves.
|
||||
pub preview: craft::behavior::Preview<Rgb>,
|
||||
/// What the pointer over a swatch or menu choice did to the live preview: `Some(c)` for a
|
||||
/// palette colour, `None` for Automatic / No Color, and `Ended` when the pointer leaves.
|
||||
pub preview: craft::behavior::Preview<Option<Rgb>>,
|
||||
/// The main part's stay of a split button; `Hover::default()` for a body without one.
|
||||
pub hover: Hover,
|
||||
}
|
||||
@@ -318,9 +376,9 @@ fn swatch_table(
|
||||
(picked, preview, out.response)
|
||||
}
|
||||
|
||||
/// Two previews of one pass: a start wins over an end, as the pointer moving from one table to
|
||||
/// Two previews of one pass: a start wins over an end, as the pointer moving from one control to
|
||||
/// the next ends one and starts the other.
|
||||
fn merge_preview(a: craft::behavior::Preview<Rgb>, b: craft::behavior::Preview<Rgb>) -> craft::behavior::Preview<Rgb> {
|
||||
fn merge_preview<T>(a: craft::behavior::Preview<T>, b: craft::behavior::Preview<T>) -> craft::behavior::Preview<T> {
|
||||
use craft::behavior::Preview;
|
||||
match (a, b) {
|
||||
(Preview::Shows(c), _) | (_, Preview::Shows(c)) => Preview::Shows(c),
|
||||
@@ -329,6 +387,26 @@ fn merge_preview(a: craft::behavior::Preview<Rgb>, b: craft::behavior::Preview<R
|
||||
}
|
||||
}
|
||||
|
||||
/// Tracks hover preview transitions for a single `MenuItem` inside a colour drop-down so hovering
|
||||
/// it previews `None` and leaving or closing the drop-down ends the preview.
|
||||
fn item_preview(ctx: &egui::Context, key: egui::Id, hovered: bool, open: bool) -> craft::behavior::Preview<Option<Rgb>> {
|
||||
use craft::behavior::Preview;
|
||||
let was = ctx.data(|d| d.get_temp::<bool>(key)).unwrap_or(false);
|
||||
if !open {
|
||||
if was {
|
||||
ctx.data_mut(|d| d.remove::<bool>(key));
|
||||
return Preview::Ended;
|
||||
}
|
||||
return Preview::Unchanged;
|
||||
}
|
||||
if hovered != was {
|
||||
ctx.data_mut(|d| d.insert_temp(key, hovered));
|
||||
if hovered { Preview::Shows(None) } else { Preview::Ended }
|
||||
} else {
|
||||
Preview::Unchanged
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme and recent swatches of `palette`; the colour in effect carries the selection mark.
|
||||
fn swatches(ui: &mut Ui, palette: &Palette, current: Option<Rgb>) -> (Option<Rgb>, craft::behavior::Preview<Rgb>) {
|
||||
let (mut picked, mut preview, _) = swatch_table(ui, "Theme Colors", &palette.theme, THEME_PER_ROW, current);
|
||||
@@ -360,7 +438,7 @@ pub fn palette(ui: &mut Ui, app: &mut WordApp, target: Target) -> ColorPick {
|
||||
if more.ran {
|
||||
open_for(app, &target, current, ColorPickerTab::Standard);
|
||||
}
|
||||
ColorPick { response: more.response, picked, preview, hover: Hover::default() }
|
||||
ColorPick { response: more.response, picked, preview: preview.map(Some), hover: Hover::default() }
|
||||
}
|
||||
|
||||
/// A command colour drop-down's body: [`palette`]; the caller closes the drop-down.
|
||||
@@ -390,30 +468,33 @@ enum Above {
|
||||
}
|
||||
|
||||
/// A split button whose main part runs `main` and whose arrow opens `body`.
|
||||
/// `body` returns its `ColorPick` and whether its `Automatic` / `No Color` item is hovered.
|
||||
fn split_with(
|
||||
ui: &mut Ui,
|
||||
app: &mut WordApp,
|
||||
label: Label,
|
||||
icon: IconSpec<'static>,
|
||||
main: CommandRef,
|
||||
mut body: impl FnMut(&mut Ui, &mut WordApp, &mut BodyCx<'_>) -> ColorPick,
|
||||
mut body: impl FnMut(&mut Ui, &mut WordApp, &mut BodyCx<'_>) -> (ColorPick, bool),
|
||||
) -> ColorPick {
|
||||
let mut inner: Option<(Option<Rgb>, craft::behavior::Preview<Rgb>)> = None;
|
||||
let mut inner: Option<(Option<Rgb>, craft::behavior::Preview<Option<Rgb>>, bool)> = None;
|
||||
// The arrow is its own button, named "<label> options" so it is told from the main part (#3172).
|
||||
let arrow_name = crate::i18n::fmt(tl!("{name} options"), &[("name", label.as_str())]);
|
||||
let out = SplitButton::<NoValue>::command(
|
||||
main,
|
||||
SplitMenu::Body(Box::new(|ui: &mut Ui, cx: &mut BodyCx<'_>| {
|
||||
let pick = body(ui, app, cx);
|
||||
inner = Some((pick.picked, pick.preview));
|
||||
let (pick, empty_hovered) = body(ui, app, cx);
|
||||
inner = Some((pick.picked, pick.preview, empty_hovered));
|
||||
})),
|
||||
)
|
||||
.label(label)
|
||||
.arrow_label(arrow_name)
|
||||
.icon(icon)
|
||||
.show(ui);
|
||||
let (picked, preview) = inner.unwrap_or((None, craft::behavior::Preview::Unchanged));
|
||||
ColorPick { response: out.response, picked, preview, hover: out.hover }
|
||||
let open = inner.is_some();
|
||||
let (picked, swatch_preview, empty_hovered) = inner.unwrap_or((None, craft::behavior::Preview::Unchanged, false));
|
||||
let empty_preview = item_preview(ui.ctx(), out.response.id.with("empty_hover"), empty_hovered, open);
|
||||
ColorPick { response: out.response, picked, preview: merge_preview(swatch_preview, empty_preview), hover: out.hover }
|
||||
}
|
||||
|
||||
/// The split button of a colour `target`: the icon of its command with a bar of the remembered
|
||||
@@ -433,24 +514,29 @@ fn color_split(ui: &mut Ui, app: &mut WordApp, label: Label, target: Target, abo
|
||||
_ => CommandRef::new(cmd.clone()),
|
||||
};
|
||||
split_with(ui, app, label, icon, main, |ui, app, cx| {
|
||||
let mut empty_hovered = false;
|
||||
match above {
|
||||
Above::Nothing => {}
|
||||
Above::Automatic => {
|
||||
let auto = CommandRef::with_params("format.color", json!({"color": "auto"}));
|
||||
if MenuItem::new(tl!("Automatic").to_string()).command(auto).show(ui).ran {
|
||||
let item = MenuItem::new(tl!("Automatic").to_string()).command(auto).check(current_is_auto(app)).show(ui);
|
||||
if item.ran {
|
||||
cx.request_close();
|
||||
}
|
||||
empty_hovered = item.response.hovered() && !item.ran;
|
||||
}
|
||||
Above::NoColor => {
|
||||
let none = CommandRef::with_params(cmd.clone(), json!({"color": null}));
|
||||
if MenuItem::new(tl!("No Color").to_string()).command(none).show(ui).ran {
|
||||
let item = MenuItem::new(tl!("No Color").to_string()).command(none).show(ui);
|
||||
if item.ran {
|
||||
cx.request_close();
|
||||
}
|
||||
empty_hovered = item.response.hovered() && !item.ran;
|
||||
}
|
||||
}
|
||||
let pick = menu(ui, app, target.clone());
|
||||
close_after(&pick, cx);
|
||||
pick
|
||||
(pick, empty_hovered)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -480,17 +566,15 @@ pub(crate) fn highlight_button_appearance(name: &str) -> (&'static str, Option<C
|
||||
/// The highlight drop-down: the highlight colours five to a row, then No Color. A pick, No Color
|
||||
/// too, becomes the split button's colour, as in Word: after No Color a click on the button
|
||||
/// removes highlighting (#2105).
|
||||
fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> ColorPick {
|
||||
fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> (ColorPick, bool) {
|
||||
use wordcraft_doc::props::Highlight;
|
||||
let in_effect = Some(wordcraft_engine::cmd::format::state(&app.session))
|
||||
.and_then(|st| st.get("highlight").and_then(Value::as_str).map(str::to_string))
|
||||
.unwrap_or_else(|| "none".into());
|
||||
let in_effect = wordcraft_engine::cmd::format::uniform_highlight(&app.session);
|
||||
let shown: Vec<(&Highlight, Rgb)> = Highlight::ALL.iter().skip(1).filter_map(|h| h.rgb().map(|c| (h, c))).collect();
|
||||
let swatches: Vec<(Label, Srgba)> = shown.iter().map(|(h, c)| (Label::from(tl!(h.name()).to_string()), srgba(*c))).collect();
|
||||
let out = SwatchTable::new("Highlight Colors".to_string(), &swatches)
|
||||
.per_row(5)
|
||||
.tips(true)
|
||||
.marks(|i: &usize| CellMarks::default().edge(shown.get(*i).is_some_and(|(h, _)| h.ooxml() == in_effect)))
|
||||
.marks(|i: &usize| CellMarks::default().edge(shown.get(*i).is_some_and(|(_, c)| in_effect == Some(Some(*c)))))
|
||||
.show_all(ui);
|
||||
let mut picked = None;
|
||||
if let Some((h, c)) = out.selected.and_then(|i| shown.get(i)) {
|
||||
@@ -500,16 +584,20 @@ fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> ColorP
|
||||
cx.request_close();
|
||||
}
|
||||
let preview = match out.preview {
|
||||
craft::behavior::Preview::Shows(i) => shown.get(i).map_or(craft::behavior::Preview::Unchanged, |(_, c)| craft::behavior::Preview::Shows(*c)),
|
||||
craft::behavior::Preview::Shows(i) => {
|
||||
shown.get(i).map_or(craft::behavior::Preview::Unchanged, |(_, c)| craft::behavior::Preview::Shows(Some(*c)))
|
||||
}
|
||||
craft::behavior::Preview::Ended => craft::behavior::Preview::Ended,
|
||||
_ => craft::behavior::Preview::Unchanged,
|
||||
};
|
||||
let none = CommandRef::with_params("format.highlight", json!({"color": "none"}));
|
||||
if MenuItem::new(tl!("No Color").to_string()).command(none).show(ui).ran {
|
||||
let no_color = MenuItem::new(tl!("No Color").to_string()).command(none).check(in_effect == Some(None)).show(ui);
|
||||
if no_color.ran {
|
||||
app.canvas.last_highlight = "none".into();
|
||||
cx.request_close();
|
||||
}
|
||||
ColorPick { response: out.response, picked, preview, hover: Hover::default() }
|
||||
let empty_hovered = no_color.response.hovered() && !no_color.ran;
|
||||
(ColorPick { response: out.response, picked, preview, hover: Hover::default() }, empty_hovered)
|
||||
}
|
||||
|
||||
/// Text Highlight Color: the highlight grid under the arrow; the main part applies the remembered
|
||||
@@ -529,14 +617,15 @@ pub fn highlight_split(ui: &mut Ui, app: &mut WordApp, label: impl Into<Label>)
|
||||
// More Colors…
|
||||
|
||||
/// The Colors dialog: Standard honeycomb and greys, Custom compact picker. `current` is the colour
|
||||
/// the target has now; `key` comes back in the result.
|
||||
/// the target has now, `None` when it has none: Current then shows no colour (as in v0.19.1) and
|
||||
/// Restore does nothing, while New starts on black. `key` comes back in the result.
|
||||
pub fn more_colors(current: Option<Rgb>, key: String, tab: ColorPickerTab) -> ColorPickerDialog {
|
||||
let (cells, greys) = standard_cells();
|
||||
ColorPickerDialog::new(key, tl!("Colors").to_string(), current.map_or(Srgba::rgb(0.0, 0.0, 0.0), srgba))
|
||||
let dialog = ColorPickerDialog::new(key, tl!("Colors").to_string(), current.map_or(Srgba::rgb(0.0, 0.0, 0.0), srgba))
|
||||
.layout(ColorPickerDialogLayout::Tabbed)
|
||||
.standard(cells, greys)
|
||||
.compare(current.is_some())
|
||||
.tab(tab)
|
||||
.tab(tab);
|
||||
if current.is_some() { dialog } else { dialog.no_current() }
|
||||
}
|
||||
|
||||
/// Opens the Colors dialog for `target`, remembering where its answer goes.
|
||||
@@ -613,6 +702,23 @@ pub enum AutoFace {
|
||||
Several(Vec<Srgba>),
|
||||
}
|
||||
|
||||
/// The swatch of a choice of several colours (By author): the colours side by side in equal shares, framed as a one-colour
|
||||
/// swatch is.
|
||||
#[derive(craft::ui::contract::MemoProps)]
|
||||
struct SwatchShares(Vec<Srgba>);
|
||||
|
||||
impl Glyph for SwatchShares {
|
||||
fn paint(&self, painter: &Painter, tokens: &UiTokens, rect: Rect, color: Color32, _mirrored: bool) {
|
||||
let width = rect.width() / self.0.len().max(1) as f32;
|
||||
for (at, share) in self.0.iter().enumerate() {
|
||||
let part = Rect::from_min_size(rect.min + vec2(width * at as f32, 0.0), vec2(width, rect.height()));
|
||||
painter.rect_filled(part, 0.0, color32(rgb_of(*share)));
|
||||
}
|
||||
let stroke = Stroke::new(StrokeWidth::Thin.points(tokens, painter.pixels_per_point()), color);
|
||||
painter.rect_stroke(rect, 0.0, stroke, StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a colour field did in a pass.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ColorFieldResponse {
|
||||
@@ -630,7 +736,7 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
|
||||
let (shown, text) = match (current, empty) {
|
||||
(Some(c), _) => (Some(srgba(c)), Label::from(c.hex())),
|
||||
(None, ColorFieldEmpty::NoColor) => (None, Label::from(tl!("No Color").to_string())),
|
||||
// PLAN: framework gap: `IconSpec` has no multi-share swatch face, so `AutoFace::Several` shows its first colour until `IconSource` can paint `SwatchFace` shares (ribbon-w2).
|
||||
// Two or more `AutoFace::Several` colours paint as `SwatchShares` (below); a single one paints as itself.
|
||||
(None, ColorFieldEmpty::Automatic { label, face, .. }) => (
|
||||
match face {
|
||||
AutoFace::One(c) => Some(*c),
|
||||
@@ -639,7 +745,14 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
|
||||
label.clone(),
|
||||
),
|
||||
};
|
||||
let icon = shown.map_or_else(IconSpec::empty_swatch, IconSpec::swatch);
|
||||
let shares = match (current, empty) {
|
||||
(None, ColorFieldEmpty::Automatic { face: AutoFace::Several(colors), .. }) if colors.len() > 1 => Some(SwatchShares(colors.clone())),
|
||||
_ => None,
|
||||
};
|
||||
let icon = match &shares {
|
||||
Some(shares) => IconSpec::glyph(shares),
|
||||
None => shown.map_or_else(IconSpec::empty_swatch, IconSpec::swatch),
|
||||
};
|
||||
let spoken_value = current.map_or_else(|| text.as_str().to_string(), |c| format!("#{}", c.hex()));
|
||||
let spoken = format!("{} {spoken_value}", label.as_str());
|
||||
let field = SplitButton::<NoValue>::body(text, |ui: &mut Ui, cx: &mut BodyCx<'_>| {
|
||||
@@ -766,4 +879,62 @@ mod tests {
|
||||
assert_eq!(app.ui.recent_colors.first().map(String::as_str), Some("7A3EC8"));
|
||||
assert!(app.more_colors.is_empty(), "no entry outlives its dialog");
|
||||
}
|
||||
|
||||
/// The Current swatch reads what the selection has, and says "no colour" where there is none or it
|
||||
/// differs (#7984).
|
||||
#[test]
|
||||
fn current_reads_the_selection_and_is_none_when_unset_or_mixed() {
|
||||
let c = |hex: u8| Rgb(hex, hex, hex);
|
||||
assert_eq!(agree([Some(c(1)), Some(c(1))].into_iter()), Some(c(1)), "all alike");
|
||||
assert_eq!(agree([Some(c(1)), Some(c(2))].into_iter()), None, "mixed");
|
||||
assert_eq!(agree([Some(c(1)), None].into_iter()), None, "one has none");
|
||||
assert_eq!(agree(std::iter::empty()), None, "nothing selected");
|
||||
|
||||
// Set on the caret's paragraph directly: the commands lay the page out, which costs ~0.7 s.
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
let shading = Target::cmd("para.shading");
|
||||
assert_eq!(current_of(&mut app, &shading), None, "no shading yet");
|
||||
assert_eq!(current_of(&mut app, &Target::cmd("table.shading")), None, "no table, no colour");
|
||||
assert_eq!(current_of(&mut app, &Target::cmd("shape.fill")), None, "no shape selected");
|
||||
let at = app.session.sel.focus.clone();
|
||||
app.session.doc.para_mut(at.story, &at.path).unwrap().props.shading = Some(c(0xAA));
|
||||
assert_eq!(current_of(&mut app, &shading), Some(c(0xAA)), "a collapsed caret reads its paragraph");
|
||||
}
|
||||
|
||||
/// Text selected inside a paragraph is what Shading changes, so Current must not report the
|
||||
/// paragraph's shading for it (#7984).
|
||||
#[test]
|
||||
fn partial_selection_reads_the_text_shading_not_the_paragraph() {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("hello world")), crate::Services::default());
|
||||
let at = app.session.sel.focus.clone();
|
||||
app.session.doc.para_mut(at.story, &at.path).unwrap().props.shading = Some(Rgb(0xAA, 0xAA, 0xAA));
|
||||
let mut end = at.clone();
|
||||
end.off = 5;
|
||||
app.session.sel = wordcraft_engine::Selection { anchor: at, focus: end };
|
||||
let shading = Target::cmd("para.shading");
|
||||
assert_eq!(current_of(&mut app, &shading), None, "the text has no shading, whatever its paragraph has");
|
||||
let _ = app.session.run("format.shading", &json!({"color": "112233"}));
|
||||
assert_eq!(current_of(&mut app, &shading), Some(Rgb(0x11, 0x22, 0x33)), "the selected run's shading");
|
||||
}
|
||||
|
||||
/// A ragged table's missing cells do not blank Current when the real cells agree (#7984).
|
||||
#[test]
|
||||
fn table_shading_skips_missing_cells() {
|
||||
let mut t = wordcraft_doc::Table::new(2, 2, 100.0);
|
||||
t.rows[1].cells.pop();
|
||||
for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
|
||||
cell.props.shading = Some(Rgb(1, 2, 3));
|
||||
}
|
||||
let all = [(0, 0), (0, 1), (1, 0), (1, 1)];
|
||||
assert_eq!(cell_shading(&t, all), Some(Rgb(1, 2, 3)), "the missing (1,1) is skipped");
|
||||
t.rows[0].cells[1].props.shading = None;
|
||||
assert_eq!(cell_shading(&t, all), None, "a real unshaded cell still blanks it");
|
||||
}
|
||||
|
||||
/// A target with no colour opens with no Current colour, not black (#7984).
|
||||
#[test]
|
||||
fn no_current_colour_is_not_black() {
|
||||
assert!(more_colors(None, "k".into(), ColorPickerTab::Standard).has_no_current());
|
||||
assert!(!more_colors(Some(Rgb(0, 0, 0)), "k".into(), ColorPickerTab::Standard).has_no_current(), "a real black stays a current colour");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
//! through `tools.customizeKeyboard`, so agents get the same result without the dialog.
|
||||
|
||||
use craft::keymap::{Binding, CommandDef, Keymap, Overrides};
|
||||
use craft::menu::shortcuts::{DialogState, Layout, Options, Outcome, ShortcutsDialog};
|
||||
use craft::menu::shortcuts::{Area, DialogState, Layout, Options, Outcome, ShortcutsDialog};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use egui::{Context, Ui};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::ribbon::{CONTEXTUAL_TABS, TABS};
|
||||
|
||||
use super::host::{DialogHooks, Settle, open_with};
|
||||
use crate::WordApp;
|
||||
@@ -49,11 +50,61 @@ fn assignable(binding: &Binding) -> bool {
|
||||
chord.mods.cmd || chord.mods.ctrl || chord.mods.alt || chord.is_function_key()
|
||||
}
|
||||
|
||||
/// The ribbon tab a command lives on, in English (the first part of its path).
|
||||
fn tab(def: &CommandDef) -> &str {
|
||||
def.paths.first().and_then(|path| path.first()).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
/// Tabs that come up with the selection or a view, besides the engine's contextual ones; they share one Categories entry.
|
||||
const EXTRA_CONTEXT_TABS: [&str; 3] = ["Header & Footer", "Outlining", "Reading"];
|
||||
|
||||
fn in_tab<const N: usize>(def: &CommandDef) -> bool {
|
||||
tab(def) == TABS[N]
|
||||
}
|
||||
|
||||
fn in_context_tab(def: &CommandDef) -> bool {
|
||||
CONTEXTUAL_TABS.contains(&tab(def)) || EXTRA_CONTEXT_TABS.contains(&tab(def))
|
||||
}
|
||||
|
||||
fn in_no_tab(def: &CommandDef) -> bool {
|
||||
!TABS.contains(&tab(def)) && !in_context_tab(def)
|
||||
}
|
||||
|
||||
/// One filter per entry of `TABS` (the array's length makes the compiler check it).
|
||||
const TAB_FILTERS: [fn(&CommandDef) -> bool; TABS.len()] = [
|
||||
in_tab::<0>,
|
||||
in_tab::<1>,
|
||||
in_tab::<2>,
|
||||
in_tab::<3>,
|
||||
in_tab::<4>,
|
||||
in_tab::<5>,
|
||||
in_tab::<6>,
|
||||
in_tab::<7>,
|
||||
in_tab::<8>,
|
||||
in_tab::<9>,
|
||||
in_tab::<10>,
|
||||
in_tab::<11>,
|
||||
in_tab::<12>,
|
||||
];
|
||||
|
||||
/// Categories as Word lists them: the ribbon tabs (not the framework's menu and panel ids), the contextual tabs, the
|
||||
/// rest, then All Commands.
|
||||
fn areas() -> Vec<Area> {
|
||||
let mut areas: Vec<Area> = TABS.iter().copied().zip(TAB_FILTERS).map(|(name, rows)| Area::new(name, tl!(name), rows)).collect();
|
||||
areas.push(Area::new("Contextual Tabs", tl!("Contextual Tabs"), in_context_tab));
|
||||
areas.push(Area::new("Other", tl!("Other"), in_no_tab));
|
||||
areas.push(Area::new("All Commands", tl!("All Commands"), |_| true));
|
||||
areas
|
||||
}
|
||||
|
||||
/// The framework dialog's options: the command-list layout, sorted by label, with the assign rule above.
|
||||
fn options() -> Options {
|
||||
Options::default().with(|o| {
|
||||
o.layout = Layout::CommandLists;
|
||||
o.sort_by_label = true;
|
||||
o.own_areas = true;
|
||||
o.size = Some(egui::vec2(720.0, 700.0));
|
||||
o.areas = areas();
|
||||
o.title = Some(tl!("Customize Keyboard").to_string());
|
||||
o.accept = Some(Box::new(|_: &CommandDef, binding: &Binding| {
|
||||
if assignable(binding) { Ok(()) } else { Err(tl!("Use a key combination with Ctrl, Alt or a function key.").to_string()) }
|
||||
@@ -247,4 +298,53 @@ mod tests {
|
||||
let unbound_labels = keys_list_labels(&h);
|
||||
assert!(unbound_labels.iter().any(|t| t == "None"), "empty keys list says None: {unbound_labels:?}");
|
||||
}
|
||||
|
||||
/// #7971: Categories are the ribbon tabs a command is on, not menu or panel ids; a command with no tab is under Other,
|
||||
/// and every command is under All Commands.
|
||||
#[test]
|
||||
fn categories_are_ribbon_tabs() {
|
||||
use craft::keymap::{CommandDef, Scope};
|
||||
let on = |path: &[&str]| {
|
||||
let mut def = CommandDef::new(CommandRef::new("x"), "X", Scope::app());
|
||||
if !path.is_empty() {
|
||||
def = def.with_path(path.iter().map(|part| part.to_string()).collect());
|
||||
}
|
||||
def
|
||||
};
|
||||
let areas = super::areas();
|
||||
let listing = |def: &CommandDef| areas.iter().filter(|a| (a.rows)(def)).map(|a| a.id).collect::<Vec<_>>();
|
||||
assert_eq!(listing(&on(&["Home", "Font"])), ["Home", "All Commands"]);
|
||||
assert_eq!(listing(&on(&["Help", "Support"])), ["Help", "All Commands"], "every ribbon tab has its entry");
|
||||
assert_eq!(listing(&on(&["Table Design", "Styles"])), ["Contextual Tabs", "All Commands"]);
|
||||
assert_eq!(listing(&on(&[])), ["Other", "All Commands"]);
|
||||
assert_eq!(areas.last().map(|a| a.id), Some("All Commands"), "All Commands comes last");
|
||||
}
|
||||
|
||||
/// #7971: under another language, and for the SmartArt tab that shows as "Diagram Design", commands still land
|
||||
/// under their tab (the catalog keeps English paths; only the display is translated).
|
||||
#[test]
|
||||
fn commands_stay_under_their_tab_in_another_language() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::i18n::fixture_host(&ctx, "x-fixture", "\tHome\tHome-FX\n\tFont\tFont-FX\n\tDiagram Design\tDiagram-FX\n");
|
||||
let mut a = app();
|
||||
let catalog = a.catalog().expect("catalog");
|
||||
let areas = super::areas();
|
||||
let under = |id: &str, area: &str| {
|
||||
let def = catalog.defs().iter().find(|def| def.command == CommandRef::new(id)).unwrap_or_else(|| panic!("{id} in catalog"));
|
||||
areas.iter().any(|a| a.id == area && (a.rows)(def))
|
||||
};
|
||||
assert!(under("format.bold", "Home"), "Bold is under Home in a translated interface");
|
||||
assert!(!under("format.bold", "Other"));
|
||||
let smart = a.session.registry.all().iter().find(|spec| spec.location.starts_with("SmartArt Design")).expect("a SmartArt command");
|
||||
assert!(under(smart.id, "Contextual Tabs") && !under(smart.id, "Other"), "{} is under the contextual tabs", smart.id);
|
||||
}
|
||||
|
||||
/// #7971: the board's catalog files each engine command under its ribbon tab.
|
||||
#[test]
|
||||
fn catalog_paths_follow_the_ribbon_location() {
|
||||
let mut a = app();
|
||||
let catalog = a.catalog().expect("catalog");
|
||||
let bold = catalog.defs().iter().find(|def| def.command == CommandRef::new("format.bold")).expect("format.bold");
|
||||
assert_eq!(bold.paths.first().and_then(|p| p.first()).map(String::as_str), Some("Home"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -869,4 +869,39 @@ mod tests {
|
||||
assert!(!black_text_samples.is_empty(), "{theme}: preview text samples must override text color with black");
|
||||
}
|
||||
}
|
||||
|
||||
/// The By author colour choice's swatch shows the first three author colours side by side, as it did before the
|
||||
/// port, not the first author's colour alone.
|
||||
#[test]
|
||||
fn track_changes_options_by_author_swatch_shows_three_author_colours() {
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
fn fills_in(shape: &egui::Shape, area: egui::Rect, out: &mut Vec<egui::Color32>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| fills_in(shape, area, out)),
|
||||
egui::Shape::Rect(rect) if area.contains_rect(rect.rect) => out.push(rect.fill),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut h = harness(app());
|
||||
h.state_mut().run("review.trackingOptions", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
// The Insertions row's colour field, at By author.
|
||||
// The first node named "Color: By author" is the field's body, or its arrow once the row's `Field` names the body
|
||||
// "Color:" (#7525); the field is every part of either name in that row.
|
||||
let first = h.query_all_by_label("Color: By author").next().expect("a By author colour field").rect();
|
||||
let field = h
|
||||
.query_all_by_label("Color: By author")
|
||||
.chain(h.query_all_by_label("Color:"))
|
||||
.map(|node| node.rect())
|
||||
.filter(|rect| (rect.center().y - first.center().y).abs() < 1.0)
|
||||
.fold(first, |all, rect| all.union(rect));
|
||||
let mut fills = Vec::new();
|
||||
for clipped in &h.output().shapes {
|
||||
fills_in(&clipped.shape, field, &mut fills);
|
||||
}
|
||||
for k in 0..3 {
|
||||
let c = wordcraft_layout::display::revision_color(k);
|
||||
assert!(fills.contains(&egui::Color32::from_rgb(c.0, c.1, c.2)), "author {k}'s colour is in the swatch: {fills:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::borrow::Cow;
|
||||
|
||||
use craft::behavior::{Mixed, SelectionChange, keyed};
|
||||
use craft::color_ui::ui::ColorPickerTab;
|
||||
use craft::pages::ui::table::{BorderEdges, EdgeKey, EdgeLook, EdgePicker, SampleArea};
|
||||
use craft::pages::ui::table::{BorderEdges, EdgeKey, EdgeLook, EdgePicker, EdgeSize, SampleArea};
|
||||
use craft::text::ui::DocUnit;
|
||||
use craft::text::ui::ruler::{TabAlign as UiAlign, TabLeader as UiLeader, TabStop as UiStop};
|
||||
use craft::text::ui::tabs_dialog::{MAX_STOPS, TabStopsDialog, TabStopsResult};
|
||||
@@ -518,7 +518,7 @@ fn lines(ui: &mut Ui, key: &'static str, l: &mut LineForm, area: SampleArea, fil
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
let mut edges = l.edges(between);
|
||||
let sample = EdgeLook::sample(area, fill.map(srgba));
|
||||
let picker = EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut edges)).look(sample);
|
||||
let picker = EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut edges)).look(sample).preview(EdgeSize::Sample);
|
||||
let picker = if between { picker.paragraph() } else { picker };
|
||||
picker.show(ui);
|
||||
l.take_edges(edges, between);
|
||||
@@ -572,7 +572,7 @@ impl WordForm for BordersForm {
|
||||
let mut none = BorderEdges::default();
|
||||
let area = if self.fill_to_text { SampleArea::Text } else { SampleArea::Paragraph };
|
||||
let sample = EdgeLook::sample(area, Rgb::parse(&self.fill).map(srgba));
|
||||
EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut none)).look(sample).enabled(false).show(ui);
|
||||
EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut none)).look(sample).preview(EdgeSize::Sample).enabled(false).show(ui);
|
||||
Self::apply_to(ui, &mut self.fill_to_text, word(tl!("Paragraph")), word(tl!("Text")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,12 +116,15 @@ impl WordForm for CaptionForm {
|
||||
let caption = Label::from(tl!("Caption:").to_string());
|
||||
if let Some(text) = Field::new(caption.clone())
|
||||
.show(ui, |ui, _| {
|
||||
TextField::new(caption.clone(), Bind::given(self.text.clone()))
|
||||
.prefix(Label::from(self.preview()))
|
||||
.placeholder(Label::from(tl!("Caption text").to_string()))
|
||||
.show(ui)
|
||||
.value()
|
||||
.cloned()
|
||||
ui.horizontal(|ui| {
|
||||
Text::new(Label::from(self.preview())).show(ui);
|
||||
TextField::new(caption.clone(), Bind::given(self.text.clone()))
|
||||
.placeholder(Label::from(tl!("Caption text").to_string()))
|
||||
.show(ui)
|
||||
.value()
|
||||
.cloned()
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner
|
||||
.flatten()
|
||||
|
||||
@@ -105,6 +105,29 @@ fn caption_dialog_remembers_the_last_label() {
|
||||
assert_eq!(CaptionForm::read(a).label, "Figure");
|
||||
}
|
||||
|
||||
/// #8042: the caption's preview is a separate label, not a prefix inside the field; an empty
|
||||
/// field shows only its placeholder.
|
||||
#[test]
|
||||
fn caption_preview_is_a_separate_label() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut a = app("A chart");
|
||||
a.run("select.text", json!({"text": "A chart"})).unwrap();
|
||||
a.run("references.caption", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let field = h.get_by_role_and_label(Role::TextInput, "Caption:");
|
||||
assert_eq!(field.value().as_deref(), Some(""), "the caption field starts empty");
|
||||
assert!(h.query_by_role_and_label(Role::Label, "Figure 1").is_some(), "the preview is its own label");
|
||||
}
|
||||
|
||||
/// #916: Cross-reference from the ribbon opens a dialog listing the targets of each type
|
||||
/// (equation captions too) and inserts a `REF` field to the one picked.
|
||||
#[test]
|
||||
|
||||
@@ -20,7 +20,7 @@ use craft::ui::contract::{
|
||||
};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, PromptChoice, StackDialog, StandardPrompt, dialog_id};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::layout_components::{Grid, Row, Stack};
|
||||
use craft::ui::list::{List, ListRow, ToggleCell, ToggleState};
|
||||
use craft::ui::notices::Notice;
|
||||
use craft::ui::runtime::env::Label;
|
||||
@@ -52,6 +52,8 @@ pub struct TreeItem {
|
||||
pub command: Option<String>,
|
||||
}
|
||||
|
||||
/// The body's panes: the command pickers, the Add and Remove buttons, then the ribbon or toolbar list.
|
||||
const PANES: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)];
|
||||
/// The column of show boxes in the ribbon tree.
|
||||
const SHOWN: ColumnKey = ColumnKey::new("shown");
|
||||
|
||||
@@ -144,10 +146,10 @@ impl RibbonDialog {
|
||||
fn body(&mut self, ui: &mut Ui) {
|
||||
self.page_tabs(ui);
|
||||
search(ui, &mut self.filter);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Grid::new(&PANES).fill_width().show(ui, |ui, _| {
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
Text::new(word("Choose a command")).show(ui);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Row::new().fill_width().show(ui, |ui, _| {
|
||||
if let Some(category) = pick(ui, "rb_categories", "Categories:", &self.categories, &self.category) {
|
||||
self.category = category;
|
||||
self.filter.clear();
|
||||
@@ -220,9 +222,9 @@ impl RibbonDialog {
|
||||
self.file("remove", Value::Object(address(&sel)));
|
||||
}
|
||||
});
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
Text::new(word("Ribbon tabs")).show(ui);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Row::new().fill_width().show(ui, |ui, _| {
|
||||
self.tree(ui);
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for (text, by) in [("Up", -1), ("Down", 1)] {
|
||||
@@ -311,9 +313,9 @@ impl RibbonDialog {
|
||||
self.file("qatRemove", json!(self.qat_selected));
|
||||
}
|
||||
});
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
Text::new(word("Quick Access Toolbar")).show(ui);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Row::new().fill_width().show(ui, |ui, _| {
|
||||
if let Some(id) = pick(ui, "rb_qat", "Quick Access Toolbar", &self.qat, &self.qat_selected) {
|
||||
self.qat_selected = id;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -22,7 +22,12 @@ use crate::WordApp;
|
||||
/// Opens `wordCount` or `zoom`; any other name opens nothing.
|
||||
pub(crate) fn open(app: &mut WordApp, name: &str, _params: &Value, parent: Option<DialogId>) -> Option<DialogId> {
|
||||
match name {
|
||||
"wordCount" => Some(open_with(app, parent, WordCountDialog::new(), DialogHooks::prepare_only(prepare_word_count))),
|
||||
"wordCount" => Some(open_with(
|
||||
app,
|
||||
parent,
|
||||
WordCountDialog::new(app.session.prefs.count_notes),
|
||||
DialogHooks { prepare: Some(prepare_word_count), settle: settle_word_count },
|
||||
)),
|
||||
"zoom" => {
|
||||
// The view keeps the zoom as a fraction (1.0 = 100%); the dialog shows and answers percent, as `view.zoom` takes it.
|
||||
let percent = (f64::from(app.session.view.zoom) * 100.0).round();
|
||||
@@ -32,15 +37,40 @@ pub(crate) fn open(app: &mut WordApp, name: &str, _params: &Value, parent: Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the six counts from the session before each pass; the dialog never keeps them beyond the pass.
|
||||
/// Reads the six counts and current `includeTextBoxes` preference from the session before each pass;
|
||||
/// does not send `includeTextBoxes` so automation changes stay in effect while the dialog is open.
|
||||
fn prepare_word_count(app: &mut WordApp, id: DialogId) {
|
||||
let include = app.dialog_host.get_by_id::<WordCountDialog>(id).is_none_or(|d| d.include_text_boxes);
|
||||
let stats = app.run("review.wordCount", json!({"includeTextBoxes": include})).ok();
|
||||
let stats = app.session.run("review.wordCount", &json!({})).ok();
|
||||
if let Some(d) = app.dialog_host.get_mut_by_id::<WordCountDialog>(id) {
|
||||
if let Some(on) = stats.as_ref().and_then(|s| s["includeTextBoxes"].as_bool()) {
|
||||
d.include_text_boxes = on;
|
||||
}
|
||||
d.stats = stats;
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies user toggles of "Count words in text boxes and notes" via `review.wordCount` and
|
||||
/// refreshes the displayed counts immediately.
|
||||
fn settle_word_count(app: &mut WordApp, ctx: &Context, id: DialogId) -> Settle {
|
||||
if let Some(res) = app.dialog_host.take_by_id::<WordCountDialog>(id) {
|
||||
if let DialogResult::Ok(Some(on)) = res {
|
||||
let _ = app.run("review.wordCount", json!({"includeTextBoxes": on}));
|
||||
}
|
||||
return Settle::Done;
|
||||
}
|
||||
if let Some(on) = app.dialog_host.get_mut_by_id::<WordCountDialog>(id).and_then(|d| d.toggled.take()) {
|
||||
let stats = app.run("review.wordCount", json!({"includeTextBoxes": on})).ok();
|
||||
if let Some(d) = app.dialog_host.get_mut_by_id::<WordCountDialog>(id) {
|
||||
if let Some(val) = stats.as_ref().and_then(|s| s["includeTextBoxes"].as_bool()) {
|
||||
d.include_text_boxes = val;
|
||||
}
|
||||
d.stats = stats;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Settle::Keep
|
||||
}
|
||||
|
||||
/// Runs `view.zoom` with the percent or the fit name the dialog answered with.
|
||||
fn settle_zoom(app: &mut WordApp, _: &Context, id: DialogId) -> Settle {
|
||||
match app.dialog_host.take_by_id::<ZoomDialog>(id) {
|
||||
@@ -68,20 +98,22 @@ const COUNT_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content; 2];
|
||||
|
||||
/// The Word Count dialog.
|
||||
pub(crate) struct WordCountDialog {
|
||||
/// The counts of the last `prepare`.
|
||||
/// The counts of the last `prepare` or `settle`.
|
||||
stats: Option<Value>,
|
||||
/// Whether text boxes and notes count.
|
||||
include_text_boxes: bool,
|
||||
/// User toggle waiting to be sent to `review.wordCount`.
|
||||
toggled: Option<bool>,
|
||||
}
|
||||
|
||||
impl WordCountDialog {
|
||||
fn new() -> Self {
|
||||
Self { stats: None, include_text_boxes: true }
|
||||
fn new(include_text_boxes: bool) -> Self {
|
||||
Self { stats: None, include_text_boxes, toggled: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl StackDialog for WordCountDialog {
|
||||
type Result = ();
|
||||
type Result = Option<bool>;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
dialog_id("wordCount")
|
||||
@@ -91,9 +123,10 @@ impl StackDialog for WordCountDialog {
|
||||
Some("wordCount")
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option<DialogResult<()>> {
|
||||
fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option<DialogResult<Option<bool>>> {
|
||||
let stats = self.stats.clone().unwrap_or(Value::Null);
|
||||
let include = &mut self.include_text_boxes;
|
||||
let pending_toggle = &mut self.toggled;
|
||||
let shown = Dialog::new(tl!("Word Count").to_string())
|
||||
// The old dialog's pair: Close as the default button, and Cancel; both only close it.
|
||||
.buttons([
|
||||
@@ -116,9 +149,10 @@ impl StackDialog for WordCountDialog {
|
||||
.show(ui);
|
||||
if let Some(on) = toggled.value().cloned() {
|
||||
*include = on;
|
||||
*pending_toggle = Some(on);
|
||||
}
|
||||
});
|
||||
shown.output.closed.map(|_| DialogResult::Ok(()))
|
||||
shown.output.closed.map(|_| DialogResult::Ok(self.toggled.take()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -16,6 +16,9 @@ use crate::WordApp;
|
||||
/// The Search Commands dialog; its answer is the query of the fallback row, when that was picked.
|
||||
pub(super) struct SearchCommandsDialog {
|
||||
entries: Vec<HelpEntry>,
|
||||
/// The entries' index and the interface language it was built in: built when the dialog first shows, and again
|
||||
/// only in another language, since building it folds every entry's labels.
|
||||
index: Option<(&'static str, SearchIndex)>,
|
||||
open: bool,
|
||||
suggested: Vec<CommandRef>,
|
||||
fallback: WordTemplate,
|
||||
@@ -27,6 +30,7 @@ impl SearchCommandsDialog {
|
||||
fn new(entries: Vec<HelpEntry>) -> Self {
|
||||
Self {
|
||||
entries,
|
||||
index: None,
|
||||
open: true,
|
||||
suggested: SEARCH_SUGGESTIONS.iter().map(|id| CommandRef::new(*id)).collect(),
|
||||
fallback: WordTemplate::new(tl!("Find “{text}” in the document")),
|
||||
@@ -48,11 +52,16 @@ impl StackDialog for SearchCommandsDialog {
|
||||
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<Option<String>>> {
|
||||
let env = Env::of(ui);
|
||||
let view = env.view();
|
||||
let index = SearchIndex::new(&view, &self.entries, &Synonyms::of(&view.words::<SearchWords>()));
|
||||
let lang = crate::i18n::current().code();
|
||||
let index = match self.index.take() {
|
||||
Some((built, index)) if built == lang => index,
|
||||
_ => SearchIndex::new(&view, &self.entries, &Synonyms::of(&view.words::<SearchWords>())),
|
||||
};
|
||||
let out = CommandPalette::new(tl!("Search Commands"), &self.entries, &index, Bind::bound(&mut self.open))
|
||||
.suggested((Label::from(tl!("Suggested")), self.suggested.clone()))
|
||||
.fallback(self.fallback.clone())
|
||||
.show(ui);
|
||||
self.index = Some((lang, index));
|
||||
if let Some(text) = out.fallback {
|
||||
return Some(DialogResult::Ok(Some(text)));
|
||||
}
|
||||
|
||||
@@ -94,15 +94,19 @@ fn flag(v: &Value, k: &str, default: bool) -> bool {
|
||||
v.get(k).and_then(Value::as_bool).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Opens Manage Styles with `params["style"]` selected (the first style when none); `None` for another name.
|
||||
/// Opens Manage Styles with `params["style"]` (or the caret's current style when omitted, falling back to the first style) selected; `None` for another name.
|
||||
pub(crate) fn open(app: &mut WordApp, name: &str, params: &Value, parent: Option<DialogId>) -> Option<DialogId> {
|
||||
if name != KEY {
|
||||
return None;
|
||||
}
|
||||
let selected =
|
||||
params.get("style").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(|| {
|
||||
wordcraft_engine::cmd::format::state(&app.session).get("style").and_then(Value::as_str).unwrap_or_default().to_string()
|
||||
});
|
||||
let dialog = ManageStylesDialog {
|
||||
id: dialog_id(KEY),
|
||||
alphabetical: false,
|
||||
selected: params.get("style").and_then(Value::as_str).unwrap_or_default().to_string(),
|
||||
selected,
|
||||
styles: Vec::new(),
|
||||
preview: None,
|
||||
made: 0,
|
||||
|
||||
@@ -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);
|
||||
@@ -1892,6 +1892,81 @@ fn word_count_shows_label_and_count_on_a_line_over_close_and_cancel() {
|
||||
assert!(!is_open(h.state(), "wordCount"), "Cancel closes Word Count");
|
||||
}
|
||||
|
||||
/// Reopening Word Count preserves the "Count words in text boxes and notes" setting.
|
||||
#[test]
|
||||
fn word_count_keeps_include_text_boxes_setting_across_reopens() {
|
||||
use egui::accesskit::{Role, Toggled};
|
||||
let mut app = app_with("one two three ");
|
||||
let _ = app.run("insert.textBox", json!({"text": "four five six seven"}));
|
||||
let mut h = app_harness(app);
|
||||
h.run_steps(2);
|
||||
|
||||
let box_label = "Count words in text boxes and notes";
|
||||
let box_toggled = |h: &egui_kittest::Harness<'_, WordApp>| h.get_by_role_and_label(Role::CheckBox, box_label).accesskit_node().toggled();
|
||||
let word_count_is = |h: &egui_kittest::Harness<'_, WordApp>, expected: &str| {
|
||||
let words_rect = h.get_by_label("Words").rect();
|
||||
h.query_all_by_label(expected).any(|n| (n.rect().center().y - words_rect.center().y).abs() < 1.0)
|
||||
};
|
||||
|
||||
super::open(h.state_mut(), "wordCount", &json!({})).expect("word count opens");
|
||||
h.run_steps(3);
|
||||
assert_eq!(box_toggled(&h), Some(Toggled::True));
|
||||
assert!(word_count_is(&h, "7"), "counts text boxes on first open");
|
||||
|
||||
h.get_by_role_and_label(Role::CheckBox, box_label).click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(box_toggled(&h), Some(Toggled::False));
|
||||
assert!(!h.state().session.prefs.count_notes);
|
||||
assert!(word_count_is(&h, "3"), "excludes text boxes after unticking");
|
||||
|
||||
h.get_by_role_and_label(Role::Button, "Cancel").click();
|
||||
h.run_steps(3);
|
||||
assert!(!is_open(h.state(), "wordCount"));
|
||||
assert!(!h.state().session.prefs.count_notes);
|
||||
|
||||
super::open(h.state_mut(), "wordCount", &json!({})).expect("word count reopens");
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().session.prefs.count_notes, "reopening must not turn count_notes back on");
|
||||
assert_eq!(box_toggled(&h), Some(Toggled::False), "checkbox stays unticked across reopens");
|
||||
assert!(word_count_is(&h, "3"), "reopened count still excludes text boxes");
|
||||
}
|
||||
|
||||
/// #8139: while Word Count is open, automation changes to `includeTextBoxes` stay in effect
|
||||
/// and update the dialog instead of being overwritten by the dialog's own checkbox copy.
|
||||
#[test]
|
||||
fn word_count_dialog_follows_automation_and_user_toggles() {
|
||||
use egui::accesskit::{Role, Toggled};
|
||||
let mut app = app_with("one two three ");
|
||||
let _ = app.run("insert.textBox", json!({"text": "four five six seven"}));
|
||||
let mut h = app_harness(app);
|
||||
h.run_steps(2);
|
||||
|
||||
let box_label = "Count words in text boxes and notes";
|
||||
let box_toggled = |h: &egui_kittest::Harness<'_, WordApp>| h.get_by_role_and_label(Role::CheckBox, box_label).accesskit_node().toggled();
|
||||
let word_count_is = |h: &egui_kittest::Harness<'_, WordApp>, expected: &str| {
|
||||
let words_rect = h.get_by_label("Words").rect();
|
||||
h.query_all_by_label(expected).any(|n| (n.rect().center().y - words_rect.center().y).abs() < 1.0)
|
||||
};
|
||||
|
||||
super::open(h.state_mut(), "wordCount", &json!({})).expect("word count opens");
|
||||
h.run_steps(3);
|
||||
assert!(h.state().session.prefs.count_notes);
|
||||
assert_eq!(box_toggled(&h), Some(Toggled::True));
|
||||
assert!(word_count_is(&h, "7"));
|
||||
|
||||
h.state_mut().run("review.wordCount", json!({"includeTextBoxes": false})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().session.prefs.count_notes, "open dialog must not overwrite automation change");
|
||||
assert_eq!(box_toggled(&h), Some(Toggled::False), "checkbox clears to reflect automation change");
|
||||
assert!(word_count_is(&h, "3"), "count updates to exclude text boxes");
|
||||
|
||||
h.get_by_role_and_label(Role::CheckBox, box_label).click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().session.prefs.count_notes, "user toggle updates preference");
|
||||
assert_eq!(box_toggled(&h), Some(Toggled::True));
|
||||
assert!(word_count_is(&h, "7"), "count updates to include text boxes");
|
||||
}
|
||||
|
||||
/// #1885: the close control is at the title bar's right end; a click in the close box
|
||||
/// closes the dialog; one just under the title bar leaves it open; a drag that starts on the box
|
||||
/// doesn't move the dialog.
|
||||
@@ -2340,6 +2415,18 @@ fn dialog_previews_are_drawn_larger_than_a_control() {
|
||||
);
|
||||
}
|
||||
}
|
||||
/// #7977: Borders and Shading draws its edge preview at sample size, not as a thumbnail.
|
||||
#[test]
|
||||
fn borders_preview_is_larger_than_a_thumbnail() {
|
||||
use egui::accesskit::Role;
|
||||
let mut h = app_harness(app_with("Lanterns"));
|
||||
h.state_mut().run("ui.dialog", json!({"name": "borders"})).unwrap();
|
||||
h.run_steps(6);
|
||||
let preview = h.get_by_role_and_label(Role::Group, "Preview").rect();
|
||||
let button = h.get_by_role_and_label(Role::Button, "Cancel").rect();
|
||||
assert!(preview.height() > 2.0 * button.height(), "the preview is {}pt high beside a {}pt button", preview.height(), button.height());
|
||||
}
|
||||
|
||||
/// #7982: Custom Properties' hint wraps inside the dialog instead of running under the Cancel button.
|
||||
#[test]
|
||||
fn custom_properties_hint_does_not_run_under_the_buttons() {
|
||||
@@ -2492,3 +2579,33 @@ fn the_ribbon_customizer_lists_are_framed() {
|
||||
h.run_steps(3);
|
||||
assert_framed(&h, "Quick Access Toolbar");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Manage Styles
|
||||
|
||||
/// Manage Styles opens on the paragraph style at the caret when no explicit `style` parameter is given,
|
||||
/// and honors an explicit `params["style"]` when provided.
|
||||
#[test]
|
||||
fn manage_styles_opens_on_caret_style() {
|
||||
let mut app = app_with("Title line\nBody line");
|
||||
app.run("para.style", json!({"style": "Heading2"})).unwrap();
|
||||
let list = wordcraft_engine::cmd::para::manage_list(&app.session, false);
|
||||
let first_id = list.as_array().and_then(|a| a.first()).and_then(|v| v.get("id")).and_then(Json::as_str).unwrap_or_default();
|
||||
assert_ne!(first_id, "Heading2", "Heading2 must not be the first style so the test checks caret selection");
|
||||
|
||||
let mut h = app_harness(app);
|
||||
h.run_steps(2);
|
||||
let _ = h.state_mut().run("styles.manage", json!({}));
|
||||
h.run_steps(3);
|
||||
assert!(is_open(h.state(), "manageStyles"), "styles.manage opens Manage Styles");
|
||||
assert_eq!(fields_of(h.state(), "manageStyles")["selected"], "Heading2", "Manage Styles starts on the caret's style");
|
||||
assert!(!h.get_by_label("New Style…").accesskit_node().is_disabled());
|
||||
assert!(
|
||||
h.query_all(egui_kittest::kittest::By::new()).any(|n| n.accesskit_node().label().is_some_and(|l| l.contains("Based on: Normal"))),
|
||||
"the dialog body renders the selected Heading 2 style's description"
|
||||
);
|
||||
let manage_id = id_of(h.state(), "manageStyles");
|
||||
cancel(&mut h, manage_id);
|
||||
|
||||
open_named(&mut h, "manageStyles", json!({"style": "Heading1"}));
|
||||
assert_eq!(fields_of(h.state(), "manageStyles")["selected"], "Heading1", "explicit style param still overrides caret style");
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ impl WordApp {
|
||||
self.info_editing = None;
|
||||
// Caches keyed by the revision alone: another document's revision can be the same number.
|
||||
self.status_counts = crate::window_ui::NOT_COUNTED;
|
||||
self.chrome.status_words = None;
|
||||
self.previews.document_changed();
|
||||
// The Start screen's placeholder (#1129) goes once a document is open beside it.
|
||||
if let Some(placeholder) = self.no_document
|
||||
@@ -340,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()));
|
||||
|
||||
@@ -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),
|
||||
];
|
||||
|
||||
|
||||
@@ -347,8 +347,13 @@ static WORDCRAFT_ICONS_TABLE: &[(&str, &[u8])] = &[
|
||||
];
|
||||
|
||||
/// The app icon set. Every document is drawn with the pen width 1.25 of the 20-unit view box,
|
||||
/// which the framework scales to its own stroke.
|
||||
pub static WORDCRAFT_ICONS: AppIcons = AppIcons::new("wordcraft", Some(1.25), WORDCRAFT_ICONS_TABLE);
|
||||
/// which the framework scales to its own stroke. The Format Painter's yellow bar is a fill drawn
|
||||
/// under the icon, so its outline keeps its full stroke instead of the fixed layer covering it.
|
||||
pub static WORDCRAFT_ICONS: AppIcons = AppIcons::new("wordcraft", Some(1.25), WORDCRAFT_ICONS_TABLE).with_fills(&[(
|
||||
"painter",
|
||||
include_bytes!("../icons/painter-fill.svg"),
|
||||
[0xF2, 0xC8, 0x11, 0xFF],
|
||||
)]);
|
||||
|
||||
/// Registers the app icon set beside the framework's catalog; runs before the first pass.
|
||||
pub fn register() {
|
||||
@@ -624,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);
|
||||
});
|
||||
|
||||
@@ -407,6 +407,8 @@ pub struct WordApp {
|
||||
pub(crate) command_states_cache: Option<app::command_board::CommandStatesCache>,
|
||||
/// Cached keytip control lists and reserved shortcut letters per registry and active ribbon tab.
|
||||
pub(crate) keytip_cache: Option<keytips::KeytipCache>,
|
||||
/// The command search's entries and index, per registry and interface language ([`chrome::search::SearchCache`]).
|
||||
pub(crate) search_cache: Option<chrome::search::SearchCache>,
|
||||
/// Frames drawn so far, counted to 2: the control channel's queued requests wait until the
|
||||
/// fonts are warm.
|
||||
pub(crate) fonts_frames: u8,
|
||||
|
||||
@@ -155,7 +155,7 @@ pub fn context_menu_visible(app: &WordApp) -> bool {
|
||||
/// command while the pointer rests on it; the context menu's copy of the bar (which calls this
|
||||
/// from `canvas/context_menu.rs`) previews nothing.
|
||||
pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
|
||||
let st: Value = wordcraft_engine::cmd::format::state(&app.session);
|
||||
let st = wordcraft_engine::cmd::format::cached_state(&app.session);
|
||||
let flag = |k: &str| match st.get(k) {
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::String(s)) => !s.is_empty() && s != "none",
|
||||
@@ -232,11 +232,12 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
|
||||
let _ = Divider::vertical().show(ui);
|
||||
|
||||
let hl = crate::colors::highlight_split(ui, app, tl!("Text Highlight Color").to_string());
|
||||
follow_list(app, preview, &hl.preview, |c| {
|
||||
wordcraft_doc::props::Highlight::ALL
|
||||
follow_list(app, preview, &hl.preview, |c| match c {
|
||||
Some(c) => wordcraft_doc::props::Highlight::ALL
|
||||
.iter()
|
||||
.find(|h| h.rgb().as_ref() == Some(c))
|
||||
.map(|h| ("format.highlight".to_string(), json!({"color": h.ooxml()})))
|
||||
.map(|h| ("format.highlight".to_string(), json!({"color": h.ooxml()}))),
|
||||
None => Some(("format.highlight".to_string(), json!({"color": "none"}))),
|
||||
});
|
||||
// PLAN: assumed ColorPick::hover (ribbon-w11, S-L413)
|
||||
let color = app.canvas.last_highlight.clone();
|
||||
@@ -250,7 +251,13 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
|
||||
tl!("Font Color").to_string(),
|
||||
Target::cmd("format.color").remember(Remember::FontColor),
|
||||
);
|
||||
follow_list(app, preview, &fc.preview, |c| Some(("format.color".to_string(), json!({"color": c.hex()}))));
|
||||
follow_list(app, preview, &fc.preview, |c| {
|
||||
let color = match c {
|
||||
Some(c) => c.hex(),
|
||||
None => "auto".to_string(),
|
||||
};
|
||||
Some(("format.color".to_string(), json!({"color": color})))
|
||||
});
|
||||
// PLAN: assumed ColorPick::hover (ribbon-w11, S-L413)
|
||||
let color = app.canvas.last_font_color.clone();
|
||||
preview_on_hover(app, fc.hover, fc.response.enabled(), "format.color", json!({"color": color}), preview);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -848,3 +849,134 @@ fn the_anchor_spans_every_run_on_the_topmost_line() {
|
||||
let l = visible_anchor(rects, clip, false).unwrap();
|
||||
assert!(l.min.x == line1[0].min.x && l.max.x < a.max.x, "LTR anchor is the top run only: {l:?}");
|
||||
}
|
||||
|
||||
/// Automatic in Font Color and No Color in Text Highlight Color mark the current choice when active.
|
||||
#[test]
|
||||
fn automatic_and_no_color_mark_the_current_choice() {
|
||||
use egui::accesskit::Toggled;
|
||||
|
||||
let mut h = bar_over("brown fox");
|
||||
|
||||
let arrow = split_arrow(&h, "Font Color");
|
||||
click_at(&mut h, arrow.center());
|
||||
let auto = h.get_by_label("Automatic");
|
||||
assert_eq!(auto.accesskit_node().role(), Role::MenuItemCheckBox);
|
||||
assert_eq!(auto.accesskit_node().toggled(), Some(Toggled::True), "Automatic is checked by default");
|
||||
h.key_press(egui::Key::Escape);
|
||||
steps(&mut h);
|
||||
|
||||
h.state_mut().run("format.color", json!({"color": "FF0000"})).unwrap();
|
||||
steps(&mut h);
|
||||
let arrow = split_arrow(&h, "Font Color");
|
||||
click_at(&mut h, arrow.center());
|
||||
assert_eq!(h.get_by_label("Automatic").accesskit_node().toggled(), Some(Toggled::False), "Automatic is unchecked after a colour pick");
|
||||
h.key_press(egui::Key::Escape);
|
||||
steps(&mut h);
|
||||
|
||||
let arrow = split_arrow(&h, "Text Highlight Color");
|
||||
click_at(&mut h, arrow.center());
|
||||
let no_color = h.get_by_label("No Color");
|
||||
assert_eq!(no_color.accesskit_node().role(), Role::MenuItemCheckBox);
|
||||
assert_eq!(no_color.accesskit_node().toggled(), Some(Toggled::True), "No Color is checked when no highlight is applied");
|
||||
h.key_press(egui::Key::Escape);
|
||||
steps(&mut h);
|
||||
|
||||
h.state_mut().run("format.highlight", json!({"color": "yellow"})).unwrap();
|
||||
steps(&mut h);
|
||||
let arrow = split_arrow(&h, "Text Highlight Color");
|
||||
click_at(&mut h, arrow.center());
|
||||
assert_eq!(h.get_by_label("No Color").accesskit_node().toggled(), Some(Toggled::False), "No Color is unchecked after highlighting");
|
||||
h.key_press(egui::Key::Escape);
|
||||
steps(&mut h);
|
||||
|
||||
// Mixed selection (partly highlighted): No Color must stay unchecked, not collapse null to "none".
|
||||
h.state_mut().run("select.text", json!({"text": "fox"})).unwrap();
|
||||
h.state_mut().run("format.highlight", json!({"color": "none"})).unwrap();
|
||||
h.state_mut().run("select.text", json!({"text": "brown fox"})).unwrap();
|
||||
steps(&mut h);
|
||||
let arrow = split_arrow(&h, "Text Highlight Color");
|
||||
click_at(&mut h, arrow.center());
|
||||
assert_eq!(
|
||||
h.get_by_label("No Color").accesskit_node().toggled(),
|
||||
Some(Toggled::False),
|
||||
"No Color is unchecked when only part of the selection is highlighted"
|
||||
);
|
||||
h.key_press(egui::Key::Escape);
|
||||
steps(&mut h);
|
||||
|
||||
// Mixed selection (two different highlight colours): No Color must stay unchecked.
|
||||
h.state_mut().run("select.text", json!({"text": "fox"})).unwrap();
|
||||
h.state_mut().run("format.highlight", json!({"color": "cyan"})).unwrap();
|
||||
h.state_mut().run("select.text", json!({"text": "brown fox"})).unwrap();
|
||||
steps(&mut h);
|
||||
let arrow = split_arrow(&h, "Text Highlight Color");
|
||||
click_at(&mut h, arrow.center());
|
||||
assert_eq!(
|
||||
h.get_by_label("No Color").accesskit_node().toggled(),
|
||||
Some(Toggled::False),
|
||||
"No Color is unchecked when selection has two highlight colours"
|
||||
);
|
||||
}
|
||||
|
||||
/// Hovering Automatic in Font Color or No Color in Text Highlight Color on the mini toolbar
|
||||
/// previews removing the formatting and clears the preview when the pointer leaves or closes.
|
||||
#[test]
|
||||
fn automatic_and_no_color_preview_on_hover() {
|
||||
for (button, item_label, swatch_query, setup_cmd, setup_color, preview_cmd, preview_color, swatch_color) in [
|
||||
("Font Color", "Automatic", "#", "format.color", "FF0000", "format.color", "auto", None),
|
||||
("Text Highlight Color", "No Color", "Yellow", "format.highlight", "yellow", "format.highlight", "none", Some("yellow")),
|
||||
] {
|
||||
let mut h = bar_over("brown fox");
|
||||
h.state_mut().run(setup_cmd, json!({"color": setup_color})).unwrap();
|
||||
steps(&mut h);
|
||||
let (doc, sel, rev) = (h.state().session.doc.clone(), h.state().session.sel.clone(), h.state().session.rev());
|
||||
|
||||
let arrow = split_arrow(&h, button);
|
||||
click_at(&mut h, arrow.center());
|
||||
let target = h.get_by_label(item_label).rect().center();
|
||||
hover_at(&mut h, target);
|
||||
|
||||
assert_eq!(
|
||||
h.state().canvas.command_previewed,
|
||||
Some((preview_cmd.to_string(), json!({"color": preview_color}))),
|
||||
"{button} {item_label} hover previews {preview_cmd}({preview_color})"
|
||||
);
|
||||
assert_ne!(crate::canvas::page_doc(h.state()), &doc, "{button} {item_label}: page shows the live preview");
|
||||
assert_eq!((&h.state().session.doc, &h.state().session.sel, h.state().session.rev()), (&doc, &sel, rev));
|
||||
|
||||
// Moving directly from Automatic / No Color to a swatch updates the preview cleanly.
|
||||
let swatch = h.query_all_by_label_contains(swatch_query).next().expect("swatch present");
|
||||
let expected_swatch = swatch_color
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| swatch.accesskit_node().label().unwrap_or_default().trim_start_matches('#').to_string());
|
||||
let swatch_pos = swatch.rect().center();
|
||||
hover_at(&mut h, swatch_pos);
|
||||
assert_eq!(
|
||||
h.state().canvas.command_previewed,
|
||||
Some((preview_cmd.to_string(), json!({"color": expected_swatch}))),
|
||||
"{button} moving to swatch switches preview"
|
||||
);
|
||||
|
||||
// Moving back to Automatic / No Color restores its preview.
|
||||
hover_at(&mut h, target);
|
||||
assert_eq!(
|
||||
h.state().canvas.command_previewed,
|
||||
Some((preview_cmd.to_string(), json!({"color": preview_color}))),
|
||||
"{button} moving back to {item_label} restores preview"
|
||||
);
|
||||
|
||||
hover_at(&mut h, pos2(5.0, 5.0));
|
||||
assert_eq!(h.state().canvas.command_previewed, None, "{button} {item_label}: moving off clears the preview");
|
||||
|
||||
// Closing the menu via Escape while hovering Automatic / No Color also clears the preview.
|
||||
hover_at(&mut h, target);
|
||||
assert_eq!(
|
||||
h.state().canvas.command_previewed,
|
||||
Some((preview_cmd.to_string(), json!({"color": preview_color}))),
|
||||
"{button} {item_label}: hover active before Escape"
|
||||
);
|
||||
h.key_press(egui::Key::Escape);
|
||||
steps(&mut h);
|
||||
assert_eq!(h.state().canvas.command_previewed, None, "{button} {item_label}: Escape clears the preview");
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user