Compare commits

..
Author SHA1 Message Date
FredAppsandClaude Opus 5.5 71741e4515 CI: Print keeps the wordcraft-web wasm check, on the macOS lint leg
The ubuntu leg was the only CI that ran cargo check -p wordcraft-web
--target wasm32-unknown-unknown: ci.yml's cargo xtask wasm checks the
library crates and ui-egui, not the web app. The check now runs once,
on the macOS lint leg, off the test legs' critical path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:14:29 +01:00
Martin BallandClaude Opus 5.5 81ac22cb33 CI: Print gate runs on Windows and macOS only, with clippy on its own leg
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCZhHKRuRB5wZUiw6BE
2026-11-20 14:50:25 +00:00
82 changed files with 246 additions and 3624 deletions
+14 -13
View File
@@ -1,4 +1,4 @@
# Exercise the native print host and all UI tests on PRs; the broad FreeBSD/ARM64 gates
# Exercise the native print host and all UI tests on Windows and macOS on PRs; the broad FreeBSD/ARM64 gates
# stay on their existing nightly/release schedule.
name: Printing
@@ -30,31 +30,32 @@ concurrency:
cancel-in-progress: true
jobs:
# The print host and UI tests on Linux, Windows and macOS, through the suite's shared gate: it
# checks out craft-i18n (craft-i18n.rev) and craft-fonts, and installs the Ubuntu packages through
# install-apt-packages, which falls back to mirrors outside ubuntu.com (as on 11 Nov 2026).
# The print host and UI tests on Windows and macOS, through the suite's shared gate: it checks out
# craft-i18n (craft-i18n.rev) and craft-fonts. Linux is not repeated here: ci.yml's gate runs
# `cargo xtask ci` there, which already covers fmt, workspace clippy, every test and the wasm build.
native:
name: Print
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["ubuntu-24.04","windows-latest","macos-latest"]'
os: '["windows-latest","macos-latest"]'
timeout-minutes: 90
# The catalogs include CJK interface languages, so the UI tests need the suite's fonts, as in
# the gate (same commit as ci.yml and release.yml).
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev
libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev libvulkan1 mesa-vulkan-drivers
# No nextest: the tests run with cargo test, as before.
tools: ""
# Its own cache, apart from ci.yml's gate, which builds the whole workspace.
cache-version: v1-printing
command: |
cargo fmt --all -- --check
# Test binaries without debug info: they link faster and shrink to about a third, and panics
# keep their file:line.
dev-strip: true
# Clippy on its own leg beside the tests, off their critical path. fmt is platform-independent
# and runs in ci.yml. The web app's wasm build, once: ci.yml's `cargo xtask wasm` checks the
# library crates and ui-egui, not apps/wordcraft-web.
lint-command: |
cargo clippy -p wordcraft -p wordcraft-ui-egui --all-targets --locked -- -D warnings
cargo test -p wordcraft -p wordcraft-ui-egui --locked
# Browser compatibility, once.
if [ "$RUNNER_OS" = Linux ]; then
if [ "$RUNNER_OS" = macOS ]; then
cargo check -p wordcraft-web --target wasm32-unknown-unknown --locked
fi
command: cargo test -p wordcraft -p wordcraft-ui-egui --locked
+1 -1
View File
@@ -73,6 +73,6 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
- `unsafe`: none; the workspace forbids it. Typing behaviour is pinned by `crates/engine/src/tests/typing.rs` and described in `docs/typing-parity.md`.
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp` (add `--connect 127.0.0.1:7981` to drive the app), see `docs/mcp.md`.
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
- Contributor credits: `docs/contributors.md`.
+5 -6
View File
@@ -206,15 +206,14 @@ Web: `cd apps/wordcraft-web && trunk serve`, then open <http://127.0.0.1:8771/?s
WordCraft was designed to be driven by people *and* by AI agents.
```sh
# headless documents; the agent reads only inside the first folder and writes only inside the second
claude mcp add wordcraft -- wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
claude mcp add wordcraft -- wordcraft-cli mcp # headless documents
# confine the agent to folders: wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
wordcraft --control 7981 & # or drive the running app…
claude mcp add wordcraft-app -- wordcraft-cli mcp --connect 127.0.0.1:7981
```
Both roots are required. Bridging an agent to the running app (`mcp --connect`) is refused until
the app confines its control channel to the same roots (#3695).
Tools include `list_commands`, `execute`, `batch`, `type_text`, `select_text`, `inspect_document`,
`render_page` and `save_document`. Agents
`render_page`, `save_document`, and, with a running app, `screenshot`, `click` and `key`. Agents
can check their work through `inspect_document` without screenshots. See [docs/mcp.md](docs/mcp.md)
and the [control protocol](docs/control-protocol.md). Macros record any sequence of commands and
play it back (`tools.recordMacro`, `tools.macros`).
+3 -15
View File
File diff suppressed because one or more lines are too long
+66 -46
View File
@@ -51,16 +51,14 @@ USAGE:
documents and with {\"id\": N} makes one active
wordcraft-cli commands [--json] list every command
wordcraft-cli parity [--markdown] feature-catalog parity
wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR [--author NAME]
MCP server on stdio, with a headless session.
Both roots are required: the agent's commands read
files (open, insert text or picture, mail-merge data,
templates…) only inside the read root and write them
(save, export, merge output…) only inside the write
root, links followed; the same folder may be both.
--connect HOST:PORT (bridge to the running app) is
refused until the app confines its control channel
(#3695, #5819).
wordcraft-cli mcp [--connect HOST:PORT | --author NAME] [--automation-read-root DIR] [--automation-write-root DIR]
MCP server on stdio (headless, or bridged to the app).
--automation-read-root / --automation-write-root confine
the files the agent's commands read (open, insert text
or picture, mail-merge data, templates…) and write (save,
export, merge output…) to DIR, links followed; a root left
out grants none of its access. They apply to the headless
server and are an error with --connect.
wordcraft-cli zotero <command> <file> [--cmd 'id={json}' …] [--save OUT] [--trace] [--port P]
run a Zotero command on a document (Zotero must be
running): addEditCitation, addEditBibliography,
@@ -219,19 +217,6 @@ fn set_author(s: &mut Session, name: &str) -> Result<(), String> {
s.run("file.setAuthor", &json!({"name": name})).map(|_| ()).map_err(|e| escape_text(&format!("--author: {e}"), false))
}
/// `mcp`'s headless backend: a session confined to `roots`, its author `author` when given. The caller confines the
/// process to the same roots first (`confine_process`), which a test must not do.
fn headless_mcp(
roots: std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>,
author: Option<&str>,
) -> Result<wordcraft_mcp::Headless, String> {
let mut headless = wordcraft_mcp::Headless::default().with_automation_roots(Some(roots));
if let Some(name) = author {
set_author(&mut headless.session, name)?;
}
Ok(headless)
}
fn arg_value(args: &[String], name: &str) -> Option<String> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()
}
@@ -367,16 +352,6 @@ const RUN_OPTIONS: &[OptionSpec] = &[
];
const COMMANDS_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_value: false }];
const PARITY_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--markdown", takes_value: false }];
/// Why `mcp` won't start unconfined (shared rule 18, #7124).
const MCP_NEEDS_ROOTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR: an agent's \
commands may read only inside the read root and write only inside the write root (the same folder may be both)";
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
--automation-read-root DIR --automation-write-root DIR";
const MCP_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--connect", takes_value: true }, OptionSpec { name: "--author", takes_value: true }];
const ZOTERO_OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--cmd", takes_value: true },
@@ -441,6 +416,14 @@ fn script_operand<S: AsRef<OsStr>>(raw: &[S]) -> Option<PathBuf> {
raw.get(at + 1).map(|a| PathBuf::from(a.as_ref()))
}
/// Whether `addr` (`HOST:PORT`, as `--connect` gives it) is at least shaped like an address: a
/// host of some kind and a numeric port. Malformed addresses fail at startup — a lazy remote
/// would otherwise retry one on every call and never say why nothing connects.
fn valid_connect_addr(addr: &str) -> bool {
let Some((host, port)) = addr.rsplit_once(':') else { return false };
!host.is_empty() && port.parse::<u16>().is_ok()
}
/// A failed `--strict` export: a strict refusal becomes [`Failure::Strict`] carrying what stderr
/// shows (each line of the report as `wordcraft-cli: …`, then its JSON on one line, from
/// `file.strictReport` for `page` of a page image, else the PDF); any other error is an ordinary
@@ -733,21 +716,58 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
}
"mcp" => {
let (roots, rest) = automation_roots("mcp", &rest)?;
// Refused with or without a value, before the option check, so `--connect=…` gets this refusal rather than
// "unknown option": a bare trailing `--connect` must not slip past either.
if rest.iter().any(|a| a == "--connect" || a.starts_with("--connect=")) {
return Err(MCP_CONNECT_REFUSED.into());
}
validate_options("mcp", &rest, MCP_OPTIONS)?;
// Shared rule 18 (#7124): an agent entry point never runs unconfined.
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
return Err(MCP_NEEDS_ROOTS.into());
let author = arg_value(&rest, "--author");
let connect = arg_value(&rest, "--connect");
if roots.is_some() && connect.is_some() {
return Err(
"mcp: --automation-read-root and --automation-write-root confine the headless server; a running app is not confined by them"
.into(),
);
}
let backend: Box<dyn wordcraft_mcp::Backend> = match connect {
// The app's user name is the person's own setting; don't rewrite it from a flag.
Some(_) if author.is_some() => {
return Err("mcp: --author applies to the headless server; with --connect, run file.setAuthor".into());
}
Some(addr) => {
// A malformed address must fail at startup, not on every tool call the lazy
// remote would retry it with.
if !valid_connect_addr(&addr) {
return Err(format!("mcp: --connect needs HOST:PORT with a numeric port, got `{addr}`").into());
}
match wordcraft_mcp::Remote::connect(&addr) {
Ok(remote) => {
eprintln!("wordcraft-cli mcp: connected to WordCraft at {addr}");
if let Some(w) = remote.key_warning() {
eprintln!("wordcraft-cli: {w}");
}
Box::new(remote)
}
// The app may start after the client does: serve anyway and connect on the
// first call, or the client marks the server failed for its whole session
// (#4078).
Err(e) => {
eprintln!("wordcraft-cli mcp: WordCraft is not reachable at {addr} yet ({e}); will retry on each call");
Box::new(wordcraft_mcp::Remote::lazy(&addr))
}
}
}
None => {
let mut headless = wordcraft_mcp::Headless::default();
if let Some(roots) = roots {
// Every thread of this process, not only the server's: nothing reaches past the roots.
wordcraft_engine::file_access::confine_process(roots.clone());
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
headless = headless.with_automation_roots(Some(roots));
}
if let Some(name) = author {
set_author(&mut headless.session, &name)?;
}
Box::new(headless)
}
};
// Every thread of this process, not only the server's: nothing reaches past the roots.
wordcraft_engine::file_access::confine_process(roots.clone());
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, arg_value(&rest, "--author").as_deref())?);
let mut server = wordcraft_mcp::Server::new(backend);
let stdin = std::io::stdin();
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
+8 -105
View File
@@ -126,6 +126,11 @@ fn author_flag_names_the_headless_session() {
assert_eq!(s.author, "Claude (copyedit)");
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
assert!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])).is_ok());
// The app's user name is the person's own; a bridge flag must not rewrite it.
assert!(run(&args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"])).is_err_and(|e| e.to_string().contains("--author")));
// A malformed address fails at startup, not on every retried call.
assert!(run(&args(&["mcp", "--connect", "127.0.0.1:notaport"])).is_err_and(|e| e.to_string().contains("numeric port")));
assert!(run(&args(&["mcp", "--connect", "notaport"])).is_err_and(|e| e.to_string().contains("numeric port")));
// The flag goes through the same protection check as the command.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
@@ -235,113 +240,11 @@ fn only_the_opened_file_may_be_other_than_unicode() {
}
}
/// An exclusively created scratch folder, removed on drop even when an assertion fails.
struct Scratch(PathBuf);
impl Scratch {
fn new(tag: &str) -> Self {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
loop {
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("wc-cli-{tag}-{}-{n}", std::process::id()));
// `create_dir` fails when the path exists, so a leftover or a planted folder is never reused. Any
// other failure (no temp folder, no permission) fails every name: report it instead of looping.
match std::fs::create_dir(&dir) {
Ok(()) => return Self(dir),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => panic!("scratch folder {}: {e}", dir.display()),
}
}
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Shared rule 18 (#7124): every agent entry point, a subcommand that serves a client's requests
/// rather than running what the person typed and exiting, refuses to start without both
/// automation roots. Each subcommand has a row, so a new one fails here until it is classified,
/// and a new agent entry point fails until it refuses.
#[test]
fn every_agent_entry_point_refuses_to_start_without_both_roots() {
enum Kind {
Agent,
NotAgent(&'static str),
}
use Kind::{Agent, NotAgent};
let table = [
("convert", NotAgent("converts the files named on its command line, then exits")),
("info", NotAgent("reads the one file named on its command line, then exits")),
("text", NotAgent("reads the one file named on its command line, then exits")),
("inspect", NotAgent("reads the one file named on its command line, then exits")),
("render", NotAgent("renders the file named on its command line, then exits")),
("run", NotAgent("runs the commands and script named on its command line, then exits")),
("commands", NotAgent("lists the commands; touches no file")),
("parity", NotAgent("prints the feature catalog; touches no file")),
("mcp", Agent),
("zotero", NotAgent("runs one named Zotero command; Zotero's replies edit citations and name no file")),
];
assert_eq!(table.iter().map(|(name, _)| *name).collect::<Vec<_>>(), SUBCOMMANDS);
let scratch = Scratch::new("entry");
let base = scratch.0.clone();
std::fs::create_dir_all(base.join("in")).unwrap();
std::fs::create_dir_all(base.join("out")).unwrap();
let read = format!("--automation-read-root={}", base.join("in").display());
let write = format!("--automation-write-root={}", base.join("out").display());
for (name, kind) in table {
if let NotAgent(why) = kind {
assert!(!why.is_empty(), "{name}: say why it is not an agent entry point");
continue;
}
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
let line = [vec![name.to_string()], given].concat();
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--automation-read-root") && e.contains("--automation-write-root"), "{line:?}: {e}");
}
}
}
/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge
/// to it is refused, with roots or without, before anything connects.
#[test]
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
fn automation_roots_are_an_error_with_connect() {
let dir = std::env::temp_dir().to_string_lossy().into_owned();
for line in [
args(&["mcp", "--connect", "127.0.0.1:9"]),
args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]),
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
] {
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
}
}
/// `mcp`'s headless session takes `--author` as the session's author, and refuses a blank one as `run` does.
#[test]
fn mcp_headless_session_takes_the_author_flag() {
let scratch = Scratch::new("mcp-author");
let roots = wordcraft_engine::file_access::AutomationRoots::new(Some(&scratch.0), Some(&scratch.0)).unwrap().unwrap();
assert_eq!(headless_mcp(roots.clone(), Some("Claude (copyedit)")).unwrap().session.author, "Claude (copyedit)");
assert!(headless_mcp(roots.clone(), Some(" ")).is_err_and(|e| e.starts_with("--author:")));
let unnamed = headless_mcp(roots, None).unwrap();
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
}
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
#[test]
fn mcp_connect_is_refused_without_a_value_too() {
let scratch = Scratch::new("connect-bare");
let dir = scratch.0.to_string_lossy().into_owned();
let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir];
for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"], vec!["--connect=127.0.0.1:9"], vec!["--connect="]] {
let line = args(&[&["mcp"][..], &roots, &tail].concat());
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
}
let e = run(&args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir])).unwrap_err().to_string();
assert!(e.contains("--automation-read-root") && e.contains("headless"), "{e}");
}
#[test]
+1 -13
View File
@@ -24,19 +24,7 @@ fn commands_json_into_a_closed_pipe_exits_quietly() {
#[test]
fn mcp_server_ends_cleanly_when_its_client_closes_stdout() {
// The server starts only with both roots (#7124); the temporary folder serves as both.
let root = std::env::temp_dir();
let mut child = cli()
.arg("mcp")
.arg("--automation-read-root")
.arg(&root)
.arg("--automation-write-root")
.arg(&root)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut child = cli().arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
drop(child.stdout.take());
let mut stdin = child.stdin.take().unwrap();
// The reply to this request has nowhere to go.
-1
View File
@@ -3,7 +3,6 @@ mod closed_stdout;
mod convert_fields;
mod convert_region;
mod help;
mod mcp_roots;
#[cfg(all(unix, not(target_os = "macos")))]
mod non_utf8_args;
mod picture_then_typing;
-179
View File
@@ -1,179 +0,0 @@
//! Shared rule 18 (#7124): `wordcraft-cli mcp` refuses to start without both
//! `--automation-read-root` and `--automation-write-root`, refuses `--connect` while the desktop
//! app doesn't confine its control channel (#3695, #5819), and with both roots refuses files
//! outside them, through the real binary.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::{Value, json};
/// An exclusively created folder holding `in` (the read root, with `a.txt`), `out` (the write
/// root) and `outside` (with `secret.txt`). Removed on drop, even when an assertion fails.
struct Folders(PathBuf);
impl Folders {
fn new(tag: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let base = loop {
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("wc-cli-mcp-roots-{tag}-{}-{n}", std::process::id()));
// `create_dir` fails when the path exists, so a leftover or a planted folder is never reused. Any
// other failure (no temp folder, no permission) fails every name: report it instead of looping.
match std::fs::create_dir(&dir) {
Ok(()) => break dir,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => panic!("scratch folder {}: {e}", dir.display()),
}
};
let folders = Self(base);
for d in ["in", "out", "outside"] {
std::fs::create_dir_all(folders.0.join(d)).unwrap();
}
std::fs::write(folders.0.join("in/a.txt"), "Inside text").unwrap();
std::fs::write(folders.0.join("outside/secret.txt"), "TOP SECRET").unwrap();
folders
}
}
impl Drop for Folders {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn s(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
/// Run `wordcraft-cli mcp <args>`, send `lines` on stdin, then hang up.
fn mcp(args: &[String], lines: &[Value]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
.arg("mcp")
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
for line in lines {
// A server that refused to start has closed its end: that is the expected outcome.
let _ = writeln!(stdin, "{line}");
}
drop(stdin);
child.wait_with_output().unwrap()
}
const PING: &str = r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#;
fn refused_at_start(args: &[String], why: &[&str]) {
let out = mcp(args, &[serde_json::from_str(PING).unwrap()]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success(), "{args:?} started: stderr {stderr}");
assert!(out.stdout.is_empty(), "{args:?} served: {}", String::from_utf8_lossy(&out.stdout));
for w in why {
assert!(stderr.contains(w), "{args:?}: `{w}` missing from {stderr}");
}
assert!(!stderr.contains("panicked"), "{stderr}");
}
#[test]
fn mcp_refuses_to_start_without_both_roots() {
let folders = Folders::new("start");
let base = folders.0.clone();
let (read, write) = (s(&base.join("in")), s(&base.join("out")));
let both = ["--automation-read-root", "--automation-write-root"];
refused_at_start(&[], &both);
refused_at_start(&["--author".into(), "Claude".into()], &both);
refused_at_start(&["--automation-read-root".into(), read.clone()], &both);
refused_at_start(&[format!("--automation-write-root={write}")], &both);
// Both: it serves.
let out = mcp(&["--automation-read-root".into(), read, "--automation-write-root".into(), write], &[serde_json::from_str(PING).unwrap()]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "stderr: {stderr}");
let reply: Value = serde_json::from_slice(out.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap();
assert_eq!(reply["id"], 1, "{reply}");
assert!(reply.get("error").is_none(), "{reply}");
}
#[test]
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
let folders = Folders::new("connect");
let base = folders.0.clone();
let (read, write) = (s(&base.join("in")), s(&base.join("out")));
let why = ["--connect", "#3695", "#5819"];
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &why);
refused_at_start(
&["--connect".into(), "127.0.0.1:9".into(), "--automation-read-root".into(), read, "--automation-write-root".into(), write],
&why,
);
}
/// `tools/call` request `id` for `name` with `arguments`.
fn tool(id: u64, name: &str, arguments: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": arguments}})
}
fn execute(id: u64, command: &str, params: Value) -> Value {
tool(id, "execute", json!({"command": command, "params": params}))
}
#[test]
fn mcp_with_both_roots_refuses_files_outside_them() {
let folders = Folders::new("files");
let base = folders.0.clone();
let sep = std::path::MAIN_SEPARATOR;
let (inside, outside) = (base.join("in"), base.join("outside"));
let secret = s(&outside.join("secret.txt"));
let up = |root: &str, rest: &str| format!("{}{sep}..{sep}{rest}", s(&base.join(root)));
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(&outside, base.join("out/away")).is_ok()
&& std::os::unix::fs::symlink(outside.join("secret.txt"), inside.join("leak.txt")).is_ok();
#[cfg(not(unix))]
let linked = false;
// (id, request, refused with). Reads first, then writes, then the allowed ones.
let mut cases = vec![
(2, tool(2, "open_document", json!({"path": secret})), Some("outside the read root")),
(3, execute(3, "file.open", json!({"path": secret})), Some("outside the read root")),
(4, execute(4, "file.open", json!({"path": up("in", "outside/secret.txt")})), Some("outside the read root")),
(5, execute(5, "insert.picture", json!({"path": s(&outside.join("pic.png"))})), Some("outside the read root")),
(6, execute(6, "insert.textFromFile", json!({"path": secret})), Some("outside the read root")),
(7, tool(7, "save_document", json!({"path": s(&outside.join("a.docx"))})), Some("outside the write root")),
(8, execute(8, "file.saveAs", json!({"path": s(&outside.join("b.docx"))})), Some("outside the write root")),
(9, execute(9, "file.exportPdf", json!({"path": s(&outside.join("c.pdf"))})), Some("outside the write root")),
(10, execute(10, "file.exportPng", json!({"path": s(&outside.join("d.png"))})), Some("outside the write root")),
(11, execute(11, "file.saveAs", json!({"path": up("out", "outside/e.docx")})), Some("outside the write root")),
// The write root isn't readable, nor the read root writable.
(12, execute(12, "file.saveAs", json!({"path": s(&inside.join("f.docx"))})), Some("outside the write root")),
(13, tool(13, "open_document", json!({"path": s(&inside.join("a.txt"))})), None),
(14, execute(14, "file.saveAs", json!({"path": s(&base.join("out/g.docx"))})), None),
];
if linked {
cases.push((15, tool(15, "open_document", json!({"path": s(&inside.join("leak.txt"))})), Some("outside the read root")));
cases.push((16, execute(16, "file.saveAs", json!({"path": s(&base.join("out/away/h.docx"))})), Some("outside the write root")));
}
let requests: Vec<Value> = cases.iter().map(|(_, r, _)| r.clone()).collect();
let out = mcp(&["--automation-read-root".into(), s(&inside), "--automation-write-root".into(), s(&base.join("out"))], &requests);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "stderr: {stderr}");
let replies: Vec<Value> =
String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.trim().is_empty()).map(|l| serde_json::from_str(l).unwrap()).collect();
for (id, request, why) in &cases {
let reply = replies.iter().find(|r| r["id"] == *id).unwrap_or_else(|| panic!("no reply to {request}"));
let result = &reply["result"];
let text: String = result["content"].as_array().into_iter().flatten().filter_map(|c| c["text"].as_str()).collect();
match why {
Some(why) => assert!(result["isError"] == true && text.contains(why), "{request} should be refused ({why}): {reply}"),
None => assert!(result["isError"] != true, "{request}: {reply}"),
}
}
let mut written: Vec<String> = std::fs::read_dir(&outside).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
written.sort();
assert_eq!(written, ["secret.txt"], "nothing was written outside the roots");
assert!(!inside.join("f.docx").exists());
assert!(base.join("out/g.docx").is_file());
}
+2 -1
View File
@@ -544,7 +544,8 @@ fn main() -> eframe::Result {
if prefs::enabled()
&& let Some(path) = prefs::user_dict_path()
{
prefs::load_user_dictionary(&mut session, &settings, path);
prefs::load_user_dictionary(&settings, &path);
session.user_dict_path = Some(path);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
+6 -114
View File
@@ -61,49 +61,11 @@ fn import_window(path: &Path, placement: &mut Store) {
}
}
/// Loads the custom dictionary into the spell checker and counts its words as loaded settings:
/// the words only the file has are in `Prefs::dictionary`, so the app's preferences list is the
/// whole dictionary (#3773). `default_path` is `custom-dictionary.txt` in the settings folder.
///
/// A bound custom dictionary file (`editing.custom_dictionary`, #5840) that reads is the source of
/// truth and the write target. If it is missing or unreadable, the default file is read for
/// spelling only and `user_dict_path` stays unset, so later writes never go to the default file
/// while the setting still names the custom one. With no custom file, the default is read and written.
pub fn load_user_dictionary(session: &mut wordcraft_engine::Session, settings: &SharedSettings<Prefs>, default_path: PathBuf) {
session.default_user_dict_path = Some(default_path.clone());
let custom = settings.lock().get().editing.custom_dictionary.as_ref().map(PathBuf::from);
let mut words = Vec::new();
let mut loaded = false;
if let Some(p) = &custom {
if p.is_file() {
match wordcraft_engine::custom_dict::load_custom_dictionary_replacing(p) {
Ok(w) => {
words = w;
session.user_dict_path = Some(p.clone());
loaded = true;
}
Err(e) => log::warn!("custom dictionary: failed to load '{}': {e}", p.display()),
}
} else {
log::warn!("custom dictionary: '{}' is not a regular file", p.display());
}
}
if !loaded {
if default_path.is_file() {
if custom.is_some() {
match wordcraft_engine::custom_dict::load_custom_dictionary_replacing(&default_path) {
Ok(w) => words = w,
Err(e) => log::warn!("default dictionary: failed to load '{}': {e}", default_path.display()),
}
} else {
words = wordcraft_proof::load_user_dictionary(&default_path);
session.user_dict_path = Some(default_path);
}
} else if custom.is_none() {
// A missing default file is not a replacement: keep any words restored from preferences.
session.user_dict_path = Some(default_path);
}
}
/// Loads the words of the custom dictionary file at `path` into the spell checker, and counts them
/// as loaded settings: the words only the file has are in `Prefs::dictionary`, so the app's
/// preferences list is the whole dictionary (#3773).
pub fn load_user_dictionary(settings: &SharedSettings<Prefs>, path: &Path) {
let words = wordcraft_proof::load_user_dictionary(path);
settings.lock().update(|prefs| {
for word in words {
if !prefs.dictionary.contains(&word) {
@@ -150,7 +112,7 @@ mod tests {
std::fs::write(&dict, "zqxinfile\n").unwrap();
let (settings, report) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
assert!(matches!(report.source, Source::Legacy(_)), "ui.json is imported: {:?}", report.source);
load_user_dictionary(&mut wordcraft_engine::Session::new(wordcraft_doc::Document::new()), &settings, dict.clone());
load_user_dictionary(&settings, &dict);
let words = settings.lock().get().dictionary.clone();
for word in ["zqxinjson", "zqxinfile"] {
assert!(words.iter().any(|w| w == word), "{word}: {words:?}");
@@ -204,74 +166,4 @@ mod tests {
assert_eq!(now.ribbon.qat, None, "A's old copy of the toolbar does not bring it back");
assert!(now.dictionary.iter().any(|w| w == "zqxtoolbar"), "A's own change is kept");
}
/// The tests that bind a custom dictionary replace the spell checker's words, which every
/// test shares: one at a time.
static CUSTOM_DICT: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// #5840: while the setting names a custom file that is missing, the default file is read
/// for spelling only. Nothing becomes the write target, so Add to Dictionary never moves the
/// person's words into `custom-dictionary.txt` behind the setting's back.
#[test]
fn a_missing_custom_dictionary_leaves_no_write_target() {
let _one = CUSTOM_DICT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = tempfile::tempdir().unwrap();
let default = dir.path().join("custom-dictionary.txt");
std::fs::write(&default, "zqxfallbackword\n").unwrap();
let (settings, _) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
let missing = dir.path().join("gone").join("CUSTOM.DIC");
settings.lock().update(|p| p.editing.custom_dictionary = Some(missing.to_string_lossy().into_owned()));
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path, None, "no write target while the custom file is missing");
assert_eq!(session.default_user_dict_path.as_deref(), Some(default.as_path()));
assert!(wordcraft_engine::proof::user_dictionary().iter().any(|w| w == "zqxfallbackword"), "the default file still spells");
wordcraft_engine::proof::remove_word("zqxfallbackword");
}
/// #5840: a custom file that is set but missing, with no default file either: nothing is a
/// write target (the `custom.is_none()` arm does not claim the default), and nothing panics.
#[test]
fn a_missing_custom_and_default_dictionary_leave_no_write_target() {
let _one = CUSTOM_DICT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = tempfile::tempdir().unwrap();
let default = dir.path().join("custom-dictionary.txt");
let (settings, _) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
let missing = dir.path().join("gone").join("CUSTOM.DIC");
settings.lock().update(|p| p.editing.custom_dictionary = Some(missing.to_string_lossy().into_owned()));
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path, None, "no write target while the custom file is missing");
assert_eq!(session.default_user_dict_path.as_deref(), Some(default.as_path()));
assert_eq!(settings.lock().get().editing.custom_dictionary.as_deref(), Some(&*missing.to_string_lossy()), "the setting is kept");
}
/// #5840: with no custom file set, the default file is the write target, whether or not it
/// exists yet; a readable custom file is the write target when it is set.
#[test]
fn the_write_target_is_the_default_file_unless_a_custom_one_reads() {
let _one = CUSTOM_DICT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = tempfile::tempdir().unwrap();
let default = dir.path().join("custom-dictionary.txt");
let (settings, _) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path.as_deref(), Some(default.as_path()), "a missing default file is still the target");
std::fs::write(&default, "zqxdefaultword\n").unwrap();
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path.as_deref(), Some(default.as_path()));
let custom = dir.path().join("CUSTOM.DIC");
std::fs::write(&custom, "zqxcustomword\r\n").unwrap();
settings.lock().update(|p| p.editing.custom_dictionary = Some(custom.to_string_lossy().into_owned()));
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path.as_deref(), Some(custom.as_path()), "a readable custom file is the target");
let words = wordcraft_engine::proof::user_dictionary();
assert!(words.iter().any(|w| w == "zqxcustomword") && !words.iter().any(|w| w == "zqxdefaultword"), "{words:?}");
wordcraft_engine::proof::remove_word("zqxcustomword");
wordcraft_engine::proof::remove_word("zqxdefaultword");
}
}
+2 -7
View File
@@ -118,13 +118,8 @@ impl ResolvedChar {
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(),
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
// Word for Windows). Other runs, including those no DOCX marked, still borrow the
// Latin values. The size keeps borrowing `w:sz` until generated styles carry a
// `w:szCs` (#4197).
bold_cs: c.bold_cs.or(c.bold.filter(|_| c.cs != Some(true))).unwrap_or(false),
italic_cs: c.italic_cs.or(c.italic.filter(|_| c.cs != Some(true))).unwrap_or(false),
bold_cs: c.bold_cs.or(c.bold).unwrap_or(false),
italic_cs: c.italic_cs.or(c.italic).unwrap_or(false),
}
}
/// The formatting complex-script text in this run is drawn with: the complex-script font,
@@ -142,34 +142,6 @@ fn complex_script_direct_properties_leave_latin_defaults_inherited() {
});
}
#[test]
fn complex_script_runs_take_bold_and_italic_only_from_bcs_and_ics() {
// Word draws Thai marked `w:cs` with `<w:b/><w:i/>` and no `w:bCs`/`w:iCs` neither bold nor
// italic, through a style too; a run not marked `w:cs`, as older writers leave Hebrew, still
// borrows the Latin values (Word draws such Hebrew bold). The Latin text of every run keeps
// `w:b` and `w:i`. Measured in Word for Windows.
let styles = r#"
<w:style w:type="paragraph" w:styleId="LatinBold"><w:name w:val="LatinBold"/><w:rPr><w:b/><w:i/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="BothBold"><w:name w:val="BothBold"/><w:rPr><w:bCs/><w:iCs/></w:rPr></w:style>"#;
let cases = [
(r#"<w:b/><w:i/><w:cs/>"#, "", false),
(r#"<w:cs/>"#, r#"<w:pStyle w:val="LatinBold"/>"#, false),
(r#"<w:b/><w:i/><w:cs/>"#, r#"<w:pStyle w:val="BothBold"/>"#, true),
(r#"<w:b/><w:bCs/><w:i/><w:iCs/><w:cs/>"#, "", true),
(r#"<w:b/><w:i/>"#, "", true),
];
for (run, style, complex) in cases {
check_generations(&package(run, "", styles, style), |d| {
let p = paragraph(d);
let c = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props);
let cs = c.complex();
assert_eq!((cs.bold, cs.italic), (complex, complex), "{run} {style}");
let latin = run.contains("<w:b/>") || style.contains("LatinBold");
assert_eq!((c.bold, c.italic), (latin, latin), "Latin text: {run} {style}");
});
}
}
#[test]
fn tracked_formatting_keeps_independent_complex_script_values() {
let defaults = r#"<w:szCs w:val="36"/><w:bCs/><w:iCs/>"#;
-10
View File
@@ -376,12 +376,6 @@ pub fn type_text_with_lang(s: &mut Session, text: &str, language: Option<&str>)
/// right-to-left direction when its first strong letter is RTL, and returns whether content or state
/// changed.
fn insert_text(s: &mut Session, text: &str, enter: bool, language: Option<&str>) -> Result<InsertEffect, CmdError> {
// Formatting Backspace carried over is for typing at the place it was deleted (#6518).
if enter {
s.drop_stale_carried();
} else {
s.forget_carried();
}
let mut props = s.typing_props();
if s.sel.is_collapsed() {
s.sel = crate::Selection::caret(s.doc.past_field_ends(&s.sel.focus));
@@ -443,10 +437,6 @@ fn insert_text(s: &mut Session, text: &str, enter: bool, language: Option<&str>)
}
}
}
// Formatting Backspace carried over goes on applying to the text typed after this (#6518).
if s.pending_at.is_some() {
s.pending_at = Some(at.clone());
}
s.sel = crate::Selection::caret(at);
s.goal_x = None;
let content_changed = deletion.content_changed || inserted;
+1 -7
View File
@@ -155,20 +155,14 @@ fn style_set(s: &mut Session, v: &Value) -> CmdResult {
match name {
"basic" if heading => {
st.chr.color = Some(TextColor::Rgb(Rgb(0x26, 0x26, 0x26)));
// Both scripts, as Word's own heading styles carry `w:b` with `w:bCs`: a Thai
// heading in a run marked `w:cs` is drawn bold too.
st.chr.bold = Some(true);
st.chr.bold_cs = Some(true);
}
"lines" if st.id == "Heading1" || st.id == "Title" => st.para.borders = Some(Borders { bottom: Some(line), ..Default::default() }),
"shaded" if st.id == "Heading1" => {
st.para.shading = Some(accent);
st.chr.color = Some(TextColor::Rgb(Rgb::WHITE));
}
"casual" if heading => {
st.chr.italic = Some(true);
st.chr.italic_cs = Some(true);
}
"casual" if heading => st.chr.italic = Some(true),
"centered" if heading => st.para.align = Some(wordcraft_doc::Align::Center),
"minimalist" if heading => {
st.chr.caps = Some(true);
+7 -14
View File
@@ -131,7 +131,7 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("file.printPdf", "Print to PDF", "File › Print", crate::print::print_pdf_to_file)
.params(
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size), "compress"?: bool (default true: compress the PDF's content streams; false writes the same pages uncompressed, which is larger)"#,
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size)}"#,
)
.pure(),
CommandSpec::new("file.print", "Print", "File", |s, _| {
@@ -485,8 +485,8 @@ fn save_as(s: &mut Session, v: &Value) -> CmdResult {
}
/// How a copy is written: Print Markup from the command's `markup`, else the File › Print
/// setting (`file.printMarkup`); comments and revision marks/colours as Track Changes Options show them;
/// digits as the Numeral setting shows them on screen.
/// setting (`file.printMarkup`); comments as Track Changes Options show them; digits as the
/// Numeral setting shows them on screen.
pub fn export_options(s: &Session, v: &Value) -> crate::io::ExportOptions {
let markup = p::bool(v, "markup").unwrap_or(s.prefs.print_markup);
crate::io::ExportOptions {
@@ -494,7 +494,6 @@ pub fn export_options(s: &Session, v: &Value) -> crate::io::ExportOptions {
comments: markup && s.prefs.markup.comments,
word2003: p::str(v, "format") == Some(FORMAT_WORD_2003),
numeral: s.view.numeral.resolve(crate::session::system_locale()),
revisions: s.prefs.markup.clone(),
strict: p::bool(v, "strict").unwrap_or(false),
}
}
@@ -518,10 +517,7 @@ fn strict_report(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {}", page + 1)));
}
// The page image `file.exportPng` writes: the printed page, tracked changes marked as
// Track Changes Options mark them.
let display = crate::io_ext::page_image_options(&opts).display;
crate::strict::strict_report(&s.doc, &l, &display, Some(page..=page), wordcraft_layout::StrictOutput::Png)
crate::strict::strict_report(&s.doc, &l, &crate::strict::png_display(), Some(page..=page), wordcraft_layout::StrictOutput::Png)
}
None => {
let out = super::references::output_fields(&s.doc);
@@ -531,7 +527,6 @@ fn strict_report(s: &mut Session, v: &Value) -> CmdResult {
Ok(report.to_json())
}
/// Exports a page of the current document as a PNG image at the requested scale.
fn export_png(s: &mut Session, v: &Value) -> CmdResult {
// No path: the app asks where to save, as file.exportPdf does (#2313).
let Some(path) = p::str(v, "path") else {
@@ -541,13 +536,11 @@ fn export_png(s: &mut Session, v: &Value) -> CmdResult {
let page = crate::p::page_index(p::u64(v, "page").unwrap_or(1));
let strict = p::bool(v, "strict").unwrap_or(false);
let scale = p::f32(v, "scale").unwrap_or(2.0).clamp(0.1, 8.0);
let export = export_options(s, v);
let l = s.export_layout_with(export.markup);
let l = s.export_layout_with(export_options(s, v).markup);
let pg = l.pages.get(page).ok_or_else(|| CmdError::Params(format!("no page {}", page + 1)))?;
// A page image is the printed page: headers and footers at full strength. Dimming them is
// the on-screen cue while editing the body, not part of the page. Tracked changes are marked
// as Track Changes Options mark them on screen.
let opts = crate::io_ext::page_image_options(&export);
// the on-screen cue while editing the body, not part of the page.
let opts = wordcraft_render::RenderOptions { display: crate::strict::png_display(), ..Default::default() };
if !path.to_ascii_lowercase().ends_with(".png") {
return Err(CmdError::Params("path must end in .png".into()));
}
+5 -20
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
toggle(
s,
v,
shown_bold,
|r| r.bold,
|c, on| {
c.bold = Some(on);
c.bold_cs = Some(on);
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
toggle(
s,
v,
shown_italic,
|r| r.italic,
|c, on| {
c.italic = Some(on);
c.italic_cs = Some(on);
@@ -281,10 +281,7 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
return out;
}
}
// Formatting waiting at a caret is what the caret shows, also inside a word: after Backspace
// it is the deleted character's (#6518), as Word's buttons show it.
let waiting = s.sel.is_collapsed() && s.waiting().is_some();
let Some((a, b)) = selected_text_box(s).or_else(|| target(s)).filter(|_| !waiting) else {
let Some((a, b)) = selected_text_box(s).or_else(|| target(s)) else {
let f = &s.sel.focus;
let style = s.doc.para_at(f).and_then(|p| p.props.style.clone());
out.push(s.doc.styles.resolve_char(style.as_deref(), &s.typing_props()));
@@ -313,18 +310,6 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
/// complex-script bold.
fn shown_bold(r: &ResolvedChar) -> bool {
if r.cs || r.rtl { r.bold_cs } else { r.bold }
}
/// Italic as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
/// complex-script italic.
fn shown_italic(r: &ResolvedChar) -> bool {
if r.cs || r.rtl { r.italic_cs } else { r.italic }
}
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
let on = match p::bool(v, "value") {
Some(b) => b,
@@ -902,8 +887,8 @@ pub fn state(s: &Session) -> Value {
"fontShownAs": shown_as,
"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),
"bold": all.iter().all(|r| r.bold),
"italic": all.iter().all(|r| r.italic),
"underline": all.iter().all(|r| r.underline != Underline::None),
"underlineColor": same(&|r| json!(r.underline_color.map_or_else(|| "auto".to_string(), |c| c.hex()))),
"strike": all.iter().all(|r| r.strike),
+1 -1
View File
@@ -114,7 +114,7 @@ fn place_picture(s: &mut Session, bytes: Vec<u8>, width: Option<f32>, alt: &str)
Err(wordcraft_geom::picture::Refusal::Unsupported(why)) => return Err(CmdError::Failed(why.into())),
Err(_) => match wordcraft_render::metafile_size(&bytes) {
Some(size) => size,
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, TIFF, WMF, EMF)".into())),
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, WMF, EMF)".into())),
},
};
let key = s.doc.add_media(bytes, ext);
+1 -80
View File
@@ -18,12 +18,11 @@ pub const MAX_WORD_CHARS: usize = 64;
/// Most words one call may add or remove.
const MAX_WORDS_PER_CALL: usize = 1000;
/// Command specifications for options commands.
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("file.options", "Options", "File", options)
.params(
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "customDictionary"?: string (a custom-word dictionary file like custom.dic, saved; auto: the default custom-dictionary.txt in the settings folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
)
.pure(),
CommandSpec::new("text.overtype", "Overtype", "File › Options › Advanced", |s, v| {
@@ -79,7 +78,6 @@ fn words_param(v: &Value, k: &str) -> Result<Vec<String>, CmdError> {
Ok(out)
}
/// Open File › Options (or change settings programmatically via `file.options`).
fn options(s: &mut Session, v: &Value) -> CmdResult {
let pane = match p::str(v, "pane") {
Some(name) if PANES.contains(&name) => name,
@@ -122,18 +120,6 @@ fn options(s: &mut Session, v: &Value) -> CmdResult {
Some(Value::String(f)) => Some(folder_setting("dictionariesFolder", f, false)?),
Some(_) => return Err(CmdError::Params("`dictionariesFolder` must be a folder path, or auto".into())),
};
let custom_dictionary = match v.get("customDictionary") {
None | Some(Value::Null) => None,
Some(Value::String(f)) => Some(file_setting("customDictionary", f)?),
Some(_) => return Err(CmdError::Params("`customDictionary` must be a file path, or auto".into())),
};
// Decode the requested dictionary while still only validating: a file that passes the
// metadata and access checks but can't be decoded refuses the call before `author`, `units`,
// `region` or any other setting changes.
let custom_dictionary_state = match custom_dictionary {
None => None,
Some(ref f) => Some((prepare_custom_dictionary(s, f.as_deref())?, f.clone())),
};
let templates_folder = match v.get("userTemplatesFolder") {
None | Some(Value::Null) => None,
// Never a folder on another machine (#2852): listing it would make Windows authenticate there.
@@ -167,7 +153,6 @@ fn options(s: &mut Session, v: &Value) -> CmdResult {
|| units.is_some()
|| region.is_some()
|| folder.is_some()
|| custom_dictionary.is_some()
|| templates_folder.is_some()
|| !flag_values.is_empty()
|| !mark_values.is_empty()
@@ -190,16 +175,6 @@ fn options(s: &mut Session, v: &Value) -> CmdResult {
use_dictionaries_folder(f.as_deref());
s.prefs.dictionaries_folder = f;
}
if let Some(((new_path, new_words), setting)) = custom_dictionary_state {
if s.user_dict_path.as_ref() != new_path.as_ref() {
crate::custom_dict::clear_user_dictionary();
for w in new_words {
wordcraft_proof::add_word(&w);
}
s.user_dict_path = new_path;
}
s.prefs.custom_dictionary = setting;
}
if let Some(f) = templates_folder {
s.prefs.user_templates_folder = f;
}
@@ -256,7 +231,6 @@ pub fn current(s: &Session) -> Value {
"ignoreNumbers": pr.ignore_numbers,
"ignoreInternet": pr.ignore_internet,
"dictionary": wordcraft_proof::user_dictionary(),
"customDictionary": pr.custom_dictionary,
"dictionariesFolder": pr.dictionaries_folder,
"userTemplatesFolder": pr.user_templates_folder,
"dictionaries": wordcraft_proof::installed_dictionaries()
@@ -266,27 +240,6 @@ pub fn current(s: &Session) -> Value {
})
}
/// The path the custom dictionary becomes and the words it holds, read before any setting is
/// applied. `None` (`auto`) means the default `custom-dictionary.txt` in the settings folder;
/// a missing default file is an empty dictionary, as it was before the setting was bound.
fn prepare_custom_dictionary(s: &Session, setting: Option<&str>) -> Result<(Option<std::path::PathBuf>, Vec<String>), CmdError> {
match setting {
Some(path_str) => {
let path = std::path::PathBuf::from(path_str);
let words = crate::custom_dict::read_custom_dictionary_words_checked(&path).map_err(CmdError::Failed)?;
Ok((Some(path), words))
}
None => {
let path = s.default_user_dict_path.clone();
let words = match path.as_deref() {
Some(def) if def.exists() => crate::custom_dict::read_custom_dictionary_words_checked(def).map_err(CmdError::Failed)?,
_ => Vec::new(),
};
Ok((path, words))
}
}
}
/// A folder setting (`dictionariesFolder`, `userTemplatesFolder`): `auto` (or nothing) forgets
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/`. With
/// `local_only`, a network folder is refused before anything looks at it (#2852): even checking
@@ -318,38 +271,6 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
Ok(Some(path.to_string_lossy().into_owned()))
}
/// A file setting (`customDictionary`): `auto` (or nothing) forgets it; otherwise an existing
/// file, given as an absolute path or one starting with `~/`.
fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
let f = f.trim();
if f.is_empty() || f.eq_ignore_ascii_case("auto") {
return Ok(None);
}
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
return Err(CmdError::Params(format!("`{key}` isn't a file path")));
}
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
let path = if let Some(rest) = f.strip_prefix("~/") {
match home {
Some(h) => h.join(rest),
None => return Err(CmdError::Params(format!("`{key}`: cannot expand `~/` because HOME or USERPROFILE is not set"))),
}
} else {
std::path::PathBuf::from(f)
};
if !path.is_absolute() {
return Err(CmdError::Params(format!("`{key}`: {f:?} isn't a full path")));
}
match crate::io::check_regular_file_setting(&path, crate::custom_dict::MAX_CUSTOM_FILE_BYTES, key) {
Ok(()) => {}
Err(crate::io::FileCheckError::IsDirectory(msg) | crate::io::FileCheckError::IsSymlink(msg)) => return Err(CmdError::Params(msg)),
Err(crate::io::FileCheckError::Access(msg) | crate::io::FileCheckError::NotFound(msg) | crate::io::FileCheckError::TooLarge(msg)) => {
return Err(CmdError::Failed(msg));
}
}
Ok(Some(path.to_string_lossy().into_owned()))
}
/// Search `folder` for Hunspell dictionaries before the system locations, from now on (the saved
/// setting, applied when the app starts and when it changes).
pub fn use_dictionaries_folder(folder: Option<&str>) {
+2 -17
View File
@@ -281,14 +281,6 @@ pub enum Pasted {
/// that knows another program owns the clipboard passes `privateClipboard: false`, which keeps
/// the fragment out even when the text matches.
pub fn paste_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let pasted = clipboard_content(s, v)?;
// Formatting Backspace carried over is for typing, not for what is pasted (#6518). An empty
// clipboard pastes nothing, so it stays.
s.forget_carried();
Ok(pasted)
}
fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
if owns_clipboard(v)
&& let Some(f) = &s.clipboard
@@ -338,16 +330,11 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
p.props = para.clone();
for run in &mut p.runs {
let src = std::mem::replace(&mut run.props, base.clone());
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
// with the complex-script bold and italic.
if src.bold == Some(true) || src.bold_cs == Some(true) {
if src.bold == Some(true) {
run.props.bold = Some(true);
run.props.bold_cs = Some(true);
}
if src.italic == Some(true) || src.italic_cs == Some(true) {
if src.italic == Some(true) {
run.props.italic = Some(true);
run.props.italic_cs = Some(true);
}
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = src.underline;
@@ -367,8 +354,6 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
/// Replace the selection with `frag`, marking it as an insertion under Track Changes.
pub fn insert(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
// The pasted text keeps its own formatting; what Backspace carried over is not for after it (#6518).
s.forget_carried();
super::controls::prepare_edit(s)?;
let at = delete_selection(s)?;
let track = s.doc.settings.track_changes;
+4 -48
View File
@@ -1,17 +1,9 @@
use super::enter_tab::tab_indent_on;
use super::{
Block, COLUMN_BREAK, CmdResult, NumRef, OBJ, PAGE_BREAK, Pos, Selection, Session, StoryRef, Value, delete_selection, delete_selection_effect,
sel_result,
};
use super::{Block, CmdResult, NumRef, OBJ, Pos, Selection, Session, StoryRef, Value, delete_selection, delete_selection_effect, sel_result};
pub(super) fn backspace(s: &mut Session, v: &Value) -> CmdResult {
let r = backspace_inner(s, v)?;
crate::cmd::controls::restore_placeholder(s)?;
// A content control's placeholder is back: typing replaces it, so nothing is carried.
if s.doc.control_at(&s.sel.focus).is_some_and(|r| r.control.showing_placeholder) {
s.pending = None;
s.pending_at = None;
}
Ok(r)
}
@@ -37,32 +29,9 @@ fn remove_number(s: &mut Session, f: &Pos, n: NumRef) -> CmdResult {
sel_result(s)
}
/// The formatting Backspace carries over from the character between `a` and `f` (#6518): only an
/// ordinary character, not an object, field or anchor marker or a page or column break. With Track
/// Changes on it carries too, as in Word: the character stays, marked deleted (or goes, when this
/// author inserted it), and the caret sits before it. Cleaned up the way the caret's own
/// formatting is: no hyperlink, symbol font, note-number style or revision marks, so typed text
/// gets its own insertion mark and never the deletion.
fn deleted_char_props(s: &Session, a: &Pos, f: &Pos) -> Option<wordcraft_doc::props::CharProps> {
let p = s.doc.para_at(f)?;
let text = p.text.get(a.off..f.off).filter(|t| !t.is_empty())?;
if text.contains([OBJ, PAGE_BREAK, COLUMN_BREAK]) {
return None;
}
let mut props = p.props_of_char(a.off).unlinked().without_symbol();
if matches!(props.style.as_deref(), Some("FootnoteReference" | "EndnoteReference")) {
props.style = None;
}
props.ins = None;
props.del = None;
props.fmt_change = None;
Some(props)
}
fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
s.goal_x = None;
// Kept for a Backspace that changes nothing, which leaves Word's carried formatting alone.
let kept = (s.pending.take(), s.pending_at.take());
s.pending = None;
if !s.sel.is_collapsed() {
let effect = delete_selection_effect(s)?;
s.set_ime_edit_outcome(crate::ImeEditOutcome {
@@ -90,8 +59,7 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
if let Some(c) = s.autocap.as_mut() {
c.note_backspace(&a, &f);
}
let carried = deleted_char_props(s, &a, &f);
s.sel = Selection { anchor: a.clone(), focus: f };
s.sel = Selection { anchor: a, focus: f };
let effect = delete_selection_effect(s)?;
s.set_ime_edit_outcome(crate::ImeEditOutcome {
classified: true,
@@ -100,12 +68,6 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
transformed: false,
selection_changed: false,
});
// As in Word, text typed next takes the deleted character's formatting until the caret
// moves (#6518): it applies here only, so whatever puts the caret elsewhere drops it.
if effect.content_changed && s.sel.is_collapsed() && s.sel.focus == a {
s.pending_at = carried.as_ref().map(|_| a.clone());
s.pending = carried;
}
return sel_result(s);
}
// At the start of a paragraph.
@@ -131,10 +93,7 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
}
let i = f.path.last();
if i == 0 {
// Start of a story or cell: nothing changes, so formatting waiting at the caret (carried
// from a deleted character, or set there) still applies to the next typed text (Word).
(s.pending, s.pending_at) = kept;
return sel_result(s);
return sel_result(s); // start of a story or cell
}
let prev_path = f.path.with_last(i - 1);
match s.doc.block(f.story, &prev_path) {
@@ -257,9 +216,6 @@ pub(super) fn delete_word_back(s: &mut Session, v: &Value) -> CmdResult {
return backspace(s, v);
}
let a = Pos { off: para.word_start(f.off), ..f.clone() };
// Formatting a Backspace just carried over belongs to that deletion, not this one.
s.pending = None;
s.pending_at = None;
s.sel = Selection { anchor: a, focus: f };
delete_selection(s)?;
crate::cmd::controls::restore_placeholder(s)?;
-706
View File
@@ -1,706 +0,0 @@
//! Custom dictionary file reading and saving (#5840).
//!
//! Microsoft Word stores custom user words in freestanding dictionary files (commonly `CUSTOM.DIC`).
//! On Windows, Word traditionally encodes `CUSTOM.DIC` as UTF-16LE with a byte order mark (BOM)
//! and CRLF line endings, but also accepts UTF-8 (with or without BOM).
//!
//! This module loads and persists custom dictionary files, preserving their detected encoding
//! across edits and merging external additions safely. Format and encoding characteristics were
//! observed black-box from synthetic user dictionary files created and saved by Word on Windows.
use std::collections::HashSet;
use std::path::Path;
/// Maximum size of a custom dictionary file read into memory, in bytes (4 MB).
pub const MAX_CUSTOM_FILE_BYTES: u64 = 4_000_000;
/// Maximum number of words loaded from a custom dictionary file.
pub const MAX_CUSTOM_WORDS: usize = 100_000;
/// The text encoding detected for a custom dictionary file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DictEncoding {
/// UTF-16 Little Endian with BOM (`[0xFF, 0xFE]`), standard for Word's `CUSTOM.DIC` on Windows.
Utf16LeBom,
/// UTF-16 Big Endian with BOM (`[0xFE, 0xFF]`).
Utf16BeBom,
/// UTF-8 with BOM (`[0xEF, 0xBB, 0xBF]`).
Utf8Bom,
/// Standard UTF-8 without BOM.
Utf8,
}
/// Check if raw bytes appear to be BOM-less UTF-16LE using a NUL-byte heuristic on even/odd positions.
pub fn is_bomless_utf16le(bytes: &[u8]) -> bool {
bytes.len() >= 4 && bytes.iter().skip(1).step_by(2).filter(|&&b| b == 0).count() > bytes.len() / 4
}
/// Detect the text encoding of raw dictionary file bytes.
pub fn detect_file_encoding(bytes: &[u8]) -> DictEncoding {
if bytes.len() >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE {
DictEncoding::Utf16LeBom
} else if bytes.len() >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF {
DictEncoding::Utf16BeBom
} else if bytes.len() >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF {
DictEncoding::Utf8Bom
} else if is_bomless_utf16le(bytes) {
DictEncoding::Utf16LeBom
} else {
DictEncoding::Utf8
}
}
/// Decode UTF-16 `payload` bytes (no BOM) in the given byte order.
fn decode_utf16(payload: &[u8], big_endian: bool, label: &str) -> Result<String, String> {
if !payload.len().is_multiple_of(2) {
return Err(format!("malformed {label}: odd byte length"));
}
let units = payload.as_chunks::<2>().0.iter().map(|&b| if big_endian { u16::from_be_bytes(b) } else { u16::from_le_bytes(b) });
char::decode_utf16(units).collect::<Result<String, _>>().map_err(|_| format!("malformed {label}: unpaired surrogate"))
}
/// Decode raw dictionary bytes into a UTF-8 string, handling UTF-16LE, UTF-16BE, UTF-8 with BOM,
/// and UTF-8, returning an error on malformed encodings, odd byte lengths, or unpaired surrogates.
pub fn decode_dictionary_bytes(bytes: &[u8]) -> Result<String, String> {
if bytes.len() >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE {
return decode_utf16(&bytes[2..], false, "UTF-16LE");
}
if bytes.len() >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF {
return decode_utf16(&bytes[2..], true, "UTF-16BE");
}
let slice = if bytes.len() >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF { &bytes[3..] } else { bytes };
// Check for UTF-16LE without a BOM (common in headless Windows exports) before the UTF-8
// attempt. ASCII-only UTF-16LE is also valid UTF-8, so the UTF-8 check cannot detect it.
if is_bomless_utf16le(slice) {
decode_utf16(slice, false, "UTF-16LE")
} else {
std::str::from_utf8(slice).map(str::to_string).map_err(|e| format!("malformed UTF-8: {e}"))
}
}
/// Parse dictionary words from decoded text lines, validating each word and capping at [`MAX_CUSTOM_WORDS`].
///
/// If `path_for_err` is `Some`, returns an error when the dictionary exceeds [`MAX_CUSTOM_WORDS`] words.
pub fn parse_dictionary_words(text: &str, path_for_err: Option<&str>) -> Result<Vec<String>, String> {
let mut words = Vec::new();
for line in text.lines() {
let cleaned = line.trim_matches(|c: char| c == '\r' || c == '\n');
if let Some(w) = wordcraft_proof::custom_word(cleaned) {
if words.len() >= MAX_CUSTOM_WORDS {
if let Some(p) = path_for_err {
return Err(format!("{p}: dictionary exceeds limit of {MAX_CUSTOM_WORDS} words"));
}
break;
}
words.push(w);
}
}
Ok(words)
}
/// Read the raw words from a custom dictionary file, capped at [`MAX_CUSTOM_FILE_BYTES`] and
/// [`MAX_CUSTOM_WORDS`].
///
/// Returns `Ok(Vec::new())` if the file does not exist (treating a missing dictionary as empty).
/// Returns an error if an existing file cannot be read within limits.
pub fn read_custom_dictionary_words(path: &Path) -> Result<Vec<String>, String> {
if !path.exists() {
return Ok(Vec::new());
}
let path_str = path.to_string_lossy();
let bytes = crate::io::read_file_capped(&path_str, MAX_CUSTOM_FILE_BYTES, "dictionary")?;
let text = decode_dictionary_bytes(&bytes).map_err(|e| format!("{path_str}: {e}"))?;
parse_dictionary_words(&text, Some(&path_str))
}
/// Read words from a custom dictionary file, capped at [`MAX_CUSTOM_FILE_BYTES`] and
/// [`MAX_CUSTOM_WORDS`].
///
/// Returns an error if the file cannot be read within limits or does not exist.
pub fn read_custom_dictionary_words_checked(path: &Path) -> Result<Vec<String>, String> {
let path_str = path.to_string_lossy();
let bytes = crate::io::read_file_capped(&path_str, MAX_CUSTOM_FILE_BYTES, "dictionary")?;
let text = decode_dictionary_bytes(&bytes).map_err(|e| format!("{path_str}: {e}"))?;
parse_dictionary_words(&text, Some(&path_str))
}
/// Load custom dictionary words from `path` into proofing's user dictionary.
///
/// Returns the list of words added to the proofing dictionary, or an error if an existing file
/// could not be read within limits.
pub fn load_custom_dictionary(path: &Path) -> Result<Vec<String>, String> {
let words = read_custom_dictionary_words(path)?;
let mut added = Vec::new();
for w in words {
wordcraft_proof::add_word(&w);
added.push(w);
}
Ok(added)
}
/// Load custom dictionary words from `path`, replacing all existing in-memory custom words
/// only if the file is successfully read.
///
/// If `path` cannot be read within limits or does not exist, returns an error without
/// modifying the existing in-memory proofing dictionary.
///
/// # Errors
/// Returns an error string if the file does not exist, exceeds size limits, or has invalid encoding.
pub fn load_custom_dictionary_replacing(path: &Path) -> Result<Vec<String>, String> {
let words = read_custom_dictionary_words_checked(path)?;
clear_user_dictionary();
for w in &words {
wordcraft_proof::add_word(w);
}
Ok(words)
}
/// Clear all custom words currently held in the in-memory proofing dictionary.
pub fn clear_user_dictionary() {
for w in wordcraft_proof::user_dictionary() {
wordcraft_proof::remove_word(&w);
}
}
/// Encode a list of words into bytes matching the requested [`DictEncoding`].
pub fn encode_dictionary_words(words: &[String], encoding: DictEncoding) -> Vec<u8> {
match encoding {
DictEncoding::Utf16LeBom => {
let mut out = Vec::with_capacity(words.len() * 20 + 2);
out.extend_from_slice(&[0xFF, 0xFE]);
for w in words {
for u in w.encode_utf16() {
out.extend_from_slice(&u.to_le_bytes());
}
// CRLF line endings for Word UTF-16LE custom dictionaries.
out.extend_from_slice(&[0x0D, 0x00, 0x0A, 0x00]);
}
out
}
DictEncoding::Utf16BeBom => {
let mut out = Vec::with_capacity(words.len() * 20 + 2);
out.extend_from_slice(&[0xFE, 0xFF]);
for w in words {
for u in w.encode_utf16() {
out.extend_from_slice(&u.to_be_bytes());
}
out.extend_from_slice(&[0x00, 0x0D, 0x00, 0x0A]);
}
out
}
DictEncoding::Utf8Bom => {
let mut out = Vec::with_capacity(words.len() * 10 + 3);
out.extend_from_slice(&[0xEF, 0xBB, 0xBF]);
for w in words {
out.extend_from_slice(w.as_bytes());
out.push(b'\n');
}
out
}
DictEncoding::Utf8 => {
let mut out = Vec::with_capacity(words.len() * 10);
for w in words {
out.extend_from_slice(w.as_bytes());
out.push(b'\n');
}
out
}
}
}
/// Save the current user dictionary to `path`, merging any external additions made on disk,
/// omitting `removed`, and preserving the file's encoding (UTF-16LE, UTF-8 BOM, or UTF-8)
/// and existing lines (preserving exact original casing, comments, spaces, and formatting).
///
/// If an existing file cannot be read within [`MAX_CUSTOM_FILE_BYTES`] or exceeds [`MAX_CUSTOM_WORDS`],
/// an error is returned before modifying the in-memory dictionary or writing to disk, keeping
/// existing file contents intact.
pub fn save_custom_dictionary(path: &Path, removed: &[String]) -> Result<(), String> {
let path_str = path.to_string_lossy();
let mut encoding = DictEncoding::Utf8;
let removed_keys: HashSet<String> = removed.iter().filter_map(|w| wordcraft_proof::custom_word(w)).collect();
let mut out_lines: Vec<String> = Vec::new();
let mut existing_keys: HashSet<String> = HashSet::new();
if path.exists() {
let bytes = crate::io::read_file_capped(&path_str, MAX_CUSTOM_FILE_BYTES, "dictionary")?;
encoding = detect_file_encoding(&bytes);
let text = decode_dictionary_bytes(&bytes).map_err(|e| format!("{path_str}: {e}"))?;
let line_count = text.lines().count();
if line_count > MAX_CUSTOM_WORDS {
return Err(format!("{path_str}: dictionary exceeds limit of {MAX_CUSTOM_WORDS} words"));
}
for raw_line in text.lines() {
let line = raw_line.trim_matches(|c: char| c == '\r' || c == '\n');
let is_removed = removed.iter().any(|r| r == line || r.trim() == line)
|| wordcraft_proof::custom_word(line).is_some_and(|k| removed_keys.contains(&k));
if is_removed {
continue;
}
out_lines.push(line.to_string());
if let Some(k) = wordcraft_proof::custom_word(line) {
wordcraft_proof::add_word(&k);
existing_keys.insert(k);
} else {
existing_keys.insert(line.to_lowercase());
}
}
}
for w in removed {
wordcraft_proof::remove_word(w);
}
for w in wordcraft_proof::user_dictionary() {
if !existing_keys.contains(&w) && !removed_keys.contains(&w) {
out_lines.push(w.clone());
existing_keys.insert(w);
}
}
if out_lines.len() > MAX_CUSTOM_WORDS {
return Err(format!("Dictionary at '{}' exceeds maximum word limit ({})", path_str, MAX_CUSTOM_WORDS));
}
let bytes = encode_dictionary_words(&out_lines, encoding);
if bytes.len() as u64 > MAX_CUSTOM_FILE_BYTES {
return Err(format!("Dictionary at '{}' exceeds maximum file size ({} bytes)", path_str, MAX_CUSTOM_FILE_BYTES));
}
crate::io::write_file(&path_str, &bytes)
}
#[cfg(test)]
pub(crate) use tests::{DICT_TEST_LOCK, TestDir};
#[cfg(test)]
mod tests {
use super::*;
/// Test lock serializing tests that access the global proofing dictionary.
pub(crate) static DICT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// RAII guard for temporary directories in dictionary tests.
pub(crate) struct TestDir(pub(crate) std::path::PathBuf);
impl TestDir {
/// Create a new unique temporary directory with the given prefix.
pub(crate) fn new(prefix: &str) -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let count = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("wc-test-{prefix}-{}-{count}", std::process::id()));
let _ = std::fs::create_dir_all(&path);
TestDir(path)
}
/// Return a reference to the temporary directory path.
pub(crate) fn path(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Test decoding UTF-16LE encoded bytes with a BOM.
#[test]
fn decodes_utf16le_with_bom() {
let mut bytes = vec![0xFF, 0xFE];
for c in "mameui\r\nfreestanding\r\n".encode_utf16() {
bytes.extend_from_slice(&c.to_le_bytes());
}
let text = decode_dictionary_bytes(&bytes).unwrap();
assert_eq!(text, "mameui\r\nfreestanding\r\n");
}
/// Test decoding UTF-8 bytes with a BOM.
#[test]
fn decodes_utf8_with_bom() {
let mut bytes = vec![0xEF, 0xBB, 0xBF];
bytes.extend_from_slice(b"retro\ncomputing\n");
let text = decode_dictionary_bytes(&bytes).unwrap();
assert_eq!(text, "retro\ncomputing\n");
}
/// Test decoding ASCII-only UTF-16LE bytes without a BOM.
#[test]
fn decodes_ascii_utf16le_without_bom() {
let mut bytes = Vec::new();
for c in "freestanding\r\nmameui\r\n".encode_utf16() {
bytes.extend_from_slice(&c.to_le_bytes());
}
let text = decode_dictionary_bytes(&bytes).unwrap();
assert_eq!(text, "freestanding\r\nmameui\r\n");
}
/// Test saving and loading a UTF-16LE dictionary file preserves encoding and content.
#[test]
fn save_and_load_utf16le_custom_dictionary() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("utf16");
let path = dir.path().join("custom.dic");
// Seed file with UTF-16LE data
let mut initial = vec![0xFF, 0xFE];
for c in "alpha\r\nbeta\r\n".encode_utf16() {
initial.extend_from_slice(&c.to_le_bytes());
}
std::fs::write(&path, initial).unwrap();
let added = load_custom_dictionary(&path).unwrap();
assert!(added.contains(&"alpha".to_string()));
assert!(added.contains(&"beta".to_string()));
// Add a new word and save
wordcraft_proof::add_word("gamma");
save_custom_dictionary(&path, &[]).unwrap();
let raw = std::fs::read(&path).unwrap();
assert_eq!(raw[0..2], [0xFF, 0xFE], "remains UTF-16LE with BOM");
let decoded = decode_dictionary_bytes(&raw).unwrap();
assert!(decoded.contains("alpha"));
assert!(decoded.contains("beta"));
assert!(decoded.contains("gamma"));
wordcraft_proof::remove_word("gamma");
}
/// Test saving and loading a UTF-16BE dictionary file preserves big-endian BOM and content.
#[test]
fn save_and_load_utf16be_custom_dictionary() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("utf16be");
let path = dir.path().join("custom_be.dic");
let mut initial = vec![0xFE, 0xFF];
for c in "alpha\r\nbeta\r\n".encode_utf16() {
initial.extend_from_slice(&c.to_be_bytes());
}
std::fs::write(&path, initial).unwrap();
let added = load_custom_dictionary(&path).unwrap();
assert!(added.contains(&"alpha".to_string()));
assert!(added.contains(&"beta".to_string()));
wordcraft_proof::add_word("gamma");
save_custom_dictionary(&path, &[]).unwrap();
let raw = std::fs::read(&path).unwrap();
assert_eq!(raw[0..2], [0xFE, 0xFF], "remains UTF-16BE with BOM");
let decoded = decode_dictionary_bytes(&raw).unwrap();
assert!(decoded.contains("alpha"));
assert!(decoded.contains("beta"));
assert!(decoded.contains("gamma"));
wordcraft_proof::remove_word("alpha");
wordcraft_proof::remove_word("beta");
wordcraft_proof::remove_word("gamma");
}
/// Test saving and loading an ASCII-only BOM-less UTF-16LE dictionary writes Word-compatible UTF-16LE with BOM.
#[test]
fn save_and_load_bomless_utf16le_custom_dictionary() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("bomless-utf16");
let path = dir.path().join("bomless.dic");
// Seed file with BOM-less UTF-16LE data
let mut initial = Vec::new();
for c in "alpha\r\nbeta\r\n".encode_utf16() {
initial.extend_from_slice(&c.to_le_bytes());
}
std::fs::write(&path, initial).unwrap();
let added = load_custom_dictionary(&path).unwrap();
assert!(added.contains(&"alpha".to_string()));
assert!(added.contains(&"beta".to_string()));
// Add a new word and save
wordcraft_proof::add_word("gamma");
save_custom_dictionary(&path, &[]).unwrap();
let raw = std::fs::read(&path).unwrap();
assert_eq!(raw[0..2], [0xFF, 0xFE], "saved with Word-compatible UTF-16LE BOM");
let decoded = decode_dictionary_bytes(&raw).unwrap();
assert!(decoded.contains("alpha"));
assert!(decoded.contains("beta"));
assert!(decoded.contains("gamma"));
wordcraft_proof::remove_word("gamma");
wordcraft_proof::remove_word("alpha");
wordcraft_proof::remove_word("beta");
}
/// Test that saving a custom dictionary merges external additions made on disk after loading.
#[test]
fn save_custom_dictionary_merges_external_additions() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("external-merge");
let path = dir.path().join("custom.dic");
std::fs::write(&path, "alpha\nbeta\n").unwrap();
let loaded = load_custom_dictionary(&path).unwrap();
assert_eq!(loaded, vec!["alpha".to_string(), "beta".to_string()]);
// External editor appends "externalword"
std::fs::write(&path, "alpha\nbeta\nexternalword\n").unwrap();
// In-session addition "internalword"
wordcraft_proof::add_word("internalword");
save_custom_dictionary(&path, &[]).unwrap();
let words = read_custom_dictionary_words(&path).unwrap();
assert!(words.contains(&"alpha".to_string()));
assert!(words.contains(&"beta".to_string()));
assert!(words.contains(&"externalword".to_string()), "external additions merged on save");
assert!(words.contains(&"internalword".to_string()), "internal additions preserved on save");
wordcraft_proof::remove_word("alpha");
wordcraft_proof::remove_word("beta");
wordcraft_proof::remove_word("externalword");
wordcraft_proof::remove_word("internalword");
}
/// Test that reading a custom dictionary rejects files exceeding the byte limit.
#[test]
fn read_custom_dictionary_words_rejects_file_over_byte_limit() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("read-overlimit");
let path = dir.path().join("oversized.dic");
let large_content = vec![b'a'; (MAX_CUSTOM_FILE_BYTES + 1024) as usize];
std::fs::write(&path, &large_content).unwrap();
let err1 = read_custom_dictionary_words(&path).unwrap_err();
assert!(err1.contains("larger than"));
let err2 = read_custom_dictionary_words_checked(&path).unwrap_err();
assert!(err2.contains("larger than"));
}
/// Test that parsing custom dictionary text enforces the maximum word limit.
#[test]
fn parse_dictionary_words_rejects_or_truncates_over_word_limit() {
let mut text = String::new();
for i in 0..MAX_CUSTOM_WORDS + 10 {
text.push_str(&format!("word{i}\n"));
}
// When path is provided for error reporting, returns an error.
let err = parse_dictionary_words(&text, Some("custom.dic")).unwrap_err();
assert!(err.contains(&format!("dictionary exceeds limit of {MAX_CUSTOM_WORDS} words")));
// When path is None, safely truncates at MAX_CUSTOM_WORDS.
let capped = parse_dictionary_words(&text, None).unwrap();
assert_eq!(capped.len(), MAX_CUSTOM_WORDS);
}
/// Test that decoding UTF-16LE bytes with an odd byte count returns an error.
#[test]
fn decode_dictionary_bytes_rejects_odd_byte_length_utf16le() {
let bytes = vec![0xFF, 0xFE, 0x61];
let err = decode_dictionary_bytes(&bytes).unwrap_err();
assert!(err.contains("odd byte length"));
}
/// Test that decoding UTF-16LE bytes with an unpaired surrogate returns an error.
#[test]
fn decode_dictionary_bytes_rejects_unpaired_surrogate_utf16le() {
let bytes = vec![0xFF, 0xFE, 0x00, 0xD8];
let err = decode_dictionary_bytes(&bytes).unwrap_err();
assert!(err.contains("unpaired surrogate"));
}
/// Test that decoding UTF-16BE bytes with an odd byte count returns an error.
#[test]
fn decode_dictionary_bytes_rejects_odd_byte_length_utf16be() {
let bytes = vec![0xFE, 0xFF, 0x61];
let err = decode_dictionary_bytes(&bytes).unwrap_err();
assert!(err.contains("odd byte length"));
}
/// Test that decoding UTF-16BE bytes with an unpaired surrogate returns an error.
#[test]
fn decode_dictionary_bytes_rejects_unpaired_surrogate_utf16be() {
let bytes = vec![0xFE, 0xFF, 0xD8, 0x00];
let err = decode_dictionary_bytes(&bytes).unwrap_err();
assert!(err.contains("unpaired surrogate"));
}
/// Test that clearing the user dictionary removes all words from memory.
#[test]
fn clear_user_dictionary_removes_all_words() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
clear_user_dictionary();
wordcraft_proof::add_word("tempclearwordone");
wordcraft_proof::add_word("tempclearwordtwo");
assert!(wordcraft_proof::user_dictionary().contains(&"tempclearwordone".to_string()));
clear_user_dictionary();
assert!(wordcraft_proof::user_dictionary().is_empty());
}
/// Test that save_custom_dictionary returns an error and preserves an existing file that
/// exceeds the maximum size limit.
#[test]
fn save_custom_dictionary_refuses_over_limit_file() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("overlimit");
let path = dir.path().join("oversized.dic");
let large_content = vec![b'a'; (MAX_CUSTOM_FILE_BYTES + 1024) as usize];
std::fs::write(&path, &large_content).unwrap();
wordcraft_proof::add_word("newword");
let result = save_custom_dictionary(&path, &[]);
assert!(result.is_err(), "should reject oversized dictionary file");
let read_back = std::fs::read(&path).unwrap();
assert_eq!(read_back.len(), large_content.len());
wordcraft_proof::remove_word("newword");
}
/// Test that read_custom_dictionary_words returns Ok(empty) on a missing file.
#[test]
fn read_custom_dictionary_words_returns_empty_on_missing_file() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("missing");
let path = dir.path().join("nonexistent.dic");
let words = read_custom_dictionary_words(&path).unwrap();
assert!(words.is_empty());
}
/// Test that save_custom_dictionary rejects writing when encoded output exceeds byte limit.
#[test]
fn save_custom_dictionary_refuses_when_output_exceeds_byte_limit() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
clear_user_dictionary();
struct ResetDict;
impl Drop for ResetDict {
fn drop(&mut self) {
clear_user_dictionary();
}
}
let _reset = ResetDict;
let dir = TestDir::new("oversized-output");
let path = dir.path().join("oversized.dic");
// Populate the in-memory custom dictionary with words that exceed MAX_CUSTOM_FILE_BYTES (4MB)
// while staying below MAX_CUSTOM_WORDS (100k) and keeping each word <= 64 chars.
// 70,000 words * 64 bytes (63 chars + '\n') = ~4.48 MB > 4 MB limit.
let word_count = 70_000;
let prefix = "a".repeat(58);
for i in 0..word_count {
wordcraft_proof::add_word(&format!("{prefix}{:05}", i));
}
let res = save_custom_dictionary(&path, &[]);
assert!(res.is_err(), "Expected save_custom_dictionary to reject oversized output");
let err = res.unwrap_err();
assert!(err.contains("exceeds maximum file size"), "Error message was: {err}");
assert!(!path.exists(), "File must not be written when output exceeds byte limit");
}
/// Test that save_custom_dictionary preserves original lines and casing (e.g. capitalized
/// entries like NASA, McDonald, multi-word lines, and lines exceeding 64 chars).
#[test]
fn save_custom_dictionary_preserves_original_lines_and_casing() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
clear_user_dictionary();
struct ResetDict;
impl Drop for ResetDict {
fn drop(&mut self) {
clear_user_dictionary();
}
}
let _reset = ResetDict;
let dir = TestDir::new("preserve-lines");
let path = dir.path().join("CUSTOM.DIC");
// Create an initial UTF-16LE dictionary matching Word's format with mixed casing,
// a multi-word line, and a line longer than 64 characters.
let over_64_chars = "a".repeat(70);
let content = format!("NASA\r\nMcDonald\r\ntwo words\r\n{over_64_chars}\r\n");
let mut initial_bytes = vec![0xFF, 0xFE];
for c in content.encode_utf16() {
initial_bytes.extend_from_slice(&c.to_le_bytes());
}
std::fs::write(&path, &initial_bytes).unwrap();
// Load the dictionary into proofing. Proofing parses valid words ("nasa", "mcdonald")
// and skips unparseable lines ("two words", 70-char line).
let loaded = load_custom_dictionary(&path).unwrap();
assert!(loaded.contains(&"nasa".to_string()));
assert!(loaded.contains(&"mcdonald".to_string()));
assert_eq!(loaded.len(), 2);
// Add a new word in session
wordcraft_proof::add_word("newword");
// Save back to the file
save_custom_dictionary(&path, &[]).unwrap();
// Verify file remains UTF-16LE with BOM
let saved_bytes = std::fs::read(&path).unwrap();
assert_eq!(saved_bytes[0..2], [0xFF, 0xFE]);
let decoded = decode_dictionary_bytes(&saved_bytes).unwrap();
// Original lines must preserve exact casing and unparsed content
assert!(decoded.contains("NASA\r\n"), "must preserve capitalized NASA");
assert!(decoded.contains("McDonald\r\n"), "must preserve mixed-case McDonald");
assert!(decoded.contains("two words\r\n"), "must preserve multi-word line");
assert!(decoded.contains(&format!("{over_64_chars}\r\n")), "must preserve line > 64 chars");
// Newly added word must be appended
assert!(decoded.contains("newword\r\n"), "must append new word");
// Now remove McDonald and save again
save_custom_dictionary(&path, &["McDonald".to_string()]).unwrap();
let after_remove = decode_dictionary_bytes(&std::fs::read(&path).unwrap()).unwrap();
assert!(after_remove.contains("NASA\r\n"), "NASA still retained");
assert!(!after_remove.contains("McDonald"), "McDonald removed");
assert!(after_remove.contains("two words\r\n"), "multi-word line still retained");
assert!(after_remove.contains(&format!("{over_64_chars}\r\n")), "line > 64 chars still retained");
assert!(after_remove.contains("newword\r\n"), "newword still retained");
}
/// Test that load_custom_dictionary_replacing replaces stale restored words on successful load,
/// but preserves in-memory words if the target file does not exist or fails to load.
#[test]
fn load_custom_dictionary_replacing_reconciles_stale_words() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("reconcile");
let path = dir.path().join("custom.dic");
clear_user_dictionary();
wordcraft_proof::add_word("stale_word");
assert!(wordcraft_proof::user_dictionary().contains(&"stale_word".to_string()));
// Non-existent file must return Err and not clear existing words
let nonexistent = dir.path().join("missing.dic");
let res = load_custom_dictionary_replacing(&nonexistent);
assert!(res.is_err(), "missing file must error");
assert!(wordcraft_proof::user_dictionary().contains(&"stale_word".to_string()), "must preserve words on missing file");
// Existing file must replace stale words with its own words
std::fs::write(&path, "fresh_word\r\n").unwrap();
let loaded = load_custom_dictionary_replacing(&path).unwrap();
assert_eq!(loaded, vec!["fresh_word".to_string()]);
let in_memory = wordcraft_proof::user_dictionary();
assert!(in_memory.contains(&"fresh_word".to_string()), "must contain fresh word");
assert!(!in_memory.contains(&"stale_word".to_string()), "must have cleared stale word");
clear_user_dictionary();
}
}
-2
View File
@@ -126,8 +126,6 @@ pub(super) struct Undo {
pub(super) sel: Selection,
/// Formatting waiting at the caret (Bold with nothing selected), so Undo takes it back too.
pub(super) pending: Option<CharProps>,
/// Where that formatting applies, if Backspace carried it over (`Session::pending_at`).
pub(super) pending_at: Option<Pos>,
/// The column block or whole cells the selection was (undoing brings the selection back as
/// it was).
pub(super) column: Option<ColumnBlock>,
+1 -92
View File
@@ -53,7 +53,7 @@ pub fn is_word_package(ext: &str) -> bool {
}
/// How a copy in another format is written.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ExportOptions {
/// Print Markup: PDFs show tracked changes marked up and, with `comments`, each page scaled
/// down beside a markup area with the comments in balloons (page images get the area too);
@@ -66,9 +66,6 @@ pub struct ExportOptions {
pub word2003: bool,
/// How digits look in PDFs and page images (the Numeral setting, `System` resolved).
pub numeral: wordcraft_layout::NumeralMode,
/// How tracked changes are marked in PDFs and page images (Track Changes Options): the
/// insertion and deletion marks and colours the screen shows (#5232).
pub revisions: wordcraft_layout::display::MarkupOptions,
/// A PDF or page image is written only if nothing in it is silently missing (a character no
/// face can draw, a picture that is missing or can't be decoded); else the save fails with
/// `strict: …` (#6005). Ignored for other formats.
@@ -732,94 +729,6 @@ pub fn read_file_head(path: &str, max: u64) -> Result<Vec<u8>, String> {
Ok(head)
}
/// Web fallback for [`read_file_capped`] and [`read_file_head`], returning an error explaining
/// that files are opened through the browser on the web.
pub fn wasm_read_file_fallback(path: &str) -> Result<Vec<u8>, String> {
Err(format!("{path}: files are opened through the browser on the web"))
}
/// Web fallback for [`read_file_capped`].
#[cfg(target_arch = "wasm32")]
pub fn read_file_capped(path: &str, _max: u64, _what: &str) -> Result<Vec<u8>, String> {
wasm_read_file_fallback(path)
}
/// Web fallback for [`read_file_head`].
#[cfg(target_arch = "wasm32")]
pub fn read_file_head(path: &str, _max: u64) -> Result<Vec<u8>, String> {
wasm_read_file_fallback(path)
}
/// Classification of file validation errors for configuration settings.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FileCheckError {
/// Automation access violation or I/O error.
Access(String),
/// The target path is a directory instead of a regular file.
IsDirectory(String),
/// The target path is a symbolic link instead of a regular file.
IsSymlink(String),
/// The path does not exist or is not a regular file.
NotFound(String),
/// The file exceeds the permitted size limit.
TooLarge(String),
}
impl std::fmt::Display for FileCheckError {
/// Format the file check error message.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Access(s) | Self::IsDirectory(s) | Self::IsSymlink(s) | Self::NotFound(s) | Self::TooLarge(s) => f.write_str(s),
}
}
}
/// Check that `path` is an accessible regular file within `max` bytes.
///
/// Ensures the path is within automation read and write roots, exists, is not a symbolic link,
/// is not a directory, is a regular writable file, and does not exceed `max` bytes.
#[cfg(not(target_arch = "wasm32"))]
pub fn check_regular_file_setting(path: &std::path::Path, max: u64, key: &str) -> Result<(), FileCheckError> {
crate::file_access::check_read(&path.to_string_lossy()).map_err(FileCheckError::Access)?;
crate::file_access::check_write(&path.to_string_lossy()).map_err(FileCheckError::Access)?;
let sym_meta = match std::fs::symlink_metadata(path) {
Ok(m) => m,
Err(e) => return Err(FileCheckError::Access(format!("{}: {e}", path.display()))),
};
if sym_meta.file_type().is_symlink() {
return Err(FileCheckError::IsSymlink(format!("`{key}`: {} is a symbolic link, not a regular file", path.display())));
}
let meta = match std::fs::metadata(path) {
Ok(m) => m,
Err(e) => return Err(FileCheckError::Access(format!("{}: {e}", path.display()))),
};
if meta.is_dir() {
return Err(FileCheckError::IsDirectory(format!("`{key}`: {} is a folder, not a file", path.display())));
}
if !meta.is_file() {
return Err(FileCheckError::NotFound(format!("no file at {}", path.display())));
}
if meta.len() > max {
return Err(FileCheckError::TooLarge(format!("{} is larger than the custom dictionary limit", path.display())));
}
if meta.permissions().readonly() {
return Err(FileCheckError::Access(format!("{}: file is read-only", path.display())));
}
let mut open = std::fs::OpenOptions::new();
open.write(true);
// A named pipe swapped in after the metadata check would block `open`; non-blocking fails it at once.
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut open, libc::O_NONBLOCK);
open.open(path).map_err(|e| FileCheckError::Access(format!("{}: {e}", path.display())))?;
Ok(())
}
/// Web fallback for [`check_regular_file_setting`].
#[cfg(target_arch = "wasm32")]
pub fn check_regular_file_setting(path: &std::path::Path, _max: u64, _key: &str) -> Result<(), FileCheckError> {
Err(FileCheckError::Access(format!("{}: files are opened through the browser on the web", path.display())))
}
/// An entry of [`list_dir`]: a file or folder (links followed).
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Debug)]
+2 -56
View File
@@ -98,15 +98,6 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
}
}
/// How a page image is drawn: the printed page, headers and footers at full strength, tracked
/// changes marked as Track Changes Options mark them. One place for `file.exportPng`,
/// `file.strictReport`'s page check and a downloaded page image.
pub(crate) fn page_image_options(opts: &crate::io::ExportOptions) -> wordcraft_render::RenderOptions {
let mut ro = wordcraft_render::RenderOptions { display: crate::strict::png_display(), ..Default::default() };
ro.display.revisions = opts.revisions.clone();
ro
}
/// Render page `page` as PNG at `scale` px/pt. With Print Markup's comments the page has its
/// markup area with the comments in balloons (page images always show tracked changes).
pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::ExportOptions) -> Result<Vec<u8>, String> {
@@ -114,7 +105,6 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
let doc = out.as_ref().unwrap_or(doc);
let lo = wordcraft_layout::LayoutOptions {
comment_balloons: opts.markup && opts.comments,
hide_marked: opts.revisions.hidden_deletions(),
numeral: opts.numeral,
output_page_refs: true,
bookmark_error: crate::locale::bookmark_error(),
@@ -123,55 +113,11 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
let l = wordcraft_layout::layout(doc, &mut wordcraft_layout::LayoutCache::new(), &lo);
let p = l.pages.get(page).ok_or_else(|| format!("no page {}", page + 1))?;
if opts.strict {
let display = page_image_options(opts).display;
let report = crate::strict::strict_report(doc, &l, &display, Some(page..=page), wordcraft_layout::StrictOutput::Png);
let report = crate::strict::strict_report(doc, &l, &crate::strict::png_display(), Some(page..=page), wordcraft_layout::StrictOutput::Png);
if !report.passed() {
return Err(report.refusal());
}
}
let img = wordcraft_render::render_page(doc, p, scale, &page_image_options(opts));
let img = wordcraft_render::render_page(doc, p, scale, &Default::default());
Ok(img.to_png())
}
#[cfg(test)]
mod tests {
use super::*;
/// A page image is the printed page: headers and footers draw at full strength (#6267).
#[test]
fn a_page_image_draws_headers_at_full_strength() {
let opts = crate::io::ExportOptions::default();
let ro = page_image_options(&opts);
assert!(!ro.display.dim_header, "a page image is the printed page");
assert_eq!(ro.display.revisions, opts.revisions, "the Track Changes Options reach the image");
let mut d = Document::from_text("body");
let png = wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 0, 0, 255]))),
image::ImageFormat::Png,
)
.unwrap();
let media = d.add_media(png, "png");
let mut hp = wordcraft_doc::Paragraph::new();
let obj = wordcraft_doc::para::InlineObject::Image {
media,
w: 40.0,
h: 40.0,
alt: String::new(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
hp.insert_object(0, obj, &Default::default()).unwrap();
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp)]);
d.last_section.headers.default = Some(id);
let rendered = render_png(&d, 0, 1.0, &opts).unwrap();
let l = wordcraft_layout::layout(&d, &mut wordcraft_layout::LayoutCache::new(), &wordcraft_layout::LayoutOptions::default());
let full = wordcraft_render::render_page(&d, &l.pages[0], 1.0, &ro).to_png();
let dimmed = wordcraft_render::render_page(&d, &l.pages[0], 1.0, &wordcraft_render::RenderOptions::default()).to_png();
assert_eq!(rendered, full, "render_png draws headers at full strength");
assert_ne!(rendered, dimmed, "render_png does not dim headers");
}
}
-1
View File
@@ -8,7 +8,6 @@
pub mod catalog;
pub mod cmd;
pub mod custom_dict;
pub(crate) mod doc_state;
pub mod file_access;
pub(crate) mod ime;
-5
View File
@@ -41,9 +41,6 @@ pub struct Prefs {
/// Language, #1063): an app started from Finder or the Dock doesn't see
/// `WORDCRAFT_DICTIONARIES`. `None` means no configured folder.
pub dictionaries_folder: Option<String>,
/// A custom dictionary file (.dic or plain text) used for custom words (File › Options › Proofing, #5840).
/// `None`: the default `custom-dictionary.txt` in the settings folder.
pub custom_dictionary: Option<String>,
/// The user templates folder File › New lists personal templates from and Save as Word
/// Template starts in (File › Options › Advanced › File locations, #2852). `None`: the app's
/// own `Templates` folder in its settings folder.
@@ -68,7 +65,6 @@ pub struct Prefs {
}
impl Default for Prefs {
/// Default preference values.
fn default() -> Self {
Prefs {
paper_color: Default::default(),
@@ -81,7 +77,6 @@ impl Default for Prefs {
units: Default::default(),
region: None,
dictionaries_folder: None,
custom_dictionary: None,
user_templates_folder: None,
marks: Default::default(),
mark_grammar: true,
+1 -4
View File
@@ -221,7 +221,7 @@ impl Session {
let markup = crate::cmd::file::export_options(self, v);
let out = crate::cmd::references::output_fields(&self.doc);
let doc = out.as_ref().unwrap_or(&self.doc);
let lay = self.output_layout_of(doc, markup.markup, !markup.markup);
let lay = self.export_layout_of(doc, markup.markup);
let plan = plan(v, lay.pages.len(), self.current_pages(&lay))?;
let mut single = v.clone();
single["copies"] = json!(1);
@@ -238,9 +238,6 @@ impl Session {
comments: markup.comments,
paper,
links,
numeral: markup.numeral,
revisions: markup.revisions.clone(),
compress: p::bool(v, "compress").unwrap_or(true),
..Default::default()
};
let bytes = wordcraft_pdf::export_layout(doc, &lay, &opts).map_err(|e| CmdError::Failed(e.to_string()))?;
-8
View File
@@ -51,11 +51,6 @@ pub struct Session {
pub view: ViewState,
/// Formatting picked with a collapsed caret, applied to the next typed text.
pub pending: Option<CharProps>,
/// Where the caret was when Backspace carried [`Self::pending`] over from the character it
/// deleted (#6518), moved on as typing advances the caret. That formatting is for typing
/// there only: once the caret is anywhere else (a paste, Find, Go To or a click put it
/// there) it is dropped (see [`Self::waiting`]). `None` for formatting picked at the caret.
pub(crate) pending_at: Option<Pos>,
/// Last highlighter choice for the shortcut; palette state, outside document undo.
pub(crate) last_highlight: wordcraft_doc::props::Highlight,
pub path: Option<std::path::PathBuf>,
@@ -68,9 +63,6 @@ pub struct Session {
/// `None`, so an agent's words stay in memory and never change the person's dictionary.
/// Add to Dictionary and File › Options › Proofing save through it (#40).
pub user_dict_path: Option<std::path::PathBuf>,
/// The default user dictionary path wired up by the host (usually `custom-dictionary.txt` in
/// the settings directory), used when [`Prefs::custom_dictionary`] is reset to auto (#5840).
pub default_user_dict_path: Option<std::path::PathBuf>,
pub clipboard: Option<Fragment>,
/// A tracked cut the next paste can turn into a move (see `cmd::moves`).
pub pending_move: Option<crate::cmd::moves::PendingMove>,
-6
View File
@@ -43,7 +43,6 @@ pub struct DocState {
pub(super) sel: Selection,
pub(super) view: ViewState,
pub(super) pending: Option<CharProps>,
pub(super) pending_at: Option<Pos>,
pub(super) path: Option<PathBuf>,
pub(super) file_name: Option<String>,
pub(super) dirty: bool,
@@ -100,7 +99,6 @@ impl DocState {
sel: Selection::caret(start),
view,
pending: None,
pending_at: None,
path: None,
file_name: None,
dirty: false,
@@ -204,7 +202,6 @@ impl Session {
sel: _,
view: _,
pending: _,
pending_at: _,
path: _,
file_name: _,
dirty: _,
@@ -253,7 +250,6 @@ impl Session {
// Names the document it belongs to, so it never applies to another one.
review_style: _,
user_dict_path: _,
default_user_dict_path: _,
clipboard: _,
clipboard_text: _,
clipboard_html: _,
@@ -307,7 +303,6 @@ impl Session {
sel,
view,
pending,
pending_at,
path,
file_name,
dirty,
@@ -357,7 +352,6 @@ impl Session {
swap(&mut self.sel, sel);
swap(&mut self.view, view);
swap(&mut self.pending, pending);
swap(&mut self.pending_at, pending_at);
swap(&mut self.path, path);
swap(&mut self.file_name, file_name);
swap(&mut self.dirty, dirty);
+1 -11
View File
@@ -14,7 +14,6 @@ impl Session {
doc: self.doc.clone(),
sel: self.sel.clone(),
pending: self.pending.clone(),
pending_at: self.pending_at.clone(),
column: self.column.clone(),
}));
if self.history.len() > MAX_UNDO {
@@ -35,14 +34,7 @@ impl Session {
/// Record `doc`/`sel` as their own undo step after the fact and close the typing group, so
/// Undo right after an automatic change (AutoFormat, AutoCorrect) reverts only that change.
pub fn push_undo(&mut self, label: &str, doc: Document, sel: Selection) {
self.history.push(Arc::new(Undo {
label: label.to_string(),
doc,
sel,
pending: self.pending.clone(),
pending_at: self.pending_at.clone(),
column: None,
}));
self.history.push(Arc::new(Undo { label: label.to_string(), doc, sel, pending: self.pending.clone(), column: None }));
if self.history.len() > MAX_UNDO {
self.history.remove(0);
self.undo_evicted += 1;
@@ -218,7 +210,6 @@ impl Session {
doc: std::mem::replace(&mut self.doc, u.doc),
sel: std::mem::replace(&mut self.sel, u.sel),
pending: std::mem::replace(&mut self.pending, u.pending),
pending_at: std::mem::replace(&mut self.pending_at, u.pending_at),
column: std::mem::replace(&mut self.column, u.column),
};
self.redo.push(Arc::new(cur));
@@ -245,7 +236,6 @@ impl Session {
doc: std::mem::replace(&mut self.doc, u.doc),
sel: std::mem::replace(&mut self.sel, u.sel),
pending: std::mem::replace(&mut self.pending, u.pending),
pending_at: std::mem::replace(&mut self.pending_at, u.pending_at),
column: std::mem::replace(&mut self.column, u.column),
};
self.history.push(Arc::new(cur));
+3 -19
View File
@@ -168,32 +168,16 @@ impl Session {
/// area with the comments in balloons. Fields Word fills in for output show their fresh
/// results ([`crate::cmd::references::output_fields`]).
pub fn export_layout_with(&self, markup: bool) -> Arc<DocLayout> {
self.output_layout(markup, false)
}
/// The layout a print job draws ([`Session::print_pdf`]): with `markup` as
/// [`Session::export_layout_with`]; without it the final text, as Word's "No Markup", so tracked
/// deletions, which the job doesn't draw, take no space either, whatever Track Changes
/// Options say. Page images keep [`Session::export_layout_with`]: they always show markup.
pub fn print_layout(&self, markup: bool) -> Arc<DocLayout> {
self.output_layout(markup, !markup)
}
/// The print-view layout for output; `final_text` leaves tracked deletions out.
fn output_layout(&self, markup: bool, final_text: bool) -> Arc<DocLayout> {
let out = crate::cmd::references::output_fields(&self.doc);
self.output_layout_of(out.as_ref().unwrap_or(&self.doc), markup, final_text)
self.export_layout_of(out.as_ref().unwrap_or(&self.doc), markup)
}
/// [`Session::output_layout`] of `doc`, this document as it is output; `final_text` leaves tracked deletions out.
pub(crate) fn output_layout_of(&self, doc: &Document, markup: bool, final_text: bool) -> Arc<DocLayout> {
/// [`Session::export_layout_with`] of `doc`, this document as it is output.
pub(crate) fn export_layout_of(&self, doc: &Document, markup: bool) -> Arc<DocLayout> {
let (fn_name, fn_path) = self.resolved_filenames();
let opts = LayoutOptions {
view: ViewMode::Print,
hide_deleted: final_text,
comment_balloons: markup && self.prefs.markup.comments,
// Deletions Track Changes Options mark Hidden take no space, as on screen.
hide_marked: self.prefs.markup.hidden_deletions(),
numeral: self.view.numeral.resolve(SYSTEM_LOCALE.get().map(String::as_str)),
filename: Some(Arc::from(fn_name.as_str())),
filepath: Some(Arc::from(fn_path.as_str())),
+1 -4
View File
@@ -22,7 +22,7 @@ impl Session {
let name = path.to_string_lossy();
if let Err(e) = crate::file_access::check_read(&name)
.and_then(|()| crate::file_access::check_write(&name))
.and_then(|()| crate::custom_dict::save_custom_dictionary(path, removed))
.and_then(|()| wordcraft_proof::save_user_dictionary(path, removed).map_err(|e| e.to_string()))
{
log::warn!("custom dictionary: save failed: {e}");
}
@@ -41,7 +41,6 @@ impl Session {
sel,
view,
pending,
pending_at,
path,
file_name,
dirty,
@@ -92,12 +91,10 @@ impl Session {
sel,
view,
pending,
pending_at,
last_highlight: wordcraft_doc::props::Highlight::Yellow,
path,
file_name,
user_dict_path: None,
default_user_dict_path: None,
dirty,
clipboard: None,
pending_move,
+2 -42
View File
@@ -225,7 +225,7 @@ impl Session {
pub fn typing_props(&self) -> CharProps {
let (a, _) = self.sel.ordered();
let first = match self.doc.para_at(&a) {
Some(p) if self.waiting().is_none() && !self.sel.is_collapsed() && a.off < p.len() => Some(p.props_of_char(a.off)),
Some(p) if self.pending.is_none() && !self.sel.is_collapsed() && a.off < p.len() => Some(p.props_of_char(a.off)),
_ => None,
};
let mut c = match first {
@@ -243,49 +243,9 @@ impl Session {
c
}
/// The formatting waiting for the next typed text ([`Self::pending`]), unless Backspace
/// carried it over at a place the caret has since left, or a selection now stands there:
/// that formatting is for typing where the character was deleted only (#6518).
pub fn waiting(&self) -> Option<&CharProps> {
let p = self.pending.as_ref()?;
match &self.pending_at {
Some(at) if !self.sel.is_collapsed() || self.sel.focus != *at => None,
_ => Some(p),
}
}
/// Forget formatting Backspace carried over once it no longer applies ([`Self::waiting`]):
/// whatever moved the caret or selected text — a paste, Find, Go To, a click — leaves the
/// next typed text the formatting of where it lands, as in Word (#6518).
pub(crate) fn drop_stale_carried(&mut self) {
if self.pending.is_none() {
self.pending_at = None;
} else if self.pending_at.is_some() && self.waiting().is_none() {
self.pending = None;
self.pending_at = None;
}
}
/// Move the caret or select text without a command, as a front end does for a right-click,
/// a click into a header or a balloon. Formatting Backspace carried over stays only if the
/// caret is still where the character was deleted: once it has been anywhere else, coming
/// back does not bring it back (#6518). Assigning [`Self::sel`] directly skips this.
pub fn set_selection(&mut self, sel: Selection) {
self.sel = sel;
self.drop_stale_carried();
}
/// Drop formatting Backspace carried over, wherever the caret is: it is for typing, and a
/// paste is not typing, so pasted text takes the formatting where it lands (#6518).
pub(crate) fn forget_carried(&mut self) {
if self.pending_at.take().is_some() {
self.pending = None;
}
}
/// The caret's formatting, as Reveal Formatting shows it.
pub fn caret_props(&self) -> CharProps {
if let Some(p) = self.waiting() {
if let Some(p) = &self.pending {
return p.clone();
}
let f = &self.sel.focus;
+1 -29
View File
@@ -70,22 +70,7 @@ impl Session {
{
crate::cmd::md_source::before_command(self, id, mutates)?;
}
// Formatting Backspace carried over is for typing where the character was deleted: a
// caret the front end moved itself (a click elsewhere) has left it behind (#6518).
self.drop_stale_carried();
let carried_before = self.pending_at.clone().map(|at| (self.pending.clone(), at));
// The formatting waiting at the caret is not part of the document snapshot a failed
// command is rolled back to: put it back here, so a refused edit (a Backspace into a
// locked content control) leaves it as it was.
let document_before = self.document_id;
let waiting_before = (self.pending.clone(), self.pending_at.clone());
let result = self.run_command(id, params);
if result.is_ok() {
self.settle_carried(carried_before);
} else if self.document_id == document_before {
(self.pending, self.pending_at) = waiting_before;
}
result
self.run_command(id, params)
}
/// Dispatches `id` through the command registry with transactional rollback on failure,
@@ -317,19 +302,6 @@ impl Session {
result
}
/// After a command, formatting Backspace carried over stays only where typing would use it
/// (#6518). One the command left alone is dropped if the caret is elsewhere now (a paste,
/// Find, Go To); one it changed (Bold, a hyperlink's end) is for the caret it left.
fn settle_carried(&mut self, before: Option<(Option<CharProps>, Pos)>) {
if let Some((pending, at)) = before
&& self.pending_at.as_ref() == Some(&at)
&& self.pending != pending
{
self.pending_at = Some(self.sel.focus.clone());
}
self.drop_stale_carried();
}
fn finish_success(&mut self, context: SuccessContext<'_>) {
let SuccessContext {
id,
+3 -12
View File
@@ -23,7 +23,6 @@ impl Session {
self.math = None;
self.sel = Selection::caret(self.doc.start_of(StoryRef::Body));
self.pending = None;
self.pending_at = None;
self.typing = None;
self.also_selected.clear();
self.member = None;
@@ -52,7 +51,7 @@ impl Session {
/// A snapshot to put back with [`Session::restore`], for a caller that runs a command and
/// may want to take it back without a trace (cheap: the document's blocks are shared).
///
/// Covered: `doc`, `sel`, `pending` with `pending_at`, the undo stack (its length, and its oldest steps when it is near
/// Covered: `doc`, `sel`, the undo stack (its length, and its oldest steps when it is near
/// the limit), `redo`, the open typing group, the pending `join_next_undo`,
/// `join_next_equation_edit` and body replacement promises, whether the typing group has a
/// step of its own, and `dirty`. `rev`,
@@ -72,14 +71,12 @@ impl Session {
doc,
sel,
view: _,
pending,
pending_at,
pending: _,
last_highlight: _,
path: _,
file_name: _,
// The custom dictionary file, like the file path: host wiring, not an edit.
user_dict_path: _,
default_user_dict_path: _,
dirty,
clipboard: _,
// Like the clipboard: what the next paste can make a move of.
@@ -184,8 +181,6 @@ impl Session {
EditSnapshot {
doc: doc.clone(),
sel: sel.clone(),
pending: pending.clone(),
pending_at: pending_at.clone(),
history_len: history.len(),
evicted: *undo_evicted,
head,
@@ -201,14 +196,12 @@ impl Session {
}
/// Put a snapshot back: the commands run since leave no trace in the document, the
/// selection, the formatting waiting at the caret or undo/redo (undo steps the limit pushed out meanwhile come back). The layout
/// selection or undo/redo (undo steps the limit pushed out meanwhile come back). The layout
/// is recomputed.
pub fn restore(&mut self, snap: EditSnapshot) {
let EditSnapshot {
doc,
sel,
pending,
pending_at,
history_len,
evicted,
head,
@@ -230,8 +223,6 @@ impl Session {
self.autocap = None;
self.doc = doc;
self.sel = sel;
self.pending = pending;
self.pending_at = pending_at;
self.also_selected.clear();
self.member = None;
self.history.truncate(history_len);
-9
View File
@@ -16,7 +16,6 @@ pub struct WindowView {
sel: Selection,
view: ViewState,
pending: Option<CharProps>,
pending_at: Option<Pos>,
goal_x: Option<f32>,
page_hint: usize,
hf_return: Option<Selection>,
@@ -63,7 +62,6 @@ impl Session {
sel: replace(&mut self.sel, Selection::caret(start)),
view: take(&mut self.view),
pending: self.pending.take(),
pending_at: self.pending_at.take(),
goal_x: self.goal_x.take(),
page_hint: take(&mut self.page_hint),
hf_return: self.hf_return.take(),
@@ -88,7 +86,6 @@ impl Session {
sel: self.sel.clone(),
view: self.view.clone(),
pending: self.pending.clone(),
pending_at: self.pending_at.clone(),
goal_x: self.goal_x,
page_hint: self.page_hint,
hf_return: self.hf_return.clone(),
@@ -119,7 +116,6 @@ impl Session {
sel,
view,
pending,
pending_at,
goal_x,
page_hint,
hf_return,
@@ -141,7 +137,6 @@ impl Session {
self.view = view;
self.view.follow_prefs(&self.prefs);
self.pending = pending;
self.pending_at = pending_at;
self.goal_x = goal_x;
self.page_hint = page_hint;
self.column_mode = column_mode;
@@ -166,10 +161,6 @@ impl Session {
self.equation_join_next = false;
self.ime_text_join = None;
self.typing = None;
// Formatting Backspace carried over was for the text it was deleted from (#6518).
if self.pending_at.take().is_some() {
self.pending = None;
}
self.also_selected = Vec::new();
self.column = None;
self.widened = None;
+2 -6
View File
@@ -8,15 +8,11 @@ use wordcraft_layout::{DocLayout, NumeralMode, ViewMode};
/// the undo and redo stacks (also the oldest undo steps the undo limit pushes out meanwhile), the
/// open typing group, the pending
/// [`Session::join_next_undo`]/[`Session::join_next_equation_edit`]/body IME replacement promises,
/// whether the group has a step of its own, the formatting waiting at the caret (with where
/// Backspace carried it over) and the dirty flag. See [`Session::edit_snapshot`].
/// whether the group has a step of its own, and the dirty flag. See
/// [`Session::edit_snapshot`].
pub struct EditSnapshot {
pub(super) doc: Document,
pub(super) sel: Selection,
/// `Session::pending` and `Session::pending_at` then: they go together, so a restored caret
/// gets back the formatting it had, carried by Backspace or set there (#6518).
pub(super) pending: Option<wordcraft_doc::props::CharProps>,
pub(super) pending_at: Option<wordcraft_doc::Pos>,
pub(super) history_len: usize,
/// `Session::undo_evicted` when the snapshot was taken.
pub(super) evicted: u64,
-1
View File
@@ -197,7 +197,6 @@ pub(crate) fn pdf_options(opts: &ExportOptions) -> wordcraft_pdf::PdfOptions {
include_markup: opts.markup,
comments: opts.markup && opts.comments,
numeral: opts.numeral,
revisions: opts.revisions.clone(),
bookmark_error: crate::locale::bookmark_error(),
..Default::default()
}
-349
View File
@@ -265,7 +265,6 @@ fn reset_shortcuts_remove_direct_formatting_but_keep_styles() {
#[test]
fn custom_dictionary_words_persist_through_their_file() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
// #40: adding a word through a command writes it to the session's file, and loading
// that file makes the word known (only the desktop app wires this up).
let dir = std::env::temp_dir().join(format!("wc-engdict-{}", std::process::id()));
@@ -293,7 +292,6 @@ fn custom_dictionary_words_persist_through_their_file() {
#[test]
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
// #3737 (findings 34 and WC-35): the custom dictionary file and the folder settings are
// held to the automation roots like any other path.
let base = scratch_dir("dict-roots");
@@ -307,7 +305,6 @@ fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_thei
let confined = |s: &mut Session, cmd: &str, v: serde_json::Value| crate::file_access::confine(roots.as_ref(), || s.run(cmd, &v));
assert!(confined(&mut s, "review.addToDictionary", json!({"word": "zxqengconfined"})).is_ok());
assert!(wordcraft_proof::user_dictionary().contains(&"zxqengconfined".to_string()), "kept in memory");
wordcraft_proof::remove_word("zxqengconfined");
assert!(!outside.exists(), "nothing written outside the write root");
for key in ["dictionariesFolder", "userTemplatesFolder"] {
assert!(confined(&mut s, "file.options", json!({key: base.join("outside").to_string_lossy()})).is_err(), "{key}");
@@ -322,7 +319,6 @@ fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_thei
#[test]
fn add_to_dictionary_takes_only_words_the_file_keeps() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
// #40: the same rule as loading the dictionary file, so nothing added is dropped on the next load.
let mut s = s();
for bad in ["two words", "tab\tword", "bell\u{7}", &"x".repeat(65)] {
@@ -331,202 +327,6 @@ fn add_to_dictionary_takes_only_words_the_file_keeps() {
}
run(&mut s, "review.addToDictionary", json!({"word": " zxqengtrimmed "}));
assert!(wordcraft_proof::user_dictionary().contains(&"zxqengtrimmed".to_string()));
wordcraft_proof::remove_word("zxqengtrimmed");
}
/// #5840: WordCraft supports choosing a freestanding custom.dic dictionary file (including
/// UTF-16LE with BOM as written by Microsoft Word), using it in conjunction with the main
/// dictionary, and persisting additions back to it in the same encoding.
#[test]
fn custom_dictionary_freestanding_file_option() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = crate::custom_dict::TestDir::new("custom-dic");
let dic_path = dir.path().join("custom.dic");
// Write a freestanding UTF-16LE dictionary file with BOM, as Word saves it on Windows.
let mut initial_bytes = vec![0xFF, 0xFE];
for u in "freestandingword\r\nmameui\r\n".encode_utf16() {
initial_bytes.extend_from_slice(&u.to_le_bytes());
}
std::fs::write(&dic_path, &initial_bytes).unwrap();
let mut s = s();
let default_path = dir.path().join("default.txt");
s.default_user_dict_path = Some(default_path.clone());
s.user_dict_path = Some(default_path.clone());
// Seed default dictionary with a default word.
std::fs::write(&default_path, "defaultword\n").unwrap();
crate::custom_dict::load_custom_dictionary(&default_path).unwrap();
assert!(wordcraft_proof::is_correct("defaultword"));
// Before binding, the word is unknown.
assert!(!wordcraft_proof::is_correct("freestandingword"));
// Set customDictionary in file.options: removes previous words and loads custom.dic.
let res = s.run("file.options", &json!({"customDictionary": dic_path.to_string_lossy()})).unwrap();
assert_eq!(res["customDictionary"], json!(dic_path.to_string_lossy()));
assert_eq!(s.prefs.custom_dictionary.as_deref(), Some(dic_path.to_string_lossy().as_ref()));
assert_eq!(s.user_dict_path.as_ref(), Some(&dic_path));
assert!(!wordcraft_proof::is_correct("defaultword"), "previous words removed on switch");
assert!(wordcraft_proof::is_correct("freestandingword"));
assert!(wordcraft_proof::is_correct("mameui"));
// Add a new word via review.addToDictionary: it persists back to custom.dic in UTF-16LE.
run(&mut s, "review.addToDictionary", json!({"word": "zxqaddedword"}));
let saved_raw = std::fs::read(&dic_path).unwrap();
assert_eq!(saved_raw[0..2], [0xFF, 0xFE], "persists as UTF-16LE with BOM");
let decoded = crate::custom_dict::decode_dictionary_bytes(&saved_raw).unwrap();
assert!(decoded.contains("freestandingword"));
assert!(decoded.contains("zxqaddedword"));
// Revert to "auto": removes custom dictionary words and restores default path.
s.run("file.options", &json!({"customDictionary": "auto"})).unwrap();
assert_eq!(s.prefs.custom_dictionary, None);
assert_eq!(s.user_dict_path.as_ref(), Some(&default_path));
assert!(!wordcraft_proof::is_correct("freestandingword"), "freestanding words removed on revert");
assert!(!wordcraft_proof::is_correct("zxqaddedword"));
assert!(wordcraft_proof::is_correct("defaultword"), "default words restored");
// Setting customDictionary to "auto" when user_dict_path is already default_path
// updates s.prefs.custom_dictionary even if it previously held a stale path.
s.prefs.custom_dictionary = Some("/stale/nonexistent.dic".to_string());
s.run("file.options", &json!({"customDictionary": "auto"})).unwrap();
assert_eq!(s.prefs.custom_dictionary, None);
// Clean up test words from proofing dictionary
wordcraft_proof::remove_word("defaultword");
// Reject nonexistent files, folders, relative paths, or oversized files.
assert!(s.run("file.options", &json!({"customDictionary": dir.path().join("missing.dic").to_string_lossy()})).is_err());
let dir_err = s.run("file.options", &json!({"customDictionary": dir.path().to_string_lossy()})).unwrap_err();
assert!(format!("{dir_err:?}").contains("is a folder, not a file"));
let rel_err = s.run("file.options", &json!({"customDictionary": "relative/custom.dic"})).unwrap_err();
assert!(format!("{rel_err:?}").contains("isn't a full path"));
// Accept ~/ path expansion when HOME points to a directory.
if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
let home_dir = std::path::PathBuf::from(home);
let test_name = format!(".wordcraft-test-tilde-{}.dic", std::process::id());
let tilde_file = home_dir.join(&test_name);
struct CleanFile(std::path::PathBuf);
impl Drop for CleanFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
if let Ok(mut f) = opts.open(&tilde_file) {
use std::io::Write;
let _ = f.write_all(b"tildeword\n");
let _cleaner = CleanFile(tilde_file.clone());
let tilde_res = s.run("file.options", &json!({"customDictionary": format!("~/{test_name}")}));
assert!(tilde_res.is_ok(), "tilde expansion succeeds: {:?}", tilde_res.err());
assert_eq!(s.prefs.custom_dictionary.as_deref(), Some(tilde_file.to_string_lossy().as_ref()));
assert!(wordcraft_proof::is_correct("tildeword"));
s.run("file.options", &json!({"customDictionary": "auto"})).unwrap();
wordcraft_proof::remove_word("tildeword");
wordcraft_proof::remove_word("defaultword");
}
}
let huge_dic = dir.path().join("huge.dic");
std::fs::write(&huge_dic, vec![b'a'; (crate::custom_dict::MAX_CUSTOM_FILE_BYTES + 1024) as usize]).unwrap();
assert!(s.run("file.options", &json!({"customDictionary": huge_dic.to_string_lossy()})).is_err());
assert_eq!(s.prefs.custom_dictionary, None, "oversized dictionary rejects without changing prefs");
wordcraft_proof::remove_word("defaultword");
}
/// #5840 review: a dictionary that passes the metadata and access checks but can't be decoded
/// refuses the whole `file.options` call before any setting is applied, so a combined call leaves
/// the preferences, the bound path and the proofing words as they were.
#[test]
fn refused_custom_dictionary_leaves_every_other_option_unchanged() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = crate::custom_dict::TestDir::new("custom-dic-refused");
let bound = dir.path().join("custom.dic");
std::fs::write(&bound, "boundword\n").unwrap();
// A lone 0xFF byte is neither UTF-8 nor a UTF-16LE BOM pair: the file is a readable, writable
// regular file, so only decoding refuses it.
let bad = dir.path().join("bad.dic");
std::fs::write(&bad, [b'h', b'i', 0xFF]).unwrap();
let mut s = s();
s.default_user_dict_path = Some(dir.path().join("custom-dictionary.txt"));
run(
&mut s,
"file.options",
json!({
"author": "Ada",
"initials": "AL",
"units": "centimeters",
"region": "pl-PL",
"dictionariesFolder": dir.path().to_string_lossy(),
"customDictionary": bound.to_string_lossy(),
"markGrammar": true,
"checkSpelling": true,
}),
);
assert!(wordcraft_proof::is_correct("boundword"));
let before = cmd::options::current(&s);
let err = s
.run(
"file.options",
&json!({
"author": "Grace",
"initials": "GH",
"units": "inches",
"region": "en-US",
"dictionariesFolder": "auto",
"customDictionary": bad.to_string_lossy(),
"markGrammar": false,
"checkSpelling": false,
"addWords": ["zxqrefusedword"],
}),
)
.unwrap_err();
assert!(format!("{err:?}").contains("malformed"), "reports the decode failure: {err:?}");
assert_eq!(cmd::options::current(&s), before, "a refused dictionary changes no setting");
assert_eq!(s.user_dict_path.as_ref(), Some(&bound), "the bound dictionary stays");
assert!(!wordcraft_proof::is_correct("zxqrefusedword"), "the refused call adds no words");
// `auto` decodes the default file before applying too, so a malformed default file is refused
// the same way and its companion settings stay as they were.
let default_path = dir.path().join("custom-dictionary.txt");
std::fs::write(&default_path, [b'x', 0xFF]).unwrap();
let before = cmd::options::current(&s);
let err = s.run("file.options", &json!({"customDictionary": "auto", "units": "points"})).unwrap_err();
assert!(format!("{err:?}").contains("malformed"), "reports the decode failure: {err:?}");
assert_eq!(cmd::options::current(&s), before, "a malformed default dictionary changes no setting");
assert_eq!(s.prefs.custom_dictionary.as_deref(), Some(bound.to_string_lossy().as_ref()));
wordcraft_proof::remove_word("boundword");
}
#[cfg(unix)]
#[test]
fn custom_dictionary_rejects_symlink_and_readonly_files() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = crate::custom_dict::TestDir::new("custom-dic-symlink");
let dic_path = dir.path().join("custom.dic");
std::fs::write(&dic_path, "word\n").unwrap();
let mut s = s();
let symlink_path = dir.path().join("symlink.dic");
let _ = std::os::unix::fs::symlink(&dic_path, &symlink_path);
let link_err = s.run("file.options", &json!({"customDictionary": symlink_path.to_string_lossy()})).unwrap_err();
assert!(format!("{link_err:?}").contains("is a symbolic link"));
let ro_path = dir.path().join("readonly.dic");
std::fs::write(&ro_path, "word\n").unwrap();
let mut perms = std::fs::metadata(&ro_path).unwrap().permissions();
perms.set_readonly(true);
let _ = std::fs::set_permissions(&ro_path, perms);
let ro_err = s.run("file.options", &json!({"customDictionary": ro_path.to_string_lossy()})).unwrap_err();
let ro_msg = format!("{ro_err:?}");
assert!(ro_msg.contains("read-only") || ro_msg.contains("Permission denied"));
}
#[test]
@@ -1875,26 +1675,6 @@ fn paste_merge_formatting_keeps_rtf_deletions() {
assert_eq!(text(&s), "xkept");
}
#[test]
fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
// #4852 review: with the caret in a run marked `w:cs` (Thai from a WPS or Word file), the
// pasted text takes `cs` too, so its bold and italic must be the complex-script ones as well.
let mut s = s();
run(&mut s, "document.setText", json!({"text": "ภาษาไทย"}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.set", json!({"props": {"cs": true}}));
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.pasteMerge", json!({"rtf": r"{\rtf1{\b bold}{\i slant}\par}"}));
let p = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
let at = |word: &str| p.props_of_char(p.text.find(word).unwrap() + 1).clone();
let (b, i) = (at("bold"), at("slant"));
assert_eq!((b.cs, b.bold, b.bold_cs), (Some(true), Some(true), Some(true)), "{b:?}");
assert_eq!((i.cs, i.italic, i.italic_cs), (Some(true), Some(true), Some(true)), "{i:?}");
assert_ne!(b.italic, Some(true));
let r = s.doc.styles.resolve_char(None, &b);
assert!(r.bold_cs, "drawn bold as complex script");
}
#[test]
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
@@ -6720,21 +6500,6 @@ fn file_capped_read_refuses_content_over_the_cap() {
assert_eq!(whole.unwrap().len(), 100);
}
/// Web fallback for `read_file_capped` and `read_file_head` returns the expected browser error.
#[test]
fn wasm_read_file_fallback_returns_browser_error() {
let err = crate::io::wasm_read_file_fallback("sample.dic").unwrap_err();
assert!(err.contains("files are opened through the browser on the web"));
}
/// #5840: On wasm32 targets, `read_file_capped` and `read_file_head` return the browser fallback error.
#[cfg(target_arch = "wasm32")]
#[test]
fn wasm_target_read_file_capped_and_head_return_browser_error() {
assert!(crate::io::read_file_capped("test.dic", 1024, "dictionary").unwrap_err().contains("browser on the web"));
assert!(crate::io::read_file_head("test.dic", 1024).unwrap_err().contains("browser on the web"));
}
/// #3666: `read_regular_file_within` (Paste Special's copied picture file) reads a file of up to
/// `limit` bytes whole and refuses one whose handle reports more, before reading any of it.
#[cfg(not(target_arch = "wasm32"))]
@@ -8815,113 +8580,6 @@ fn insert_icon_places_a_picture_of_the_requested_size_that_saves_and_recolours()
assert!(s.run("picture.iconColor", &json!({})).is_err());
}
/// #5232: a PDF with markup (file.exportPdf, file.printPdf) marks tracked changes in the Track
/// Changes Options colours, not always by author.
#[test]
fn markup_pdf_takes_the_track_changes_option_colours() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
let markup = json!({"markup": true});
let uncompressed_markup = json!({"markup": true, "compress": false});
let pdf = |s: &Session| crate::io::save_bytes_opts("x.pdf", &s.doc, &cmd::file::export_options(s, &markup)).unwrap();
let print = |s: &Session| s.print_pdf(&markup).unwrap().0;
let (by_author, printed_by_author) = (pdf(&s), print(&s));
// Exports are deterministic, so differences are solely due to the colours.
assert_eq!(pdf(&s), by_author, "pdf export must be deterministic");
assert_eq!(print(&s), printed_by_author, "print_pdf must be deterministic");
let has = |t: &[&str], op: &str| {
let want: Vec<_> = op.split_ascii_whitespace().collect();
t.windows(want.len()).any(|w| w == want.as_slice())
};
let by_author_print_uncompressed = s.print_pdf(&uncompressed_markup).unwrap().0;
let by_author_print_raw = String::from_utf8_lossy(&by_author_print_uncompressed);
let by_author_print_tokens: Vec<_> = by_author_print_raw.split_ascii_whitespace().collect();
assert!(!has(&by_author_print_tokens, "0 0 1 rg") && !has(&by_author_print_tokens, "1 0 0 rg"), "by-author print has no pure blue or red");
s.run("review.trackingOptions", &json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
let opts = cmd::file::export_options(&s, &markup);
assert_eq!(opts.revisions.insert_color, Some(wordcraft_doc::props::Rgb(0, 0, 255)));
assert_eq!(opts.revisions.delete_color, Some(wordcraft_doc::props::Rgb(255, 0, 0)));
let coloured_pdf = pdf(&s);
let coloured_print = print(&s);
assert_ne!(coloured_pdf, by_author, "file.exportPdf ignores the tracking colours");
assert_ne!(coloured_print, printed_by_author, "file.printPdf ignores the tracking colours");
let coloured_print_uncompressed = s.print_pdf(&uncompressed_markup).unwrap().0;
let print_raw = String::from_utf8_lossy(&coloured_print_uncompressed);
let print_tokens: Vec<_> = print_raw.split_ascii_whitespace().collect();
assert!(has(&print_tokens, "0 0 1 rg"), "coloured print_pdf has blue operator for insertion");
assert!(has(&print_tokens, "1 0 0 rg"), "coloured print_pdf has red operator for deletion");
}
/// #5232 review: File › Print without Print Markup leaves out tracked deletions in layout,
/// so the page count matches the PDF export and deletions take no blank space.
#[test]
fn print_jobs_without_markup_lay_out_the_final_text() {
let text: Vec<String> = (0..200).map(|i| format!("Line {i} of the original agreement")).collect();
let mut s = Session::new(wordcraft_doc::Document::from_text(&text.join("\n")));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.all", &json!({})).unwrap();
s.run("text.insert", &json!({"text": "Replaced"})).unwrap();
// With markup: 200 deleted lines take space in print.
let (marked_pdf, marked_plan) = s.print_pdf(&json!({"markup": true})).unwrap();
assert!(marked_plan.chosen > 1);
assert!(marked_pdf.starts_with(b"%PDF-"));
// Without markup: final text only, 1 page.
let (plain_pdf, plain_plan) = s.print_pdf(&json!({"markup": false})).unwrap();
assert_eq!(plain_plan.chosen, 1);
assert!(plain_pdf.starts_with(b"%PDF-"));
}
/// #5232 review: page images (render_png and file.exportPng) respect Track Changes Options
/// colours and hidden deletions.
#[test]
fn markup_png_takes_the_track_changes_option_colours() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
let markup_opts = json!({"markup": true});
let by_author_opts = cmd::file::export_options(&s, &markup_opts);
let by_author_png = crate::io_ext::render_png(&s.doc, 0, 1.0, &by_author_opts).unwrap();
// Change tracking options to blue insertions / red deletions.
s.run("review.trackingOptions", &json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
let coloured_opts = cmd::file::export_options(&s, &markup_opts);
let coloured_png = crate::io_ext::render_png(&s.doc, 0, 1.0, &coloured_opts).unwrap();
assert_ne!(by_author_png, coloured_png, "PNG export must reflect tracking colours");
// Also verify via file.exportPng command.
struct TempDir(std::path::PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = TempDir(std::env::temp_dir().join(format!("wordcraft-tracking-png-{}", std::process::id())));
std::fs::create_dir_all(&dir.0).unwrap();
let p1 = dir.0.join("by_author.png");
let p2 = dir.0.join("coloured.png");
s.run("review.trackingOptions", &json!({"insertColor": "byAuthor", "deleteColor": "byAuthor"})).unwrap();
s.run("file.exportPng", &json!({"path": p1.to_string_lossy(), "markup": true, "scale": 1.0})).unwrap();
s.run("review.trackingOptions", &json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
s.run("file.exportPng", &json!({"path": p2.to_string_lossy(), "markup": true, "scale": 1.0})).unwrap();
assert_ne!(std::fs::read(&p1).unwrap(), std::fs::read(&p2).unwrap());
assert_eq!(std::fs::read(&p1).unwrap(), by_author_png);
assert_eq!(std::fs::read(&p2).unwrap(), coloured_png);
// Verify hidden deletions take no space in PNG export.
s.run("review.trackingOptions", &json!({"deleteMark": "hidden"})).unwrap();
let hidden_opts = cmd::file::export_options(&s, &markup_opts);
let hidden_png = crate::io_ext::render_png(&s.doc, 0, 1.0, &hidden_opts).unwrap();
assert_ne!(hidden_png, coloured_png, "hidden deletions must affect PNG pixels/layout");
}
/// Print Markup (#589): `file.printMarkup` or a command's `markup` puts the comments into PDFs
/// (balloons beside the scaled page) and at the end of HTML, Markdown and text copies.
#[test]
@@ -13571,13 +13229,6 @@ fn style_set_keeps_imported_styles_latent_styles_and_defaults() {
let mut s = s();
run(&mut s, "design.styleSet", json!({ "name": "title" }));
assert_eq!(s.doc.styles.get("Title").unwrap().chr.size, Some(36.0));
// #4852 review: the sets that make headings bold or italic do it in both scripts, so a Thai
// heading in a run marked `w:cs` is drawn bold or italic too.
let cs = wordcraft_doc::props::CharProps { cs: Some(true), ..Default::default() };
run(&mut s, "design.styleSet", json!({ "name": "basic" }));
assert!(s.doc.styles.resolve_char(Some("Heading1"), &cs).bold_cs, "basic");
run(&mut s, "design.styleSet", json!({ "name": "casual" }));
assert!(s.doc.styles.resolve_char(Some("Heading2"), &cs).italic_cs, "casual");
}
fn style_size(s: &Session, id: &str) -> f32 {
-35
View File
@@ -156,41 +156,6 @@ fn font_commands_override_inherited_complex_script_properties_explicitly() {
assert_eq!((c.size, c.size_cs, c.bold_cs, c.italic_cs), (Some(12.0), Some(18.0), Some(false), Some(false)));
}
#[test]
fn bold_and_italic_buttons_follow_what_a_complex_script_run_shows() {
// Thai marked `w:cs` with `w:b`/`w:i` and no `w:bCs`/`w:iCs` is drawn plain, so the buttons
// are off and the first click makes it bold and italic.
let mut s = session("ทดสอบ", false);
let p = s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
for r in &mut p.runs {
(r.props.cs, r.props.bold, r.props.italic) = (Some(true), Some(true), Some(true));
}
run(&mut s, "select.all", json!({}));
let state = run(&mut s, "format.state", json!({}));
assert_eq!((state["bold"].as_bool(), state["italic"].as_bool()), (Some(false), Some(false)));
run(&mut s, "format.bold", json!({}));
run(&mut s, "format.italic", json!({}));
let c = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().props_of_char(0).clone();
assert_eq!((c.bold_cs, c.italic_cs), (Some(true), Some(true)));
let state = run(&mut s, "format.state", json!({}));
assert_eq!((state["bold"].as_bool(), state["italic"].as_bool()), (Some(true), Some(true)));
// A right-to-left run is drawn with its complex-script values too.
let mut s = session("שלום", true);
let p = s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
for r in &mut p.runs {
(r.props.rtl, r.props.bold, r.props.bold_cs, r.props.italic, r.props.italic_cs) =
(Some(true), Some(true), Some(false), Some(true), Some(false));
}
run(&mut s, "select.all", json!({}));
let state = run(&mut s, "format.state", json!({}));
assert_eq!((state["bold"].as_bool(), state["italic"].as_bool()), (Some(false), Some(false)));
run(&mut s, "format.bold", json!({}));
run(&mut s, "format.italic", json!({}));
let c = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().props_of_char(0).clone();
assert_eq!((c.bold, c.bold_cs, c.italic, c.italic_cs), (Some(true), Some(true), Some(true), Some(true)));
}
#[test]
fn arrow_keys_move_visually_in_rtl_text() {
let fa = "سلام دنیا";
-349
View File
@@ -1708,355 +1708,6 @@ fn undoing_bold_at_the_caret_turns_bold_typing_off_again() {
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().props_of_char(0).bold, Some(true));
}
/// `text` with the characters from `from` to `to` bold, the caret at `caret`.
fn with_bold(text: &str, from: usize, to: usize, caret: usize) -> Session {
let mut s = Session::new(wordcraft_doc::Document::from_text(text));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": from}, "focus": {"block": 0, "off": to}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": caret}}));
s
}
/// Whether the character at `off` of the first paragraph is bold.
fn bold_at(s: &Session, off: usize) -> bool {
s.doc.para_at(&Pos::body(0, 0)).unwrap().props_of_char(off).bold == Some(true)
}
/// #6518: after Backspace, Word types with the deleted character's formatting, not the one to
/// the left of the caret, and the Bold button shows it.
#[test]
fn typing_after_backspace_takes_the_deleted_characters_formatting() {
// "Abc abc", "Abc" bold: Backspace after the plain space, then X is plain.
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbcXabc");
assert!(!bold_at(&s, 3));
// "abc Abc", "Abc" bold: Backspace after the bold A, then X is bold beside a plain space.
let mut s = with_bold("abc Abc", 4, 7, 5);
typ(&mut s, "\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "XY");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "abc XYbc");
assert!(bold_at(&s, 4) && bold_at(&s, 5));
// Several Backspaces: the last character deleted wins ("c", then the plain space).
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}\u{8}X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbXabc");
assert!(bold_at(&s, 2));
// Inside a word the Bold button shows the deleted character too, not the word: in "Ab c"
// with all but the space bold, Backspace after the space leaves the caret in a bold "Abc".
let mut s = with_bold("Ab c", 0, 2, 3);
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 3}, "focus": {"block": 0, "off": 4}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 3}}));
typ(&mut s, "\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbXc");
assert!(!bold_at(&s, 2));
}
/// #6518: the carried formatting goes once the caret moves, and Delete never carries it.
#[test]
fn backspace_formatting_is_dropped_by_a_caret_move_and_delete_does_not_carry() {
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}");
run(&mut s, "caret.right", json!({}));
run(&mut s, "caret.left", json!({}));
assert_eq!(s.typing_props().bold, Some(true));
typ(&mut s, "X");
assert!(bold_at(&s, 3));
// Delete after the bold "Abc" removes the plain space: X takes the bold to its left.
let mut s = with_bold("Abc abc", 0, 3, 3);
run(&mut s, "text.delete", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbcXabc");
assert!(bold_at(&s, 3));
// Deleting a plain selection with Delete or Backspace carries nothing either.
for key in ["text.delete", "text.backspace"] {
let mut s = with_bold("Abc abc", 0, 3, 3);
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 3}, "focus": {"block": 0, "off": 5}}));
run(&mut s, key, json!({}));
typ(&mut s, "X");
assert!(bold_at(&s, 3), "{key}");
}
// Undo takes the Backspace back, and with it the carried formatting.
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}");
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 4));
assert_eq!(s.pending, None);
}
/// #6518: a Backspace that changes nothing, at the start of the document, keeps formatting waiting
/// at the caret; one that joins paragraphs drops it. Observed in Word for Windows.
#[test]
fn backspace_at_the_document_start_keeps_waiting_formatting() {
// "Abc def", "Abc" bold: Backspace deletes the bold A, the second one does nothing, X is bold.
let mut s = with_bold("Abc def", 0, 3, 1);
typ(&mut s, "\u{8}\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xbc def");
assert!(bold_at(&s, 0));
// Bold at the caret before plain "abc", then a Backspace that does nothing: X is still bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("abc"));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 0}}));
run(&mut s, "format.bold", json!({"value": true}));
typ(&mut s, "\u{8}X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xabc");
assert!(bold_at(&s, 0) && !bold_at(&s, 1));
// "xyz" then bold "Abc": Backspace deletes the bold A, the second joins the paragraphs, and X
// takes the plain z to its left.
let mut s = Session::new(wordcraft_doc::Document::from_text("xyz\nAbc"));
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 1, "off": 1}}));
typ(&mut s, "\u{8}\u{8}X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "xyzXbc");
assert!(!bold_at(&s, 3) && bold_at(&s, 4));
}
/// #6518: Ctrl+Backspace that deletes nothing, at the start of the document, keeps formatting
/// waiting at the caret, as a plain Backspace there does; one that deletes a word or joins
/// paragraphs drops it. Observed in Word for Windows.
#[test]
fn ctrl_backspace_at_the_document_start_keeps_waiting_formatting() {
// "Ab def", "A" bold: Backspace deletes the bold A, Ctrl+Backspace does nothing, X is bold
// beside a plain "b".
let mut s = with_bold("Ab def", 0, 1, 1);
typ(&mut s, "\u{8}");
run(&mut s, "text.deleteWordBack", json!({}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xb def");
assert!(bold_at(&s, 0) && !bold_at(&s, 1));
// Bold at the caret before plain "abc", then a Ctrl+Backspace that does nothing: X is bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("abc"));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 0}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "text.deleteWordBack", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xabc");
assert!(bold_at(&s, 0) && !bold_at(&s, 1));
// "pq xy Ab", "A" bold: Backspace deletes the bold A, Ctrl+Backspace deletes "xy ", X is plain.
let mut s = with_bold("pq xy Ab", 6, 7, 7);
typ(&mut s, "\u{8}");
run(&mut s, "text.deleteWordBack", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "pq Xb");
assert!(!bold_at(&s, 3));
// "pq" then "Ab", "A" bold: Backspace deletes the bold A, Ctrl+Backspace joins the
// paragraphs, X is plain.
let mut s = Session::new(wordcraft_doc::Document::from_text("pq\nAb"));
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 1}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 1, "off": 1}}));
typ(&mut s, "\u{8}");
run(&mut s, "text.deleteWordBack", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "pqXb");
assert!(!bold_at(&s, 2));
}
/// #6518 review: what Backspace carries over is for typing where the character was deleted. A
/// paste leaves the next typed text the formatting where it lands, and pasted text never takes it.
#[test]
fn backspace_formatting_is_not_kept_past_a_paste() {
// "hello wrld World", "World" bold: copy it, Backspace the plain r, paste, then ! is bold
// like the pasted text to its left.
let mut s = with_bold("hello wrld World", 11, 16, 0);
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 11}, "focus": {"block": 0, "off": 16}}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 8}}));
typ(&mut s, "\u{8}");
run(&mut s, "edit.paste", json!({}));
typ(&mut s, "!");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "hello wWorld!ld World");
assert!(bold_at(&s, 7) && bold_at(&s, 12), "! takes the pasted bold, not the deleted plain r");
// "ab Cd", "C" bold: Backspace the bold C, paste plain text: it takes the plain space before
// it, and so does ! after it.
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}");
run(&mut s, "edit.paste", json!({"text": "zz"}));
typ(&mut s, "!");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab zz!d");
assert!((3..6).all(|i| !bold_at(&s, i)), "pasted text and ! are plain");
}
/// #6518 review: Find, Go To and a click elsewhere move the caret without the caret commands;
/// the formatting Backspace carried over stays behind. Observed in Word for Windows: typing over
/// a found word takes that word's formatting, and a Find with no match keeps the carried one.
#[test]
fn backspace_formatting_is_not_kept_past_find_or_go_to() {
// "Xy plain word", "X" bold: Backspace the bold X, Find "word" and type over it: Q is plain.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
run(&mut s, "edit.find", json!({"text": "word"}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "y plain Q");
assert!(!bold_at(&s, 8));
// Go To a paragraph puts a caret before a plain word: Q is plain.
let mut s = Session::new(wordcraft_doc::Document::from_text("Xy plain\nword"));
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}}));
typ(&mut s, "\u{8}");
run(&mut s, "edit.goto", json!({"paragraph": 2}));
assert_eq!(s.sel, crate::Selection::caret(Pos::body(1, 0)));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(1, 0)).unwrap().text, "Qword");
assert_ne!(s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold, Some(true));
// A caret the front end puts elsewhere itself (a right-click in the text): Q is plain.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
s.sel = crate::Selection::caret(Pos::body(0, 8));
assert_ne!(s.typing_props().bold, Some(true));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "y plain Qword");
assert!(!bold_at(&s, 8));
// A Find with no match leaves the caret where it was, and the formatting with it: Q is bold.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
run(&mut s, "edit.find", json!({"text": "zzz"}));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Qy plain word");
assert!(bold_at(&s, 0));
}
/// #6518 review: a Paste with nothing on the clipboard pastes nothing: the formatting Backspace
/// carried over stays for the typing that follows.
#[test]
fn backspace_formatting_survives_a_paste_of_an_empty_clipboard() {
// "ab Cd", "C" bold: Backspace the bold C, Paste fails, X is bold.
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}");
assert!(s.run("edit.paste", &json!({})).is_err(), "the clipboard is empty");
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab Xd");
assert!(bold_at(&s, 3));
// What Paste would insert, asked for on its own: nothing, and the formatting stays.
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}");
assert!(crate::cmd::paste::paste_content(&mut s, &json!({})).is_err());
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true));
}
/// #6518 review: a front end that moves the caret itself (a right-click) goes through
/// `Session::set_selection`: once the caret has been elsewhere, putting it back where the
/// character was deleted does not bring the carried formatting back.
#[test]
fn backspace_formatting_is_not_kept_past_a_direct_caret_move_and_back() {
// "Xy plain word", "X" bold: Backspace the bold X, the caret goes to "word" and back: Q is plain.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
s.set_selection(crate::Selection::caret(Pos::body(0, 8)));
s.set_selection(crate::Selection::caret(Pos::body(0, 0)));
assert_ne!(s.typing_props().bold, Some(true));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Qy plain word");
assert!(!bold_at(&s, 0));
// Put where it already is, the caret keeps it: Q is bold.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
s.set_selection(crate::Selection::caret(Pos::body(0, 0)));
typ(&mut s, "Q");
assert!(bold_at(&s, 0));
}
/// #6518 review: a command that fails leaves the formatting waiting at the caret as it was: a
/// Backspace refused by a content control locked against editing keeps what an earlier Backspace
/// carried over, and Bold picked at the caret.
#[test]
fn a_refused_backspace_keeps_the_formatting_waiting_at_the_caret() {
let w = wordcraft_doc::para::OBJ.len_utf8();
// "abC" in a content control, "C" bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("abC"));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 2}, "focus": {"block": 0, "off": 3}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 3}}));
run(&mut s, "developer.richText", json!({"tag": "ctl"}));
let lock = |s: &mut Session| run(s, "developer.properties", json!({"control": "ctl", "lockEdit": true}));
// Backspace the bold C, lock the control: the next Backspace is refused, and X is still bold.
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": w + 3}}));
typ(&mut s, "\u{8}");
lock(&mut s);
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true));
let before = s.doc.clone();
assert!(s.run("text.backspace", &json!({})).is_err(), "the control is locked");
assert_eq!(s.doc, before);
assert_eq!(s.sel, crate::Selection::caret(Pos::body(0, w + 2)));
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true), "the refused Backspace keeps the carried bold");
// Bold picked at the caret, then a refused Backspace: still bold.
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": w + 1}}));
s.pending = Some(wordcraft_doc::props::CharProps { bold: Some(true), ..Default::default() });
assert!(s.run("text.backspace", &json!({})).is_err(), "the control is locked");
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true), "the refused Backspace keeps the Bold picked at the caret");
}
/// #6518: the carried formatting goes on with the typing that follows, and Undo of that typing
/// brings it back where it was, so typing again there takes it once more.
#[test]
fn backspace_formatting_follows_typing_and_comes_back_with_undo() {
// "ab Cd", "C" bold: Backspace the bold C, then Y and X are both bold (Word).
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}YX");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab YXd");
assert!(bold_at(&s, 3) && bold_at(&s, 4) && !bold_at(&s, 5));
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab d");
typ(&mut s, "Z");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab Zd");
assert!(bold_at(&s, 3));
}
/// #6518: with Track Changes on, Backspace leaves the character in place marked deleted, and text
/// typed next still takes its formatting (a tracked insertion, never marked deleted); moving the
/// caret away and back drops it. Backspace over the author's own tracked insertion, which removes
/// it, carries it too. Observed in Word for Windows.
#[test]
fn tracked_backspace_carries_the_deleted_characters_formatting() {
// "xy Abc", "Abc" bold: Backspace after the bold A, then X is bold beside a plain space.
let mut s = with_bold("xy Abc", 3, 6, 4);
run(&mut s, "review.trackChanges", json!({"value": true}));
typ(&mut s, "\u{8}");
assert_eq!(s.sel, crate::Selection::caret(Pos::body(0, 3)));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "X");
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
assert_eq!(p.text, "xy XAbc", "the A stays, marked deleted");
let x = p.props_of_char(3);
assert!(x.bold == Some(true) && x.ins.is_some() && x.del.is_none(), "X is a bold tracked insertion: {x:?}");
assert!(p.props_of_char(4).del.is_some() && p.props_of_char(5).del.is_none());
// Moving the caret right and back after the Backspace drops it: X is plain.
let mut s = with_bold("xy Abc", 3, 6, 4);
run(&mut s, "review.trackChanges", json!({"value": true}));
typ(&mut s, "\u{8}");
run(&mut s, "caret.right", json!({}));
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel, crate::Selection::caret(Pos::body(0, 3)));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "xy XAbc");
assert!(!bold_at(&s, 3));
// A bold A this author typed with Track Changes on: Backspace removes it, X is still bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("xy "));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 3}}));
run(&mut s, "format.bold", json!({"value": true}));
typ(&mut s, "A");
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 4}}));
typ(&mut s, "\u{8}");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "xy ");
typ(&mut s, "X");
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
assert_eq!(p.text, "xy X");
let x = p.props_of_char(3);
assert!(x.bold == Some(true) && x.ins.is_some() && x.del.is_none(), "X is a bold tracked insertion: {x:?}");
}
/// Myanmar (#604): typed in memory order (consonant, medial, then the prevowel ေ that is drawn
/// before it), the caret steps over whole syllables and Backspace removes one sign at a time.
#[test]
+1 -2
View File
@@ -21,8 +21,7 @@ use wordcraft_engine::Session;
use wordcraft_engine::file_access::{self, AutomationRoots};
/// Methods that need the desktop app.
pub const NEEDS_APP: &str =
"needs the desktop app; `wordcraft-cli mcp --connect` is refused until the app confines its control channel to automation roots (#3695)";
pub const NEEDS_APP: &str = "needs the desktop app: start `wordcraft --control 7981` and run `wordcraft-cli mcp --connect 127.0.0.1:7981`";
/// An in-process session.
pub struct Headless {
-1
View File
@@ -220,7 +220,6 @@ impl Exporter<'_> {
}
}
/// Draws the content of a single page (background, watermark, headers, footers, body items, and comments) onto the surface.
pub(crate) fn page(&mut self, s: &mut Surface, page: &Page, w: f32, h: f32) {
if let Some(c) = self.doc.settings.page_color
&& let Some(p) = rect_path(&Rect::new(0.0, 0.0, w, h))
-6
View File
@@ -50,9 +50,6 @@ pub struct PdfOptions {
/// How [`export`] shows digits (the Numeral setting; callers resolve `System`, see
/// [`NumeralMode::resolve`]). [`export_layout`] keeps the layout it is given.
pub numeral: NumeralMode,
/// How tracked changes are marked (Track Changes Options): the insertion and deletion marks
/// and colours the screen shows (#5232). Default: marks as on screen, colours by author.
pub revisions: wordcraft_layout::display::MarkupOptions,
/// What [`export`] shows for a page reference to a bookmark the document doesn't have, in the
/// interface language (`None`: Word's English "Error! Bookmark not defined."). [`export_layout`]
/// keeps the layout it is given.
@@ -73,7 +70,6 @@ impl PdfOptions {
dim_body: false,
markup: self.include_markup,
placeholders: false,
revisions: self.revisions.clone(),
..Default::default()
}
}
@@ -83,7 +79,6 @@ impl PdfOptions {
pub fn layout_options(&self) -> wordcraft_layout::LayoutOptions {
wordcraft_layout::LayoutOptions {
hide_deleted: !self.include_markup,
hide_marked: self.revisions.hidden_deletions(),
comment_balloons: self.comments,
numeral: self.numeral,
output_page_refs: true,
@@ -110,7 +105,6 @@ impl Default for PdfOptions {
links: true,
paper: None,
numeral: NumeralMode::Arabic,
revisions: wordcraft_layout::display::MarkupOptions::default(),
bookmark_error: None,
}
}
-143
View File
@@ -4,7 +4,6 @@ use wordcraft_doc::para::InlineObject;
use wordcraft_doc::picfx::PicFx;
use wordcraft_doc::props::NumRef;
use wordcraft_doc::{Block, CharProps, Document, ListKind, Paragraph, Table, Watermark, para_block};
use wordcraft_layout::display::{DeleteMark, MarkupOptions};
use crate::*;
use wordcraft_layout::LayoutOptions;
@@ -168,65 +167,6 @@ fn extract_text(bytes: &[u8]) -> Vec<String> {
.collect()
}
/// Extract text runs with their RGB fill colour from `bytes`.
fn extract_colored_text(bytes: &[u8]) -> Vec<(String, [u8; 3])> {
use hayro_interpret::font::Glyph;
use hayro_interpret::{
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,
interpret_page,
};
use hayro_syntax::Pdf;
/// A testing device that records extracted text runs along with their RGB fill colour.
struct Ex(Vec<(String, [u8; 3])>);
impl Device<'_> for Ex {
/// Ignore soft masks during text extraction.
fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}
/// Ignore blend modes during text extraction.
fn set_blend_mode(&mut self, _: BlendMode) {}
/// Ignore paths during text extraction.
fn draw_path(&mut self, _: &kurbo::BezPath, _: kurbo::Affine, _: &Paint<'_>, _: &PathDrawMode) {}
/// Ignore clip paths during text extraction.
fn push_clip_path(&mut self, _: &ClipPath) {}
/// Ignore transparency groups during text extraction.
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}
/// Records glyph text with its non-stroking RGB color, merging adjacent glyphs of identical color.
fn draw_glyph(&mut self, g: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, paint: &Paint<'_>, mode: &GlyphDrawMode) {
if matches!(mode, GlyphDrawMode::Stroke(_)) {
return;
}
let Paint::Color(color) = paint else { return };
let rgba = color.to_rgba().to_rgba8();
let rgb = [rgba[0], rgba[1], rgba[2]];
let ch = match g.as_unicode() {
Some(hayro_cmap::BfString::Char(c)) => c.to_string(),
Some(hayro_cmap::BfString::String(s)) => s.to_string(),
None => "\u{FFFD}".to_string(),
};
if let Some((last_text, last_rgb)) = self.0.last_mut()
&& *last_rgb == rgb
{
last_text.push_str(&ch);
return;
}
self.0.push((ch, rgb));
}
/// Ignore images during text extraction.
fn draw_image(&mut self, _: Image<'_, '_>, _: kurbo::Affine) {}
/// Ignore clip path pop during text extraction.
fn pop_clip_path(&mut self) {}
/// Ignore transparency group pop during text extraction.
fn pop_transparency_group(&mut self) {}
}
let pdf = Pdf::new(bytes.to_vec()).expect("parse");
let cache = InterpreterCache::new();
let mut ex = Ex(Vec::new());
for page in pdf.pages().iter() {
let mut ctx = Context::new(kurbo::Affine::IDENTITY, kurbo::Rect::new(0.0, 0.0, 1.0, 1.0), &cache, pdf.xref(), InterpreterSettings::default());
interpret_page(page, &mut ctx, &mut ex);
}
ex.0
}
fn squash(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
@@ -353,89 +293,6 @@ fn tracked_deletions_are_left_out_without_markup() {
assert_eq!(text, "Keep DELETEDTEXT INSERTED");
}
/// #5232: the Track Changes Options colours (blue insertions, red deletions) reach the PDF instead
/// of every revision taking its author's colour.
#[test]
fn markup_takes_the_track_changes_option_colours() {
use wordcraft_doc::props::Rgb;
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let mut p = Paragraph::with_text("Keep ", CharProps::default());
let n = p.len();
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
let n = p.len();
p.insert_text(n, "Missouri", &CharProps { ins: Some(1), ..Default::default() }).unwrap();
d.body = vec![para_block(p)];
// By author: both revisions take Ada's colour (#B01E8F = [176, 30, 143]), no pure blue or red.
let by_author_bytes = export(&d, &PdfOptions { include_markup: true, compress: false, ..Default::default() }).unwrap();
let by_author_runs = extract_colored_text(&by_author_bytes);
let kansas_author = by_author_runs.iter().find(|(s, _)| s.contains("Kansas")).map(|(_, c)| *c).expect("Kansas present");
let missouri_author = by_author_runs.iter().find(|(s, _)| s.contains("Missouri")).map(|(_, c)| *c).expect("Missouri present");
assert_eq!(kansas_author, missouri_author, "by-author colours must match for the same author");
assert_ne!(kansas_author, [255, 0, 0], "by-author is not red");
assert_ne!(missouri_author, [0, 0, 255], "by-author is not blue");
// With explicit Track Changes colours: insertions are blue, deletions are red.
let blue = Rgb(0, 0, 255);
let red = Rgb(255, 0, 0);
let coloured_opts = PdfOptions {
include_markup: true,
compress: false,
revisions: MarkupOptions { insert_color: Some(blue), delete_color: Some(red), ..Default::default() },
..Default::default()
};
let coloured_bytes = export(&d, &coloured_opts).unwrap();
let coloured_runs = extract_colored_text(&coloured_bytes);
let kansas_color = coloured_runs.iter().find(|(s, _)| s.contains("Kansas")).map(|(_, c)| *c).expect("Kansas present");
let missouri_color = coloured_runs.iter().find(|(s, _)| s.contains("Missouri")).map(|(_, c)| *c).expect("Missouri present");
assert_eq!(kansas_color, [255, 0, 0], "deleted Kansas must be red");
assert_eq!(missouri_color, [0, 0, 255], "inserted Missouri must be blue");
// Also assert the PDF content stream has the corresponding color operators preceding each run.
let raw = String::from_utf8_lossy(&coloured_bytes);
let tokens: Vec<_> = raw.split_ascii_whitespace().collect();
let has = |op: &str| {
let want: Vec<_> = op.split_ascii_whitespace().collect();
tokens.windows(want.len()).any(|w| w == want.as_slice())
};
assert!(has("1 0 0 rg"), "raw PDF stream contains red non-stroking operator");
assert!(has("0 0 1 rg"), "raw PDF stream contains blue non-stroking operator");
}
/// #5232: deletions marked Hidden in Track Changes Options take no space and are omitted from
/// the exported PDF with markup.
#[test]
fn hidden_deletions_stay_out_of_markup_pdf() {
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let mut p = Paragraph::with_text("Keep ", CharProps::default());
let n = p.len();
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
let n = p.len();
p.insert_text(n, "Missouri", &CharProps { ins: Some(1), ..Default::default() }).unwrap();
d.body = vec![para_block(p)];
// Strikethrough: deleted Kansas is included in markup PDF.
let strike_opts = PdfOptions {
include_markup: true,
revisions: MarkupOptions { delete_mark: DeleteMark::Strikethrough, ..Default::default() },
..Default::default()
};
let strike_text = squash(&extract_text(&export(&d, &strike_opts).unwrap()).concat());
assert_eq!(strike_text, "Keep Kansas Missouri");
// Hidden: deleted Kansas is omitted from markup PDF.
let hidden_opts =
PdfOptions { include_markup: true, revisions: MarkupOptions { delete_mark: DeleteMark::Hidden, ..Default::default() }, ..Default::default() };
let hidden_text = squash(&extract_text(&export(&d, &hidden_opts).unwrap()).concat());
assert_eq!(hidden_text, "Keep Missouri");
}
#[test]
fn deleted_heading_text_stays_out_of_bookmarks_and_tags() {
use wordcraft_doc::{Revision, RevisionKind};
-364
View File
@@ -1,364 +0,0 @@
//! Screen readers: what a formatting shortcut did, said as Word says it ("Bold On", "Center Off",
//! "Font 14pt"). Word raises these itself; here they go through a polite live region, which
//! screen readers read when it appears.
use egui::accesskit::{Live, Role};
use serde_json::Value;
use wordcraft_doc::Align;
use crate::WordApp;
/// How long an announcement stays in the tree: a screen reader reads its name after the
/// live-region event, so it must still be there then.
const SHOWN_MS: f64 = 3000.0;
/// An announcement for screen readers. Each one gets its own node, numbered: a live region is
/// read when it appears or its text changes, so the same text twice needs a new node.
#[derive(Clone, Debug)]
pub(crate) struct Announcement {
text: String,
serial: u64,
at: f64,
}
/// Announces what the shortcut for command `id` did, once it has run; nothing for a command Word
/// doesn't announce.
pub(crate) fn after_shortcut(app: &mut WordApp, id: &str, ctx: &egui::Context) {
let Some(text) = describe(app, id) else { return };
let serial = app.announcement.as_ref().map_or(0, |a| a.serial.wrapping_add(1));
app.announcement = Some(Announcement { text, serial, at: ctx.input(|i| i.time) * 1000.0 });
}
/// The words for what command `id` did: the command's name and whether its formatting is now on,
/// or the font size the selection now has.
fn describe(app: &WordApp, id: &str) -> Option<String> {
let on_off = |name: &str, on: bool| format!("{name} {}", if on { tl!("On") } else { tl!("Off") });
let state = || wordcraft_engine::cmd::format::state(&app.session);
let character = match id {
"format.bold" => Some(("bold", tl!("Bold"))),
"format.italic" => Some(("italic", tl!("Italic"))),
"format.underline" => Some(("underline", tl!("Underline"))),
"format.subscript" => Some(("subscript", tl!("Subscript"))),
"format.superscript" => Some(("superscript", tl!("Superscript"))),
_ => None,
};
if let Some((key, name)) = character {
return Some(on_off(name, state().get(key).and_then(Value::as_bool).unwrap_or(false)));
}
let alignment = match id {
"para.alignLeft" => Some((Align::Left, tl!("Align Left"))),
"para.alignCenter" => Some((Align::Center, tl!("Center"))),
"para.alignRight" => Some((Align::Right, tl!("Align Right"))),
"para.justify" => Some((Align::Justify, tl!("Justify"))),
_ => None,
};
if let Some((want, name)) = alignment {
// As the ribbon's buttons show it: Center twice centres, then goes back to the left. Read
// in a paragraph the command formatted: a selection ending at the next paragraph's start
// leaves that one out (#418).
let s = &app.session;
let formatted = wordcraft_engine::cmd::selected_paths(s);
let path = if formatted.contains(&s.sel.focus.path) { Some(s.sel.focus.path.clone()) } else { formatted.last().cloned() };
let at = path.map(|path| wordcraft_doc::Pos { path, off: 0, ..s.sel.focus.clone() });
let align = at.and_then(|at| s.doc.para_at(&at)).map(|p| s.doc.styles.resolve_para(&p.props)).map(|r| r.align.visual(r.bidi));
return Some(on_off(name, align == Some(want)));
}
if matches!(id, "format.growFont" | "format.shrinkFont" | "format.growFont1" | "format.shrinkFont1") {
// A selection of mixed sizes has no one size to say.
let size = state().get("size").and_then(Value::as_f64)?;
let unit = wordcraft_geom::Unit::Points;
let number = unit.number(size as f32, app.session.region().decimal());
return Some(format!("{} {number}{}", tl!("Font"), crate::options::unit_suffix(unit)));
}
None
}
/// Puts the latest announcement in the tree, as a polite live region, while it is fresh.
pub(crate) fn expose(app: &WordApp, ctx: &egui::Context) {
let Some(a) = &app.announcement else { return };
let age = ctx.input(|i| i.time) * 1000.0 - a.at;
if !(0.0..SHOWN_MS).contains(&age) {
return;
}
ctx.accesskit_node_builder(egui::Id::unique(("announcement", a.serial)), |node| {
// A label's text is its value: that is the name screen readers read (UI Automation's
// live-region event goes only to a node with a name).
node.set_role(Role::Label);
node.set_live(Live::Polite);
node.set_value(a.text.clone());
});
// A frame when it's due to go, so it leaves the tree even while nothing else happens.
ctx.request_repaint_after(std::time::Duration::from_secs_f64((SHOWN_MS - age) / 1000.0));
}
#[cfg(test)]
mod tests {
use egui::accesskit::{Live, Role};
use egui::{Key, Modifiers};
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::WordApp;
/// An announcement belongs to the window whose shortcut made it, as its status message does:
/// another window drawn within its three seconds doesn't put it in its own tree.
#[test]
fn an_announcement_stays_with_its_window() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.announcement = Some(super::Announcement { text: "Bold On".into(), serial: 0, at: 0.0 });
let mut other = crate::window_ui::WindowUi::new(app.session.document_id());
app.swap_window(&mut other);
assert!(app.announcement.is_none(), "the other window has nothing to say");
app.swap_window(&mut other);
assert_eq!(app.announcement.as_ref().map(|a| a.text.as_str()), Some("Bold On"), "it is back with its window");
}
fn harness(text: &str) -> egui_kittest::Harness<'static, WordApp> {
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text(text)), crate::Services::default());
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
crate::test_harness::frames(&mut h, 6);
assert!(h.state().canvas.focused(&ctx), "the page has the keyboard");
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 8) };
crate::test_harness::frames(&mut h, 2);
h
}
/// The live region's text and node (its id, written out), if one is in the tree. The text is
/// the label's value, which is its name to screen readers.
fn heard(h: &egui_kittest::Harness<'_, WordApp>) -> Option<(String, String)> {
let node = h.query_by(|n| n.role() == Role::Label && n.data().live() == Some(Live::Polite))?;
let n = node.accesskit_node();
assert!(n.label_comes_from_value(), "a label, named by its value");
Some((n.value().unwrap_or_default(), format!("{:?}", n.id())))
}
fn press(h: &mut egui_kittest::Harness<'_, WordApp>, m: Modifiers, key: Key) -> Option<(String, String)> {
h.key_press_modifiers(m, key);
crate::test_harness::frames(h, 2);
heard(h)
}
/// Ctrl+B, Ctrl+I, Ctrl+U and the alignment keys say what they did, as Word does ("Bold On",
/// then "Bold Off"), each time in a new live region, so the same words twice are heard twice.
#[test]
fn formatting_shortcuts_say_what_they_did() {
let mut h = harness("Lanterns glow");
assert_eq!(heard(&h), None, "nothing to say before a shortcut");
let (text, first) = press(&mut h, Modifiers::COMMAND, Key::B).expect("Ctrl+B is announced");
assert_eq!(text, "Bold On");
let (text, second) = press(&mut h, Modifiers::COMMAND, Key::B).expect("again");
assert_eq!(text, "Bold Off");
assert_ne!(first, second, "each announcement is a new live region");
for (key, said) in [
(Key::I, "Italic On"),
(Key::U, "Underline On"),
(Key::E, "Center On"),
(Key::E, "Center Off"),
(Key::R, "Align Right On"),
(Key::J, "Justify On"),
(Key::L, "Align Left On"),
] {
assert_eq!(press(&mut h, Modifiers::COMMAND, key).map(|(t, _)| t).as_deref(), Some(said), "{key:?}");
}
let (_, before) = heard(&h).expect("the last one");
let (text, again) = press(&mut h, Modifiers::COMMAND, Key::L).expect("Ctrl+L twice");
assert_eq!(text, "Align Left On", "left alignment stays");
assert_ne!(before, again, "the same words twice are a new live region, so they are heard again");
let grown = press(&mut h, Modifiers::COMMAND | Modifiers::SHIFT, Key::Period).map(|(t, _)| t).expect("Ctrl+Shift+. is announced");
assert!(grown.starts_with("Font ") && grown.ends_with(" pt"), "{grown}");
}
/// Only shortcuts are announced: a ribbon button says its own state, and a command that isn't
/// formatting says nothing. An announcement leaves the tree after three seconds.
#[test]
fn only_formatting_shortcuts_are_announced_for_a_while() {
let mut h = harness("Lanterns glow");
h.state_mut().run("format.bold", json!({})).unwrap();
crate::test_harness::frames(&mut h, 2);
assert_eq!(heard(&h), None, "a command run another way isn't announced");
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::Z), None, "Undo isn't announced");
assert!(press(&mut h, Modifiers::COMMAND, Key::I).is_some());
if let Some(a) = &mut h.state_mut().announcement {
a.at -= super::SHOWN_MS;
}
crate::test_harness::frames(&mut h, 2);
assert_eq!(heard(&h), None, "gone after three seconds");
}
/// A selection ending at the next paragraph's start (Shift+Down from a paragraph's start)
/// formats only the paragraph it covers, as in Word: that is the one the announcement says.
#[test]
fn alignment_is_said_for_the_paragraph_the_shortcut_formatted() {
let mut h = harness("Lanterns glow\nRivers run");
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(1, 0) };
crate::test_harness::frames(&mut h, 2);
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::E).map(|(t, _)| t).as_deref(), Some("Center On"));
let align =
|h: &egui_kittest::Harness<'_, WordApp>, i| h.state().session.doc.para_at(&wordcraft_doc::Pos::body(i, 0)).and_then(|p| p.props.align);
assert_eq!((align(&h, 0), align(&h, 1)), (Some(wordcraft_doc::Align::Center), None), "only the first paragraph is centred");
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::E).map(|(t, _)| t).as_deref(), Some("Center Off"));
}
/// The shortcut runs after the announcement's place in the frame, so the announcement goes in
/// the next frame's tree: a key asks egui for that frame itself.
#[test]
fn the_announcement_is_in_the_frame_after_the_key() {
let mut h = harness("Lanterns glow");
// The key down alone, in one frame (`key_press_modifiers` gives each event a frame).
h.input_mut().events.push(egui::Event::Key { key: Key::B, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
crate::test_harness::frame(&mut h);
assert_eq!(heard(&h), None, "the key's own frame built its tree before the shortcut ran");
assert!(h.ctx.has_requested_repaint(), "the key asked for another frame");
crate::test_harness::frame(&mut h);
assert_eq!(heard(&h).map(|(t, _)| t).as_deref(), Some("Bold On"));
}
/// Each formatting shortcut says its own words, read from the formatting after it ran: the
/// format's name and On or Off for Ctrl+B, I, U, = (Subscript) and Shift+= (Superscript), the
/// alignment's name for Ctrl+E, R, J and L, and the size the selection now has for
/// Ctrl+Shift+. and , (Grow and Shrink Font) and Ctrl+] and [ (by 1 pt). A selection of mixed
/// sizes has no one size to say, so nothing is said.
#[test]
fn every_formatting_shortcut_says_its_own_words() {
let mut h = harness("Lanterns glow");
h.state_mut().run("format.size", json!({"size": 12})).unwrap();
crate::test_harness::frames(&mut h, 2);
let (cmd, shift) = (Modifiers::COMMAND, Modifiers::COMMAND | Modifiers::SHIFT);
for (m, key, said) in [
(cmd, Key::B, "Bold On"),
(cmd, Key::B, "Bold Off"),
(cmd, Key::I, "Italic On"),
(cmd, Key::I, "Italic Off"),
(cmd, Key::U, "Underline On"),
(cmd, Key::U, "Underline Off"),
(cmd, Key::Equals, "Subscript On"),
(cmd, Key::Equals, "Subscript Off"),
(shift, Key::Equals, "Superscript On"),
(shift, Key::Equals, "Superscript Off"),
(cmd, Key::E, "Center On"),
(cmd, Key::R, "Align Right On"),
(cmd, Key::J, "Justify On"),
(cmd, Key::L, "Align Left On"),
(shift, Key::Period, "Font 14 pt"),
(shift, Key::Comma, "Font 12 pt"),
(cmd, Key::CloseBracket, "Font 13 pt"),
(cmd, Key::OpenBracket, "Font 12 pt"),
] {
assert_eq!(press(&mut h, m, key).map(|(t, _)| t).as_deref(), Some(said), "{m:?} {key:?}");
}
let mut h = harness("Lanterns glow");
let sizes = [(0, 8, 12.0), (8, 13, 16.0)];
for (from, to, size) in sizes {
h.state_mut().session.sel =
wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, from), focus: wordcraft_doc::Pos::body(0, to) };
h.state_mut().run("format.size", json!({"size": size})).unwrap();
}
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 13) };
crate::test_harness::frames(&mut h, 2);
assert_eq!(press(&mut h, shift, Key::Period), None, "mixed sizes: nothing to say");
assert!(h.state().announcement.is_none(), "and nothing waits to be said");
}
/// The words are looked up in the interface catalogs, so each language says its own.
#[test]
fn the_words_go_through_the_interface_catalogs() {
let mut h = harness("Lanterns glow");
// These delimiters mark translations in the synthetic locale and are absent from some test fonts.
h.ctx.add_glyph_rasterizer(egui::GlyphRasterizer::new("wordcraft::announce::pseudo_markers", |request| {
matches!(request.cluster, "⟦" | "⟧").then(|| egui::RasterizedGlyph {
bitmap: egui::GlyphBitmap {
image: egui::ColorImage::new([1, 1], vec![egui::Color32::WHITE]),
offset_px: egui::Vec2::ZERO,
is_color: false,
},
advance_px: request.font_size_px.max(1.0),
})
}));
h.state_mut().ui.language = "pseudo".into();
let said = press(&mut h, Modifiers::COMMAND, Key::B).map(|(t, _)| t).unwrap_or_default();
crate::i18n::apply_language(crate::i18n::Lang::EN);
assert!(
said.split_whitespace().all(|word| word.starts_with('⟦') && word.ends_with('⟧')) && said.contains('⟦'),
"every word is marked: {said:?}"
);
}
/// Ten presses in a burst, one per frame or all in one frame (a held key, or keys typed
/// faster than frames), leave one announcement at a time, the latest, in one live region:
/// each replaces the last (`WordApp::announcement` holds one), so nothing queues up.
#[test]
fn a_burst_of_ten_presses_leaves_one_announcement_the_latest() {
let live =
|h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by(|n| n.role() == Role::Label && n.data().live() == Some(Live::Polite)).count();
let mut h = harness("Lanterns glow");
let mut nodes = std::collections::HashSet::new();
for i in 0..10 {
let (text, node) = press(&mut h, Modifiers::COMMAND, Key::B).expect("each press is announced");
assert_eq!(text, if i % 2 == 0 { "Bold On" } else { "Bold Off" }, "press {i}");
assert_eq!(live(&h), 1, "press {i}: one live region in the tree");
nodes.insert(node);
}
assert_eq!(nodes.len(), 10, "each press a new node, so each is heard");
let mut h = harness("Lanterns glow");
let key = |pressed| egui::Event::Key { key: Key::B, physical_key: None, pressed, repeat: false, modifiers: Modifiers::COMMAND };
for _ in 0..10 {
h.input_mut().events.extend([key(true), key(false)]);
}
crate::test_harness::frames(&mut h, 2);
let bold = wordcraft_engine::cmd::format::state(&h.state().session).get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(false), "ten Ctrl+B in one frame: bold on and off five times");
assert_eq!(live(&h), 1, "one live region in the tree");
assert_eq!(heard(&h).map(|(t, _)| t).as_deref(), Some("Bold Off"), "the latest is said");
}
/// The words go through the interface's catalogs (`tl!`), as the ribbon's labels do: a
/// translated interface says them in its language. Checked with a fixture language and, when
/// the craft-i18n catalogs are embedded (`CRAFT_I18N_DIR`), Turkish and Simplified Chinese.
#[test]
fn the_announcements_are_in_the_interface_language() {
let said = |app: &mut WordApp, id: &str| {
app.run(id, json!({})).unwrap();
super::describe(app, id)
};
let app = || {
let mut app =
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns glow")), crate::Services::default());
app.session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 8) };
app.run("format.size", json!({"size": 12})).unwrap();
app
};
let mut a = app();
crate::i18n::apply_language(crate::i18n::fixture_lang(
"x-fixture",
"\tBold\tBold-FX\n\tOn\tOn-FX\n\tOff\tOff-FX\n\tCenter\tCenter-FX\n\tFont\tFont-FX\n\tpt\tpt-FX\n",
));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some("Bold-FX On-FX"));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some("Bold-FX Off-FX"));
assert_eq!(said(&mut a, "para.alignCenter").as_deref(), Some("Center-FX On-FX"));
assert_eq!(said(&mut a, "format.growFont").as_deref(), Some("Font-FX 14 pt-FX"));
// The catalogs' own words: craft-i18n's `common.tsv` and `wordcraft.tsv` rows.
if crate::i18n::catalogs_embedded() {
for (code, bold, center, font) in
[("tr", "Kalın Açık", "Ortala Açık", "Yazı Tipi 14 pt"), ("zh-hans", "加粗 开", "居中 开", "字体 14 磅")]
{
let mut a = app();
crate::i18n::apply_language(crate::i18n::Lang::from_code(code).expect("an interface language"));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some(bold), "{code}");
assert_eq!(said(&mut a, "para.alignCenter").as_deref(), Some(center), "{code}");
assert_eq!(said(&mut a, "format.growFont").as_deref(), Some(font), "{code}");
}
}
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
}
-2
View File
@@ -53,7 +53,6 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
@@ -138,7 +137,6 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
+1 -4
View File
@@ -123,7 +123,7 @@ impl WordApp {
for (id, label) in GATED_UI_COMMANDS {
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
}
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
// plain keys type, and every modified chord is offered to the keymap first.
match AppCatalog::new(defs, generation) {
Ok(catalog) => {
@@ -204,9 +204,6 @@ impl WordApp {
self.edits = host;
}
let result = if fired.source == FireSource::Automation { self.execute(id, params) } else { self.run(id, params) };
if from_key && result.is_ok() {
crate::announce::after_shortcut(self, id, ctx);
}
if let Err(error) = result {
log::debug!("command {id}: {error}");
}
+1 -1
View File
@@ -674,7 +674,7 @@ impl WordApp {
let name = file.path.as_ref().map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|| file.name.clone());
let lower = name.to_ascii_lowercase();
let data = file.bytes.as_ref().map(|b| wordcraft_engine::cmd::insert::base64_encode(b.as_ref()));
let img = file_dialogs::is_picture_name(&name);
let img = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".wmf", ".emf"].iter().any(|e| lower.ends_with(e));
// Any recipient file ends the pending picker request, so a later .txt drop opens normally.
let asked = std::mem::take(&mut self.recipient_list_pending);
let list = lower.ends_with(".csv") || lower.ends_with(".tsv") || (lower.ends_with(".txt") && asked);
-1
View File
@@ -75,7 +75,6 @@ impl WordApp {
/// handed in as values and read back after, so no body reads a stale copy. Returns the
/// shell's regions; a window another command swapped in mid-draw returns none.
pub(super) fn paint_window(&mut self, ui: &mut egui::Ui) -> ShellRegions {
crate::announce::expose(self, ui.ctx());
let window = self.windows.shown();
let stale = |app: &WordApp| app.windows.shown() != window;
let mode = self.screen_mode();
+2 -2
View File
@@ -22,7 +22,7 @@ impl WordApp {
let Some(off) = end.off.checked_sub(wordcraft_doc::para::OBJ.len_utf8()) else { return };
let start = wordcraft_doc::Pos { off, ..end.clone() };
if self.session.doc.para_at(&start).and_then(|p| p.object_at(off)).is_some_and(|o| o.is_drawing()) {
self.session.set_selection(wordcraft_engine::Selection { anchor: start, focus: end });
self.session.sel = wordcraft_engine::Selection { anchor: start, focus: end };
}
}
@@ -38,7 +38,7 @@ impl WordApp {
/// arrive in one drop, put the caret after the picture placed by the previous file (#1592).
pub(super) fn caret_after_placed_picture(&mut self, placed: bool) {
if placed {
self.session.set_selection(wordcraft_engine::Selection::caret(self.session.sel.focus.clone()));
self.session.sel.anchor = self.session.sel.focus.clone();
}
}
+4 -10
View File
@@ -52,16 +52,10 @@ impl WordApp {
self.session.author = author;
}
self.session.initials = std::mem::take(&mut self.ui.initials).chars().take(wordcraft_engine::cmd::options::MAX_INITIALS_CHARS).collect();
// A bound custom dictionary file is the source of truth: `load_user_dictionary` reads it
// at start-up. Restoring the `ui.json` copy first would let a missing or unreadable file's
// words reach the default `custom-dictionary.txt` on the next Add to Dictionary (#5840).
let saved_words = std::mem::take(&mut self.ui.dictionary);
if self.ui.editing.custom_dictionary.is_none() {
for w in saved_words.iter().take(MAX_DICTIONARY) {
let w = w.trim();
if !w.is_empty() && w.chars().count() <= wordcraft_engine::cmd::options::MAX_WORD_CHARS {
wordcraft_engine::proof::add_word(w);
}
for w in std::mem::take(&mut self.ui.dictionary).iter().take(MAX_DICTIONARY) {
let w = w.trim();
if !w.is_empty() && w.chars().count() <= wordcraft_engine::cmd::options::MAX_WORD_CHARS {
wordcraft_engine::proof::add_word(w);
}
}
self.session.prefs = std::mem::take(&mut self.ui.editing);
+1 -1
View File
@@ -76,7 +76,7 @@ fn apply(app: &mut WordApp, cards: &[Card], edit: CommentEdit) {
_ => None,
});
if let Some(pos) = pos {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
}
}
CommentEdit::Edit { thread, index, text, .. } => {
+1 -1
View File
@@ -154,7 +154,7 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
let (a, b) = app.session.sel.ordered();
let trimmed = app.session.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).map(|t| t.trim_end().len()).unwrap_or(0);
let end = wordcraft_doc::Pos { off: a.off + trimmed, ..b };
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: end });
app.session.sel = wordcraft_engine::Selection { anchor: a, focus: end };
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
}
}
+8 -8
View File
@@ -304,13 +304,13 @@ pub(crate) fn handle_secondary_selection(app: &mut WordApp, body: &PageBody<'_>,
return;
}
if let Some(pos) = layout.hit(page, x, y, app.session.sel.focus.story) {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.page_hint = page;
}
}
match layout.equation_hit(page, x, y, app.session.sel.focus.story) {
Some((pos, inner)) => {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
let _ = app.run("equation.edit", json!({"pos": serde_json::to_value(&inner).unwrap_or_default()}));
return;
}
@@ -334,7 +334,7 @@ pub(crate) fn handle_secondary_selection(app: &mut WordApp, body: &PageBody<'_>,
}
}
if let Some(pos) = layout.hit(page, x, y, app.session.sel.focus.story) {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.page_hint = page;
}
}
@@ -372,7 +372,7 @@ fn handle_primary_press(
if app.run(id, json!({ "page": page })).is_ok() {
let to = app.session.sel.focus.story;
if let Some(pos) = app.session.layout().hit(page, x, y, to) {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
}
app.session.page_hint = page;
}
@@ -388,7 +388,7 @@ fn handle_primary_press(
if !mods.shift
&& let Some((at, inner)) = layout.equation_hit(page, x, y, story)
{
app.session.set_selection(wordcraft_engine::Selection::caret(at));
app.session.sel = wordcraft_engine::Selection::caret(at);
let _ = app.run("equation.edit", json!({"pos": serde_json::to_value(&inner).unwrap_or_default()}));
app.session.page_hint = page;
return true;
@@ -521,14 +521,14 @@ fn handle_completed_click(app: &mut WordApp, pointer: &PagePointer<'_>) -> bool
if app.run(id, json!({ "page": page })).is_ok()
&& let Some(pos) = app.session.layout().hit(page, x, y, app.session.sel.focus.story)
{
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
}
return true;
}
if matches!(story, StoryRef::Part(_)) && !in_text_box(app) && hf_zone.is_none() {
let _ = app.run("insert.closeHeader", json!({}));
if let Some(pos) = layout.hit(page, x, y, StoryRef::Body) {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
}
return true;
}
@@ -536,7 +536,7 @@ fn handle_completed_click(app: &mut WordApp, pointer: &PagePointer<'_>) -> bool
if let Some(pos) = layout.hit(page, x, y, story)
&& let Some(field) = field_showing_code(app, &pos)
{
app.session.set_selection(wordcraft_engine::Selection::caret(field));
app.session.sel = wordcraft_engine::Selection::caret(field);
let _ = app.run("fields.setCode", json!({}));
return true;
}
+3 -7
View File
@@ -303,7 +303,7 @@ fn swatch_table(
current: Option<Rgb>,
) -> (Option<Rgb>, craft::behavior::Preview<Rgb>, egui::Response) {
use craft::behavior::Preview;
let swatches: Vec<(Label, Srgba)> = colors.iter().map(|c| (Label::from(format!("#{}", c.hex())), srgba(*c))).collect();
let swatches: Vec<(Label, Srgba)> = colors.iter().map(|c| (Label::from(c.hex()), srgba(*c))).collect();
let out = SwatchTable::new(name.to_string(), &swatches)
.per_row(per_row)
.tips(true)
@@ -640,9 +640,7 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
),
};
let icon = shown.map_or_else(IconSpec::empty_swatch, IconSpec::swatch);
let spoken_value = current.map_or_else(|| text.as_str().to_string(), |c| format!("#{}", c.hex()));
let spoken = format!("{} {spoken_value}", label.as_str());
let field = SplitButton::<NoValue>::body(text, |ui: &mut Ui, cx: &mut BodyCx<'_>| {
SplitButton::<NoValue>::body(text, |ui: &mut Ui, cx: &mut BodyCx<'_>| {
let empty_label = match empty {
ColorFieldEmpty::NoColor => Label::from(tl!("No Color").to_string()),
ColorFieldEmpty::Automatic { label, .. } => label.clone(),
@@ -666,11 +664,9 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
cx.request_close();
}
})
.arrow_label(spoken.clone())
.arrow_label(label.clone())
.icon(icon)
.show(ui);
// The framework keeps the short visible value; both parts say the field and its value.
ui.ctx().accesskit_node_builder(field.response.id, |node| node.set_label(spoken));
resp
}
+19 -113
View File
@@ -374,28 +374,25 @@ fn shortcut_text_is_swallowed_once() {
frames(&mut h, 4);
h
};
// Alt+Q is the command search off macOS only (Option+Q types a character there; `tools.search` has no key).
if !cfg!(target_os = "macos") {
// The shortcut and its text in one frame.
let mut h = fresh();
h.event(key(egui::Key::Q, true));
h.event(egui::Event::Text("q".into()));
frames(&mut h, 3);
// The app is in Focus, where the title bar's Search box is hidden, so the dialog takes the request (#5398).
assert!(is_open(h.state(), "commands"), "Alt+Q opens the palette");
assert_eq!(query(&h), "", "Alt+Q's q, same frame");
// The text a frame late; then typing.
let mut h = fresh();
h.event(key(egui::Key::Q, true));
frames(&mut h, 1);
h.event(egui::Event::Text("q".into()));
frames(&mut h, 1);
assert_eq!(query(&h), "", "the q a frame late");
h.event(key(egui::Key::B, false));
h.event(egui::Event::Text("b".into()));
frames(&mut h, 2);
assert_eq!(query(&h), "b", "then typing lands");
}
// The shortcut and its text in one frame.
let mut h = fresh();
h.event(key(egui::Key::Q, true));
h.event(egui::Event::Text("q".into()));
frames(&mut h, 3);
// The app is in Focus, where the title bar's Search box is hidden, so the dialog takes the request (#5398).
assert!(is_open(h.state(), "commands"), "Alt+Q opens the palette");
assert_eq!(query(&h), "", "Alt+Q's q, same frame");
// The text a frame late; then typing.
let mut h = fresh();
h.event(key(egui::Key::Q, true));
frames(&mut h, 1);
h.event(egui::Event::Text("q".into()));
frames(&mut h, 1);
assert_eq!(query(&h), "", "the q a frame late");
h.event(key(egui::Key::B, false));
h.event(egui::Event::Text("b".into()));
frames(&mut h, 2);
assert_eq!(query(&h), "b", "then typing lands");
// A palette opened by a click takes typing.
let mut h = fresh();
open_named(&mut h, "commands", json!({}));
@@ -1694,94 +1691,3 @@ fn font_dialog_effects_stand_two_to_a_line_and_kerning_on_one() {
let size = h.query_all_by_label("Points and above").map(|node| node.rect()).min_by(|a, b| a.min.x.total_cmp(&b.min.x)).expect("the kerning size");
assert!((kern.center().y - size.center().y).abs() < 4.0 && kern.max.x <= size.min.x, "the kerning size is on the check box's line");
}
/// #5057: keep the accessibility contract when dialogs move onto the framework.
#[test]
fn dialogs_their_tabs_and_colour_fields_say_what_they_are() {
use egui::accesskit::Role;
let mut app = app_with("Lanterns");
// The framework palette lists the document theme; use a known colour rather than its default.
app.session.doc.settings.theme_colors = vec![wordcraft_doc::Rgb(0xC0, 0, 0)];
let mut h = app_harness(app);
open_named(&mut h, "paragraph", json!({}));
assert!(h.query_by_role_and_label(Role::Dialog, "Paragraph").is_some(), "Paragraph is a dialog");
assert!(h.query_by_role_and_label(Role::Window, "Paragraph").is_none(), "not only a window");
assert_eq!(h.get_by_role_and_label(Role::Tab, "Indents and Spacing").accesskit_node().is_selected(), Some(true));
assert_eq!(h.get_by_role_and_label(Role::Tab, "Line and Page Breaks").accesskit_node().is_selected(), Some(false));
assert!(h.query_by_role_and_label(Role::Button, "Indents and Spacing").is_none(), "not a button");
let ctx = h.ctx.clone();
close_all(h.state_mut(), &ctx);
h.run_steps(2);
open_named(&mut h, "font", json!({}));
// The framework's split field has a face and a menu arrow; the latter opens the palette.
h.query_all_by_role_and_label(Role::Button, "Font color: Automatic").last().expect("named colour field").click();
h.run_steps(3);
assert!(h.query_by_label("#C00000").is_some(), "the swatches say their colour");
h.get_by_label("#C00000").click();
h.run_steps(3);
assert!(h.query_all_by_role_and_label(Role::Button, "Font color: #C00000").next().is_some(), "the field says the colour picked");
}
/// #5057: every caller retains its translated label and selected colour.
#[test]
fn colour_fields_say_their_label_and_colour_in_the_interface_language() {
use egui::accesskit::Role;
let mut app = app_with("Lanterns");
// The framework palette lists the document theme; use a known colour rather than its default.
app.session.doc.settings.theme_colors = vec![wordcraft_doc::Rgb(0xC0, 0, 0)];
let mut h = app_harness(app);
for (dialog, names) in [("font", vec!["Font color: Automatic"]), ("borders", vec!["Color: Automatic"]), ("shading", vec!["Fill No Color"])] {
let ctx = h.ctx.clone();
close_all(h.state_mut(), &ctx);
h.run_steps(2);
open_named(&mut h, dialog, json!({}));
for name in names {
assert!(h.query_all_by_role_and_label(Role::Button, name).next().is_some(), "{dialog}: {name}");
}
}
h.query_all_by_role_and_label(Role::Button, "Fill No Color").last().expect("shading colour field").click();
h.run_steps(3);
h.get_by_label("#C00000").click();
h.run_steps(3);
assert!(h.query_all_by_role_and_label(Role::Button, "Fill #C00000").next().is_some());
let ctx = h.ctx.clone();
close_all(h.state_mut(), &ctx);
h.state_mut().run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
open_named(&mut h, "newTableStyle", json!({}));
for name in ["Font color: No Color", "Fill color: No Color"] {
assert!(h.query_all_by_role_and_label(Role::Button, name).next().is_some(), "newTableStyle: {name}");
}
// Draw the shared app field directly: the app frame selects its configured language.
crate::i18n::apply_language(crate::i18n::fixture_lang(
"x-fixture",
"\tFont color:\tFont-color-FX:\n\tAutomatic\tAutomatic-FX\n\tFill\tFill-FX\n\tNo Color\tNo-Color-FX\n",
));
let mut h = crate::test_harness::builder().with_size(egui::vec2(600.0, 300.0)).build_ui_state(
|ui, values: &mut [String; 2]| {
use crate::colors::{AutoFace, ColorFieldEmpty, Palette, color_field};
use craft::ui::runtime::env::Label;
ui.push_id("font", |ui| {
let empty = ColorFieldEmpty::Automatic {
label: Label::from(tl!("Automatic")),
value: "auto",
face: AutoFace::One(craft::theme::Srgba::rgb(0.0, 0.0, 0.0)),
};
color_field(ui, &Label::from(tl!("Font color:")), &mut values[0], &empty, &Palette::default());
});
ui.push_id("fill", |ui| {
color_field(ui, &Label::from(tl!("Fill")), &mut values[1], &ColorFieldEmpty::NoColor, &Palette::default());
});
},
["auto".to_string(), String::new()],
);
h.run_steps(3);
let found: Vec<_> = ["Font-color-FX: Automatic-FX", "Fill-FX No-Color-FX"]
.into_iter()
.map(|name| (name, h.query_all_by_role_and_label(Role::Button, name).next().is_some()))
.collect();
crate::i18n::apply_language(crate::i18n::Lang::EN);
for (name, present) in found {
assert!(present, "the translated field is {name}");
}
}
+1 -54
View File
@@ -18,8 +18,7 @@ use crate::WordApp;
/// Most font files one Add Font pick tries; the rest of a bigger selection is skipped.
const MAX_FONTS_PER_PICK: usize = 2000;
/// Picture suffixes shared by native/web choosers, drop dispatch and copied-file paste.
pub const PICTURES: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff", "wmf", "emf"];
const PICTURES: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "wmf", "emf"];
const DOCUMENTS: &[&str] =
&["docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "fodt", "rtf", "txt", "md", "html", "htm", "mht", "mhtml", "tex", "json", "xml"];
@@ -35,11 +34,6 @@ pub fn open_filters(purpose: &str) -> &'static [(&'static str, &'static [&'stati
}
}
/// Whether a file name has a picture suffix offered by the Insert/Change Picture chooser.
pub(crate) fn is_picture_name(name: &str) -> bool {
name.rsplit_once('.').is_some_and(|(_, ext)| PICTURES.iter().any(|known| known.eq_ignore_ascii_case(ext)))
}
/// `request` with the file types `open_filters` offers for `purpose`.
fn with_open_filters(mut request: PickRequest, purpose: &str) -> PickRequest {
for (label, exts) in open_filters(purpose) {
@@ -531,50 +525,3 @@ impl WordApp {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod picture_dispatch_tests {
use std::sync::Arc;
use craft::host::{AppInfo, Host, Picked, ScriptedFiles};
use craft::platform::open::{DropTarget, DroppedFile, FileIntake};
use super::*;
/// Pickers, drops and copied paths must agree on TIFF suffixes after the framework cutover.
#[test]
fn tiff_suffixes_dispatch_picked_and_dropped_images_and_copied_paths_as_pictures() {
for ext in ["tif", "tiff", "TIF", "TIFF"] {
let name = format!("scan.{ext}");
// Routing depends on the supplied name; the insertion decoder probes these PNG bytes.
let bytes = crate::paste_picture::png_from_rgba(4, 4, vec![200; 4 * 4 * 4]).unwrap();
let files = Arc::new(ScriptedFiles::held());
let host = Host::builder(AppInfo { id: "wordcraft-test", name: "WordCraft", version: "0" }).files(files.clone()).build();
let session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
let mut app = WordApp::new(session, crate::Services::default()).with_host(Arc::new(host));
let document = app.session.document_id();
app.pick_picture();
let request = files.requests().pop().unwrap();
let extensions: Vec<_> = request.filters.iter().flat_map(|f| f.extensions.iter().map(String::as_str)).collect();
assert!(extensions.contains(&"tif") && extensions.contains(&"tiff") && extensions.contains(&"png"));
assert!(!extensions.contains(&"txt"));
files.answer(Picked::Contents(vec![(name.clone(), bytes.clone())]));
app.poll_file_dialog().unwrap().unwrap();
assert_eq!(app.session.document_id(), document, "picker inserts into the current document: {ext}");
let pictures = app.session.run("arrange.selectionPane", &json!({})).unwrap();
assert_eq!(pictures.as_array().unwrap().len(), 1, "picker inserts a picture: {ext}");
let (intake, sender) = FileIntake::new(craft::host::Wake::none());
let services = crate::Services { intake: Some(intake), ..Default::default() };
let mut dropped = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
let document = dropped.session.document_id();
sender.dropped(vec![DroppedFile { path: None, name, bytes: Some(bytes.into()) }], DropTarget::Elsewhere);
dropped.drain_inbox();
assert_eq!(dropped.session.document_id(), document, "drop inserts into the current document: {ext}");
let pictures = dropped.session.run("arrange.selectionPane", &json!({})).unwrap();
assert_eq!(pictures.as_array().unwrap().len(), 1, "drop inserts a picture: {ext}");
assert!(crate::paste_picture::names_picture_files(&format!("file:///tmp/scan.{ext}")));
}
assert!(!is_picture_name("notes.txt"));
}
}
+1 -3
View File
@@ -239,10 +239,8 @@ impl<'a> Exempt<'a> {
fn allows(&self, app: &WordApp, text: &str) -> bool {
let plain = unmarked(text);
let plain = plain.trim().trim_end_matches(" —").trim();
// A chord is `Ctrl+Shift+K` or, on macOS, the modifiers' symbols run into the key (`⌥⌘Space`, `⇧⌘K`).
let chord = |s: &str| {
let key = |k: &str| matches!(k, "Ctrl" | "Shift" | "Alt" | "Cmd" | "Esc" | "Tab" | "Enter" | "Space") || k.chars().count() <= 3;
s.split('+').all(|k| key(k) || key(k.trim_start_matches(['⌃', '⌥', '⇧', '⌘'])))
s.split('+').all(|k| matches!(k, "Ctrl" | "Shift" | "Alt" | "Cmd" | "Esc" | "Tab" | "Enter" | "Space") || k.chars().count() <= 3)
};
let is_shortcut = || chord(plain);
// A command's hover hint, drawn as one text: its marked label, name and location, so what is left is the
+3 -4
View File
@@ -704,10 +704,9 @@ fn type_text(app: &mut WordApp, pass: &ToolPass, ctx: &egui::Context, text: &str
let start = app.session.sel.ordered().0;
let pending_before = app.session.pending.clone();
let typed = if let Some(props) = app.canvas.ime_join_text.take() {
// The replacement takes the erased text's formatting. A failed `Session::run` puts back
// what was waiting when it started, which is this formatting, so the earlier one is put
// back here: a refused replacement must not leave its formatting waiting for the next
// ordinary key.
// The replacement takes the erased text's formatting. `Session::run` does not restore
// `pending` on failure (it is not part of the document snapshot), so keep it here: a
// refused replacement must not leave its formatting waiting for the next ordinary key.
// The undo join itself is the engine's scoped body-replacement promise, consumed by
// `Session::run` only for this `text.insert` at the promised selection.
app.session.pending = Some(props);
+4 -3
View File
@@ -248,6 +248,7 @@ fn restored_placeholder_end(s: &wordcraft_engine::Session, deleted_start: usize)
struct ImeRollback {
snapshot: Option<wordcraft_engine::EditSnapshot>,
original: wordcraft_engine::Selection,
pending: Option<wordcraft_doc::props::CharProps>,
goal_x: Option<f32>,
}
@@ -257,9 +258,8 @@ impl ImeRollback {
return;
};
app.session.restore(snapshot);
// The snapshot puts back the formatting waiting at the caret, with where Backspace
// carried it over (#6518).
app.session.sel = self.original.clone();
app.session.pending = self.pending.clone();
app.session.goal_x = self.goal_x;
refuse_ime_request(app);
}
@@ -387,6 +387,7 @@ fn delete_surrounding_common(
let join = app.session.typing_open();
let props = app.session.typing_props();
let original = app.session.sel.clone();
let pending_before = app.session.pending.clone();
let goal_x_before = app.session.goal_x;
let before_stamp = ime_stamp(app);
// Both sides are one IME request: if the second half is refused (Restrict Editing, a
@@ -396,7 +397,7 @@ fn delete_surrounding_common(
// restored: `last_command`, macro recording, Go Back marks, `also_selected`, `typing`/
// `autocap` and canvas preedit (a refusal clears it).
let snapshot = app.session.edit_snapshot();
let mut rollback = ImeRollback { snapshot: Some(snapshot), original, goal_x: goal_x_before };
let mut rollback = ImeRollback { snapshot: Some(snapshot), original, pending: pending_before, goal_x: goal_x_before };
// Stored offsets of the suffix (and of the original selection) move by the paragraph's
// signed length change. A placeholder can make that positive; subtracting a removed-byte
// count cannot describe that, and would leave the second range and the caret inside the
+3 -41
View File
@@ -113,16 +113,6 @@ fn batch_frame(h: &mut H, events: Vec<egui::Event>) {
crate::test_harness::frame(h);
}
/// The modifiers of the platform's Mod key as egui reports them: Cmd on macOS (`mac_cmd` with `command`, and no
/// Control), Ctrl elsewhere.
fn mod_held() -> Modifiers {
if cfg!(target_os = "macos") {
Modifiers { mac_cmd: true, command: true, ..Default::default() }
} else {
Modifiers { ctrl: true, command: true, ..Default::default() }
}
}
/// One frame with `modifiers` held, then `events`.
fn mods_frame(h: &mut H, modifiers: Modifiers, events: Vec<egui::Event>) {
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
@@ -234,7 +224,7 @@ fn user_assignments_become_overrides() {
/// bold HTML, whichever of Shift and V is released first.
#[test]
fn mod_shift_v_released_shift_first_pastes_once() {
let chord = Modifiers { shift: true, ..mod_held() };
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
let ctrl = Modifiers { shift: false, ..chord };
let mut h = alt_frame_app();
run(&mut h, "text.insert", json!({"text": "source target"}));
@@ -251,7 +241,7 @@ fn mod_shift_v_released_shift_first_pastes_once() {
#[test]
fn a_global_mod_shift_v_leaves_the_next_mod_v_picture_paste_alone() {
let mut h = picture_app();
let chord = Modifiers { shift: true, ..mod_held() };
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
mods_frame(&mut h, chord, vec![key_event(Key::V, true, chord)]);
let ctrl = Modifiers { shift: false, ..chord };
mods_frame(&mut h, ctrl, vec![key_event(Key::V, false, ctrl)]);
@@ -306,7 +296,7 @@ fn key_event(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
/// whether V or Ctrl is released first, and a plain V is no paste.
#[test]
fn mod_v_released_mod_first_pastes_the_clipboard_picture() {
let ctrl = mod_held();
let ctrl = Modifiers { ctrl: true, command: true, ..Default::default() };
let mut h = alt_frame_app();
run(&mut h, "text.insert", json!({"text": "x"}));
@@ -898,34 +888,6 @@ fn tracked_own_insertion_then_a_refused_side_rolls_the_whole_request_back() {
assert_eq!(h.state().session.goal_x, Some(123.0), "the Up/Down goal column is restored");
}
/// #6518 review: a refused `DeleteSurrounding` rolls back the formatting Backspace carried
/// over together with where it applies: typing at the restored caret still takes it, and a
/// caret moved away leaves it behind, as before the request.
#[test]
fn a_refused_delete_surrounding_keeps_formatting_backspace_carried() {
let mut h = alt_frame_app();
run(&mut h, "document.setText", json!({"text": "abc"}));
// Wrap `c` in a rich-text control that refuses edits, and make `b` bold.
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 2), focus: wordcraft_doc::Pos::body(0, 3) };
run(&mut h, "developer.richText", json!({"tag": "locked"}));
run(&mut h, "developer.properties", json!({"control": "locked", "lockEdit": true}));
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 1), focus: wordcraft_doc::Pos::body(0, 2) };
run(&mut h, "format.bold", json!({"value": true}));
caret(&mut h, 2);
// Backspace the bold `b`: the caret, now after `a`, carries its bold.
run(&mut h, "text.backspace", json!({}));
assert_eq!(h.state().session.typing_props().bold, Some(true));
alt_frame(&mut h, vec![surround(1, 1)]);
assert_eq!(body(h.state()), "ac", "the request is refused and rolled back");
assert_eq!(h.state().session.sel, wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 1)));
assert_eq!(h.state().session.typing_props().bold, Some(true), "the carried bold still applies at the restored caret");
// It is still carried over by Backspace, not picked at the caret: a caret moved elsewhere
// and back leaves it behind.
h.state_mut().session.set_selection(wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 0)));
h.state_mut().session.set_selection(wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 1)));
assert_ne!(h.state().session.typing_props().bold, Some(true), "the caret has been elsewhere");
}
/// Selects a body range, wraps it in a rich-text content control with `tag`, and sets its
/// placeholder.
fn wrap_in_control(h: &mut H, start: usize, end: usize, tag: &str, placeholder: &str) {
-3
View File
@@ -101,7 +101,6 @@ pub use dialogs::dialogs_ribbon;
pub use dialogs::dialogs_smart_art;
pub use file_dialogs::open_filters;
mod announce;
mod app;
mod services;
mod state;
@@ -417,8 +416,6 @@ pub struct WordApp {
pub spelling_review: Option<proofing_pane::SpellingForm>,
/// The status bar's message, until its `until` passes.
pub(crate) status: Option<Status>,
/// The latest formatting shortcut announcement for the active window.
pub(crate) announcement: Option<announce::Announcement>,
pub previews: previews::Previews,
/// Media key of the picture a pending Change Picture replaces (#147).
pub change_picture_target: Option<String>,
+2 -11
View File
@@ -1131,20 +1131,11 @@ fn rotation_drag_turns_picture_pixels_live_and_commits_once_or_cancels() {
}
}
}
// A second angle reuses the raster rather than regenerating it on pointer moves. Only the preview texture
// counts: it is the one mesh painted faded (PREVIEW_SHARE), while page pictures are opaque and may be
// uploaded between the two moves.
// A second angle reuses the raster rather than regenerating it on pointer moves.
let textures = |h: &H| {
h.output()
.shapes
.iter()
.filter_map(|s| if let egui::Shape::Mesh(m) = &s.shape { Some(m) } else { None })
.filter(|m| m.texture_id != egui::TextureId::default() && m.vertices.first().is_some_and(|v| v.color.a() < 255))
.map(|m| m.texture_id)
.collect::<Vec<_>>()
h.output().shapes.iter().filter_map(|s| if let egui::Shape::Mesh(m) = &s.shape { Some(m.texture_id) } else { None }).collect::<Vec<_>>()
};
let before_move = textures(&h);
assert_eq!(before_move.len(), 1, "{initial}/{flip_h}/{flip_v}: exactly one faded preview mesh");
let next = handle(target + 15.0);
h.event(egui::Event::PointerMoved(next));
steps(&mut h, 2);
+2 -32
View File
@@ -5,7 +5,7 @@
//! setting an agent changes and the same setting changed here take one path. Settings the app keeps
//! outside the engine are written directly by [`OptionsModel::set`].
use craft::behavior::{EditEvent, MotionMode, keyed};
use craft::behavior::{MotionMode, keyed};
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Entry, Props as _, Show, ShowCollection, ShowContainer};
use craft::ui::display::{Elide, Shade, Text};
@@ -268,7 +268,6 @@ impl<'a> OptionsModel<'a> {
("proofing.ignoreInternet", Bool(prefs.ignore_internet)),
("proofing.checkSpelling", Bool(view.proofing)),
("proofing.markGrammar", Bool(prefs.mark_grammar)),
("proofing.customDictionaryFile", Text(String::new())),
],
"save" => vec![("save.removePersonalInfo", Bool(false)), ("save.removeDateTime", Bool(false))],
"language" => vec![("language.interface", Choice(crate::i18n::AUTO.to_string())), ("language.dictionariesFolder", Text(String::new()))],
@@ -427,14 +426,7 @@ impl PreferencesModel for OptionsModel<'_> {
b("proofing.markGrammar", tl!("Mark grammar errors as you type"), prefs.mark_grammar).enabled(app.session.view.proofing),
],
),
GroupSpec::new(
Some(tl!("Custom dictionary")),
vec![
RowSpec::new("proofing.customDictionaryFile", tl!("Dictionary file:"), RowKind::Custom)
.help(tl!("A custom-word dictionary file (.dic or plain text) used in conjunction with the main dictionary. Empty uses custom-dictionary.txt.")),
custom("proofing.customDictionary", tl!("Custom dictionary")),
],
),
GroupSpec::new(Some(tl!("Custom dictionary")), vec![custom("proofing.customDictionary", tl!("Custom dictionary"))]),
],
);
@@ -674,10 +666,6 @@ impl PreferencesModel for OptionsModel<'_> {
("save.removePersonalInfo", Bool(v)) => self.run("file.privacyOptions", json!({"removePersonalInfo": v})),
("save.removeDateTime", Bool(v)) => self.run("file.privacyOptions", json!({"removeDateTime": v})),
("language.interface", Choice(c)) => self.run("ui.language", json!({"value": c})),
("proofing.customDictionaryFile", Text(t)) => {
let t = t.trim();
self.options(json!({"customDictionary": if t.is_empty() { "auto" } else { t }}));
}
("language.dictionariesFolder", Text(t)) => {
let t = t.trim();
self.options(json!({"dictionariesFolder": if t.is_empty() { "auto" } else { t }}));
@@ -713,7 +701,6 @@ impl PreferencesModel for OptionsModel<'_> {
self.run("tools.autocorrect", json!({}));
}
}
"proofing.customDictionaryFile" => self.custom_dictionary_file(ui),
"proofing.customDictionary" => self.custom_dictionary(ui),
"language.proofingLanguage" => {
Text::new(self.strings.proofing_language.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
@@ -757,23 +744,6 @@ const CUSTOM_WORDS_SHOWN: u16 = 8;
struct NewWord(String);
impl OptionsModel<'_> {
/// The Dictionary file field. A text row reports every typed draft, and each would bind (and
/// later write to) whatever file the half-typed path names, so the path is committed only on
/// Enter or focus loss. The field is given the saved path and never writes it: the framework
/// holds the draft while an edit is open and drops it when the saved path changes (an agent's
/// `file.options`) or the page is left, so no edit open always shows the saved path.
fn custom_dictionary_file(&mut self, ui: &mut Ui) {
let saved = self.app.session.prefs.custom_dictionary.clone().unwrap_or_default();
let out = TextField::new(tl!("Dictionary file:"), Bind::given(saved)).limit(None).show(ui);
let committed = out.events.into_iter().find_map(|event| match event {
EditEvent::Commit { after, .. } => Some(after),
_ => None,
});
if let Some(path) = committed {
self.set("proofing.customDictionaryFile", PrefValue::Text(path));
}
}
/// The custom dictionary: the words Add to Dictionary kept, each with a Remove button, and a
/// field to add one.
fn custom_dictionary(&mut self, ui: &mut Ui) {
-182
View File
@@ -258,185 +258,3 @@ fn screen_paper_color_options_round_trip_and_work_without_a_document() {
with_model(&mut b, true, |m| m.set("general.paperColor", PrefValue::Choice("cream".into())));
assert_eq!(b.session.prefs.paper_color, PaperColor::Cream);
}
/// #5840: File › Options › Proofing has the Dictionary file setting.
#[test]
fn proofing_custom_dictionary_file_setting_is_visible() {
let mut a = app();
let found = with_model(&mut a, true, |m| {
m.pages().iter().flat_map(|p| p.groups.iter()).flat_map(|g| g.rows.iter()).any(|r| r.key == "proofing.customDictionaryFile")
});
assert!(found);
}
/// #5840: File › Options › Proofing sets, clears and validates the custom dictionary path.
#[test]
fn proofing_custom_dictionary_interaction() {
let dir = std::env::temp_dir().join(format!("wc-ui-dict-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let valid_path = dir.join("ui_custom.dic");
std::fs::write(&valid_path, "uiword\n").unwrap();
let valid_path_str = valid_path.to_string_lossy().into_owned();
let mut a = app();
// An invalid path is refused and not applied to the preferences.
with_model(&mut a, true, |m| m.set("proofing.customDictionaryFile", PrefValue::Text("/invalid/path/nonexistent.dic".into())));
assert_eq!(a.session.prefs.custom_dictionary, None, "invalid path was not applied to prefs");
let path = valid_path_str.clone();
with_model(&mut a, true, move |m| m.set("proofing.customDictionaryFile", PrefValue::Text(path)));
assert_eq!(a.session.prefs.custom_dictionary.as_deref(), Some(&valid_path_str[..]));
// Empty reverts to the default dictionary.
with_model(&mut a, true, |m| m.set("proofing.customDictionaryFile", PrefValue::Text(String::new())));
assert_eq!(a.session.prefs.custom_dictionary, None, "empty reverts custom dictionary to default");
let _ = std::fs::remove_dir_all(&dir);
}
/// #5840: a bound custom dictionary file is the source of truth. The saved word copy must not
/// be restored first, or words from a missing file would reach the default dictionary on the next
/// Add to Dictionary.
#[test]
fn a_bound_custom_dictionary_does_not_restore_saved_backup_words() {
let saved = Prefs {
dictionary: vec!["zqxbackupword".to_string()],
editing: wordcraft_engine::Prefs { custom_dictionary: Some("/nonexistent/custom.dic".to_string()), ..Default::default() },
..Default::default()
};
let mut a = app();
a.apply_prefs(saved);
assert!(!wordcraft_engine::proof::user_dictionary().contains(&"zqxbackupword".to_string()), "backup words stay out of memory");
assert_eq!(a.session.prefs.custom_dictionary.as_deref(), Some("/nonexistent/custom.dic"), "the file setting is kept");
}
/// #5840: the Dictionary file field commits the path on Enter, not on every keystroke. Typing
/// `notes.dic` passes through `notes`, a file that exists, which must not be bound on the way.
#[test]
fn typing_the_custom_dictionary_path_binds_it_only_on_enter() {
use egui_kittest::kittest::Queryable;
let dir = std::env::temp_dir().join(format!("wc-ui-dict-typing-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("notes"), "partway\n").unwrap();
let target = dir.join("notes.dic");
std::fs::write(&target, "uiword\n").unwrap();
let target_str = target.to_string_lossy().into_owned();
let mut a = app();
a.run("ui.backstage", json!({"value": true, "page": "options", "pane": "proofing"})).unwrap();
let mut h = crate::test_harness::builder().build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
options_frames(&mut h, 3);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").focus();
options_frames(&mut h, 2);
for c in target_str.chars() {
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").type_text(&c.to_string());
options_frames(&mut h, 2);
assert_eq!(h.state().session.prefs.custom_dictionary, None, "typing {c:?} bound a path");
}
h.key_press(egui::Key::Enter);
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(target_str.as_str()));
let _ = std::fs::remove_dir_all(&dir);
}
/// A harness over the real Options page, Proofing pane, with two dictionary files on disk.
fn dictionary_harness(tag: &str) -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf, String, String) {
let dir = std::env::temp_dir().join(format!("wc-ui-dict-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let one = dir.join("one.dic");
let two = dir.join("two.dic");
std::fs::write(&one, "oneword\n").unwrap();
std::fs::write(&two, "twoword\n").unwrap();
let mut a = app();
a.run("ui.backstage", json!({"value": true, "page": "options", "pane": "proofing"})).unwrap();
let mut h = crate::test_harness::builder().build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
options_frames(&mut h, 3);
(h, dir, one.to_string_lossy().into_owned(), two.to_string_lossy().into_owned())
}
fn dictionary_field_text(h: &egui_kittest::Harness<'static, WordApp>) -> String {
use egui_kittest::kittest::Queryable;
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").value().unwrap_or_default()
}
fn type_into_dictionary_field(h: &mut egui_kittest::Harness<'static, WordApp>, text: &str) {
use egui_kittest::kittest::Queryable;
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").focus();
options_frames(h, 2);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").type_text(text);
options_frames(h, 2);
}
/// #5899: a path typed but not committed yields to a saved path an agent sets meanwhile: the field
/// shows the agent's value (the framework ends the edit when the value changes outside it), and a
/// later Enter does not write the abandoned draft over it.
#[test]
fn an_outside_change_replaces_a_path_being_typed() {
let (mut h, dir, one, two) = dictionary_harness("outside");
type_into_dictionary_field(&mut h, &one);
assert_eq!(h.state().session.prefs.custom_dictionary, None, "typing binds nothing");
h.state_mut().run("file.options", json!({"customDictionary": two})).unwrap();
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(two.as_str()));
assert_eq!(dictionary_field_text(&h), two, "the field shows the agent's path");
h.key_press(egui::Key::Enter);
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(two.as_str()), "Enter did not overwrite it");
let _ = std::fs::remove_dir_all(&dir);
}
/// #5899: an uncommitted draft does not outlive its pane: back on Proofing the field shows the saved path.
#[test]
fn leaving_the_pane_drops_an_uncommitted_path() {
let (mut h, dir, one, two) = dictionary_harness("leave");
h.state_mut().run("file.options", json!({"customDictionary": two})).unwrap();
options_frames(&mut h, 3);
type_into_dictionary_field(&mut h, &one);
h.state_mut().run("ui.backstage", json!({"value": false})).unwrap();
options_frames(&mut h, 3);
h.state_mut().run("ui.backstage", json!({"value": true, "page": "options", "pane": "proofing"})).unwrap();
options_frames(&mut h, 3);
assert_eq!(dictionary_field_text(&h), two, "the field shows the saved path");
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(two.as_str()));
let _ = std::fs::remove_dir_all(&dir);
}
/// #5899: focus leaving the field commits the typed path.
#[test]
fn focus_loss_commits_the_custom_dictionary_path() {
use egui_kittest::kittest::Queryable;
let (mut h, dir, one, _two) = dictionary_harness("blur");
type_into_dictionary_field(&mut h, &one);
assert_eq!(h.state().session.prefs.custom_dictionary, None);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "New word").focus();
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(one.as_str()));
let _ = std::fs::remove_dir_all(&dir);
}
/// #5899: Escape abandons the typed path: nothing binds, and the field shows the saved path again.
#[test]
fn escape_does_not_commit_the_custom_dictionary_path() {
let (mut h, dir, one, _two) = dictionary_harness("escape");
type_into_dictionary_field(&mut h, &one);
h.key_press(egui::Key::Escape);
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary, None);
assert_eq!(dictionary_field_text(&h), "", "the field shows the saved (empty) path");
let _ = std::fs::remove_dir_all(&dir);
}
+2 -1
View File
@@ -18,6 +18,7 @@ use crate::{WordApp, system_clipboard};
pub(crate) const MAX_FILE_BYTES: u64 = 200 << 20;
/// Most picture files one paste inserts.
const MAX_FILES: usize = 20;
const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "wmf", "emf"];
/// PNG bytes for clipboard pixels, or why they can't be pasted. The platform read has checked the
/// size already.
@@ -30,7 +31,7 @@ pub fn png_from_rgba(width: usize, height: usize, rgba: Vec<u8>) -> Result<Vec<u
}
fn is_picture_file(path: &Path) -> bool {
path.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| crate::file_dialogs::PICTURES.iter().any(|x| x.eq_ignore_ascii_case(e)))
path.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| IMAGE_EXTS.iter().any(|x| x.eq_ignore_ascii_case(e)))
}
/// Pasted text that is only paths or `file://` addresses of picture files — what file managers
+7 -69
View File
@@ -144,24 +144,15 @@ pub(crate) const PAGES_PER_SHEET: [(&str, &str); 8] = [
("bookletReverse", "Booklet (right binding)"),
];
/// The settings that decide how tracked changes and comments look in the print preview:
/// Print Markup and Track Changes Options.
type MarkupKey = (bool, wordcraft_layout::display::MarkupOptions);
/// The [`MarkupKey`] now.
fn markup_key(app: &WordApp) -> MarkupKey {
(app.session.prefs.print_markup, app.session.prefs.markup.clone())
}
/// What the preview's layout is made from besides the document's text: the document id, the
/// revision, Print Markup and Track Changes Options, the file name and path FILENAME fields show
/// (#6282: Save As and Rename change them without an edit), and the font database generation the
/// app has seen (#6283: `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, u64, MarkupKey, (String, String), u64);
/// What the preview's layout is made from besides the document's text: the revision, Print
/// Markup, the file name and path FILENAME fields show (#6282: Save As and Rename change them
/// without an edit), and the font database generation the app has seen (#6283:
/// `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, bool, (String, String), u64);
/// The [`LayoutKey`] now.
fn layout_key(app: &WordApp) -> LayoutKey {
(app.session.document_id(), app.session.rev(), markup_key(app), app.session.resolved_filenames(), app.font_generation)
(app.session.rev(), app.session.prefs.print_markup, app.session.resolved_filenames(), app.font_generation)
}
/// The output layout, kept in `cache` while what it is made from ([`LayoutKey`]) is unchanged.
@@ -173,21 +164,11 @@ fn layout_of(app: &WordApp, cache: &mut Option<(LayoutKey, Arc<DocLayout>)>) ->
{
return l.clone();
}
let l = app.session.print_layout(app.session.prefs.print_markup);
let l = app.session.export_layout_with(app.session.prefs.print_markup);
*cache = Some((key, l.clone()));
l
}
/// How the preview draws a page: tracked changes marked as the print job marks them, headers and
/// footers at full strength (the preview is the printed page, not the editing view).
pub(super) fn preview_options(app: &WordApp) -> wordcraft_render::RenderOptions {
let mut opts = wordcraft_render::RenderOptions::default();
opts.display.markup = app.session.prefs.print_markup;
opts.display.revisions = app.session.prefs.markup.clone();
opts.display.dim_header = false;
opts
}
/// One choice list over `(id, label)` pairs, named `label`; true when the choice changed.
fn choice(ui: &mut Ui, label: &str, salt: &str, current: &mut String, items: &[(&str, &str)]) -> bool {
let mut changed = false;
@@ -603,47 +584,4 @@ mod tests {
let (sparse, dense) = (at(1.0), at(2.0));
assert!(sparse > 0 && dense > sparse * 2, "{dense} {sparse}");
}
/// The preview pages as the print job does (#5269 review): without Print Markup tracked
/// deletions take no space, whatever Track Changes Options mark them with.
#[test]
fn the_preview_pages_as_the_print_job() {
let text: Vec<String> = (0..200).map(|i| format!("Line {i} of the old text")).collect();
let doc = wordcraft_doc::Document::from_text(&text.join("\n"));
let mut app = crate::WordApp::new(wordcraft_engine::Session::new(doc), Default::default());
let mut cache = None;
app.run("review.trackChanges", json!({"value": true})).unwrap();
app.run("select.all", json!({})).unwrap();
app.run("text.insert", json!({"text": "Kept"})).unwrap();
// The preview is the printed page: headers and footers draw at full strength (#6267).
assert!(!preview_options(&app).display.dim_header);
let mut pages = |app: &crate::WordApp| (layout_of(app, &mut cache).pages.len(), app.session.print_pdf(&json!({})).unwrap().1.chosen);
app.run("file.printMarkup", json!({"value": true})).unwrap();
let (marked, job) = pages(&app);
assert!(marked > 1 && marked == job, "{marked} vs {job}");
app.run("file.printMarkup", json!({"value": false})).unwrap();
assert_eq!(pages(&app), (1, 1));
// The cached layout follows the Delete mark option too (it changes the layout with markup).
app.run("file.printMarkup", json!({"value": true})).unwrap();
app.run("review.trackingOptions", json!({"deleteMark": "hidden"})).unwrap();
assert_eq!(pages(&app), (1, 1));
// Changing revision colours refreshes the preview revision even on the same page count.
let rev_before = preview::inputs(&app);
app.run("review.trackingOptions", json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
let rev_after = preview::inputs(&app);
assert_ne!(rev_before, rev_after, "tracking colours refresh preview revision");
}
/// Two documents at the same revision drawn in one window's context (#5270 review): each
/// preview gets its own layout, not the other's cached one.
#[test]
fn the_preview_cache_tells_documents_apart() {
let long: Vec<String> = (0..200).map(|i| format!("Line {i}")).collect();
let app = |text: &str| crate::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text(text)), Default::default());
let (long, short) = (app(&long.join("\n")), app("One line"));
assert_eq!(long.session.rev(), short.session.rev(), "the test needs equal revisions");
let mut cache = None;
assert!(layout_of(&long, &mut cache).pages.len() > 1);
assert_eq!(layout_of(&short, &mut cache).pages.len(), 1);
}
}
+2 -2
View File
@@ -13,7 +13,7 @@ use craft::ui::primitives::textures::{Priority, Revision, TextureState, ThumbRen
use egui::{Color32, ColorImage, Ui};
use wordcraft_layout::DocLayout;
use super::{PrintPage, layout_key, preview_options};
use super::{PrintPage, layout_key};
use crate::WordApp;
/// The salt of the preview's thumbnail store.
@@ -68,7 +68,7 @@ impl ThumbSource<usize> for SheetSource<'_> {
}
let x0 = ((slot.x + (slot.width - pg.w * k) / 2.0) * scale).round() as i64;
let y0 = ((slot.y + (slot.height - pg.h * k) / 2.0) * scale).round() as i64;
let page = wordcraft_render::render_page(&self.app.session.doc, pg, page_scale, &preview_options(self.app));
let page = wordcraft_render::render_page(&self.app.session.doc, pg, page_scale, &Default::default());
let straight = page.to_straight();
let row_len = (page.width as usize).max(1) * 4;
for (row, line) in straight.chunks_exact(row_len).enumerate() {
+1 -1
View File
@@ -41,7 +41,7 @@ pub fn poll(app: &mut WordApp, ctx: &egui::Context) {
let current = if reads_shown_document(app) { app.session.read_aloud.current().map(|u| u.start) } else { None };
if current != app.read_aloud_at {
if let Some(start) = &current {
app.session.set_selection(wordcraft_engine::Selection::caret(app.session.doc.clamp(start)));
app.session.sel = wordcraft_engine::Selection::caret(app.session.doc.clamp(start));
app.session.goal_x = None;
app.canvas.scroll_to_caret = true;
}
+1 -1
View File
@@ -245,7 +245,7 @@ fn enforced_ui(app: &mut WordApp, ui: &mut Ui, st: &mut RestrictPane, mode: &str
if (regions > 0 || fields > 0) && Button::new(tl!("Find Next Editable Region")).show(ui).clicked() {
let from = app.session.sel.ordered().1;
if let Some((a, b)) = wordcraft_engine::cmd::protect::next_region(&app.session, &from) {
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: b });
app.session.sel = wordcraft_engine::Selection { anchor: a, focus: b };
app.canvas.focus_page(ui.ctx());
}
}
+3 -11
View File
@@ -1911,7 +1911,6 @@ fn window_close_save_as_that_fails_says_so_and_keeps_the_document() {
/// #1445: the prompt that comes back after a failed save shows the reason on screen.
#[test]
fn save_prompt_shows_why_the_save_failed() {
use egui_kittest::kittest::NodeT;
let dir = scratch("prompt-reason");
let blocker = dir.join("folder");
std::fs::write(&blocker, b"not a folder").unwrap();
@@ -1924,13 +1923,7 @@ fn save_prompt_shows_why_the_save_failed() {
h.run_steps(4);
// The prompt shows it, and so does the status line the failed save wrote it to (`prompt_message` above is the prompt's own).
assert!(h.query_all_by_label(reason.as_str()).next().is_some(), "the reason is in the prompt");
// The accepting button: the platform's word for Save (the framework asks Yes, No, Cancel off macOS). macOS also
// keeps a hidden, greyed Save in the title bar, so ask for the one on screen.
let accept = if cfg!(target_os = "macos") { "Save" } else { "Yes" };
let offered = h
.query_all_by_role_and_label(egui::accesskit::Role::Button, accept)
.any(|n| !n.accesskit_node().is_hidden() && !n.accesskit_node().is_disabled());
assert!(offered, "{accept} again is offered");
assert!(h.query_by_label("Save").is_some(), "Save again is offered");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -2019,9 +2012,8 @@ fn the_default_app_button_shows_only_with_the_hosts_hook() {
);
h.run_steps(4);
assert!(h.query_by_label("Show the community button in the title bar").is_some(), "hook {hook}: the Options page rendered");
// The row carries the label too (macOS shows it, with Finder's steps instead of a button): ask for the button.
let button = h.query_all_by_role_and_label(egui::accesskit::Role::Button, LABEL).next().is_some();
assert_eq!(button, hook, "hook {hook}: the button");
// The framework's button and the row that holds it can both carry the label.
assert_eq!(h.query_all_by_label(LABEL).next().is_some(), hook, "hook {hook}: the button");
if hook {
// The button itself, not the row that carries its label.
h.get_by_role_and_label(egui::accesskit::Role::Button, LABEL).click();
-5
View File
@@ -22,8 +22,6 @@ pub(crate) struct WindowUi {
pub(crate) restrict: crate::restrict_pane::RestrictPane,
pub(crate) spelling_review: Option<crate::proofing_pane::SpellingForm>,
pub(crate) status: Option<Status>,
/// Announcement belonging to this document window.
pub(crate) announcement: Option<crate::announce::Announcement>,
pub(crate) previews: previews::Previews,
pub(crate) change_picture_target: Option<String>,
pub(crate) recipient_list_pending: bool,
@@ -76,7 +74,6 @@ impl WindowUi {
restrict: Default::default(),
spelling_review: None,
status: None,
announcement: None,
previews: Default::default(),
change_picture_target: None,
recipient_list_pending: false,
@@ -187,7 +184,6 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
@@ -285,7 +281,6 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
+2 -4
View File
@@ -1,6 +1,6 @@
# Control protocol
> **Last updated:** 2026-11-20 · `wordcraft-cli mcp --connect` is refused for now (#7124); the token section describes the bridge for when it returns. Earlier: The control channel authenticates once per connection with a token (`auth`), replacing the per-request key. Earlier: Correct the force-close request envelope and document the optional command search parameter; command behavior unchanged. #6146: scroll speed preferences (`ui.scrollSpeed`, `ui.touchpadScrollSpeed`); #6159: refuse ui.screenshot on secondary document windows and support root window selection with view.switchWindows.
> **Last updated:** 2026-11-18 · The control channel authenticates once per connection with a token (`auth`), replacing the per-request key. Earlier: Correct the force-close request envelope and document the optional command search parameter; command behavior unchanged. #6146: scroll speed preferences (`ui.scrollSpeed`, `ui.touchpadScrollSpeed`); #6159: refuse ui.screenshot on secondary document windows and support root window selection with view.switchWindows.
Start the app with a control port: `wordcraft --control 7981` (or `WORDCRAFT_CONTROL_PORT=7981`).
A missing or invalid port after `--control` (not 1–65535) prints an error and exits with status 2.
@@ -52,9 +52,7 @@ exit.
sends. After that the connection may stay idle.
- At most 16 connections are served at once; the next one gets `connection limit reached`.
`wordcraft-cli mcp --connect` is refused for now, until the app confines this channel to automation
roots (#3695, #5819; see [docs/mcp.md](mcp.md)). When it returns, it takes the token from
`WORDCRAFT_CONTROL_TOKEN`, or else from the
`wordcraft-cli mcp --connect` takes the token from `WORDCRAFT_CONTROL_TOKEN`, or else from the
token file for the port it connects to, and reads it again on every new connection (the app may
have restarted). It sends the token only to the app's own address, `127.0.0.1` (`localhost`
connects there too, never to `::1`): another loopback address such as `::1` or `127.0.0.2` is not
File diff suppressed because one or more lines are too long
+2 -5
View File
File diff suppressed because one or more lines are too long
+11 -20
View File
@@ -1,26 +1,17 @@
# MCP server
> **Last updated:** 2026-11-20 · `wordcraft-cli mcp` starts only with both `--automation-read-root` and `--automation-write-root`, and `--connect` is refused until the desktop app confines its control channel (#7124, shared rule 18). Earlier: The bridge authenticates once per connection with the control token (`WORDCRAFT_CONTROL_TOKEN` or the app's token file). Earlier: The protocol core is the shared `craft-mcp-server` crate (#778); `click` and `key` list every argument they accept. Earlier: Keep the complete `type_text` description in one tool-table row; behavior wording unchanged. Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests.
> **Last updated:** 2026-11-18 · The bridge authenticates once per connection with the control token (`WORDCRAFT_CONTROL_TOKEN` or the app's token file). Earlier: The protocol core is the shared `craft-mcp-server` crate (#778); `click` and `key` list every argument they accept. Earlier: Keep the complete `type_text` description in one tool-table row; behavior wording unchanged. Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests.
WordCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) over stdio, so
Claude and other agents can write and edit documents.
```sh
wordcraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project/out
wordcraft-cli mcp # headless session (no window)
wordcraft --control 7981 & # or: drive the running app…
wordcraft-cli mcp --connect 127.0.0.1:7981 # …including clicks, keys and screenshots
```
Claude Code: `claude mcp add wordcraft -- wordcraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project/out`.
The server runs a headless session (no window) and starts only with both roots: see
[Confining file access](#confining-file-access). Without them it stops with an error naming the
two flags (shared rule 18, #7124).
**`--connect` is refused for now.** `wordcraft-cli mcp --connect HOST:PORT` bridged an agent to the
running app (`wordcraft --control 7981`), with clicks, keys and screenshots. The app doesn't
confine its control channel to automation roots yet, so the bridge would give the agent every file
the user can reach; it stops with an error pointing to #3695 and #5819. Once the app confines the
channel, connected mode will be allowed when the app has both roots set. The rest of this page
describes the connected mode as it will work then.
Claude Code: `claude mcp add wordcraft -- wordcraft-cli mcp`.
With `--connect`, the bridge authenticates once per connection with the app's control token, which
it reads from `WORDCRAFT_CONTROL_TOKEN` or from the token file the app writes at start. It sends
@@ -84,7 +75,7 @@ status 1, and nothing is saved. Every output is checked (known extension, folder
Tracked changes and comments are recorded under the session's user name ("WordCraft User" by
default). Name the agent so reviewers can tell its edits from people's: start the headless server
with `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR --author "Claude (copyedit)"`, or run
with `wordcraft-cli mcp --author "Claude (copyedit)"`, or run
`file.setAuthor {"name": "Claude (copyedit)"}`. Turn tracking on explicitly with
`review.trackChanges {"value": true}`; without `value` it toggles, which turns tracking *off* in
a document that was saved with it on. `wordcraft-cli run` takes `--author` too.
@@ -120,8 +111,8 @@ config works across the suite) keep the agent to the folders you give it:
the name it is given, so that name must be inside the write root as well as what it leads to:
a link outside the root pointing in is refused (#3735).
- Read and write access are separate. Give the same folder twice for both; a root left out grants
none of its access at the engine level. `wordcraft-cli mcp` needs both flags and refuses to start
with one or neither.
none of its access (with only `--automation-read-root`, nothing can be written to disk). Without
either flag nothing changes.
- A path is made absolute against the server's working directory, then its links are followed: a
file (or folder) link that leads out of a root is outside it. For a file that doesn't exist yet,
its nearest existing folder's links are followed and the rest must be plain names, so `..` below a
@@ -135,9 +126,9 @@ config works across the suite) keep the agent to the folders you give it:
- The roots must be existing folders; a missing one stops the server with an error. Each flag is
given once (`--flag <dir>` or `--flag=<dir>`).
The flags confine the headless server. WordCraft's desktop app has no equivalent flags yet, so a
running app (`wordcraft --control`) is not confined, and `--connect` is refused, with the flags or
without (#3695, #5819).
The flags confine the headless server; `--connect` with them is an error, since the server would
otherwise talk to an app that isn't confined. WordCraft's desktop app has no equivalent flags yet,
so a running app (`wordcraft --control`) is not confined.
What the roots do not cover: commands that take no path (`text.insert`, `execute` of anything that
works on the open document) can still read and change that document, and `get_text` and
+1 -16
View File
@@ -1,6 +1,6 @@
# Installing languages and spelling dictionaries
> **Last reviewed:** 2026-10-16 · **Last updated:** 2026-11-20 · **Change:** trivial (The Dictionary file field in File › Options › Proofing shows the saved path whenever no edit is open: a path typed but not committed is dropped when the saved path changes or the pane is left, #5899); previously trivial (Freestanding custom dictionary file support in File › Options › Proofing, supporting plain UTF-8 and Word CUSTOM.DIC UTF-16LE with BOM; other encodings are refused without touching the file, #5840); previously trivial (Language packs are installed from Your languages and Add a language…; the Dictionaries folder is in Options › Language); previously trivial (Language packs: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (Language packs: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); Mongolian and Thai aren't packs yet); previously trivial (Language packs: the first set, language-packs-1, is published and pinned: 61 languages, and which aren't packs yet); previously minor (Language packs: install a language's spelling and hyphenation from File › Options › Language, or from the bar a document in that language shows; they are searched after the dictionaries folder and before the system's dictionaries; previously trivial: the Flatpak's own dictionaries folder; previously trivial: WordCraft's own dictionaries folder is searched on macOS and Linux too, as on Windows, so a dictionary dropped there works without a setting; previously minor: ISO 8859-9 Turkish dictionaries are read, #3692; previously minor: Spanish: `es_ES`, `es_MX`, `es_419` and `es_UY` with their fallbacks, #3360, #3553; previously trivial: every Hunspell language shows (no dictionary), not only Polish and Portuguese, and Indonesian is listed, #3150; previously trivial: ISO 8859-1 dictionaries are read, #2824)
> **Last reviewed:** 2026-10-16 · **Last updated:** 2026-11-03 · **Change:** trivial (Language packs are installed from Your languages and Add a language…; the Dictionaries folder is in Options › Language); previously trivial (Language packs: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (Language packs: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); Mongolian and Thai aren't packs yet); previously trivial (Language packs: the first set, language-packs-1, is published and pinned: 61 languages, and which aren't packs yet); previously minor (Language packs: install a language's spelling and hyphenation from File › Options › Language, or from the bar a document in that language shows; they are searched after the dictionaries folder and before the system's dictionaries; previously trivial: the Flatpak's own dictionaries folder; previously trivial: WordCraft's own dictionaries folder is searched on macOS and Linux too, as on Windows, so a dictionary dropped there works without a setting; previously minor: ISO 8859-9 Turkish dictionaries are read, #3692; previously minor: Spanish: `es_ES`, `es_MX`, `es_419` and `es_UY` with their fallbacks, #3360, #3553; previously trivial: every Hunspell language shows (no dictionary), not only Polish and Portuguese, and Indonesian is listed, #3150; previously trivial: ISO 8859-1 dictionaries are read, #2824)
English spelling works out of the box. Polish, Russian, Portuguese, Czech, Italian, Croatian,
Turkish, Indonesian and Spanish spelling use a standard **Hunspell** dictionary (an `.aff` and a `.dic` file) that
@@ -172,19 +172,6 @@ Other languages work the same way: replace `pt_BR` with the language's folder an
from the LibreOffice repository (for example `it_IT/it_IT.aff`; the Spanish ones are all in
`es/`, for example `es/es_MX.aff`).
## Custom word dictionary (custom.dic)
Words added via **Add to Dictionary** or through `review.addToDictionary` are kept in a custom dictionary.
By default, WordCraft saves them to `custom-dictionary.txt` in the settings folder.
To use an existing freestanding custom dictionary (such as Microsoft Word's `CUSTOM.DIC`):
1. Open **File › Options › Proofing**.
2. Under **Custom dictionary**, set **Dictionary file** to the path of your `.dic` or text file and press **Enter** (or click out of the field). The path is saved then, not while you type. Absolute paths or `~/` paths (expanded via `HOME` or `USERPROFILE`) are supported.
3. Words in that dictionary are checked in conjunction with the main dictionary, and new additions persist back to the file. Switching dictionaries clears previously loaded custom words from memory and loads the words from the newly selected file.
4. Emptying the field and pressing **Enter** (or setting `"customDictionary": "auto"`) means automatic: it reverts to the default settings folder, reloading the words from `custom-dictionary.txt`.
WordCraft supports plain UTF-8 word lists as well as UTF-16LE with BOM (`[0xFF, 0xFE]`), UTF-16BE with BOM (`[0xFE, 0xFF]`), and UTF-8 with BOM, preserving the file's original encoding when saving additions or removals. Lines that do not conform to valid single words (such as comments or malformed entries) are ignored during spellchecking, but existing lines are preserved verbatim when saving back so that custom dictionaries shared with Word retain non-word lines, comments, and original casing. Files in another encoding (for example Windows-1252/ANSI) are refused with an error and left untouched rather than guessed: convert such a file to UTF-8 once and select it again. The chosen file must also be a regular, writable file within the automation roots; symbolic links and read-only files are refused. If a save is refused at run time, the new word stays in the in-memory dictionary for the session and the reason is written to the log, so Add to Dictionary never fails or loses the word mid-session.
## Checking that it works
- Restart WordCraft. The status bar no longer says **(no dictionary)**, and a misspelled word
@@ -206,8 +193,6 @@ Never commit dictionary files to this repository: they stay on the user's system
| Date | Change | Summary |
|---|---|---|
| 2026-11-20 | trivial | The Dictionary file field shows the saved path whenever no edit is open: a typed path that was not committed does not survive a change to the saved path (an agent's `file.options`) or leaving the pane, and Enter does not overwrite the new value (#5899) |
| 2026-11-07 | trivial | Freestanding custom dictionary file support in File › Options › Proofing, supporting plain UTF-8 and Word CUSTOM.DIC UTF-16LE with BOM; other encodings are refused without touching the file (#5840) |
| 2026-11-03 | trivial | Language packs (CP4.3): the missing-pack bar offers a language before the list is fetched and gets the list, then the pack, on Install; a missing or stale list is fetched once while downloading is on; the caret's typing language counts |
| 2026-11-03 | trivial | Language packs: install from Your languages or Add a language… in Options › Language; the Dictionaries folder is in Options › Language, not Proofing |
| 2026-11-03 | trivial | Language packs: language-packs-2 is published and pinned (75 languages, adding the compounding languages); Mongolian and Thai aren't packs yet, and why |
+2 -3
View File
@@ -1,6 +1,6 @@
# WordCraft parity with Microsoft Word
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** trivial (Proofing: freestanding custom dictionary file support, #5840; previously trivial: Equations: `\int` + Space leaves ∫ waiting for its limits, `_a^b` then Space builds them, and the operand typed next goes inside, observed in Word for Windows on #4938, #4917; no percentage change; previously trivial: Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Tables row: tables nest 18 deep at most, so a .json save reads back, #3618); previously trivial (Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** trivial (Equations: `\int` + Space leaves ∫ waiting for its limits, `_a^b` then Space builds them, and the operand typed next goes inside, observed in Word for Windows on #4938, #4917; no percentage change; previously trivial: Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Tables row: tables nest 18 deep at most, so a .json save reads back, #3618); previously trivial (Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
The authoritative assessment of how close WordCraft is to Microsoft Word. [`ROADMAP.md`](../ROADMAP.md)
summarizes it; [`gaps.md`](gaps.md) itemizes every shortfall; the deep checklists are
@@ -68,7 +68,7 @@ full parity for the area.
| Footnotes and endnotes | 3 | 60% | 60% | 3–5 | Placed and editable, numbers from Word files (#103); long notes continue onto the next page under the continuation separator (#352). Footnote and Endnote dialog with options per section: below text, end of section, number format, start at, restart each section or page, custom mark, convert (#385). |
| References (TOC, citations, bibliography, captions, index, TOA) | 5 | 65% | 60% | 12–20 | Working first versions, Zotero integration (#189), Zotero/Mendeley `ADDIN` fields round-trip. Caption, Index, Mark Entry, Custom TOC, Table of Figures and Create/Edit Source dialogs; updates honour the TOC (`\o \u \t \f \n \p \h`), table of figures (`\c \a \n \p`, any caption label, so a list of tables sits beside a list of figures; #3013), INDEX (`\c \e \h \r`), XE (`\b \i \t \r`) and SEQ/STYLEREF chapter switches (#402); Insert Caption… on the right-click menu of pictures, shapes, text boxes and charts (#1230). All 12 of Word's bibliography styles (APA, MLA, Chicago, IEEE, Harvard, ISO 690 author-date and numerical, Turabian, GB/T 7714, GOST name and title sort, SIST02; #383); bibliography sources saved in DOCX (#790). Manage Sources imports Word's bibliography file (`b:Sources`, `Sources.xml`, #2640). |
| Review (proofing UI, comments, track changes, compare, protect) | 8 | 72% | 75% | 15–25 | Comment balloons, tracked insert/delete incl. paragraph marks (#244, #125), Compare / Combine with comparison settings (case, white space, formatting, tables, word or character level, #412), Restrict Editing pane with formatting and editing restrictions, exceptions for everyone and a password (#412). Formatting revisions (#41): kept in DOCX, recorded while tracking, accepted/rejected, "Formatted: …" balloons and change bars. Moves (#400): kept in DOCX, recorded on a tracked cut and paste, accepted/rejected at either end, green markup and "Moved from/to" balloons. Show revisions in balloons takes tracked deletions in the body out of the text into "Deleted: …" balloons (insertions stay inline, as in Word; deletions in headers, footers, notes and text boxes, and in print and PDF, stay inline). Missing: drag-and-drop moves, insert/delete balloons, Translate, Block Authors, modern comment threads/mentions. Lowered: these gaps are confirmed by source (no `rPrChange` anywhere). |
| Proofing (spelling, grammar, thesaurus, languages) | 5 | 44% | (in Review) | 20–40 | English, Polish, Portuguese, Italian and Czech (system Hunspell, #1048), chosen per run from its language (`w:lang`): English word list (Moby plus our supplement of modern words such as "desktop", #520) and rule-based grammar; Polish against the installed Hunspell dictionary through a Hunspell-style affix engine, Polish grammar rules and TeX hyphenation patterns (2026-10-10); Portuguese (pt-BR) against the installed VERO Hunspell dictionary — the affix engine reads its `FLAG UTF-8` flags, continuation classes and forbidden spellings — with accent-first suggestions, conservative grammar rules and TeX patterns (2026-10-12); Italian (it-IT) against the installed Hunspell dictionary through the same affix engine, with accent-first suggestions and conservative grammar rules. Other languages are left unmarked. The custom dictionary persists across sessions (#40), and freestanding custom dictionary files (such as Microsoft Word's CUSTOM.DIC in UTF-16LE with BOM) can be selected in File › Options › Proofing (#5840). Word ships 120 proofing tools for ~50 languages plus Editor (style refinements, similarity). Issues #25, #40, #100. |
| Proofing (spelling, grammar, thesaurus, languages) | 5 | 44% | (in Review) | 20–40 | English, Polish, Portuguese, Italian and Czech (system Hunspell, #1048), chosen per run from its language (`w:lang`): English word list (Moby plus our supplement of modern words such as "desktop", #520) and rule-based grammar; Polish against the installed Hunspell dictionary through a Hunspell-style affix engine, Polish grammar rules and TeX hyphenation patterns (2026-10-10); Portuguese (pt-BR) against the installed VERO Hunspell dictionary — the affix engine reads its `FLAG UTF-8` flags, continuation classes and forbidden spellings — with accent-first suggestions, conservative grammar rules and TeX patterns (2026-10-12); Italian (it-IT) against the installed Hunspell dictionary through the same affix engine, with accent-first suggestions and conservative grammar rules. Other languages are left unmarked. The custom dictionary persists across sessions (#40). Word ships 120 proofing tools for ~50 languages plus Editor (style refinements, similarity). Issues #25, #40, #100. |
| Mailings | 2 | 70% | 70% | 6–10 | Mail merge from CSV, fields, rules (IF, SKIPIF, NEXT, NEXTIF, evaluated alike in preview and merge), fields in headers/footers (one section per letter), preview, envelopes, labels. Select Recipients takes a typed list or CSV (#247); no Excel/Outlook/Contacts data sources, no email merge. |
| Pictures, shapes, text boxes, WordArt | 6 | 60% | 60% | 20–30 | Insert, crop, recolour, styles, floating placement like Word (#136), wrap (square/top-bottom/behind/front), text boxes edit and overflow (#46), VML text boxes (#242), free rotation and flips with a rotation handle (#332), WordArt: text fill (solid, gradient, none), outline, shadow, glow and reflection with our own styles, and Transform warps along arch, circle, wave, slant, inflate/deflate, chevron and triangle (other presets kept and drawn flat), connectors (straight, elbow, curved, arrowheads) glued to shapes' connection sites and re-routed when those move (#416). Missing: tight/through contour wrap, rotated text-box text, group (#267 open), shape effects, WordArt 3-D/bevel and editing text in its bent form, connector routing around shapes, Drawing Canvas, Icons, online pictures, screenshot. |
| Mailings | 2 | 70% | 70% | 6–10 | Mail merge from CSV, fields, rules (IF, SKIPIF, NEXT, NEXTIF, evaluated alike in preview and merge), fields in headers/footers (one section per letter), preview, envelopes, labels. Select Recipients takes a typed list, CSV (#247) or a sheet of an Excel (.xlsx/.xlsm) or OpenDocument (.ods) workbook, with Select Table to pick the sheet (#334); no Outlook/Contacts/Access data sources, no email merge. |
@@ -324,4 +324,3 @@ can be used without committing Word output.
| 2026-10-10 | major | Created from ROADMAP.md's "Parity by area" and "Estimate to 100%" sections; full re-measure against Word for Mac 16.113.4 (bundle listing, catalog diff from source, issue tracker); split into feature depth (67%) and ready for real work (60%); added proofing, East Asian, accessibility areas and the dimension table; hours re-calibrated from PR history |
| 2026-10-06 | major | First estimate in ROADMAP.md: ~62% real feature parity, 120–150 h to 100% |
| 2026-10-29 | trivial | Tables row: Table Properties' row, column and cell settings apply to the selection, as in Word (#4857); no percentage change |
| 2026-11-07 | trivial | Proofing: freestanding custom dictionary file support (plain UTF-8 and Word CUSTOM.DIC UTF-16LE with BOM) in File › Options › Proofing (#5840); no percentage change |
File diff suppressed because one or more lines are too long
+2 -5
View File
File diff suppressed because one or more lines are too long