Compare commits

..
Author SHA1 Message Date
skylartaylor 3ffbe57ebe Consume texture deltas in owner-picker test passes 2026-12-03 19:20:09 +01:00
skylartaylor 551463ca51 Deliver cancellation to a superseded PathRow ticket 2026-12-03 18:59:30 +01:00
skylartaylor bd69ff6e73 Pin the frozen private native viewport hook for qualification 2026-12-03 18:51:26 +01:00
skylartaylor c867a329be Merge commit '72ef3083e7e47eea6b314bb50a4269bcf7e67380' into private/wordcraft-windowless-desktop-host 2026-12-03 18:40:45 +01:00
skylartaylor ba68b13b19 Exercise guard Save As with an untitled third document 2026-12-03 18:38:24 +01:00
skylartaylor b0fd8cbfe9 Launch nothing once quit is decided, and let a quit prompt's Save As replace its window's queued pick
A clean quit replayed inside a pump set quit_requested and the same pump could launch a queued dialog; launches now stop once quit is decided. A dirty window that owns the quit prompt could not get its Save As because its own queued, unlaunched pick held the window's slot; that Save As now supersedes exactly such a pick (same window and document, nothing launched or answered), quietly, and everything else stays Busy. No build run.
2026-12-03 18:37:04 +01:00
skylartaylor c6bceddb93 Launch no queued system dialog while a quit waits or asks, except its own Save As
A queued pick could launch in the pass where the dialogs a deferred quit waited for answered. Launches now pause while a quit is deferred or its unsaved-changes guard runs, except the Save As its prompt asks for, and a quit whose dialogs have ended is replayed before the launch loop. No build run.
2026-12-03 18:33:31 +01:00
skylartaylor 5a71494219 Honor a final quit before pumping document pickers 2026-12-03 18:32:29 +01:00
skylartaylor b2adf0f456 Close a retired pick's chooser and Replace question on its window wherever it is retired
Quiescing removed picks without closing the in-app chooser or Replace question they had opened on their window, leaving one on screen that nothing answers. Every retirement now closes exactly those instances first, and give-up refuses while a Replace question shows. No build run.
2026-12-03 18:30:39 +01:00
skylartaylor 255309155b Route PathRow's own picks to the window and dialog that file them in the windowless trial
Compare/Combine, Templates and Add-ins and the Organizer browse through the SDK PathRow, which files its pick on the Env host's file service and keeps the ticket in its row, bypassing ask_file. In the windowless trial the frame host now carries an app-owned Files wrapper (file_dialogs/path_rows.rs) over the app's own host.

A pick is bound when it is filed. It binds to the drawn window's draw scope: logical window, its document, and the exact native window (viewport, mount attempt, incarnation) from the injected lookup. It also binds to the dialog opening running it: overlay::running_dialog, at that opening's serial, read right before the window's dialog run. Every dialog the run shows is open before it starts. A pick from a dialog that cannot be told apart opens nothing.

Staged picks join the owned route through push_owned_pick, the one admission point, after the owner's drawing. The admission rechecks the window, document, native window and opening first. The system dialog launches only on the pinned native window under its lease, one pick per window.

The settled answer is posted under the row's exact ticket. It is read only from a drawing of the same window, document, native window and dialog opening; a row reading it after a detach, recreation or reopen gets nothing. A pick whose window, document, native window or opening goes first is cancelled and posts nothing. Undelivered answers are pruned and bounded per window. A pick filed outside any window's drawing answers Cancelled and opens nothing. Every other file-service call forwards to the app's host, and outside the trial the frame host is unchanged.

Only rustfmt ran; no build or test run here.
2026-12-03 18:29:54 +01:00
skylartaylor daa74a4fda Count admission across the whole pass, defer File Close before its prompt, never cancel a launched system dialog, and quiesce picks at exit
Admission walks the picks in place so the bound of two counts every live and settling dialog. User File Close and every quit path (including the updater) defer before any Save Changes prompt; a deferred close keeps the document it was for. Cancelled picks no longer forget a launched dialog: it finishes as the user answers it, its answer is dropped and its parent lease is held until then, and retired dialogs keep their window for close deferral. quiesce_native_file_panels stops admission and launches at exit and drops unlaunched picks unpumped while launched ones drain. No build run.
2026-12-03 18:29:54 +01:00
skylartaylor ec687a6876 Rename the owner-document predicate so it does not clash with window_shows 2026-12-03 18:29:54 +01:00
skylartaylor 1e2e0cf217 Quiesce windowless picker launches before root shutdown 2026-12-03 18:23:59 +01:00
skylartaylor ba01027379 Pin windowless picks to their exact native window and wait for system dialogs before close and quit
Address ROUTER-REVIEW: an injected read-only NativeWindowLookup pins an attached owner at the gesture (a mounting owner binds once, on its first attachment) and the pin is checked again at every pump and at answer consumption. Native admission is bounded at two operations counting cancelled ones that are still settling; retiring schedules its first drain. Quit and an owner window's Close or File Close are recorded while a system dialog may still use a window, and replayed once through the usual guards. Cancelled Picture and Recipients picks clear only their own window's pending state. Tests reworked; no build run.
2026-12-03 18:20:13 +01:00
skylartaylor 61953d5fa9 Expose exact document attachment identity to picker ownership 2026-12-03 18:17:17 +01:00
skylartaylor ae35ca4fd8 Lease exact native picker parent windows in the desktop host 2026-12-03 18:08:53 +01:00
skylartaylor c7d2d85a86 Start WordCraft windowless by default, with one windowed fallback
The windowless root is now the default. WORDCRAFT_WINDOWLESS_TRIAL=0
(exactly 0) rolls back to a windowed root.

A start that winit will open on X11 or XWayland (forced by the existing
display-server policy, or unforced with no Wayland display) starts
windowed and is never retried. Otherwise, when eframe's windowless
bootstrap returns UnsupportedConfiguration before the app creator has
taken the one-shot startup inputs, the app starts once more with normal
windowed options and hooks. That retry reuses the thread's cached event
loop (run_and_return). Every other error, a second refusal, and any
error after the creator started are returned unchanged.

Not compiled or run here: the focused test build was stopped for host
load and is waiting for admission through the managed lane.
2026-12-03 18:07:11 +01:00
skylartaylor 7c74a5fa93 Bind windowless file picks to their window and launch system dialogs on its live native window
Every windowless-trial pick (Save As, close Save As, template, Export, Print to PDF, Open, Picture, Recipients, Font, Sources) is bound at ask time to the asking window and its document, in an app-wide list that window swaps do not move. A private file service per pick launches the system dialog only with that window's exact live native window (viewport, mount attempt, host incarnation) as parent, and holds a parent lease until the panel answers or its forgotten panel settles. The in-app chooser is used when preferred, when the panel reports Unavailable, when the host has no window lookup, or after a bounded number of scheduled passes with the native window missing. Stale owners cancel only their own pick; quit waits for open system dialogs. No build run here.
2026-12-03 18:04:42 +01:00
skylartaylor 89e336f645 Keep trial chooser history app-wide during window swaps 2026-12-03 17:44:15 +01:00
skylartaylor 18c7cfd8d6 Trial the qualified fallible document window SDK privately 2026-12-03 17:25:44 +01:00
skylartaylor 8670496a46 Merge commit 'c013dff3326543595d6b679be83901d1739720b7' into private/wordcraft-windowless-four-fixes 2026-12-03 17:25:12 +01:00
skylartaylor 2895ab88d4 Cancel only the parked document’s Save As chooser 2026-12-03 17:25:12 +01:00
skylartaylor 5288ef3255 Dispose texture output in the rejection test renderer 2026-12-03 17:24:55 +01:00
skylartaylor 8527081bc2 Keep WordCraft open when a trial document surface is rejected
Use the additive fallible DocumentWindow mount in the windowless trial and preserve the ordinary mount. Park rejected declarations, retain their drafts, and leave the survivor available until an inaccessible draft can be reopened.
2026-12-03 17:24:55 +01:00
skylartaylor 342931078a Expose close guard cancellation to viewport recovery 2026-12-03 17:10:04 +01:00
skylartaylor 6c47d77c19 Cancel Save As when its windowless surface is rejected 2026-12-03 17:09:37 +01:00
skylartaylor 0eed1a0d15 Track the exact windowless Save As Replace opening 2026-12-03 17:09:17 +01:00
skylartaylor 820742d5dc Scope windowless Save As to its document chooser 2026-12-03 17:05:48 +01:00
skylartaylor 5cc4702ca8 Fix file intake for windowless document drops 2026-12-03 16:52:17 +01:00
skylartaylor 1f73bb9486 Require a registered windowless target for automation effects 2026-12-03 16:49:37 +01:00
skylartaylor 017af2f3f9 Pin the landed windowless egui and winit revisions 2026-12-03 16:15:05 +01:00
skylartaylor 72afcbd32d Stage WordCraft windowless adoption pending landed dependencies 2026-12-03 16:14:12 +01:00
188 changed files with 4754 additions and 8641 deletions
Generated
+131 -146
View File
File diff suppressed because it is too large Load Diff
+55 -55
View File
@@ -13,7 +13,7 @@ run_slots = 3
test_threads = 4
[workspace.package]
version = "0.20.1"
version = "0.18.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -37,22 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
# store's `language-pack` kind is #486 (CP4.1).
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
wordcraft-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 = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -75,7 +75,7 @@ regex-automata = { version = "0.4", default-features = false, features = ["std",
# text / rendering / formats
skrifa = "0.47"
harfrust = "0.15"
harfrust = "0.13"
# WOFF / WOFF2 web fonts added by the user (#582): pure Rust (MIT); its brotli and zlib decoders
# (brotli-decompressor, flate2) are already in the tree.
wuff = "0.2.9"
@@ -85,28 +85,28 @@ wuff = "0.2.9"
brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false, features = ["write"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
miniz_oxide = "0.9"
cfb = "0.15"
@@ -174,27 +174,27 @@ debug = 0
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
# and the egui and winit forks it builds with.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
-3
View File
@@ -386,12 +386,9 @@ emerge --ask app-office/wordcraft-bin
### FreeBSD
Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds.
| Build | File |
|---|---|
| x86_64 | `wordcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 | `wordcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
+1 -4
View File
File diff suppressed because one or more lines are too long
+6 -18
View File
@@ -563,17 +563,6 @@ fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option
(from_file, from_template)
}
/// Show a successful command's result, or its warning when results aren't printed.
fn report_run_result(id: &str, result: &Value, print: bool) -> Result<(), Failure> {
if print {
return write_stdout(|o| writeln!(o, "{id}: {result}"));
}
if let Some(warning) = result.get("warning").and_then(Value::as_str) {
let _ = writeln!(std::io::stderr().lock(), "wordcraft-cli: warning: {}", escape_text(warning, false));
}
Ok(())
}
/// Run the subcommand named by `args` (the command line after the program name). Files named
/// there are opened by their real names, which may not be valid Unicode.
fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
@@ -677,7 +666,9 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
let print = rest.iter().any(|a| a == "--print");
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
report_run_result(id, &r, print)?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
}
let mut i = 0;
while i < rest.len() {
@@ -690,7 +681,9 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
None => (spec.clone(), json!({})),
};
let r = s.run(&id, &params).map_err(|e| engine_error(format!("{id}: {e}")))?;
report_run_result(&id, &r, print)?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
i += 2;
} else {
i += 1;
@@ -1070,11 +1063,6 @@ fn main() -> ExitCode {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
return ExitCode::from(2);
}
// The engine logs this, but the command line installs no logger, and it is where a
// reproducible build runs.
if let Some(problem) = wordcraft_engine::cmd::source_date_epoch_problem() {
eprintln!("wordcraft-cli: warning: {problem}");
}
// Language packs installed in the suite's font store are used; `proof.installPack` installs
// only while the person has turned downloading on in the app.
wordcraft_engine::packs::use_font_store(false);
-64
View File
@@ -710,70 +710,6 @@ fn script_reads_from_a_stream_and_caps_its_size() {
assert!(script::load_from(&b"{"[..], "-", None).is_err());
}
#[test]
fn run_result_warnings_use_stderr_without_print() {
use std::process::Command;
const CHILD_ARGS: &str = "WORDCRAFT_CLI_WARNING_TEST_ARGS";
const STORE: &str = "WORDCRAFT_CLI_WARNING_TEST_STORE";
const WARNING: &str = "added for this session only: couldn't store it";
if let Ok(argv) = std::env::var(CHILD_ARGS) {
let store = PathBuf::from(std::env::var_os(STORE).unwrap());
wordcraft_fonts::FontDb::global().load_user_fonts(&store);
run(&serde_json::from_str::<Vec<String>>(&argv).unwrap()).unwrap();
// Bypass the test harness summary so the parent sees only the same header and the CLI's
// output. Each child has its own font database and never configures a real user store.
std::process::exit(0);
}
let dir = script_dir("run-warnings");
let store = dir.join("not-a-directory");
std::fs::write(&store, b"blocked font store").unwrap();
// Like the engine's font.add fixture, rename the bundled JetBrains Mono family in memory
// so it is treated as a new face. No additional font asset is used.
let mut font = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec();
let utf16 = |name: &str| name.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (old, new) in [(b"JetBrains Mono".to_vec(), b"Cli Fixture 42".to_vec()), (utf16("JetBrains Mono"), utf16("Cli Fixture 42"))] {
let mut start = 0;
while let Some(at) = font[start..].windows(old.len()).position(|bytes| bytes == old) {
let range = start + at..start + at + old.len();
start = range.end;
font[range].copy_from_slice(&new);
}
}
let path = dir.join("fixture.ttf");
std::fs::write(&path, font).unwrap();
let params = json!({"path": path.to_string_lossy()});
let spec = format!("font.add={params}");
let script = write_script(&dir, &json!({"commands": [{"command": "font.add", "params": params}]}).to_string());
let child = |argv: &[&str]| {
let out = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::run_result_warnings_use_stderr_without_print", "--nocapture"])
.env(CHILD_ARGS, json!(argv).to_string())
.env(STORE, &store)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
(String::from_utf8(out.stdout).unwrap(), String::from_utf8(out.stderr).unwrap())
};
let (header, quiet_stderr) = child(&["run", "--cmd", "caret.docEnd"]);
assert!(quiet_stderr.is_empty(), "{quiet_stderr}");
for argv in [["run", "--cmd", &spec], ["run", "--script", &script]] {
let (stdout, stderr) = child(&argv);
assert_eq!(stdout, header);
assert!(stderr.starts_with(&format!("wordcraft-cli: warning: {WARNING}")), "{stderr}");
assert_eq!(stderr.lines().count(), 1, "{stderr}");
let (stdout, stderr) = child(&[argv[0], argv[1], argv[2], "--print"]);
assert!(stderr.is_empty(), "{stderr}");
let result = stdout.strip_prefix(&header).unwrap().strip_prefix("font.add: ").unwrap();
let result: Value = serde_json::from_str(result).unwrap();
let warning = result["warning"].as_str().unwrap();
assert!(warning.starts_with(WARNING), "{result}");
}
}
#[test]
fn script_commands_run_before_cmd_flags() {
let dir = script_dir("order");
-24
View File
@@ -37,27 +37,3 @@ fn run_saves_the_document_opened_last() {
let stdout = String::from_utf8_lossy(&listed.stdout);
assert_eq!(stdout.matches("\"id\"").count(), 1, "{stdout}");
}
struct TempFile(std::path::PathBuf);
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn failed_run_commands_still_exit_with_an_error() {
let script = TempFile(std::env::temp_dir().join(format!("wordcraft-cli-run-error-{}.json", std::process::id())));
std::fs::write(&script.0, r#"{"commands":["no.such.command"]}"#).unwrap();
let script_path = script.0.to_string_lossy();
let cases = [(["run", "--cmd", "no.such.command"], "no.such.command:"), (["run", "--script", &script_path], "command 1 (no.such.command):")];
for (args, expected) in cases {
let out = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.starts_with("wordcraft-cli: ") && stderr.contains(expected), "{stderr}");
assert!(!stderr.contains("wordcraft-cli: warning:"), "{stderr}");
}
}
@@ -1,127 +0,0 @@
//! Direct PDF exports use the saved timestamp without changing the source document.
use std::process::Command;
#[test]
fn direct_pdf_exports_use_the_pinned_epoch() {
check_creation_date("", "20261005140300");
}
#[test]
fn direct_pdf_exports_preserve_an_existing_creation_date() {
check_creation_date("2000-01-01T00:00:00Z", "20000101000000");
}
/// A .docx records `dcterms:created` as text and the reader takes it as it finds it, so a
/// document can arrive holding something that is not a date at all. The PDF writer cannot put
/// that in a document and fell back to the clock, so two exports of the same file differed even
/// with `SOURCE_DATE_EPOCH` set -- the one thing it is there to stop (noted in review).
#[test]
fn direct_pdf_exports_use_the_pinned_epoch_when_the_existing_date_is_unreadable() {
for created in ["not-a-date", "", " ", "2000-13-01T00:00:00Z", "2000-01-32T00:00:00Z", "99-01-01", "today"] {
check_creation_date(created, "20261005140300");
}
}
fn check_creation_date(created: &str, expected: &str) {
// A sequence number, not the clock alone: `as_nanos` carries microsecond granularity on
// macOS, so two of these tests starting in the same microsecond took the same directory,
// wrote each other's `input.json` and failed the preservation assertion below -- a flake in
// this harness, not in the export. `create_dir` rather than `create_dir_all` so that if a
// name ever does repeat it fails here instead of quietly sharing a directory again.
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("wordcraft-pdf-date-{}-{unique}-{seq}", std::process::id()));
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
let mut doc = wordcraft_doc::Document::from_text("Original reproducible PDF check.");
doc.core.created = created.into();
let input = dir.join("input.json");
let source = serde_json::to_vec(&doc).unwrap();
std::fs::write(&input, &source).unwrap();
for command in ["file.exportPdf", "file.printPdf"] {
let output = dir.join(format!("{command}.pdf"));
let params = serde_json::json!({"path": output});
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
.arg("run")
.arg("--file")
.arg(&input)
.arg("--cmd")
.arg(format!("{command}={params}"))
.env("SOURCE_DATE_EPOCH", "1791208980")
.output()
.unwrap();
assert!(run.status.success(), "{command}: {}", String::from_utf8_lossy(&run.stderr));
let bytes = std::fs::read(output).unwrap();
let date = format!("/CreationDate(D:{expected}");
assert!(bytes.windows(date.len()).any(|part| part == date.as_bytes()), "{command} must use {expected}");
assert_eq!(std::fs::read(&input).unwrap(), source, "export must preserve its source file");
}
}
/// A fresh directory for one test's files.
fn scratch(name: &str) -> std::path::PathBuf {
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("wordcraft-{name}-{}-{unique}", std::process::id()));
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
dir
}
fn cli(env: &str, cmds: &[String]) -> std::process::Output {
let mut run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
run.arg("run").env("SOURCE_DATE_EPOCH", env);
for c in cmds {
run.arg("--cmd").arg(c);
}
run.output().unwrap()
}
/// The pinned date is the file's, not the edits': a comment and a tracked change made in the
/// same run keep the time they were made, so a pinned epoch cannot back-date them (noted in
/// review). Saved as flat XML, which holds both in plain text.
#[test]
fn a_pinned_epoch_dates_the_file_and_not_the_edits_in_it() {
let out = scratch("pinned-edits").join("edits.xml");
let before = wordcraft_engine::cmd::now_iso();
let run = cli(
"1791208980",
&[
r#"review.trackChanges={"value": true}"#.to_string(),
r#"text.insert={"text": "tracked"}"#.to_string(),
r#"review.newComment={"text": "note"}"#.to_string(),
format!("file.saveAs={}", serde_json::json!({"path": out})),
],
);
let after = wordcraft_engine::cmd::now_iso();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let xml = std::fs::read_to_string(&out).unwrap();
assert!(xml.contains(r#"<dcterms:modified xsi:type="dcterms:W3CDTF">2026-10-05T14:03:00Z</dcterms:modified>"#), "the file's date is pinned");
let dates: Vec<&str> = xml.split(r#"w:date=""#).skip(1).filter_map(|rest| rest.split('"').next()).collect();
assert!(xml.contains("<w:ins ") && xml.contains("<w:comment "), "a tracked insertion and a comment were saved");
assert!(dates.len() >= 2, "both carry a date: {dates:?}");
for date in dates {
assert!((before.as_str()..=after.as_str()).contains(&date), "{date} is the clock's, between {before} and {after}");
}
}
/// A value that is set and cannot be used is said out loud, and the run still succeeds: the
/// files take the clock's date, as they would with the variable unset (noted in review).
#[test]
fn an_unusable_epoch_is_reported_on_stderr() {
let dir = scratch("epoch-warning");
let save = |name: &str| format!("file.exportPdf={}", serde_json::json!({"path": dir.join(name)}));
let run = cli("later", &[save("later.pdf")]);
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let stderr = String::from_utf8_lossy(&run.stderr);
assert!(stderr.contains(r#"warning: SOURCE_DATE_EPOCH="later" is not a whole number of seconds"#), "{stderr}");
let pdf = std::fs::read(dir.join("later.pdf")).unwrap();
let pinned = b"/CreationDate(D:20261005140300";
assert!(pdf.windows(b"/CreationDate(D:".len()).any(|w| w == b"/CreationDate(D:"), "the export has a creation date");
assert!(!pdf.windows(pinned.len()).any(|w| w == pinned), "and it is the clock's, not a pinned one");
for quiet in ["1791208980", ""] {
let run = cli(quiet, &[save("quiet.pdf")]);
assert!(run.status.success());
assert!(!String::from_utf8_lossy(&run.stderr).contains("SOURCE_DATE_EPOCH"), "{quiet:?} says nothing");
}
}
-1
View File
@@ -27,7 +27,6 @@ const POLL_MS: i32 = 16;
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
let (queue, requests) = channel::<ControlRequest>();
let request: Request = Rc::new(move |method, params| {
let params = super::page_params::control_params(&method, params);
let (control, reply) = ControlRequest::new(method, params);
if queue.send(control).is_err() {
return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) });
-2
View File
@@ -23,8 +23,6 @@ mod prefs;
mod api;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(any(target_arch = "wasm32", test))]
mod page_params;
#[cfg(target_arch = "wasm32")]
mod web;
-55
View File
@@ -1,55 +0,0 @@
use serde_json::Value;
pub(super) fn control_params(method: &str, mut params: Value) -> Value {
// The page helper asks for inline data. A screenshot without a path already returns it.
if method == "ui.screenshot"
&& let Some(fields) = params.as_object_mut()
&& !fields.contains_key("path")
&& fields.get("data") == Some(&Value::Bool(true))
{
fields.remove("data");
}
params
}
#[cfg(test)]
mod tests {
use craft::automation::screenshot::ScreenshotParams;
use serde_json::json;
use super::control_params;
#[test]
fn page_helper_requests_the_same_capture_as_a_direct_request() {
for (helper, direct) in
[(json!({"data": true}), json!({})), (json!({"data": true, "region": [10, 20, 100, 200]}), json!({"region": [10, 20, 100, 200]}))]
{
let params = control_params("ui.screenshot", helper);
assert_eq!(params, direct);
assert!(ScreenshotParams::from_params(&params).is_ok());
}
}
#[test]
fn page_helper_keeps_screenshot_validation() {
for (input, expected) in [
(json!({"data": true, "region": [100, 200, 10, 20]}), json!({"region": [100, 200, 10, 20]})),
(json!({"data": true, "viewport": "other"}), json!({"viewport": "other"})),
(json!({"data": true, "path": "capture.png"}), json!({"data": true, "path": "capture.png"})),
(json!({"data": true, "path": null}), json!({"data": true, "path": null})),
(json!({"data": false}), json!({"data": false})),
(json!({"data": "true"}), json!({"data": "true"})),
] {
let params = control_params("ui.screenshot", input);
assert_eq!(params, expected);
assert!(ScreenshotParams::from_params(&params).is_err());
}
}
#[test]
fn direct_requests_keep_their_parameters() {
for (method, params) in [("ui.screenshot", json!({"path": "capture.png"})), ("file.new", json!({"data": true}))] {
assert_eq!(control_params(method, params.clone()), params);
}
}
}
+4
View File
@@ -74,6 +74,10 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan
x11-dl = "2.21"
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# Name the window supplied by eframe's attachment hook on targets that otherwise use winit indirectly.
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
winit = { version = "0.30", default-features = false }
[target.'cfg(windows)'.dependencies]
# The update helper: a copy of this program started with `--finish-update`
# (`craft::update::self_update::finish`).
+14 -128
View File
@@ -10,7 +10,6 @@ use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use craft::automation::AutomationError;
use craft::automation::args::ControlOptions;
use craft::automation::control::ControlRequest;
use craft::automation::server::{Listening, serve};
@@ -39,22 +38,6 @@ fn remove(path: Option<&Path>) {
}
}
/// Why starting the control server did not succeed.
enum StartError {
/// Windows external-tool timeout while creating or checking the owner-only token file.
TokenTimeout(String),
/// Any other bind, token, or accept-thread error.
Other(String),
}
impl StartError {
fn message(&self) -> &str {
match self {
Self::TokenTimeout(msg) | Self::Other(msg) => msg,
}
}
}
/// Bind `127.0.0.1:port`, settle the token and serve. `None` when the port cannot be bound or
/// the token cannot be set up (the control channel is off); a taken port leaves no token file.
///
@@ -62,49 +45,35 @@ impl StartError {
/// `port` in `settings`; a file left by a run that did not exit cleanly is replaced. Without a
/// settings folder a fresh token is generated and reported by the log.
pub fn start(options: &ControlOptions, port: u16, host: WindowHost, settings: Option<&Path>) -> Option<(Receiver<ControlRequest>, Control)> {
match start_with(options, port, host, settings, ControlOptions::server_token) {
Ok(started) => Some(started),
Err(err) => {
log::error!("{}", err.message());
None
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
return None;
}
}
}
fn start_with(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnOnce(&ControlOptions) -> Result<String, AutomationError>,
) -> Result<(Receiver<ControlRequest>, Control), StartError> {
let listener =
TcpListener::bind(("127.0.0.1", port)).map_err(|e| StartError::Other(format!("control server failed to bind 127.0.0.1:{port}: {e}")))?;
};
let created = settings.filter(|_| options.token.is_none() && options.token_file.is_none()).map(|dir| wordcraft_control_key::key_path(dir, port));
// The port was free, so no other run owns a file left here.
remove(created.as_deref());
let effective = ControlOptions { token_file: created.clone().or_else(|| options.token_file.clone()), ..options.clone() };
let token = match token_for(&effective) {
let token = match effective.server_token() {
Ok(t) => t,
Err(e) => {
remove(created.as_deref());
let msg = format!("control server off: {e}");
return Err(if matches!(&e, AutomationError::Io(text) if text.contains("did not finish within ")) {
StartError::TokenTimeout(msg)
} else {
StartError::Other(msg)
});
log::error!("control server off: {e}");
return None;
}
};
let notice = effective.token_notice(&token);
match serve(listener, token, host) {
Ok((rx, listening)) => {
log::info!("control server listening on {}, {notice}", listening.addr);
Ok((rx, Control { listening, created }))
Some((rx, Control { listening, created }))
}
Err(e) => {
remove(created.as_deref());
Err(StartError::Other(format!("control server off: cannot start the accept thread ({e})")))
log::error!("control server off: cannot start the accept thread ({e})");
None
}
}
}
@@ -118,41 +87,6 @@ mod tests {
WindowHost::of(&egui::Context::default())
}
/// Attempts for `start_with` when Windows `owner_only` hits its 10 s external-tool limit on
/// a busy CI runner (#8556). Non-timeout failures stop on the first attempt.
const TOKEN_TIMEOUT_ATTEMPTS: usize = 3;
fn try_start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
mut token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
let mut attempt = 1;
loop {
match start_with(options, port, host.clone(), settings, &mut token_for) {
Ok(started) => return Ok(started),
Err(StartError::TokenTimeout(msg)) if attempt < TOKEN_TIMEOUT_ATTEMPTS => {
log::warn!("retrying control server start after Windows token-file timeout ({attempt}/{TOKEN_TIMEOUT_ATTEMPTS}): {msg}");
attempt += 1;
}
Err(err) => return Err((attempt, err)),
}
}
}
fn start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
) -> (Receiver<ControlRequest>, Control) {
try_start_retrying_token_timeout(options, port, host, settings, token_for)
.unwrap_or_else(|(attempt, err)| panic!("control server start failed on attempt {attempt}: {}", err.message()))
}
#[test]
fn the_token_file_is_written_after_the_bind_and_removed_on_exit() {
let dir = std::env::temp_dir().join(format!("wordcraft-control-life-{}", std::process::id()));
@@ -167,7 +101,7 @@ mod tests {
drop(taken);
// Bound: the default file holds the token that opens the port.
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
let path = control.created.clone().unwrap();
assert_eq!(path, wordcraft_control_key::key_path(&dir, 0));
let token = std::fs::read_to_string(&path).unwrap();
@@ -183,61 +117,13 @@ mod tests {
// A token file the user supplied stays.
let supplied = dir.join("supplied-token");
let options = ControlOptions { token_file: Some(supplied.clone()), ..ControlOptions::default() };
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
assert!(control.created.is_none());
control.shut_down();
assert!(supplied.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_transient_token_file_timeout_retries_while_other_errors_stop() {
let dir = std::env::temp_dir().join(format!("wordcraft-control-retry-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let options = ControlOptions::default();
// A Windows `owner_only` external-tool timeout retries and recovers on a later attempt.
let mut timeout_then_ok = 0usize;
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), |effective| {
timeout_then_ok += 1;
if timeout_then_ok == 1 {
let path = effective.token_file.as_ref().unwrap();
Err(AutomationError::Io(format!(
"{}: cannot create the control token file for its owner only: powershell.exe did not finish within 10 s and was ended",
path.display()
)))
} else {
Ok(TOKEN.to_string())
}
});
assert_eq!(timeout_then_ok, 2);
control.shut_down();
// Repeated timeouts stop after `TOKEN_TIMEOUT_ATTEMPTS` instead of looping forever.
let mut exhausted = 0usize;
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
exhausted += 1;
Err(AutomationError::Io("powershell.exe did not finish within 10 s and was ended".into()))
}) else {
panic!("exhausted timeouts must fail");
};
assert_eq!((attempt, exhausted), (TOKEN_TIMEOUT_ATTEMPTS, TOKEN_TIMEOUT_ATTEMPTS));
assert!(matches!(err, StartError::TokenTimeout(_)));
// Non-timeout failures stop on the first attempt.
let mut other = 0usize;
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
other += 1;
Err(AutomationError::Io("permission denied".into()))
}) else {
panic!("non-timeout error must fail");
};
assert_eq!((attempt, other), (1, 1));
assert!(matches!(err, StartError::Other(msg) if msg.contains("permission denied")));
let _ = std::fs::remove_dir_all(&dir);
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
+87
View File
@@ -0,0 +1,87 @@
//! Native parent windows for document-owned file pickers in windowless mode.
use std::collections::HashMap;
use std::num::NonZeroU64;
use std::sync::{Arc, Mutex, Weak};
use craft::dialogs::service::FilePanels;
use craft::platform::open::IntakeSender;
use craft::ui::dialog::DialogHost;
use eframe::{ViewportHooks, ViewportWindowKey};
use egui::{Context, RawInput, ViewportId};
use winit::window::Window;
use wordcraft_ui_egui::file_dialogs::{NativeWindowLookup, OwnerPanels, ParentLease};
use crate::drop_intake::ChildDrops;
/// The latest successful attachment for each viewport. The registry does not keep windows alive.
#[derive(Clone, Default)]
pub(crate) struct DocumentWindows(Arc<Mutex<HashMap<ViewportId, (ViewportWindowKey, Weak<Window>)>>>);
impl DocumentWindows {
pub(crate) fn hooks(&self, drops: IntakeSender) -> Arc<dyn ViewportHooks> {
Arc::new(DocumentHooks { windows: self.clone(), drops: ChildDrops(drops) })
}
}
struct DocumentHooks {
windows: DocumentWindows,
drops: ChildDrops,
}
impl ViewportHooks for DocumentHooks {
fn window_attached(&self, key: ViewportWindowKey, window: Weak<Window>) {
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
attached.insert(key.viewport_id(), (key, window));
}
fn window_detached(&self, key: ViewportWindowKey) {
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
if attached.get(&key.viewport_id()).is_some_and(|(current, _)| *current == key) {
attached.remove(&key.viewport_id());
}
}
fn raw_input(&self, ctx: &Context, raw: &mut RawInput) {
self.drops.raw_input(ctx, raw);
}
}
impl NativeWindowLookup for DocumentWindows {
fn incarnation(&self, viewport: ViewportId) -> Option<NonZeroU64> {
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
let (key, weak) = attached.get(&viewport)?;
(weak.strong_count() > 0).then(|| key.incarnation())
}
}
impl OwnerPanels for DocumentWindows {
fn pump_parented(
&mut self,
viewport: ViewportId,
incarnation: NonZeroU64,
panels: &mut FilePanels,
host: &mut DialogHost,
) -> Option<ParentLease> {
// Upgrade only the exact live incarnation, on the event-loop thread. Never hold the
// registry lock across the pump (macOS can enter native dialog code here).
let parent = {
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
let (key, weak) = attached.get(&viewport)?;
if key.incarnation() != incarnation {
return None;
}
weak.upgrade()?
};
panels.pump_with(host, Some(parent.as_ref()));
// rfd can use the copied handles on a later worker callback. The router retains this
// lease through backend completion even if the initiating document detached meanwhile.
Some(ParentLease::new(parent))
}
fn pump_unparented(&mut self, panels: &mut FilePanels, host: &mut DialogHost) {
// The router allows this only for an explicitly in-app request or an already launched
// operation with an empty native queue. It cannot open an unowned system dialog here.
panels.pump_with::<eframe::Frame>(host, None);
}
}
+111
View File
@@ -0,0 +1,111 @@
//! Route desktop drop events to WordCraft's existing file intake.
use std::path::Path;
use std::sync::Arc;
use craft::platform::open::{DroppedFile, IntakeSender};
use eframe::ViewportHooks;
use egui::{Context, RawInput, ViewportId};
/// The ordinary app input hook leaves files in `raw` for the runtime's own reading.
pub(crate) fn forward_app_input(sender: &IntakeSender, raw: &RawInput) {
sender.dropped(
raw.dropped_files
.iter()
.map(|file| {
dropped_path(file.path()).unwrap_or_else(|| DroppedFile { path: None, name: String::new(), bytes: file.bytes().ok().map(Arc::from) })
})
.collect(),
);
}
fn dropped_path(path: &Path) -> Option<DroppedFile> {
if path.as_os_str().is_empty() {
return None;
}
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Some(DroppedFile { path: Some(path.to_path_buf()), name, bytes: None })
}
/// Immediate child input in the windowless trial.
pub(crate) struct ChildDrops(pub(crate) IntakeSender);
impl ViewportHooks for ChildDrops {
fn raw_input(&self, _ctx: &Context, raw: &mut RawInput) {
// Immediate viewports skip App::raw_input_hook. The regular ROOT input still goes there.
// Consume this child batch so no later hook or pass feeds it again. Native OS drops carry
// paths: pass those through without reading the files on the event loop.
if raw.viewport_id != ViewportId::ROOT && !raw.dropped_files.is_empty() {
self.0.dropped(raw.dropped_files.drain(..).filter_map(|file| dropped_path(file.path())).collect());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use craft::host::Wake;
use craft::platform::open::{FileIntake, Intake};
#[derive(Debug)]
struct NativeDrop(PathBuf);
impl egui::DroppedFile for NativeDrop {
fn path(&self) -> &Path {
&self.0
}
fn bytes(&self) -> Result<Vec<u8>, String> {
panic!("the raw-input hook must not read native dropped files");
}
}
fn raw_drops(viewport_id: ViewportId, paths: &[PathBuf]) -> RawInput {
RawInput {
viewport_id,
dropped_files: paths.iter().map(|path| Arc::new(NativeDrop(path.clone())) as egui::DroppedFileHandle).collect(),
..Default::default()
}
}
#[test]
fn child_drop_enters_intake_once_in_drop_order() {
let (intake, sender) = FileIntake::new(Wake::none());
let hooks = ChildDrops(sender.clone());
let ctx = Context::default();
let child = ViewportId::from_hash_of("document");
let paths = [std::env::temp_dir().join("second.docx"), std::env::temp_dir().join("first.docx")];
let mut raw = raw_drops(child, &paths);
// The immediate child goes through the viewport hook, not the App hook.
hooks.raw_input(&ctx, &mut raw);
let batches = intake.take();
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one child drop batch, got {batches:?}") };
assert!(files.iter().map(|file| file.path.as_ref()).eq(paths.iter().map(Some)));
// A replay of this input, or another input path seeing it, cannot send it again.
hooks.raw_input(&ctx, &mut raw);
forward_app_input(&sender, &raw);
assert!(intake.take().is_empty());
}
#[test]
fn root_drop_still_reaches_intake_only_from_app_input() {
let (intake, sender) = FileIntake::new(Wake::none());
let hooks = ChildDrops(sender.clone());
let ctx = Context::default();
let path = std::env::temp_dir().join("document.docx");
let mut raw = raw_drops(ViewportId::ROOT, std::slice::from_ref(&path));
// Pinned eframe calls both hooks on ROOT, in this order.
hooks.raw_input(&ctx, &mut raw);
assert!(intake.take().is_empty());
forward_app_input(&sender, &raw);
let batches = intake.take();
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one root drop batch, got {batches:?}") };
assert!(matches!(files.as_slice(), [file] if file.path.as_ref() == Some(&path)));
assert!(matches!(raw.dropped_files.as_slice(), [file] if file.path() == path.as_path()));
}
}
+107 -169
View File
@@ -19,6 +19,8 @@ mod build_channel;
mod build_flavor;
mod control_server;
mod default_apps;
mod document_panels;
mod drop_intake;
mod launch_profile;
#[cfg(target_os = "macos")]
mod native_menu;
@@ -27,6 +29,7 @@ mod prefs;
mod process_identity;
mod profile_root;
mod region;
mod startup_mode;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock};
@@ -40,12 +43,12 @@ use craft::platform::appearance::SystemReader;
use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard};
use craft::platform::default_app::{DefaultApp, DefaultAppError};
use craft::platform::logs::{self, LogNames, crash};
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
use craft::platform::open::{FileIntake, IntakeSender};
use craft::print::spool::Spool;
use craft::settings::SharedSettings;
use craft::ui::InstallSpec;
use craft::ui::runtime::windows::{WindowAction, WindowHost};
use craft::ui::shell::embed;
use craft::ui::shell::embed::{self, CloseDecision};
use craft::window::restore::{self, Store};
use craft::window::system::SystemWindows;
use wordcraft_engine::Session;
@@ -60,6 +63,8 @@ struct App {
native_menu: Option<craft::menu::NativeMenu>,
/// The native panels behind the file service the app reaches through `Host::files`.
panels: FilePanels,
/// Native parent windows for the owned picker route, populated only in windowless mode.
document_windows: document_panels::DocumentWindows,
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
/// queue the OS's requests are read from.
drops: IntakeSender,
@@ -86,19 +91,35 @@ impl App {
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
// Validate native incarnations before WordApp logic can settle an available answer.
// A final Quit from a previous pass takes priority over launching any new pick.
if self.app.quit_requested {
self.app.quiesce_native_file_panels();
}
self.app.pump_owned_picks(ctx, &mut self.document_windows);
self.app.logic(ctx);
#[cfg(target_os = "macos")]
if let Some(menu) = &mut self.native_menu {
native_menu::update(menu, &mut self.app, ctx);
}
self.panels.pump_with(self.app.dialog_host_mut(), frame);
// A quit that waits for nothing (the documents are answered for) closes the root window.
if self.app.quit_requested && !self.app.printing.busy() {
// Once the document guards have settled Quit, not even this pass's last pump can open
// another picker. Keep the event loop and display alive for handles already in use.
if self.app.quit_requested {
self.app.quiesce_native_file_panels();
}
self.pump_file_panels(ctx, frame);
if self.app.quit_requested && !self.app.printing.busy() && !self.app.native_file_panels_open() {
WindowHost::of(ctx).act(egui::ViewportId::ROOT, WindowAction::Close);
}
// The decision holds the close while a Save Changes prompt is open; a closure over
// `close_requested` would ask again on every frame of the prompt.
embed::logic(ctx, || self.app.close_decision());
// A platform close can be accepted without setting quit_requested (e.g. no unsaved work).
// Shut off new launches only when that final close is accepted, not before a Save prompt.
embed::logic(ctx, || {
let decision = self.app.close_decision();
if matches!(decision, CloseDecision::Close) {
self.app.quiesce_native_file_panels();
}
decision
});
}
/// One pass of the root window's UI.
@@ -107,7 +128,12 @@ impl App {
embed::before_ui(ui.ctx(), frame);
}
self.app.ui(ui);
self.pump_file_panels(ui.ctx(), frame);
}
fn pump_file_panels(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
self.panels.pump_with(self.app.dialog_host_mut(), frame);
self.app.pump_owned_picks(ctx, &mut self.document_windows);
}
/// Everything that must happen before the process ends, whichever way the window closes.
@@ -134,11 +160,7 @@ impl eframe::App for App {
/// Hands the app what the runtime gathered since the last frame (fired commands) and the
/// runtime the input the app gives back, before any pass of the frame runs.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// Once per frame, before any pass; the files stay in `raw` for the runtime's own reading.
let files = dropped_files(raw);
if !files.is_empty() {
self.drops.dropped(files);
}
drop_intake::forward_app_input(&self.drops, raw);
self.before_input(ctx);
}
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
@@ -152,36 +174,6 @@ impl eframe::App for App {
}
}
/// Files dropped on a document window. eframe hands `raw_input_hook` only the root's and deferred
/// viewports' input, and document windows are immediate viewports (every one under the windowless
/// root), so their drops come through this hook. It runs first and takes the batch, so nothing reads
/// it twice.
struct ChildDrops(IntakeSender);
impl eframe::ViewportHooks for ChildDrops {
fn raw_input(&self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
if raw.viewport_id != egui::ViewportId::ROOT && !raw.dropped_files.is_empty() {
self.0.dropped(dropped_files(raw));
raw.dropped_files.clear();
}
}
}
/// The files dropped in this frame's input, as the intake carries them: a file with a path by its
/// path, a file without one by its bytes.
fn dropped_files(raw: &egui::RawInput) -> Vec<DroppedFile> {
raw.dropped_files
.iter()
.map(|file| {
let path = Some(file.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty());
let name = path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
// A file without a path (the web) carries its bytes; one that cannot be read is dropped as empty.
let bytes = if path.is_none() { file.bytes().ok().map(std::sync::Arc::from) } else { None };
DroppedFile { path, name, bytes }
})
.collect()
}
/// Whether the window runs through XWayland (X11) rather than native Wayland, and the log line
/// saying why. `WORDCRAFT_WAYLAND` wins (`0`, `false`, `no` or `off` asks for X11, any other value
/// for Wayland), then File › Options › Advanced › Linux display server (#2184). Automatic is X11
@@ -478,46 +470,6 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
}
/// Runs the app with the windowless root when `windowless` is set, and with the visible root when it is not. eframe
/// refuses a windowless root on a session that cannot run it before it calls the creator, which then stays in its
/// cell for a retry with the visible root: the app always starts.
fn run_with_visible_root_fallback(
creator: eframe::AppCreator<'static>,
windowless: Arc<std::sync::atomic::AtomicBool>,
mut options: eframe::NativeOptions,
) -> eframe::Result {
use std::sync::atomic::Ordering::Relaxed;
let creator = std::rc::Rc::new(std::cell::RefCell::new(Some(creator)));
let name = wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity());
let run = |options: eframe::NativeOptions| {
let creator = creator.clone();
eframe::run_native(
name,
options,
Box::new(move |cc| match creator.borrow_mut().take() {
Some(create) => create(cc),
None => Err("the app was already created".into()),
}),
)
};
let on = windowless.load(Relaxed);
// The clone keeps no event-loop hook, which only the X11 start sets and that start is windowed.
let mut visible_root = on.then(|| options.clone());
if on {
options.root_viewport_mode = eframe::RootViewportMode::Windowless;
}
let result = run(options);
if let Err(eframe::Error::UnsupportedConfiguration(reason)) = &result
&& let Some(options) = visible_root.take()
&& creator.borrow().is_some()
{
log::warn!("windowless root unavailable ({reason}); starting with a visible root window");
windowless.store(false, Relaxed);
return run(options);
}
result
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
/// geometry, opens requested documents or the Start screen, starts the control server when
/// asked, and runs the eframe event loop.
@@ -671,25 +623,17 @@ fn main() -> eframe::Result {
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
};
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
.with_app_id(app_id)
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false),
..Default::default()
};
let mut viewport = egui::ViewportBuilder::default()
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
.with_app_id(app_id)
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false);
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
}
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler and
// the GPU that drives the screen (#603, #2652, #5199).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
craft::gpu::configure(setup);
viewport = viewport.with_icon(icon);
}
prefs::load_user_fonts();
// Where the root window was last, kept beside the settings; in memory when preferences are off.
@@ -708,16 +652,18 @@ fn main() -> eframe::Result {
let display_server = settings.lock().get().display_server;
let (x11, why) = uses_x11(display_server, |name| std::env::var_os(name), x11_libraries);
log::info!("{why}");
if x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
x11
};
#[cfg(not(all(unix, not(target_os = "macos"))))]
let x11 = false;
// The windowless root by default; windowed when rolled back, or when winit will open X11 or
// XWayland, which its bootstrap doesn't support (`startup_mode`).
#[cfg(all(unix, not(target_os = "macos")))]
let winit_x11 = startup_mode::winit_picks_x11(x11, |name| std::env::var_os(name));
#[cfg(not(all(unix, not(target_os = "macos"))))]
let winit_x11 = false;
let first_mode = startup_mode::first_mode(std::env::var_os(startup_mode::ROLLBACK_VAR).as_deref(), winit_x11);
log::info!("root: {first_mode:?} first");
// What the OS asks of a running app arrives here; its wake repaints once the window exists.
let repaint: Arc<OnceLock<egui::Context>> = Arc::new(OnceLock::new());
let (intake, sender) = FileIntake::new(Wake::new({
@@ -728,10 +674,39 @@ fn main() -> eframe::Result {
}
}
}));
let drops = intake.sender();
// Each start's options, from scratch: a fallback start gets the plain windowed ones.
let hook_drops = drops.clone();
let document_windows = document_panels::DocumentWindows::default();
let hook_windows = document_windows.clone();
let native_options = move |mode: eframe::RootViewportMode| {
let mut options = eframe::NativeOptions {
root_viewport_mode: mode,
// A refused start must return here, on the thread whose event loop the fallback reuses.
run_and_return: true,
viewport: viewport.clone(),
..Default::default()
};
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler
// and the GPU that drives the screen (#603, #2652, #5199).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
craft::gpu::configure(setup);
}
// Read only when the first start builds the event loop; a fallback reuses that loop.
#[cfg(all(unix, not(target_os = "macos")))]
if x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
if mode == eframe::RootViewportMode::Windowless {
options.viewport_hooks = Some(hook_windows.hooks(hook_drops.clone()));
}
options
};
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns.
let drops = intake.sender();
options.viewport_hooks = Some(Arc::new(ChildDrops(drops.clone())));
#[cfg(target_os = "macos")]
let _apple_events = craft::platform::open::apple_events::install(sender);
#[cfg(not(target_os = "macos"))]
@@ -761,12 +736,10 @@ fn main() -> eframe::Result {
let noticed_for_exit = unclean_notice_shown.clone();
let noticed_in_window = unclean_notice_shown.clone();
let exit_settings = settings.clone();
// The root window is never shown (ADR 0001): eframe runs a windowless root and every document is a child
// window. X11, XWayland and BSD on X11 cannot, so they keep the visible root (the ADR's amendment). The mode
// is read by the app creator, which runs once the mode is settled.
let windowless = Arc::new(std::sync::atomic::AtomicBool::new(!x11));
let windowless_in_app = windowless.clone();
let creator: eframe::AppCreator<'static> = Box::new(move |cc| {
// Everything a start hands the app, used by the one creator that runs (`startup_mode::run`).
let create_app = move |cc: &eframe::CreationContext<'_>,
mode: eframe::RootViewportMode|
-> Result<Box<dyn eframe::App>, Box<dyn std::error::Error + Send + Sync>> {
let ctx = cc.egui_ctx.clone();
let _ = repaint.set(ctx.clone());
let wake = {
@@ -785,15 +758,11 @@ fn main() -> eframe::Result {
.build(),
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let mut spec = InstallSpec::new(shell, Arc::new(SystemWindows))
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
// The runtime and eframe must agree on the root.
if windowless_in_app.load(std::sync::atomic::Ordering::Relaxed) {
spec = spec.windowless_root();
}
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
// The system region picks the new document's paper, the units and the decimal
@@ -810,6 +779,11 @@ fn main() -> eframe::Result {
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
let windowless = mode == eframe::RootViewportMode::Windowless;
app.enable_windowless_trial(windowless);
if windowless {
app.set_native_window_lookup(Some(Arc::new(document_windows.clone())));
}
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
if let Some(state) = &cc.wgpu_render_state {
let info = state.adapter.get_info();
@@ -897,6 +871,7 @@ fn main() -> eframe::Result {
native_menu: native_menu::install(&ctx, &app),
app,
panels,
document_windows,
drops,
settings,
spool,
@@ -905,8 +880,17 @@ fn main() -> eframe::Result {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
};
let result = startup_mode::run(first_mode, create_app, |mode, inputs| {
eframe::run_native(
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
native_options(mode),
Box::new(move |cc| {
let create = inputs.take().ok_or("the app was already created")?;
create(cc, mode)
}),
)
});
let result = run_with_visible_root_fallback(creator, windowless, options);
// The exit hook has run; this is the no-op fallback for a start that created no window.
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
// The app is dropped by now: whatever it saved on the way out is in the store.
@@ -1070,6 +1054,7 @@ mod launch_arg_tests {
#[cfg(test)]
mod smoke {
use super::*;
use craft::platform::open::DroppedFile;
use craft::ui::testing::Frames;
use serde_json::json;
@@ -1117,6 +1102,7 @@ mod smoke {
native_menu: None,
app,
panels,
document_windows: Default::default(),
drops,
settings,
spool,
@@ -1271,54 +1257,6 @@ mod smoke {
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
}
/// With a modal dialog open, Quit stays enabled and ⌘Q / menu Quit still run `ui.quit`:
/// a clean document quits and a modified one opens Save Changes (#8792).
#[cfg(target_os = "macos")]
#[test]
fn native_quit_works_while_a_modal_dialog_is_open() {
use craft::menu::{ItemRole, NativeMenu};
let mut clean = Run::new();
let fake = native_menu::FakeBackend::default();
let synced = fake.synced.clone();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
clean.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
clean.app.app.run("ui.dialog", json!({"name": "about"})).unwrap();
clean.settle();
assert!(clean.app.app.dialog_host_mut().shows_modal());
let quit = {
let bars = synced.borrow();
let bar = bars.last().unwrap();
let about = bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
let quit = bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert!(!about.enabled, "About is greyed while About is open");
assert!(quit.enabled, "Quit stays enabled while About is open");
quit.clone()
};
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
let cmd_q = quit.shortcut.unwrap();
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None));
clean.settle();
assert!(clean.app.app.quit_requested, "Cmd+Q quits a clean document while About is open");
let mut dirty = Run::new();
let fake = native_menu::FakeBackend::default();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
dirty.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
dirty.app.app.run("text.insert", json!({"text": "unsaved"})).unwrap();
dirty.app.app.run("ui.dialog", json!({"name": "paragraph"})).unwrap();
dirty.settle();
assert!(dirty.app.app.dialog_host_mut().shows_modal());
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None));
dirty.settle();
assert!(!dirty.app.app.quit_requested, "Quit asks Save Changes first for a modified document");
dirty.app.app.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
assert!(dirty.app.app.quit_requested, "Don't Save completes the quit");
}
}
#[cfg(test)]
+5 -87
View File
@@ -1,27 +1,18 @@
//! The macOS application menu uses the same About dialog as File › About.
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, ModalRules, NativeMenu, mac_layout};
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
use serde_json::json;
use wordcraft_ui_egui::{WordApp, i18n};
const APP_NAME: &str = "WordCraft";
const ABOUT: &str = "About WordCraft";
const QUIT: &str = "Quit WordCraft";
/// The application menu, with `tr` the translation of an English string.
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
// Without its own Quit `mac_layout` adds one whose click only closes the root window: it must ask about every document.
let quit = Item::new(CommandRef::new("ui.quit"), tr(QUIT)).role(ItemRole::Quit);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into(), quit.into()]).role(MenuRole::App)]);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
let label = |s: &'static str| {
tr(match s {
"About {app}" => ABOUT,
"Quit {app}" => QUIT,
s => s,
})
};
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
// WordCraft's document menus live in its ribbon; keep only the application menu.
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
@@ -36,24 +27,15 @@ fn layout_in(lang: i18n::Lang) -> Layout {
layout(&|s| i18n::tr(lang, s).to_owned())
}
/// Commands that still run from the application menu while a modal dialog is open: `ui.quit` asks
/// about unsaved documents through `WordApp::quit`, matching the built-in Quit item and the Dock.
fn modal_rules() -> ModalRules {
ModalRules::default().in_dialogs(["ui.quit"])
}
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
let mut menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if let Some(menu) = &mut menu {
menu.set_modal_rules(modal_rules());
} else {
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if menu.is_none() {
log::warn!("the WordCraft application menu could not be installed");
}
menu
}
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
menu.set_modal_rules(modal_rules());
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
for command in menu.take_clicks(ctx) {
if let Err(error) = app.run(&command.id, command.params) {
@@ -67,29 +49,6 @@ pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Conte
}
}
#[cfg(test)]
#[derive(Default)]
pub(super) struct FakeBackend {
pub(super) synced: std::rc::Rc<std::cell::RefCell<Vec<MenuBar>>>,
pub(super) events: std::rc::Rc<std::cell::RefCell<Vec<craft::menu::Event>>>,
pub(super) dispatch: std::rc::Rc<std::cell::RefCell<Option<craft::menu::Dispatch>>>,
}
#[cfg(test)]
impl craft::menu::Backend for FakeBackend {
fn sync(&mut self, bar: &MenuBar) {
self.synced.borrow_mut().push(bar.clone());
}
fn attach(&mut self, dispatch: craft::menu::Dispatch) {
*self.dispatch.borrow_mut() = Some(dispatch);
}
fn drain(&mut self) -> Vec<craft::menu::Event> {
std::mem::take(&mut *self.events.borrow_mut())
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -102,45 +61,4 @@ mod tests {
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
assert_eq!(about.label, "Über WordCraft");
}
/// ⌘Q and the menu's Quit run `ui.quit`, which asks about unsaved documents; craft's built-in Quit only closes the root window (#8709).
#[test]
fn quit_runs_the_command_that_asks_about_documents() {
let layout = layout(&|s| s.to_owned());
let quit = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert_eq!(quit.command.id, "ui.quit");
}
/// Quit stays enabled while a modal dialog is open, and both a menu click and ⌘Q pass the gate (#8792).
#[test]
fn quit_stays_enabled_and_runs_under_modal_rules() {
let fake = FakeBackend::default();
let synced = fake.synced.clone();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
let mut menu = NativeMenu::new(Box::new(fake));
menu.set_modal_rules(modal_rules());
menu.set_gate(Gate::default().modal(true));
let ctx = egui::Context::default();
menu.sync_with("en", || layout(&|s| s.to_owned()));
let bar = synced.borrow();
let last = bar.last().unwrap();
let about = last.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().clone();
let quit = last.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap().clone();
drop(bar);
assert!(!about.enabled, "About is greyed while a modal dialog is open");
assert!(quit.enabled, "Quit stays enabled while a modal dialog is open");
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
let cmd_q = quit.shortcut.unwrap();
events.borrow_mut().extend([
dispatch.chosen(&about.command, about.shortcut.as_ref(), about.layout_shortcut, false, Default::default(), None),
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None),
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None),
]);
menu.poll(&ctx);
assert_eq!(menu.take_clicks(&ctx), vec![quit.command.clone(), quit.command]);
}
}
+172
View File
@@ -0,0 +1,172 @@
//! Which root WordCraft starts with, and the one fallback to normal windows.
//!
//! The windowless root is the default. `WORDCRAFT_WINDOWLESS_TRIAL=0` (exactly `0`) rolls back to
//! a windowed root; any other value, or none, keeps the default. On Linux and the BSDs the
//! windowless bootstrap supports only native Wayland, so a start whose event loop winit will open
//! on X11 or XWayland starts windowed from the outset and never retries ([`winit_picks_x11`]).
//!
//! Everything else is decided by eframe, from the display it actually connected to: its windowless
//! bootstrap returns [`eframe::Error::UnsupportedConfiguration`] for an X11 display handle (and,
//! on macOS and Windows, for a renderer bootstrap it cannot use) before it calls the app creator
//! and before any root window exists. With `run_and_return` that error comes back out of
//! `run_native`, the thread's event loop stays cached, and a second `run_native` on this thread
//! reuses it. [`run`] then starts once more with normal windows, only when the creator has not
//! started. Every other error, a second `UnsupportedConfiguration`, and any error after the
//! creator started (including a document window whose surface cannot be attached later, which
//! eframe reports per document) is returned unchanged.
//!
//! Source-only caveat: on a native Wayland display eframe's logical root takes the launcher's
//! activation token before the renderer starts, so a fallback window there may open without it.
use std::cell::RefCell;
use std::rc::Rc;
use eframe::RootViewportMode;
/// The variable that rolls the windowless root back to a windowed one, with the value `0`.
pub(crate) const ROLLBACK_VAR: &str = "WORDCRAFT_WINDOWLESS_TRIAL";
/// The root mode of the first start: windowed when rolled back or when winit opens X11.
pub(crate) fn first_mode(rollback: Option<&std::ffi::OsStr>, x11: bool) -> RootViewportMode {
if x11 || rollback.is_some_and(|v| v == "0") { RootViewportMode::Windowed } else { RootViewportMode::Windowless }
}
/// Whether winit's event loop opens on X11 (XWayland included): forced by the app, or unforced
/// with no Wayland display and an X server. Mirrors the pinned winit's choice exactly: empty and
/// non-Unicode values count as unset, and Wayland wins over `DISPLAY` when unforced. Neither set
/// means winit fails to start at all, which no mode changes.
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) fn winit_picks_x11(forced_x11: bool, env: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
let set = |name: &str| env(name).is_some_and(|v| v.to_str().is_some_and(|v| !v.is_empty()));
forced_x11 || (!set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") && set("DISPLAY"))
}
/// The app's one-shot startup inputs, shared by every start but taken by one app creator only.
pub(crate) struct OneShot<T>(Rc<RefCell<Option<T>>>);
impl<T> Clone for OneShot<T> {
fn clone(&self) -> Self {
Self(Rc::clone(&self.0))
}
}
impl<T> OneShot<T> {
/// The inputs, for the app creator that runs; `None` once any creator has taken them.
pub(crate) fn take(&self) -> Option<T> {
self.0.borrow_mut().take()
}
fn untouched(&self) -> bool {
self.0.borrow().is_some()
}
}
/// Starts the app in `first` mode through `launch`, and once more with normal windows when a
/// windowless start was refused as unsupported before its app creator took `inputs`.
pub(crate) fn run<T>(first: RootViewportMode, inputs: T, mut launch: impl FnMut(RootViewportMode, OneShot<T>) -> eframe::Result) -> eframe::Result {
let inputs = OneShot(Rc::new(RefCell::new(Some(inputs))));
match launch(first, inputs.clone()) {
Err(eframe::Error::UnsupportedConfiguration(reason)) if first == RootViewportMode::Windowless && inputs.untouched() => {
log::warn!("windowless start unsupported here ({reason}); opening normal windows instead");
launch(RootViewportMode::Windowed, inputs)
}
other => other,
}
}
#[cfg(test)]
mod tests {
use super::*;
use RootViewportMode::{Windowed, Windowless};
fn unsupported() -> eframe::Result {
Err(eframe::Error::UnsupportedConfiguration("windowless root: X11".into()))
}
/// Runs the real policy with scripted starts; each step sees whether it may create the app and
/// returns that start's result. Returns the modes started, the modes that created the app, and
/// the result.
fn script(first: RootViewportMode, mut steps: Vec<(bool, eframe::Result)>) -> (Vec<RootViewportMode>, Vec<RootViewportMode>, eframe::Result) {
steps.reverse();
let mut started = Vec::new();
let mut created = Vec::new();
let result = run(first, "inputs", |mode, inputs| {
started.push(mode);
let (creates, result) = steps.pop().unwrap_or((false, Ok(())));
if creates && inputs.take().is_some() {
created.push(mode);
}
result
});
(started, created, result)
}
#[test]
fn an_unsupported_windowless_bootstrap_starts_once_more_with_windows() {
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (true, Ok(()))]);
assert_eq!(started, [Windowless, Windowed]);
assert_eq!(created, [Windowed], "the inputs reach the windowed start's creator, once");
assert!(result.is_ok());
}
#[test]
fn the_windowed_start_is_the_last_one() {
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (false, unsupported())]);
assert_eq!(started, [Windowless, Windowed]);
assert!(created.is_empty());
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
}
#[test]
fn a_windowed_start_is_never_retried() {
let (started, _, result) = script(first_mode(None, true), vec![(false, unsupported())]);
assert_eq!(started, [Windowed], "X11 starts windowed, once");
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
}
#[test]
fn other_errors_come_back_unchanged() {
let (started, _, result) = script(Windowless, vec![(false, Err(eframe::Error::AppCreation("no runtime".into())))]);
assert_eq!(started, [Windowless]);
assert!(matches!(result, Err(eframe::Error::AppCreation(e)) if e.to_string() == "no runtime"));
}
#[test]
fn nothing_starts_again_once_the_app_creator_ran() {
let (started, created, result) = script(Windowless, vec![(true, unsupported())]);
assert_eq!((started, created), (vec![Windowless], vec![Windowless]));
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
}
#[test]
fn only_exactly_zero_rolls_back() {
let var = |v: &str| Some(std::ffi::OsString::from(v));
assert_eq!(first_mode(var("0").as_deref(), false), Windowed);
for value in [None, var("1"), var(""), var("off"), var(" 0")] {
assert_eq!(first_mode(value.as_deref(), false), Windowless, "{value:?}");
}
}
/// The pinned winit opens Wayland whenever a Wayland display is named and the app forces
/// nothing, even with `DISPLAY` set; X11 only when forced or with no Wayland display.
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn x11_is_what_winit_opens_not_what_the_session_says() {
use std::os::unix::ffi::OsStringExt;
let picks = |forced, vars: &[(&str, &str)]| {
winit_picks_x11(forced, |name| vars.iter().find(|(k, _)| *k == name).map(|(_, v)| std::ffi::OsString::from(v)))
};
let both = [("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "wayland-0")];
assert!(picks(true, &both), "forced XWayland");
assert!(!picks(false, &both), "unforced, Wayland wins");
assert!(!picks(false, &[("DISPLAY", ":0"), ("WAYLAND_SOCKET", "3")]));
assert!(picks(false, &[("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "")]), "an empty Wayland display is unset");
assert!(!picks(false, &[]));
let non_unicode = |name: &str| match name {
"DISPLAY" => Some(":0".into()),
"WAYLAND_DISPLAY" => Some(std::ffi::OsString::from_vec(b"w\xe9".to_vec())),
_ => None,
};
assert!(winit_picks_x11(false, non_unicode), "winit reads a non-Unicode Wayland display as unset");
}
}
+1 -24
View File
@@ -23,8 +23,7 @@ mod para_props;
mod table_props;
pub use char_props::{
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, ThemeFont, Underline,
VertAlign,
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, Underline, VertAlign,
};
pub use color::{Rgb, TextColor};
pub use para_props::{
@@ -201,26 +200,4 @@ mod tests {
assert_eq!(changed.sym_font.as_deref(), Some("Wingdings"));
assert_eq!(p.cleared().sym_font.as_deref(), Some("Wingdings"));
}
#[test]
fn named_east_asian_font_replaces_theme_slot_and_minus_round_trips() {
let mut base = CharProps { font_ea: Some("Times New Roman".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
let named = CharProps { font_ea: Some("SimSun".into()), ..Default::default() };
base.overlay(&named);
assert_eq!(base.font_ea.as_deref(), Some("SimSun"));
assert_eq!(base.font_ea_theme, None);
// Changing only `font_ea` while keeping `font_ea_theme` preserves the slot across minus/overlay.
let themed_base = CharProps { font_ea: Some("SimSun".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
let run = CharProps { font_ea: Some("MS Mincho".into()), ..themed_base.clone() };
let mut back = themed_base.clone();
back.overlay(&run.clone().minus(&themed_base));
assert_eq!(back, run);
// Clearing `font_ea_theme` while keeping the same `font_ea` preserves `font_ea` in the patch.
let cleared_slot = CharProps { font_ea_theme: None, ..themed_base.clone() };
let mut back_cleared = themed_base.clone();
back_cleared.overlay(&cleared_slot.clone().minus(&themed_base));
assert_eq!(back_cleared, cleared_slot);
}
}
+2 -76
View File
@@ -329,10 +329,6 @@ pub struct CharProps {
/// inherit, then `font`.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea: Option<String>,
/// The theme font slot of the East Asian font (`w:rFonts/@w:eastAsiaTheme`: `minorEastAsia`,
/// `majorEastAsia`…), taking precedence over `font_ea` when set.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea_theme: Option<ThemeFont>,
/// Complex-script size, points (`w:szCs`). `None` leaves the inherited value unchanged.
#[serde(skip_serializing_if = "Option::is_none")]
pub size_cs: Option<f32>,
@@ -454,62 +450,6 @@ impl CombineBrackets {
}
}
/// A theme font slot in `w:rFonts` (`ST_Theme`, ECMA-376 §17.18.96).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ThemeFont {
MajorEastAsia,
MajorBidi,
MajorAscii,
MajorHAnsi,
MinorEastAsia,
MinorBidi,
MinorAscii,
MinorHAnsi,
}
impl ThemeFont {
const ALL: [ThemeFont; 8] = [
ThemeFont::MajorEastAsia,
ThemeFont::MajorBidi,
ThemeFont::MajorAscii,
ThemeFont::MajorHAnsi,
ThemeFont::MinorEastAsia,
ThemeFont::MinorBidi,
ThemeFont::MinorAscii,
ThemeFont::MinorHAnsi,
];
/// The OOXML `ST_Theme` value.
pub fn as_str(self) -> &'static str {
match self {
ThemeFont::MajorEastAsia => "majorEastAsia",
ThemeFont::MajorBidi => "majorBidi",
ThemeFont::MajorAscii => "majorAscii",
ThemeFont::MajorHAnsi => "majorHAnsi",
ThemeFont::MinorEastAsia => "minorEastAsia",
ThemeFont::MinorBidi => "minorBidi",
ThemeFont::MinorAscii => "minorAscii",
ThemeFont::MinorHAnsi => "minorHAnsi",
}
}
/// Parse an OOXML `ST_Theme` value (`None` for any value outside the schema).
pub fn parse(s: &str) -> Option<ThemeFont> {
ThemeFont::ALL.into_iter().find(|t| t.as_str() == s)
}
/// Whether this slot picks the theme's major (heading) font rather than minor (body).
pub fn is_major(self) -> bool {
matches!(self, ThemeFont::MajorEastAsia | ThemeFont::MajorBidi | ThemeFont::MajorAscii | ThemeFont::MajorHAnsi)
}
/// Whether this is one of the Latin theme slots (`ascii` / `hAnsi`).
pub fn is_latin(self) -> bool {
matches!(self, ThemeFont::MajorAscii | ThemeFont::MajorHAnsi | ThemeFont::MinorAscii | ThemeFont::MinorHAnsi)
}
}
/// A tracked formatting change (ECMA-376 §17.13.5: `w:rPrChange`, `w:pPrChange`,
/// `w:tblPrChange`, `w:trPrChange`, `w:tcPrChange`, `w:sectPrChange`): the properties as they
/// were before the change, and the revision (author, date) that made it.
@@ -569,16 +509,7 @@ impl CharProps {
}
fn minus_script_style(&mut self, base: &CharProps) {
// A theme slot stays while its named font does; a same font stays when its slot differs.
let keep = self.font_ea_theme;
let ea = self.font_ea.clone();
drop_same_fields!(self, base; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
if self.font_ea.is_none() && keep != base.font_ea_theme {
self.font_ea = ea;
}
if self.font_ea.is_some() {
self.font_ea_theme = keep;
}
drop_same_fields!(self, base; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
}
fn minus_document_marks(&mut self, base: &CharProps) {
@@ -609,12 +540,7 @@ impl CharProps {
}
fn overlay_script_style(&mut self, patch: &CharProps) {
// A named East Asian font without a theme slot replaces the slot too: Word gives the slot
// precedence over the named font, so keeping it would hide the font just chosen.
if patch.font_ea.is_some() && patch.font_ea_theme.is_none() {
self.font_ea_theme = None;
}
overlay_fields!(self, patch; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
overlay_fields!(self, patch; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
}
fn overlay_document_marks(&mut self, patch: &CharProps) {
+1 -6
View File
@@ -4,7 +4,7 @@
use serde::{Deserialize, Serialize};
use crate::props::{
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, ThemeFont, Underline, VertAlign,
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, Underline, VertAlign,
};
use crate::styles::{StyleKind, StyleSheet};
@@ -71,10 +71,6 @@ pub struct ResolvedChar {
/// East Asian font (Chinese, Japanese and Korean text), when one is set.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea: Option<String>,
/// Theme font slot for the East Asian font (`w:eastAsiaTheme`), taking precedence over
/// `font_ea` when set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub font_ea_theme: Option<ThemeFont>,
pub size_cs: f32,
pub bold_cs: bool,
pub italic_cs: bool,
@@ -121,7 +117,6 @@ impl ResolvedChar {
cs: c.cs.unwrap_or(false),
font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
font_ea: c.font_ea.clone(),
font_ea_theme: c.font_ea_theme,
size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0),
// A run marked complex script (`w:cs`) is bold and italic only by `w:bCs` and `w:iCs`:
// Word draws Thai with `<w:b/><w:cs/>` and no `w:bCs` upright and plain (measured in
+3 -22
View File
@@ -296,7 +296,6 @@ impl NumFormat {
use crate::cjk_numbers as cjk;
match self {
NumFormat::DecimalZero => format!("{n:02}"),
NumFormat::Hex => format!("{n:X}"),
NumFormat::ThaiNumbers => thai_digits(n),
NumFormat::UpperRoman => roman(n).to_uppercase(),
NumFormat::LowerRoman => roman(n),
@@ -342,6 +341,7 @@ impl NumFormat {
NumFormat::Chosung => cjk::chosung(n),
NumFormat::Decimal
| NumFormat::DecimalHalfWidth
| NumFormat::Hex
| NumFormat::VietnameseCounting
| NumFormat::Hebrew1
| NumFormat::Hebrew2
@@ -496,21 +496,13 @@ pub fn cardinal_text(n: u32) -> String {
let h = format!("{} hundred", words(n / 100));
if n.is_multiple_of(100) { h } else { format!("{h} {}", words(n % 100)) }
}
1_000..=999_999 => {
_ => {
let th = format!("{} thousand", words(n / 1000));
if n.is_multiple_of(1000) { th } else { format!("{th} {}", words(n % 1000)) }
}
1_000_000..=999_999_999 => {
let m = format!("{} million", words(n / 1_000_000));
if n.is_multiple_of(1_000_000) { m } else { format!("{m} {}", words(n % 1_000_000)) }
}
_ => {
let b = format!("{} billion", words(n / 1_000_000_000));
if n.is_multiple_of(1_000_000_000) { b } else { format!("{b} {}", words(n % 1_000_000_000)) }
}
}
}
capitalize(&words(n))
capitalize(&words(n.min(999_999)))
}
/// English ordinal words (`Twenty-First`).
@@ -1012,17 +1004,6 @@ mod tests {
assert_eq!(NumFormat::from_ooxml("klingon"), NumFormat::Decimal, "unknown formats are decimal");
}
#[test]
fn hex_and_large_number_text() {
assert_eq!(NumFormat::Hex.format(10), "A");
assert_eq!(NumFormat::Hex.format(15), "F");
assert_eq!(NumFormat::Hex.format(16), "10");
assert_eq!(NumFormat::Hex.format(255), "FF");
assert_eq!(NumFormat::CardinalText.format(1_000_000), "One Million");
assert_eq!(NumFormat::OrdinalText.format(1_000_000), "One Millionth");
assert_eq!(NumFormat::CardinalText.format(2_000_000_000), "Two Billion");
}
/// #5757: Thai numbers are the decimal number in Thai digits, every digit, at any length.
#[test]
fn thai_numbers_use_thai_digits() {
+16 -36
View File
@@ -1330,8 +1330,6 @@ fn hinted_east_asian_or_cs_font_does_not_replace_the_latin_font() {
assert_eq!((ea.font.as_str(), ea.font_ea.as_deref()), ("Times New Roman", Some("宋体")));
let cs = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[1].props);
assert_eq!((cs.font.as_str(), cs.font_cs.as_str()), ("Times New Roman", "Arial"));
assert_eq!(ea.font_ea_theme, None, "named w:eastAsia replaces Heading2's w:eastAsiaTheme");
assert_eq!(cs.font_ea_theme, Some(wordcraft_doc::props::ThemeFont::MajorEastAsia));
}
#[test]
@@ -2446,51 +2444,33 @@ fn note_separators_and_continuation_notice_round_trip() {
check(&wordcraft_docx::read(&out).unwrap());
}
/// A hyperlinked nested group in a footnote or endnote separator is flattened through the block
/// mapping just as it is in the document body.
/// A picture frame shape in a footnote or endnote separator opens as the same shape kind as it does
/// in the body, instead of failing the whole document. (The test name dates from when the body
/// opened this shape as a rectangle.)
#[test]
fn linked_nested_group_in_a_note_separator_is_flattened() {
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="Frame"/><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></wpg:grpSp>"#;
let group = format!(
r#"<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>"#
);
fn a_frame_shape_in_a_note_separator_reads_as_a_rectangle() {
let frame = r#"<w:r><w:drawing><wp:inline><wp:extent cx="508000" cy="381000"/><wp:docPr id="1" name="F"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#;
let notes = |root: &str, item: &str| {
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{group}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{frame}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
};
let footnotes = notes("footnotes", "footnote");
let endnotes = notes("endnotes", "endnote");
let link_rels = rels(&[("rId9", "hyperlink", "https://example.com/")]);
let bytes = docx(
&format!("<w:p>{group}</w:p>"),
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml"), ("rId9", "hyperlink", "https://example.com/")],
&[
("word/footnotes.xml", &footnotes),
("word/_rels/footnotes.xml.rels", &link_rels),
("word/endnotes.xml", &endnotes),
("word/_rels/endnotes.xml.rels", &link_rels),
],
&format!("<w:p>{frame}</w:p>"),
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml")],
&[("word/footnotes.xml", &footnotes), ("word/endnotes.xml", &endnotes)],
);
let d = wordcraft_docx::read(&bytes).unwrap();
let flattened = |p: &Paragraph| -> Vec<(f32, f32, ShapeKind, f32)> {
let Some(children) = p.objects.iter().find_map(|o| match o {
InlineObject::Group { children, .. } => Some(children),
_ => None,
}) else {
panic!("{:?}", p.objects);
};
children
.iter()
.map(|c| match &c.obj {
InlineObject::Shape { kind, w, .. } => (c.x, c.y, *kind, *w),
other => panic!("{other:?}"),
})
.collect()
let shapes = |p: &Paragraph| -> Vec<(ShapeKind, f32)> {
p.objects.iter().filter_map(|o| if let InlineObject::Shape { kind, w, .. } = o { Some((*kind, *w)) } else { None }).collect()
};
let in_body = flattened(d.body[0].as_para().unwrap());
assert_eq!(in_body, [(50.0, 0.0, ShapeKind::Frame, 50.0)]);
let in_body = shapes(d.body[0].as_para().unwrap());
assert_eq!(in_body.len(), 1, "{in_body:?}");
assert_eq!(in_body[0].1, 40.0);
assert_eq!(in_body[0].0, ShapeKind::Frame);
for separators in [&d.footnote_separators, &d.endnote_separators] {
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
assert_eq!(flattened(sep), in_body);
assert_eq!(shapes(sep), in_body);
}
}
-1
View File
@@ -132,7 +132,6 @@ fn every_char_prop_round_trips() {
cs: Some(true),
font_cs: Some("B Nazanin".into()),
font_ea: Some("宋体".into()),
font_ea_theme: Some(wordcraft_doc::props::ThemeFont::MinorEastAsia),
size_cs: Some(13.0),
bold_cs: Some(false),
italic_cs: Some(true),
-77
View File
@@ -93,83 +93,6 @@ fn run_and_style_snap_to_grid_and_web_hidden_survive_two_saves() {
}
}
/// Keeps run and style emphasis values intact across repeated DOCX saves.
#[test]
fn run_and_style_emphasis_marks_survive_two_saves() {
use wordcraft_doc::props::EmphasisMark;
let styles = r#"
<w:style w:type="character" w:styleId="Dot"><w:rPr><w:em w:val="dot"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="Comma"><w:rPr><w:em w:val="comma"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="Circle"><w:rPr><w:em w:val="circle"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="UnderDot"><w:rPr><w:em w:val="underDot"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="NoMark"><w:rPr><w:em w:val="none"/></w:rPr></w:style>
"#;
let body = r#"
<w:p>
<w:r><w:rPr><w:rStyle w:val="Dot"/></w:rPr><w:t>default dot</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Comma"/></w:rPr><w:t>comma</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Circle"/></w:rPr><w:t>circle</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="UnderDot"/></w:rPr><w:t>under dot</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Dot"/><w:em w:val="none"/></w:rPr><w:t>explicit none</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="NoMark"/></w:rPr><w:t>style none</w:t></w:r>
<w:r><w:rPr><w:em w:val="dot"/></w:rPr><w:t>run dot</w:t></w:r>
<w:r><w:rPr><w:em w:val="comma"/></w:rPr><w:t>run comma</w:t></w:r>
<w:r><w:rPr><w:em w:val="circle"/></w:rPr><w:t>run circle</w:t></w:r>
<w:r><w:rPr><w:em w:val="underDot"/></w:rPr><w:t>run under dot</w:t></w:r>
<w:r><w:rPr><w:em w:val="none"/></w:rPr><w:t>run none</w:t></w:r>
<w:r><w:t>inherit absent</w:t></w:r>
</w:p>
"#;
let mut doc = wordcraft_docx::read(&docx(body, styles)).unwrap();
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
let expected_styles = [
("Dot", Some(EmphasisMark::Dot)),
("Comma", Some(EmphasisMark::Comma)),
("Circle", Some(EmphasisMark::Circle)),
("UnderDot", Some(EmphasisMark::UnderDot)),
("NoMark", Some(EmphasisMark::None)),
];
for (id, mark) in expected_styles {
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark);
}
assert_eq!(p.runs[4].props.emphasis, Some(EmphasisMark::None));
let expected_runs = [
Some(EmphasisMark::Dot),
Some(EmphasisMark::Comma),
Some(EmphasisMark::Circle),
Some(EmphasisMark::UnderDot),
Some(EmphasisMark::None),
None,
];
for (run, mark) in p.runs.iter().skip(6).zip(expected_runs) {
assert_eq!(run.props.emphasis, mark);
}
for pass in 0..2 {
let out = wordcraft_docx::write(&doc).unwrap();
let style_xml = part(&out, "word/styles.xml");
for value in ["dot", "comma", "circle", "underDot", "none"] {
assert!(style_xml.contains(&format!(r#"<w:em w:val="{value}"/>"#)), "pass {pass}: {style_xml}");
}
let document_xml = part(&out, "word/document.xml");
assert!(document_xml.contains(r#"<w:em w:val="none"/>"#), "pass {pass}: {document_xml}");
assert!(document_xml.contains("default dot"));
doc = wordcraft_docx::read(&out).unwrap();
for (id, mark) in expected_styles {
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "pass {pass}");
}
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
for index in [0, 1, 2, 3, 5] {
assert_eq!(p.runs[index].props.emphasis, None, "pass {pass}: run {index}");
}
assert_eq!(p.runs[4].props.emphasis, Some(EmphasisMark::None), "pass {pass}: run 4",);
for (run, mark) in p.runs.iter().skip(6).zip(expected_runs) {
assert_eq!(run.props.emphasis, mark, "pass {pass}");
}
}
}
#[test]
fn style_paragraph_and_run_changes_keep_independent_authors() {
let styles = r#"
+1 -108
View File
@@ -580,65 +580,11 @@ pub fn now_unix() -> u64 {
}
}
/// ISO-8601 timestamp (UTC, seconds): the clock, for an event that happened now -- a comment, a
/// tracked change, a version. Not for what a saved or exported file records: see [`saved_iso`].
/// ISO-8601 timestamp (UTC, seconds).
pub fn now_iso() -> String {
iso_from_unix_secs(now_unix())
}
/// The timestamp a saved or exported file records (its created and modified properties):
/// `SOURCE_DATE_EPOCH` when it holds a non-negative whole number of seconds, else the clock. With
/// it set, separate conversions of unchanged input can produce the same bytes. Repeated saves
/// of one session still advance the document revision
/// (<https://reproducible-builds.org/specs/source-date-epoch/>).
///
/// The clock stays in [`now_iso`]: an editing event's time is not the file's, and pinning it would
/// misdate comments and tracked changes.
///
/// A value that is set but not one of those is ignored with a warning, so a build that meant to
/// pin its dates hears that it did not.
pub fn saved_iso() -> String {
let raw = std::env::var("SOURCE_DATE_EPOCH").ok();
if let Some(problem) = epoch_problem(raw.as_deref()) {
log::warn!("{problem}");
}
iso_from_unix_secs(pinned_or(|_| raw.clone(), now_unix))
}
/// Why `SOURCE_DATE_EPOCH` is set and still not used, for a caller with no logger to say so (the
/// command line). `None` when it is unset, empty, or a value [`saved_iso`] takes.
pub fn source_date_epoch_problem() -> Option<String> {
epoch_problem(std::env::var("SOURCE_DATE_EPOCH").ok().as_deref())
}
/// An empty value counts as unset, as a CI file's `SOURCE_DATE_EPOCH=` with nothing after it
/// means; anything else that does not pin a date is worth a warning.
fn epoch_problem(value: Option<&str>) -> Option<String> {
let v = value?;
if v.trim().is_empty() || pinned(v).is_some() {
return None;
}
Some(format!(
"SOURCE_DATE_EPOCH={v:?} is not a whole number of seconds from 1970 to 9999-12-31, so saved and exported files take the clock's date"
))
}
/// The seconds a `SOURCE_DATE_EPOCH` value pins, if it pins any.
fn pinned(v: &str) -> Option<u64> {
v.trim().parse::<u64>().ok().filter(|secs| *secs <= LAST_DATE)
}
/// [`saved_iso`]'s choice, with the environment and the clock given so a test can show which wins.
pub(crate) fn pinned_or(get: impl Fn(&str) -> Option<String>, clock: impl Fn() -> u64) -> u64 {
get("SOURCE_DATE_EPOCH").as_deref().and_then(pinned).unwrap_or_else(clock)
}
/// The last date a document can record, as Unix seconds: 9999-12-31T23:59:59Z. A year runs to
/// four digits in `xsd:dateTime`, which is what a .docx core property holds, so a value past this
/// would be written as something no reader accepts -- `292277026596-12-04T15:30:07Z` for
/// `i64::MAX`. Such a value is left to the clock, as a malformed one is.
const LAST_DATE: u64 = 253_402_300_799;
/// 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 {
@@ -789,56 +735,3 @@ mod iso_tests {
let _ = (civil_from_days(i64::MAX), civil_from_days(i64::MIN));
}
}
#[cfg(test)]
mod saved_time_tests {
use super::{epoch_problem, iso_from_unix_secs, pinned_or};
/// What a saved or exported file records: `SOURCE_DATE_EPOCH` when it holds a non-negative
/// whole number of seconds, the clock whenever it does not. The environment and the clock are
/// given here rather than set, so no test changes this process's environment -- that is
/// `unsafe` under edition 2024 and would reach every test beside it.
#[test]
fn a_pinned_epoch_is_preferred_and_the_clock_answers_otherwise() {
let env = |v: Option<&'static str>| move |_: &str| v.map(str::to_owned);
let clock = || 1_000_000;
assert_eq!(pinned_or(env(Some("1791208980")), clock), 1_791_208_980, "the variable wins");
assert_eq!(pinned_or(env(Some("0")), clock), 0, "the epoch itself counts");
assert_eq!(pinned_or(env(Some(" 1791208980 ")), clock), 1_791_208_980, "spaces around it are allowed");
// The last date a document can write is honoured; past it the year would not fit
// `xsd:dateTime` and the clock answers instead.
assert_eq!(pinned_or(env(Some("253402300799")), clock), 253_402_300_799);
assert_eq!(iso_from_unix_secs(253_402_300_799), "9999-12-31T23:59:59Z");
for ignored in [
None,
Some(""),
Some(" "),
Some("-1"),
Some("later"),
Some("1791208980.5"),
Some("99999999999999999999"),
Some("253402300800"),
Some("9223372036854775807"),
] {
assert_eq!(pinned_or(env(ignored), clock), 1_000_000, "{ignored:?} leaves it to the clock");
}
// Only that variable is read.
assert_eq!(pinned_or(|name: &str| (name == "TZ").then(|| "1791208980".to_owned()), clock), 1_000_000);
// And it reaches the stamp as that instant, not as something near it.
assert_eq!(iso_from_unix_secs(pinned_or(env(Some("1791208980")), clock)), "2026-10-05T14:03:00Z");
}
/// A value that is set and still ignored is reported, so a build that meant to pin its dates
/// hears that it did not (noted in review). Unset and empty say nothing: an empty value is
/// how a CI file leaves the variable off.
#[test]
fn a_set_but_unusable_epoch_is_reported_and_nothing_else_is() {
for quiet in [None, Some(""), Some(" "), Some("0"), Some("1791208980"), Some(" 1791208980 "), Some("253402300799")] {
assert_eq!(epoch_problem(quiet), None, "{quiet:?}");
}
for loud in ["later", "-1", "1791208980.5", "1e9", "253402300800", "99999999999999999999"] {
let problem = epoch_problem(Some(loud)).unwrap_or_else(|| panic!("{loud:?} should be reported"));
assert!(problem.contains(&format!("{loud:?}")) && problem.contains("clock"), "{problem}");
}
}
}
+45 -228
View File
@@ -2,9 +2,8 @@
use serde_json::Value;
use wordcraft_doc::math_edit::MathPos;
use wordcraft_doc::para::{NBSP, OBJ};
use wordcraft_doc::props::TextDirection;
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
use wordcraft_doc::para::OBJ;
use wordcraft_doc::{InlineObject, Pos, StoryRef};
use wordcraft_layout::ViewMode;
use super::{parse_pos, sel_result};
@@ -54,10 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("caret.set", "Set Caret", "Navigation", set)
.params(r#"{"pos": Pos, "extend"?: bool} | {"page": n, "x": pt, "y": pt}"#)
.pure(),
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all)
.key("Mod+A")
.params(r#"{"whole"?: bool (default true: select the whole story; false: grow through the cell, row and table first)}"#)
.pure(),
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all).key("Mod+A").pure(),
CommandSpec::new("select.range", "Select Range", "Navigation", select_range).params(r#"{"anchor": Pos, "focus": Pos}"#).pure(),
CommandSpec::new("select.word", "Select Word", "Navigation", select_word).pure(),
CommandSpec::new("select.sentence", "Select Sentence", "Navigation", select_sentence).pure(),
@@ -114,51 +110,7 @@ fn bidi_para(s: &Session) -> bool {
/// Left/Right: with a selection and no Shift, collapse to its edge.
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if let Some(t) = turn(s) {
// Vertical text (#8986): Left/Right change line; top-to-bottom lines stack leftwards.
return line_step(s, v, (t == TextDirection::Down) == is_left, is_left);
}
lr_along(s, v, is_left)
}
/// The text direction at the caret when it is in turned (vertical) text.
fn turn(s: &mut Session) -> Option<TextDirection> {
let l = s.layout();
l.turn_at(&s.sel.focus, s.page_hint)
}
/// Vertical text: to the next (`next`) or previous line, at the same distance along it. With no
/// such line in the caret's flow, Left/Right stop in a table cell or text box and otherwise step along
/// the text as they did before (`is_left`: backwards).
fn line_step(s: &mut Session, v: &Value, next: bool, is_left: bool) -> CmdResult {
let ext = extend(v);
if !ext && !s.sel.is_collapsed() {
let (a, b) = s.sel.ordered();
s.sel = Selection::caret(if next { b } else { a });
s.goal_x = None;
return sel_result(s);
}
let l = s.layout();
let from = s.sel.focus.clone();
let to = match l.turned_line(&from, s.goal_x, next, s.page_hint) {
Some((p, g)) => {
s.goal_x = Some(g);
p
}
// Inside a table cell or text box the caret stops at the edge rather than leaving it.
None if from.path.0.len() > 1 => return sel_result(s),
None => return lr_along(s, v, is_left),
};
let gx = s.goal_x;
apply(s, to, ext);
s.goal_x = gx;
sel_result(s)
}
/// Left/Right as a step along the text (`is_left`: backwards).
fn lr_along(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
let ext = extend(v);
if !ext && !s.sel.is_collapsed() {
if !extend(v) && !s.sel.is_collapsed() {
let (a, b) = s.sel.ordered();
// The left edge of a selection in right-to-left text is its logical end.
let to_start = is_left != rtl_para(s);
@@ -169,33 +121,26 @@ fn lr_along(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if bidi_para(s) {
return visual_lr(s, v, is_left);
}
let from = s.sel.focus.clone();
// Equation entry and the grapheme step start at the same visible edge.
let hidden = s.layout_hides_deleted(from.story);
let edge = logical_edge(s, &from, is_left, hidden);
if !ext
if !extend(v)
&& !s.math_left
&& let Some(r) = into_equation(s, &from, edge, is_left, hidden)
&& let Some(r) = into_equation(s, is_left)
{
return r;
}
s.goal_x = None;
let to = step_from_edge(s, &from, edge, is_left);
apply(s, to, ext);
sel_result(s)
mv(s, v, if is_left { left } else { right })
}
/// Left/Right onto an equation opens it, at its end from the right and at its start from the
/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then
/// moves on instead of going back in. A caret.left/right that itself left an equation (sent
/// while editing one) moves on too.
fn into_equation(s: &mut Session, from: &Pos, edge: usize, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> Option<CmdResult> {
let off = if is_left { edge.checked_sub(OBJ.len_utf8())? } else { edge };
let para = s.doc.para_at(from)?;
if !matches!(para.object_at(off), Some(InlineObject::Equation { .. })) || (hidden.any() && hidden.hides(&s.doc, para.props_of_char(off).del)) {
fn into_equation(s: &mut Session, is_left: bool) -> Option<CmdResult> {
let f = s.sel.focus.clone();
let off = if is_left { f.off.checked_sub(OBJ.len_utf8())? } else { f.off };
if !matches!(s.doc.para_at(&f)?.object_at(off), Some(InlineObject::Equation { .. })) {
return None;
}
s.sel = Selection::caret(Pos { off, ..from.clone() });
s.sel = Selection::caret(Pos { off, ..f });
s.goal_x = None;
s.pending = None;
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
@@ -214,187 +159,63 @@ fn visual_lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
Some(wordcraft_layout::VisualStep::Edge { start, stop, last_line, rtl }) => {
let at = |off| Pos { off, ..from.clone() };
if is_left != rtl {
logical_step(s, &at(start), true)
match s.doc.para_at(&from) {
Some(para) if start > 0 => at(para.prev_boundary(start)),
_ => left(s, &at(0)),
}
} else if !last_line {
at(stop)
} else {
let len = s.doc.para_at(&from).map_or(stop, |p| p.len());
logical_step(s, &at(len), false)
right(s, &at(len))
}
}
None => logical_step(s, &from, is_left),
None if is_left => left(s, &from),
None => right(s, &from),
};
apply(s, to, ext);
sel_result(s)
}
/// Find the run containing `byte` from the nearer end of `para`.
fn run_at_byte(para: &Paragraph, byte: usize) -> Option<(usize, std::ops::Range<usize>)> {
if byte >= para.len() {
return None;
}
if byte < para.len() / 2 {
para.run_ranges().enumerate().find_map(|(i, (range, _))| range.contains(&byte).then_some((i, range)))
} else {
let mut end = para.len();
para.runs.iter().enumerate().rev().find_map(|(i, run)| {
let start = end.saturating_sub(run.len);
let range = start..end;
end = start;
range.contains(&byte).then_some((i, range))
})
}
}
/// The two ends of a hidden deletion share a caret position. Cross the hidden
/// span before taking the normal grapheme step, including adjacent deletions.
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool, hides: impl Fn(Option<u32>) -> bool) -> usize {
// At a run boundary, inspect the byte on the side the caret is moving toward.
let Some(byte) = off.checked_sub(usize::from(is_left)) else { return off };
let Some((i, range)) = run_at_byte(para, byte) else { return off };
if !hides(para.runs[i].props.del) {
return off;
}
if is_left {
range.start - para.runs[..i].iter().rev().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
} else {
range.end + para.runs[i + 1..].iter().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
}
}
fn logical_edge(s: &Session, from: &Pos, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> usize {
if hidden.any()
&& let Some(para) = s.doc.para_at(from)
fn left(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p)
&& p.off > 0
{
return hidden_deletion_edge(para, from.off, is_left, |del| hidden.hides(&s.doc, del));
return Pos { off: para.prev_boundary(p.off), ..p.clone() };
}
match s.doc.prev_para(p.story, &p.path) {
Some(q) => {
let off = s.doc.para(p.story, &q).map(|x| x.len()).unwrap_or(0);
Pos { story: p.story, path: q, off }
}
None => p.clone(),
}
from.off
}
fn logical_step(s: &Session, from: &Pos, is_left: bool) -> Pos {
let edge = logical_edge(s, from, is_left, s.layout_hides_deleted(from.story));
step_from_edge(s, from, edge, is_left)
}
fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
if let Some(para) = s.doc.para_at(from) {
if is_left && edge > 0 {
return Pos { off: para.prev_boundary(edge), ..from.clone() };
}
if !is_left && edge < para.len() {
return Pos { off: para.next_boundary(edge), ..from.clone() };
}
fn right(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p)
&& p.off < para.len()
{
return Pos { off: para.next_boundary(p.off), ..p.clone() };
}
step_to_neighbor(s, from, is_left, !s.view.show_markup)
}
fn step_to_neighbor(s: &Session, from: &Pos, is_left: bool, skip_deleted: bool) -> Pos {
let story = from.story;
let neighbor = if is_left { s.doc.prev_para(story, &from.path) } else { s.doc.next_para(story, &from.path) };
let Some(mut path) = neighbor else { return from.clone() };
// Layout collapses a wholly deleted paragraph in No Markup. A surviving mark still gives
// even a paragraph without visible text a caret stop.
let deleted = |path: &Path| s.doc.para(story, path).is_some_and(|p| p.mark.del.is_some() && p.runs.iter().all(|r| r.props.del.is_some()));
if skip_deleted && deleted(&path) {
// Get the story's paths once for the rest of the walk, even across many deleted paragraphs.
let paths = s.doc.para_paths(story);
let Ok(i) = paths.binary_search(&path) else { return from.clone() };
let stop = if is_left { paths[..i].iter().rev().find(|p| !deleted(p)) } else { paths[i + 1..].iter().find(|p| !deleted(p)) };
let Some(stop) = stop else { return from.clone() };
path = stop.clone();
match s.doc.next_para(p.story, &p.path) {
Some(q) => Pos { story: p.story, path: q, off: 0 },
None => p.clone(),
}
let off = if is_left { s.doc.para(story, &path).map_or(0, Paragraph::len) } else { 0 };
Pos { story, path, off }
}
fn visible_word_start(para: &Paragraph, off: usize) -> Option<usize> {
let off = para.clamp(off);
let byte = off.checked_sub(1)?;
let (i, range) = run_at_byte(para, byte)?;
let mut idx = off;
let mut seen_word = false;
let mut seen_visible = false;
let mut end = range.end;
for run in para.runs[..=i].iter().rev() {
let start = end.saturating_sub(run.len);
let range_end = end.min(off);
end = start;
if run.props.del.is_some() {
continue;
}
let Some(slice) = para.text.get(start..range_end) else { continue };
for (rel, c) in slice.char_indices().rev() {
seen_visible = true;
if wordcraft_doc::bidi::is_word_char(c) {
seen_word = true;
idx = start + rel;
} else if seen_word {
return Some(idx);
} else {
idx = start + rel;
}
}
}
seen_visible.then_some(idx)
}
fn visible_word_end(para: &Paragraph, off: usize) -> Option<usize> {
let off = para.clamp(off);
let (i, range) = run_at_byte(para, off)?;
let mut first_word = None;
let mut in_space = false;
let mut last_end = None;
let mut run_start = range.start;
for run in &para.runs[i..] {
let run_end = run_start.saturating_add(run.len);
let start = run_start.max(off);
run_start = run_end;
if run.props.del.is_some() {
continue;
}
let Some(slice) = para.text.get(start..run_end) else { continue };
for (rel, c) in slice.char_indices() {
let abs = start + rel;
last_end = Some(abs + c.len_utf8());
let is_first = first_word.is_none();
let fw = *first_word.get_or_insert_with(|| wordcraft_doc::bidi::is_word_char(c) && c != '\'');
let w = wordcraft_doc::bidi::is_word_char(c);
if c == ' ' || c == NBSP {
in_space = true;
continue;
}
if in_space || (fw && !w) || (!fw && !is_first) {
return Some(abs);
}
}
}
last_end
}
fn word_left(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p) {
if !s.view.show_markup {
if let Some(off) = visible_word_start(para, p.off) {
return Pos { off, ..p.clone() };
}
} else if p.off > 0 {
return Pos { off: para.word_start(p.off), ..p.clone() };
}
match s.doc.para_at(p) {
Some(para) if p.off > 0 => Pos { off: para.word_start(p.off), ..p.clone() },
_ => left(s, p),
}
step_to_neighbor(s, p, true, false)
}
fn word_right(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p) {
if !s.view.show_markup {
if let Some(off) = visible_word_end(para, p.off) {
return Pos { off, ..p.clone() };
}
} else if p.off < para.len() {
return Pos { off: para.word_end(p.off), ..p.clone() };
}
match s.doc.para_at(p) {
Some(para) if p.off < para.len() => Pos { off: para.word_end(p.off), ..p.clone() },
_ => right(s, p),
}
step_to_neighbor(s, p, false, false)
}
fn para_up(s: &mut Session, p: &Pos) -> Pos {
@@ -418,10 +239,6 @@ fn para_down(s: &mut Session, p: &Pos) -> Pos {
}
fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
if let Some(t) = turn(s) {
// Vertical text (#8986): Up/Down step along the line (top-to-bottom text runs down).
return lr_along(s, v, (dir < 0) == (t == TextDirection::Down));
}
let ext = extend(v);
let l = s.layout();
let from = s.sel.focus.clone();
@@ -528,7 +345,7 @@ fn select_all(s: &mut Session, v: &Value) -> CmdResult {
s.column_mode = false;
return sel_result(s);
}
if !p::bool(v, "whole").unwrap_or(true)
if !p::bool(v, "whole").unwrap_or(false)
&& let Some(r) = super::table::grow_select_all(s)
{
return r;
-7
View File
@@ -521,13 +521,6 @@ fn place(s: &mut Session, layout: &DocLayout, obj: InlineObject, page: usize, (x
float.y = y - origin.y;
}
para.touch();
if !on_page && let Some(offset) = super::objects::shifted_float_offset(s, &at, page, y, origin.y) {
super::objects::edit_obj(s, &at, |o| {
if let Some(float) = o.float_mut() {
float.y = offset;
}
})?;
}
Ok(at)
}
+1 -1
View File
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
sel_result(s)
})
.key("Mod+W / Mod+F4")
.params(r#"{"save"?: bool (desktop app's control channel and MCP bridge only: save the shown document, then close it; it does not apply to a background `doc`, which needs force or its own save first), "force"?: bool (desktop app's control channel and MCP bridge only: without save or force a document with unsaved changes is an error and stays open; with force the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
.params(r#"{"force"?: bool (desktop app's control channel and MCP bridge only: without it a document with unsaved changes is an error and stays open; with it the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
.pure(),
CommandSpec::new("file.closeDocument", "Close Document", "Agents", close_document)
.params(r#"{"id"?: n (an open document, see view.switchWindows; default the active one), "force"?: bool (discard unsaved changes; without it a document with unsaved changes is an error and stays open)} → {"closed": id, "active": id, "documents": [{"id", "title", "path", "dirty", "active"}]}; closing the last document leaves a new blank one"#)
+5 -23
View File
@@ -1,13 +1,12 @@
//! Character formatting (Home › Font).
use std::collections::HashMap;
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};
use wordcraft_doc::resolve::ResolvedChar;
use wordcraft_doc::{Document, InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use super::sel_result;
use super::tools::{is_turkic, lower_char, upper_char};
@@ -353,14 +352,11 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// Whether a toggle without a `value` turns its format on. A selection (including a selected
/// text box or a non-empty column block, whose `sel` is non-collapsed) follows its first
/// character in document order, as Word does: one that starts formatted loses the format, all of
/// it (#6516). A collapsed caret (including an empty column block) requires the whole word to
/// carry the format before toggling it off.
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
let chars = resolved(s);
if !s.sel.is_collapsed() {
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
return !chars.first().is_some_and(has);
}
!chars.iter().all(has)
@@ -428,7 +424,6 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
}
if let Some(n) = &ea {
c.font_ea = Some(n.clone());
c.font_ea_theme = None;
}
})
}
@@ -956,19 +951,6 @@ pub fn state(s: &Session) -> Value {
(*cached_state(s)).clone()
}
/// The common East Asian family shown by the font controls. If a slot has no face, keep
/// showing the named font. Resolve each theme slot once even for a selection with many runs.
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> Option<&'a str> {
let mut themes = HashMap::new();
let mut fonts = runs.iter().map(|run| {
run.font_ea_theme
.and_then(|slot| *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run)))
.or(run.font_ea.as_deref())
});
let first = fonts.next().flatten()?;
fonts.all(|font| font == Some(first)).then_some(first)
}
fn compute_state(s: &Session) -> Value {
let all = resolved(s);
let first = all.first().cloned();
@@ -989,7 +971,7 @@ fn compute_state(s: &Session) -> Value {
json!({
"font": font,
"fontShownAs": shown_as,
"fontEastAsia": selection_east_asian_font(&s.doc, &all),
"fontEastAsia": same(&|r| json!(r.font_ea)),
"size": same(&|r| json!(r.size)),
"bold": all.iter().all(shown_bold),
"italic": all.iter().all(shown_italic),
+3 -3
View File
@@ -16,8 +16,8 @@ mod objects;
pub(crate) use header_footer::saved_copy;
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
pub use items::{
DropCapState, default_date_picture, default_time_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in,
format_date_parts, format_date_parts_in,
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts,
format_date_parts_in,
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
.then_some("text boxes can't go inside a text box")
}),
CommandSpec::new("insert.link", "Link", "Insert › Links", link).key("Mod+K").params(
r#"{"url": string} | {"bookmark": name} | {"heading": block (see link.targets)} | {"top": true}, "text"?: string (Place in This Document: a bookmark, a heading or the top of the document); for every target, the result has a "warning" when a selection keeps its own text instead of "text""#,
r#"{"url": string} | {"bookmark": name} | {"heading": block (see link.targets)} | {"top": true}, "text"?: string (Place in This Document: a bookmark, a heading or the top of the document)"#,
),
CommandSpec::new("link.targets", "Link", "Insert › Links", link_targets).pure(),
CommandSpec::new("insert.removeLink", "Remove Hyperlink", "Insert › Links", |s, _| super::format::apply(s, &|c| {
-34
View File
@@ -218,8 +218,6 @@ struct DateNames {
days_short: [&'static str; 7],
/// The picture of a `DATE` field without `\@`.
default: &'static str,
/// The picture of a `TIME` field without `\@`.
default_time: &'static str,
}
const ENGLISH: DateNames = DateNames {
@@ -228,7 +226,6 @@ const ENGLISH: DateNames = DateNames {
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
default: "M/d/yyyy",
default_time: "h:mm am/pm",
};
/// Portuguese (observed in Word for Mac with a pt-BR document): lower-case names, `MMM` = `out`,
@@ -239,7 +236,6 @@ const PORTUGUESE: DateNames = DateNames {
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
default: "dd/MM/yyyy",
default_time: "h:mm am/pm",
};
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
@@ -250,7 +246,6 @@ const GERMAN: DateNames = DateNames {
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
default_time: "HH:mm",
};
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
@@ -261,7 +256,6 @@ const GERMAN_AUSTRIA: DateNames = DateNames {
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
default_time: "HH:mm",
};
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
@@ -285,12 +279,6 @@ pub fn default_date_picture(lang: Option<&str>) -> &'static str {
date_names(lang).default
}
/// The picture Word gives a `TIME` field that has no `\@` switch, in the field's language: German
/// shows the 24-hour clock (#8562).
pub fn default_time_picture(lang: Option<&str>) -> &'static str {
date_names(lang).default_time
}
/// Format a date and time with a Word picture; `days_since` (days since 1970-01-01) gives the weekday.
pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u32), days_since: i64) -> String {
format_date_parts_in(fmt, None, y, m, d, hms, days_since)
@@ -634,28 +622,6 @@ mod date_time_locale_tests {
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
}
/// A `TIME` field without `\@` shows the 24-hour clock in a German document and the 12-hour
/// clock in an English one (#8562).
#[test]
fn bare_time_field_follows_the_document_language() {
let refreshed = |lang: &str| {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("review.language", &json!({"lang": lang, "default": true})).unwrap();
s.run("insert.field", &json!({"instr": "TIME", "result": "stale"})).unwrap();
crate::cmd::references::refresh_date_fields(&mut s.doc);
let path = s.doc.para_paths(StoryRef::Body).remove(0);
let p = s.doc.para(StoryRef::Body, &path).unwrap();
let result = p.objects.iter().find_map(|o| if let InlineObject::Field { result, .. } = o { Some(result.clone()) } else { None });
result.expect("a TIME field")
};
for lang in ["de-DE", "de-AT", "de-CH"] {
let time = refreshed(lang);
assert!(time != "stale" && !time.contains("AM") && !time.contains("PM"), "{lang}: {time}");
}
let time = refreshed("en-US");
assert!(time.contains("AM") || time.contains("PM"), "en-US: {time}");
}
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
/// trailing full stop (#7146).
#[test]
-10
View File
@@ -75,21 +75,11 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
s.sel = Selection::caret(end);
s.pending = Some(CharProps::default());
} else {
// A Text to display that differs from the selection but can't retype it is not applied:
// the caller is told so rather than left to think it was (#8541).
let kept = p::str(v, "text").is_some_and(|t| !t.is_empty() && one_line_selection(s) != Some(t) && s.selected_text() != t);
let (a, b) = s.sel.ordered();
s.doc.format_range(&a, &b, &|c| {
c.link = Some(url.clone());
c.style = style.clone();
})?;
if kept {
const KEPT: &str = "Text to display was not applied: the selection is linked with its own text.";
s.status = KEPT.into();
let mut out = sel_result(s)?;
out["warning"] = json!(KEPT);
return Ok(out);
}
}
sel_result(s)
}
-25
View File
@@ -908,29 +908,4 @@ mod tests {
let spec = s.registry.get(TEXT).unwrap();
assert!(spec.mutates, "view.markdownSourceText mutates session and dirty state");
}
/// Verifies entering and applying Markdown Source keep the document intact and report errors
/// when Markdown conversion fails.
#[test]
fn failed_markdown_conversion_keeps_document_and_reports_error() {
let mut s = session(SAMPLE);
s.md_file = FileText::default();
let err = wordcraft_formats::with_shared_conversion_error("bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
assert!(err.to_string().contains("bridge failed"), "{err}");
assert!(s.md_source.is_none());
for skip in [1, 2] {
let err = wordcraft_formats::with_shared_conversion_error_after(skip, "bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
assert!(err.to_string().contains("bridge failed"), "skip={skip}: {err}");
assert!(s.md_source.is_none());
}
let mut s = session(SAMPLE);
s.run(TOGGLE, &json!({})).unwrap();
let before = body_text(&s);
set_text(&mut s, "# Replaced\n");
wordcraft_formats::with_shared_conversion_error("bridge failed", || apply(&mut s));
assert_eq!(body_text(&s), before, "failed apply leaves the document intact");
assert!(s.status.contains("bridge failed"), "{}", s.status);
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ mod shape;
mod specs;
pub use arrange::moves_with_text;
pub(crate) use arrange::{anchor_paragraph, nearest_line, shifted_float_offset};
pub(crate) use arrange::{anchor_paragraph, nearest_line};
#[cfg(test)]
use group::ungroup;
pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, original_size};
+1 -30
View File
@@ -212,29 +212,9 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
f.x = (x - origin.x).clamp(-MAX_OFFSET, MAX_OFFSET);
f.y = (y - origin.y).clamp(-MAX_OFFSET, MAX_OFFSET);
})?;
if let Some(offset) = shifted_float_offset(s, &at, page, y, origin.y) {
edit_float(s, &at, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
}
Ok(at)
}
/// A page-to-paragraph conversion can make a float move from the unpushed paragraph top to
/// the pushed first line. Once layout has resolved that choice, offset from the origin it used.
/// Leave other layout effects, such as wrapping settlement or a change of page, to the caller.
pub(crate) fn shifted_float_offset(s: &mut Session, at: &Pos, page: usize, y: f32, old_origin: f32) -> Option<f32> {
let offset = y - old_origin;
if offset >= 0.0
|| at.story != StoryRef::Body
|| at.path.depth() != 0
|| (!s.view.read_mode && !matches!(s.view.mode, wordcraft_layout::ViewMode::Print | wordcraft_layout::ViewMode::Read))
{
return None;
}
s.touch();
let hit = s.layout().object(at, page)?;
(hit.page == page && hit.origin.y > old_origin + 0.01 && (hit.rect.y - hit.origin.y - offset).abs() < 0.01).then_some(y - hit.origin.y)
}
/// Turn the selected floating object's alignment (left, centred, …) into an offset from its
/// column / paragraph that keeps it where it is, so it can be moved by an offset.
pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
@@ -265,12 +245,6 @@ pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
f.y = oy.clamp(-MAX_OFFSET, MAX_OFFSET);
}
})?;
if float.v_align.is_some()
&& float.v_rel != Anchor::Page
&& let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y)
{
edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
}
Ok(())
}
@@ -294,14 +268,11 @@ pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult {
let hit = s.layout().object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?;
// Paragraph offsets start at the paragraph's top (the hit's origin), page offsets at the page's.
let y = if with_text { hit.rect.y - hit.origin.y } else { hit.rect.y };
let mut o = edit_float(s, &pos, |f| {
let o = edit_float(s, &pos, |f| {
f.v_rel = if with_text { Anchor::Paragraph } else { Anchor::Page };
f.v_align = None;
f.y = y.clamp(-MAX_OFFSET, MAX_OFFSET);
})?;
if with_text && let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y) {
o = edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
}
Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)}))
}
+1 -6
View File
@@ -18,7 +18,6 @@ mod styles;
mod tabs_borders;
mod tools;
pub(super) use format::drop_direct_indents;
use format::{align, asian_typography, cur, direction, line_spacing, ls, set_align, set_props, tog};
pub use format::{cur as selection_para, fmt, indent, outdent};
pub use lists::{ListButtons, list_buttons, manage_list, touch_all};
@@ -167,17 +166,13 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("para.heading3", "Heading 3", "Home › Styles", |s, _| apply_style(s, &json!({"style": "Heading3"}))).key("Mod+Alt+3"),
CommandSpec::new("para.bullets", "Bullets", "Home › Paragraph", |s, v| list(s, v, ListKind::Bullet)).params(r#"{"kind"?: "bullet" | single char, "off"?: bool}"#).key("Mod+Shift+L"),
CommandSpec::new("para.numbering", "Numbering", "Home › Paragraph", |s, v| list(s, v, ListKind::Numbered))
.params(r#"{"kind"?: "numbered|numberedParen|outline|upperLetter|lowerLetter|lowerLetterDot|lowerRoman", "off"?: bool}"#),
.params(r#"{"kind"?: "numbered|numberedParen|upperLetter|lowerLetter|lowerRoman|outline", "off"?: bool}"#),
CommandSpec::new("para.multilevel", "Multilevel List", "Home › Paragraph", |s, v| list(s, v, ListKind::Legal)).params(r#"{"kind"?: "legal|outline"}"#),
CommandSpec::new("para.listLevel", "Change List Level", "Home › Paragraph › Bullets", |s, v| {
let lvl = p::u64(v, "level").unwrap_or(0).min(8) as u8;
fmt(s, &|p| {
if let Some(n) = p.numbering.as_mut() {
let moved = n.level != lvl;
n.level = lvl;
if moved {
format::drop_direct_indents(p);
}
}
})
})
+2 -24
View File
@@ -163,16 +163,6 @@ pub(super) fn set_props(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// A list item that moves to another level takes that level's indents: a direct indent (a ruler
/// drag, a pasted block, a Word file's `w:ind`) would otherwise win over them and leave the item
/// out of line with its level (#4287).
pub(in crate::cmd) fn drop_direct_indents(p: &mut ParaProps) {
p.indent_left = None;
p.indent_first = None;
p.indent_left_chars = None;
p.indent_first_chars = None;
}
pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
let a = s.sel.ordered().0;
let paths = crate::cmd::selected_paths(s);
@@ -184,13 +174,7 @@ pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
};
let para = s.doc.para_mut(a.story, &path)?;
match num {
Some(n) => {
let level = n.level.saturating_add(1).min(8);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
drop_direct_indents(&mut para.props);
}
}
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) }),
None => {
para.props.indent_left = Some(((left / tab).floor() + 1.0) * tab);
para.props.cancel_char_indents(true, false, false);
@@ -212,13 +196,7 @@ pub fn outdent(s: &mut Session, _: &Value) -> CmdResult {
};
let para = s.doc.para_mut(a.story, &path)?;
match num {
Some(n) => {
let level = n.level.saturating_sub(1);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
drop_direct_indents(&mut para.props);
}
}
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) }),
None => {
para.props.indent_left = Some((((left / tab).ceil() - 1.0) * tab).max(0.0));
para.props.cancel_char_indents(true, false, false);
+6 -17
View File
@@ -13,24 +13,13 @@ pub(super) fn list(s: &mut Session, v: &Value, default: ListKind) -> CmdResult {
.map(|p| s.doc.para(a.story, p).and_then(|x| s.doc.styles.resolve_para(&x.props).numbering).filter(|n| n.num != 0))
.collect();
let same_kind = |n: &NumRef| {
let want = wordcraft_doc::numbering::levels_for(kind);
// Is the list's level `i` (with this list's own overrides) the preset's level `i`?
let level_is = |i: u8, with_text: bool| match (s.doc.numbering.level(n.num, i), want.get(usize::from(i))) {
(Some(l), Some(w)) => {
s.doc.numbering.level(n.num, n.level).is_some_and(|l| {
let want = wordcraft_doc::numbering::levels_for(kind);
want.get(usize::from(n.level)).is_some_and(|w| {
(w.format == wordcraft_doc::section::NumFormat::Bullet) == (l.format == wordcraft_doc::section::NumFormat::Bullet)
// A named preset is the same one only in its number style and text: "1." and "A." are
// both `%1.`, so picking one over the other changes the list, not switches it off (#4281).
&& (!with_text || (w.text == l.text && w.format == l.format))
}
_ => false,
};
let named = p::str(v, "kind").is_some();
// A named preset is told by its first level as well as the paragraph's own, as deeper levels of
// two presets can look alike; unless the list starts with the other kind of marker (a bullet
// above numbers, or the reverse), where the paragraph's own level decides.
let is_bullet = |i: u8| s.doc.numbering.level(n.num, i).map(|l| l.format == wordcraft_doc::section::NumFormat::Bullet);
let one_kind_throughout = is_bullet(0) == is_bullet(n.level);
level_is(n.level, named) && (!named || !one_kind_throughout || level_is(0, true))
&& (p::str(v, "kind").is_none() || w.text == l.text)
})
})
};
let remove = off || (!current.is_empty() && current.iter().all(|n| n.as_ref().is_some_and(same_kind)));
if remove {
+1 -7
View File
@@ -54,13 +54,7 @@ type Reset = (fn(&CharProps) -> bool, fn(&mut CharProps));
const RESETS: [Reset; 24] = [
(|c| c.font.is_some(), |c| c.font = None),
(|c| c.font_cs.is_some(), |c| c.font_cs = None),
(
|c| c.font_ea.is_some() || c.font_ea_theme.is_some(),
|c| {
c.font_ea = None;
c.font_ea_theme = None;
},
),
(|c| c.font_ea.is_some(), |c| c.font_ea = None),
(|c| c.size.is_some(), |c| c.size = None),
(|c| c.size_cs.is_some(), |c| c.size_cs = None),
(|c| c.color.is_some(), |c| c.color = None),
+1 -1
View File
@@ -337,7 +337,7 @@ fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
match text {
Some(t) if !t.is_empty() => Ok(Pasted::Text(t)),
_ => Err(CmdError::ClipboardEmpty),
_ => Err(CmdError::Failed("the clipboard is empty".into())),
}
}
+7 -10
View File
@@ -402,7 +402,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
}
let mut updates: Vec<(usize, String)> = Vec::new();
for (k, o) in p.objects.iter().enumerate() {
let InlineObject::Field { instr, result, locked: false, .. } = o else { continue };
let InlineObject::Field { instr, locked: false, .. } = o else { continue };
// A table formula reads the cells around its own cell again.
if instr.trim_start().starts_with('=') {
if let Some((tp, r, c)) = path.cell()
@@ -425,15 +425,12 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
let created = s.doc.core.created.trim();
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
// document, never saved, has no creation date yet and saving stamps now. A
// file opened without one, or with one that can't be read, keeps any result
// it already has; when inserted with none, it shows today's date (the date
// a save would stamp).
let text = if name == "CREATEDATE"
&& let Some((unix, offset)) = created_at(created)
{
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
} else if name != "CREATEDATE" || result.is_empty() || (created.is_empty() && s.path.is_none()) {
// file opened without one, or with one that can't be read, keeps the result
// it has.
let text = if name != "CREATEDATE" || (created.is_empty() && s.path.is_none()) {
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
} else if let Some((unix, offset)) = created_at(created) {
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
} else {
continue;
};
@@ -607,7 +604,7 @@ fn created_at(stamp: &str) -> Option<(u64, i64)> {
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
fn default_picture(name: &str, lang: Option<&str>) -> String {
if name == "TIME" { crate::cmd::insert::default_time_picture(lang).into() } else { crate::cmd::insert::default_date_picture(lang).into() }
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
}
/// Most names SET fields give values.
const MAX_SET: usize = 10_000;
-110
View File
@@ -556,26 +556,6 @@ fn createdate_without_a_readable_creation_date() {
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
}
/// Inserting CREATEDATE into an opened file that has no creation date (plain text, Markdown, or a
/// DOCX without `dcterms:created`) shows today's date rather than an empty result, while an
/// existing field with a cached result keeps it.
#[test]
fn createdate_inserted_into_opened_file_without_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Notes"));
s.path = Some(std::env::temp_dir().join("notes.txt"));
s.doc.core.created.clear();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let expected = crate::cmd::insert::format_date("yyyy-MM");
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone()]);
// An unreadable creation date behaves the same way: cached results stay, empty ones fill in.
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone(), expected]);
}
#[test]
fn toc_tabs_ignore_nonentries() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
@@ -697,96 +677,6 @@ fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_paragraph() {
assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_)));
}
/// Inserting a table of contents in the middle of a document places the caret in the paragraph
/// right after the table and leaves the text above and below it unchanged.
#[test]
fn a_toc_inserted_in_the_middle_of_a_document_leaves_the_caret_after_it() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Intro\nAfter TOC\nChapter One\nBody below."));
s.run("select.text", &json!({"text": "Chapter One"})).unwrap();
s.run("styles.apply", &json!({"style": "Heading 1"})).unwrap();
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(1), off: 0 });
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
assert_eq!(start, 1, "the TOC must immediately follow Intro without an extra blank paragraph");
assert_eq!(s.doc.body[0].as_para().map(|p| p.plain_text()).as_deref(), Some("Intro"));
assert_eq!(
s.sel.focus,
Pos { story: StoryRef::Body, path: Path::top(end + 1), off: 0 },
"the caret must land in the paragraph right after the TOC"
);
let below: Vec<String> = s.doc.body[end + 1..].iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect();
assert_eq!(below, ["After TOC", "Chapter One", "Body below."]);
}
/// One undo removes both the table of contents and the empty paragraph `caret_after_toc` adds
/// when the table ends the document or comes right before a table, leaving no stray blank
/// paragraph behind.
#[test]
fn undoing_a_toc_removes_both_the_table_and_the_added_paragraph() {
let toc_instr = |s: &Session, i: usize| {
s.doc.body[i].as_para().and_then(|p| {
p.objects.iter().find_map(|o| match o {
InlineObject::Field { instr, .. } => Some(instr.clone()),
_ => None,
})
})
};
// Fresh insert on an empty document undoes in one step.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
assert!(toc_range(&s).is_some());
assert_eq!(s.undo_depth(), 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), 0);
assert!(toc_range(&s).is_none());
assert_eq!(s.doc.body.len(), 1);
assert_eq!(s.doc.plain_text(StoryRef::Body), "");
// Table ending the document: `caret_after_toc` appends an empty paragraph, and one undo
// removes both the replaced table and that added paragraph.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
while s.doc.body.len() > end + 1 {
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
}
let before_blocks = s.doc.body.len();
let depth = s.undo_depth();
s.run("references.toc", &json!({"levels": 3})).unwrap();
let (_, new_end) = toc_range(&s).unwrap();
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
assert_eq!(s.doc.body.len(), before_blocks + 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), depth);
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added trailing paragraph");
assert_eq!(toc_range(&s), Some((start, end)));
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
// Table right before another table: `caret_after_toc` inserts an empty paragraph before the
// table, and one undo removes both the replaced TOC and that added paragraph.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let (start, end) = toc_range(&s).unwrap();
while s.doc.body.get(end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())) {
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
}
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
let before_blocks = s.doc.body.len();
let depth = s.undo_depth();
s.run("references.toc", &json!({"levels": 3})).unwrap();
let (_, new_end) = toc_range(&s).unwrap();
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
assert_eq!(s.doc.body.len(), before_blocks + 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), depth);
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added paragraph before the table");
assert_eq!(toc_range(&s), Some((start, end)));
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
}
/// A fresh scratch directory for the file-name tests below.
#[cfg(not(target_arch = "wasm32"))]
fn filename_scratch_dir(tag: &str) -> std::path::PathBuf {
-2
View File
@@ -439,8 +439,6 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
s.doc.remove_block(StoryRef::Body, &at.path)?;
}
at.path.last()
} else if at.off == 0 {
at.path.last()
} else {
s.doc.split_paragraph(&at)?.path.last()
};
+11 -3
View File
@@ -19,8 +19,10 @@ pub use changes::{
DELETION_TEXT_CHARS, DeletionBalloon, deletion_balloons, format_changes, has_deletions, has_format_changes, move_changes, tracking_json,
};
use changes::{list_changes, nav_change, resolve_all_then, resolve_sel_then, tracking_options};
use comments::{
comment_at_caret, comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, validate_comment_id,
};
pub use comments::{comment_list, comment_range_at_caret};
use comments::{comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, resolve_comment};
use proofing::{all_issues, issue_at, next_issue, suggestions, thesaurus, word_count};
pub fn specs() -> Vec<CommandSpec> {
@@ -35,8 +37,14 @@ pub fn specs() -> Vec<CommandSpec> {
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", resolve_comment)
.params(r#"{"id"?: non-negative 32-bit JSON integer (a comment or reply; omit to use the caret), "value"?: bool (omit to toggle the whole thread)}"#),
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()))?;
let c = s.doc.comments.get_mut(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
sel_result(s)
})
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
+11 -67
View File
@@ -26,8 +26,7 @@ fn resolve_runs(para: &mut wordcraft_doc::Paragraph, from: usize, to: usize, pro
}
/// Accept or reject a revision range in one paragraph; `mark` includes its paragraph mark (and
/// the section break on it), `props` the paragraph's own formatting change. If the next
/// paragraph moves into this path, return how many bytes of this paragraph precede it.
/// the section break on it), `props` the paragraph's own formatting change.
fn resolve_para(
s: &mut Session,
story: StoryRef,
@@ -35,11 +34,11 @@ fn resolve_para(
(from, to): (usize, usize),
(mark, props): (bool, bool),
accept: bool,
) -> Result<Option<usize>, CmdError> {
) -> Result<(), CmdError> {
let para = s.doc.para_mut(story, path)?;
resolve_runs(para, from, to, props, accept)?;
if !mark {
return Ok(None);
return Ok(());
}
if para.mark.fmt_change.is_some() || para.section.as_ref().is_some_and(|x| x.fmt_change.is_some()) {
fmt_revisions::resolve_char(&mut para.mark, accept);
@@ -50,9 +49,8 @@ fn resolve_para(
}
let (ins, del) = (para.mark.ins, para.mark.del);
if ins.is_none() && del.is_none() {
return Ok(None);
return Ok(());
}
let prefix_len = para.len();
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
@@ -68,18 +66,15 @@ fn resolve_para(
if sectioned {
s.doc.remove_section_break(path.last());
}
if crate::cmd::remove_empty_para(s, story, path)? {
return Ok(Some(0));
}
if crate::cmd::join_next_para(s, story, path)? {
return Ok(Some(prefix_len));
if crate::cmd::remove_empty_para(s, story, path)? || crate::cmd::join_next_para(s, story, path)? {
return Ok(());
}
}
let para = s.doc.para_mut(story, path)?;
para.mark.ins = None;
para.mark.del = None;
para.touch();
Ok(None)
Ok(())
}
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
@@ -264,49 +259,7 @@ fn resolve_loose_blocks(blocks: &mut wordcraft_doc::Blocks, accept: bool) -> Res
Ok(())
}
/// Byte offset after resolving the runs in the endpoint's original paragraph. Only apply it
/// when paragraph removal or joining also moves the endpoint.
fn resolved_offset(s: &Session, end: &Pos, accept: bool) -> usize {
let Some(para) = s.doc.para_at(end) else { return end.off };
let removed: usize = para
.run_ranges()
.filter(|(_, c)| if accept { c.del.is_some() } else { c.ins.is_some() })
.map(|(range, _)| end.off.min(range.end).saturating_sub(range.start))
.sum();
end.off - removed
}
/// The next paragraph has moved into `path` (empty removal) or been appended to its surviving
/// prefix (join). Later siblings, including a table containing an endpoint, shift one block back.
fn remap_after_middle_paragraph(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, prefix_len: usize, offsets: &mut [usize; 2]) {
let depth = path.parent().len();
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(offsets) {
if end.story != story || !end.path.0.starts_with(path.parent()) {
continue;
}
let Some(&block) = end.path.0.get(depth) else { continue };
if block as usize > path.last() {
let mut dest = end.path.clone();
dest.0[depth] -= 1;
// An endpoint in a terminal paragraph removed earlier still uses terminal clamping.
if s.doc.para(story, &dest).is_none() {
continue;
}
if &dest == path {
*offset = offset.saturating_add(prefix_len);
}
end.path = dest;
} else if &end.path == path {
*offset = (*offset).min(prefix_len);
} else {
continue;
}
end.off = *offset;
}
}
fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let mut offsets = [&s.sel.anchor, &s.sel.focus].map(|end| resolved_offset(s, end, accept));
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for st in stories {
for path in s.doc.para_paths(st).into_iter().rev() {
@@ -316,18 +269,9 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
let prefix_len = resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing && remove_trailing_para(s, st, &path)? {
// Selection ends in the removed paragraph go to the end of the one before it;
// clamping later would keep their offsets in that paragraph's text (#8500).
for end in [&mut s.sel.anchor, &mut s.sel.focus] {
if end.story == st && end.path == path {
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
}
}
}
if let Some(prefix_len) = prefix_len {
remap_after_middle_paragraph(s, st, &path, prefix_len, &mut offsets);
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing {
remove_trailing_para(s, st, &path)?;
}
}
}
@@ -1013,7 +957,7 @@ fn resolve_sel(s: &mut Session, accept: bool, next: bool) -> CmdResult {
// A paragraph's mark is in the selection when the selection goes on past it.
let mark = path != b.path || caret_mark.as_ref() == Some(&path);
let props = (ranged && (path != b.path || to > from)) || caret_props.as_ref() == Some(&path);
let _ = resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
if ranged {
resolve_cell(s, a.story, &path, accept)?;
}
-23
View File
@@ -186,29 +186,6 @@ fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
ids
}
/// Resolve or reopen the whole discussion, even when the target is a reply. A toggle uses
/// the target's state, matching its Resolve/Reopen button even in a mixed-state file.
pub(super) fn resolve_comment(s: &mut Session, v: &Value) -> CmdResult {
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()))?;
let c = s.doc.comments.get(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
let resolved = p::bool(v, "value").unwrap_or(!c.resolved);
let mut root = id;
let mut seen = BTreeSet::new();
while seen.insert(root) {
match s.doc.comments.get(&root).and_then(|c| c.parent).filter(|p| s.doc.comments.contains_key(p)) {
Some(parent) => root = parent,
None => break,
}
}
for id in threads_of(s, [root]) {
if let Some(c) = s.doc.comments.get_mut(&id) {
c.resolved = resolved;
}
}
sel_result(s)
}
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
validate_comment_id(v)?;
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
+1 -141
View File
@@ -311,7 +311,7 @@ fn comment_range_at_caret_needs_the_caret_inside_the_range() {
assert_eq!(super::comment_range_at_caret(&s), Some(id), "inside the commented text");
s.run("select.text", &json!({"text": "three"})).unwrap();
assert_eq!(super::comment_range_at_caret(&s), None, "elsewhere in the paragraph");
assert_eq!(super::comments::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
assert_eq!(super::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
}
fn glyph_text(d: &[Draw]) -> String {
@@ -491,81 +491,6 @@ fn deletions_outside_the_body_stay_inline_when_revisions_go_in_balloons() {
assert_eq!(deletion_balloons(&s), vec![DeletionBalloon { at: Pos::body(0, at), author: "Ana".into(), text: "zeta".into() }]);
}
fn assert_revision_arrow_stops(s: &mut Session, story: wordcraft_doc::StoryRef, from: [usize; 2], to: [usize; 2]) {
use wordcraft_doc::{Path, Pos};
let pos = |off| Pos::new(story, Path::top(0), off);
for (key, start, end) in [("Right", from[0], to[0]), ("Left", from[1], to[1])] {
let cmd = s.registry.by_shortcut(key).unwrap().id;
for extend in [false, true] {
s.run("caret.set", &json!({"pos": pos(start)})).unwrap();
s.run(cmd, &json!({"extend": extend})).unwrap();
assert_eq!(s.sel.focus, pos(end), "{key}, Shift {extend}, from {start}");
assert_eq!(s.sel.anchor, pos(if extend { start } else { end }));
}
}
}
#[test]
fn horizontal_arrows_follow_revision_balloon_visibility_by_story() {
use wordcraft_doc::{Path, Pos, StoryRef};
let mut s = Session::new(Document::from_text("AQRSZ"));
let id = s.run("insert.header", &json!({"text": "ABCDZ"})).unwrap()["story"].as_u64().unwrap() as u32;
let header = StoryRef::Part(id);
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
for story in [StoryRef::Body, header] {
let at = |off| Pos::new(story, Path::top(0), off);
s.run("select.range", &json!({"anchor": at(1), "focus": at(4)})).unwrap();
s.run("text.delete", &json!({})).unwrap();
assert!(s.doc.para_at(&at(1)).unwrap().props_of_char(1).del.is_some());
}
s.run("review.trackingOptions", &json!({"balloons": "revisions"})).unwrap();
assert!(s.revisions_in_balloons());
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [5, 0]);
assert_revision_arrow_stops(&mut s, header, [1, 4], [2, 3]);
s.run("view.commentsPane", &json!({"value": true})).unwrap();
assert!(!s.revisions_in_balloons());
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
s.run("review.trackingOptions", &json!({"balloons": "inline"})).unwrap();
s.run("view.commentsPane", &json!({"value": false})).unwrap();
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
s.run("review.markup", &json!({"value": "noMarkup"})).unwrap();
for story in [StoryRef::Body, header] {
assert_revision_arrow_stops(&mut s, story, [1, 4], [5, 0]);
}
}
#[test]
fn horizontal_arrows_distinguish_hidden_deletions_from_hidden_move_sources() {
use wordcraft_doc::{Pos, Revision, RevisionKind, StoryRef};
let mut doc = Document::from_text("AxyuvZuv");
let deletion = Revision::new(RevisionKind::Delete, "Author", "");
let source = Revision { move_name: Some("Move1".into()), ..deletion.clone() };
let destination = Revision { kind: RevisionKind::Insert, ..source.clone() };
doc.revisions.extend([deletion, source, destination]);
doc.format_range(&Pos::body(0, 1), &Pos::body(0, 3), &|c| c.del = Some(0)).unwrap();
doc.format_range(&Pos::body(0, 3), &Pos::body(0, 5), &|c| c.del = Some(1)).unwrap();
doc.format_range(&Pos::body(0, 6), &Pos::body(0, 8), &|c| c.ins = Some(2)).unwrap();
let mut s = Session::new(doc);
for (delete_mark, move_from_mark, expected) in [
("strikethrough", "strikethrough", [2, 4]),
("hidden", "strikethrough", [4, 4]),
("strikethrough", "hidden", [2, 2]),
("hidden", "hidden", [6, 0]),
] {
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": delete_mark, "moveFromMark": move_from_mark})).unwrap();
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 5], expected);
}
}
fn body_para(s: &Session) -> &wordcraft_doc::Paragraph {
s.doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap()
}
@@ -1000,71 +925,6 @@ fn deleting_a_comment_deletes_replies_to_replies() {
assert_eq!(anchors(&s).len(), 2);
}
/// Resolving from the root, the caret or a nested reply changes the whole discussion in one
/// undo step. Reopening is also thread-wide, and unrelated discussions stay untouched.
#[test]
fn resolving_a_comment_changes_its_whole_thread() {
let mut s = Session::new(Document::from_text("first second"));
s.run("select.text", &json!({"text": "first"})).unwrap();
let root = s.run("review.newComment", &json!({"text": "root"})).unwrap()["id"].as_u64().unwrap();
let reply = s.run("review.reply", &json!({"id": root, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
let nested = s.run("review.reply", &json!({"id": reply, "text": "nested"})).unwrap()["id"].as_u64().unwrap();
s.run("review.reply", &json!({"id": root, "text": "sibling"})).unwrap();
s.run("select.text", &json!({"text": "second"})).unwrap();
let other = s.run("review.newComment", &json!({"text": "other"})).unwrap()["id"].as_u64().unwrap() as u32;
s.run("select.text", &json!({"text": "first"})).unwrap();
let before = s.doc.comments.clone();
let body = s.doc.body.clone();
let parts = s.doc.parts.clone();
let depth = s.undo_depth();
let mut resolved = before.clone();
for (id, c) in &mut resolved {
c.resolved = *id != other;
}
for params in [json!({"id": root, "value": true}), json!({}), json!({"id": nested})] {
s.run("review.resolveComment", &params).unwrap();
assert_eq!(s.doc.comments, resolved, "{params}: all replies resolve, not the other discussion");
assert_eq!(s.undo_depth(), depth + 1, "one undo step for the whole thread");
s.run("review.resolveComment", &json!({"id": reply, "value": true})).unwrap();
assert_eq!(s.undo_depth(), depth + 1, "resolving an already resolved thread adds no step");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, before, "one undo restores every comment");
s.run("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc.comments, resolved);
s.run("review.resolveComment", &json!({"id": nested})).unwrap();
assert_eq!(s.doc.comments, before, "toggling a reply reopens the whole thread");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, resolved);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, before);
}
assert_eq!(s.doc.body, body, "resolution leaves the body and anchors alone");
assert_eq!(s.doc.parts, parts, "resolution leaves the comments' text alone");
}
/// Imported comments can have mixed resolved flags, missing parents or a parent cycle. A
/// thread operation reconciles the connected comments without following a missing parent.
#[test]
fn resolving_a_comment_handles_mixed_state_and_broken_parent_links() {
use wordcraft_doc::Comment;
for parent in [None, Some(99), Some(2)] {
let mut doc = Document::new();
doc.comments.insert(0, Comment { resolved: true, parent, ..Default::default() });
doc.comments.insert(1, Comment { parent: Some(0), ..Default::default() });
doc.comments.insert(2, Comment { parent: Some(1), ..Default::default() });
doc.comments.insert(3, Comment { parent: Some(99), ..Default::default() });
let mut s = Session::new(doc);
s.run("review.resolveComment", &json!({"id": 2})).unwrap();
assert!(
s.doc.comments.iter().all(|(id, c)| c.resolved == (*id != 3)),
"a reply's Resolve action must not reopen its resolved parent: {parent:?}"
);
s.run("review.resolveComment", &json!({"id": 1, "value": false})).unwrap();
assert!(s.doc.comments.values().all(|c| !c.resolved), "{parent:?}");
}
}
/// A parent cycle (possible in a hostile file) doesn't hang Delete; both comments go.
#[test]
fn deleting_a_comment_in_a_parent_cycle_ends() {
+1 -1
View File
@@ -1,7 +1,7 @@
use super::cells::{cell, cell_at, grid_cols, row_ends, selected_cells};
use super::{CmdError, CmdResult, Paragraph, Path, Pos, Selection, Session, StoryRef, Value, sel_result};
/// Explicit staged select-all in a table: the cell, then its row, then the table. A nested table that
/// Ctrl+A in a table, as in Word: the cell, then its row, then the table. A nested table that
/// is already fully selected grows to the cell around it. Returns `None` when the next step is
/// the whole story (not in a table, or the top-level table is already selected).
pub(crate) fn grow_select_all(s: &mut Session) -> Option<CmdResult> {
+4 -4
View File
@@ -630,10 +630,10 @@ fn room_right(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget)
let Some(b) = boxes.iter().find(|b| b.story == target.story && b.table == outer && b.row == row && b.cell == cell) else {
return margin;
};
// A cell's right margin is on its right in a right-to-left table too, as the layout draws
// it (#6941): Word doesn't mirror cell margins.
let right_margin = wordcraft_layout::cell_margins(doc, t, row, cell)[3];
(b.rect.right() - right_margin).min(margin)
// A right-to-left table has its cells' start (left) margin on their right.
let m = wordcraft_layout::cell_margins(doc, t, row, cell);
let inset = if t.props.bidi_visual { m[1] } else { m[3] };
(b.rect.right() - inset).min(margin)
}
#[cfg(test)]
@@ -136,30 +136,6 @@ fn a_selected_column_is_edited_cell_by_cell() {
assert_eq!(s.cell_range().map(|r| r.cols), Some((1, 1)), "undo brings the column selection back");
}
/// Toggling a format on a selected table column follows the first character in document order (#8589).
#[test]
fn toggle_on_a_selected_table_column_follows_first_character() {
let toggled = |bold_row: usize| -> Vec<bool> {
let mut s = table_session(3, 3);
fill(&mut s);
let p = cell_pos(&s, bold_row, 1);
s.sel = Selection { anchor: p.clone(), focus: Pos { off: 4, ..p } };
s.run("format.bold", &json!({"value": true})).unwrap();
// Start from the bottom row so the caret is not on row 0.
s.sel = Selection::caret(cell_pos(&s, 2, 1));
s.run("table.selectColumn", &json!({})).unwrap();
s.run("format.bold", &json!({})).unwrap();
for r in 0..3 {
assert!(!bold(&s, r, 0) && !bold(&s, r, 2), "row {r}'s other cells stay plain");
}
(0..3).map(|r| bold(&s, r, 1)).collect()
};
// First row bold, later rows plain: Bold turns off across the column.
assert_eq!(toggled(0), vec![false, false, false]);
// First row plain, middle row bold: Bold turns on across the column.
assert_eq!(toggled(1), vec![true, true, true]);
}
/// Numbering a column numbers its cells as one list, like Word.
#[test]
fn numbering_a_column_makes_one_list() {
@@ -534,46 +510,6 @@ fn a_nested_tables_column_fits_within_its_cell() {
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
}
/// #8441: a right-to-left table keeps its cells' right margins on their right (#6941), so a
/// nested table in such a cell fits up to that cell's right margin, not its left one, when the
/// two differ.
#[test]
fn a_nested_tables_column_fits_within_a_right_to_left_cell() {
let mut s = rtl_table_session(1, 2);
s.sel = Selection::caret(cell_pos(&s, 0, 0));
s.run("insert.table", &json!({"rows": 1, "cols": 2})).unwrap();
let (inner, _, _) = s.sel.focus.path.cell().unwrap();
let outer = table_path(&s);
// A left margin of 20 pt and a right one of 2 pt; the nested table itself left to right.
s.doc.table_mut(StoryRef::Body, &outer).unwrap().rows[0].cells[0].props.margins = Some([0.0, 20.0, 0.0, 2.0]);
s.doc.table_mut(StoryRef::Body, &inner).unwrap().props.bidi_visual = false;
s.touch();
let rect = |s: &mut Session, table: &Path, cell: usize| {
s.layout().pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, table: t, row: 0, cell: c, .. } if t == table && *c == cell => Some(*rect),
_ => None,
})
.unwrap()
};
for col in [1, 0] {
let r = rect(&mut s, &inner, col);
s.run("table.fitColumn", &json!({"page": 0, "x": r.right(), "y": mid_y(r)})).unwrap();
}
s.run("text.insert", &json!({"text": "word ".repeat(40)})).unwrap();
let host = rect(&mut s, &outer, 0);
let (a, b) = (rect(&mut s, &inner, 0), rect(&mut s, &inner, 1));
assert!(b.right() < host.right() - 40.0, "{b:?} in {host:?}");
s.run("table.fitColumn", &json!({"page": 0, "x": a.right(), "y": mid_y(a)})).unwrap();
let b1 = rect(&mut s, &inner, 1);
let text_right = host.right() - 2.0;
assert!((b1.right() - text_right).abs() < 0.5, "the table fills its cell's text up to its right margin: {b1:?}, {text_right}");
let host1 = rect(&mut s, &outer, 0);
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
}
/// Pasting formatting onto a selected column leaves its text (it used to clear it).
#[test]
fn the_format_painter_keeps_a_selected_columns_text() {
+3 -15
View File
@@ -206,11 +206,7 @@ pub(super) fn tab(s: &mut Session, _: &Value) -> CmdResult {
&& n.num != 0
{
let para = s.doc.para_mut(f.story, &f.path)?;
let level = n.level.saturating_add(1).min(8);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut para.props);
}
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
para.touch();
return sel_result(s);
}
@@ -259,11 +255,7 @@ fn indent_by_tab(s: &mut Session, f: &Pos) -> CmdResult {
&& let Some(n) = r.numbering.filter(|n| n.num != 0)
{
let p = s.doc.para_mut(f.story, &f.path)?;
let level = n.level.saturating_add(1).min(8);
p.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut p.props);
}
p.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
p.touch();
return sel_result(s);
}
@@ -296,11 +288,7 @@ pub(super) fn back_tab(s: &mut Session, _: &Value) -> CmdResult {
let f = s.sel.focus.clone();
if let Some(n) = s.doc.para_at(&f).and_then(|x| x.props.numbering).filter(|n| n.num != 0) {
let para = s.doc.para_mut(f.story, &f.path)?;
let level = n.level.saturating_sub(1);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut para.props);
}
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) });
para.touch();
return sel_result(s);
}
+9 -20
View File
@@ -260,12 +260,12 @@ fn diff_notes(
}
for &new_id in &notes.inserted {
if let Some(part) = doc.parts.get_mut(&new_id) {
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins), &|_| {}))).collect();
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins)))).collect();
}
}
for &orig_id in &notes.deleted {
if let Some(part) = doc.parts.get_mut(&orig_id) {
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del), &|_| {}))).collect();
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del)))).collect();
}
}
}
@@ -443,18 +443,14 @@ fn diff_blocks(doc: &mut Document, old: &[Arc<Block>], new: &[Arc<Block>], ctx:
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(doc, pa, pb, ctx))),
_ => {
if let Some(x) = a {
out.push(Arc::new(mark_block(
x,
&|c| {
// An existing deletion is another author's: keep their revision
// stamp instead of re-attributing the paragraph to this compare.
c.del.get_or_insert(ctx.del);
},
&|_| {},
)));
out.push(Arc::new(mark_block(x, &|c| {
// An existing deletion is another author's: keep their revision
// stamp instead of re-attributing the paragraph to this compare.
c.del.get_or_insert(ctx.del);
})));
}
if let Some(x) = b {
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins), &|c| c.del = None)));
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins))));
}
}
}
@@ -1631,13 +1627,7 @@ fn block_text(b: &Block, depth: usize) -> String {
/// where the paragraph carries a section break or is the container's only paragraph. A
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
///
/// `mark` additionally updates each paragraph mark. A whole inserted block keeps only the
/// compare's insertion on its mark: a `del` the revised document's mark already carried (a pending
/// deletion by another author) must not survive next to the compare's `ins` — on accept the
/// deletion branch would resolve the inserted paragraph away (#6899). Run-level revisions of the
/// source block are left alone.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), mark: &dyn Fn(&mut CharProps)) -> Block {
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
let mut out = b.clone();
let mut todo = vec![&mut out];
while let Some(blk) = todo.pop() {
@@ -1646,7 +1636,6 @@ fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), mark: &dyn Fn(&mut CharProp
let len = p.len();
let _ = p.format(0, len, f);
f(&mut p.mark);
mark(&mut p.mark);
p.touch();
}
Block::Table(t) => {
+57 -158
View File
@@ -55,37 +55,6 @@ fn compare_marks_a_whole_paragraph_and_its_mark() {
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
}
#[test]
fn resolving_a_middle_paragraph_keeps_the_caret_with_its_text() {
for (original, revised, command) in [("A\nB\nC", "A\nNEW\nB\nC", "review.rejectAll"), ("A\nOLD\nB\nC", "A\nB\nC", "review.acceptAll")] {
let mut s = Session::new(Document::from_text(original));
s.run("review.compare", &json!({"text": revised})).unwrap();
s.sel = Selection::caret(Pos::body(2, 1));
s.run(command, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nC");
assert!(s.sel.is_collapsed());
assert_eq!(s.sel.focus, Pos::body(1, 1), "{command} keeps the caret after B");
s.run("text.insert", &json!({"text": "!"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB!\nC");
}
}
#[test]
fn accepting_a_middle_paragraph_join_keeps_the_backward_selection() {
let mut s = Session::new(Document::from_text("A\néDROP\nX🙂B\nC"));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.sel = Selection { anchor: Pos::body(1, "é".len()), focus: Pos::body(2, "X".len()) };
s.run("text.delete", &json!({})).unwrap();
s.sel = Selection { anchor: Pos::body(2, "X🙂".len()), focus: Pos::body(1, 0) };
s.run("review.acceptAll", &json!({"stopTracking": true})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\né🙂B\nC");
assert_eq!(s.sel.anchor, Pos::body(1, "é🙂".len()));
assert_eq!(s.sel.focus, Pos::body(1, 0));
s.run("text.insert", &json!({"text": "Q"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nQB\nC");
}
#[test]
fn compare_marks_an_empty_paragraphs_mark() {
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
@@ -161,24 +130,6 @@ fn compare_terminal_deleted_paragraph_resolves_fully() {
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
}
#[test]
fn resolving_a_selected_terminal_paragraph_puts_the_caret_before_it() {
// A selection inside the terminal paragraph that Reject All (insertion) or Accept All
// (deletion) removes ends as a caret at the end of the paragraph before it, not over the
// same offsets of that paragraph's text (#8500).
let cases = [("A\nKeep this", "A\nKeep this\nNEW", "review.rejectAll"), ("A\nKeep this\nOLD", "A\nKeep this", "review.acceptAll")];
for (orig, revised, cmd) in cases {
let mut s = Session::new(Document::from_text(orig));
s.run("review.compare", &json!({"text": revised})).unwrap();
s.sel = Selection { anchor: Pos::body(2, 0), focus: Pos::body(2, 3) };
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep this", "{cmd}");
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}");
s.run("text.insert", &json!({"text": "Z"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}");
}
}
#[test]
fn reject_all_keeps_an_empty_inserted_paragraph_between_tables() {
// An empty paragraph between two tables is not the container's last block: removing it
@@ -269,8 +220,16 @@ fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
}
#[test]
fn compare_keeps_terminal_paragraph_when_insertion_accepted_or_deletion_rejected() {
// Inserted last paragraph: accepting keeps it whole.
fn compare_marks_the_last_paragraphs_mark() {
// Inserted last paragraph: rejecting removes it whole.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.ins.is_some());
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
@@ -278,7 +237,15 @@ fn compare_keeps_terminal_paragraph_when_insertion_accepted_or_deletion_rejected
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
// Deleted last paragraph: rejecting keeps it whole.
// Deleted last paragraph: accepting removes it whole.
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.del.is_some());
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
@@ -1776,123 +1743,55 @@ fn compare_lcs_window_move_past_cap_does_not_cascade_false_revisions() {
assert_eq!(s.doc.plain_text(StoryRef::Body), revised);
}
fn assert_whole_block_mark_compare(from: &str, to: &str, expected_mid: &str, is_del: bool, preserve_bold: bool) {
let expected_empty = |text: &str| text.split('\n').filter(|line| line.is_empty()).count();
let from_len = from.split('\n').count();
let to_len = to.split('\n').count();
let mut s = Session::new(Document::from_text(from));
if preserve_bold && let Some(Block::Para(p)) = s.doc.body.get_mut(1).map(Arc::make_mut) {
p.mark.bold = Some(true);
}
s.run("review.compare", &json!({"text": to})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().expect("block 1 must be paragraph");
assert_eq!(mid.plain_text(), expected_mid);
if expected_mid.is_empty() {
assert_eq!(mid.len(), 0);
}
if is_del {
assert!(mid.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
} else {
assert!(mid.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
}
if preserve_bold {
assert_eq!(mid.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
}
let mut s_rej = Session::new(s.doc.clone());
s_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s_rej.doc.plain_text(StoryRef::Body), from);
assert_eq!(s_rej.doc.body.len(), from_len);
assert_eq!(empty_paras(&s_rej), expected_empty(from), "rejecting a whole-block revision changed empty paragraph count");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), to);
assert_eq!(s.doc.body.len(), to_len);
assert_eq!(empty_paras(&s), expected_empty(to), "accepting a whole-block revision changed empty paragraph count");
}
/// Verifies that `mark_block` records paragraph mark revisions on whole-block deletions,
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`
/// and `review.rejectAll`.
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`.
#[test]
fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes() {
// Whole block delete/insert: test with differing paragraph count so whole-block paths trigger
let orig_multi = "Keep start.\nDelete me.\nKeep end.";
let rev_multi = "Keep start.\nKeep end.";
assert_whole_block_mark_compare(orig_multi, rev_multi, "Delete me.", true, true);
assert_whole_block_mark_compare(rev_multi, orig_multi, "Delete me.", false, false);
let mut s2 = Session::new(Document::from_text(orig_multi));
if let Some(Block::Para(p)) = s2.doc.body.get_mut(1).map(Arc::make_mut) {
p.mark.bold = Some(true);
}
s2.run("review.compare", &json!({"text": rev_multi})).unwrap();
// In s2.doc.body, block 1 was deleted whole.
// Verify that p.mark.del is recorded by mark_block and formatting is preserved.
let del_para = s2.doc.body[1].as_para().expect("block 1 must be paragraph");
assert!(del_para.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
assert_eq!(del_para.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
// Accept all changes: deleted paragraph is removed
s2.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s2.doc.plain_text(StoryRef::Body), rev_multi);
// Test whole-block insertion
let mut s3 = Session::new(Document::from_text(rev_multi));
s3.run("review.compare", &json!({"text": orig_multi})).unwrap();
let ins_para = s3.doc.body[1].as_para().expect("block 1 must be paragraph");
assert!(ins_para.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
s3.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s3.doc.plain_text(StoryRef::Body), orig_multi);
// Test empty paragraph deletion and insertion (len == 0, where only mark carries the revision)
let orig_empty = "Before.\n\nAfter.";
let rev_empty = "Before.\nAfter.";
assert_whole_block_mark_compare(orig_empty, rev_empty, "", true, false);
assert_whole_block_mark_compare(rev_empty, orig_empty, "", false, false);
}
let mut s4 = Session::new(Document::from_text(orig_empty));
s4.run("review.compare", &json!({"text": rev_empty})).unwrap();
let empty_del = s4.doc.body[1].as_para().expect("empty paragraph block");
assert_eq!(empty_del.len(), 0);
assert!(empty_del.mark.del.is_some(), "empty paragraph deletion must set mark.del");
s4.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s4.doc.plain_text(StoryRef::Body), rev_empty);
/// Issue #6899: when the revised document's paragraph mark already carries another author's
/// pending deletion, a whole-paragraph insertion by compare must not leave the mark with both
/// `ins` and `del` — on accept the deletion branch would remove the inserted paragraph (or join
/// it away), losing the inserted break. The revised clone's mark keeps only the compare's `ins`.
#[test]
fn compare_inserted_paragraph_mark_drops_a_foreign_del() {
use wordcraft_doc::{Revision, RevisionKind};
let mut rev = Document::from_text("Keep start.\nNew line.\nKeep end.");
rev.revisions.push(Revision { kind: RevisionKind::Delete, author: "Other".into(), date: String::new(), date_utc: None, move_name: None });
if let Some(Block::Para(p)) = rev.body.get_mut(1).map(Arc::make_mut) {
p.mark.del = Some(0);
}
let path = std::env::temp_dir().join(format!("wc-compare-6899-{}.docx", std::process::id()));
crate::io::save_path(&path, &rev).unwrap();
let check = crate::io::open_path(&path).unwrap();
assert!(check.body[1].as_para().unwrap().mark.del.is_some(), "the foreign del must survive the docx round-trip, or this test proves nothing");
let mut s = Session::new(Document::from_text("Keep start.\nKeep end."));
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
let _ = std::fs::remove_file(&path);
let ins = s.doc.body[1].as_para().expect("block 1 is the inserted paragraph");
assert!(ins.mark.ins.is_some(), "compare marks the whole inserted paragraph's mark");
assert!(ins.mark.del.is_none(), "the foreign del does not sit next to the compare's ins");
// Accepting keeps the inserted paragraph break: the text reads as the revised document's.
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "Keep start.\nNew line.\nKeep end.");
}
/// Issue #6899, inside a table: `mark_block` recurses into cells, so a paragraph mark there gets
/// the same treatment — a foreign `del` does not sit next to the compare's `ins`.
#[test]
fn compare_inserted_table_cell_paragraph_mark_drops_a_foreign_del() {
use wordcraft_doc::{Revision, RevisionKind, Table};
let mut rev = Document::from_text("Keep start.\nKeep end.");
rev.revisions.push(Revision { kind: RevisionKind::Delete, author: "Other".into(), date: String::new(), date_utc: None, move_name: None });
let mut t = Table::new(1, 1, 200.0);
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut())
&& let Some(Block::Para(p)) = c.blocks.first_mut().map(Arc::make_mut)
{
p.mark.del = Some(0);
}
rev.body.insert(1, Arc::new(Block::Table(t)));
let path = std::env::temp_dir().join(format!("wc-compare-6899-table-{}.docx", std::process::id()));
crate::io::save_path(&path, &rev).unwrap();
let check = crate::io::open_path(&path).unwrap();
let cell_marked = check.body.iter().any(|b| match &**b {
Block::Table(t) => {
t.rows.iter().flat_map(|r| r.cells.iter()).flat_map(|c| c.blocks.iter()).any(|b| b.as_para().is_some_and(|p| p.mark.del.is_some()))
}
_ => false,
});
assert!(cell_marked, "the cell paragraph's foreign del must survive the docx round-trip, or this test proves nothing");
let mut s = Session::new(Document::from_text("Keep start.\nKeep end."));
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
let _ = std::fs::remove_file(&path);
let Some(Block::Table(t)) = s.doc.body.get(1).map(|b| &**b) else { panic!("block 1 is the inserted table") };
let cell_para = t.rows[0].cells[0].blocks[0].as_para().expect("the cell paragraph");
assert!(cell_para.mark.ins.is_some(), "compare marks the inserted cell paragraph's mark");
assert!(cell_para.mark.del.is_none(), "the foreign del does not sit next to the compare's ins");
s.run("review.acceptAll", &json!({})).unwrap();
assert!(matches!(s.doc.body.get(1).map(|b| &**b), Some(Block::Table(_))), "accepting keeps the inserted table");
let mut s5 = Session::new(Document::from_text(rev_empty));
s5.run("review.compare", &json!({"text": orig_empty})).unwrap();
let empty_ins = s5.doc.body[1].as_para().expect("empty paragraph block");
assert_eq!(empty_ins.len(), 0);
assert!(empty_ins.mark.ins.is_some(), "empty paragraph insertion must set mark.ins");
s5.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s5.doc.plain_text(StoryRef::Body), orig_empty);
}
#[test]
+1 -1
View File
@@ -509,7 +509,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
/// Largest document file opened by path.
#[cfg(not(target_arch = "wasm32"))]
const MAX_DOCUMENT: u64 = 2u64 << 30;
const MAX_DOCUMENT: u64 = 2 << 30;
/// The bytes of the document at `path`, read as `file.open` reads a path: inside the automation
/// read root, and only a regular file of at most 2 GB. A named pipe would block the open and a
+1 -18
View File
@@ -92,7 +92,7 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
// Output shows the fields Word fills in as it prints (see `output_fields`).
let out = crate::cmd::references::output_fields(doc);
let doc = out.as_ref().unwrap_or(doc);
Some(crate::strict::export_pdf(&pdf_document(doc), opts))
Some(crate::strict::export_pdf(doc, opts))
}
other => wordcraft_formats::export_with(other, doc, &wordcraft_formats::ExportOptions { comments: opts.markup && opts.comments }),
}
@@ -142,23 +142,6 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
Ok(img.to_png())
}
/// Supply an absent or unreadable PDF creation date without changing the document or advancing
/// its revision. This covers direct exports and web downloads, which do not pass through
/// `stamp_save`.
///
/// Unreadable, not only absent: the DOCX reader takes `core.created` as it finds it, so a file can
/// arrive carrying something like `not-a-date`. The PDF writer cannot put that in a document and
/// falls back to the clock, which is the one thing a pinned date is meant to stop -- so the
/// question asked here is the writer's own (`reads_as_date`), not whether the string is empty
/// (noted in review).
pub(crate) fn pdf_document(doc: &Document) -> std::borrow::Cow<'_, Document> {
let mut output = std::borrow::Cow::Borrowed(doc);
if !wordcraft_pdf::reads_as_date(&doc.core.created) {
output.to_mut().core.created = crate::cmd::saved_iso();
}
output
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
-2
View File
@@ -84,8 +84,6 @@ pub enum CmdError {
Params(String),
#[error("not available: {0}")]
Disabled(String),
#[error("the clipboard is empty")]
ClipboardEmpty,
#[error("{0}")]
Failed(String),
}
+1 -1
View File
@@ -243,7 +243,7 @@ impl Session {
compress: p::bool(v, "compress").unwrap_or(true),
..Default::default()
};
let bytes = wordcraft_pdf::export_layout(&crate::io_ext::pdf_document(doc), &lay, &opts).map_err(|e| CmdError::Failed(e.to_string()))?;
let bytes = wordcraft_pdf::export_layout(doc, &lay, &opts).map_err(|e| CmdError::Failed(e.to_string()))?;
Ok((bytes, plan))
}
}
+1 -1
View File
@@ -106,7 +106,7 @@ impl Session {
pub fn stamp_save(&mut self) {
self.doc.settings.zoom = crate::cmd::view::saved_zoom(&self.view);
let core = &mut self.doc.core;
core.modified = crate::cmd::saved_iso();
core.modified = crate::cmd::now_iso();
if core.created.is_empty() {
core.created = core.modified.clone();
}
+5 -19
View File
@@ -1,5 +1,3 @@
use wordcraft_layout::HideDeleted;
use super::doc_state::{Selection, TypedWord, typed_range};
use super::locale::SYSTEM_LOCALE;
use super::snapshot_types::LayoutEntry;
@@ -13,20 +11,6 @@ impl Session {
self.layout_with(typing)
}
fn revision_layout_options(&self) -> LayoutOptions {
LayoutOptions {
hide_deleted: !self.view.show_markup,
hide_marked: self.prefs.markup.hidden_deletions(),
deletions_in_balloons: self.revisions_in_balloons(),
..LayoutOptions::default()
}
}
/// Which tracked deletions the editor leaves out of this story.
pub(crate) fn layout_hides_deleted(&self, story: StoryRef) -> HideDeleted {
self.revision_layout_options().hides_deleted(story)
}
/// [`Session::layout`] with `typing` as the word being typed.
fn layout_with(&mut self, typing: Option<wordcraft_layout::TypingWord>) -> Arc<DocLayout> {
let mode = if self.view.read_mode { ViewMode::Read } else { self.view.mode };
@@ -39,8 +23,8 @@ impl Session {
let spacing = if self.view.read_mode { self.view.read_line_spacing.map(f32::to_bits) } else { None };
// Deletions in balloons depend on the view (the Comments pane, Read Mode, side by side), so
// a view change that moves them in or out of the text lays it out again.
let revisions = self.revision_layout_options();
let deleted = (revisions.hide_deleted, revisions.hide_marked, revisions.deletions_in_balloons);
let hide_deleted = !self.view.show_markup;
let deleted = (hide_deleted, self.prefs.markup.hidden_deletions(), self.revisions_in_balloons());
let outline = (mode == ViewMode::Outline).then(|| self.view.outline.view());
let shown = (self.view.marks || self.prefs.marks.hidden, self.view.field_codes);
// A dictionary or Language pack installed, removed or edited (in this document's window or
@@ -78,6 +62,9 @@ impl Session {
read_height: height,
read_line_spacing: spacing.map(f32::from_bits),
show_hidden: shown.0,
hide_deleted,
hide_marked: deleted.1,
deletions_in_balloons: deleted.2,
proofing: self.view.proofing,
numeral: self.view.numeral.resolve(SYSTEM_LOCALE.get().map(String::as_str)),
comment_balloons: false,
@@ -90,7 +77,6 @@ impl Session {
// The editor shows a body page reference as stored until fields are updated.
output_page_refs: false,
bookmark_error: None,
..revisions
};
let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts));
let [newest, _] = std::mem::take(&mut self.layout);
+91 -419
View File
@@ -293,6 +293,14 @@ fn custom_dictionary_words_persist_through_their_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn confined_sessions_test_is_native_only() {
let source = include_str!("tests.rs");
assert!(source.contains(
"#[cfg(not(target_arch = \"wasm32\"))]\n#[test]\nfn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots()"
));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
@@ -1110,79 +1118,6 @@ fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
assert_eq!(toggled(false, true), Some(false));
}
/// Toggling a format on a selected text box follows the first character of its text (#8589).
#[test]
fn toggle_on_a_selected_text_box_follows_first_character() {
let toggled = |first_bold: bool, second_bold: bool, leading_empty_bold: Option<bool>| -> String {
let mut s = s();
let id = run(&mut s, "insert.textBox", json!({}))["story"].as_u64().unwrap() as u32;
let boxed = StoryRef::Part(id);
if let Some(mark_bold) = leading_empty_bold {
s.doc.para_mut(boxed, &wordcraft_doc::Path::top(0)).unwrap().mark.bold = Some(mark_bold);
run(&mut s, "text.newParagraph", json!({}));
}
let text_block = usize::from(leading_empty_bold.is_some());
run(&mut s, "text.insert", json!({"text": "ab"}));
let box_pos = |off| Pos { story: boxed, path: wordcraft_doc::Path::top(text_block), off };
run(&mut s, "select.range", json!({"anchor": box_pos(0), "focus": box_pos(1)}));
run(&mut s, "format.bold", json!({"value": first_bold}));
run(&mut s, "select.range", json!({"anchor": box_pos(1), "focus": box_pos(2)}));
run(&mut s, "format.bold", json!({"value": second_bold}));
let anchor = s.doc.text_box_anchor(id).unwrap();
run(&mut s, "select.range", json!({"anchor": Pos { off: anchor.off - "\u{FFFC}".len(), ..anchor.clone() }, "focus": anchor}));
run(&mut s, "format.bold", json!({}));
let p = s.doc.para(boxed, &wordcraft_doc::Path::top(text_block)).unwrap();
(0..2).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
};
// First character bold, second plain: Bold turns off across the box.
assert_eq!(toggled(true, false, None), "..");
// First character plain, second bold: Bold turns on across the box.
assert_eq!(toggled(false, true, None), "BB");
// A bold empty paragraph at the top of the box does not override plain text after it.
assert_eq!(toggled(false, true, Some(true)), "BB");
}
/// Toggling a format on a column block follows the first character in document order (#8589).
#[test]
fn toggle_on_a_column_block_follows_first_character() {
let toggled = |bold_row: usize, top_to_bottom: bool| -> Vec<bool> {
let mut s = column_doc();
run(&mut s, "select.range", json!({"anchor": {"block": bold_row, "off": 2}, "focus": {"block": bold_row, "off": 4}}));
run(&mut s, "format.bold", json!({"value": true}));
let (a, f) = if top_to_bottom { (Pos::body(0, 2), Pos::body(2, 4)) } else { (Pos::body(2, 4), Pos::body(0, 2)) };
run(&mut s, "select.column", json!({"anchor": a, "focus": f}));
run(&mut s, "format.bold", json!({}));
(0..3).map(|i| s.doc.para_at(&Pos::body(i, 0)).unwrap().props_of_char(2).bold == Some(true)).collect()
};
// Row 0 bold, rows 1-2 plain: Bold turns off across the block even when selected bottom-to-top.
assert_eq!(toggled(0, true), vec![false, false, false]);
assert_eq!(toggled(0, false), vec![false, false, false]);
// Row 0 plain, row 1 bold: Bold turns on across the block even when selected bottom-to-top.
assert_eq!(toggled(1, true), vec![true, true, true]);
assert_eq!(toggled(1, false), vec![true, true, true]);
}
/// A collapsed caret inside a partly formatted word (including when column mode just started with
/// an empty block) turns the format on unless the whole word already has it (#8658).
#[test]
fn toggle_at_collapsed_caret_in_partly_formatted_word_turns_on() {
let toggled = |column_mode: bool| -> String {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Abc"}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 1}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 1}}));
if column_mode {
run(&mut s, "select.column", json!({}));
}
run(&mut s, "format.bold", json!({}));
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
(0..3).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
};
assert_eq!(toggled(false), "BBB");
assert_eq!(toggled(true), "BBB");
}
#[test]
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
@@ -3711,23 +3646,6 @@ fn tracked_table_changes_are_kept_as_formatting_changes() {
assert!(b && !ch, "Accept All keeps it");
}
#[test]
fn ctrl_a_inside_table_selects_document() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Before"}));
run(&mut s, "text.newParagraph", json!({}));
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
run(&mut s, "text.insert", json!({"text": "A1"}));
assert!(s.sel.focus.path.cell().is_some());
run(&mut s, "select.all", json!({}));
assert_eq!(s.sel.ordered(), (s.doc.start_of(StoryRef::Body), s.doc.end_of(StoryRef::Body)));
assert!(s.column.is_none());
assert!(s.selected_text().contains("Before"));
assert!(s.selected_text().contains("A1"));
}
#[test]
fn select_all_grows_cell_then_row_then_table_then_document() {
let mut s = s();
@@ -3737,24 +3655,24 @@ fn select_all_grows_cell_then_row_then_table_then_document() {
run(&mut s, "text.insert", json!({"text": "A1"}));
assert_eq!(s.sel.focus.path.cell().map(|(_, r, c)| (r, c)), Some((0, 0)));
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 0), (0, 0))), "first staged selection selects the cell");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 0), (0, 0))), "first Ctrl+A selects the cell");
assert_eq!(s.selected_text(), "A1");
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 0), (0, 1))), "second staged selection selects the row");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 0), (0, 1))), "second Ctrl+A selects the row");
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "third staged selection selects the table");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "third Ctrl+A selects the table");
run(&mut s, "select.all", json!({"whole": false}));
run(&mut s, "select.all", json!({}));
assert!(s.column.is_none());
let (a, b) = s.sel.ordered();
assert_eq!(a, s.doc.start_of(StoryRef::Body));
assert_eq!(b, s.doc.end_of(StoryRef::Body));
assert!(s.selected_text().starts_with("Before"));
run(&mut s, "select.all", json!({"whole": false}));
run(&mut s, "select.all", json!({}));
let (a, b) = s.sel.ordered();
assert_eq!((a, b), (s.doc.start_of(StoryRef::Body), s.doc.end_of(StoryRef::Body)));
}
@@ -3765,8 +3683,8 @@ fn select_all_from_a_column_grows_to_the_table() {
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
run(&mut s, "table.selectColumn", json!({}));
assert_eq!(cells(&s), Some(((0, 1), (0, 0))));
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "staged selection on a column selects the table");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "Ctrl+A on a column selects the table");
}
#[test]
@@ -5191,174 +5109,6 @@ fn no_markup_view_lays_out_the_final_text() {
assert!(gap(&mut s).abs() < 0.01);
}
#[test]
fn horizontal_caret_skips_hidden_tracked_deletions() {
let mut s = s();
let text = "Aé🧪ZUVΩT";
let before = Pos::body(0, "A".len());
let between = Pos::body(0, "Aé".len());
let after = Pos::body(0, "Aé🧪".len());
let far_start = Pos::body(0, "Aé🧪ZUV".len());
let far_end = Pos::body(0, "Aé🧪ZUVΩ".len());
run(&mut s, "document.setText", json!({"text": text}));
// Keep the adjacent deleted characters in separate formatting runs.
s.doc.format_range(&before, &between, &|c| c.bold = Some(true)).unwrap();
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "é🧪"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "select.text", json!({"text": "Ω"}));
run(&mut s, "text.delete", json!({}));
assert_eq!(s.doc.para_at(&before).unwrap().deleted_ranges(), [before.off..between.off, between.off..after.off, far_start.off..far_end.off]);
s.sel = crate::Selection::caret(before.clone());
run(&mut s, "caret.right", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé".len()), "visible markup still has ordinary caret stops");
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(before.clone());
run(&mut s, "caret.right", json!({"extend": true}));
assert_eq!(s.sel.anchor, before);
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪Z".len()), "Right crosses the next visible character in one step");
s.sel = crate::Selection::caret(after);
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0), "Left crosses the previous visible character in one step");
assert!(s.sel.is_collapsed());
s.sel = crate::Selection::caret(Pos::body(0, "Aé🧪Z".len()));
run(&mut s, "caret.right", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "a distant deletion does not change a visible stop");
s.sel = crate::Selection::caret(far_end);
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "Left also skips the later deletion");
}
#[test]
fn word_caret_skips_hidden_tracked_deletions() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "one two three"}));
let two_start = Pos::body(0, "one ".len());
let two_mid = Pos::body(0, "one tw".len());
let three_start = Pos::body(0, "one two ".len());
let end = Pos::body(0, "one two three".len());
// Keep the deleted word split across two formatting runs.
s.doc.format_range(&two_start, &two_mid, &|c| c.bold = Some(true)).unwrap();
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "two "}));
run(&mut s, "text.delete", json!({}));
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, two_start, "visible markup still stops at the deleted word");
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordRight", json!({"extend": true}));
assert_eq!(s.sel.anchor, Pos::body(0, 0));
assert_eq!(s.sel.focus, three_start, "Ctrl+Right skips the hidden deleted word in one press");
s.sel = crate::Selection::caret(two_start.clone());
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, end, "Ctrl+Right from the hidden start moves across the next visible word");
s.sel = crate::Selection::caret(end.clone());
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, three_start);
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left skips the hidden deleted word in one press");
s.sel = crate::Selection::caret(two_start);
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0));
// A deleted space between two visible word fragments joins them into one visible word.
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "foot ball next"}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": " "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
let next_start = Pos::body(0, "foot ball ".len());
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, next_start, "Ctrl+Right crosses a hidden deleted space inside a word");
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left crosses back over the joined word");
// Trailing and leading hidden deletions step to the neighbouring paragraph once no visible text remains.
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "alpha beta\ngamma delta"}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "beta"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "select.text", json!({"text": "gamma "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "alpha ".len()));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, Pos::body(1, 0), "Ctrl+Right before a trailing deletion crosses to the next paragraph");
s.sel = crate::Selection::caret(Pos::body(1, "gamma delta".len()));
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(1, "gamma ".len()));
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "alpha beta".len()), "Ctrl+Left after a leading deletion crosses to the previous paragraph");
// Multi-run paragraph with separately formatted words, a far-away deletion, and adjacent deleted runs.
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "alpha beta gamma delta epsilon zeta"}));
for word in ["alpha", "gamma", "epsilon"] {
run(&mut s, "select.text", json!({"text": word}));
run(&mut s, "format.bold", json!({}));
}
let beta_mid = Pos::body(0, "alpha be".len());
let gamma_start = Pos::body(0, "alpha beta ".len());
s.doc.format_range(&Pos::body(0, "alpha ".len()), &beta_mid, &|c| c.italic = Some(true)).unwrap();
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "beta "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "select.text", json!({"text": "epsilon "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
let expected_right = [
Pos::body(0, "alpha beta ".len()),
Pos::body(0, "alpha beta gamma ".len()),
Pos::body(0, "alpha beta gamma delta epsilon ".len()),
Pos::body(0, "alpha beta gamma delta epsilon zeta".len()),
];
s.sel = crate::Selection::caret(Pos::body(0, 0));
for expected in &expected_right {
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, *expected, "Ctrl+Right keeps the same visible word stops across formatted runs and far-away/adjacent deletions");
}
let expected_left =
[Pos::body(0, "alpha beta gamma delta epsilon ".len()), Pos::body(0, "alpha beta gamma ".len()), gamma_start, Pos::body(0, 0)];
for expected in &expected_left {
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, *expected, "Ctrl+Left keeps the same visible word stops across formatted runs and far-away/adjacent deletions");
}
// Word boundaries at paragraph edges preserve step_to_neighbor (do not skip a wholly deleted neighbor paragraph).
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "AB\nCD\nEF"}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 1), "focus": Pos::body(2, 1)}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(Pos::body(0, 1));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, Pos::body(1, 0), "Ctrl+Right at paragraph edge uses step_to_neighbor(skip_deleted=false)");
s.sel = crate::Selection::caret(Pos::body(2, 1));
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(1, "CD".len()), "Ctrl+Left at paragraph edge uses step_to_neighbor(skip_deleted=false)");
}
#[test]
fn replace_all_is_tracked() {
let mut s = s();
@@ -7312,56 +7062,6 @@ fn select_box(s: &mut Session) {
run(s, "select.range", json!({"anchor": o.pos(), "focus": end}));
}
#[test]
fn dragging_above_a_pushed_first_line_keeps_the_drop_position() {
use wordcraft_doc::para::{Anchor, Float, InlineObject, OBJ, ShapeKind, Wrap};
let shape = |w, h, float| InlineObject::Shape {
kind: ShapeKind::Rectangle,
w,
h,
fill: None,
stroke: None,
stroke_width: 1.0,
float,
story: None,
freeform: None,
effects: Default::default(),
extra: Default::default(),
};
for frame_wrap in [Wrap::TopAndBottom, Wrap::BehindText] {
// Original synthetic version of #6587's first-line push. Only the frame wraps text.
let mut doc = wordcraft_doc::Document::from_text("A line under a frame.");
let old_top = doc.last_section.margin_top;
let (x, y) = (120.0, old_top - 22.0);
let object = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: old_top + 12.0, ..Default::default() };
let frame = Float { wrap: frame_wrap, v_rel: Anchor::Paragraph, y: -20.0, ..Default::default() };
let at = Pos::body(0, 0);
let end = Pos::body(0, OBJ.len_utf8());
doc.insert_object(&at, shape(40.0, 18.0, object), &Default::default()).unwrap();
doc.insert_object(&end, shape(300.0, 250.0, frame), &Default::default()).unwrap();
let mut s = Session::new(doc);
run(&mut s, "select.range", json!({"anchor": at, "focus": end}));
run(&mut s, "arrange.bounds", json!({"page": 0, "x": x, "y": y}));
let hit = s.layout().object(&at, 0).unwrap();
assert!((hit.rect.y - y).abs() < 0.01 && (hit.rect.x - x).abs() < 0.01, "{frame_wrap:?}: {hit:?}");
assert_eq!(hit.origin.y > old_top + 1.0, frame_wrap == Wrap::TopAndBottom);
for (with_text, anchor) in [(false, Anchor::Page), (true, Anchor::Paragraph)] {
run(&mut s, "arrange.moveWithText", json!({"value": with_text}));
let hit = s.layout().object(&at, 0).unwrap();
let (_, _, float) = s.doc.para_at(&at).unwrap().object_at(at.off).unwrap().frame().unwrap();
assert_eq!(float.v_rel, anchor);
assert!((hit.rect.y - y).abs() < 0.01, "{frame_wrap:?}, {anchor:?}: {hit:?}");
let origin = if with_text { hit.origin.y } else { 0.0 };
assert!((hit.rect.y - origin - float.y).abs() < 0.01, "{frame_wrap:?}, {anchor:?}: {hit:?}");
}
run(&mut s, "draw.stroke", json!({"page": 0, "points": [[x, y], [x + 10.0, y]], "width": 2.0}));
let ink = s.layout().object(&at, 0).unwrap();
assert!((ink.rect.y - (y - 1.0)).abs() < 0.01, "{frame_wrap:?}: {ink:?}");
}
}
#[test]
fn arrange_bounds_resizes_and_moves_objects() {
use wordcraft_doc::para::{Anchor, Wrap};
@@ -10304,6 +10004,77 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
assert_eq!(text(&s), "Q");
}
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
#[test]
fn change_case_follows_turkic_language_mapping() {
// 1. Turkish (tr-TR): all 5 modes
// Capitalize Each Word (title)
let mut s = s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Işık");
// UPPERCASE
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
assert_eq!(text(&s), "İSTANBUL IŞIK");
// lowercase
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
assert_eq!(text(&s), "istanbul ışık");
// sentence case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
assert_eq!(text(&s), "İstanbul. Işık.");
// toggle case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
assert_eq!(text(&s), "iSTANBUL ıŞIK");
// 2. Azerbaijani (az-AZ)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 3. Crimean Tatar (crh)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 4. English control (en-US): unchanged Unicode default
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "Istanbul");
// 5. Mixed-language selection: Turkish run followed by English run
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
run(&mut s, "review.language", json!({"lang": "en-US"}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Istanbul");
}
#[test]
fn change_case_sentence_ignores_decimal_points() {
// #3485: Sentence case should not capitalize after decimal points.
@@ -12852,12 +12623,10 @@ fn outline_level_changes_are_undoable() {
assert!(s.run("outline.level", &json!({"level": 12})).is_err());
assert!(s.run("outline.level", &json!({})).is_err());
// Every outline command survives junk parameters in Outline view.
let reg = cmd::registry();
for spec in reg.all().iter().filter(|c| c.id.starts_with("outline.")) {
for spec in cmd::registry().all().iter().filter(|c| c.id.starts_with("outline.")) {
for j in [json!(null), json!({"block": 99999, "level": "x", "value": 5}), json!({"block": -1, "level": 0})] {
let mut s = outline_doc();
let r = s.run(spec.id, &j);
assert!(!caught_panic(&reg, &r), "{} panicked on {j}: {r:?}", spec.id);
let _ = s.run(spec.id, &j);
let _ = s.layout();
}
}
@@ -16397,100 +16166,3 @@ fn nested_group_text_box_survives_mutating_session_commands() {
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
}
}
#[test]
fn copy_refuses_to_fill_clipboard_by_halves_when_export_fails() {
let mut s = Session::new(wordcraft_doc::Document::from_text("first second"));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 5)}));
run(&mut s, "edit.copy", json!({}));
let prev_text = s.clipboard_text.clone();
let prev_html = s.clipboard_html.clone();
let prev_rtf = s.clipboard_rtf.clone();
let prev_history_len = s.clip_history.len();
assert_eq!(prev_text, "first");
assert!(!prev_html.is_empty() && !prev_rtf.is_empty());
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 6), "focus": Pos::body(0, 12)}));
// HTML export fails first.
let err = wordcraft_formats::with_shared_conversion_error("html failed", || s.run("edit.copy", &json!({}))).unwrap_err();
assert!(err.to_string().contains("html failed"), "{err}");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
assert_eq!(s.clip_history.len(), prev_history_len);
// HTML export succeeds and RTF export fails: clipboard still keeps "first" whole.
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.copy", &json!({}))).unwrap_err();
assert!(err.to_string().contains("rtf failed"), "{err}");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
assert_eq!(s.clip_history.len(), prev_history_len);
// Cut also refuses to delete the selection when export fails.
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.cut", &json!({}))).unwrap_err();
assert!(err.to_string().contains("rtf failed"), "{err}");
assert_eq!(text(&s), "first second");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clip_history.len(), prev_history_len);
}
#[test]
fn paste_reports_or_falls_back_when_html_import_fails() {
let mut s = Session::new(wordcraft_doc::Document::from_text("kept"));
let err = wordcraft_formats::with_shared_conversion_error("html import failed", || {
s.run("edit.pasteSpecial", &json!({"as": "html", "html": "<p>new</p>"}))
})
.unwrap_err();
assert!(err.to_string().contains("html import failed"), "{err}");
assert_eq!(text(&s), "kept");
let fallback = wordcraft_formats::with_shared_conversion_error_after(0, "html import failed", || {
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>", "rtf": "{\\rtf1 from rtf}"}))
});
assert_eq!(fallback.as_ref().map(|f| f.plain_text()), Some("from rtf".to_string()));
let none = wordcraft_formats::with_shared_conversion_error("html import failed", || {
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>"}))
});
assert!(none.is_none());
}
#[test]
fn open_and_save_report_format_conversion_errors() {
let doc = wordcraft_doc::Document::from_text("hello");
wordcraft_formats::with_shared_conversion_error("bridge down", || {
for (name, bytes) in [("a.html", b"<p>hello</p>" as &[u8]), ("a.md", b"# hello"), ("a.tex", b"hello")] {
let err = crate::io::open_bytes(name, bytes).unwrap_err();
assert!(err.contains("bridge down"), "{name}: {err}");
}
for name in ["a.html", "a.md", "a.tex", "a.rtf"] {
let err = crate::io::save_bytes(name, &doc).unwrap_err();
assert!(err.contains("bridge down"), "{name}: {err}");
}
});
}
#[test]
fn opening_open_document_files_reports_section_conversion_errors_without_replacing_the_document() {
let incoming = wordcraft_doc::Document::from_text("Incoming document");
let message = "OpenDocument page conversion failed";
for name in ["incoming.odt", "incoming.ott", "incoming.fodt"] {
let bytes = crate::io::save_bytes(name, &incoming).unwrap();
let params = json!({"path": name, "data": crate::cmd::insert::base64_encode(&bytes)});
let mut s = Session::new(wordcraft_doc::Document::from_text("Keep this document"));
let id = s.document_id();
let err = wordcraft_formats::with_shared_conversion_error(message, || s.run("file.open", &params)).unwrap_err();
assert!(err.to_string().contains(message), "{name}: {err}");
assert_eq!(s.document_id(), id, "{name}");
assert_eq!(text(&s), "Keep this document", "{name}");
run(&mut s, "file.open", params);
assert_eq!(text(&s), "Incoming document", "{name}");
}
}
-37
View File
@@ -226,27 +226,6 @@ fn arrow_keys_move_visually_in_rtl_text() {
assert_eq!(s.sel.focus.off, b.off);
}
#[test]
fn arrow_keys_skip_hidden_deletions_in_rtl_text() {
let text = "אבגדה";
let mut s = session(text, true);
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "בגד"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
for (command, from, to, direction) in [("caret.left", 0, text.len(), -1.0), ("caret.right", text.len(), 0, 1.0)] {
s.sel = crate::Selection::caret(Pos::body(0, from));
for _ in 0..2 {
let before = caret_x(&mut s);
run(&mut s, command, json!({}));
assert!((caret_x(&mut s) - before) * direction > 0.01, "{command} moves to the next visual stop");
assert!(s.sel.focus.off <= "א".len() || s.sel.focus.off >= "אבגד".len());
}
assert_eq!(s.sel.focus.off, to);
}
}
#[test]
fn arrow_keys_in_mixed_text_visit_each_position() {
// A left-to-right paragraph with a Persian word: Right walks across the screen.
@@ -274,22 +253,6 @@ fn word_moves_follow_reading_order() {
assert_eq!(s.sel.focus.off, 0);
}
#[test]
fn word_moves_skip_hidden_deletions_in_rtl_text() {
let mut s = session("אב גדה וז", true);
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "גדה "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
let third_word = "אב גדה ".len();
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus.off, third_word, "Ctrl+Left skips the hidden deleted word in RTL text");
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus.off, 0, "Ctrl+Right skips back across the hidden deleted word in RTL text");
}
#[test]
fn typing_persian_keeps_logical_order() {
let mut s = session("", true);
+8 -31
View File
@@ -179,57 +179,34 @@ fn fit_one_page_respects_max_delta() {
#[test]
fn fit_one_page_respects_step_pt() {
let set_size = |s: &mut Session, size_pt: f32| {
let at_11_4 = |lines: usize| {
let mut s = create_multiline_doc(lines);
for b in &mut s.doc.body {
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
p.mark.size = Some(size_pt);
p.mark.size = Some(11.4);
for r in &mut p.runs {
r.props.size = Some(size_pt);
r.props.size = Some(11.4);
}
}
}
s.touch();
s.relayout();
};
let at_size = |lines: usize, size_pt: f32| {
let mut s = create_multiline_doc(lines);
set_size(&mut s, size_pt);
s
};
// Find the most lines that fit on one page at 11.4 pt, spill the last paragraph at 11.1 pt
// so 0.1..0.3 pt reductions are not enough, then restore 11.4 pt so fitting requires 0.4 pt.
let mut lines = 10;
while at_size(lines + 1, 11.4).layout().pages.len() < 2 {
lines += 1;
assert!(lines < 120, "{lines} lines still fit on one page at 11.4 pt");
}
let mut s = at_size(lines, 11.1);
assert_eq!(s.layout().pages.len(), 1, "{lines} lines must fit on one page at 11.1 pt");
spill_last_paragraph(&mut s);
set_size(&mut s, 11.4);
let mut s = just_spilling(at_11_4);
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
assert_fixture_font(&mut s);
// Hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
// Both calls hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
// Default 0.5 pt step generates no candidates <= 0.4 pt, so it must fail.
let doc_backup = s.doc.clone();
let default_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "adjustSpacing": false}));
assert!(default_res.is_err(), "default step 0.5 must skip all candidates when maxDelta is 0.4");
// With stepPt = 0.1 and maxDeltaPt = 0.3, the document still spills onto page 2.
s.doc = doc_backup.clone();
s.touch();
let too_small_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.3, "stepPt": 0.1, "adjustSpacing": false}));
assert!(too_small_res.is_err(), "0.3 pt cap must not recover a document needing 0.4 pt");
// With stepPt = 0.1 under maxDeltaPt = 0.4, the 0.4 pt boundary step (11.4 -> 11.0 pt) succeeds.
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, a fine-grained step (0.1 to 0.4 pt) succeeds.
s.doc = doc_backup;
s.touch();
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "stepPt": 0.1, "adjustSpacing": false}));
assert!(res.is_ok(), "stepPt=0.1 must reach the 0.4 pt boundary step under maxDelta 0.4: {res:?}");
assert!(res.is_ok(), "stepPt=0.1 must generate fine-grained candidates under maxDelta 0.4: {res:?}");
assert_eq!(s.layout().pages.len(), 1);
assert!(s.status.contains("font: -0.4 pt"), "expected 0.4 pt reduction in status, got: {}", s.status);
}
#[test]
-24
View File
@@ -6,30 +6,6 @@ use wordcraft_doc::Pos;
use crate::Session;
use crate::cmd::insert::base64_encode;
#[test]
fn format_state_reports_the_east_asian_theme_face_and_keeps_unresolved_and_mixed_controls() {
use std::sync::Arc;
use wordcraft_doc::props::ThemeFont;
use wordcraft_doc::{Document, Path, StoryRef};
let mut doc = Document::from_text("漢字");
Arc::make_mut(&mut doc.styles).default_chr.font_ea = Some("Times New Roman".into());
doc.para_mut(StoryRef::Body, &Path::top(0))
.unwrap()
.format(0, "漢".len(), &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia))
.unwrap();
let mut fallback = Session::new(doc.clone());
fallback.run("select.all", &json!({})).unwrap();
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Times New Roman");
doc.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tExample CJK Face\n".to_vec()));
let mut s = Session::new(doc);
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, "漢".len())})).unwrap();
assert_eq!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Example CJK Face");
s.run("select.all", &json!({})).unwrap();
assert!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the theme face and named face differ");
}
/// The bundled face `file` of family `original` renamed `family` (as long as `original`), so it
/// is a font the database doesn't have.
fn renamed(file: &str, original: &str, family: &str) -> Vec<u8> {
+17 -296
View File
@@ -1598,20 +1598,11 @@ fn a_new_selection_drops_the_formatting_left_after_a_link() {
#[test]
fn a_link_over_two_paragraphs_keeps_their_text() {
// Word shows <<Selection in Document>> for such a selection: the text to display is ignored.
// The caller is told the text was not applied, not left to think it was (#8541).
let mut s = typed("one\ntwo");
run(&mut s, "select.all", json!({}));
let r = s.run("insert.link", &json!({"url": "https://example.org/", "text": "both"})).unwrap();
run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "both"}));
assert_eq!(texts(&s), ["one", "two"]);
assert_eq!(links(&s), [("One".into(), false), ("two".into(), false)]);
let warning = r.get("warning").and_then(|w| w.as_str()).unwrap_or_default();
assert!(!warning.is_empty(), "the result says the text was kept: {r}");
assert_eq!(s.status, warning, "the status line says the same");
// Text to display left as the selection shows it is no change, so there is nothing to report.
let mut s = typed("go see kiln now");
run(&mut s, "select.text", json!({"text": "see"}));
let r = s.run("insert.link", &json!({"url": "https://example.org/", "text": "see"})).unwrap();
assert!(r.get("warning").is_none(), "{r}");
}
#[test]
@@ -2416,57 +2407,6 @@ fn arrow(s: &mut Session, key: &str) {
run(s, id, if extend { json!({"extend": true}) } else { json!({}) });
}
#[test]
fn arrow_keys_skip_wholly_deleted_paragraphs_in_no_markup() {
for (text, last) in [("AB\nCD\nEF", 2), ("AB\nCD\nDE\nEF", 3)] {
let mut s = typed(text);
let after_a = Pos::body(0, 1);
let before_f = Pos::body(last, 1);
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": after_a, "focus": before_f}));
run(&mut s, "text.delete", json!({}));
for i in 1..last {
let middle = s.doc.para_at(&Pos::body(i, 0)).unwrap();
assert!(middle.mark.del.is_some() && middle.runs.iter().all(|r| r.props.del.is_some()));
}
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
for (from, key, shift, across, next) in [
(after_a.clone(), "Right", "Shift+Right", Pos::body(last, 0), Pos::body(last, 2)),
(before_f.clone(), "Left", "Shift+Left", Pos::body(0, 2), Pos::body(0, 0)),
] {
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, shift);
assert_eq!((&s.sel.anchor, &s.sel.focus), (&from, &across));
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert!(s.sel.is_collapsed());
assert_eq!(s.sel.focus, across);
arrow(&mut s, key);
assert_eq!(s.sel.focus, next);
}
run(&mut s, "review.markup", json!({"value": "allMarkup"}));
run(&mut s, "review.trackingOptions", json!({"balloons": "inline"}));
for (from, key, expected) in [(Pos::body(0, 2), "Right", Pos::body(1, 0)), (Pos::body(last, 0), "Left", Pos::body(last - 1, 2))] {
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert_eq!(s.sel.focus, expected);
}
}
}
#[test]
fn arrow_keys_stop_in_a_visible_empty_paragraph_in_no_markup() {
let mut s = typed("AB\n\nEF");
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
for (from, key) in [(Pos::body(0, 2), "Right"), (Pos::body(2, 0), "Left")] {
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert_eq!(s.sel.focus, Pos::body(1, 0));
}
}
/// The equation being edited and the caret in it.
fn editing(s: &Session) -> Option<(Pos, wordcraft_doc::math_edit::MathPos)> {
s.math.as_ref().map(|m| (m.at.clone(), m.pos.clone()))
@@ -2531,63 +2471,6 @@ fn left_and_right_keys_step_into_and_out_of_an_equation() {
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1)));
}
#[test]
fn arrow_keys_skip_a_deleted_equation_in_no_markup() {
let mut s = equations_between_a_and_b(1);
let before = Pos::body(0, 1);
let after = Pos::body(0, 1 + wordcraft_doc::para::OBJ.len_utf8());
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": before, "focus": after}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
let end = Pos::body(0, after.off + 1);
for (from, key, expected) in [(before, "Right", end), (after, "Left", Pos::body(0, 0))] {
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert!(editing(&s).is_none(), "{key} must not open a hidden equation");
assert_eq!(s.sel.focus, expected);
}
}
#[test]
fn arrow_keys_enter_a_visible_equation_across_a_hidden_deletion() {
use wordcraft_doc::math_edit::{MathPos, units};
let equation_width = wordcraft_doc::para::OBJ.len_utf8();
let before = "a".len();
let after = "aé".len();
let end = MathPos::new(Vec::new(), units(&wordcraft_doc::math::parse_linear("x+y")));
for markup in ["noMarkup", "allMarkup"] {
for (key, shift_key, equation, from, across, math_pos) in [
("Right", "Shift+Right", after, before, after + equation_width, MathPos::default()),
("Left", "Shift+Left", before, after + equation_width, before, end.clone()),
] {
let mut s = typed("aéb");
let from = Pos::body(0, from);
let equation = Pos::body(0, equation);
run(&mut s, "caret.set", json!({"pos": equation}));
run(&mut s, "insert.equation", json!({"linear": "x+y", "edit": false}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "é"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": markup}));
if markup == "allMarkup" {
run(&mut s, "review.trackingOptions", json!({"balloons": "inline", "deleteMark": "hidden"}));
}
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, shift_key);
assert!(editing(&s).is_none(), "{shift_key} extends the selection");
assert_eq!((s.sel.anchor.clone(), s.sel.focus.clone()), (from.clone(), Pos::body(0, across)));
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert_eq!(editing(&s), Some((equation, math_pos)), "{key} with {markup}");
}
}
}
#[test]
fn right_out_of_an_equation_steps_into_the_one_beside_it() {
let e = wordcraft_doc::para::OBJ.len_utf8();
@@ -3582,11 +3465,11 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
fn change_case_follows_turkic_case_mapping() {
for tag in ["tr-TR", "az-AZ", "crh"] {
for (mode, input, want) in [
("upper", "istanbul ışık", "İSTANBUL IŞIK"),
("lower", "İSTANBUL IŞIK", "istanbul ışık"),
("title", "istanbul ışık", "İstanbul Işık"),
("sentence", "istanbul. izmir. ışık.", "İstanbul. İzmir. Işık."),
("toggle", "iIİı", "İıiI"),
("upper", "istanbul", "İSTANBUL"),
("lower", "IŞIK", "ışık"),
("title", "istanbul güzel", "İstanbul Güzel"),
("sentence", "istanbul. izmir", "İstanbul. İzmir"),
("toggle", "iI", "İı"),
] {
let mut s = s();
run(&mut s, "review.language", json!({"lang": tag, "default": true}));
@@ -3603,20 +3486,17 @@ fn change_case_follows_turkic_case_mapping() {
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(s.doc.plain_text(StoryRef::Body), "Istanbul", "en-US");
// Mixed runs: each run's own language decides.
for (mode, first, second, want) in [
("lower", "IŞIK ", "IŞIK", "ışık işik"),
("title", "istanbul ", "istanbul", "İstanbul Istanbul"),
("upper", "istanbul ", "istanbul", "İSTANBUL ISTANBUL"),
] {
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
run(&mut s, "text.insert", json!({"text": first, "raw": true}));
run(&mut s, "review.language", json!({"lang": "en-US"}));
run(&mut s, "text.insert", json!({"text": second, "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": mode}));
assert_eq!(s.doc.plain_text(StoryRef::Body), want, "mixed runs {mode}");
}
let mut s = self::s();
run(&mut s, "text.insert", json!({"text": "IŞIK IŞIK", "raw": true}));
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 5), "extend": true}));
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 6)}));
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 11), "extend": true}));
run(&mut s, "review.language", json!({"lang": "en-US"}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
assert_eq!(s.doc.plain_text(StoryRef::Body), "ışık işik", "mixed runs");
}
// Spelling as you type (#1552): the word being typed gets no red squiggle until the caret leaves
@@ -4648,149 +4528,6 @@ fn issues_1281_1045_english_dialects_proof_typed_text() {
assert_eq!(words, ["21th"]);
}
/// #4281: Home › Numbering offers every preset, "a. b. c." among them, and picking another preset
/// for a list that is already numbered changes its style (only picking the same one again turns it off).
#[test]
fn the_numbering_gallery_presets_each_apply_and_switch_between_each_other() {
let labels = |s: &mut Session| numbers(s).into_iter().map(|(l, _)| l.unwrap_or_default()).collect::<Vec<_>>();
for (kind, want) in [
("numbered", ["1.", "2.", "3."]),
("numberedParen", ["1)", "2)", "3)"]),
("outline", ["I.", "II.", "III."]),
("upperLetter", ["A.", "B.", "C."]),
("lowerLetter", ["a)", "b)", "c)"]),
("lowerLetterDot", ["a.", "b.", "c."]),
("lowerRoman", ["i.", "ii.", "iii."]),
] {
let mut s = s();
typ(&mut s, "One\nTwo\nThree");
run(&mut s, "select.all", json!({}));
run(&mut s, "para.numbering", json!({"kind": kind}));
assert_eq!(labels(&mut s), want, "{kind}");
// Picking the same preset again turns the list off.
run(&mut s, "para.numbering", json!({"kind": kind}));
assert_eq!(labels(&mut s), ["", "", ""], "{kind} again");
}
// From one preset to another: the list changes style, it doesn't go off.
let mut s = s();
typ(&mut s, "One\nTwo\nThree");
run(&mut s, "select.all", json!({}));
run(&mut s, "para.numbering", json!({"kind": "numbered"}));
for (kind, want) in [("upperLetter", "A."), ("lowerLetterDot", "a."), ("lowerRoman", "i."), ("outline", "I."), ("numbered", "1.")] {
run(&mut s, "para.numbering", json!({"kind": kind}));
assert_eq!(labels(&mut s)[0], want, "to {kind}");
}
}
/// #4281: whatever level a list item is on, picking a different Numbering preset changes the list
/// and never turns it off; deeper levels of two presets can look alike.
#[test]
fn another_numbering_preset_never_switches_a_list_off_at_any_level() {
let kinds = ["numbered", "numberedParen", "outline", "upperLetter", "lowerLetter", "lowerLetterDot", "lowerRoman"];
for a in kinds {
for b in kinds.into_iter().filter(|b| *b != a) {
for level in 0..9 {
let mut s = s();
typ(&mut s, "One");
run(&mut s, "para.numbering", json!({"kind": a}));
run(&mut s, "para.listLevel", json!({"level": level}));
run(&mut s, "para.numbering", json!({"kind": b}));
let label = numbers(&mut s).into_iter().next().and_then(|(l, _)| l);
assert!(label.is_some(), "{a} -> {b} at level {level} turned the list off");
}
}
}
}
/// Where the first paragraph's list label starts (points from the page's text edge), and where its text starts.
fn label_and_text_x(s: &mut Session) -> (f32, f32) {
let l = s.layout();
l.pages
.iter()
.flat_map(|p| &p.items)
.find_map(|i| {
if let wordcraft_layout::Placed::Lines { para, l0: 0, .. } = i {
// The text starts where the first cluster is placed, after the label's suffix or tab stop.
para.label.as_ref().and_then(|lb| para.lines.first().and_then(|line| line.xs.first().map(|&x| (lb.x, x))))
} else {
None
}
})
.expect("a list label")
}
/// #4287: changing a list item's level (Change List Level, Tab, Shift+Tab) puts it at the new level's
/// indent, also when it carried a direct indent (a ruler drag, a pasted block, a Word file's `w:ind`).
#[test]
fn changing_a_list_level_drops_a_direct_indent() {
// The reference: a fresh list item moved to level 2 with no direct indent in the way.
let fresh = |command: &str, params: serde_json::Value| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
run(&mut s, command, params);
label_and_text_x(&mut s)
};
let dragged = |command: &str, params: serde_json::Value| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
// The ruler's left-indent marker dragged to a custom place.
run(&mut s, "para.indents", json!({"left": 120.0, "firstLine": -6.0}));
run(&mut s, command, params);
label_and_text_x(&mut s)
};
for (command, params) in [("para.listLevel", json!({"level": 1})), ("para.indent", json!({}))] {
assert_eq!(dragged(command, params.clone()), fresh(command, params), "{command}");
}
// Tab at the start of the item takes it down a level the same way.
let tabbed = |drag: bool| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
if drag {
run(&mut s, "para.indents", json!({"left": 120.0, "firstLine": -6.0}));
}
run(&mut s, "caret.home", json!({}));
run(&mut s, "text.tab", json!({}));
label_and_text_x(&mut s)
};
assert_eq!(tabbed(true), tabbed(false), "text.tab");
// Shift+Tab takes it back up.
let backtabbed = |drag: bool| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
run(&mut s, "para.listLevel", json!({"level": 1}));
if drag {
run(&mut s, "para.indents", json!({"left": 200.0, "firstLine": -30.0}));
}
run(&mut s, "text.backTab", json!({}));
label_and_text_x(&mut s)
};
assert_eq!(backtabbed(true), backtabbed(false), "text.backTab");
// Back out (Shift+Tab) from level 2 to 1 as well.
let back = |drag: bool| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
run(&mut s, "para.listLevel", json!({"level": 1}));
if drag {
run(&mut s, "para.indents", json!({"left": 200.0, "firstLine": -30.0}));
}
run(&mut s, "para.outdent", json!({}));
label_and_text_x(&mut s)
};
assert_eq!(back(true), back(false), "para.outdent");
// A ruler drag with no level change sticks.
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
let before = label_and_text_x(&mut s);
run(&mut s, "para.indents", json!({"left": 120.0, "firstLine": -6.0}));
assert_ne!(label_and_text_x(&mut s), before, "the drag moves the item");
}
/// #6788: Enter in a paragraph with a drop cap makes a normal paragraph; only the first keeps
/// the cap (Word behaviour), for a dropped cap and one in the margin.
#[test]
@@ -4812,19 +4549,3 @@ fn enter_in_a_drop_cap_paragraph_makes_a_normal_paragraph() {
assert_eq!(second.drop_cap_font, None, "{position}");
}
}
/// #8986: in top-to-bottom text Left/Right change line (lines stack leftwards), keeping the
/// distance along the line, and stop at the first/last line of a table cell.
#[test]
fn arrows_in_vertical_text_change_line_and_stop_in_a_cell() {
let mut d = wordcraft_doc::Document::from_text("abc\ndef");
d.last_section.text_direction = wordcraft_doc::props::TextDirection::Down;
let mut s = Session::new(d);
s.sel = crate::Selection::caret(Pos::body(0, 1));
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel.focus, Pos::body(1, 1), "Left goes to the next, leftward line");
run(&mut s, "caret.right", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 1));
run(&mut s, "caret.left", json!({"extend": true}));
assert!(!s.sel.is_collapsed(), "Shift+Left extends over the line change");
}
+33
View File
@@ -183,6 +183,18 @@ fn german_date_fields_inherit_the_document_default_language() {
}
}
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
#[test]
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
const PICTURE: &str = "ddd, d. MMM yyyy";
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
// The abbreviations at a fixed date, independent of when the test runs.
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
}
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
/// English result cached in the fixture is replaced with German weekday and month names.
#[test]
@@ -195,6 +207,27 @@ fn a_german_time_field_uses_german_names() {
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
/// of the same formatter at a fixed January instant.
#[test]
fn austrian_german_documents_use_jaenner() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
}
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
/// FIB, one compressed text piece, and the Clx that points at it.
fn binary_doc_with_stale_date() -> Vec<u8> {
-11
View File
@@ -224,17 +224,6 @@ impl FontDb {
log::debug!("cataloged {n} system font faces");
*self.catalog.write().unwrap_or_else(std::sync::PoisonError::into_inner) = found;
self.catalog_gen.fetch_add(1, Ordering::AcqRel);
{
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
sys.tried.clear();
sys.misses.clear();
}
self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner).map.clear();
{
let mut rf = self.run_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
rf.map.clear();
rf.chars = 0;
}
n
}
+7 -4
View File
@@ -82,12 +82,12 @@ pub struct FontFace {
/// than the full-width figure in the table. Word's automatic spacing between East Asian and
/// Latin text is half of it (see `wordcraft_layout::para::grid::auto_space`).
pub avg_char_width: f64,
/// The shaper's view of the face, at the named instance's location for variable fonts.
pub hb: harfrust::Font,
/// Variable fonts: the named instance's axis settings (user units; empty = default instance)
/// and the normalised location.
pub shaper: harfrust::ShaperData,
/// Variable fonts: the named instance's axis settings (user units; empty = default instance),
/// the normalised location and the shaper's view of it.
pub coords: Vec<([u8; 4], f32)>,
pub(super) location: Location,
pub instance: Option<harfrust::ShaperInstance>,
/// Basic Multilingual Plane coverage bitset, built on first use.
pub(super) bmp: std::sync::OnceLock<Box<[u64]>>,
// Some legacy CJK fonts assemble their contours with TrueType instructions.
@@ -205,6 +205,9 @@ impl FontFace {
pub fn skrifa(&self) -> Option<skrifa::FontRef<'_>> {
skrifa::FontRef::from_index(self.data(), self.index).ok()
}
pub fn hb(&self) -> Option<harfrust::FontRef<'_>> {
harfrust::FontRef::from_index(self.data(), self.index).ok()
}
/// Where in the design space glyphs, metrics and outlines come from.
pub fn location(&self) -> LocationRef<'_> {
(&self.location).into()
+1 -1
View File
@@ -98,7 +98,7 @@ impl FontDb {
#[cfg(not(target_arch = "wasm32"))]
{
let enabled = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled;
if enabled && self.family_maps(FAMILY, c) {
if enabled {
self.load_cataloged(FAMILY);
}
}
+6 -7
View File
@@ -418,12 +418,10 @@ pub(super) fn make_face(
let location = if coords.is_empty() { Location::default() } else { f.axes().location(settings.iter().copied()) };
let m = f.metrics(Size::unscaled(), &location);
let a = f.attributes();
let source: harfrust::font::Source = match &bytes {
FontBytes::Static(b) => (*b).into(),
FontBytes::Owned(v) => (v.clone() as Arc<dyn AsRef<[u8]> + Send + Sync>).into(),
};
let hb = harfrust::Font::new(source, index)?;
let hb = if coords.is_empty() { hb } else { hb.instance_builder().variations(coords.iter().map(|(t, v)| (harfrust::Tag::new(t), *v))).build() };
let hb = harfrust::FontRef::from_index(data, index).ok()?;
let shaper = harfrust::ShaperData::new(&hb);
let instance = (!coords.is_empty())
.then(|| harfrust::ShaperInstance::from_variations(&hb, settings.iter().map(|(t, v)| harfrust::Variation { tag: *t, value: *v })));
let axis = |tag: &[u8; 4]| coords.iter().find(|(t, _)| t == tag).map(|(_, v)| *v);
// Old releases of heavy faces (Arial Black in the core fonts) claim weight 400 where current
// ones say 900, which Word doesn't embolden: a family named for its weight is that heavy.
@@ -449,9 +447,10 @@ pub(super) fn make_face(
cap_height: m.cap_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.72),
x_height: m.x_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.5),
avg_char_width: avg_char_width(&f, upem),
hb,
shaper,
coords,
location,
instance,
bytes,
index,
bmp: std::sync::OnceLock::new(),
-33
View File
@@ -1018,39 +1018,6 @@ fn catalog_postscript_names() {
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn cataloged_family_without_glyph_is_not_loaded_by_fallback_and_rescan_clears_misses() {
struct Cleanup(std::path::PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = std::env::temp_dir().join(format!("wc-sysfonts-{}-cmap-skip-and-rescan", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let _cleanup = Cleanup(dir.clone());
// SourceSerif4-Regular lacks '●' (\u{25CF}): cataloging it under Times New Roman and Arial
// must not cause circle_fallback or system_fallback to load those families when searching for '●'.
std::fs::write(dir.join("TNR.ttf"), named_face("SourceSerif4-Regular.ttf", "Times New Roman")).unwrap();
std::fs::write(dir.join("Arial.ttf"), named_face("SourceSerif4-Regular.ttf", "Arial")).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
db.faces.write().unwrap().retain(|face| face.family == "Source Serif 4");
let primary = db.face("Source Serif 4", "Regular");
assert!(db.fallback_for('●', primary.id()).is_none(), "no loaded or cataloged face covers '●'");
assert!(!db.is_loaded("Times New Roman"), "circle_fallback must skip Times New Roman when its cmap lacks '●'");
assert!(!db.is_loaded("Arial"), "system_fallback must skip Arial when its cmap lacks '●'");
// Populate sys.tried before rescanning; replacing Arial.ttf in place with a covering face and
// rescanning clears sys.tried, cached misses, and stale file coverage ranges.
db.sys.lock().unwrap().tried.insert("Arial");
std::fs::write(dir.join("Arial.ttf"), named_face("SourceSans3-Regular.ttf", "Arial")).unwrap();
db.load_system_fonts();
assert!(db.sys.lock().unwrap().tried.is_empty(), "rescan clears sys.tried");
let resolved = db.fallback_for('●', primary.id()).expect("rescan drops cached miss and reloads replaced Arial.ttf");
assert_eq!(resolved.family, "Arial");
}
/// Diagram fallback matches the primary font's serif/sans classification while body-text
/// fallback preserves loaded order (#5672), and changing user fonts invalidates run fallbacks.
#[test]
+53 -67
View File
@@ -20,7 +20,7 @@ pub use fontdb::{
base_style, bundled, bundled_inter, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
};
pub use harfrust::Feature;
use harfrust::{Buffer, Direction, ShapeOptions, ShapePlan, ShapePlanKey, ShaperFont, Tag};
use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer};
pub use kurbo::BezPath;
pub use script::{fallback_rank, is_emoji, joins_cursively, needs_layout_tables, script_fallbacks};
use skrifa::MetadataProvider;
@@ -202,53 +202,50 @@ fn shape_dir(
around: ShapeContext<'_>,
) -> Vec<ShapedGlyph> {
let mut out = Vec::with_capacity(text.len());
let sf = ShaperFont::new(&face.hb);
// One script per shaping call: the shaper picks its script engine (Myanmar, Khmer,
// Indic, USE reordering…) from the run's script, so "Hi မြန်မာ" in one face must not be
// shaped as Latin. Runs come in text order; right-to-left callers regroup by cluster.
for r in script::script_runs(text) {
let Some(sub) = text.get(r.clone()) else { continue };
let mut buf = Buffer::new();
for (i, c) in sub.char_indices() {
buf.push(map(c) as u32, (r.start + i) as u32);
let shaped = face.hb().map(|hb| {
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
// One script per shaping call: the shaper picks its script engine (Myanmar, Khmer,
// Indic, USE reordering…) from the run's script, so "Hi မြန်မာ" in one face must not be
// shaped as Latin. Runs come in text order; right-to-left callers regroup by cluster.
for r in script::script_runs(text) {
let Some(sub) = text.get(r.clone()) else { continue };
let mut buf = UnicodeBuffer::new();
for (i, c) in sub.char_indices() {
buf.add(map(c), (r.start + i) as u32);
}
// After the text: adding to a buffer clears what follows it.
let around = around.at_edges_of(text, &r);
buf.set_pre_context(around.before);
buf.set_post_context(around.after);
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
let plan = shape_plan(face, &shaper, &buf, features);
let gb = shaper.shape(buf, ShapeOptions::new().plan(plan.as_deref()).features(features));
for (info, pos) in gb.glyph_infos().iter().zip(gb.glyph_positions()) {
out.push(ShapedGlyph {
gid: info.glyph_id,
cluster: info.cluster as usize,
x_advance: pos.x_advance,
x_offset: pos.x_offset,
y_offset: pos.y_offset,
});
}
}
// After the text: adding to a buffer clears what follows it.
let around = around.at_edges_of(text, &r);
buf.set_pre_context(around.before);
buf.set_post_context(around.after);
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
let plan = shape_plan(face, &buf, features);
// A run that exhausts the shaper's budget returns Ok with an incomplete buffer.
if harfrust::shape(&sf, &mut buf, ShapeOptions::new().plan(plan.as_deref()).features(features)).is_err() || !buf.allocation_successful() {
cmap_glyphs(face, sub, r.start, map, &mut out);
continue;
}
for (info, pos) in buf.glyph_infos().iter().zip(buf.glyph_positions()) {
out.push(ShapedGlyph {
gid: info.glyph_id,
cluster: info.cluster as usize,
x_advance: pos.x_advance,
x_offset: pos.x_offset,
y_offset: pos.y_offset,
});
});
if shaped.is_none()
&& let Some(f) = face.skrifa()
{
let cmap = f.charmap();
let gm = f.glyph_metrics(Size::unscaled(), face.location());
for (i, c) in text.char_indices() {
let g = cmap.map(map(c)).unwrap_or_default();
let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5);
out.push(ShapedGlyph { gid: g.to_u32(), cluster: i, x_advance: adv.round() as i32, x_offset: 0, y_offset: 0 });
}
}
out
}
/// One glyph per character straight from the cmap, for a run the shaper could not do.
fn cmap_glyphs(face: &FontFace, text: &str, base: usize, map: &impl Fn(char) -> char, out: &mut Vec<ShapedGlyph>) {
let Some(f) = face.skrifa() else { return };
let cmap = f.charmap();
let gm = f.glyph_metrics(Size::unscaled(), face.location());
for (i, c) in text.char_indices() {
let g = cmap.map(map(c)).unwrap_or_default();
let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5);
out.push(ShapedGlyph { gid: g.to_u32(), cluster: base + i, x_advance: adv.round() as i32, x_offset: 0, y_offset: 0 });
}
}
/// How many shape plans each thread keeps: the oldest is dropped to make room, so a thread never
/// holds more than this many, whatever fonts, scripts and feature sets it shapes.
const MAX_SHAPE_PLANS: usize = 64;
@@ -282,22 +279,22 @@ thread_local! {
/// oldest dropped past [`MAX_SHAPE_PLANS`]). A kept plan is used only for the same face and when
/// harfrust's own [`ShapePlanKey::matches`] accepts it (script, direction, language, the face's
/// variation instance and the features). `None` leaves making it to the shaper.
fn shape_plan(face: &FontFace, buf: &Buffer, features: &[Feature]) -> Option<std::rc::Rc<ShapePlan>> {
fn shape_plan(face: &FontFace, shaper: &Shaper, buf: &UnicodeBuffer, features: &[Feature]) -> Option<std::rc::Rc<ShapePlan>> {
// The buffer's script is unset when it reads as unknown: the guess never sets that.
let script = buf.script().filter(|s| *s != harfrust::Script::UNKNOWN);
let script = Some(buf.script()).filter(|s| *s != harfrust::script::UNKNOWN);
let language = buf.language();
let direction = buf.direction();
if direction == Direction::Invalid {
return None;
}
let key = ShapePlanKey::new(&face.hb, script, direction).language(language).features(features);
let key = ShapePlanKey::new(script, direction).language(language.as_ref()).instance(face.instance.as_ref()).features(features);
let of = PlanFace::of(face);
SHAPE_PLANS.with(|cell| {
let mut plans = cell.try_borrow_mut().ok()?;
if let Some((_, plan)) = plans.iter().find(|(f, plan)| *f == of && key.matches(plan)) {
return Some(plan.clone());
}
let plan = std::rc::Rc::new(ShapePlan::new(&face.hb, direction, script, language, features));
let plan = std::rc::Rc::new(ShapePlan::new(shaper, direction, script, language.as_ref(), features));
if plans.len() >= MAX_SHAPE_PLANS {
plans.remove(0);
}
@@ -362,14 +359,14 @@ mod tests {
#[test]
fn kept_shape_plans_shape_as_fresh_ones() {
let fresh = |face: &FontFace, text: &str, features: &[Feature], rtl: bool| -> Vec<(u32, u32, i32, i32, i32)> {
let mut buf = Buffer::new();
let Some(hb) = face.hb() else { return Vec::new() };
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
let mut buf = UnicodeBuffer::new();
buf.push_str(text);
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
if harfrust::shape(&ShaperFont::new(&face.hb), &mut buf, ShapeOptions::new().features(features)).is_err() {
return Vec::new();
}
buf.glyph_infos().iter().zip(buf.glyph_positions()).map(|(i, p)| (i.glyph_id, i.cluster, p.x_advance, p.x_offset, p.y_offset)).collect()
let gb = shaper.shape(buf, ShapeOptions::new().features(features));
gb.glyph_infos().iter().zip(gb.glyph_positions()).map(|(i, p)| (i.glyph_id, i.cluster, p.x_advance, p.x_offset, p.y_offset)).collect()
};
let kept = |face: &FontFace, text: &str, features: &[Feature], rtl: bool| -> Vec<(u32, u32, i32, i32, i32)> {
shape_dir(face, text, features, &|c| c, rtl, ShapeContext::default())
@@ -398,14 +395,14 @@ mod tests {
fn kept_shape_plans_are_bounded() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
let fresh = |features: &[Feature], rtl: bool| -> Vec<(u32, i32)> {
let mut buf = Buffer::new();
let Some(hb) = face.hb() else { return Vec::new() };
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
let mut buf = UnicodeBuffer::new();
buf.push_str("office");
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
if harfrust::shape(&ShaperFont::new(&face.hb), &mut buf, ShapeOptions::new().features(features)).is_err() {
return Vec::new();
}
buf.glyph_infos().iter().zip(buf.glyph_positions()).map(|(i, p)| (i.glyph_id, p.x_advance)).collect()
let gb = shaper.shape(buf, ShapeOptions::new().features(features));
gb.glyph_infos().iter().zip(gb.glyph_positions()).map(|(i, p)| (i.glyph_id, p.x_advance)).collect()
};
for n in 0..3 * MAX_SHAPE_PLANS as u32 {
let features = [feature_value(b"kern", n % 2), feature_value(b"liga", n)];
@@ -418,17 +415,6 @@ mod tests {
assert_eq!(kept_shape_plans(), MAX_SHAPE_PLANS);
}
/// The cmap fallback for a failed run gives one glyph per character, its clusters offset by
/// where the run starts in the text.
#[test]
fn cmap_fallback_keeps_cluster_offsets() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
let mut out = Vec::new();
cmap_glyphs(&face, "ab", 5, &|c| c, &mut out);
assert_eq!(out.iter().map(|g| g.cluster).collect::<Vec<_>>(), [5, 6]);
assert!(out.iter().all(|g| g.gid != 0 && g.x_advance > 0));
}
#[test]
fn ligatures_can_be_disabled() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
+3 -4
View File
@@ -122,8 +122,7 @@ const COLOR_EMOJI: &[&str] = &["Segoe UI Emoji", "Apple Color Emoji", "Noto Colo
pub fn is_emoji(c: char) -> bool {
matches!(
u32::from(c),
0x1F000..=0x1F7FF
| 0x1F900..=0x1FAFF
0x1F000..=0x1FAFF
| 0x231A..=0x231B
| 0x23E9..=0x23EC
| 0x23F0
@@ -211,8 +210,8 @@ mod tests {
assert!(fallback_rank(c, "Segoe UI Emoji") < fallback_rank(c, "Segoe UI Symbol"), "{c}");
assert!(fallback_rank(c, "Noto Color Emoji") < fallback_rank(c, "Noto Emoji"), "{c}");
}
// Text-style symbols keep the symbol fonts, including Supplemental Arrows-C.
for c in ['✔', '☺', '→', '\u{1F86A}', 'a', '1'] {
// Text-style symbols keep the symbol fonts.
for c in ['✔', '☺', '→', 'a', '1'] {
assert!(!is_emoji(c), "{c}");
}
}
+2 -4
View File
@@ -9,10 +9,8 @@ description = "WordCraft import/export: plain text, Markdown, HTML, RTF, OpenDoc
workspace = true
[features]
# Test helpers shared with other crates: `sheet::xls_fixture` (binary workbook builder via
# `craft-xls/test-support`) and `with_shared_conversion_error` / `with_shared_conversion_error_after`,
# which wire thread-local forced-failure hooks into `to_shared` and `from_shared`. Never enable
# outside dev-dependencies, so those hooks are never built into the app.
# `sheet::xls_fixture`, the binary workbook builder other crates' tests share; turned on only as a
# dev-dependency, so never built into the app.
test-support = ["craft-xls/test-support"]
[dependencies]
-59
View File
@@ -28,76 +28,17 @@ use wordcraft_doc::Document;
/// (`wordcraft_docx::package::MAX_ENTRIES`); checked before `zip` parses them (#3660).
pub const MAX_ZIP_ENTRIES: u64 = 20_000;
#[cfg(any(test, feature = "test-support"))]
thread_local! {
/// `(skip, repeat, message)`: when `Some`, lets `skip` calls to `to_shared` / `from_shared`
/// run normally, then fails the next call with `message` (and every subsequent call when
/// `repeat` is `true`).
static SHARED_ERROR: std::cell::Cell<Option<(usize, bool, &'static str)>> = const { std::cell::Cell::new(None) };
}
#[cfg(any(test, feature = "test-support"))]
fn take_shared_error() -> Option<String> {
SHARED_ERROR.with(|slot| {
let (skip, repeat, msg) = slot.get()?;
if skip > 0 {
slot.set(Some((skip - 1, repeat, msg)));
None
} else {
if !repeat {
slot.set(None);
}
Some(msg.to_string())
}
})
}
#[cfg(any(test, feature = "test-support"))]
fn with_shared_error_state<T>(state: Option<(usize, bool, &'static str)>, f: impl FnOnce() -> T) -> T {
struct Reset(Option<(usize, bool, &'static str)>);
impl Drop for Reset {
fn drop(&mut self) {
SHARED_ERROR.with(|slot| slot.set(self.0));
}
}
let prev = SHARED_ERROR.with(|slot| slot.replace(state));
let _reset = Reset(prev);
f()
}
/// Simulates a `to_shared` / `from_shared` conversion failure for every call inside `f`.
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub fn with_shared_conversion_error<T>(msg: &'static str, f: impl FnOnce() -> T) -> T {
with_shared_error_state(Some((0, true, msg)), f)
}
/// Lets `skip` `to_shared` / `from_shared` conversions run normally, then fails the next one once.
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub fn with_shared_conversion_error_after<T>(skip: usize, msg: &'static str, f: impl FnOnce() -> T) -> T {
with_shared_error_state(Some((skip, false, msg)), f)
}
/// The document as the shared model the format crates read and write.
///
/// A conversion that fails is an error, never an empty document or an empty file: the caller
/// says so instead of writing a file with nothing in it.
pub(crate) fn to_shared(doc: &Document) -> Result<craft_wordmodel::Document, String> {
#[cfg(any(test, feature = "test-support"))]
if let Some(err) = take_shared_error() {
return Err(err);
}
wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())
}
/// The shared model as the app's document model. A conversion that fails is an error, never
/// an empty document.
pub(crate) fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
#[cfg(any(test, feature = "test-support"))]
if let Some(err) = take_shared_error() {
return Err(err);
}
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
}
+8 -4
View File
@@ -4,13 +4,17 @@ use std::sync::Arc;
use wordcraft_doc::{Block, Document, SectionProps};
use crate::shared_section;
pub use craft_odf::text::{CryptError, TEMPLATE_MIME, TEXT_MIME, decrypt, encrypt, is_encrypted};
/// Text room, points, that header and footer bands leave on a page (as Page Setup's margins must).
const MIN_TEXT_ROOM: f32 = 36.0;
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
let mut d = Document::new();
d.last_section = page.clone();
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
}
/// A shared document opened as a WordCraft one, its pages keeping the text room the header and
/// footer bands leave ([`keep_text_room`]).
fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
@@ -65,7 +69,7 @@ pub fn import(bytes: &[u8]) -> Result<Document, String> {
}
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
from_shared(craft_odf::text::import_on(bytes, &shared_section(page)?)?)
from_shared(craft_odf::text::import_on(bytes, &shared_section(page))?)
}
pub fn import_flat(bytes: &[u8]) -> Result<Document, String> {
@@ -73,7 +77,7 @@ pub fn import_flat(bytes: &[u8]) -> Result<Document, String> {
}
pub fn import_flat_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
from_shared(craft_odf::text::import_flat_on(bytes, &shared_section(page)?)?)
from_shared(craft_odf::text::import_flat_on(bytes, &shared_section(page))?)
}
/// The shared model an OpenDocument file is written from. ODF's `dc:date` is an instant (a `Z`
-96
View File
@@ -338,74 +338,6 @@ fn a_format_that_cannot_be_read_is_an_error_not_a_blank_document() {
assert!(e.contains("RTF"), "{e}");
}
/// Every HTML, Markdown, LaTeX, RTF and MHT importer and exporter propagates `to_shared` /
/// `from_shared` errors instead of falling back to an empty document or empty string.
#[test]
fn shared_conversion_errors_propagate_through_all_formats_without_empty_fallback() {
let doc = sample();
let page = wordcraft_doc::SectionProps::default();
let mht_bytes = b"MIME-Version: 1.0\r\nContent-Type: multipart/related; boundary=\"b\"\r\n\r\n--b\r\nContent-Type: text/html\r\n\r\n<p>hello</p>\r\n--b--\r\n";
let msg = "simulated shared conversion failure";
let assert_err = |res: Result<String, String>, label: &str| {
let e = res.unwrap_err();
assert!(e.contains(msg), "{label}: {e}");
};
crate::with_shared_conversion_error(msg, || {
assert_err(crate::html::import("<p>hello</p>").map(|_| String::new()), "html::import");
assert_err(crate::html::import_page("<p>hello</p>", &|_| None).map(|_| String::new()), "html::import_page");
assert_err(crate::html::import_with("<p>hello</p>", &|_| None).map(|_| String::new()), "html::import_with");
assert_err(crate::html::import_on("<p>hello</p>", &|_| None, &page).map(|_| String::new()), "html::import_on (section)");
assert_err(crate::html::export(&doc), "html::export");
assert_err(crate::html::export_fragment(&doc), "html::export_fragment");
assert_err(crate::markdown::import("hello").map(|_| String::new()), "markdown::import");
assert_err(crate::markdown::import_on("hello", &page).map(|_| String::new()), "markdown::import_on (section)");
assert_err(crate::markdown::import_on_with_lines("hello", &page).map(|_| String::new()), "markdown::import_on_with_lines (section)");
assert_err(crate::markdown::export(&doc), "markdown::export");
assert_err(crate::latex::import(b"hello").map(|_| String::new()), "latex::import");
assert_err(crate::latex::import_on(b"hello", &page).map(|_| String::new()), "latex::import_on");
assert_err(crate::latex::export(&doc), "latex::export");
assert_err(crate::rtf::import(br"{\rtf1 hello}").map(|_| String::new()), "rtf::import");
assert_err(crate::rtf::export(&doc), "rtf::export");
assert_err(crate::mht::import(mht_bytes).map(|_| String::new()), "mht::import (section)");
assert_err(crate::mht::import_on(mht_bytes, &page).map(|_| String::new()), "mht::import_on (section)");
for (ext, bytes) in [("html", b"<p>hello</p>" as &[u8]), ("md", b"hello"), ("tex", b"hello"), ("rtf", br"{\rtf1 hello}"), ("mht", mht_bytes)]
{
assert_err(import(ext, bytes).unwrap().map(|_| String::new()), &format!("import({ext})"));
assert_err(crate::import_on(ext, bytes, &page).unwrap().map(|_| String::new()), &format!("import_on({ext})"));
}
for ext in ["html", "md", "tex", "rtf"] {
assert_err(export(ext, &doc).unwrap().map(|_| String::new()), &format!("export({ext})"));
assert_err(
crate::export_with(ext, &doc, &crate::ExportOptions { comments: true }).unwrap().map(|_| String::new()),
&format!("export_with({ext})"),
);
}
});
// For `import_on` helpers that first convert `page` via `shared_section`, also verify that
// a `from_shared` failure after `shared_section` succeeds still propagates as an error.
for (label, res) in [
(
"html::import_on (from_shared)",
crate::with_shared_conversion_error_after(1, msg, || crate::html::import_on("<p>hello</p>", &|_| None, &page)),
),
("markdown::import_on (from_shared)", crate::with_shared_conversion_error_after(1, msg, || crate::markdown::import_on("hello", &page))),
(
"markdown::import_on_with_lines (from_shared)",
crate::with_shared_conversion_error_after(1, msg, || crate::markdown::import_on_with_lines("hello", &page).map(|(d, _)| d)),
),
("mht::import_on (from_shared)", crate::with_shared_conversion_error_after(1, msg, || crate::mht::import_on(mht_bytes, &page))),
] {
assert_err(res.map(|_| String::new()), label);
}
}
#[test]
fn odt_round_trip() {
check_round_trip("odt", true);
@@ -418,34 +350,6 @@ fn odt_round_trip() {
assert_eq!(back.core.creator, "Ada Writer");
}
#[test]
fn open_document_import_on_reports_section_conversion_errors() {
// Original synthetic ODT, OTT and FODT without a page layout, so they use the supplied paper size.
let ns = concat!(
r#"xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" "#,
r#"xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3""#,
);
let body = "<office:body><office:text><text:p>Page geometry</text:p></office:text></office:body>";
let packaged = |mime: &str| {
let content = format!("<office:document-content {ns}>{body}</office:document-content>");
let mut zip = craft_zip::Writer::new();
zip.add("mimetype", mime.as_bytes(), craft_zip::Compression::Stored).unwrap();
zip.add("content.xml", content.as_bytes(), craft_zip::Compression::Stored).unwrap();
zip.finish().unwrap()
};
let flat = format!(r#"<office:document {ns} office:mimetype="{}">{body}</office:document>"#, crate::odt::TEXT_MIME);
let cases = [("odt", packaged(crate::odt::TEXT_MIME)), ("ott", packaged(crate::odt::TEMPLATE_MIME)), ("fodt", flat.into_bytes())];
let page = wordcraft_doc::SectionProps { page_w: 505.0, page_h: 731.0, ..Default::default() };
let message = "OpenDocument page conversion failed";
for (ext, bytes) in cases {
let open = || crate::import_on(ext, &bytes, &page).unwrap();
let doc = open().unwrap();
assert_eq!((doc.last_section.page_w, doc.last_section.page_h), (page.page_w, page.page_h), "{ext}");
assert_eq!(doc.plain_text(wordcraft_doc::StoryRef::Body), "Page geometry", "{ext}");
assert_eq!(crate::with_shared_conversion_error(message, open).unwrap_err(), message, "{ext}");
}
}
/// A flat ODT on A4 with a header and a footer, their bands' minimum heights (`fo:min-height`)
/// stated, and two body paragraphs.
fn flat_odt_with_bands(header: &str, footer: &str) -> Vec<u8> {
-1
View File
@@ -14,7 +14,6 @@ wordcraft-doc = { workspace = true }
wordcraft-fonts = { workspace = true }
wordcraft-proof = { workspace = true }
craft-metafile = { workspace = true }
craft-xml = { workspace = true }
kurbo = { workspace = true }
unicode-bidi = { workspace = true }
unicode-linebreak = { workspace = true }
+12 -21
View File
@@ -1,6 +1,6 @@
use super::ctx::{Ctx, Joining, page_anchored};
use super::floats::{
AnchoredFloat, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
};
use super::flow::again;
use super::page::PageFrame;
@@ -160,8 +160,8 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
let layout = table::layout_table(ctx, story, t, path, width, depth + 1);
let (tx, ty) = match t.props.float {
Some(float) => {
let place = FloatPlace { shift: table::float_offset_shift(ctx, t), modern: ctx.doc.settings.compat_mode >= 15 };
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, place, float_tables);
let legacy = (ctx.doc.settings.compat_mode < 15).then(|| table::first_cell_left_margin(ctx, t));
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, legacy, float_tables);
exclusions.push((area, false, None, WrapText::BothSides, true));
float_tables.push(area);
table_areas.push(area);
@@ -361,9 +361,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
let outline = ctx.wrap_outline(o);
excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice)));
}
floats.insert(oi, AnchoredFloat::new(r));
floats.insert(oi, r);
}
let rel = rel_exclusions(&excl, 0.0, y, applied);
let rel = rel_exclusions(&excl, 0.0, y);
if !rel.is_empty() {
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
}
@@ -525,25 +525,17 @@ pub(crate) struct BoxLayout {
pub(crate) last_top: f32,
}
/// How a floating table placed by an offset stands from it.
#[derive(Clone, Copy)]
struct FloatPlace {
/// How far left of the offset its edge stands ([`table::float_offset_shift`]).
shift: f32,
/// Word 2013 layout (compatibility mode 15).
modern: bool,
}
/// Where floating table `tl` goes in a box `width` wide whose next paragraph starts at `y`, and
/// the area text keeps clear of. Positions relative to the page or its margins need the box's
/// `frame`; without one (a table cell) they're relative to the box.
/// `frame`; without one (a table cell) they're relative to the box. `legacy` is the first cell's
/// left margin before Word 2013 layout, `None` in it.
fn box_float_table_rect(
frame: Option<PageFrame>,
width: f32,
y: f32,
tl: &table::TableLayout,
f: &TableFloat,
place: FloatPlace,
legacy: Option<f32>,
float_tables: &[Rect],
) -> (Rect, Rect) {
let h = tl.rows.iter().map(|r| r.height).sum::<f32>().clamp(0.0, 100_000.0);
@@ -579,8 +571,8 @@ fn box_float_table_rect(
};
// Nor is there an area to align in: the table starts where the text is.
let v_align = if frame.is_none() && matches!(f.v_rel, Anchor::Page | Anchor::Margin) { None } else { f.v_align };
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { place.shift } else { 0.0 };
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, place.modern, h_area.0 - place.shift, float_tables);
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { legacy.unwrap_or(0.0) } else { 0.0 };
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, legacy.is_none(), h_area.0, float_tables);
let [dl, dt, dr, db] = f.dist_from_text();
(r, r.inset(-dl, -dt, -dr, -db))
}
@@ -835,9 +827,8 @@ impl Joint {
}
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
/// it, it runs right to left, or it is a text frame placed apart (`frames` and `cell_frame`
/// both hold, sharing no line; in a table cell, only frames anchored to `"text"`): without
/// its space before, as [`Joint::fit`] lays it out.
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
/// without its space before, as [`Joint::fit`] lays it out.
fn take_up(
self,
ctx: &mut Ctx,
-5
View File
@@ -152,11 +152,6 @@ pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOpt
let outline = (opts.view == ViewMode::Outline).then(|| opts.outline.as_ref().is_some_and(|o| o.plain));
let mut h = std::collections::hash_map::DefaultHasher::new();
styles.hash(&mut h);
// Theme fonts affect East Asian slot resolution (when `font_ea_theme` is set).
doc.settings.major_font.hash(&mut h);
doc.settings.minor_font.hash(&mut h);
doc.passthrough.get("wordcraft:theme.fonts").hash(&mut h);
doc.passthrough.get("wordcraft:settings.orig").hash(&mut h);
// The compatibility mode changes paragraph layout too (widow control in table cells).
doc.settings.compat_mode.hash(&mut h);
opts.show_hidden.hash(&mut h);
+23 -84
View File
@@ -219,10 +219,8 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, false))
}
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
/// `space_before` the space before it that the flow laid out above it.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before: f32) -> Vec<para::Exclusion> {
let before = if space_before > 0.0 { space_before } else { 0.0 };
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::Exclusion> {
excl.iter()
.map(|(r, tb, c, side, table)| para::Exclusion {
top: r.y - y0,
@@ -234,11 +232,10 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before:
side: *side,
table: *table,
})
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
// room, with that space laid out again below them (#7143). Any ending at or above it
// (like side-wrapping areas above the first line) cannot reach the paragraph and is
// dropped so paragraphs below keep empty exclusions and hit the cache (#8613).
.filter(|e| e.bottom > 0.0 || (e.top_bottom && e.bottom > -before))
// Top-and-Bottom areas above the first line can still take room: they sit in the
// paragraph's space before, which Word lays out again below them (#7143). Side-wrapping
// areas there are above the text and take no room, as before.
.filter(|e| e.bottom > 0.0 || e.top_bottom)
.collect()
}
@@ -349,7 +346,7 @@ pub(crate) fn anchor_floats(
pb: &mut PageBuilder,
anchor: FloatAnchor,
force: &[usize],
) -> (HashMap<usize, AnchoredFloat>, Arc<ParaLayout>, Vec<para::Exclusion>, Vec<usize>) {
) -> (HashMap<usize, Rect>, Arc<ParaLayout>, Vec<para::Exclusion>, Vec<usize>) {
let FloatAnchor { p, block, y0, place, .. } = anchor;
ctx.fields.page = pb.number;
// Each layout of it here counts its automatic equation numbers from the same place.
@@ -471,32 +468,18 @@ pub(crate) fn anchor_lines(p: &Paragraph, pl: &ParaLayout) -> Vec<Option<usize>>
out
}
/// A float placed before its paragraph's objects are drawn.
pub(crate) struct AnchoredFloat {
rect: Rect,
/// The origin used when the float was placed again from the pushed first line.
pushed_origin: Option<f32>,
}
impl AnchoredFloat {
pub(crate) fn new(rect: Rect) -> Self {
Self { rect, pushed_origin: None }
}
}
/// [`anchor_floats`], leaving out the floats in `late` (in order).
fn anchor_floats_but(
ctx: &mut Ctx,
pb: &mut PageBuilder,
anchor: FloatAnchor,
late: &[usize],
) -> (HashMap<usize, AnchoredFloat>, Arc<ParaLayout>, Vec<para::Exclusion>) {
) -> (HashMap<usize, Rect>, Arc<ParaLayout>, Vec<para::Exclusion>) {
let FloatAnchor { p, block, y0, before, excl_mark, label, place } = anchor;
ctx.fields.page = pb.number;
ctx.fields.page_format = pb.page_format;
let (col_x, width) = (pb.col_x(), pb.col_w());
let mut rects = HashMap::new();
let mut areas = HashMap::new();
if !pb.web && place {
// (A mark from a page before may be short of the areas this page started with.)
pb.excl.truncate(excl_mark.max(pb.seeded));
@@ -528,68 +511,25 @@ fn anchor_floats_but(
let seed = early.and_then(|v| v.iter().find(|(b, k, _)| (*b, *k) == (block, oi))).map(|(_, _, a)| a);
(r, area) = settle_early(r, area, seed, top, |r| wrap_area(r, float, outline));
}
rects.insert(oi, AnchoredFloat::new(r));
rects.insert(oi, r);
// Above the paragraph, beside text laid out before it: the page is laid out again
// with it known from the start (#2048).
let above = area.as_ref().filter(|a| text_before && a.0.y < top - 0.5).map(|a| (page, a.clone()));
ctx.floats_above.insert((block, oi), above);
let slot = if let Some(area) = area {
let b = area.0.bottom();
let k = match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) {
if let Some(area) = area {
match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) {
Some(k) => {
if let Some(slot) = pb.excl.get_mut(k) {
*slot = area;
}
k
}
None => {
let k = pb.excl.len();
pb.excl.push(area);
k
}
};
Some((k, b))
} else {
None
};
areas.insert(oi, slot);
}
}
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0, before);
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
if !pb.web && place && lead > 0.0 {
let page = pb.pages.len().saturating_sub(1);
let top = y0 - before;
let text_before = top > pb.top + 0.5 || pb.col > 0;
let frame = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
for (oi, o) in p.objects.iter().enumerate() {
let Some((_, _, float)) = floating(o) else { continue };
let Some(&area) = areas.get(&oi) else { continue };
let Some(placed) = rects.get_mut(&oi) else { continue };
let r = placed.rect;
if float.y < 0.0 && area.map_or(r.bottom(), |(_, b)| b) < y0 + lead - 0.5 {
// Only down: across it stays where it was placed (`settle_early` may have moved it).
let moved = Rect { y: float_rect(Some(frame), (col_x, width), top + lead, r.w, r.h, float).y, ..r };
// A wrap area moved onto the first line would cover text laid out without it.
if area.is_some_and(|(_, b)| b + (moved.y - r.y) > y0 + lead - 0.5) {
continue;
}
placed.rect = moved;
placed.pushed_origin = match float.v_rel {
Anchor::Page | Anchor::Margin | Anchor::TopMargin | Anchor::BottomMargin | Anchor::InsideMargin | Anchor::OutsideMargin => None,
_ => Some(top + lead),
};
if let Some((k, _)) = area
&& let Some(slot) = pb.excl.get_mut(k)
{
slot.0.y += moved.y - r.y;
let above = (text_before && slot.0.y < top - 0.5).then(|| (page, slot.clone()));
ctx.floats_above.insert((block, oi), above);
None => pb.excl.push(area),
}
}
}
}
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0);
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
(rects, pl, rel)
}
@@ -756,7 +696,7 @@ pub(crate) struct ObjectPlacement<'a> {
pub lines: (usize, usize),
pub origin: (f32, f32),
pub at: &'a ObjFrame<'a>,
pub floats: &'a HashMap<usize, AnchoredFloat>,
pub floats: &'a HashMap<usize, Rect>,
pub depth: usize,
}
@@ -816,23 +756,22 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
continue;
}
let pinned = at.pinned.and_then(|m| m.get(&oi)).copied().filter(|_| floating);
let (rect, origin_y) = if let Some(r) = pinned {
(r, at.para_y)
let rect = if let Some(r) = pinned {
r
} else if let Some(l) = late_here {
(l.rect, l.top)
l.rect
} else if floating {
match floats.get(&oi) {
Some(placed) => (placed.rect, placed.pushed_origin.unwrap_or(at.para_y)),
Some(r) => *r,
None => {
let h = ctx.float_height(obj, w, h);
(float_rect(at.page, at.col, at.para_y, w, h, float), at.para_y)
float_rect(at.page, at.col, at.para_y, w, h, float)
}
}
} else {
let cx = x + line.cl_left(k).unwrap_or(0.0);
let modern = ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT;
let r = display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern);
(r, at.para_y)
display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern)
};
let (mut behind, mut front) = (Vec::new(), Vec::new());
let layer = if float.wrap == Wrap::BehindText { &mut behind } else { &mut front };
@@ -879,7 +818,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
off: c.start,
text_box: shown,
wrap: float.wrap,
origin: Point::new(at.col.0, origin_y),
origin: Point::new(at.col.0, late_here.map_or(at.para_y, |l| l.top)),
group_boxes,
});
for (id, rect) in boxes {
@@ -925,7 +864,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
/// touch its lines and are left out.
pub(crate) fn continued_exclusions(rel: &[para::Exclusion], excl: &[WrapArea], x0: f32, y: f32, t: f32, width: f32) -> Vec<para::Exclusion> {
let before = rel.iter().filter(|e| e.top < t).map(|e| para::Exclusion { bottom: e.bottom.min(t), ..e.clone() });
let here = rel_exclusions(excl, x0, y - t, 0.0)
let here = rel_exclusions(excl, x0, y - t)
.into_iter()
.filter(|e| e.bottom > t && e.right > -width && e.left < 2.0 * width)
.map(|e| if e.top < t && e.contour.is_none() { para::Exclusion { top: t, ..e } } else { e });
+5 -6
View File
@@ -2,16 +2,16 @@ use super::boxes::{BoxInput, BoxLayout, Edges, Joint, frame_float, joined, layou
use super::cache::has_page_number_fields;
use super::ctx::{Ctx, Joining};
use super::floats::{
AnchoredFloat, FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect,
late_floats, place_late, place_objects, wrap_area,
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect, late_floats,
place_late, place_objects, wrap_area,
};
use super::notes::{DECOR_STORY, NoteBox, para_notes};
use super::page::{PageBuilder, PageFrame, item_bottom};
use super::placed::Placed;
use super::table_flow::table_start_need;
use super::{
Arc, Block, Counters, Document, HashMap, InlineObject, Level, LineEnd, Page, ParaLayout, Paragraph, Path, StoryRef, TextDirection, ViewMode,
outline, para,
Arc, Block, Counters, Document, HashMap, InlineObject, Level, LineEnd, Page, ParaLayout, Paragraph, Path, Rect, StoryRef, TextDirection,
ViewMode, outline, para,
};
#[cfg(test)]
use crate::WRAP_RELAYS;
@@ -279,7 +279,7 @@ struct Flow<'a> {
excl_mark: usize,
/// Where its automatic equation numbers start: each layout of it again counts from here.
eq_start: u32,
float_rects: HashMap<usize, AnchoredFloat>,
float_rects: HashMap<usize, Rect>,
pl: Arc<ParaLayout>,
rel: Vec<para::Exclusion>,
/// The page its fields were laid out for, and the width.
@@ -1312,7 +1312,6 @@ mod tests {
use wordcraft_doc::Pos;
use wordcraft_doc::para::{Anchor, Float, LINE_BREAK, Wrap, WrapText};
use wordcraft_doc::props::LineSpacing;
use wordcraft_geom::Rect;
#[test]
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
+2 -3
View File
@@ -40,9 +40,8 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
/// header and footer go on: the page where the section begins. A page's section is the one at its
/// top, so a section that starts continuously part-way down `prev` has no first page of its own:
/// Word shows the earlier section's header there and the section's default one from the next page
/// on; the case where its first paragraph begins on `prev` and runs over is treated the same way
/// (inferred, not measured separately in Word). `sections` as [`Document::sections`] gives them
/// (each with its last block).
/// on, also when its first paragraph begins on `prev` and runs over. `sections` as
/// [`Document::sections`] gives them (each with its last block).
pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool {
if prev.is_some_and(|p| p.section == page.section) {
return false;
-55
View File
@@ -786,55 +786,6 @@ impl DocLayout {
None
}
/// The text direction of the lines holding `pos`; `None` for upright (horizontal) text.
pub fn turn_at(&self, pos: &Pos, page_hint: usize) -> Option<TextDirection> {
self.pieces(pos.story, &pos.path, page_hint).into_iter().find_map(|(_, it)| match it {
Placed::Lines { para, l0, l1, turn, .. } if turn.is_turned() && (*l0..*l1).contains(&para.line_of(pos.off)) => Some(*turn),
_ => None,
})
}
/// In turned text, the position on the next (`next`) or previous line in reading order, at
/// `goal` along the line (its own frame; `None` keeps the caret's). Returns it with that
/// along-line coordinate. Only lines of the same flow count (the paragraphs of one story
/// level or of one table cell, not another cell's), so `None` at the first/last line of the
/// caret's flow on the page.
pub fn turned_line(&self, pos: &Pos, goal: Option<f32>, next: bool, page_hint: usize) -> Option<(Pos, f32)> {
let c = self.caret_on(pos, page_hint)?;
let flow = |pi: usize| -> Option<Vec<(&Path, &std::sync::Arc<ParaLayout>, usize)>> {
Some(
items_of(self.pages.get(pi)?, pos.story)
.filter_map(|it| match it {
Placed::Lines { story, path, para, l0, l1, turn, .. }
if *story == pos.story && turn.is_turned() && path.parent() == pos.path.parent() =>
{
Some((path, para, *l0, *l1))
}
_ => None,
})
.flat_map(|(path, para, l0, l1)| (l0..l1).map(move |li| (path, para, li)))
.collect(),
)
};
let lines = flow(c.page)?;
let here = lines.iter().position(|(path, para, li)| *path == &pos.path && *li == para.line_of(pos.off))?;
// Past the page's first/last line, the flow goes on at the adjacent page's last/first.
let target = if next { lines.get(here + 1).copied() } else { here.checked_sub(1).and_then(|i| lines.get(i).copied()) }.or_else(|| {
let other = flow(if next { c.page + 1 } else { c.page.checked_sub(1)? })?;
if next { other.first().copied() } else { other.last().copied() }
});
let (path, para, li) = target?;
let gx = match goal {
Some(g) => g,
None => {
let x = lines[here].1.x_of(lines[here].2, pos.off)?;
lines[here].1.caret_limit(lines[here].2).map_or(x, |m| x.min(m))
}
};
let off = para.off_at_x(li, gx);
Some((Pos { story: pos.story, path: path.clone(), off }, gx))
}
/// The position one line up (`dir < 0`) or down from `pos`, keeping `goal_x` (page x).
pub fn vertical(&self, pos: &Pos, goal_x: Option<f32>, dir: i32, page_hint: usize) -> Option<(Pos, f32)> {
let c = self.caret_on(pos, page_hint)?;
@@ -1074,12 +1025,6 @@ impl DocLayout {
let here = para.x_of(li, pos.off)?;
let mut best: Option<(usize, f32)> = None;
for (off, x) in para.line_carets(li) {
// Omitted runs retain byte offsets as zero-width markers. Keep their
// visible edges as candidates without placing the caret inside a run.
let span = para.left_out.partition_point(|range| range.end <= off);
if para.left_out.get(span).is_some_and(|range| range.start < off) {
continue;
}
let Some(x) = x else { continue };
let ahead = if left { x < here - 0.01 } else { x > here + 0.01 };
let d = (x - here).abs();
-6
View File
@@ -45,12 +45,6 @@ pub use paragraph::layout_para;
pub(crate) use paragraph::word_widths;
pub use proof::{ProofRun, is_list_item, paragraph_issues, proof_runs, proof_text};
/// The East Asian family requested by layout for this run, before installed-font substitution.
/// A theme slot takes precedence over the inherited name and can have no resolved face.
pub fn east_asian_font<'a>(doc: &'a Document, run: &'a ResolvedChar) -> Option<&'a str> {
chars::east_asian_font(doc, run)
}
/// A laid-out paragraph.
#[derive(Clone, Debug)]
pub struct ParaLayout {
+12 -28
View File
@@ -155,14 +155,11 @@ impl<'a> Builder<'a> {
_ => wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f)),
};
// A mark is set like the character it belongs to, as for `complex`: in small capitals at
// that character's size, even when the run's font already draws the mark, so the two
// stay in one shaping run, can compose or position together, and match their cluster
// whole (#7865, #8571). Any other character: Small Caps draws lowercase letters, and
// the space and ideographic space, at the small-caps size, as Word does; a no-break
// space, digits and punctuation keep the full size (#7062).
// that character's size, so the two stay in one shaping run and its cluster is matched
// whole.
let small = match cur {
Some(k) if mark => k.small,
_ => rc.small_caps && !rc.caps && (c.is_lowercase() || c == ' ' || c == '\u{3000}'),
_ => rc.small_caps && !rc.caps && c.is_lowercase(),
};
let key = SegKey { face, small, complex, rtl };
match cur {
@@ -208,9 +205,7 @@ impl<'a> Builder<'a> {
return i;
}
}
// Small capitals are set at 80% of the size rounded to the half point, as Word does
// (16 pt → 13, 14 → 11, 12 → 9.5, #7062).
let size = if small { (rc.draw_size() * 0.8 * 2.0).round() / 2.0 } else { rc.draw_size() };
let size = rc.draw_size() * if small { 0.8 } else { 1.0 };
// A symbol font that isn't installed, or is installed one em tall (Apple's Symbol), takes
// the height Word gives it.
let (a, d) = match wordcraft_fonts::word::symbol_line(&rc.font, &r) {
@@ -226,9 +221,7 @@ impl<'a> Builder<'a> {
}
None => wordcraft_fonts::word::line_metrics(&face),
};
// A small-caps piece is drawn at 80% but measured for the line at the full size: a Small
// Caps line is as tall as without Small Caps, as in Word (#7063).
let k = rc.draw_size() as f64 / face.upem.max(1.0);
let k = size as f64 / face.upem.max(1.0);
// A fallback face (letters the requested font lacks) is emboldened or slanted when it has
// no bold or italic of its own.
let (synth_bold, synth_italic) = match face_override {
@@ -353,15 +346,13 @@ impl<'a> Builder<'a> {
(resolved.face, resolved.substituted || !family.eq_ignore_ascii_case(&r.font))
});
let primary_cs = resolved_cs.map(|(face, _)| face);
// Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsiaTheme`
// over `w:eastAsia`) when it, or the font table alternate it is drawn in (#2702), is
// installed and has them.
let wanted_ea =
super::chars::east_asian_font(self.env.doc, rc).filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| {
let family = lookup_family(self.env.doc, f);
let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic);
(f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f))
});
// Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsia`) when
// it, or the font table alternate it is drawn in (#2702), is installed and has them.
let wanted_ea = rc.font_ea.as_deref().filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| {
let family = lookup_family(self.env.doc, f);
let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic);
(f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f))
});
let primary_ea = wanted_ea.filter(|(_, r, _)| !r.substituted).map(|(_, r, _)| r.face);
// The levels by byte of `text`, from `lbase` on.
let (levels, lbase): (&[u8], usize) = match dir {
@@ -590,13 +581,6 @@ impl<'a> Builder<'a> {
}
}
}
// The ligature glyph's kerning pair with the following glyph belongs after its last
// letter, not on the head inside the ligature (#8618).
if let Some((head, rest)) = self.clusters.get_mut(i..=i + n).and_then(|cs| cs.split_first_mut())
&& let Some(last) = rest.last_mut()
{
last.kern = std::mem::take(&mut head.kern);
}
i += n + 1;
}
}
-56
View File
@@ -213,62 +213,6 @@ pub fn substitute_face(doc: &Document, font: &str) -> Option<FaceRef> {
(r.substituted || family != font).then_some(r.face)
}
const THEME_FONTS_PASSTHROUGH: &str = "wordcraft:theme.fonts";
/// The theme's East Asian face, falling back to its per-script font for the settings'
/// East Asian theme language when the main `a:ea` face is empty.
fn theme_ea_face(doc: &Document, major: bool) -> Option<&str> {
let text = std::str::from_utf8(doc.passthrough.get(THEME_FONTS_PASSTHROUGH)?).ok()?;
let key = if major { "major" } else { "minor" };
let find = |kind: &str, which: &str| {
text.lines().find_map(|line| {
let mut parts = line.splitn(4, '\t');
let (k, t, w, face) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
(k == key && t == kind && w == which && !face.trim().is_empty()).then_some(face)
})
};
find("face", "ea").or_else(|| {
let settings = craft_xml::parse(doc.passthrough.get("wordcraft:settings.orig")?).ok()?;
let lang = settings.child(craft_xml::Local("themeFontLang"))?.attr_local("eastAsia")?;
find("script", theme_ea_script(lang)?)
})
}
/// The East Asian scripts used by theme font entries. An explicit script takes precedence
/// over the language's usual script, including Traditional Chinese outside Taiwan/Hong Kong.
fn theme_ea_script(lang: &str) -> Option<&'static str> {
let mut parts = lang.trim().split(['-', '_']);
let language = parts.next()?;
let rest: Vec<_> = parts.collect();
if let Some(script) = rest.iter().find_map(|p| ["Hans", "Hant", "Jpan", "Hang"].into_iter().find(|s| s.eq_ignore_ascii_case(p))) {
return Some(script);
}
if language.eq_ignore_ascii_case("ja") {
Some("Jpan")
} else if language.eq_ignore_ascii_case("ko") {
Some("Hang")
} else if language.eq_ignore_ascii_case("zh") {
Some(if rest.iter().any(|p| ["TW", "HK", "MO"].iter().any(|r| r.eq_ignore_ascii_case(p))) { "Hant" } else { "Hans" })
} else {
None
}
}
/// The East Asian font effective for a run (`w:eastAsiaTheme` takes precedence over `w:eastAsia`,
/// including an inherited `w:eastAsia`). Returns `None` when none is named or the theme slot
/// points to an East Asian theme font with neither a main face nor a matching per-script face.
pub(super) fn east_asian_font<'a>(doc: &'a Document, rc: &'a ResolvedChar) -> Option<&'a str> {
use wordcraft_doc::props::ThemeFont;
match rc.font_ea_theme {
Some(ThemeFont::MajorEastAsia) => theme_ea_face(doc, true),
Some(ThemeFont::MinorEastAsia) => theme_ea_face(doc, false),
Some(ThemeFont::MajorAscii | ThemeFont::MajorHAnsi) => Some(doc.settings.major_font.as_str()).filter(|f| !f.trim().is_empty()),
Some(ThemeFont::MinorAscii | ThemeFont::MinorHAnsi) => Some(doc.settings.minor_font.as_str()).filter(|f| !f.trim().is_empty()),
Some(ThemeFont::MajorBidi | ThemeFont::MinorBidi) => None,
None => rc.font_ea.as_deref().filter(|f| !f.trim().is_empty()),
}
}
/// The face Chinese, Japanese and Korean text is drawn in when its East Asian font (`w:eastAsia`)
/// `font_ea` isn't installed and the run's font is `font`; `None` when `font_ea` is installed. As
/// layout draws it: an East Asian font is looked up by name alone (the roman-font rule of
+5 -15
View File
@@ -70,8 +70,6 @@ pub(super) fn snap_chars(b: &mut Builder, text: &str, grid: &Grid) {
g.dx += shift;
}
c.adv = adv;
// The snapped advance no longer includes the shaped kerning adjustment.
c.kern = 0.0;
}
}
@@ -101,17 +99,14 @@ fn auto_space_room(st: &StyleRun) -> f32 {
/// size for Times New Roman, 0.2203 for Arial, 0.2575 for Calibri, 0.2980 for Courier New,
/// 0.3041 for Cambria — which is half each face's average character width. With different sizes
/// either side, the room after the Latin run takes the Latin size, not the Asian one.
///
/// `ea_lacks(at, c)`: the run at byte `at` names an installed East Asian font that has no glyph
/// for `c`. Word adds no room beside such a character, though a substituted face draws it (#6591).
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lacks: impl Fn(usize, char) -> bool) -> Vec<(usize, f32)> {
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec<(usize, f32)> {
let mut out = Vec::new();
if !de && !dn {
return out;
}
let mut shown = b.shown.iter().map(|s| (s.0, s.1.as_str())).peekable();
// The previous text cluster: index, its last character and its start byte.
let mut prev: Option<(usize, char, usize)> = None;
// The previous text cluster: index and its last character.
let mut prev: Option<(usize, char)> = None;
for k in 0..b.clusters.len() {
let Some(c) = b.clusters.get(k) else { break };
match c.kind {
@@ -131,13 +126,8 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lac
prev = None;
continue;
};
let start = c.start;
if let Some((pk, pc, pstart)) = prev
if let Some((pk, pc)) = prev
&& let Some(side) = crate::kinsoku::auto_space(pc, first, de, dn)
&& !match side {
crate::kinsoku::AsianSide::Left => ea_lacks(pstart, pc),
crate::kinsoku::AsianSide::Right => ea_lacks(start, first),
}
{
let style = b.clusters.get(pk).map(|p| p.style as usize);
let st = style.and_then(|i| b.styles.get(i));
@@ -152,7 +142,7 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lac
out.push((pk, gap));
}
}
prev = Some((k, last, start));
prev = Some((k, last));
}
out
}
+16 -25
View File
@@ -61,9 +61,6 @@ struct Breaker<'e> {
i: usize,
top: f32,
first: bool,
/// Whether `[top - space_before, top]` holds laid-out space before (initially and after a
/// Top-and-Bottom push), rather than a span cleared past a side-wrapping object (#8614, #8687).
space_band: bool,
/// The rest of the current row: spans on the far side of floating objects, left to right.
row_rest: VecDeque<(f32, f32)>,
row_first: usize,
@@ -235,7 +232,6 @@ impl<'e> Breaker<'e> {
i: 0,
top: 0.0,
first: true,
space_band: true,
row_rest: VecDeque::new(),
row_first: 0,
skipped: 0,
@@ -272,13 +268,13 @@ impl<'e> Breaker<'e> {
let lo = self.row_left(pl);
// A Top-and-Bottom object ending in the paragraph's space before (or reaching into
// its first line) is a block the first line must start below, with that space before
// laid out again under it (#7143). Look `space_before` above `self.top` initially and
// after a Top-and-Bottom push so stacked Top-and-Bottom objects re-apply `space_before`
// too (#8687), but not after a side-wrapping push (`row_spans` or `skip_row`), where
// the span above `self.top` was cleared past a side-wrapping object (#8614).
if self.first && self.space_band && self.space_before > 0.0 {
// laid out again under it (#7143). Exclusions are relative to the first line, so look
// `space_before` above it too: the space the flow actually laid out, so an object
// above a gap that collapsing, contextual spacing or a page top removed takes no
// room, while the part of a merged gap that was laid out still does.
if self.first && self.space_before > 0.0 {
let before = self.space_before;
let row = (self.top - before, self.est_h + before, self.table_h + before);
let row = (self.top - before, self.est_h + before, self.table_h);
if let Some(below) = self
.exclusions
.iter()
@@ -286,12 +282,8 @@ impl<'e> Breaker<'e> {
.filter(|e| e.intersects_row(row.0, row.1, row.2, lo, self.base_right))
.map(|e| e.bottom)
.reduce(f32::max)
&& below + before > self.top
&& guard < 50
{
self.top = below + before;
guard += 1;
continue;
self.top = self.top.max(below + before);
}
}
let row = (self.top, self.est_h, self.table_h);
@@ -306,7 +298,6 @@ impl<'e> Breaker<'e> {
}
Err(below) if below > self.top && guard < 50 => {
self.top = below;
self.space_band = false;
guard += 1;
}
Ok((None, _)) | Err(_) => {
@@ -388,7 +379,6 @@ impl<'e> Breaker<'e> {
self.top + even_row(self.lines.get_mut(self.row_first..).unwrap_or_default())
} else {
// Nothing on this row: go below the first object that ends, as when no span is wide enough.
self.space_band = false;
self.exclusions
.iter()
.filter(|e| e.intersects_row(self.top, self.est_h, self.table_h, sc.row_lo, self.base_right))
@@ -402,8 +392,7 @@ impl<'e> Breaker<'e> {
/// Returns how it ends.
fn close_line(&mut self, pl: &mut ParaLayout, mut sc: Scan) -> LineEnd {
if sc.end == LineEnd::Para || sc.end == LineEnd::Wrap {
let kern = if sc.end == LineEnd::Wrap && sc.j > sc.c0 { line_end_kern(pl, sc.j - 1) } else { 0.0 };
let xc = sc.x - kern;
let xc = sc.x;
resolve_tab(pl, &mut sc.pending_tab, &mut sc.xs, sc.c0, xc, &mut sc.x);
}
if sc.j >= self.n && sc.end != LineEnd::Wrap && !matches!(sc.end, LineEnd::LineBreak | LineEnd::PageBreak | LineEnd::ColumnBreak) {
@@ -465,8 +454,8 @@ impl<'e> Breaker<'e> {
let hyphen = (sc.end == LineEnd::Wrap && c1 > c0 && pl.hyph_after.binary_search(&((c1 - 1) as u32)).is_ok())
.then(|| pl.clusters.get(c1 - 1).map(|c| hyphen_glyph(pl, c.style, &mut self.hcache)))
.flatten();
let end_x = match (sc.xs.last(), c1.checked_sub(1).and_then(|k| pl.clusters.get(k).map(|c| (k, c)))) {
(Some(lx), Some((k, c))) => lx + c.adv - line_end_kern(pl, k) + hyphen.map_or(0.0, |h| h.2),
let end_x = match (sc.xs.last(), c1.checked_sub(1).and_then(|k| pl.clusters.get(k))) {
(Some(lx), Some(c)) => lx + c.adv + hyphen.map_or(0.0, |h| h.2),
_ => sc.line_start_x,
};
sc.xs.push(end_x);
@@ -962,9 +951,11 @@ impl Scan {
self.x += w;
}
_ => {
// Its room grows from nothing with its text (a tab moved on from the line before
// may still hold the width it had there).
if let Some(c) = pl.clusters.get_mut(j) {
// A right tab's room grows from nothing with its text (a tab moved on from the
// line before may still hold the width it had there).
if stop.align == TabAlign::Right
&& let Some(c) = pl.clusters.get_mut(j)
{
c.adv = 0.0;
}
self.pending_tab = Some((j, stop, self.x));
@@ -1105,7 +1096,7 @@ impl Scan {
self.word_from = if c.kind == ClKind::Space { self.x - c.adv } else { self.x };
} else if self.hyph_ok
&& !pl.clusters.get(j + 1).is_some_and(|n| n.kind == ClKind::Text && n.g1 <= n.g0)
&& self.x - line_end_kern(pl, j) + hyphen_glyph(pl, c.style, &mut bk.hcache).2 <= self.right_edge + shrink + 0.01
&& self.x + hyphen_glyph(pl, c.style, &mut bk.hcache).2 <= self.right_edge + shrink + 0.01
{
self.last_break = Some(j);
}
+1 -23
View File
@@ -306,7 +306,6 @@ impl<'a> Shaped<'a> {
big.font = f.clone();
big.font_cs = f.clone();
big.font_ea = Some(f.clone());
big.font_ea_theme = None;
}
let before = self.b.clusters.len();
self.b.shape(first, 0, &Arc::new(big), None);
@@ -664,22 +663,6 @@ fn shown_text(cx: &Cx) -> Option<String> {
Some(shown)
}
/// Each run's end byte and the installed East Asian font (`w:eastAsiaTheme` over `w:eastAsia`)
/// it resolves to, `None` when none is resolved or it isn't installed. Empty when `wanted` is
/// false or the text is ASCII, which has no East Asian characters to look the fonts up for.
fn installed_east_asian_fonts(cx: &Cx, wanted: bool) -> Vec<(usize, Option<wordcraft_fonts::FaceRef>)> {
if !wanted || cx.p.text.is_ascii() {
return Vec::new();
}
cx.p.run_ranges()
.map(|(range, props)| {
let rc = cx.res.char(props);
let face = super::chars::east_asian_font(cx.env.doc, &rc).map(|f| wordcraft_fonts::word::resolve(f, rc.bold, rc.italic));
(range.end, face.filter(|r| !r.substituted).map(|r| r.face))
})
.collect()
}
/// Lay out one paragraph.
pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
#[cfg(test)]
@@ -715,12 +698,7 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
let auto_space = if rp.snap_to_grid && env.grid.snap_all && env.grid.chars.is_some() {
Vec::new()
} else {
let ea = installed_east_asian_fonts(&cx, rp.auto_space_de || rp.auto_space_dn);
// Runs come in order, so their ends rise: the run holding `at` is a binary search away.
let ea_lacks = |at: usize, c: char| {
ea.get(ea.partition_point(|(end, _)| *end <= at)).and_then(|(_, face)| *face).is_some_and(|f: wordcraft_fonts::FaceRef| !f.covers(c))
};
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn, ea_lacks)
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn)
};
let mut skip = sh.left.clone();
skip.extend(sh.bare.iter().cloned());
+11 -107
View File
@@ -333,30 +333,9 @@ pub fn autofit_widths(cols: &[(f32, f32)], avail: f32) -> Vec<f32> {
cols.iter().map(|c| c.0 + (c.1 - c.0) * k).collect()
}
/// How far left of its offset (`w:tblpX`) a floating table placed by one has its edge. Before
/// Word 2013 layout the first cell's text is at the offset, moved by the table's indent; from it
/// the edge is, moved in by half its left border, the indent ignored (measured in Word for
/// Windows). A right-to-left table (`w:bidiVisual`) has its left edge at the offset in every
/// mode: Word moves it by neither a cell margin nor the indent nor a border (#8517).
pub(crate) fn float_offset_shift(ctx: &Ctx, t: &Table) -> f32 {
if t.props.bidi_visual {
return 0.0;
}
let style = table_style(ctx, t);
if ctx.doc.settings.compat_mode < 15 {
first_cell_left_margin_in(t, default_margins(t, style.as_ref())) - t.props.indent.unwrap_or(0.0)
} else {
-half_edge_border(t, &table_borders(t, style.as_ref()))
}
}
/// Half the left border of a table's first cell, which Word (from mode 15) moves the table in by:
/// the cell's own border, else its row's `w:tblPrEx`, else the table's (`borders`, with its style's).
fn half_edge_border(t: &Table, borders: &Borders) -> f32 {
let row = t.rows.first();
let own = row.and_then(|r| r.cells.first()).and_then(|c| c.props.borders.and_then(|b| b.left));
let exception = row.and_then(|r| r.props.exceptions.as_ref()).and_then(|e| e.borders).and_then(|b| b.left);
own.or(exception).or(borders.left).filter(Border::is_visible).map_or(0.0, |b| b.width.clamp(0.0, 12.0) / 2.0)
/// The first cell's left margin: how far its text sits inside the table's edge.
pub(crate) fn first_cell_left_margin(ctx: &Ctx, t: &Table) -> f32 {
first_cell_left_margin_in(t, default_margins(t, table_style(ctx, t).as_ref()))
}
fn first_cell_left_margin_in(t: &Table, def: [f32; 4]) -> f32 {
@@ -596,20 +575,18 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
let margins_def = default_margins(t, style);
let indent = t.props.indent.unwrap_or(0.0);
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
// (left) border is drawn on its right (cell margins stay on the sides they name).
// (left) margin and border are on its right.
let rtl = t.props.bidi_visual;
// How far in from the start margin the table's edge sits when it is start-aligned.
let start_offset = if ctx.doc.settings.compat_mode >= 15 {
// The border is centred on the edge, so half of it sits outside: Word moves the table in
// by that half.
indent + half_edge_border(t, &tborders)
let border = first_cell.and_then(|c| c.props.borders.and_then(|b| b.left)).or(tborders.left);
indent + border.filter(Border::is_visible).map_or(0.0, |b| b.width.clamp(0.0, 12.0) / 2.0)
} else {
// A right-to-left table too, though its first cell's left margin is on the cell's far
// side: with a left margin of 10 pt and a right one of 2 pt its text ends 8 pt past the
// right margin, as in Word (#8517, measured in Word for Windows). A floating one isn't
// moved ([`float_offset_shift`]).
indent - first_cell_left_margin_in(t, margins_def)
};
// The reading view fits the table into what the start offset leaves of the column, mirrored or not (#7988).
@@ -776,13 +753,9 @@ fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], av
} else if turn.is_turned() {
collapsed = false;
// Turned text: its lines run along the cell's height. An exact row height sets
// their length, and a minimum height (`AtLeast`, or the combined minimum of a
// vertical merge) does when the lines fit across the column; otherwise they get
// the length the text needs unwrapped and the row grows to fit (the second pass
// lays them out again if the row ends up taller). Checked in Word (#6528): in an
// "At least" row, turned text wraps to the minimum height instead of growing the
// row, and a word longer than that minimum runs past the row (tested at 0.3 cm)
// without growing it.
// their length, and a minimum height does when the lines fit across the column;
// otherwise they get the length the text needs unwrapped and the row grows to fit
// (the second pass lays them out again if the row ends up taller).
let snap = (ctx.counters.clone(), ctx.eq_count);
let merged = merged_min_height(t, ri, g);
let preferred = merged.or(row.props.height.filter(|h| h.is_finite() && *h > 0.0)).map(|h| h.clamp(4.0, TURNED_LIMIT));
@@ -866,13 +839,7 @@ fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], av
};
bottoms.push(row_below);
edges.push(row_edge);
heights.push(
if (collapsed && !cells.is_empty()) || matches!((row.props.height, row.props.height_rule), (Some(h), HeightRule::Exact) if h > 0.0) {
rh.max(0.0)
} else {
rh.max(4.0)
},
);
heights.push(if collapsed && !cells.is_empty() { rh.max(0.0) } else { rh.max(4.0) });
rows.push(cells);
}
grow_vertical_merges(&rows, &mut heights);
@@ -1752,10 +1719,6 @@ fn is_automatic(t: &Table) -> bool {
/// Consistent cell widths replace a stale grid without changing the table's total width.
/// Conflicting widths, spans and percentages need the full shared-grid algorithm.
fn apply_cell_widths(t: &Table, grid: &mut [f32]) {
if let Some(widths) = stale_grid_widths(t, grid) {
grid.copy_from_slice(&widths);
return;
}
let Some(first) = t.rows.first() else { return };
if first.cells.len() != grid.len() {
return;
@@ -1775,41 +1738,6 @@ fn apply_cell_widths(t: &Table, grid: &mut [f32]) {
grid.copy_from_slice(&widths);
}
// An autofit table whose width matches its complete point-width rows but not its grid takes the rows.
fn stale_grid_widths(t: &Table, grid: &[f32]) -> Option<Vec<f32>> {
const WIDTH_EPSILON: f32 = 0.5;
const EDGE_EPSILON: f32 = 0.01;
let width = t.props.width.filter(|w| w.is_finite() && (w - grid.iter().sum::<f32>()).abs() > WIDTH_EPSILON)?;
if t.props.fixed || t.props.width_pct.is_some() || t.rows.is_empty() {
return None;
}
let mut edges = vec![None; grid.len() + 1];
edges[0] = Some(0.0);
for row in &t.rows {
if row.first_grid() != 0 || row.grid_after() != 0 {
return None;
}
let (mut g, mut x) = (0usize, 0.0f32);
for cell in &row.cells {
x += cell.props.width.filter(|w| w.is_finite() && *w > 0.0 && cell.props.width_pct.is_none())?;
g = g.saturating_add(cell.span());
let edge = edges.get_mut(g)?;
if edge.is_some_and(|previous: f32| (previous - x).abs() > EDGE_EPSILON) {
return None;
}
edge.get_or_insert(x);
}
if g != grid.len() {
return None;
}
}
if (edges[grid.len()]? - width).abs() > WIDTH_EPSILON {
return None;
}
let widths: Option<Vec<f32>> = edges.windows(2).map(|pair| Some(pair[1]? - pair[0]?)).collect();
widths.filter(|widths| widths.iter().all(|w| *w > 0.0))
}
/// Word sizes each column by the percentage its cells ask for, whichever rows ask: cells without a
/// preferred width take no part, so a header row of percentages sizes the automatic rows below it.
/// The percentages are shares of the table's width, scaled up when they come short of 100%; past
@@ -2011,30 +1939,6 @@ mod width_tests {
assert_eq!(grid, [25.0, 40.0]);
}
#[test]
fn rows_outrank_grid_total() {
let mut table = Table::new(3, 4, 400.0);
let rows = [vec![(4, 400.0)], vec![(2, 150.0), (1, 200.0), (1, 50.0)], vec![(1, 60.0), (1, 90.0), (2, 250.0)]];
for (row, widths) in table.rows.iter_mut().zip(rows) {
row.cells.truncate(widths.len());
for (cell, (span, width)) in row.cells.iter_mut().zip(widths) {
cell.props.span = span;
cell.props.width = Some(width);
}
}
table.grid = vec![100.0, 200.0, 250.0, 100.0];
table.props.width = Some(400.0);
let mut grid = table.grid.clone();
apply_cell_widths(&table, &mut grid);
assert_eq!(grid, [60.0, 90.0, 200.0, 50.0]);
table.props.fixed = true;
grid.copy_from_slice(&table.grid);
apply_cell_widths(&table, &mut grid);
assert_eq!(grid, [100.0, 200.0, 250.0, 100.0], "a fixed table keeps its grid");
}
#[test]
fn autofit_keeps_fitting_widths() {
crate::test_fonts();
+5 -7
View File
@@ -207,9 +207,8 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
let mut tl = table::layout_table(ctx, StoryRef::Body, t, &[block as u32], width, 1);
if let Some(f) = t.props.float.filter(|_| !pb.web) {
// Before Word 2013 layout (compatibility mode 15) an offset places the first cell's text,
// so the edge sits a cell margin further out (and the indent further); from it the edge,
// half its border in.
let legacy = table::float_offset_shift(ctx, t);
// so the edge sits a cell margin further out.
let legacy = if ctx.doc.settings.compat_mode < 15 { table::first_cell_left_margin(ctx, t) } else { 0.0 };
let h: f32 = tl.rows.iter().map(|r| r.height).sum();
if h <= pb.uncapped_bottom() - pb.top + 0.01 {
place_floating_table(ctx, pb, &tl, &f, legacy, block, body_top);
@@ -401,12 +400,11 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
let x = float_table_x(pb, w, f, legacy, ctx.mirror);
let mut obstacles = if f.overlap { Vec::new() } else { header_table_areas(ctx, pb) };
obstacles.extend_from_slice(&pb.float_tables);
// Moved below another, it keeps its distance from the text's edge, half its border in.
let r = clear_of_float_tables(
Rect::new(x, align_in(v_area, f.y, h, f.v_align), w, h),
f,
ctx.doc.settings.compat_mode >= 15,
h_area.0 - legacy,
h_area.0,
&obstacles,
);
// Like Word, a table that doesn't fit below the text before it moves to the next page with
@@ -487,8 +485,8 @@ fn float_table_h_area(pb: &PageBuilder, f: &TableFloat, mirror: bool) -> (f32, f
}
}
/// A floating table's left edge on the page (`legacy`: how far left of an offset its edge stands,
/// [`table::float_offset_shift`]).
/// A floating table's left edge on the page (`legacy`: the first cell's left margin before Word
/// 2013 layout, when an offset places the cell's text).
fn float_table_x(pb: &PageBuilder, w: f32, f: &TableFloat, legacy: f32, mirror: bool) -> f32 {
let align = PageFrame::h_align(Some(&page_frame(pb, mirror)), f.h_align);
let x = align_in(float_table_h_area(pb, f, mirror), f.x, w, align);
+1 -847
View File
@@ -2058,29 +2058,6 @@ fn right_tab_past_the_right_indent_takes_its_number_up_to_the_stop() {
assert!(close > 0, "no entry whose text ends within a digit of the indent");
}
/// A centre tab moved onto the next line with its text starts with no room there, as a right
/// tab does: it doesn't keep the width it had on the line before, so the text is centred on the
/// stop (#8683).
#[test]
fn a_centre_tab_moved_to_the_next_line_centres_its_text_on_the_stop() {
use wordcraft_doc::props::{TabAlign, TabLeader, TabStop};
crate::test_fonts();
for n in 74..=83 {
let text = format!("{}\tWXYZWXWXYZ1.5", "x".repeat(n));
let len = text.chars().count();
let mut d = Document::from_text(&text);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.tabs = Some(vec![TabStop { pos: 460.0, align: TabAlign::Center, leader: TabLeader::None }]);
})
.unwrap();
let l = lay(&d);
let start = l.caret(&Pos::body(0, n + 1)).unwrap().x;
let end = l.caret(&Pos::body(0, len)).unwrap().x;
let mid = (start + end) / 2.0;
assert!((mid - (72.0 + 460.0)).abs() < 0.5, "n={n}: text after the centre tab is centred at {mid}, expected {}", 72.0 + 460.0);
}
}
/// A left tab whose only stop is past the right indent wraps; on the next line it still can't
/// reach that stop, so it takes no room there and its text starts at the indent instead of
/// going to a line of its own.
@@ -3894,51 +3871,6 @@ fn a_text_box_skips_the_min_height_probe_for_turned_text() {
assert!(b.h > 80.0, "and so it runs on past the minimum height: {b:?}");
}
/// A single word longer than an at-least row's minimum height (0.3 cm / ~8.5 pt) breaks across
/// multiple lines instead of growing the row, and letters wider than that minimum overhang the
/// row along its length, as long as the wrapped lines fit across the column.
#[test]
fn a_word_longer_than_min_height_does_not_grow_an_at_least_row() {
use wordcraft_doc::props::HeightRule;
crate::test_fonts();
let min_h = 8.5;
for turn in [TextDirection::Up, TextDirection::Down] {
let mut d = Document::from_text("After");
let mut t = Table::new(1, 1, 160.0);
t.props.style = None;
t.rows[0].props.height = Some(min_h);
t.rows[0].props.height_rule = HeightRule::AtLeast;
t.rows[0].cells[0].props.text_direction = turn;
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("WWWW", Default::default()))];
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let (rect, clip) = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, clip, cell: 0, .. } => Some((*rect, *clip)),
_ => None,
})
.unwrap();
assert!((rect.h - min_h).abs() < 0.01, "{turn:?}: cell grew past min height {min_h}: {rect:?}");
assert!(!clip, "{turn:?}: an at-least row does not clip overflowing text");
let (lines, extent) = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Lines { para, l0, l1, path, .. } if path.0 == [0, 0, 0, 0] => {
let lines = l1 - l0;
let extent = para.lines.get(*l0..*l1).unwrap_or(&[]).iter().filter_map(|line| line.xs.last().copied()).fold(0.0f32, f32::max);
Some((lines, extent))
}
_ => None,
})
.unwrap();
assert!(lines > 1, "{turn:?}: word should break across multiple lines, got {lines}");
assert!(extent > min_h, "{turn:?}: letters should overhang the min height {min_h}, got {extent}");
}
}
#[test]
fn turned_text_wraps_to_merged_rows_height() {
use wordcraft_doc::props::{HeightRule, VMerge};
@@ -6906,30 +6838,6 @@ fn row_height(l: &DocLayout, row: usize) -> f32 {
l.pages[0].items.iter().find_map(|i| if let Placed::Cell { rect, row: r, .. } = i { (*r == row).then_some(rect.h) } else { None }).unwrap()
}
#[test]
fn exact_rows_below_four_points_keep_their_height() {
crate::test_fonts();
use wordcraft_doc::props::HeightRule;
let mut doc = Document::new();
let mut table = Table::new(40, 1, 200.0);
table.props.cell_margins = Some([0.0; 4]);
for row in &mut table.rows {
row.props.height = Some(2.85);
row.props.height_rule = HeightRule::Exact;
}
doc.body = vec![Arc::new(Block::Table(table))];
let layout = lay(&doc);
let height: f32 = layout
.pages
.iter()
.flat_map(|page| &page.items)
.filter_map(|item| if let Placed::Cell { rect, table, .. } = item { (table == &Path::top(0)).then_some(rect.h) } else { None })
.sum();
assert!((height - 40.0 * 2.85).abs() < 0.1, "40 exact rows should total 114 pt, got {height}");
}
/// The laid-out paragraph in cell (row, col) of the table at body index 1.
fn cell_para(l: &DocLayout, row: u32, col: u32) -> Arc<ParaLayout> {
l.pages[0]
@@ -8988,188 +8896,6 @@ fn moved_kept_paragraph_lays_out_no_space_before_under_an_object_at_its_top() {
assert!((top - bottom).abs() < 0.01, "the first line {top} starts at the rule's bottom {bottom}, with no space before laid out above it");
}
/// #8614: when a side-wrapping object pushes the first line down before it is placed, the
/// space-before Top-and-Bottom band must stay anchored to the first line's original top (0), not
/// shift down with `self.top` into the paragraph's area and re-apply `space_before` below a
/// Top-and-Bottom object ending there.
#[test]
fn side_wrapping_push_does_not_shift_space_before_band_into_para_area() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
const BEFORE: f32 = 12.0;
let build = |with_top_bottom: bool| {
let mut d = Document::from_text("Anchor line.\nProbe line with several words in it.");
for block in &mut d.body {
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
}
}
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
p.props.space_before = Some(BEFORE);
}
let plain = lay(&d);
let top_of = |l: &DocLayout, block: u32| {
l.pages[0]
.items
.iter()
.find_map(|i| match i {
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some(*y),
_ => None,
})
.unwrap()
};
let anchor_y = top_of(&plain, 0);
let probe_y = top_of(&plain, 1);
// Full-width side-wrapping object starting at the probe's original top and extending 30 pt
// down, pushing the probe's first line to probe_y + 30.
let side = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y - anchor_y, ..Default::default() };
d.insert_object(&Pos::body(0, 0), rect_shape(500.0, 30.0, side), &Default::default()).unwrap();
if with_top_bottom {
// Top-and-Bottom object inside the side-wrapped vertical span (18..22 pt below probe_y),
// below the original first line [0, 14] and above the Square object's bottom (30).
let tb = Float {
wrap: Wrap::TopAndBottom,
h_rel: Anchor::Column,
v_rel: Anchor::Paragraph,
y: probe_y + 18.0 - anchor_y,
..Default::default()
};
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 4.0, tb), &Default::default()).unwrap();
}
let l = lay(&d);
top_of(&l, 1)
};
let plain_wrap_top = build(false);
let with_tb_top = build(true);
assert!(
(with_tb_top - plain_wrap_top).abs() < 0.01,
"probe first line {with_tb_top} must stay at plain-wrap position {plain_wrap_top} without re-applying space_before"
);
}
/// #8687: when a Top-and-Bottom object pushes the first line down into a second Top-and-Bottom
/// object, the paragraph's space before is laid out again below the second object too.
#[test]
fn stacked_top_and_bottom_objects_reapply_space_before() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
const BEFORE: f32 = 12.0;
let mut d = Document::from_text("Anchor line.\nProbe line with several words in it.");
for block in &mut d.body {
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
}
}
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
p.props.space_before = Some(BEFORE);
}
let plain = lay(&d);
let top_of = |l: &DocLayout, block: u32| {
l.pages[0]
.items
.iter()
.find_map(|i| match i {
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some(*y),
_ => None,
})
.unwrap()
};
let anchor_y = top_of(&plain, 0);
let probe_y = top_of(&plain, 1);
// First Top-and-Bottom object ending 5 pt above the probe's original first line (inside its
// 12 pt space before), pushing the line down to -5 + 12 = 7..21 pt below probe_y.
let first =
Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y - 10.0 - anchor_y, ..Default::default() };
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 5.0, first), &Default::default()).unwrap();
// Second Top-and-Bottom object from 17 to 27 pt below the probe's original first line,
// below the unpushed first line's `est_h` (~15 pt) but reaching into the moved line [7, 21+].
let second =
Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y + 17.0 - anchor_y, ..Default::default() };
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 10.0, second), &Default::default()).unwrap();
let l = lay(&d);
let top = top_of(&l, 1);
let second_bottom = shapes(&l.pages[0].items).iter().map(|r| r.bottom()).fold(f32::NEG_INFINITY, f32::max);
assert!(
(top - (second_bottom + BEFORE)).abs() < 0.01,
"probe first line {top} must start at second object bottom {second_bottom} + {BEFORE} space before"
);
}
/// #8614 / #8687: when a side-wrapping object pushes the first line down into a Top-and-Bottom
/// object (via either `row_spans` or `skip_row`), the line moves below it without re-applying
/// `space_before`.
#[test]
fn side_wrapping_push_into_top_and_bottom_does_not_reapply_space_before() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
const BEFORE: f32 = 12.0;
// 500 pt leaves no span (`row_spans` Err); 445 pt leaves a ~23 pt strip that `skip_row` skips.
for side_width in [500.0, 445.0] {
let mut d = Document::from_text("Anchor line.\nProbe line with several words in it.");
for block in &mut d.body {
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
}
}
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
p.props.space_before = Some(BEFORE);
}
let plain = lay(&d);
let top_of = |l: &DocLayout, block: u32| {
l.pages[0]
.items
.iter()
.find_map(|i| match i {
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some(*y),
_ => None,
})
.unwrap()
};
let anchor_y = top_of(&plain, 0);
let probe_y = top_of(&plain, 1);
// Side-wrapping object from 0 to 30 pt below the probe's original first line, pushing the
// first line down to [30, 44] below probe_y.
let side = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y - anchor_y, ..Default::default() };
d.insert_object(&Pos::body(0, 0), rect_shape(side_width, 30.0, side), &Default::default()).unwrap();
// Top-and-Bottom object from 32 to 36 pt below probe_y: below the original first line
// [0, 14] and reaching into the side-wrapped line [30, 44].
let tb =
Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y + 32.0 - anchor_y, ..Default::default() };
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 4.0, tb), &Default::default()).unwrap();
let l = lay(&d);
let top = top_of(&l, 1);
let tb_bottom = shapes(&l.pages[0].items).iter().map(|r| r.bottom()).fold(f32::NEG_INFINITY, f32::max);
assert!(
(top - tb_bottom).abs() < 0.01,
"side_width={side_width}: probe first line {top} must start at Top-and-Bottom bottom {tb_bottom} without re-applying {BEFORE} space before"
);
}
}
#[test]
fn float_follows_its_paragraph_to_the_next_page() {
crate::test_fonts();
@@ -10446,6 +10172,7 @@ fn a_line_breaks_after_the_space_of_an_opening_bracket() {
assert!(lines.iter().any(|l| l.trim_end().ends_with('(')), "no line ends with the bracket: {lines:?}");
}
/// The lines of the body's first paragraph, as text.
/// The text of every laid-out line.
fn body_lines(l: &DocLayout, text: &str) -> Vec<String> {
l.pages
@@ -15291,30 +15018,6 @@ fn cell_widths_override_grid() {
}
}
// Word sizes an autofit table whose width matches its rows from the rows, not a stale grid.
#[test]
fn ordinary_table_takes_row_widths() {
crate::test_fonts();
let mut t = Table::new(3, 2, 132.0);
t.grid = vec![70.0, 62.0];
t.props.width = Some(120.0);
for row in &mut t.rows {
for (cell, width) in row.cells.iter_mut().zip([40.0, 80.0]) {
cell.props.width = Some(width);
cell.blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("A", Default::default()))];
}
}
t.rows[0].cells.truncate(1);
t.rows[0].cells[0].props.span = 2;
t.rows[0].cells[0].props.width = Some(120.0);
let mut d = Document::from_text("After");
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let [(x0, _, _)] = para_at(&l, &[0, 1, 0, 0])[..] else { panic!("cell missing") };
let [(x1, _, _)] = para_at(&l, &[0, 1, 1, 0])[..] else { panic!("cell missing") };
assert!((x1 - x0 - 40.0).abs() < 0.01, "{}", x1 - x0);
}
#[test]
fn percentage_cell_widths_that_disagree_or_span_columns() {
// Measured in Word (A4, 451.3 pt between the margins; 468 pt here), autofit tables 100% wide:
@@ -15807,91 +15510,6 @@ fn caps_draw_sharp_s_as_two_capitals_in_one_cluster() {
assert_eq!(cl.iter().map(|c| c.2.len()).sum::<usize>(), 6, "{cl:?}");
}
/// `text` laid out with `f` applied to all of it: its paragraph's layout.
fn para_with(text: &str, f: &dyn Fn(&mut wordcraft_doc::props::CharProps)) -> ParaLayout {
let mut d = Document::from_text(text);
d.format_range(&Pos::body(0, 0), &Pos::body(0, text.len()), f).unwrap();
let l = lay(&d);
l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some((**para).clone()) } else { None }).expect("a laid-out line")
}
/// Small Caps draws a space (U+0020) at the small-caps size, like a lowercase letter, as Word
/// does (measured: 40 spaces in Times New Roman Bold 10 pt are 80% as wide in Small Caps); a
/// no-break space keeps its full width, and with All Caps as well the space keeps its full width,
/// as All Caps wins (#7062).
#[test]
fn a_space_in_small_caps_is_as_wide_as_at_the_small_caps_size() {
crate::test_fonts();
// The gap between the first and the last letter of `text`.
let gap = |text: &str, f: &dyn Fn(&mut wordcraft_doc::props::CharProps)| {
let pl = para_with(text, f);
let line = &pl.lines[0];
let x = |start: usize| (line.c0..line.c1).find(|&k| pl.clusters[k].start == start).and_then(|k| line.cl_left(k)).unwrap();
x(text.len() - 1) - x(1)
};
// At 10 pt the small-caps size is exactly 8 pt (80%, no rounding to the half point).
let plain: &dyn Fn(&mut wordcraft_doc::props::CharProps) = &|c| c.size = Some(10.0);
let small: &dyn Fn(&mut wordcraft_doc::props::CharProps) = &|c| {
c.small_caps = Some(true);
c.size = Some(10.0);
};
let both: &dyn Fn(&mut wordcraft_doc::props::CharProps) = &|c| {
c.caps = Some(true);
c.small_caps = Some(true);
c.size = Some(10.0);
};
let spaces = format!("a{}a", " ".repeat(10));
let ratio = gap(&spaces, small) / gap(&spaces, plain);
assert!((ratio - 0.8).abs() < 0.01, "Small Caps spaces are 80% as wide: {ratio}");
assert!((gap(&spaces, both) - gap(&spaces, plain)).abs() < 0.01, "All Caps wins: full-width spaces");
let nbsp = format!("a{}a", "\u{a0}".repeat(10));
assert!((gap(&nbsp, small) - gap(&nbsp, plain)).abs() < 0.01, "a no-break space keeps its width");
}
/// Word sets small capitals at 80% of the size rounded to the half point, a size the format can
/// store, like superscript (measured in Word for Microsoft 365, Times New Roman: 10 pt → 8,
/// 11 → 9, 12 → 9.5, 14 → 11, 16 → 13); a Small Caps space takes that size too (#7062).
#[test]
fn small_caps_take_eighty_percent_of_the_size_rounded_to_the_half_point() {
crate::test_fonts();
let width = |text: &str, f: &dyn Fn(&mut wordcraft_doc::props::CharProps)| {
let pl = para_with(text, f);
let line = &pl.lines[0];
(line.c0..line.c1).map(|k| pl.clusters[k].adv).sum::<f32>()
};
for (size, small) in [(16.0_f32, 13.0_f32), (14.0, 11.0), (12.0, 9.5)] {
let small_caps = width("xxxxxxxxxx", &|c| {
c.small_caps = Some(true);
c.size = Some(size);
});
let capitals = width("XXXXXXXXXX", &|c| c.size = Some(small));
assert!((small_caps - capitals).abs() < 0.01, "{size} pt Small Caps draws capitals at {small} pt: {small_caps} vs {capitals}");
let spaces = width("x x", &|c| {
c.small_caps = Some(true);
c.size = Some(size);
}) - width("xx", &|c| {
c.small_caps = Some(true);
c.size = Some(size);
});
let plain = width("x x", &|c| c.size = Some(small)) - width("xx", &|c| c.size = Some(small));
assert!((spaces - plain).abs() < 0.01, "{size} pt Small Caps spaces are {small} pt spaces: {spaces} vs {plain}");
}
}
/// A Small Caps line of lowercase letters is as tall as the same line without Small Caps: the
/// small capitals are drawn at 80% of the size, but the line is measured at the full size, as in
/// Word (#7063).
#[test]
fn a_small_caps_line_of_lowercase_is_as_tall_as_without_small_caps() {
crate::test_fonts();
let text = "only lowercase letters here";
let line = |f: &dyn Fn(&mut wordcraft_doc::props::CharProps)| para_with(text, f).lines[0].clone();
let plain = line(&|c| c.bold = Some(false));
let small = line(&|c| c.small_caps = Some(true));
assert!((small.height - plain.height).abs() < 0.01, "line height: Small Caps {} vs plain {}", small.height, plain.height);
assert!((small.baseline - plain.baseline).abs() < 0.01, "baseline: Small Caps {} vs plain {}", small.baseline, plain.baseline);
}
/// A caps run in a symbol font draws each code as its symbol: ß never becomes two glyphs (#1581).
#[test]
fn caps_in_a_symbol_font_never_expand_characters() {
@@ -18687,186 +18305,6 @@ fn continuous_section_first_paragraph_running_over_keeps_first_page_header_hidde
assert!(l.pages[next..].iter().all(|p| p.hf_slot == crate::HfSlot::Default));
}
/// A continuous section starting mid-page has no first page of its own, so on its second page
/// `header_table_areas` checks its default header rather than its first-page header.
#[test]
fn continuous_section_second_page_ignores_first_page_header_table() {
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::{HeightRule, LineSpacing, TableFloat};
use wordcraft_doc::section::SectionStart;
for start in [SectionStart::Continuous, SectionStart::NextPage] {
let mut paras: Vec<String> = (0..10).map(|i| format!("Section 1 {i}")).collect();
paras.extend((0..24).map(|i| format!("Section 2 {i}")));
let mut d = Document::from_text(&paras.join("\n"));
for block in &mut d.body {
let Block::Para(p) = Arc::make_mut(block) else { panic!("paragraph") };
p.props =
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(20.0)), ..Default::default() };
}
d.settings.compat_mode = 15;
let make_table = |y, height| {
let mut t = Table::new(1, 2, 300.0);
t.props.cell_margins = Some([0.0; 4]);
t.props.float = Some(TableFloat { h_rel: Anchor::Page, v_rel: Anchor::Page, x: 72.0, y, overlap: false, ..Default::default() });
t.rows[0].props.height = Some(height);
t.rows[0].props.height_rule = HeightRule::Exact;
t
};
let first_hdr = d.add_part(wordcraft_doc::PartKind::Header, vec![Arc::new(Block::Table(make_table(60.0, 80.0)))]);
let s1 = d.last_section.clone();
d.para_mut(StoryRef::Body, &Path::top(9)).unwrap().section = Some(Box::new(s1));
d.last_section.start = start;
d.last_section.title_page = true;
d.last_section.headers.first = Some(first_hdr);
d.body.push(Arc::new(Block::Table(make_table(100.0, 48.0))));
let l = lay(&d);
let begins = l.caret(&Pos::body(10, 0)).unwrap().page;
let target = match start {
SectionStart::Continuous => {
assert_eq!(l.caret(&Pos::body(9, 0)).unwrap().page, begins, "section 2 starts mid-page");
begins + 1
}
_ => begins,
};
let cell_top = l.pages[target]
.items
.iter()
.filter_map(|it| match it {
Placed::Cell { rect, .. } => Some(rect.y),
_ => None,
})
.fold(f32::MAX, f32::min);
let expected = if start == SectionStart::Continuous { 100.0 } else { 140.0 };
assert!((cell_top - expected).abs() < 0.01, "{start:?}: body floating table top {cell_top} on page {target}, expected {expected}");
}
}
/// The same for `footer_table_wraps`: body lines on a continuous section's second page do not wrap
/// around a floating table in the section's first-page footer.
#[test]
fn continuous_section_second_page_ignores_first_page_footer_table_wrap() {
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::{HeightRule, LineSpacing, TableFloat};
use wordcraft_doc::section::SectionStart;
const FLOAT_TOP: f32 = 100.0;
const TABLE_HEIGHT: f32 = 80.0;
const TABLE_WIDTH: f32 = 468.0;
for start in [SectionStart::Continuous, SectionStart::NextPage] {
let mut paras: Vec<String> = (0..10).map(|i| format!("Section 1 {i}")).collect();
let long = "Body wrap word ".repeat(22);
paras.extend((0..14).map(|_| long.clone()));
let mut d = Document::from_text(&paras.join("\n"));
for block in &mut d.body[10..] {
let Block::Para(p) = Arc::make_mut(block) else { panic!("paragraph") };
p.props =
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(24.0)), ..Default::default() };
}
let mut table = Table::new(1, 1, TABLE_WIDTH);
table.props.cell_margins = Some([0.0; 4]);
table.props.float = Some(TableFloat { y: FLOAT_TOP, h_rel: Anchor::Page, v_rel: Anchor::Page, ..Default::default() });
table.rows[0].props.height = Some(TABLE_HEIGHT);
table.rows[0].props.height_rule = HeightRule::Exact;
let first_ftr = d.add_part(wordcraft_doc::PartKind::Footer, vec![Arc::new(Block::Table(table))]);
let s1 = d.last_section.clone();
d.para_mut(StoryRef::Body, &Path::top(9)).unwrap().section = Some(Box::new(s1));
d.last_section.start = start;
d.last_section.title_page = true;
d.last_section.footers.first = Some(first_ftr);
let l = lay(&d);
let begins = l.caret(&Pos::body(10, 0)).unwrap().page;
let target = match start {
SectionStart::Continuous => {
assert_eq!(l.caret(&Pos::body(9, 0)).unwrap().page, begins, "section 2 starts mid-page");
begins + 1
}
_ => begins,
};
assert!(l.pages.len() > target, "{start:?}: expected page {target}");
let margin_left = d.last_section.margin_left;
let beside: Vec<_> = (10..d.body.len() as u32)
.flat_map(|b| line_boxes(&l, target, b, margin_left))
.filter(|(_, top, _, bottom)| *bottom > FLOAT_TOP + 0.01 && *top < FLOAT_TOP + TABLE_HEIGHT - 0.01)
.collect();
assert!(!beside.is_empty(), "{start:?}: no body lines beside footer table band on page {target}");
if start == SectionStart::Continuous {
assert!(
beside.iter().all(|(left, ..)| (*left - margin_left).abs() < 0.01),
"{start:?}: continuous second page wrapped around first-page footer table: {beside:?}"
);
} else {
assert!(
beside.iter().all(|(left, ..)| *left >= TABLE_WIDTH - 0.01),
"{start:?}: new-page section failed to wrap around first-page footer table: {beside:?}"
);
}
}
}
/// The same `begins_section` rule governs `footer_story` (first-page versus default footer), both
/// when the continuous section starts mid-page with separate paragraphs and when its first
/// paragraph runs over onto the next page.
#[test]
fn continuous_section_first_page_footer_is_not_shown_on_its_second_page() {
use wordcraft_doc::section::SectionStart;
for start in [SectionStart::Continuous, SectionStart::NextPage] {
let text = (0..140).map(|i| format!("Paragraph {i}")).collect::<Vec<_>>().join("\n");
let mut d = Document::from_text(&text);
let part = |d: &mut Document, t: &str| {
d.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))])
};
let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO"));
let mut s1 = d.last_section.clone();
s1.footers.default = Some(one);
d.para_mut(StoryRef::Body, &Path::top(19)).unwrap().section = Some(Box::new(s1));
d.last_section.start = start;
d.last_section.title_page = true;
d.last_section.footers.first = Some(first);
d.last_section.footers.default = Some(two);
let l = lay(&d);
let begins = l.caret(&Pos::body(20, 0)).unwrap().page;
let shown: Vec<_> = l.pages.iter().map(|p| p.footer_story).collect();
assert!(l.pages.len() > begins + 2, "{start:?}: the second section runs over several pages");
match start {
SectionStart::Continuous => {
assert_eq!(l.caret(&Pos::body(19, 0)).unwrap().page, begins, "the second section starts part-way down a page");
assert_eq!(shown[begins], Some(one), "{start:?}: the page where it starts keeps the first section's footer");
assert!(
shown[begins + 1..].iter().all(|f| *f == Some(two)),
"{start:?}: then its default footer, never its first-page one: {shown:?}"
);
}
_ => {
assert_eq!(shown[begins], Some(first), "{start:?}: a section on a new page shows its first-page footer there");
assert!(shown[begins + 1..].iter().all(|f| *f == Some(two)), "{start:?}: {shown:?}");
}
}
}
let mut paras: Vec<String> = (0..44).map(|i| format!("Paragraph {i}")).collect();
paras.push("word ".repeat(1200));
paras.extend((0..60).map(|i| format!("After {i}")));
let mut d = Document::from_text(&paras.join("\n"));
let part = |d: &mut Document, t: &str| {
d.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))])
};
let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO"));
let mut s1 = d.last_section.clone();
s1.footers.default = Some(one);
d.para_mut(StoryRef::Body, &Path::top(43)).unwrap().section = Some(Box::new(s1));
d.last_section.start = SectionStart::Continuous;
d.last_section.title_page = true;
d.last_section.footers.first = Some(first);
d.last_section.footers.default = Some(two);
let l = lay(&d);
let begins = l.caret(&Pos::body(44, 0)).unwrap().page;
assert_eq!(l.caret(&Pos::body(43, 0)).unwrap().page, begins, "the second section starts part-way down a page");
let next = begins + 1;
assert!(l.pages.get(next).is_some_and(|p| p.first_block == 44), "its first paragraph runs over onto the next page");
let shown: Vec<_> = l.pages.iter().map(|p| p.footer_story).collect();
assert_eq!(shown[begins], Some(one));
assert!(shown[next..].iter().all(|f| *f == Some(two)), "{shown:?}");
}
/// Sections starting continuously one after another still go onto new pages: a paragraph that
/// doesn't fit below the text above it moves on rather than running off the page (#3907). A
/// hundred one-line sections lay out like a hundred plain paragraphs.
@@ -19422,76 +18860,6 @@ fn turned_cell_float_keeps_its_along_text_offset() {
}
}
/// #6567: when a wrapping float (such as a page-tall `wrapTopAndBottom` frame) pushes its anchor
/// paragraph's first line to the bottom of the page, sibling paragraph-relative floats with
/// negative vertical offsets are measured from the displaced paragraph line rather than placed
/// above the page from the pre-wrap origin.
#[test]
fn negative_offset_floats_in_a_paragraph_pushed_down_by_a_wrapping_float_stay_on_the_page() {
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
let mut doc = Document::from_text("");
doc.last_section.page_w = 595.3;
doc.last_section.page_h = 841.9;
let mut para = Paragraph::new();
let title = Float {
wrap: Wrap::InFrontOfText,
h_rel: Anchor::Margin,
h_align: Some(FloatAlign::Center),
v_rel: Anchor::Paragraph,
y: -652.55,
..Default::default()
};
let row = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 36.0, y: -460.75, ..Default::default() };
let frame = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: -43.11, ..Default::default() };
para.insert_object(para.len(), rect_shape(378.5, 105.75, title), &Default::default()).unwrap();
para.insert_object(para.len(), rect_shape(194.55, 38.45, row), &Default::default()).unwrap();
para.insert_object(para.len(), rect_shape(556.46, 802.52, frame), &Default::default()).unwrap();
doc.body = vec![wordcraft_doc::para_block(para)];
let l = lay(&doc);
assert_eq!(l.pages.len(), 1);
let placed = shapes(&l.pages[0].items);
assert_eq!(placed.len(), 3, "{placed:?}");
let frame_rect = placed.iter().find(|r| (r.h - 802.52).abs() < 0.1).unwrap();
let title_rect = placed.iter().find(|r| (r.h - 105.75).abs() < 0.1).unwrap();
let row_rect = placed.iter().find(|r| (r.h - 38.45).abs() < 0.1).unwrap();
let line_top = first_line_top(&l.pages[0].items);
assert!((frame_rect.y - (72.0 - 43.11)).abs() < 0.5, "frame stays at the top of the page: {frame_rect:?}");
assert!((title_rect.y - (line_top - 652.55)).abs() < 0.5, "title measured from displaced line {line_top}: {title_rect:?}");
assert!((row_rect.y - (line_top - 460.75)).abs() < 0.5, "row measured from displaced line {line_top}: {row_rect:?}");
assert!(title_rect.y > frame_rect.y && row_rect.bottom() < frame_rect.bottom(), "{placed:?}");
let frame = l.object(&Pos::body(0, 2 * wordcraft_doc::para::OBJ.len_utf8()), 0).unwrap();
let title = l.object(&Pos::body(0, 0), 0).unwrap();
assert!((title.origin.y - line_top).abs() < 0.5, "moved float's offset starts at the pushed line: {title:?}");
assert!((frame.rect.y - frame.origin.y + 43.11).abs() < 0.5, "unmoved wrapping float keeps its origin: {frame:?}");
}
/// #6567 review: a wrapping float above its paragraph that would land on the first line when
/// placed from it again isn't moved there: that line was laid out without it in the way.
#[test]
fn a_wrapping_float_isnt_moved_onto_a_first_line_laid_out_without_it() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
let mut doc = Document::from_text("Words in the first line of the paragraph.");
let frame = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
let square = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: -10.0, ..Default::default() };
doc.insert_object(&Pos::body(0, 0), rect_shape(150.0, 50.0, square), &Default::default()).unwrap();
doc.insert_object(&Pos::body(0, 0), rect_shape(200.0, 100.0, frame), &Default::default()).unwrap();
let l = lay(&doc);
let items = &l.pages[0].items;
let square = shapes(items).into_iter().find(|r| (r.h - 50.0).abs() < 0.1).unwrap();
let (x, y, height) = items
.iter()
.find_map(|i| match i {
Placed::Lines { x, y, para, story: StoryRef::Body, .. } => para.lines.first().map(|l| (*x + l.left, *y, l.height)),
_ => None,
})
.unwrap();
assert!(y > 72.0 + 99.0, "the frame pushes the first line down: {y}");
let overlaps = square.y < y + height && square.bottom() > y && square.x < x + 1.0 && square.right() > x;
assert!(!overlaps, "the float {square:?} covers the first line's text at ({x}, {y})");
}
/// A caption kept with the next paragraph (`keepNext`) before a table goes over with the table
/// when the table's repeated header row and the start of its first row don't fit under it, as in
/// Word, instead of staying alone at the foot of the page: keep with next asked a table for a
@@ -19824,145 +19192,6 @@ fn header_text_covers_the_whole_band_of_centred_and_right_lines() {
}
}
/// A floating table placed by an offset from the margin (measured in Word for Windows): before
/// Word 2013 its first cell's text is at the offset, moved by `w:tblInd`; from it its edge is,
/// moved in by half its left border, and `w:tblInd` doesn't move it.
#[test]
fn a_floating_table_placed_by_an_offset_takes_its_indent_before_word_2013_only() {
crate::test_fonts();
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::TableFloat;
let text_x = |mode: u32, indent: Option<f32>| {
let mut t = Table::new(1, 2, 300.0);
t.props.fixed = true;
t.props.indent = indent;
t.props.cell_margins = Some([0.0, 5.4, 0.0, 5.4]);
t.props.borders = Some(wordcraft_doc::props::Borders::all(wordcraft_doc::props::Border::single(0.5)));
t.props.float = Some(TableFloat { h_rel: Anchor::Margin, v_rel: Anchor::Paragraph, ..Default::default() });
for c in &mut t.rows[0].cells {
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
}
let mut d = Document::from_text("Below");
d.settings.compat_mode = mode;
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
lay(&d).pages[0]
.items
.iter()
.find_map(|i| match i {
Placed::Lines { path, x, .. } if path.0 == [0, 0, 0, 0] => Some(*x),
_ => None,
})
.expect("the first cell's text")
};
let margin = 72.0;
assert!((text_x(14, None) - margin).abs() < 0.01, "mode 14: {}", text_x(14, None));
assert!((text_x(14, Some(-5.4)) - (margin - 5.4)).abs() < 0.01, "mode 14, indent: {}", text_x(14, Some(-5.4)));
assert!((text_x(15, None) - (margin + 0.25 + 5.4)).abs() < 0.01, "mode 15: {}", text_x(15, None));
assert!((text_x(15, Some(-5.4)) - (margin + 0.25 + 5.4)).abs() < 0.01, "mode 15, indent: {}", text_x(15, Some(-5.4)));
}
/// #8517: a floating right-to-left table placed by an offset has its left edge at the offset in
/// every mode, whatever its first cell's margins, its indent or its left border (measured in
/// Word for Windows: with `w:tblpX` 1 inch from the margin and cells of left 10 / right 2 pt,
/// the leftmost cell's text is 10 pt in from 144 in modes 14 and 15, with or without a 36 pt
/// indent or an 8 pt left border). A left-to-right one still moves out by its first cell's left
/// margin before Word 2013.
#[test]
fn a_floating_right_to_left_table_has_its_edge_at_its_offset() {
crate::test_fonts();
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::TableFloat;
let left_edge = |mode: u32, rtl: bool, indent: Option<f32>, border: bool| {
let mut t = Table::new(1, 2, 300.0);
t.props.fixed = true;
t.props.bidi_visual = rtl;
t.props.indent = indent;
t.props.cell_margins = Some([0.0, 10.0, 0.0, 2.0]);
if border {
t.props.borders = Some(Borders { left: Some(Border::single(8.0)), ..Default::default() });
}
t.props.float = Some(TableFloat { h_rel: Anchor::Margin, v_rel: Anchor::Paragraph, x: 72.0, ..Default::default() });
for c in &mut t.rows[0].cells {
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
}
let mut d = Document::from_text("Below");
d.settings.compat_mode = mode;
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
lay(&d).pages[0]
.items
.iter()
.filter_map(|i| match i {
Placed::Cell { rect, .. } => Some(rect.x),
_ => None,
})
.fold(f32::INFINITY, f32::min)
};
let offset = 72.0 + 72.0;
for mode in [14, 15] {
for indent in [None, Some(36.0)] {
for border in [false, true] {
let x = left_edge(mode, true, indent, border);
assert!((x - offset).abs() < 0.01, "mode {mode}, indent {indent:?}, border {border}: {x}");
}
}
}
assert!((left_edge(14, false, None, false) - (offset - 10.0)).abs() < 0.01, "left to right, mode 14");
}
/// From Word 2013 a table moves in by half its first cell's left border, and a first row's
/// `w:tblPrEx` border is that border (measured in Word for Windows): with an 8 pt table border and
/// a 2 pt exception the first cell's text is at 78.38, 1 pt in; without the exception at 81.38.
/// The same inline and floating, and for every row.
#[test]
fn a_first_rows_exception_border_is_the_half_border_a_table_moves_in_by() {
crate::test_fonts();
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::TableFloat;
let text_x = |float: bool, exception: bool| {
let mut t = Table::new(2, 2, 300.0);
t.props.fixed = true;
t.props.style = None;
t.props.cell_margins = Some([0.0, 5.4, 0.0, 5.4]);
t.props.borders = Some(Borders { left: Some(Border::single(8.0)), ..Default::default() });
if float {
t.props.float = Some(TableFloat { h_rel: Anchor::Margin, v_rel: Anchor::Paragraph, ..Default::default() });
}
if exception {
t.rows[0].props.exceptions = Some(Box::new(wordcraft_doc::props::TableProps {
borders: Some(Borders { left: Some(Border::single(2.0)), ..Default::default() }),
..Default::default()
}));
}
for r in &mut t.rows {
for c in &mut r.cells {
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
}
}
let mut d = Document::from_text("Below");
d.settings.compat_mode = 15;
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let at = |row: u32| {
l.pages[0]
.items
.iter()
.find_map(|i| match i {
Placed::Lines { path, x, .. } if path.0 == [0, row, 0, 0] => Some(*x),
_ => None,
})
.expect("the first cell's text")
};
(at(0), at(1))
};
for float in [false, true] {
for (exception, want) in [(false, 72.0 + 4.0 + 5.4), (true, 72.0 + 1.0 + 5.4)] {
let (first, second) = text_x(float, exception);
assert!((first - want).abs() < 0.01, "float {float}, exception {exception}: {first}");
assert!((second - want).abs() < 0.01, "float {float}, exception {exception}, row 2: {second}");
}
}
}
#[test]
fn reading_layout_keeps_a_negatively_indented_table_in_the_column() {
crate::test_fonts();
@@ -20244,78 +19473,3 @@ fn evict_unused_caps_stale_entries_across_repeated_edits() {
assert!(c.len() <= base + 1025, "stale cache entries must be bounded (got {}, base {base})", c.len());
}
}
/// #8613: a Top-and-Bottom object ending above a paragraph's applied space before cannot affect
/// it, so paragraphs below keep empty exclusions and hit the cache when shifted vertically, and
/// paragraphs below it in a box are not laid out twice.
#[test]
fn top_and_bottom_float_above_space_before_keeps_cache_hits_on_shift() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
let mut d = Document::from_text(&"line\n".repeat(12));
for block in &mut d.body {
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
p.props.line_spacing = Some(LineSpacing::Exactly(12.0));
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
}
}
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(4).map(Arc::make_mut) {
p.props.space_before = Some(12.0);
}
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 10.0, f), &Default::default()).unwrap();
let mut c = LayoutCache::new();
let before = layout(&d, &mut c, &LayoutOptions::default());
let y_before = before.caret(&Pos::body(6, 0)).unwrap().top;
let misses = c.misses;
d.insert_text(&Pos::body(2, 0), &"word ".repeat(30), &Default::default()).unwrap();
let after = layout(&d, &mut c, &LayoutOptions::default());
let y_after = after.caret(&Pos::body(6, 0)).unwrap().top;
assert!(y_after > y_before + 10.0, "paragraphs below shifted down ({y_before} -> {y_after})");
assert_eq!(c.misses, misses + 1, "only the edited paragraph should miss the cache");
}
/// #8613: in table cells and other boxes, paragraphs below a Top-and-Bottom float (and clear of
/// its space-before band) get empty exclusions, so they are laid out once and hit the cache when
/// shifted vertically.
#[test]
fn top_and_bottom_float_in_cell_keeps_cache_hits_on_shift() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
let mut d = Document::new();
let mut t = Table::new(1, 1, 468.0);
t.props.fixed = true;
t.rows[0].cells[0].blocks = (0..6)
.map(|i| {
let mut p = Paragraph::with_text(&format!("cell line {i}"), Default::default());
p.props.line_spacing = Some(LineSpacing::Exactly(12.0));
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
wordcraft_doc::para_block(p)
})
.collect();
d.body = vec![Arc::new(wordcraft_doc::Block::Table(t))];
let cell_pos = |para: usize| Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, para as u32]), off: 0 };
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
d.insert_object(&cell_pos(0), rect_shape(100.0, 10.0, f), &Default::default()).unwrap();
let mut c = LayoutCache::new();
let before = layout(&d, &mut c, &LayoutOptions::default());
let y_before = before.caret(&cell_pos(4)).unwrap().top;
// Paragraph 0 holds the float so it lays out twice; paragraphs 1..6 sit below it and lay out once each.
assert_eq!(c.misses, 7, "paragraphs below the float should be laid out only once");
let misses = c.misses;
d.insert_text(&cell_pos(1), &"word ".repeat(30), &Default::default()).unwrap();
let after = layout(&d, &mut c, &LayoutOptions::default());
let y_after = after.caret(&cell_pos(4)).unwrap().top;
assert!(y_after > y_before + 10.0, "cell paragraphs below shifted down ({y_before} -> {y_after})");
assert_eq!(c.misses, misses + 1, "only the edited cell paragraph should miss the cache");
}
-100
View File
@@ -133,106 +133,6 @@ fn spaces_punctuation_hangul_and_latin_alone_get_nothing() {
}
}
/// Word adds no automatic space, on either side, beside an ideograph whose run names an installed
/// East Asian font without ideographs, even though a substituted face draws it (#6591: 0.00 pt
/// with `w:eastAsia="Times New Roman"`). A font that isn't installed keeps the space.
#[test]
fn an_east_asian_font_without_ideographs_turns_it_off() {
crate::test_fonts();
let with = |latin: Option<&str>, asian: &str| {
let mut d = Document::from_text("法院94年A字");
let p = para0(&mut d);
let len = p.text.len();
p.format(0, len, &|c: &mut CharProps| {
c.font = latin.map(str::to_string);
c.font_ea = Some(asian.to_string());
})
.unwrap();
d
};
// Source Serif 4 is installed for the tests and has no ideographs.
for d in [with(None, "Source Serif 4"), with(Some("Source Serif 4"), "Source Serif 4")] {
assert!(gaps(&d).iter().all(|g| *g == 0.0), "{:?}", gaps(&d));
}
let d = with(None, "No Such East Asian Font 6591");
let q = quarter(&d);
// The room after each Latin character follows the face that draws it, as without a
// `w:eastAsia` font at all (#6583).
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "a font that isn't installed");
}
/// A `w:eastAsiaTheme` slot on a style or run takes precedence over an inherited named East Asian
/// font (`w:eastAsia`) without ideographs: Word draws the ideographs in the theme face instead, so
/// it still keeps the automatic space unless the theme slot itself names an installed font without
/// ideographs. Conversely, a named `w:eastAsia` on a run replaces an inherited theme slot.
#[test]
fn east_asian_theme_slot_overrides_inherited_named_font() {
crate::test_fonts();
use wordcraft_doc::props::ThemeFont;
// Base default names an installed font without ideographs (`Source Serif 4`).
// A style or run setting `minorEastAsia` overrides it: with no non-CJK `a:ea` face, spaces stay.
let mut d = Document::from_text("法院94年A字");
Arc::make_mut(&mut d.styles).default_chr.font_ea = Some("Source Serif 4".to_string());
let len = para0(&mut d).text.len();
para0(&mut d).format(0, len, &|c: &mut CharProps| c.font_ea_theme = Some(ThemeFont::MinorEastAsia)).unwrap();
let q = quarter(&d);
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "theme slot overrides inherited font_ea");
// When the theme's `a:ea` face (in `wordcraft:theme.fonts`) itself is an installed font without
// ideographs, the space is suppressed.
let mut themed_no_cjk = d.clone();
themed_no_cjk.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tSource Serif 4\n".to_vec()));
assert!(gaps(&themed_no_cjk).iter().all(|g| *g == 0.0), "theme a:ea without ideographs: {:?}", gaps(&themed_no_cjk));
// A Latin theme slot (`minorHAnsi`) resolves to `settings.minor_font`: if installed and lacking
// ideographs, it also suppresses the space.
let mut latin_slot = d.clone();
latin_slot.settings.minor_font = "Source Serif 4".to_string();
para0(&mut latin_slot).format(0, len, &|c: &mut CharProps| c.font_ea_theme = Some(ThemeFont::MinorHAnsi)).unwrap();
assert!(gaps(&latin_slot).iter().all(|g| *g == 0.0), "Latin theme slot without ideographs: {:?}", gaps(&latin_slot));
// A named `w:eastAsia` without `w:eastAsiaTheme` on a run overrides an inherited theme slot.
let mut overridden = Document::from_text("法院94年A字");
Arc::make_mut(&mut overridden.styles).default_chr.font_ea_theme = Some(ThemeFont::MinorEastAsia);
para0(&mut overridden).format(0, len, &|c: &mut CharProps| c.font_ea = Some("Source Serif 4".to_string())).unwrap();
assert!(gaps(&overridden).iter().all(|g| *g == 0.0), "named font_ea overrides inherited theme slot: {:?}", gaps(&overridden));
}
#[test]
fn east_asian_theme_script_fonts_follow_the_theme_language() {
crate::test_fonts();
use wordcraft_doc::props::ThemeFont;
for (lang, script) in [("zh-CN", "Hans"), ("zh-TW", "Hant"), ("zh-Hant-CN", "Hant"), ("ja-JP", "Jpan"), ("ko-KR", "Hang")] {
for (scheme, slot) in [("major", ThemeFont::MajorEastAsia), ("minor", ThemeFont::MinorEastAsia)] {
let mut d = Document::from_text("漢A漢");
Arc::make_mut(&mut d.styles).default_chr.font_ea = Some("宋体".into());
para0(&mut d).format(0, 7, &|c: &mut CharProps| c.font_ea_theme = Some(slot)).unwrap();
let settings = format!(
r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:themeFontLang w:eastAsia="{lang}"/></w:settings>"#
);
d.passthrough.insert("wordcraft:settings.orig".into(), Arc::new(settings.into_bytes()));
d.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(format!("{scheme}\tface\tea\tSource Serif 4\n").into_bytes()));
let main = gaps(&d);
assert!(main.iter().all(|g| *g == 0.0));
// The same installed face without ideographs suppresses spacing when selected by script.
d.passthrough.insert(
"wordcraft:theme.fonts".into(),
Arc::new(format!("{scheme}\tface\tea\t\n{scheme}\tscript\t{script}\tSource Serif 4\n").into_bytes()),
);
assert_eq!(gaps(&d), main, "{scheme}: {lang}/{script}");
// A nonempty main face takes precedence over the script entry.
d.passthrough.insert(
"wordcraft:theme.fonts".into(),
Arc::new(format!("{scheme}\tscript\t{script}\tSource Serif 4\n{scheme}\tface\tea\tMissing CJK Face 8749\n").into_bytes()),
);
assert!(gaps(&d).iter().any(|g| *g > 0.0), "{scheme}: main face wins");
}
}
}
#[test]
fn a_field_result_is_classed_by_the_text_it_shows() {
crate::test_fonts();
+1 -2
View File
@@ -106,8 +106,7 @@ fn cell_letterhead_pulls_an_outside_picture_to_the_outer_left_edge() {
}
}
/// Confinement follows the particular cell, including asymmetric margins and RTL column
/// mirroring (cell margins themselves stay on the sides they name).
/// Confinement follows the particular cell, including asymmetric margins mirrored for RTL.
#[test]
fn cell_float_outer_edges_include_asymmetric_and_mirrored_margins() {
for rtl in [false, true] {
@@ -101,34 +101,6 @@ fn in_small_capitals_a_letter_and_its_marks_go_together_to_a_face_that_has_them_
}
}
/// In small capitals a mark after a lower-case letter shares the letter's 0.8-size shaping run
/// even when the run's font already draws every mark, so it composes and positions with the
/// drawn capital instead of splitting into a separate full-size run (#8571).
#[test]
fn in_small_capitals_a_mark_the_run_font_draws_shares_its_letters_size_and_run() {
let serif = serif();
let (lower, upper, mark) = ('e', 'E', '\u{301}');
assert!(serif.covers(lower) && serif.covers(upper) && serif.covers(mark), "{SERIF} has e, E and U+0301");
let text = format!("{lower}{mark} {upper}{mark}");
let chr = CharProps { font: Some(SERIF.into()), size: Some(12.0), small_caps: Some(true), ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(Paragraph::with_text(&text, chr))];
let (para, missing) = laid_doc(&d);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
let style_at = |at: usize| para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character").style;
let lower_mark = lower.len_utf8();
let upper_at = text.find(upper).expect("upper-case letter is in the text");
let upper_mark = upper_at + upper.len_utf8();
assert_eq!(face_at(&para, 0).id(), serif.id(), "lower-case letter stays in the run's font");
assert_eq!(face_at(&para, lower_mark).id(), serif.id(), "mark stays in the run's font");
assert_eq!(style_at(lower_mark), style_at(0), "mark after lower-case letter shares its small-caps run");
assert_eq!(style_at(upper_mark), style_at(upper_at), "mark after upper-case letter shares its full-size run");
assert!(
para.styles[style_at(lower_mark) as usize].size < para.styles[style_at(upper_at) as usize].size,
"mark after lower-case letter is drawn smaller than the upper-case run"
);
}
#[test]
fn a_mark_the_font_composes_with_its_letter_stays_in_the_run_font() {
let serif = serif();
-37
View File
@@ -3,7 +3,6 @@
#[allow(unused_imports)]
use crate::*;
use wordcraft_doc::Pos;
use wordcraft_doc::props::LineSpacing;
use wordcraft_doc::section::{DocGrid, DocGridType};
@@ -98,39 +97,3 @@ fn character_grid_places_east_asian_text_on_the_pitch() {
}
}
}
#[test]
fn an_exact_character_grid_line_fits_all_its_cells_with_kerning() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let mut grid = with_grid(text, DocGridType::SnapToChars, 0);
let styles = std::sync::Arc::make_mut(&mut grid.styles);
styles.default_chr.font = Some("Inter".into());
styles.default_chr.kern = Some(1.0);
let set_width = |doc: &mut Document, width: f32| {
let indent = doc.last_section.text_width() - width;
doc.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent)).unwrap();
};
// In proportional text the fifth letter still needs its unkerned width at a line break.
let mut plain = grid.clone();
plain.last_section.doc_grid = None;
let wide = lay(&plain);
let para = wide.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let kern = para.clusters[4].kern;
assert!(kern < -0.02, "the test font must kern the pair across the break");
set_width(&mut plain, paired - kern / 2.0);
assert_eq!(super::body_lines(&lay(&plain), text)[0], "AVAV");
let size = para::Grid::of(&grid, &grid.last_section).font_size;
grid.last_section.doc_grid.as_mut().unwrap().char_space = DocGrid::char_space_for(20.0, size);
let pitch = grid.last_section.grid_char_pitch(size).unwrap();
set_width(&mut grid, 5.0 * pitch);
for kern in [0.0, 1.0] {
std::sync::Arc::make_mut(&mut grid.styles).default_chr.kern = Some(kern);
let got = super::body_lines(&lay(&grid), text);
assert_eq!(got[0], "AVAVA", "kerning threshold {kern}: {got:?}");
}
}
+9 -283
View File
@@ -28,13 +28,13 @@ fn a_word_broken_by_letters_ends_without_its_kerning_pair() {
assert_eq!(got.first().map(String::as_str), Some("AVAVA"), "{got:?}");
}
/// Inter under `family` (a 5-byte name) with its `GPOS` hidden and an old-style `kern` table
/// that kerns `(left, right)` by `units` (and nothing else): a shaper splits such a pair between
/// the two glyphs, half in the first one's advance and half in the second one's advance and offset.
fn legacy_kern_family(family: &'static str, left: char, right: char, units: i16) -> &'static str {
assert_eq!(family.len(), "Inter".len());
/// Inter under the family name "Kernx" with its `GPOS` hidden and an old-style `kern` table that
/// kerns "AV" by `units` (and nothing else): a shaper splits such a pair between the two letters,
/// half in the first one's advance and half in the second one's advance and offset.
fn legacy_kern_family(units: i16) -> &'static str {
const FAMILY: &str = "Kernx";
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
let (a, v) = (inter.glyph_for(left) as u16, inter.glyph_for(right) as u16);
let (a, v) = (inter.glyph_for('A') as u16, inter.glyph_for('V') as u16);
let src = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
@@ -76,7 +76,7 @@ fn legacy_kern_family(family: &'static str, left: char, right: char, units: i16)
let name = tables.iter().take_while(|t| &t.0 != b"name").map(|t| t.1.len().div_ceil(4) * 4).sum::<usize>() + 12 + 16 * n;
let len = tables.iter().find(|t| &t.0 == b"name").map_or(0, |t| t.1.len());
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(family)), (b"Inter".to_vec(), family.as_bytes().to_vec())] {
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
@@ -84,7 +84,7 @@ fn legacy_kern_family(family: &'static str, left: char, right: char, units: i16)
}
}
wordcraft_fonts::FontDb::global().add_font(data);
family
FAMILY
}
/// A letter ending a line whose kerning pair with the letter before it the shaper split between
@@ -95,7 +95,7 @@ fn legacy_kern_family(family: &'static str, left: char, right: char, units: i16)
fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let family = legacy_kern_family("Kernx", 'A', 'V', -300);
let family = legacy_kern_family(-300);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
@@ -112,277 +112,3 @@ fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() {
let got = body_lines(&lay(&doc(468.0 - six - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAVAV"), "{got:?}");
}
/// A ligature's kerning pair with the letter after it belongs on the ligature's last cluster, not
/// on its head (#8618): a forced character wrap inside the ligature must not subtract the pair
/// after the whole ligature, and a line ending after the ligature drops that pair.
#[test]
fn a_ligatures_kerning_pair_sits_on_its_last_cluster() {
crate::test_fonts();
let text = "flYflYflYflY";
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.font = Some("Source Serif 4".into());
st.default_chr.size = Some(14.0);
st.default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
assert!(para.clusters[0].g1 > para.clusters[0].g0 && para.clusters[1].g1 == para.clusters[1].g0, "fixture forms an \"fl\" ligature");
assert_eq!(para.clusters[0].kern, 0.0, "the ligature's head cluster carries no kerning pair");
assert!(para.clusters[1].kern < -0.3, "the ligature's last cluster carries its pair with \"Y\": {}", para.clusters[1].kern);
assert_eq!(para.clusters[3].kern, 0.0);
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - para.clusters[4].kern;
assert!(alone - paired > 0.3, "Source Serif 4 kerns \"fl\" + \"Y\": {paired} vs {alone}");
// Between paired and alone: "flYfl" fits only with its pair with "Y", so "fl" wraps whole.
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
assert_eq!(got.first().map(String::as_str), Some("flY"), "{got:?}");
// Wide enough for "flYfl" without the pair after it.
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("flYfl"), "{got:?}");
// A three-letter ligature ("ffi") also puts its pair with "V" only on its last cluster.
let mut d3 = Document::from_text("ffiV");
let st3 = Arc::make_mut(&mut d3.styles);
st3.default_chr.font = Some("Source Serif 4".into());
st3.default_chr.size = Some(14.0);
st3.default_chr.kern = Some(1.0);
let l3 = lay(&d3);
let p3 = l3.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
assert!(p3.clusters[0].g1 > p3.clusters[0].g0 && p3.clusters[1].g1 == p3.clusters[1].g0 && p3.clusters[2].g1 == p3.clusters[2].g0);
assert_eq!(p3.clusters[0].kern, 0.0);
assert_eq!(p3.clusters[1].kern, 0.0);
assert!(p3.clusters[2].kern < -0.2, "last cluster of \"ffi\" carries pair with \"V\": {}", p3.clusters[2].kern);
}
fn first_para(d: &Document) -> Arc<ParaLayout> {
lay(d).pages.into_iter().flat_map(|p| p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap()
}
#[test]
fn a_wrapped_line_end_caret_and_alignment_drop_the_line_end_pair() {
let text = "AVAVAVAVAVAVAVAVAVAV";
let doc = |indent_right: f32, align: Align| {
let mut d = Document::from_text(text);
Arc::make_mut(&mut d.styles).default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(align);
})
.unwrap();
d
};
let base = first_para(&doc(0.0, Align::Left));
let kern = base.clusters[4].kern;
assert!(kern < -0.1, "the test font kerns \"AV\": {kern}");
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_last = base.clusters[4].adv - kern;
// Slight slack past the five unkerned letters so right and centre alignments move the line.
let slack = 6.0;
let indent_right = 468.0 - (alone + slack);
let left = first_para(&doc(indent_right, Align::Left));
let l0 = &left.lines[0];
assert_eq!(l0.c1, 5);
assert!((l0.end_x() - alone).abs() < 0.01, "end_x {} should match unkerned {alone}, not {paired}", l0.end_x());
assert!((left.x_of(0, l0.stop).unwrap() - alone).abs() < 0.01);
let right = first_para(&doc(indent_right, Align::Right));
let r0 = &right.lines[0];
assert_eq!(r0.c1, 5);
let r_end = r0.cl_left(4).unwrap() + unkerned_last;
assert!((r_end - r0.right).abs() < 0.01, "right-aligned unkerned end {r_end} should sit at right edge {}", r0.right);
let center = first_para(&doc(indent_right, Align::Center));
let c0 = &center.lines[0];
assert_eq!(c0.c1, 5);
let left_gap = c0.cl_left(0).unwrap() - c0.left;
let right_gap = c0.right - (c0.cl_left(4).unwrap() + unkerned_last);
assert!((left_gap - right_gap).abs() < 0.01, "centred gaps differ: left {left_gap} vs right {right_gap}");
}
#[test]
fn a_positive_kerning_pair_at_line_end_stays_inside_the_right_edge() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let family = legacy_kern_family("Kernp", 'A', 'V', 300);
let doc = |indent_right: f32, align: Align| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(align);
})
.unwrap();
d
};
let base = first_para(&doc(0.0, Align::Left));
let kern = base.clusters[4].kern;
assert!(kern > 0.5, "the test font positively kerns \"AV\": {kern}");
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_last = base.clusters[4].adv - kern;
let width = (paired + alone) / 2.0;
let indent_right = 468.0 - width;
let left = first_para(&doc(indent_right, Align::Left));
let l0 = &left.lines[0];
assert_eq!(l0.c1, 5);
assert!(l0.end_x() <= l0.right + 0.01, "end_x {} ran past right edge {}", l0.end_x(), l0.right);
assert!((l0.end_x() - alone).abs() < 0.01);
let right = first_para(&doc(indent_right, Align::Right));
let r0 = &right.lines[0];
assert_eq!(r0.c1, 5);
assert!(r0.cl_left(0).unwrap() > 0.01, "right-aligned line failed to shift right");
assert!((r0.cl_left(4).unwrap() + unkerned_last - r0.right).abs() < 0.01);
let center = first_para(&doc(indent_right, Align::Center));
let c0 = &center.lines[0];
assert_eq!(c0.c1, 5);
let left_gap = c0.cl_left(0).unwrap() - c0.left;
let right_gap = c0.right - (c0.cl_left(4).unwrap() + unkerned_last);
assert!(left_gap > 0.01 && (left_gap - right_gap).abs() < 0.01, "centred gaps: left {left_gap} vs right {right_gap}");
}
#[test]
fn a_justified_line_adjusts_spaces_without_the_line_end_pair() {
crate::test_fonts();
// Distributed alignment stretches gaps across clusters directly using `content_end`.
let text = "AVAVAVAVAVAVAVAVAVAV";
for (family, units) in [("Kerdn", -300i16), ("Kerdp", 300i16)] {
let family = legacy_kern_family(family, 'A', 'V', units);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(Align::Distribute);
})
.unwrap();
d
};
let base = first_para(&doc(0.0));
let kern = base.clusters[4].kern;
assert!((kern.signum() as i16) == units.signum(), "{family}: {kern}");
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_last = base.clusters[4].adv - kern;
let width = if units < 0 { alone + 4.0 } else { (paired + alone) / 2.0 };
let para = first_para(&doc(468.0 - width));
let l0 = &para.lines[0];
assert_eq!(l0.c1, 5, "{family}: expected wrap after 5th letter");
assert!(l0.cl_left(4).unwrap() > base.clusters[..4].iter().map(|c| c.adv).sum::<f32>() + 0.01);
let end = l0.cl_left(4).unwrap() + unkerned_last;
assert!((end - l0.right).abs() < 0.01, "{family}: distributed end {end} should meet right edge {}", l0.right);
assert!((l0.end_x() - l0.right).abs() < 0.01);
}
// Justified line with spaces breaking mid-word (`word_wrap = false`): both stretching and
// shrinking adjust spaces against the unkerned line end.
let j_text = "a b AVAVAVAVAVAVAVAVAVAV";
for (family, units) in [("Kerjn", -300i16), ("Kerjp", 300i16)] {
let family = legacy_kern_family(family, 'A', 'V', units);
let doc = |indent_right: f32| {
let mut d = Document::from_text(j_text);
d.settings.compat_mode = wordcraft_doc::COMPAT_MODE_CURRENT;
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(Align::Justify);
p.word_wrap = Some(false);
})
.unwrap();
d
};
let base = first_para(&doc(0.0));
// "a b AVAVA" is clusters 0..9; cluster 8 is 'A', cluster 9 is 'V'.
let kern = base.clusters[8].kern;
assert!((kern.signum() as i16) == units.signum(), "{family}: {kern}");
let paired: f32 = base.clusters[..9].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_a = base.clusters[8].adv - kern;
let width = if units < 0 { alone + 4.0 } else { (paired + alone) / 2.0 };
let para = first_para(&doc(468.0 - width));
let l0 = &para.lines[0];
assert_eq!(l0.c1, 9, "{family}: expected wrap after 9th cluster");
let space_w = l0.cl_left(2).unwrap() - l0.cl_left(1).unwrap();
assert!(space_w > base.clusters[1].adv + 0.01, "{family}: spaces should widen, got {space_w} vs {}", base.clusters[1].adv);
let end = l0.cl_left(8).unwrap() + unkerned_a;
assert!((end - l0.right).abs() < 0.01, "{family}: justified end {end} should meet right edge {}", l0.right);
assert!((l0.end_x() - l0.right).abs() < 0.01);
if units < 0 {
let shrunk = first_para(&doc(468.0 - (alone - 0.5)));
let s0 = &shrunk.lines[0];
assert_eq!(s0.c1, 9, "{family}: expected shrunk wrap after 9th cluster");
let s_space = s0.cl_left(2).unwrap() - s0.cl_left(1).unwrap();
assert!(s_space < base.clusters[1].adv - 0.01, "{family}: spaces should shrink, got {s_space} vs {}", base.clusters[1].adv);
let s_end = s0.cl_left(8).unwrap() + unkerned_a;
assert!((s_end - s0.right).abs() < 0.01, "{family}: shrunk end {s_end} should meet right edge {}", s0.right);
}
}
}
#[test]
fn auto_hyphenation_uses_the_unkerned_width_before_a_negative_pair() {
crate::test_fonts();
let text = "word consideration";
let family = legacy_kern_family("Kerhy", 'n', 's', -300);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
d.settings.auto_hyphenation = true;
d.settings.hyphenation_zone = 0.0;
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let base = first_para(&doc(0.0));
let k = *base
.hyph_after
.iter()
.find(|&&k| {
let i = k as usize;
text.get(base.clusters[i].start..base.clusters[i].end) == Some("n")
&& base.clusters.get(i + 1).and_then(|c| text.get(c.start..c.end)) == Some("s")
})
.expect("expected automatic hyphenation point at \"con-sideration\"");
let k = k as usize;
let kern = base.clusters[k].kern;
assert!(kern < -0.5, "the test font kerns \"ns\": {kern}");
let paired_no_hyph: f32 = base.clusters[..=k].iter().map(|c| c.adv).sum();
// Wide enough for "word con-" with room to spare so we can measure the hyphen advance.
let probe = first_para(&doc(468.0 - (paired_no_hyph + 12.0)));
assert_eq!(probe.lines[0].c1, k + 1);
let hyph_w = probe.lines[0].hyphen.expect("probe should hyphenate at \"con-\"").2;
let paired = paired_no_hyph + hyph_w;
let alone = paired - kern;
// Between the kerned and unkerned widths (plus hyphen): "con-" would overrun the margin
// once the "ns" pair is dropped, so the line must fall back to the earlier space.
let mid = first_para(&doc(468.0 - (paired + alone) / 2.0));
let m0 = &mid.lines[0];
assert!(m0.hyphen.is_none(), "hyphenated line {} overran right edge {}", m0.end_x(), m0.right);
assert_eq!(m0.stop, "word ".len(), "expected fallback to space break, got {:?}", &text[..m0.stop]);
// Wide enough for the unkerned letters plus hyphen: the break at "con-" fits inside the margin.
let fit = first_para(&doc(468.0 - (alone + 0.004)));
let f0 = &fit.lines[0];
assert_eq!(f0.c1, k + 1);
assert!(f0.hyphen.is_some());
assert!(f0.end_x() <= f0.right + 0.01, "end_x {} ran past right edge {}", f0.end_x(), f0.right);
assert!((f0.end_x() - alone).abs() < 0.01);
}
-43
View File
@@ -1167,46 +1167,3 @@ fn a_page_reference_into_nested_text_boxes_stops_where_layout_does() {
let output = layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, ..Default::default() });
assert_eq!(shown_in(&output, 0, StoryRef::Body), ["2", "2", "9"]);
}
#[test]
fn a_page_keeps_a_multiple_spaced_picture_line_while_the_picture_fits() {
// A paragraph holding only a picture, at 1.15 spacing, as the page's last line stays on the
// page while the picture itself ends above the bottom margin; the font's descent and the
// spacing's leading below it may run into the margin. Only the picture's own extent counts:
// ending 1 pt above the margin it stays, reaching past the margin it moves on.
crate::test_fonts();
use wordcraft_doc::props::LineSpacing;
let make = |h: f32| {
let mut d = Document::from_text("A line of text\n");
for b in &mut d.body {
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(b) {
p.props.line_spacing = Some(LineSpacing::Multiple(1.15));
p.props.space_after = Some(0.0);
p.props.space_before = Some(0.0);
}
}
d.insert_object(&Pos::body(1, 0), super::rect_shape(200.0, h, Default::default()), &Default::default()).unwrap();
lay(&d)
};
let bottom = {
let s = &Document::from_text("").last_section;
s.page_h - s.margin_bottom
};
// Where the picture's line starts: below the text line, whatever the test font's height.
let control = make(10.0);
assert_eq!(control.pages.len(), 1);
let pic_top = control.pages[0]
.items
.iter()
.filter_map(|it| match it {
Placed::Lines { story: StoryRef::Body, y, para, l0, .. } if para.lines.get(*l0).is_some() => Some(*y),
_ => None,
})
.fold(f32::MIN, f32::max);
let room = bottom - pic_top;
assert!(room > 500.0, "{room}");
let fits = make(room - 1.0);
assert_eq!(fits.pages.len(), 1, "a picture ending 1 pt above the margin stays on the page ({room})");
let too_tall = make(room + 0.5);
assert_eq!(too_tall.pages.len(), 2, "a picture reaching past the margin moves on ({room})");
}
-43
View File
@@ -171,46 +171,3 @@ fn a_click_outside_a_floating_table_in_a_vertical_section_skips_its_cells() {
// Inside the table a click still lands in a cell.
assert!(l.hit(0, cx, cy, StoryRef::Body).unwrap().path.0.len() > 1);
}
/// #8986: in vertical text the next line is the next paragraph's, left of this one, at the same
/// distance along it; the first and last lines have no previous/next.
#[test]
fn turned_line_steps_to_the_adjacent_column() {
crate::test_fonts();
let mut d = Document::from_text("abc\ndef\nghi");
d.last_section.text_direction = TextDirection::Down;
let l = lay(&d);
let p = Pos::body(1, 1);
assert_eq!(l.turn_at(&p, 0), Some(TextDirection::Down));
let (next, g) = l.turned_line(&p, None, true, 0).unwrap();
assert_eq!((next.path, next.off), (Path::top(2), 1));
let (prev, _) = l.turned_line(&p, Some(g), false, 0).unwrap();
assert_eq!((prev.path, prev.off), (Path::top(0), 1));
assert!(l.turned_line(&Pos::body(2, 0), None, true, 0).is_none());
assert_eq!(lay(&Document::from_text("abc")).turn_at(&Pos::body(0, 0), 0), None);
}
/// #8986: in a table whose cells run vertical text, the next line is one of the same cell, never
/// another cell's (a cell's only line has no previous/next).
#[test]
fn turned_line_stays_in_its_table_cell() {
crate::test_fonts();
let mut d = Document::from_text("before");
let mut t = wordcraft_doc::Table::new(1, 3, 468.0);
for (i, c) in t.rows[0].cells.iter_mut().enumerate() {
c.props.text_direction = TextDirection::Down;
let paras = if i == 1 { ["abc", "def"].as_slice() } else { ["xyz"].as_slice() };
c.blocks = paras.iter().map(|s| wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(s, Default::default()))).collect();
}
d.insert_block(StoryRef::Body, &Path::top(1), Block::Table(t)).unwrap();
let l = lay(&d);
let at = |cell: u32, para: u32, off: usize| Pos { story: StoryRef::Body, path: Path(vec![1, 0, cell, para]), off };
let (next, _) = l.turned_line(&at(1, 0, 1), None, true, 0).unwrap();
assert_eq!((next.path, next.off), (Path(vec![1, 0, 1, 1]), 1));
assert!(l.turned_line(&at(1, 1, 1), None, true, 0).is_none());
assert!(l.turned_line(&at(1, 0, 1), None, false, 0).is_none());
for cell in [0, 2] {
assert!(l.turned_line(&at(cell, 0, 1), None, true, 0).is_none());
assert!(l.turned_line(&at(cell, 0, 1), None, false, 0).is_none());
}
}

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