mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-06 12:47:00 -06:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0eda97fe8c | ||
|
|
f9ff36d67c |
@@ -21,6 +21,4 @@ jobs:
|
||||
with:
|
||||
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
|
||||
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
secrets:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
SONAR_CLOUD_PAT: ${{ secrets.SONAR_CLOUD_PAT }}
|
||||
secrets: inherit
|
||||
|
||||
@@ -73,7 +73,7 @@ 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: plain `wordcraft-cli mcp` reaches the open window while ArtCraft Launcher › Settings › AI agents is on (`crates/ui-egui/src/agents.rs`, `crates/mcp/src/live.rs`); `--headless`, or the switch off, needs `--automation-read-root DIR --automation-write-root DIR`; 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 --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`.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
|
||||
- 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`.
|
||||
|
||||
Generated
-26
@@ -1211,16 +1211,6 @@ dependencies = [
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ai-agents"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72"
|
||||
dependencies = [
|
||||
"dirs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
@@ -1362,13 +1352,8 @@ name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-control-protocol",
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1493,16 +1478,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
@@ -9371,7 +9346,6 @@ dependencies = [
|
||||
"craft",
|
||||
"craft-mcp-server",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wordcraft-control-key",
|
||||
"wordcraft-doc",
|
||||
|
||||
@@ -205,17 +205,13 @@ 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.
|
||||
|
||||
With ArtCraft Launcher › Settings › AI agents on, AI apps reach the open WordCraft window through
|
||||
the launcher's one `ArtCraft` entry: tool calls act in the window, and files go to the agent folder
|
||||
(`Documents/ArtCraft/Agents/WordCraft`, or the folders in File › Options › Agents). Without the
|
||||
launcher:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
A headless server needs both roots.
|
||||
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
|
||||
|
||||
File diff suppressed because one or more lines are too long
+44
-191
@@ -54,25 +54,16 @@ USAGE:
|
||||
wordcraft-cli commands [--json] list every command
|
||||
wordcraft-cli parity [--markdown] feature-catalog parity
|
||||
wordcraft-cli validate <file> [--json] structural integrity check (exit 0 pass, 1 fail, 2 incomplete, 3 usage/IO)
|
||||
wordcraft-cli mcp [--automation-read-root DIR --automation-write-root DIR] [--headless]
|
||||
[--when-closed launch|headless|error] [--author NAME]
|
||||
MCP server on stdio. While AI agents are on in
|
||||
ArtCraft Launcher › Settings › AI agents, each tool
|
||||
call goes to the open WordCraft window, working in
|
||||
its agent folder (File › Options › Agents); while
|
||||
WordCraft is closed, --when-closed or that page's
|
||||
choice decides: open it, work without a window, or
|
||||
ask to open it. Otherwise, and with --headless, a
|
||||
headless session, which needs both roots: 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. Given with AI agents
|
||||
on, the roots replace the agent folder for headless
|
||||
work. --author names the author of a headless
|
||||
session's tracked changes and comments.
|
||||
--connect HOST:PORT is deprecated and ignored.
|
||||
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 zotero <command> <file> [--cmd 'id={json}' …] [--save OUT] [--trace] [--port P]
|
||||
run a Zotero command on a document (Zotero must be
|
||||
running): addEditCitation, addEditBibliography,
|
||||
@@ -270,17 +261,6 @@ fn find_option_arg<'a>(args: &'a [String], name: &str) -> OptionArg<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp --author NAME`: absent is the default author; a flag without a name, or given twice, is a
|
||||
/// usage error, never an unnamed session or the next option taken as the name.
|
||||
fn mcp_author(args: &[String]) -> Result<Option<String>, String> {
|
||||
match find_option_arg(args, "--author") {
|
||||
OptionArg::Absent => Ok(None),
|
||||
OptionArg::Duplicate => Err("mcp: duplicate --author option".into()),
|
||||
OptionArg::MissingValue => Err("mcp: --author requires a name".into()),
|
||||
OptionArg::Value(name) => Ok(Some(name.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_page_arg(command: &str, args: &[String]) -> Result<Option<u64>, String> {
|
||||
match find_option_arg(args, "--page") {
|
||||
OptionArg::Absent => Ok(None),
|
||||
@@ -396,86 +376,13 @@ const VALIDATE_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_val
|
||||
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` won't start while the suite's AI-MCP flag is on but the launcher's switch keeps agents
|
||||
/// out of the window: without roots it would have no folders to work in.
|
||||
const MCP_NEEDS_ROOTS_OR_AGENTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR, or \
|
||||
turn on AI agents in ArtCraft Launcher › Settings › AI agents to work in WordCraft's open window and its agent folder";
|
||||
/// 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";
|
||||
|
||||
/// `--connect HOST:PORT`, from before plain `mcp` found the window by itself: kept for one release,
|
||||
/// ignored with this note on stderr, then removed.
|
||||
const MCP_CONNECT_DEPRECATED: &str = "wordcraft-cli: --connect is deprecated and will be removed in the next release: \
|
||||
plain `wordcraft-cli mcp` finds the open WordCraft window by itself while AI agents are on in ArtCraft Launcher › \
|
||||
Settings › AI agents. The address given is not used.";
|
||||
|
||||
const MCP_OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec { name: "--headless", takes_value: false },
|
||||
OptionSpec { name: "--when-closed", takes_value: true },
|
||||
OptionSpec { name: "--author", takes_value: true },
|
||||
];
|
||||
|
||||
/// Takes the deprecated `--connect` out of `args`, with its value (written apart, unless it is
|
||||
/// another option, or as `--connect=…`): whether it was there.
|
||||
fn take_connect(args: &mut Vec<String>) -> bool {
|
||||
let mut found = false;
|
||||
let mut i = 0;
|
||||
while let Some(arg) = args.get(i) {
|
||||
if arg == "--connect" {
|
||||
found = true;
|
||||
let with_value = args.get(i + 1).is_some_and(|v| !v.starts_with("--"));
|
||||
args.drain(i..if with_value { i + 2 } else { i + 1 });
|
||||
} else if arg.starts_with("--connect=") {
|
||||
found = true;
|
||||
args.remove(i);
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The suite's AI-MCP flag and whether the ArtCraft Launcher's switch lets agents use WordCraft.
|
||||
#[cfg(not(test))]
|
||||
fn agents_state() -> (bool, bool) {
|
||||
let flag = wordcraft_mcp::live::mcp_flag();
|
||||
(flag, flag && wordcraft_mcp::live::agents_allowed_now())
|
||||
}
|
||||
|
||||
/// Unit tests run `mcp` as without the suite's flag, whatever this machine's flags say; the plan
|
||||
/// itself is tested for every combination (`mcp_plan`), and the binary's tests set the flag.
|
||||
#[cfg(test)]
|
||||
fn agents_state() -> (bool, bool) {
|
||||
(false, false)
|
||||
}
|
||||
|
||||
/// How `mcp` runs.
|
||||
#[derive(Debug)]
|
||||
enum McpPlan {
|
||||
/// A headless session confined to both roots.
|
||||
Headless(std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>),
|
||||
/// The open window while agents may use it, otherwise a headless session in the given roots
|
||||
/// or the app's agent folder ([`wordcraft_mcp::Live`]).
|
||||
Live(Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>),
|
||||
}
|
||||
|
||||
/// `mcp`'s plan. With `--headless`, or without the suite's AI-MCP flag (`flag`), a headless session
|
||||
/// that needs both roots (shared rule 18). With the flag, the live client when the launcher's
|
||||
/// switch lets agents in (`switch`) or both roots are given, so nothing it does is unconfined;
|
||||
/// otherwise a refusal.
|
||||
fn mcp_plan(
|
||||
roots: Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>,
|
||||
headless: bool,
|
||||
flag: bool,
|
||||
switch: bool,
|
||||
) -> Result<McpPlan, &'static str> {
|
||||
let both = roots.clone().filter(|r| r.read_root().is_some() && r.write_root().is_some());
|
||||
if headless || !flag {
|
||||
return both.map(McpPlan::Headless).ok_or(MCP_NEEDS_ROOTS);
|
||||
}
|
||||
if switch || both.is_some() {
|
||||
return Ok(McpPlan::Live(roots));
|
||||
}
|
||||
Err(MCP_NEEDS_ROOTS_OR_AGENTS)
|
||||
}
|
||||
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 },
|
||||
OptionSpec { name: "--save", takes_value: true },
|
||||
@@ -610,10 +517,8 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
|
||||
let markup = rest.iter().any(|a| a == "--markup");
|
||||
let strict = rest.iter().any(|a| a == "--strict");
|
||||
// Before the input is opened: a wrong output type is a usage error, not a file error.
|
||||
let lower_output = o.to_ascii_lowercase();
|
||||
let to_png = lower_output.ends_with(".png");
|
||||
let rendered = to_png || lower_output.ends_with(".pdf");
|
||||
if strict && !rendered {
|
||||
let to_png = o.to_ascii_lowercase().ends_with(".png");
|
||||
if strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
|
||||
return Err("convert: --strict needs a .pdf or .png output".into());
|
||||
}
|
||||
let password = password_from(rest)?;
|
||||
@@ -633,12 +538,8 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
|
||||
if let Err(e) = r {
|
||||
return Err(if strict { refusal(&mut s, e, markup, to_png.then_some(1)) } else { engine_error(e) });
|
||||
}
|
||||
// A refusal already returned its report. Word, text and other non-rendered copies need no layout.
|
||||
if rendered {
|
||||
report_missing_metric_fonts(&s, markup, to_png);
|
||||
}
|
||||
// The confirmation is a result, so it goes to stdout with the others (#7070).
|
||||
write_stdout(|w| writeln!(w, "wrote {o}"))
|
||||
eprintln!("wrote {o}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_run_script(rest: &[String], script_path: Option<&Path>) -> Result<Option<script::Script>, Failure> {
|
||||
@@ -662,17 +563,6 @@ fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option
|
||||
(from_file, from_template)
|
||||
}
|
||||
|
||||
fn report_missing_metric_fonts(s: &Session, markup: bool, to_png: bool) {
|
||||
for (word, used) in wordcraft_engine::cmd::font::output_metric_font_notices(s, markup, to_png) {
|
||||
let used = escape_peer(&used);
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"note: {word} is drawn in {used}, which measures differently, so lines and pages may not match Word's; uncovered characters may use glyph fallback"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show a successful command's result, or its warning when results aren't printed.
|
||||
fn report_run_result(id: &str, result: &Value, print: bool) -> Result<(), Failure> {
|
||||
if print {
|
||||
@@ -834,11 +724,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
s.run("file.save", &json!({"path": out}))
|
||||
};
|
||||
r.map_err(engine_error)?;
|
||||
// A reader that hung up only loses the confirmation; the remaining saves still run.
|
||||
match write_stdout(|w| writeln!(w, "wrote {out}")) {
|
||||
Ok(()) | Err(Failure::StdoutClosed) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
eprintln!("wrote {out}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -868,7 +754,28 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
"validate" => run_validate(file.as_deref(), &rest),
|
||||
"mcp" => run_mcp(&rest),
|
||||
"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());
|
||||
};
|
||||
// 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.
|
||||
Ok(server.serve(stdin.lock(), std::io::stdout())?)
|
||||
}
|
||||
"zotero" => {
|
||||
validate_options("zotero", &rest, ZOTERO_OPTIONS)?;
|
||||
let paths = positionals(&rest, ZOTERO_OPTIONS);
|
||||
@@ -908,7 +815,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
eprintln!("{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
|
||||
if let Some(o) = arg_value(&rest, "--save") {
|
||||
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
|
||||
write_stdout(|w| writeln!(w, "wrote {o}"))?;
|
||||
eprintln!("wrote {o}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -918,60 +825,6 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `wordcraft-cli mcp`: serves MCP on stdin and stdout, headless or through the open window.
|
||||
fn run_mcp(rest: &[String]) -> Result<(), Failure> {
|
||||
let (roots, mut rest) = automation_roots("mcp", rest)?;
|
||||
// Taken out before the option check, with or without a value, so it never reads as unknown.
|
||||
if take_connect(&mut rest) {
|
||||
eprintln!("{MCP_CONNECT_DEPRECATED}");
|
||||
}
|
||||
validate_options("mcp", &rest, MCP_OPTIONS)?;
|
||||
let when_closed = match (rest.iter().any(|a| a == "--when-closed"), arg_value(&rest, "--when-closed")) {
|
||||
(false, _) => None,
|
||||
(true, value) => {
|
||||
Some(value.as_deref().and_then(wordcraft_mcp::live::WhenAppClosed::parse).ok_or("mcp: --when-closed takes launch, headless or error")?)
|
||||
}
|
||||
};
|
||||
let author = mcp_author(&rest)?;
|
||||
let (flag, switch) = agents_state();
|
||||
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = match mcp_plan(roots, rest.iter().any(|a| a == "--headless"), flag, switch)? {
|
||||
McpPlan::Headless(roots) => {
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined. Every thread of this process,
|
||||
// not only the server's: nothing reaches past the roots.
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
Box::new(headless_mcp(roots, author.as_deref())?)
|
||||
}
|
||||
McpPlan::Live(roots) => {
|
||||
let mut config = wordcraft_mcp::LiveConfig::installed()
|
||||
.ok_or("mcp: can't find WordCraft's settings folder (no home folder; set WORDCRAFT_PROFILE_DIR)")?;
|
||||
if let Some(roots) = &roots {
|
||||
config.read_root = roots.read_root().map(std::path::Path::to_path_buf);
|
||||
config.write_root = roots.write_root().map(std::path::Path::to_path_buf);
|
||||
// Both roots given: every headless session works in them, so the whole process is confined to
|
||||
// them. Calls to the window run in the app, inside its agent folders.
|
||||
if config.read_root.is_some() && config.write_root.is_some() {
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
}
|
||||
}
|
||||
config.when_closed = when_closed;
|
||||
config.author = author;
|
||||
config.launch = std::env::current_exe().ok().and_then(|exe| wordcraft_mcp::live::launcher(&exe));
|
||||
eprintln!(
|
||||
"wordcraft-cli: tool calls go to the open WordCraft window while AI agents are on in ArtCraft Launcher, otherwise to a headless session (read root {}, write root {}; none: WordCraft's agent folder)",
|
||||
show(config.read_root.as_deref()),
|
||||
show(config.write_root.as_deref())
|
||||
);
|
||||
Box::new(wordcraft_mcp::Live::new(config))
|
||||
}
|
||||
};
|
||||
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.
|
||||
Ok(server.serve(stdin.lock(), std::io::stdout())?)
|
||||
}
|
||||
|
||||
/// At most 400 characters of `s`, for traces.
|
||||
fn clip(s: &str) -> String {
|
||||
match s.char_indices().nth(400) {
|
||||
|
||||
@@ -38,7 +38,7 @@ fn validators_accept_only_the_documented_options() {
|
||||
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
|
||||
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--headless", "--when-closed", "launch"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(
|
||||
validate_options(
|
||||
@@ -326,32 +326,18 @@ fn every_agent_entry_point_refuses_to_start_without_both_roots() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp`'s plan never runs anything unconfined (shared rule 18): headless needs both roots, and
|
||||
/// with the suite's AI-MCP flag the live client runs without them only while the launcher's switch
|
||||
/// lets agents into the window, which confines them to its agent folder.
|
||||
/// 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_never_plans_an_unconfined_session() {
|
||||
let scratch = Scratch::new("mcp-plan");
|
||||
let root = |read: bool, write: bool| {
|
||||
let (r, w) = (read.then_some(scratch.0.as_path()), write.then_some(scratch.0.as_path()));
|
||||
wordcraft_engine::file_access::AutomationRoots::new(r, w).unwrap()
|
||||
};
|
||||
let both = || root(true, true);
|
||||
// --headless, or no flag: both roots or nothing.
|
||||
for (headless, flag, switch) in [(true, true, true), (true, false, false), (false, false, true), (false, false, false)] {
|
||||
assert!(matches!(mcp_plan(both(), headless, flag, switch), Ok(McpPlan::Headless(_))));
|
||||
for partial in [None, root(true, false), root(false, true)] {
|
||||
assert_eq!(mcp_plan(partial, headless, flag, switch).unwrap_err(), MCP_NEEDS_ROOTS);
|
||||
}
|
||||
}
|
||||
// The flag and the switch: the window, with or without roots.
|
||||
for roots in [None, root(true, false), both()] {
|
||||
assert!(matches!(mcp_plan(roots, false, true, true), Ok(McpPlan::Live(_))));
|
||||
}
|
||||
// The flag without the switch: only with both roots, which confine its headless sessions.
|
||||
assert!(matches!(mcp_plan(both(), false, true, false), Ok(McpPlan::Live(Some(_)))));
|
||||
for partial in [None, root(true, false), root(false, true)] {
|
||||
assert_eq!(mcp_plan(partial, false, true, false).unwrap_err(), MCP_NEEDS_ROOTS_OR_AGENTS);
|
||||
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,38 +352,19 @@ fn mcp_headless_session_takes_the_author_flag() {
|
||||
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
|
||||
}
|
||||
|
||||
/// `mcp --author` without a name is refused, also when another option follows it, instead of
|
||||
/// starting with the default author or that option as the name.
|
||||
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
|
||||
#[test]
|
||||
fn mcp_author_needs_a_name() {
|
||||
assert_eq!(mcp_author(&args(&["--headless", "--author", "Claude"])), Ok(Some("Claude".to_string())));
|
||||
assert_eq!(mcp_author(&args(&["--headless"])), Ok(None));
|
||||
for given in [vec!["--author"], vec!["--author", "--headless"], vec!["--author", "A", "--author", "B"]] {
|
||||
assert!(mcp_author(&args(&given)).is_err(), "{given:?}");
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The deprecated `--connect` is taken out with its value, whether it has one, written apart or as
|
||||
/// `--connect=…`, and leaves the other options as they were.
|
||||
#[test]
|
||||
fn mcp_connect_is_taken_out_with_its_value() {
|
||||
for (given, left) in [
|
||||
(vec!["--connect", "127.0.0.1:9", "--author", "Claude"], vec!["--author", "Claude"]),
|
||||
(vec!["--connect"], vec![]),
|
||||
(vec!["--connect", "--author", "Claude"], vec!["--author", "Claude"]),
|
||||
(vec!["--headless", "--connect=127.0.0.1:9"], vec!["--headless"]),
|
||||
(vec!["--connect=", "--connect", "x"], vec![]),
|
||||
] {
|
||||
let mut rest = args(&given);
|
||||
assert!(take_connect(&mut rest), "{given:?}");
|
||||
assert_eq!(rest, args(&left), "{given:?}");
|
||||
assert!(validate_options("mcp", &rest, MCP_OPTIONS).is_ok());
|
||||
}
|
||||
let mut rest = args(&["--author", "Claude"]);
|
||||
assert!(!take_connect(&mut rest));
|
||||
assert_eq!(rest, args(&["--author", "Claude"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
//! Conversion notes are scoped to rendered output and to the core fonts it uses.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
|
||||
const NOTE: &str = "lines and pages may not match Word's";
|
||||
|
||||
fn convert(input: &Path, output: &Path, flags: &[&str]) -> String {
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(input).arg(output).args(flags).output().unwrap();
|
||||
let stderr = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(run.status.success(), "{output:?}: {stderr}");
|
||||
assert!(output.is_file(), "{output:?}");
|
||||
assert_eq!(String::from_utf8_lossy(&run.stdout).trim_end(), format!("wrote {}", output.display()));
|
||||
stderr.into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversion_font_notes_follow_the_output_format_and_pages() {
|
||||
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-convert-font-notices-{}-{unique}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let input = dir.join("input.json");
|
||||
let mut doc = Document::new();
|
||||
|
||||
// Pick a real non-metric core substitution available on this runner, when there is one.
|
||||
// WordCraft's own bundled Source Sans 3 is the font on the first page.
|
||||
let (font, expected) = ["Cambria", "Calibri", "Arial", "Times New Roman", "Courier New"]
|
||||
.into_iter()
|
||||
.find_map(|font| {
|
||||
let primary = wordcraft_engine::cmd::font::shown_as(&doc, font)?;
|
||||
wordcraft_engine::cmd::font::warns(font, &primary).then_some((font, Some(format!("note: {font} is drawn in {primary},"))))
|
||||
})
|
||||
.unwrap_or(("Arial", None));
|
||||
let paragraph =
|
||||
|text: &str, family: &str| Paragraph::with_text(text, wordcraft_doc::CharProps { font: Some(family.into()), ..Default::default() });
|
||||
let mut later_page = paragraph("This uses an Office family", font);
|
||||
later_page.props.page_break_before = Some(true);
|
||||
doc.body = vec![para_block(paragraph("Bundled font only", "Source Sans 3")), para_block(later_page)];
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
|
||||
for (target, flags) in [
|
||||
("out.docx", &[][..]),
|
||||
("out.odt", &[][..]),
|
||||
("out.rtf", &[][..]),
|
||||
("out.txt", &[][..]),
|
||||
("out.xml", &["--format", "wordml2003"][..]),
|
||||
("flat.xml", &["--format", "flatopc"][..]),
|
||||
("first.PNG", &[][..]),
|
||||
] {
|
||||
let stderr = convert(&input, &dir.join(target), flags);
|
||||
assert!(!stderr.contains(NOTE), "{target}: {stderr}");
|
||||
}
|
||||
let xml = std::fs::read_to_string(dir.join("out.xml")).unwrap();
|
||||
assert!(xml.contains("http://schemas.microsoft.com/office/word/2003/wordml"));
|
||||
let flat = std::fs::read_to_string(dir.join("flat.xml")).unwrap();
|
||||
assert!(flat.contains("http://schemas.microsoft.com/office/2006/xmlPackage"));
|
||||
assert!(std::fs::read(dir.join("first.PNG")).unwrap().starts_with(b"\x89PNG\r\n\x1a\n"));
|
||||
|
||||
let whole = dir.join("whole.PDF");
|
||||
let stderr = convert(&input, &whole, &["--update-fields"]);
|
||||
assert!(std::fs::read(&whole).unwrap().starts_with(b"%PDF-"));
|
||||
let notes: Vec<_> = stderr.lines().filter(|line| line.contains(NOTE)).collect();
|
||||
if let Some(prefix) = expected {
|
||||
assert_eq!(notes.len(), 1, "{stderr}");
|
||||
assert!(notes[0].starts_with(&prefix), "{stderr}");
|
||||
|
||||
// A one-page image does report a non-metric core font when that page uses it.
|
||||
doc.body = vec![para_block(paragraph("This uses an Office family", font))];
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let stderr = convert(&input, &dir.join("used.png"), &[]);
|
||||
assert_eq!(stderr.lines().filter(|line| line.starts_with(&prefix)).count(), 1, "{stderr}");
|
||||
|
||||
// The two pages can share a single shaped paragraph. Its later font must still
|
||||
// stay out of a first-page image's notices, but appear in the complete PDF.
|
||||
let mut split = paragraph(&"Bundled line\n".repeat(16), "Source Sans 3");
|
||||
split
|
||||
.insert_text(split.len(), "Office family only on page two", &wordcraft_doc::CharProps { font: Some(font.into()), ..Default::default() })
|
||||
.unwrap();
|
||||
split.props.line_spacing = Some(wordcraft_doc::props::LineSpacing::Exactly(17.0));
|
||||
let section = doc.last_section.clone();
|
||||
doc.last_section.page_h = 240.0;
|
||||
doc.last_section.margin_top = 24.0;
|
||||
doc.last_section.margin_bottom = 24.0;
|
||||
doc.body = vec![para_block(split)];
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let stderr = convert(&input, &dir.join("split.png"), &[]);
|
||||
assert!(!stderr.contains(NOTE), "{stderr}");
|
||||
let stderr = convert(&input, &dir.join("split.pdf"), &[]);
|
||||
assert_eq!(stderr.lines().filter(|line| line.starts_with(&prefix)).count(), 1, "{stderr}");
|
||||
doc.last_section = section;
|
||||
} else {
|
||||
assert!(notes.is_empty(), "{stderr}");
|
||||
}
|
||||
|
||||
doc.body = vec![para_block(paragraph("Bundled font only", "Source Sans 3"))];
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let stderr = convert(&input, &dir.join("unused.pdf"), &["--strict"]);
|
||||
assert!(!stderr.contains(NOTE), "{stderr}");
|
||||
|
||||
let invalid = dir.join("invalid.pdf");
|
||||
let run =
|
||||
Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(&input).arg(&invalid).args(["--format", "wordml2003"]).output().unwrap();
|
||||
assert!(!run.status.success());
|
||||
assert!(!invalid.exists());
|
||||
let stderr = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(stderr.contains("only for an .xml file") && !stderr.contains(NOTE), "{stderr}");
|
||||
assert!(run.stdout.is_empty());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Removes the temporary test folder when the test finishes or panics.
|
||||
struct TempRoot(PathBuf);
|
||||
|
||||
impl TempRoot {
|
||||
fn remove(self) -> std::io::Result<()> {
|
||||
let res = std::fs::remove_dir_all(&self.0);
|
||||
std::mem::forget(self);
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_saves_home_relative_paths_and_can_clear_the_override() {
|
||||
let root = TempRoot(std::env::temp_dir().join(format!("wc-custom-dictionary-{}", std::process::id())));
|
||||
let home = root.0.join("home");
|
||||
let profile = root.0.join("profile");
|
||||
for folder in [&home, &profile] {
|
||||
std::fs::create_dir_all(folder).unwrap();
|
||||
std::fs::write(folder.join("custom.dic"), "wordcraftdictionary\n").unwrap();
|
||||
}
|
||||
let (preferred, fallback) = if cfg!(windows) { (&profile, &home) } else { (&home, &profile) };
|
||||
let options = |home: Option<&Path>, profile: Option<&Path>, paths: &[&str]| {
|
||||
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cli.env_remove("HOME").env_remove("USERPROFILE");
|
||||
if let Some(home) = home {
|
||||
cli.env("HOME", home);
|
||||
}
|
||||
if let Some(profile) = profile {
|
||||
cli.env("USERPROFILE", profile);
|
||||
}
|
||||
cli.args(["run", "--print"]);
|
||||
for path in paths {
|
||||
cli.args(["--cmd", &format!("file.options={}", json!({"customDictionary": path})), "--cmd", "file.options"]);
|
||||
}
|
||||
cli.output().unwrap()
|
||||
};
|
||||
let assert_saved = |home, profile, paths: &[&str], expected: &[Option<&Path>]| {
|
||||
let report = options(home, profile, paths);
|
||||
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
|
||||
let out = String::from_utf8(report.stdout).unwrap();
|
||||
let reads: Vec<Value> =
|
||||
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(reads.len(), expected.len() * 2, "{out}");
|
||||
for (pair, expected) in reads.as_chunks::<2>().0.iter().zip(expected) {
|
||||
for read in pair {
|
||||
assert_eq!(read["customDictionary"].as_str().map(Path::new), *expected, "{out}");
|
||||
}
|
||||
}
|
||||
};
|
||||
let assert_refused = |home, profile, path, reason: &str| {
|
||||
let report = options(home, profile, &[path]);
|
||||
let error = String::from_utf8_lossy(&report.stderr);
|
||||
assert!(!report.status.success() && error.contains(reason), "{error}");
|
||||
};
|
||||
|
||||
let dic = preferred.join("custom.dic");
|
||||
let absolute = dic.to_str().unwrap();
|
||||
assert_saved(Some(&home), Some(&profile), &["~/custom.dic"], &[Some(&dic)]);
|
||||
assert_saved(None, None, &[absolute, "auto", absolute, ""], &[Some(&dic), None, Some(&dic), None]);
|
||||
let empty = Path::new("");
|
||||
let (empty_home, empty_profile) = if cfg!(windows) { (fallback.as_path(), empty) } else { (empty, fallback.as_path()) };
|
||||
assert_saved(Some(empty_home), Some(empty_profile), &["~/custom.dic"], &[Some(&fallback.join("custom.dic"))]);
|
||||
assert_refused(None, None, "~/custom.dic", "cannot expand");
|
||||
if cfg!(windows) {
|
||||
assert_saved(Some(&home), Some(&profile), &[r"~\custom.dic"], &[Some(&dic)]);
|
||||
assert_refused(None, None, r"~\custom.dic", "cannot expand");
|
||||
assert_refused(Some(&home), Some(&profile), r"~\C:\custom.dic", "relative to the home folder");
|
||||
assert_refused(Some(&home), Some(&profile), r"~\\custom.dic", "relative to the home folder");
|
||||
} else {
|
||||
assert_refused(Some(&home), Some(&profile), r"~\custom.dic", "isn't a full path");
|
||||
}
|
||||
root.remove().unwrap();
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn folder_options_save_home_relative_paths_and_validate_before_reading() {
|
||||
let profile = std::env::temp_dir().join(format!("wc-folder-options-profile-{}", std::process::id()));
|
||||
let templates = profile.join("Templates").join("Personal");
|
||||
let dictionaries = profile.join("Dictionaries");
|
||||
std::fs::create_dir_all(&templates).unwrap();
|
||||
std::fs::create_dir_all(&dictionaries).unwrap();
|
||||
let options = |profile: Option<&Path>, params: Value| {
|
||||
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cli.env_remove("HOME").env_remove("USERPROFILE");
|
||||
if let Some(profile) = profile {
|
||||
cli.env(if cfg!(windows) { "USERPROFILE" } else { "HOME" }, profile);
|
||||
}
|
||||
cli.args(["run", "--print", "--cmd", &format!("file.options={params}"), "--cmd", "file.options"]).output().unwrap()
|
||||
};
|
||||
let assert_saved = |profile, params| {
|
||||
let report = options(profile, params);
|
||||
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
|
||||
let out = String::from_utf8(report.stdout).unwrap();
|
||||
let reads: Vec<Value> =
|
||||
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(reads.len(), 2, "{out}");
|
||||
for read in reads {
|
||||
assert_eq!(Path::new(read["userTemplatesFolder"].as_str().unwrap()), templates);
|
||||
assert_eq!(Path::new(read["dictionariesFolder"].as_str().unwrap()), dictionaries);
|
||||
}
|
||||
};
|
||||
assert_saved(Some(profile.as_path()), json!({"userTemplatesFolder": "~/Templates/Personal", "dictionariesFolder": "~/Dictionaries"}));
|
||||
assert_saved(None, json!({"userTemplatesFolder": templates, "dictionariesFolder": dictionaries}));
|
||||
|
||||
let win_params = json!({"userTemplatesFolder": r"~\Templates/Personal", "dictionariesFolder": r"~\Dictionaries"});
|
||||
let assert_refused = |profile, params, reason: &str| {
|
||||
let report = options(profile, params);
|
||||
let error = String::from_utf8_lossy(&report.stderr);
|
||||
assert!(!report.status.success() && error.contains(reason), "{error}");
|
||||
};
|
||||
if cfg!(windows) {
|
||||
assert_saved(Some(profile.as_path()), win_params.clone());
|
||||
assert_refused(None, win_params, "cannot expand");
|
||||
assert_refused(Some(profile.as_path()), json!({"userTemplatesFolder": r"~\C:\Templates"}), "relative to the home folder");
|
||||
} else {
|
||||
assert_refused(Some(profile.as_path()), win_params, "isn't a full path");
|
||||
}
|
||||
assert_refused(None, json!({"dictionariesFolder": "~/Dictionaries"}), "cannot expand");
|
||||
assert_refused(None, json!({"userTemplatesFolder": r"\\unreachable.invalid\share"}), "can't be a network folder");
|
||||
std::fs::remove_dir_all(profile).unwrap();
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
#[cfg(unix)]
|
||||
mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_font_notices;
|
||||
mod convert_region;
|
||||
mod custom_dictionary;
|
||||
mod folder_options;
|
||||
mod help;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
mod malloc_tuning;
|
||||
@@ -15,4 +12,3 @@ mod picture_then_typing;
|
||||
mod reproducible_pdf;
|
||||
mod strict;
|
||||
mod text_tracked;
|
||||
mod wrote_on_stdout;
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
//! Shared rule 18 (#7124): `wordcraft-cli mcp` refuses to start without both
|
||||
//! `--automation-read-root` and `--automation-write-root` unless the ArtCraft Launcher's switch
|
||||
//! lets agents into WordCraft's window (which confines them to its agent folder), takes the
|
||||
//! deprecated `--connect` with a note, and with both roots refuses files outside them, through the
|
||||
//! real binary. Each run gets its own suite flags, launcher folder and settings folder, so this
|
||||
//! machine's own never count.
|
||||
//! `--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};
|
||||
@@ -50,17 +48,11 @@ fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Run `wordcraft-cli mcp <args>` without the suite's AI-MCP flag, send `lines` on stdin, then hang up.
|
||||
/// Run `wordcraft-cli mcp <args>`, send `lines` on stdin, then hang up.
|
||||
fn mcp(args: &[String], lines: &[Value]) -> Output {
|
||||
mcp_with(args, lines, &[("CRAFT_FLAGS", "-AI-MCP".into())])
|
||||
}
|
||||
|
||||
/// [`mcp`] with these environment variables.
|
||||
fn mcp_with(args: &[String], lines: &[Value], env: &[(&str, std::ffi::OsString)]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
.arg("mcp")
|
||||
.args(args)
|
||||
.envs(env.iter().map(|(k, v)| (*k, v)))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -107,60 +99,17 @@ fn mcp_refuses_to_start_without_both_roots() {
|
||||
assert!(reply.get("error").is_none(), "{reply}");
|
||||
}
|
||||
|
||||
/// `--connect` is kept for one release: it says it is deprecated and is otherwise ignored, so a
|
||||
/// client configuration that still has it keeps working, and it opens no way around the roots.
|
||||
#[test]
|
||||
fn mcp_connect_is_a_deprecated_alias_of_plain_mcp() {
|
||||
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 out = mcp(
|
||||
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],
|
||||
&[serde_json::from_str(PING).unwrap()],
|
||||
&why,
|
||||
);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "stderr: {stderr}");
|
||||
assert!(stderr.contains("--connect is deprecated"), "{stderr}");
|
||||
let reply: Value = serde_json::from_slice(out.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap();
|
||||
assert_eq!(reply["id"], 1, "{reply}");
|
||||
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &["--connect is deprecated", "--automation-read-root"]);
|
||||
}
|
||||
|
||||
/// With the suite's AI-MCP flag: while the launcher's switch keeps agents out, `mcp` still needs
|
||||
/// both roots and says how to let agents in; once the launcher's list names WordCraft, plain `mcp`
|
||||
/// starts without roots and follows the closed-app choice (here: ask to open WordCraft).
|
||||
#[test]
|
||||
fn with_the_flag_the_launcher_switch_lets_plain_mcp_start() {
|
||||
let folders = Folders::new("switch");
|
||||
let base = folders.0.clone();
|
||||
let launcher = base.join("launcher");
|
||||
let settings = base.join("settings");
|
||||
std::fs::create_dir_all(&launcher).unwrap();
|
||||
std::fs::create_dir_all(&settings).unwrap();
|
||||
std::fs::write(settings.join("config.toml"), "schema_version = 1\n[integrations]\nwhenAppClosed = \"error\"\n").unwrap();
|
||||
let env = [
|
||||
("CRAFT_FLAGS", std::ffi::OsString::from("AI-MCP")),
|
||||
("CRAFT_MCP_DIR", launcher.clone().into_os_string()),
|
||||
("WORDCRAFT_PROFILE_DIR", settings.into_os_string()),
|
||||
];
|
||||
let ping: Value = serde_json::from_str(PING).unwrap();
|
||||
let off = mcp_with(&[], std::slice::from_ref(&ping), &env);
|
||||
let stderr = String::from_utf8_lossy(&off.stderr);
|
||||
assert!(!off.status.success() && off.stdout.is_empty(), "started with the switch off: {stderr}");
|
||||
assert!(stderr.contains("ArtCraft Launcher") && stderr.contains("--automation-read-root"), "{stderr}");
|
||||
|
||||
let cli = s(Path::new(env!("CARGO_BIN_EXE_wordcraft-cli")));
|
||||
let list = json!({"version": 1, "apps": [{"id": "wordcraft", "name": "WordCraft", "command": cli, "args": ["mcp"]}]});
|
||||
std::fs::write(launcher.join("apps.json"), list.to_string()).unwrap();
|
||||
let on = mcp_with(&[], &[ping, tool(2, "list_documents", json!({}))], &env);
|
||||
let stderr = String::from_utf8_lossy(&on.stderr);
|
||||
assert!(on.status.success(), "stderr: {stderr}");
|
||||
let replies: Vec<Value> =
|
||||
String::from_utf8_lossy(&on.stdout).lines().filter(|l| !l.trim().is_empty()).map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert!(replies.iter().any(|r| r["id"] == 1 && r.get("error").is_none()), "{replies:?}");
|
||||
let call = replies.iter().find(|r| r["id"] == 2).expect("the tool call is answered");
|
||||
assert_eq!(call["result"]["isError"], true, "{call}");
|
||||
assert!(call.to_string().contains("isn't running"), "the closed-app choice answers: {call}");
|
||||
}
|
||||
|
||||
/// `tools/call` request `id` for `name` with `arguments`.
|
||||
|
||||
@@ -148,8 +148,6 @@ fn an_uncovered_code_point_fails_strict_with_a_report_and_no_file() {
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
assert!(!text.contains("lines and pages may not match Word's"), "{text}");
|
||||
assert!(r.stdout.is_empty());
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["schema"], 1);
|
||||
assert_eq!(json["strict"], "failed");
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
//! A write's `wrote <path>` confirmation is a result, so it goes to stdout, where a script that
|
||||
//! captures the output finds it; stderr keeps errors and diagnostics (#7070).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("wc-cli-wrote-{name}-{}", std::process::id()));
|
||||
// A failed run leaves its directory behind (cleanup runs only after the assertions), and a
|
||||
// later process can reuse the PID: start clean so a stale file cannot pass a check.
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The confirmation is on stdout and not on stderr, and the file is there.
|
||||
fn assert_wrote_on_stdout(run: &Output, out: &Path) {
|
||||
let (stdout, stderr) = (String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
|
||||
assert!(out.is_file(), "{} was not written", out.display());
|
||||
let line = format!("wrote {}", out.display());
|
||||
assert!(stdout.lines().any(|l| l == line), "stdout lacks `{line}`: {stdout:?}");
|
||||
assert!(!stderr.contains("wrote "), "the confirmation is on stderr too: {stderr:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_confirms_the_write_on_stdout() {
|
||||
let d = dir("convert");
|
||||
let (input, out) = (d.join("in.txt"), d.join("out.docx"));
|
||||
std::fs::write(&input, "Hello").unwrap();
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(&input).arg(&out).output().unwrap();
|
||||
assert_wrote_on_stdout(&run, &out);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_confirms_each_save_on_stdout() {
|
||||
let d = dir("run");
|
||||
let out = d.join("out.docx");
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
.args(["run", "--template", "blank", "--cmd", r#"text.insert={"text":"x"}"#, "--save"])
|
||||
.arg(&out)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_wrote_on_stdout(&run, &out);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A reader that has already hung up does not stop the job: every save still runs, though its
|
||||
/// confirmation has nowhere to go. A PNG is written only in the confirming loop, so it shows a
|
||||
/// save that was skipped.
|
||||
#[test]
|
||||
fn run_keeps_saving_after_stdout_closes() {
|
||||
let d = dir("closed");
|
||||
let job = d.join("job.json");
|
||||
std::fs::write(
|
||||
&job,
|
||||
r#"{"template": "blank", "commands": [{"command": "text.insert", "params": {"text": "x"}}], "save": ["first.docx", "second.png"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (reader, writer) = std::io::pipe().unwrap();
|
||||
drop(reader);
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(["run", "--script"]).arg(&job).stdout(writer).output().unwrap();
|
||||
let stderr = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
|
||||
for out in ["first.docx", "second.png"] {
|
||||
assert!(d.join(out).is_file(), "{out} was not written; stderr: {stderr}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -36,7 +36,6 @@ craft = { workspace = true, features = [
|
||||
"ui-app",
|
||||
"dialogs",
|
||||
"automation",
|
||||
"automation-agents",
|
||||
"gpu-startup",
|
||||
"print",
|
||||
"settings",
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
//! A connection authenticates once with the token (`docs/control-protocol.md`, Token). When no
|
||||
//! token or token file is supplied, the app generates a token and writes it to
|
||||
//! `<settings>/control-key.<instance>` (mode 0600) after the port is bound, and removes the file
|
||||
//! when the window closes. The server itself goes to the agent link for the run
|
||||
//! (`AgentLink::from_launch`), so File › Options › Agents says the launch options manage it.
|
||||
//! when the window closes.
|
||||
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -26,37 +25,17 @@ pub struct Control {
|
||||
}
|
||||
|
||||
impl Control {
|
||||
/// The server, for the agent link to keep for the whole run (`AgentLink::from_launch`), and the
|
||||
/// token file this run wrote, which the app removes when the window closes.
|
||||
pub fn split(self) -> (Listening, TokenFile) {
|
||||
(self.listening, TokenFile(self.created))
|
||||
}
|
||||
|
||||
/// Stop accepting connections and remove the token file this run wrote, if any.
|
||||
#[cfg(test)]
|
||||
pub fn shut_down(self) {
|
||||
let (listening, file) = self.split();
|
||||
let Self { listening, created } = self;
|
||||
drop(listening);
|
||||
file.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/// The default token file a run wrote, if any; a token file the user supplied is never removed.
|
||||
pub struct TokenFile(Option<PathBuf>);
|
||||
|
||||
impl TokenFile {
|
||||
/// Removes the file this run wrote.
|
||||
pub fn remove(self) {
|
||||
remove(self.0.as_deref());
|
||||
remove(created.as_deref());
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(path: Option<&Path>) {
|
||||
if let Some(path) = path
|
||||
&& let Err(e) = std::fs::remove_file(path)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
log::warn!("couldn't remove {}: {e}", path.display());
|
||||
if let Some(path) = path {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +62,7 @@ impl StartError {
|
||||
/// `port` in `settings`; a file left by a run that did not exit cleanly is replaced. Without a
|
||||
/// settings folder a fresh token is generated and reported by the log.
|
||||
pub fn start(options: &ControlOptions, port: u16, host: WindowHost, settings: Option<&Path>) -> Option<(Receiver<ControlRequest>, Control)> {
|
||||
match start_with(options, port, host, settings, ControlOptions::server_token, serve) {
|
||||
match start_with(options, port, host, settings, ControlOptions::server_token) {
|
||||
Ok(started) => Some(started),
|
||||
Err(err) => {
|
||||
log::error!("{}", err.message());
|
||||
@@ -98,7 +77,6 @@ fn start_with(
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
token_for: impl FnOnce(&ControlOptions) -> Result<String, AutomationError>,
|
||||
serve: impl FnOnce(TcpListener, String, WindowHost) -> std::io::Result<(Receiver<ControlRequest>, Listening)>,
|
||||
) -> Result<(Receiver<ControlRequest>, Control), StartError> {
|
||||
let listener =
|
||||
TcpListener::bind(("127.0.0.1", port)).map_err(|e| StartError::Other(format!("control server failed to bind 127.0.0.1:{port}: {e}")))?;
|
||||
@@ -144,17 +122,16 @@ mod tests {
|
||||
/// a busy CI runner (#8556). Non-timeout failures stop on the first attempt.
|
||||
const TOKEN_TIMEOUT_ATTEMPTS: usize = 3;
|
||||
|
||||
fn try_start_retrying_token_timeout_with(
|
||||
fn try_start_retrying_token_timeout(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
mut token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
|
||||
mut serve: impl FnMut(TcpListener, String, WindowHost) -> std::io::Result<(Receiver<ControlRequest>, Listening)>,
|
||||
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
|
||||
let mut attempt = 1;
|
||||
loop {
|
||||
match start_with(options, port, host.clone(), settings, &mut token_for, &mut serve) {
|
||||
match start_with(options, port, host.clone(), settings, &mut token_for) {
|
||||
Ok(started) => return Ok(started),
|
||||
Err(StartError::TokenTimeout(msg)) if attempt < TOKEN_TIMEOUT_ATTEMPTS => {
|
||||
log::warn!("retrying control server start after Windows token-file timeout ({attempt}/{TOKEN_TIMEOUT_ATTEMPTS}): {msg}");
|
||||
@@ -165,16 +142,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn try_start_retrying_token_timeout(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
|
||||
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
|
||||
try_start_retrying_token_timeout_with(options, port, host, settings, token_for, serve)
|
||||
}
|
||||
|
||||
fn start_retrying_token_timeout(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
@@ -433,52 +400,4 @@ mod tests {
|
||||
assert!(rx.try_recv().is_err(), "refused auth attempts must not reach the UI");
|
||||
control.shut_down();
|
||||
}
|
||||
|
||||
struct TempDir(std::path::PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(name: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_key_file_is_replaced() {
|
||||
let dir = TempDir::new("wordcraft-control-stale");
|
||||
std::fs::create_dir_all(&dir.0).unwrap();
|
||||
let p = wordcraft_control_key::key_path(&dir.0, 0);
|
||||
std::fs::write(&p, "old").unwrap();
|
||||
|
||||
let options = ControlOptions::default();
|
||||
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir.0), ControlOptions::server_token);
|
||||
let token = std::fs::read_to_string(&p).unwrap();
|
||||
assert_ne!(token.trim(), "old");
|
||||
assert!(ControlClient::connect(control.listening.addr, token.trim()).is_ok());
|
||||
control.shut_down();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_accept_thread_spawn_failure_aborts_start_and_removes_the_key() {
|
||||
let dir = TempDir::new("wordcraft-control-spawn-fail");
|
||||
let path = wordcraft_control_key::key_path(&dir.0, 0);
|
||||
let options = ControlOptions::default();
|
||||
let result =
|
||||
try_start_retrying_token_timeout_with(&options, 0, host(), Some(&dir.0), ControlOptions::server_token, |_listener, _token, _host| {
|
||||
assert!(path.exists(), "startup wrote the token file before spawning");
|
||||
Err(std::io::Error::other("injected accept thread spawn failure"))
|
||||
});
|
||||
assert!(
|
||||
matches!(result, Err((_, StartError::Other(ref msg))) if msg.contains("cannot start the accept thread")),
|
||||
"a server without its accept thread must not report success"
|
||||
);
|
||||
assert!(!path.exists(), "failed startup must remove its published key");
|
||||
}
|
||||
}
|
||||
|
||||
+10
-38
@@ -67,8 +67,8 @@ struct App {
|
||||
settings: SharedSettings<Prefs>,
|
||||
/// The print spool, a handle on the one in the app's services: jobs being sent finish first.
|
||||
spool: Spool,
|
||||
/// The token file `--control` wrote, removed at exit; its server runs in the agent link.
|
||||
control: Option<control_server::TokenFile>,
|
||||
/// The control server, when `--control` started one; it removes the token file it made.
|
||||
control: Option<control_server::Control>,
|
||||
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
|
||||
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
|
||||
exit: Option<Box<dyn FnOnce()>>,
|
||||
@@ -118,8 +118,8 @@ impl App {
|
||||
if let Err(e) = self.settings.lock().flush() {
|
||||
log::warn!("preferences: {e}");
|
||||
}
|
||||
if let Some(file) = self.control.take() {
|
||||
file.remove();
|
||||
if let Some(control) = self.control.take() {
|
||||
control.shut_down();
|
||||
}
|
||||
if !launch_profile::current().is_nightly() {
|
||||
self.app.start_pending_update();
|
||||
@@ -858,41 +858,13 @@ fn main() -> eframe::Result {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
}
|
||||
// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents)
|
||||
// names WordCraft, the agent link serves them and publishes where, so `wordcraft-cli mcp`
|
||||
// finds the window. `--control` runs its own server for the whole run instead. Allow
|
||||
// Agent Control off (File › Options › Agents) refuses both. A Nightly window serves none.
|
||||
let mut control_server = None;
|
||||
if !nightly {
|
||||
let settings_dir = wordcraft_control_key::settings_dir();
|
||||
// A file a crashed launch left behind names a port nothing serves; before this
|
||||
// launch's own listener, so it doesn't keep it.
|
||||
if let Some(dir) = &settings_dir {
|
||||
craft::automation::agents::remove_stale_connection(dir);
|
||||
}
|
||||
let allow = settings.lock().get().integrations.allow_agent_control;
|
||||
let launched = match control.port {
|
||||
Some(port) if !allow => {
|
||||
complain(format_args!("File › Options › Agents › Allow Agent Control is off: not listening on port {port}"));
|
||||
None
|
||||
}
|
||||
Some(port) => control_server::start(&control, port, WindowHost::of(&ctx), settings_dir.as_deref()),
|
||||
None => None,
|
||||
};
|
||||
let link = match launched {
|
||||
Some((rx, started)) => {
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
let (listening, token_file) = started.split();
|
||||
control_server = Some(token_file);
|
||||
craft::automation::agents::AgentLink::from_launch(listening)
|
||||
}
|
||||
None => craft::automation::agents::AgentLink::new(settings_dir, format!("WordCraft {}", env!("CARGO_PKG_VERSION"))),
|
||||
};
|
||||
let switch = craft::automation::agents::AgentSwitch::watch(wordcraft_ui_egui::agents::LAUNCHER_APP_ID, {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
});
|
||||
app = app.with_agents(wordcraft_ui_egui::agents::Agents::new(link, switch));
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
|
||||
@@ -39,21 +39,15 @@ fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let written = std::io::Write::write_all(&mut file, bytes).and_then(|()| file.sync_all());
|
||||
drop(file);
|
||||
if let Err(error) = written {
|
||||
if let Err(e) = std::fs::remove_file(&temporary) {
|
||||
log::warn!("couldn't remove {}: {e}", temporary.display());
|
||||
}
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
return Err(error);
|
||||
}
|
||||
if let Err(error) = std::fs::rename(&temporary, path) {
|
||||
if let Err(e) = std::fs::remove_file(&temporary) {
|
||||
log::warn!("couldn't remove {}: {e}", temporary.display());
|
||||
}
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
return Err(error);
|
||||
}
|
||||
if let Ok(directory) = File::open(directory)
|
||||
&& let Err(e) = directory.sync_all()
|
||||
{
|
||||
log::warn!("couldn't sync {}: {e}", path.display());
|
||||
if let Ok(directory) = File::open(directory) {
|
||||
let _ = directory.sync_all();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -206,10 +206,6 @@ display_name = "entropybeater"
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.adikshan11]
|
||||
real_name = "Adithya Shankaran"
|
||||
sync_github_name = true
|
||||
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
|
||||
|
||||
@@ -432,7 +432,6 @@ impl Document {
|
||||
}
|
||||
let Some(Block::Para(p)) = self.body.get_mut(block).map(Arc::make_mut) else { return false };
|
||||
let Some(before) = p.section.take() else { return false };
|
||||
p.touch();
|
||||
self.section_mut(block).absorb(&before);
|
||||
true
|
||||
}
|
||||
@@ -440,10 +439,7 @@ impl Document {
|
||||
/// Allocate a new part id and insert the part. Part ids run out only past `u32::MAX` parts, more
|
||||
/// than memory holds; then nothing is added and the id is 0, which [`free_id`] never gives a part.
|
||||
pub fn add_part(&mut self, kind: PartKind, blocks: Blocks) -> u32 {
|
||||
self.try_add_part(kind, blocks).unwrap_or_else(|e| {
|
||||
log::error!("add_part: {e}");
|
||||
0
|
||||
})
|
||||
self.try_add_part(kind, blocks).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// [`Document::add_part`], or an error, adding nothing, when every part id is taken.
|
||||
@@ -817,14 +813,8 @@ impl Document {
|
||||
/// Repair every paragraph's runs (see [`Paragraph::normalize`]); for models from untrusted
|
||||
/// JSON, whose run lengths may overflow, fall short or split a character.
|
||||
pub fn normalize_runs(&mut self) {
|
||||
let separators = [&mut self.footnote_separators, &mut self.endnote_separators]
|
||||
.into_iter()
|
||||
.flat_map(|s| [&mut s.separator, &mut s.continuation_separator, &mut s.continuation_notice])
|
||||
.flatten();
|
||||
let stories = std::iter::once(&mut self.body)
|
||||
.chain(self.parts.values_mut().map(|part| &mut part.blocks))
|
||||
.chain(separators)
|
||||
.chain(self.glossary.iter_mut().map(|entry| &mut entry.blocks));
|
||||
let mut stories: Vec<&mut Blocks> = vec![&mut self.body];
|
||||
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
|
||||
for blocks in stories {
|
||||
for b in blocks.iter_mut() {
|
||||
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
|
||||
|
||||
@@ -478,8 +478,6 @@ impl Relink<'_> {
|
||||
self.shift_change(&mut row.props.fmt_change);
|
||||
for cell in row.cells.iter_mut() {
|
||||
self.shift_change(&mut cell.props.fmt_change);
|
||||
let merge = cell.props.merge_change.take();
|
||||
cell.props.merge_change = merge.and_then(|m| Some(crate::props::CellMergeChange { rev: self.rev_id(m.rev)?, ..m }));
|
||||
todo.extend(cell.blocks.iter_mut().map(Arc::make_mut));
|
||||
}
|
||||
}
|
||||
@@ -1651,13 +1649,7 @@ impl Document {
|
||||
}
|
||||
}
|
||||
budget.active.pop();
|
||||
let id = match self.try_add_part(PartKind::TextBox, blocks) {
|
||||
Ok(id) => id,
|
||||
Err(e) => {
|
||||
log::warn!("adopt_text_boxes: cannot add a part: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let id = self.try_add_part(PartKind::TextBox, blocks).ok()?;
|
||||
if let Some(p) = self.parts.get_mut(&id) {
|
||||
p.body = body;
|
||||
}
|
||||
|
||||
+11
-147
@@ -87,10 +87,6 @@ pub struct AbstractNum {
|
||||
/// `None`: derived from the levels.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub multi_level_type: Option<String>,
|
||||
/// The list starts over after each section break, continuous or not (Word 2013's
|
||||
/// `w15:restartNumberingAfterBreak`; measured in Word for Windows, #7382).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub restart_after_section_break: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||
@@ -292,10 +288,7 @@ impl Numbering {
|
||||
/// Create a new list of `kind`; returns the `num` id. List ids run out only past `u32::MAX`
|
||||
/// lists, more than memory holds; then nothing is added and the id is 0, "no list".
|
||||
pub fn add_list(&mut self, kind: ListKind) -> u32 {
|
||||
self.try_add_list(kind).unwrap_or_else(|e| {
|
||||
log::error!("add_list: {e}");
|
||||
0
|
||||
})
|
||||
self.try_add_list(kind).unwrap_or(0)
|
||||
}
|
||||
/// [`Numbering::add_list`], or an error, adding nothing, when list ids are all taken.
|
||||
pub fn try_add_list(&mut self, kind: ListKind) -> crate::Result<u32> {
|
||||
@@ -344,8 +337,8 @@ impl Numbering {
|
||||
pub struct Counters {
|
||||
/// Per abstract list: current value per level.
|
||||
state: HashMap<u32, [u32; 9]>,
|
||||
/// Which levels of which nums have started: a num's start override for a level applies on
|
||||
/// first use and again at each restart by that list (ECMA-376 Part 1, 17.9.27 startOverride).
|
||||
/// Which levels of which nums have started: a num's start override for a level applies
|
||||
/// once, when that level of that num is first used (ECMA-376 Part 1, 17.9.27 startOverride).
|
||||
seen: HashMap<(u32, u8), bool>,
|
||||
/// Per abstract list: whether each level has counted yet (a value of 0 can be a real count when a
|
||||
/// level starts at 0).
|
||||
@@ -388,33 +381,12 @@ impl Counters {
|
||||
self.next_label_from(n, abs, level)
|
||||
}
|
||||
|
||||
/// A section ends: the lists that start over after a section break
|
||||
/// ([`AbstractNum::restart_after_section_break`]) do, every level, as if not used yet. A
|
||||
/// list's start overrides aren't applied again: after the break it counts from its levels'
|
||||
/// starts (measured in Word for Windows, #7382). Walks that count labels in document order
|
||||
/// call it after each paragraph that ends a section.
|
||||
pub fn section_break(&mut self, numbering: &Numbering) {
|
||||
for a in numbering.abstracts.iter().filter(|a| a.restart_after_section_break) {
|
||||
self.state.remove(&a.id);
|
||||
self.flags.remove(&a.id);
|
||||
self.labels.retain(|(id, _), _| *id != a.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`Self::values`], using one walk's borrowed definition index.
|
||||
pub fn values_indexed(&self, numbering: &NumberingIndex<'_>, num: u32) -> Option<[u32; 9]> {
|
||||
let abs = numbering.abstract_of(num)?;
|
||||
Some(self.state.get(&abs.id).copied().unwrap_or([0; 9]))
|
||||
}
|
||||
|
||||
/// The values counted so far for `num`, including implicitly counted ancestors and zero starts.
|
||||
/// An unstarted level has no value even when its definition has a default start.
|
||||
pub fn counted_values_indexed(&self, numbering: &NumberingIndex<'_>, num: u32) -> [Option<u32>; 9] {
|
||||
let Some(abs) = numbering.abstract_of(num) else { return [None; 9] };
|
||||
let (Some(values), Some(flags)) = (self.state.get(&abs.id), self.flags.get(&abs.id)) else { return [None; 9] };
|
||||
std::array::from_fn(|level| flags[level].started.then_some(values[level]))
|
||||
}
|
||||
|
||||
fn next_label_from(&mut self, n: &Num, abs: &AbstractNum, level: u8) -> Option<(String, Level)> {
|
||||
let num = n.id;
|
||||
let lv = (level as usize).min(8);
|
||||
@@ -423,13 +395,6 @@ impl Counters {
|
||||
// A "none" level (Word's numFmt none) still counts and restarts the levels below it; only
|
||||
// its number reads as nothing, so its literal text ("RESPONSE:") shows (#4985).
|
||||
let def = level_def(lv)?.clone();
|
||||
// A level not restarted yet counts from its abstract list's start: one this list defines
|
||||
// itself counts on with the abstract list. A level a paragraph of this list restarts, by
|
||||
// counting above it, starts again at this list's start override for it, every time, or
|
||||
// else at the start of this list's definition of it (measured in Word for Windows, #7381).
|
||||
let start_of = |k: usize| abs.levels.get(k).or_else(|| level_def(k)).map_or(1, |l| l.start);
|
||||
let restart_at =
|
||||
|k: usize| n.start_overrides.iter().find(|(l, _)| *l as usize == k).map(|(_, s)| *s).or_else(|| level_def(k).map(|l| l.start));
|
||||
let st = self.state.entry(abs.id).or_insert([0; 9]);
|
||||
let fl = self.flags.entry(abs.id).or_default();
|
||||
// Only this level's override, not the num's others: the counters are shared by every
|
||||
@@ -460,11 +425,11 @@ impl Counters {
|
||||
}
|
||||
std::collections::hash_map::Entry::Occupied(_) => None,
|
||||
};
|
||||
*v = start.or(f.first).unwrap_or_else(|| start_of(k));
|
||||
*v = start.or(f.first).unwrap_or_else(|| level_def(k).map_or(1, |l| l.start));
|
||||
*f = LevelFlags { started: true, first: None };
|
||||
}
|
||||
if let (Some(v), Some(f)) = (st.get_mut(lv), fl.get_mut(lv)) {
|
||||
*v = if f.started { v.saturating_add(1) } else { f.first.unwrap_or_else(|| start_of(lv)) };
|
||||
*v = if f.started { v.saturating_add(1) } else { f.first.unwrap_or(def.start) };
|
||||
*f = LevelFlags { started: true, first: None };
|
||||
}
|
||||
// Deeper levels restart, unless they never restart or only restart after a level above
|
||||
@@ -473,7 +438,7 @@ impl Counters {
|
||||
let restarts = level_def(d).is_none_or(|l| l.restart && l.restart_after.is_none_or(|k| lv < k as usize));
|
||||
if restarts {
|
||||
*deeper = 0;
|
||||
*f = LevelFlags { started: false, first: restart_at(d) };
|
||||
*f = LevelFlags::default();
|
||||
self.labels.remove(&(abs.id, d as u8));
|
||||
}
|
||||
}
|
||||
@@ -528,19 +493,16 @@ impl Counters {
|
||||
}
|
||||
}
|
||||
|
||||
fn placeholder_level(digit: char) -> Option<usize> {
|
||||
digit.to_digit(10).filter(|d| (1..=9).contains(d)).map(|d| (d - 1) as usize)
|
||||
}
|
||||
|
||||
/// The zero-based levels a label template shows (`"%1.%2"` → `[0, 1]`, `"(%3)"` → `[2]`).
|
||||
pub fn template_levels(text: &str) -> Vec<usize> {
|
||||
let mut out = Vec::new();
|
||||
let mut chars = text.chars().take(MAX_LEVEL_TEXT).peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '%'
|
||||
&& let Some(k) = chars.peek().copied().and_then(placeholder_level)
|
||||
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
|
||||
{
|
||||
chars.next();
|
||||
let k = (d as usize).saturating_sub(1).min(8);
|
||||
if !out.contains(&k) {
|
||||
out.push(k);
|
||||
}
|
||||
@@ -556,9 +518,11 @@ fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level,
|
||||
let mut chars = def.text.chars().take(MAX_LEVEL_TEXT).peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '%'
|
||||
&& let Some(k) = chars.peek().copied().and_then(placeholder_level)
|
||||
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
|
||||
&& (1..=9).contains(&d)
|
||||
{
|
||||
chars.next();
|
||||
let k = (d as usize).saturating_sub(1).min(8);
|
||||
let val = vals.get(k).copied().unwrap_or(0);
|
||||
let counted = started.get(k).is_some_and(|f| f.started);
|
||||
let level = level_def(k);
|
||||
@@ -629,66 +593,13 @@ mod tests {
|
||||
assert_eq!(counters.started(&numbering, second_id).unwrap()[..2], [true, true]);
|
||||
}
|
||||
|
||||
/// #7381: a level a list defines itself (Word's lvlOverride/lvl) counts on with its abstract
|
||||
/// list, from the abstract list's start; its own start counts with a start override, which
|
||||
/// restarts the level there (measured in Word for Windows: 5. F. G. 8. I. and 5. C. D. 5. F.).
|
||||
#[test]
|
||||
fn a_level_a_list_defines_itself_counts_on_with_its_abstract_list() {
|
||||
for (overrides, want) in [(vec![], ["5.", "F.", "G.", "8.", "I."]), (vec![(0, 3)], ["5.", "C.", "D.", "5.", "F."])] {
|
||||
let mut n = Numbering::default();
|
||||
let first = n.add_list(ListKind::Numbered);
|
||||
let abs = n.num(first).unwrap().abstract_id;
|
||||
n.abstracts.iter_mut().find(|a| a.id == abs).unwrap().levels[0].start = 5;
|
||||
let letters = Level { format: NumFormat::UpperLetter, text: "%1.".into(), start: 3, ..Level::default() };
|
||||
let second = n.free_num_id().unwrap();
|
||||
n.nums.push(Num { id: second, abstract_id: abs, start_overrides: overrides.clone(), level_overrides: vec![(0, letters)] });
|
||||
let labels = |order: &[u32]| {
|
||||
let mut c = Counters::default();
|
||||
order.iter().map(|id| c.next_label(&n, *id, 0).unwrap().0).collect::<Vec<String>>()
|
||||
};
|
||||
assert_eq!(labels(&[first, second, second, first, second]), want, "{overrides:?}");
|
||||
if overrides.is_empty() {
|
||||
// Used first, it starts at the abstract list's 5, not its own 3: E. F. 7. H.
|
||||
assert_eq!(labels(&[second, second, first, second]), ["E.", "F.", "7.", "H."]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A level 2 that list 2 defines itself (upper letters from 3, the abstract list's from 5)
|
||||
/// starts at the abstract list's start until a level 1 restarts it, and then at the start the
|
||||
/// restarting paragraph's list gives it: its start override, every time, or its own
|
||||
/// definition's start (measured in Word for Windows, #7381).
|
||||
#[test]
|
||||
fn a_restarted_level_starts_where_the_restarting_list_says() {
|
||||
let lvl = |format, text: &str, start| Level { format, text: text.into(), start, ..Level::default() };
|
||||
let case = |overrides: Vec<(u8, u32)>, own: Option<Level>, items: &[(u32, u8)]| {
|
||||
let mut n = Numbering::default();
|
||||
let plain = n.try_add_levels(None, vec![lvl(NumFormat::Decimal, "%1.", 1), lvl(NumFormat::UpperLetter, "%2)", 5)]).unwrap();
|
||||
let abs = n.num(plain).unwrap().abstract_id;
|
||||
let id = n.free_num_id().unwrap();
|
||||
n.nums.push(Num { id, abstract_id: abs, start_overrides: overrides, level_overrides: own.into_iter().map(|l| (1, l)).collect() });
|
||||
let mut c = Counters::default();
|
||||
items.iter().map(|&(list, level)| c.next_label(&n, if list == 1 { plain } else { id }, level).unwrap().0).collect::<Vec<String>>()
|
||||
};
|
||||
let own = || Some(lvl(NumFormat::UpperLetter, "%2)", 3));
|
||||
let nested = [(2, 0), (2, 1), (2, 1), (2, 0), (2, 1)];
|
||||
assert_eq!(case(vec![], own(), &nested), ["1.", "C)", "D)", "2.", "C)"]);
|
||||
assert_eq!(case(vec![(1, 3)], own(), &nested), ["1.", "C)", "D)", "2.", "C)"]);
|
||||
assert_eq!(case(vec![(1, 7)], None, &nested), ["1.", "G)", "H)", "2.", "G)"], "the override again at each restart");
|
||||
assert_eq!(case(vec![], own(), &[(2, 1), (2, 1), (2, 0), (2, 1)]), ["E)", "F)", "2.", "C)"], "not restarted yet");
|
||||
assert_eq!(case(vec![], own(), &[(1, 0), (2, 1), (2, 1), (1, 0), (2, 1)]), ["1.", "E)", "F)", "2.", "E)"], "restarted by the plain list");
|
||||
assert_eq!(case(vec![], own(), &[(2, 0), (1, 1), (2, 1), (2, 0), (1, 1)]), ["1.", "C)", "D)", "2.", "C)"], "restarted by list 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_level_text_gives_a_bounded_label() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
let huge = Level { format: NumFormat::UpperRoman, text: "%1".repeat(30_000), start: u32::MAX, ..Level::default() };
|
||||
if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) {
|
||||
// The level's own start counts with a start override (as Word's lvlOverride reads).
|
||||
num.level_overrides = vec![(0, huge)];
|
||||
num.start_overrides = vec![(0, u32::MAX)];
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
let label = c.next_label(&n, id, 0).unwrap().0;
|
||||
@@ -917,35 +828,6 @@ mod tests {
|
||||
assert_eq!(n.find_kind(ListKind::Bullet), Some(b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_flagged_to_restart_after_a_section_break_starts_over_there() {
|
||||
let mut n = Numbering::default();
|
||||
let flagged = n.add_list(ListKind::Numbered);
|
||||
let abs = n.num(flagged).unwrap().abstract_id;
|
||||
n.abstracts.iter_mut().find(|a| a.id == abs).unwrap().restart_after_section_break = true;
|
||||
let mut other_levels = n.abstract_of(flagged).unwrap().levels.clone();
|
||||
other_levels[0].text = "(%1)".into();
|
||||
let other = n.try_add_levels(None, other_levels).unwrap();
|
||||
// The same list's other instance, with a start override it applies once.
|
||||
let overridden = n.free_num_id().unwrap();
|
||||
n.nums.push(Num { id: overridden, abstract_id: abs, start_overrides: vec![(0, 5)], ..Default::default() });
|
||||
let mut c = Counters::default();
|
||||
let next = |c: &mut Counters, num, level| c.next_label(&n, num, level).unwrap().0;
|
||||
assert_eq!([next(&mut c, flagged, 0), next(&mut c, flagged, 0), next(&mut c, other, 0)], ["1.", "2.", "(1)"]);
|
||||
next(&mut c, flagged, 1);
|
||||
c.section_break(&n);
|
||||
// Every level of the flagged list starts over; the other list goes on.
|
||||
assert_eq!(c.values(&n, flagged), Some([0; 9]));
|
||||
assert_eq!(next(&mut c, other, 0), "(2)");
|
||||
next(&mut c, flagged, 1);
|
||||
assert_eq!(c.values(&n, flagged).unwrap()[..2], [1, 1], "the level above counts its first number");
|
||||
assert_eq!(next(&mut c, flagged, 0), "2.");
|
||||
// An override already used isn't applied again after a break.
|
||||
assert_eq!(next(&mut c, overridden, 0), "5.");
|
||||
c.section_break(&n);
|
||||
assert_eq!(next(&mut c, overridden, 0), "1.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_keeps_the_list_s_own_level_definitions() {
|
||||
let mut n = Numbering::default();
|
||||
@@ -987,23 +869,6 @@ mod tests {
|
||||
assert_eq!(labels, ["0.", "1.", "2."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_counted_zero_ancestor_replaces_the_unstarted_fallback() {
|
||||
let mut numbering = Numbering::default();
|
||||
let num = numbering.add_list(ListKind::Numbered);
|
||||
numbering.abstracts[0].levels[0].start = 7;
|
||||
numbering.abstracts[0].levels[1] = Level { text: "%1.%2.".into(), ..Default::default() };
|
||||
numbering.nums[0].start_overrides = vec![(0, 0)];
|
||||
let index = NumberingIndex::new(&numbering);
|
||||
let mut counters = Counters::default();
|
||||
|
||||
assert_eq!(counters.counted_values_indexed(&index, num)[0], None);
|
||||
assert_eq!(counters.current_label(&numbering, num, 1).as_deref(), Some("7.1."));
|
||||
let (label, _) = counters.next_label_indexed(&index, num, 1).unwrap();
|
||||
assert_eq!(label, "0.1.");
|
||||
assert_eq!(counters.counted_values_indexed(&index, num)[0], Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholder_percent_zero_is_preserved_as_literal() {
|
||||
let mut n = Numbering::default();
|
||||
@@ -1013,7 +878,6 @@ mod tests {
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "%0 1.");
|
||||
assert_eq!(template_levels("%0 %2. %9 %2"), [1, 8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -18,7 +18,7 @@ mod inline_kinds;
|
||||
mod inline_object;
|
||||
mod run;
|
||||
|
||||
pub use float::{AltText, Anchor, Float, FloatAlign, MAX_ALT_TEXT, RelSize, SizeFrom, Wrap, WrapText, cap_alt};
|
||||
pub use float::{AltText, Anchor, Float, FloatAlign, MAX_ALT_TEXT, Wrap, WrapText, cap_alt};
|
||||
pub use inline_kinds::{NoteKind, PTabAlign, PTabBase, RubyAlign, ShapeKind, ruby_offset, ruby_raise};
|
||||
pub use inline_object::{CanvasStyle, GroupChild, InlineObject, MAX_GROUP_CHILDREN};
|
||||
pub use run::{COLUMN_BREAK, LINE_BREAK, NB_HYPHEN, NBSP, OBJ, PAGE_BREAK, Run, SOFT_HYPHEN, next_rev};
|
||||
|
||||
@@ -103,41 +103,6 @@ pub enum FloatAlign {
|
||||
Outside,
|
||||
}
|
||||
|
||||
/// What an anchored object's relative width or height is a share of (`relativeFrom` of
|
||||
/// `wp14:sizeRelH` and `wp14:sizeRelV`, [MS-ODRAWXML]). As craft-wordmodel's, which the DOCX
|
||||
/// bridge carries it from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SizeFrom {
|
||||
/// The page's text area (the page less its margins).
|
||||
Margin,
|
||||
Page,
|
||||
LeftMargin,
|
||||
RightMargin,
|
||||
TopMargin,
|
||||
BottomMargin,
|
||||
InsideMargin,
|
||||
OutsideMargin,
|
||||
}
|
||||
|
||||
/// An anchored object's width or height as a share of the page or a margin (`wp14:sizeRelH` with
|
||||
/// `wp14:pctWidth`, `wp14:sizeRelV` with `wp14:pctHeight`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RelSize {
|
||||
pub from: SizeFrom,
|
||||
/// Thousandths of a percent: 100000 is the whole length. 0 leaves the object its own size, as
|
||||
/// Word does.
|
||||
pub pct: u32,
|
||||
}
|
||||
|
||||
impl RelSize {
|
||||
/// The length this share gives of `base` (points), `None` for a share of 0.
|
||||
pub fn of(self, base: f32) -> Option<f32> {
|
||||
(self.pct > 0).then(|| base.max(0.0) * self.pct as f32 / 100_000.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl FloatAlign {
|
||||
/// From an OOXML alignment (`wp:align`, `w:tblpXSpec`, `w:tblpYSpec`).
|
||||
pub fn from_ooxml(v: &str) -> Option<FloatAlign> {
|
||||
@@ -226,13 +191,6 @@ pub struct Float {
|
||||
/// drawing on its anchor paragraph's page.
|
||||
#[serde(skip_serializing_if = "is_zero_u32")]
|
||||
pub page: u32,
|
||||
/// The width and the height as a share of the page or a margin (`wp14:sizeRelH`,
|
||||
/// `wp14:sizeRelV`), which Word sizes the object by instead of its own size: a cover page's
|
||||
/// sidebar is as tall as any page (#6770). See [`RelSize`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub rel_w: Option<RelSize>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub rel_h: Option<RelSize>,
|
||||
/// Turned, but the file keeps no room for the turn (`wp:effectExtent` missing or zero, as
|
||||
/// files from other tools have): Word then keeps an inline one's line to its frame and lets
|
||||
/// the turned object overhang it (see [`Float::line_pad`]). Cleared by [`Float::set_spin`].
|
||||
|
||||
@@ -258,19 +258,8 @@ impl InlineObject {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Resize a drawing (a group's members scale with it; a canvas's keep their size and place). A
|
||||
/// side whose size changes loses a share of the page or a margin it had (`Float::rel_w`,
|
||||
/// `Float::rel_h`), which would otherwise size it instead.
|
||||
/// Resize a drawing (a group's members scale with it; a canvas's keep their size and place).
|
||||
pub fn set_size(&mut self, nw: f32, nh: f32) {
|
||||
let old = self.frame().map(|(w, h, _)| (w, h));
|
||||
if let (Some((ow, oh)), Some(f)) = (old, self.float_mut()) {
|
||||
if ow != nw {
|
||||
f.rel_w = None;
|
||||
}
|
||||
if oh != nh {
|
||||
f.rel_h = None;
|
||||
}
|
||||
}
|
||||
if let InlineObject::Image { w, h, .. }
|
||||
| InlineObject::Graphic { w, h, .. }
|
||||
| InlineObject::Shape { w, h, .. }
|
||||
|
||||
@@ -32,8 +32,8 @@ pub use para_props::{
|
||||
TextAlignment, TextFrame,
|
||||
};
|
||||
pub use table_props::{
|
||||
CellMergeChange, CellPicture, CellProps, HeightRule, MergeMark, PictureRepeat, RowProps, TableFloat, TableLook, TableProps, TextDirection,
|
||||
TextVert, VAlign, VMerge, anchor_ooxml, valign_from_anchor,
|
||||
CellPicture, CellProps, HeightRule, PictureRepeat, RowProps, TableFloat, TableLook, TableProps, TextDirection, TextVert, VAlign, VMerge,
|
||||
anchor_ooxml, valign_from_anchor,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -300,58 +300,12 @@ pub struct CellProps {
|
||||
/// Tracked formatting change (`w:tcPrChange`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fmt_change: Option<Box<PropChange<CellProps>>>,
|
||||
/// Tracked vertical merge or split of the cell (`w:cellMerge`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub merge_change: Option<CellMergeChange>,
|
||||
/// A picture behind the cell's content (an ODF cell's `style:background-image`; Word has
|
||||
/// none).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub picture: Option<Box<CellPicture>>,
|
||||
}
|
||||
|
||||
/// A tracked vertical merge or split of a table cell (ECMA-376 §17.13.5.3, `w:cellMerge`): the
|
||||
/// revision that made it, and the cell's vertical merge after it (`w:vMerge`) and before it
|
||||
/// (`w:vMergeOrig`). The table already shows the change. Word for Windows lists one with
|
||||
/// `w:vMerge` as merged cells and one without as split cells. Accepting or rejecting it drops
|
||||
/// only the record: the cells stay as they are.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CellMergeChange {
|
||||
/// Index into `Document::revisions`.
|
||||
pub rev: u32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub v_merge: Option<MergeMark>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub v_merge_orig: Option<MergeMark>,
|
||||
}
|
||||
|
||||
/// A cell's vertical merge in a tracked merge or split (`ST_AnnotationVMerge`): it continues the
|
||||
/// merge from the cell above (`cont`) or starts one (`rest`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MergeMark {
|
||||
Continue,
|
||||
Restart,
|
||||
}
|
||||
|
||||
impl MergeMark {
|
||||
pub fn ooxml(self) -> &'static str {
|
||||
match self {
|
||||
MergeMark::Continue => "cont",
|
||||
MergeMark::Restart => "rest",
|
||||
}
|
||||
}
|
||||
|
||||
/// The value for `s`, `None` for one the schema doesn't have.
|
||||
pub fn from_ooxml(s: &str) -> Option<MergeMark> {
|
||||
match s {
|
||||
"cont" => Some(MergeMark::Continue),
|
||||
"rest" => Some(MergeMark::Restart),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cell's background picture: drawn at its own size where `align` puts it, tiled, or stretched
|
||||
/// over the cell, and cut off at the cell's edges.
|
||||
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
|
||||
|
||||
@@ -773,10 +773,6 @@ pub struct SectionProps {
|
||||
pub page_w: f32,
|
||||
pub page_h: f32,
|
||||
pub landscape: bool,
|
||||
/// Top and bottom margins, points. Negative is Word's exact margin (`w:pgMar` `w:top` /
|
||||
/// `w:bottom` below zero, ECMA-376 §17.6.11; DOC `dyaTop` / `dyaBottom`): the text starts
|
||||
/// (ends) at the absolute value from the page edge even when the header (footer) is taller,
|
||||
/// and overlaps it.
|
||||
pub margin_top: f32,
|
||||
pub margin_bottom: f32,
|
||||
pub margin_left: f32,
|
||||
@@ -916,21 +912,17 @@ impl SectionProps {
|
||||
pub fn text_width(&self) -> f32 {
|
||||
(self.page_w - self.margin_left - self.margin_right - self.gutter).max(18.0)
|
||||
}
|
||||
/// Height of the text area between the margins, points (a negative, exact margin counts at
|
||||
/// its size).
|
||||
pub fn text_height(&self) -> f32 {
|
||||
(self.page_h - self.margin_top.abs() - self.margin_bottom.abs()).max(18.0)
|
||||
(self.page_h - self.margin_top - self.margin_bottom).max(18.0)
|
||||
}
|
||||
/// Swap to landscape/portrait (keeps margins relative to the paper as Word does: rotates them).
|
||||
/// An exact (negative) top or bottom turns into a side at its size, as in Word: only the top
|
||||
/// and bottom can be exact.
|
||||
pub fn set_landscape(&mut self, on: bool) {
|
||||
if on == self.landscape {
|
||||
return;
|
||||
}
|
||||
self.landscape = on;
|
||||
std::mem::swap(&mut self.page_w, &mut self.page_h);
|
||||
let (t, b, l, r) = (self.margin_top.abs(), self.margin_bottom.abs(), self.margin_left, self.margin_right);
|
||||
let (t, b, l, r) = (self.margin_top, self.margin_bottom, self.margin_left, self.margin_right);
|
||||
if on {
|
||||
self.margin_top = l;
|
||||
self.margin_bottom = r;
|
||||
|
||||
@@ -216,8 +216,6 @@ impl Table {
|
||||
for c in &src.cells {
|
||||
let mut nc = Cell::empty();
|
||||
nc.props = c.props.clone();
|
||||
// A tracked merge or split is the source cell's own: the new one has none.
|
||||
nc.props.merge_change = None;
|
||||
if nc.props.vmerge == VMerge::Restart {
|
||||
nc.props.vmerge = VMerge::None;
|
||||
}
|
||||
@@ -598,7 +596,6 @@ impl Table {
|
||||
for (i, cell) in src.cells.iter_mut().enumerate() {
|
||||
let mut nc = Cell::empty();
|
||||
nc.props = cell.props.clone();
|
||||
nc.props.merge_change = None;
|
||||
if i == ci {
|
||||
cell.props.vmerge = VMerge::None;
|
||||
nc.props.vmerge = VMerge::None;
|
||||
@@ -833,25 +830,4 @@ mod tests {
|
||||
assert_eq!(v.rows[0].cells[0].props.vmerge, VMerge::Restart);
|
||||
assert_eq!(v.rows[2].cells[0].props.vmerge, VMerge::Continue);
|
||||
}
|
||||
|
||||
/// A tracked merge or split of a cell stays with that cell: a row inserted beside it, or the rows
|
||||
/// a cell is split into, are new cells the revision never touched.
|
||||
#[test]
|
||||
fn new_cells_take_no_tracked_cell_merge() {
|
||||
use crate::props::{CellMergeChange, MergeMark};
|
||||
let merged = Some(CellMergeChange { rev: 0, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
|
||||
let mut t = Table::new(2, 2, 144.0);
|
||||
for row in &mut t.rows {
|
||||
for c in &mut row.cells {
|
||||
c.props.merge_change = merged;
|
||||
}
|
||||
}
|
||||
t.insert_row(1, 0);
|
||||
assert_eq!(t.rows.len(), 3);
|
||||
assert!(t.rows[1].cells.iter().all(|c| c.props.merge_change.is_none()), "the inserted row");
|
||||
assert!(t.rows[0].cells.iter().all(|c| c.props.merge_change == merged), "the row it was copied from keeps its record");
|
||||
assert!(t.split_cell_grid(0, 0, 1, 2));
|
||||
let records = t.rows.iter().map(|r| r.cells.iter().filter(|c| c.props.merge_change.is_some()).count()).collect::<Vec<_>>();
|
||||
assert_eq!(records, [2, 0, 0, 2], "the row the split adds takes none");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -959,25 +959,6 @@ fn normalize_runs_reconciles_objects_with_markers() {
|
||||
// Deleting the first marker keeps B on the second.
|
||||
p.delete(1, 4).unwrap();
|
||||
assert_eq!(p.objects, vec![fs("B")]);
|
||||
|
||||
let mut d = build();
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.objects.push(fs("Surplus"));
|
||||
p.runs[0].len = 1;
|
||||
d.footnote_separators.continuation_notice = Some(d.body.clone());
|
||||
d.endnote_separators.separator = Some(d.body.clone());
|
||||
d.glossary.push(BuildingBlock { name: "Quick Parts example".into(), blocks: d.body.clone(), ..Default::default() });
|
||||
d.normalize_runs();
|
||||
for (name, blocks) in [
|
||||
("footnote continuation notice", d.footnote_separators.continuation_notice.as_ref().unwrap()),
|
||||
("endnote separator", d.endnote_separators.separator.as_ref().unwrap()),
|
||||
("Quick Parts entry", &d.glossary[0].blocks),
|
||||
] {
|
||||
edit::each_para(&blocks[0], 0, &mut |p| {
|
||||
assert_eq!(p.objects, vec![fs("A"), fs("B")], "{name} drops the surplus object");
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len(), "{name} repairs its runs");
|
||||
});
|
||||
}
|
||||
// The cost is linear: the markers and runs `reconcile_objects` walks (`crate::work`), not a
|
||||
// timing. 8x the unmatched markers cost about 8x the steps, far more if each removal rescans.
|
||||
let reconcile = |extra: usize| {
|
||||
|
||||
@@ -189,9 +189,6 @@ pub(crate) fn story_word_count_of(
|
||||
total = total.saturating_add(count_label_words(&label));
|
||||
}
|
||||
total = total.saturating_add(count_words(&p.plain_text()));
|
||||
if p.section.is_some() {
|
||||
counters.section_break(numbering);
|
||||
}
|
||||
}
|
||||
Block::Table(t) => {
|
||||
for row in &t.rows {
|
||||
|
||||
@@ -15,13 +15,13 @@ wordcraft-doc = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-doc = { workspace = true, features = ["test-support"] }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
base64 = { workspace = true }
|
||||
cfb = { workspace = true }
|
||||
log = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
|
||||
+3
-15
@@ -57,13 +57,7 @@ pub fn read_with(bytes: &[u8], opts: &ReadOptions) -> Result<wordcraft_doc::Docu
|
||||
let importer = opts.chunks?;
|
||||
let chunk = AltChunk { content_type: shared_chunk.content_type, part: shared_chunk.part, bytes: shared_chunk.bytes };
|
||||
let doc = importer(&chunk)?;
|
||||
match to_shared_model(&doc) {
|
||||
Ok(shared) => Some(shared),
|
||||
Err(e) => {
|
||||
log::warn!("docx: dropping alt chunk {}: {e}", chunk.part);
|
||||
None
|
||||
}
|
||||
}
|
||||
to_shared_model(&doc).ok()
|
||||
};
|
||||
|
||||
let shared_opts =
|
||||
@@ -112,10 +106,7 @@ pub fn chart_items(spec: &wordcraft_doc::chart::ChartSpec, theme: &[wordcraft_do
|
||||
return Vec::new();
|
||||
};
|
||||
let shared_items = craft_docx::chart_items(&shared_spec, &shared_theme, w, h);
|
||||
model_bridge::convert(shared_items).unwrap_or_else(|e| {
|
||||
log::warn!("docx: chart items could not be converted: {e}");
|
||||
Vec::new()
|
||||
})
|
||||
model_bridge::convert(shared_items).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Write a chart part.
|
||||
@@ -140,10 +131,7 @@ pub fn smart_art_items(
|
||||
return Vec::new();
|
||||
};
|
||||
let shared_items = craft_docx::smart_art_items(&shared_spec, &shared_theme, w, h);
|
||||
model_bridge::convert(shared_items).unwrap_or_else(|e| {
|
||||
log::warn!("docx: smart art items could not be converted: {e}");
|
||||
Vec::new()
|
||||
})
|
||||
model_bridge::convert(shared_items).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Read bibliography sources from a `b:Sources` file.
|
||||
|
||||
@@ -363,10 +363,8 @@ fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
|
||||
return Err(CmdError::Failed("the member vanished".into()));
|
||||
}
|
||||
let text = f.clipboard_text();
|
||||
let r = super::edit::copy_result(s, f, text)?;
|
||||
if let Some(f) = &s.clipboard {
|
||||
s.clip_history.push(f, &s.clipboard_text);
|
||||
}
|
||||
let r = super::edit::copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::math_edit::MathPos;
|
||||
use wordcraft_doc::para::{NBSP, OBJ};
|
||||
use wordcraft_doc::props::TextDirection;
|
||||
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
|
||||
use wordcraft_layout::ViewMode;
|
||||
|
||||
@@ -114,47 +113,6 @@ fn bidi_para(s: &Session) -> bool {
|
||||
|
||||
/// Left/Right: with a selection and no Shift, collapse to its edge.
|
||||
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
if let Some(t) = turn(s) {
|
||||
// Vertical text (#8986): Left/Right change line; top-to-bottom lines stack leftwards.
|
||||
return line_step(s, v, (t == TextDirection::Down) == is_left, is_left);
|
||||
}
|
||||
lr_along(s, v, is_left)
|
||||
}
|
||||
|
||||
/// The text direction at the caret when it is in turned (vertical) text.
|
||||
fn turn(s: &mut Session) -> Option<TextDirection> {
|
||||
let l = s.layout();
|
||||
l.turn_at(&s.sel.focus, s.page_hint)
|
||||
}
|
||||
|
||||
/// Vertical text: to the next (`next`) or previous line, at the same distance along it. With no
|
||||
/// such line in the caret's flow (a table cell's only line, the last column), Left/Right step along
|
||||
/// the text as they did before (`is_left`: backwards).
|
||||
fn line_step(s: &mut Session, v: &Value, next: bool, is_left: bool) -> CmdResult {
|
||||
let ext = extend(v);
|
||||
if !ext && !s.sel.is_collapsed() {
|
||||
let (a, b) = s.sel.ordered();
|
||||
s.sel = Selection::caret(if next { b } else { a });
|
||||
s.goal_x = None;
|
||||
return sel_result(s);
|
||||
}
|
||||
let l = s.layout();
|
||||
let from = s.sel.focus.clone();
|
||||
let to = match l.turned_line(&from, s.goal_x, next, s.page_hint) {
|
||||
Some((p, g)) => {
|
||||
s.goal_x = Some(g);
|
||||
p
|
||||
}
|
||||
None => return lr_along(s, v, is_left),
|
||||
};
|
||||
let gx = s.goal_x;
|
||||
apply(s, to, ext);
|
||||
s.goal_x = gx;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Left/Right as a step along the text (`is_left`: backwards).
|
||||
fn lr_along(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
let ext = extend(v);
|
||||
if !ext && !s.sel.is_collapsed() {
|
||||
let (a, b) = s.sel.ordered();
|
||||
@@ -305,7 +263,7 @@ fn step_to_neighbor(s: &Session, from: &Pos, is_left: bool, skip_deleted: bool)
|
||||
Pos { story, path, off }
|
||||
}
|
||||
|
||||
fn visible_word_start(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) -> bool) -> Option<usize> {
|
||||
fn visible_word_start(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
let off = para.clamp(off);
|
||||
let byte = off.checked_sub(1)?;
|
||||
let (i, range) = run_at_byte(para, byte)?;
|
||||
@@ -317,7 +275,7 @@ fn visible_word_start(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>)
|
||||
let start = end.saturating_sub(run.len);
|
||||
let range_end = end.min(off);
|
||||
end = start;
|
||||
if hides(run.props.del) {
|
||||
if run.props.del.is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(slice) = para.text.get(start..range_end) else { continue };
|
||||
@@ -336,7 +294,7 @@ fn visible_word_start(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>)
|
||||
seen_visible.then_some(idx)
|
||||
}
|
||||
|
||||
fn visible_word_end(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) -> bool) -> Option<usize> {
|
||||
fn visible_word_end(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
let off = para.clamp(off);
|
||||
let (i, range) = run_at_byte(para, off)?;
|
||||
let mut first_word = None;
|
||||
@@ -347,7 +305,7 @@ fn visible_word_end(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) ->
|
||||
let run_end = run_start.saturating_add(run.len);
|
||||
let start = run_start.max(off);
|
||||
run_start = run_end;
|
||||
if hides(run.props.del) {
|
||||
if run.props.del.is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(slice) = para.text.get(start..run_end) else { continue };
|
||||
@@ -370,10 +328,9 @@ fn visible_word_end(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) ->
|
||||
}
|
||||
|
||||
fn word_left(s: &mut Session, p: &Pos) -> Pos {
|
||||
let hidden = s.layout_hides_deleted(p.story);
|
||||
if let Some(para) = s.doc.para_at(p) {
|
||||
if hidden.any() {
|
||||
if let Some(off) = visible_word_start(para, p.off, |del| hidden.hides(&s.doc, del)) {
|
||||
if !s.view.show_markup {
|
||||
if let Some(off) = visible_word_start(para, p.off) {
|
||||
return Pos { off, ..p.clone() };
|
||||
}
|
||||
} else if p.off > 0 {
|
||||
@@ -384,10 +341,9 @@ fn word_left(s: &mut Session, p: &Pos) -> Pos {
|
||||
}
|
||||
|
||||
fn word_right(s: &mut Session, p: &Pos) -> Pos {
|
||||
let hidden = s.layout_hides_deleted(p.story);
|
||||
if let Some(para) = s.doc.para_at(p) {
|
||||
if hidden.any() {
|
||||
if let Some(off) = visible_word_end(para, p.off, |del| hidden.hides(&s.doc, del)) {
|
||||
if !s.view.show_markup {
|
||||
if let Some(off) = visible_word_end(para, p.off) {
|
||||
return Pos { off, ..p.clone() };
|
||||
}
|
||||
} else if p.off < para.len() {
|
||||
@@ -418,10 +374,6 @@ fn para_down(s: &mut Session, p: &Pos) -> Pos {
|
||||
}
|
||||
|
||||
fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
if let Some(t) = turn(s) {
|
||||
// Vertical text (#8986): Up/Down step along the line (top-to-bottom text runs down).
|
||||
return lr_along(s, v, (dir < 0) == (t == TextDirection::Down));
|
||||
}
|
||||
let ext = extend(v);
|
||||
let l = s.layout();
|
||||
let from = s.sel.focus.clone();
|
||||
@@ -436,7 +388,7 @@ fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
}
|
||||
};
|
||||
if let Some(c) = l.caret_on(&to, s.page_hint) {
|
||||
s.set_page_hint(c.page);
|
||||
s.page_hint = c.page;
|
||||
}
|
||||
let gx = s.goal_x;
|
||||
apply(s, to, ext);
|
||||
@@ -488,7 +440,7 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
} else {
|
||||
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
|
||||
};
|
||||
s.set_page_hint(np);
|
||||
s.page_hint = np;
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
}
|
||||
@@ -511,7 +463,7 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let story = super::story_param(s, v);
|
||||
let l = s.layout();
|
||||
let page = usize::try_from(pg).unwrap_or(usize::MAX);
|
||||
s.set_page_hint(page);
|
||||
s.page_hint = page;
|
||||
l.hit(page, x, y, story).ok_or_else(|| CmdError::Params("no text on that page".into()))?
|
||||
} else {
|
||||
return Err(CmdError::Params("`pos` or `page`/`x`/`y` required".into()));
|
||||
|
||||
@@ -26,7 +26,6 @@ use generated::ENTRY_STYLE;
|
||||
pub(crate) use generated::generated_list;
|
||||
use generated::table_of_figures;
|
||||
pub use generated::{figures_instr, update_generated};
|
||||
pub(super) use generated::{is_list_entry, wrapped_list};
|
||||
pub use render::{cite, entry};
|
||||
pub use sources::update_citations;
|
||||
use sources::{citation, sources};
|
||||
|
||||
@@ -65,7 +65,6 @@ fn generated_list_with(s: &mut Session, instr: &str, title: &str, leader: Option
|
||||
seed.props.tabs = Some(vec![TabStop { pos: 0.0, align: TabAlign::Right, leader }]);
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i.saturating_add(1)), Block::Para(seed))?;
|
||||
}
|
||||
s.touch();
|
||||
update_generated(s)
|
||||
}
|
||||
|
||||
@@ -75,7 +74,7 @@ const MAX_WRAPPED: usize = 10_000;
|
||||
/// A generated list (index, bibliography, table of figures or authorities) held as a complex
|
||||
/// field that starts at body block `i` and runs over its entries: its field code and the block
|
||||
/// it ends in. `None` for anything else (a TOC has its own update).
|
||||
pub(in crate::cmd) fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> {
|
||||
fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> {
|
||||
let p = s.doc.body.get(i)?.as_para()?;
|
||||
let (k, off, instr) = p.objects_with_offsets().enumerate().find_map(|(k, (off, o))| match o {
|
||||
InlineObject::FieldStart { instr, .. } => {
|
||||
@@ -198,15 +197,9 @@ fn caption_body(p: &Paragraph, label: &str) -> String {
|
||||
|
||||
pub(super) const ENTRY_STYLE: &str = "ListEntry";
|
||||
|
||||
/// A result paragraph can share its style with a field header split out of an imported list.
|
||||
pub(in crate::cmd) fn is_list_entry(p: &Paragraph) -> bool {
|
||||
p.props.style.as_deref() == Some(ENTRY_STYLE) && list_kind(p).is_none()
|
||||
}
|
||||
|
||||
/// Rebuild every generated list.
|
||||
pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
let mut i = 0;
|
||||
let mut relocated_index_leader = None;
|
||||
while i < s.doc.body.len() {
|
||||
// A list held as a field around its entries (as Word and ODT files hold them): made the
|
||||
// field's own paragraph, as WordCraft inserts one, its old entries rebuilt below.
|
||||
@@ -214,11 +207,7 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
// break, are the document's and stay.
|
||||
// (The field it is made: what comes before it in its paragraph may hold other fields.)
|
||||
let mut converted = None;
|
||||
let mut index_leader = None;
|
||||
if let Some((instr, start, last, end)) = wrapped_list(s, i) {
|
||||
if instr.starts_with("INDEX") {
|
||||
index_leader = crate::cmd::index::wrapped_entry_leader(s, i, start, last, end);
|
||||
}
|
||||
// The entries between its first and last paragraphs go.
|
||||
for _ in i.saturating_add(1)..last {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
|
||||
@@ -258,14 +247,9 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(i))?;
|
||||
if p.objects_with_offsets().any(|(off, o)| off < start && list_field(o).is_some()) {
|
||||
let list = p.split_off(start)?;
|
||||
// Rebuilding the preceding list can shift the new paragraph's block index.
|
||||
if let Some(leader) = index_leader.take() {
|
||||
relocated_index_leader = Some((list.rev, leader));
|
||||
}
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i + 1), Block::Para(list))?;
|
||||
converted = None;
|
||||
}
|
||||
s.touch();
|
||||
}
|
||||
let kind = converted.or_else(|| s.doc.body.get(i).and_then(|b| b.as_para()).and_then(list_kind));
|
||||
let Some(kind) = kind else {
|
||||
@@ -274,11 +258,7 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
};
|
||||
add_entry_style(s);
|
||||
if kind.starts_with("INDEX") {
|
||||
let index_leader = index_leader.or_else(|| {
|
||||
let rev = s.doc.body.get(i)?.as_para()?.rev;
|
||||
relocated_index_leader.take_if(|(relocated, _)| *relocated == rev).map(|(_, leader)| leader)
|
||||
});
|
||||
crate::cmd::index::rebuild_from(s, i, index_leader, kind)?;
|
||||
crate::cmd::index::rebuild_from(s, i, None, kind)?;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -310,11 +290,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
.body
|
||||
.get(i + 1)
|
||||
.and_then(|b| b.as_para())
|
||||
.filter(|p| is_list_entry(p))
|
||||
.filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE))
|
||||
.and_then(|p| p.props.tabs.as_ref()?.last().map(|t| t.leader))
|
||||
.or(saved_leader)
|
||||
.unwrap_or(TabLeader::Dot);
|
||||
while s.doc.body.get(i + 1).and_then(|b| b.as_para()).is_some_and(is_list_entry) {
|
||||
while s.doc.body.get(i + 1).and_then(|b| b.as_para()).is_some_and(|p| p.props.style.as_deref() == Some(ENTRY_STYLE)) {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
|
||||
}
|
||||
let lines = entries_for(s, &kind);
|
||||
@@ -330,7 +310,6 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
}
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i + 1 + k), Block::Para(para))?;
|
||||
}
|
||||
s.touch();
|
||||
i += 1;
|
||||
}
|
||||
s.touch();
|
||||
@@ -584,56 +563,4 @@ mod tests {
|
||||
assert_eq!(lists, [Some("INDEX".to_string()), Some("BIBLIOGRAPHY".to_string())]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapped_index_keeps_its_leader_when_split_from_a_bibliography() {
|
||||
let old_entry = "Old entry\t1";
|
||||
let mut s = wrapped("Old entry\t1\n\nKilns are hot.", 0, 0, old_entry.len());
|
||||
s.run("select.text", &serde_json::json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &serde_json::json!({})).unwrap();
|
||||
s.doc.sources.push(wordcraft_doc::Source { tag: "a".into(), kind: "book".into(), title: "Listed Source".into(), ..Default::default() });
|
||||
|
||||
let props = CharProps::default();
|
||||
let instr = "INDEX \\e \"\t\"";
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.objects[0] = InlineObject::FieldStart { instr: instr.into(), locked: false, dirty: false };
|
||||
p.insert_object(
|
||||
0,
|
||||
InlineObject::Field {
|
||||
instr: "BIBLIOGRAPHY".into(),
|
||||
result: String::new(),
|
||||
locked: false,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new(),
|
||||
},
|
||||
&props,
|
||||
)
|
||||
.unwrap();
|
||||
p.props.style = Some(ENTRY_STYLE.into());
|
||||
p.props.tabs = Some(vec![TabStop { pos: 120.0, align: TabAlign::Right, leader: TabLeader::Hyphen }]);
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
|
||||
// A separate INDEX with the same instruction has no prior result and must get the default.
|
||||
p.insert_object(
|
||||
0,
|
||||
InlineObject::Field { instr: instr.into(), result: String::new(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
&props,
|
||||
)
|
||||
.unwrap();
|
||||
s.touch();
|
||||
let (_, start, last, end) = wrapped_list(&s, 0).unwrap();
|
||||
assert_eq!(crate::cmd::index::wrapped_entry_leader(&mut s, 0, start, last, end), Some(TabLeader::Hyphen));
|
||||
|
||||
for _ in 0..2 {
|
||||
update_generated(&mut s).unwrap();
|
||||
let paras: Vec<_> = s.doc.body.iter().filter_map(|b| b.as_para()).collect();
|
||||
assert_eq!(list_kind(paras[0]).as_deref(), Some("BIBLIOGRAPHY"));
|
||||
assert!(paras[1].plain_text().contains("Listed Source"), "the bibliography inserts an entry before the relocated index");
|
||||
for (header, leader) in [(2, TabLeader::Hyphen), (4, TabLeader::Dot)] {
|
||||
assert_eq!(list_kind(paras[header]).as_deref(), Some(instr));
|
||||
assert_eq!(paras[header + 1].plain_text(), "Kilns\t1");
|
||||
assert_eq!(paras[header + 1].props.tabs.as_ref().unwrap()[0].leader, leader);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,7 +247,7 @@ fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
|
||||
let text = rows.join("\n");
|
||||
let media = s.doc.media_of_blocks(&blocks);
|
||||
let f = Fragment { blocks, parts, media };
|
||||
super::edit::copy_result(s, f, text)
|
||||
super::edit::copy_result(s, &f, &text)
|
||||
}
|
||||
|
||||
/// Delete each row's piece (bottom up, so earlier positions stay valid) and leave the caret at
|
||||
|
||||
@@ -332,6 +332,7 @@ mod tests {
|
||||
|
||||
/// Drawing commands must not search every page again for each glued connector.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn rerouting_many_pages_does_not_rescan_all_objects_per_connector() {
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
fn glued_pages(n: u32) -> Session {
|
||||
@@ -362,33 +363,34 @@ mod tests {
|
||||
assert_eq!(s.layout().pages.len(), n as usize);
|
||||
s
|
||||
}
|
||||
const SMALL: u32 = 32;
|
||||
const SCALE: u32 = 8;
|
||||
let mut small = glued_pages(SMALL);
|
||||
let mut big = glued_pages(SMALL * SCALE);
|
||||
let layout = big.layout();
|
||||
let small_steps = wordcraft_doc::work::count(|| assert!(reroute(&mut small)));
|
||||
let big_steps = wordcraft_doc::work::count(|| assert!(reroute(&mut big)));
|
||||
// One layout walk to build the index plus bounded work per connector: roughly 8x the
|
||||
// steps for 8x the pages. Allow room for fixed differences in the first and last pages.
|
||||
let budget = small_steps * 12;
|
||||
assert!(small_steps > 0 && big_steps > small_steps, "reroute steps: {small_steps} -> {big_steps}");
|
||||
assert!(big_steps <= budget, "reroute repeated lookup work: {small_steps} -> {big_steps} steps for {SCALE}x pages");
|
||||
|
||||
// The previous lookup starts at the caret's page for every connector. Run just that
|
||||
// part of the old route to verify it would exceed the same budget on this fixture.
|
||||
let connector_off = 2 * wordcraft_doc::para::OBJ.len_utf8();
|
||||
let scan_steps = wordcraft_doc::work::count(|| {
|
||||
for page in 0..layout.pages.len() {
|
||||
let hit = layout.object(&Pos::body(page, connector_off), 0).unwrap();
|
||||
assert_eq!(hit.page, page);
|
||||
// Use the running thread's CPU time on Linux; scheduler pauses are not reroute work.
|
||||
fn cpu_cost(mut f: impl FnMut()) -> f64 {
|
||||
let ran = || std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse::<u64>().ok();
|
||||
let (wall, before) = (std::time::Instant::now(), ran());
|
||||
f();
|
||||
match (before, ran()) {
|
||||
(Some(a), Some(b)) if b > a => (b - a) as f64 * 1e-9,
|
||||
_ => wall.elapsed().as_secs_f64(),
|
||||
}
|
||||
});
|
||||
assert!(scan_steps > budget, "per-connector scans took only {scan_steps} steps for a budget of {budget}");
|
||||
|
||||
}
|
||||
const SMALL: u32 = 500;
|
||||
const SCALE: u32 = 8;
|
||||
let (mut small_min, mut big_min) = (f64::INFINITY, f64::INFINITY);
|
||||
let mut last_big = None;
|
||||
for _ in 0..3 {
|
||||
let mut small = glued_pages(SMALL);
|
||||
small_min = small_min.min(cpu_cost(|| assert!(reroute(&mut small))));
|
||||
let mut big = glued_pages(SMALL * SCALE);
|
||||
big_min = big_min.min(cpu_cost(|| assert!(reroute(&mut big))));
|
||||
last_big = Some(big);
|
||||
}
|
||||
let ratio = big_min / small_min.max(1e-9);
|
||||
eprintln!("{SMALL} vs {} pages reroute: {small_min:.4}s vs {big_min:.4}s (ratio {ratio:.2}x)", SMALL * SCALE);
|
||||
assert!(ratio < SCALE as f64 * 3.0, "reroute scaled superlinearly: {small_min:.4}s -> {big_min:.4}s ({ratio:.2}x for {SCALE}x pages)");
|
||||
let mut big = last_big.unwrap();
|
||||
for path in big.doc.para_paths(StoryRef::Body) {
|
||||
let para = big.doc.para(StoryRef::Body, &path).unwrap();
|
||||
let InlineObject::Shape { w, h, float, .. } = para.object_at(connector_off).unwrap() else { panic!("connector") };
|
||||
let InlineObject::Shape { w, h, float, .. } = para.object_at(6).unwrap() else { panic!("connector") };
|
||||
assert_eq!((*w, *h, float.x, float.y), (160.0, 0.0, 140.0, 210.0));
|
||||
}
|
||||
big.touch();
|
||||
|
||||
@@ -7,9 +7,6 @@ use wordcraft_doc::{Path, Pos, StoryRef};
|
||||
use super::{delete_selection, find_pattern, pos_json, sel_result};
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
|
||||
/// Ribbon location of the linked Cut, Copy and Paste commands.
|
||||
pub const LINKED_CLIPBOARD_LOCATION: &str = "Home › Clipboard";
|
||||
|
||||
/// Browsers reserve Mod+Shift+C for their inspector. Keep the desktop binding, but
|
||||
/// advertise a web alternative through the same registry/keymap as every other command.
|
||||
/// Mod+Alt+C already inserts copyright, and Mod+Alt+Shift+V is Keep Text Only.
|
||||
@@ -75,8 +72,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
.key("Mod+Y / Mod+Shift+Z")
|
||||
.pure(),
|
||||
CommandSpec::new("edit.cut", "Cut", LINKED_CLIPBOARD_LOCATION, cut).key("Mod+X").when(has_sel),
|
||||
CommandSpec::new("edit.copy", "Copy", LINKED_CLIPBOARD_LOCATION, copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
|
||||
CommandSpec::new("edit.cut", "Cut", "Home › Clipboard", cut).key("Mod+X").when(has_sel),
|
||||
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
|
||||
// Word's Spike (Ctrl+F3, Ctrl+Shift+F3; ⌘ on the Mac): the AutoText entry "Spike", so Quick
|
||||
// Parts and AutoText insert it without emptying it, as in Word.
|
||||
CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_text_sel),
|
||||
@@ -89,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Some("the Spike is empty")
|
||||
}
|
||||
}),
|
||||
CommandSpec::new("edit.paste", "Paste", LINKED_CLIPBOARD_LOCATION, paste)
|
||||
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste)
|
||||
.key("Mod+V / Shift+Insert")
|
||||
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool}"#),
|
||||
CommandSpec::new("edit.pasteNestedTable", "Paste as Nested Table", "Home › Clipboard › Paste", paste_nested)
|
||||
@@ -212,10 +209,8 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
|
||||
None => s.doc.copy_range(&a, &b),
|
||||
};
|
||||
let text = f.clipboard_text();
|
||||
let r = copy_result(s, f, text)?;
|
||||
if let Some(f) = &s.clipboard {
|
||||
s.clip_history.push(f, &s.clipboard_text);
|
||||
}
|
||||
let r = copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -225,7 +220,7 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
|
||||
///
|
||||
/// The copy goes on the clipboard whole or not at all: a copy whose HTML or RTF cannot be made
|
||||
/// is refused, and the clipboard keeps what it held.
|
||||
pub(crate) fn copy_result(s: &mut Session, f: Fragment, text: String) -> CmdResult {
|
||||
pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResult {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
@@ -248,8 +243,8 @@ pub(crate) fn copy_result(s: &mut Session, f: Fragment, text: String) -> CmdResu
|
||||
}
|
||||
// The copy is on the clipboard now: its text, its fragment and its HTML and RTF flavours,
|
||||
// all at once.
|
||||
s.clipboard_text = text;
|
||||
s.clipboard = Some(f);
|
||||
s.clipboard_text = text.to_string();
|
||||
s.clipboard = Some(f.clone());
|
||||
s.clipboard_html = html;
|
||||
s.clipboard_rtf = rtf;
|
||||
Ok(r)
|
||||
@@ -862,20 +857,9 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
found.push(results);
|
||||
}
|
||||
let n: usize = found.iter().map(Vec::len).sum();
|
||||
let saved_sel = s.sel.clone();
|
||||
let orig_story = saved_sel.focus.story;
|
||||
let mut orig_story_sel = None;
|
||||
// The main text comes last, so under Track Changes keep the selection from the caret's own
|
||||
// story (or restore the saved selection if that story had no match, #9063 / #9186).
|
||||
// The main text comes last, so under Track Changes the caret ends where it did before.
|
||||
for results in found.into_iter().rev() {
|
||||
let is_orig = results[0].a.story == orig_story;
|
||||
replace_found(s, results)?;
|
||||
if s.doc.settings.track_changes && is_orig {
|
||||
orig_story_sel = Some(s.sel.clone());
|
||||
}
|
||||
}
|
||||
if s.doc.settings.track_changes {
|
||||
s.sel = orig_story_sel.unwrap_or(saved_sel);
|
||||
}
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
|
||||
@@ -70,8 +70,6 @@ fn rename(s: &mut Session, v: &Value) -> CmdResult {
|
||||
{
|
||||
crate::io::rename_file(path, &destination).map_err(CmdError::Failed)?;
|
||||
}
|
||||
// Renamed, the file is the same one, with the same size and modified time: the stamp
|
||||
// taken when it was read or saved still says whether another program changed it.
|
||||
s.path = Some(destination);
|
||||
s.relayout();
|
||||
}
|
||||
@@ -96,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("file.save", "Save", "File", save)
|
||||
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
|
||||
.params(r#"{"path"?: string (required with `copy`), "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy at `path`, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`), "ifUnchanged"?: bool (AutoSave: refuse, writing nothing, if the document's own file was changed or removed by another program since it was opened or saved here)}"#)
|
||||
.params(r#"{"path"?: string (required with `copy`), "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy at `path`, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save), "copy"?: bool (as file.save)}"#).pure(),
|
||||
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
|
||||
@@ -258,9 +256,6 @@ fn open(s: &mut Session, v: &Value) -> CmdResult {
|
||||
);
|
||||
}
|
||||
let password = p::str(v, "password");
|
||||
// How the file looks before it is read (none for bytes passed in): one another program
|
||||
// replaces while it is being read then no longer matches, and AutoSave leaves it (#7069).
|
||||
let disk_stamp = if p::str(v, "data").is_none() { crate::io::file_stamp(std::path::Path::new(path)) } else { None };
|
||||
// An empty file opens as a new blank document that saves back to it (#1384).
|
||||
let (doc, encrypted) = read_document(s, path, v)?;
|
||||
match s.used_because() {
|
||||
@@ -274,7 +269,6 @@ fn open(s: &mut Session, v: &Value) -> CmdResult {
|
||||
super::view::restore_zoom(s, z);
|
||||
}
|
||||
s.path = Some(path.into());
|
||||
s.disk_stamp = disk_stamp;
|
||||
// A Markdown file's own text, for the view to show and Save to write back as it is.
|
||||
if super::md_source::is_markdown_file(std::path::Path::new(path)) {
|
||||
s.md_file = markdown_file_text(path, v);
|
||||
@@ -417,24 +411,6 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
};
|
||||
check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?;
|
||||
// AutoSave (`ifUnchanged`) never writes over the document's own file once another program has
|
||||
// changed it since the document was read from it or last saved to it: that program's changes
|
||||
// would be lost without a word (#7069). Checked again just before the new bytes replace the
|
||||
// file (`unchanged`); first here, so a changed file costs no serializing. A save the user asks
|
||||
// for writes as before.
|
||||
let own_conditional = p::bool(v, "ifUnchanged") == Some(true) && s.path.as_deref() == Some(path.as_path());
|
||||
let unchanged = if own_conditional { s.disk_stamp } else { None };
|
||||
let name = || path.file_name().map_or_else(|| path.to_string_lossy(), |n| n.to_string_lossy()).to_string();
|
||||
// Without a record of how the file looked (it was missing a moment when it was read, say),
|
||||
// nothing says another program left it alone: no conditional write over it.
|
||||
if own_conditional && unchanged.is_none() {
|
||||
return Err(CmdError::Failed(format!("{} could not be checked against the file as it was opened or saved here", name())));
|
||||
}
|
||||
if let Some(stamp) = unchanged
|
||||
&& crate::io::file_stamp(&path) != Some(stamp)
|
||||
{
|
||||
return Err(CmdError::Failed(format!("{} was changed or removed by another program after it was opened or saved here", name())));
|
||||
}
|
||||
if as_copy && v.get("password").is_some_and(|pw| !pw.is_null()) {
|
||||
return Err(CmdError::Params("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into()));
|
||||
}
|
||||
@@ -477,19 +453,15 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let exact = super::md_source::text_to_save(s, &path, opts.markup);
|
||||
let rewritten = exact.is_none() && !s.md_file.is_empty() && super::md_source::is_markdown_file(&path);
|
||||
let written = match &exact {
|
||||
Some(text) => crate::io::save_text_path_checked(&path, text, unchanged),
|
||||
None => crate::io::save_path_checked(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts, unchanged),
|
||||
Some(text) => crate::io::save_text_path(&path, text),
|
||||
None => crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts),
|
||||
};
|
||||
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
|
||||
if written.is_err() || as_copy {
|
||||
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
|
||||
}
|
||||
let stamp = written.map_err(CmdError::Failed)?;
|
||||
written.map_err(CmdError::Failed)?;
|
||||
if as_copy {
|
||||
// A copy over the document's own file is the file now: what AutoSave checks against.
|
||||
if s.path.as_deref() == Some(path.as_path()) {
|
||||
s.disk_stamp = Some(stamp);
|
||||
}
|
||||
return Ok(json!({"saved": true, "path": path.to_string_lossy(), "encrypted": encrypted, "copy": true}));
|
||||
}
|
||||
// A save in a format that doesn't keep everything (plain text, Markdown, a page image) is a
|
||||
@@ -499,8 +471,6 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let markdown_to_markdown = super::md_source::is_markdown_file(&path) && s.path.as_deref().is_some_and(super::md_source::is_markdown_file);
|
||||
if own_file || markdown_to_markdown || ["docx", "docm", "dotx", "dotm", "odt", "ott", "fodt", "rtf", "json", "xml"].contains(&ext.as_str()) {
|
||||
s.path = Some(path.clone());
|
||||
// The file this save wrote, not whatever is there by the time it is looked at again.
|
||||
s.disk_stamp = Some(stamp);
|
||||
s.dirty = false;
|
||||
s.relayout();
|
||||
// What the file holds now.
|
||||
|
||||
@@ -221,7 +221,7 @@ fn strip_row(r: &RowProps) -> RowProps {
|
||||
RowProps { fmt_change: None, ..r.clone() }
|
||||
}
|
||||
fn strip_cell(c: &CellProps) -> CellProps {
|
||||
CellProps { fmt_change: None, merge_change: None, span: 0, vmerge: VMerge::None, ..c.clone() }
|
||||
CellProps { fmt_change: None, span: 0, vmerge: VMerge::None, ..c.clone() }
|
||||
}
|
||||
fn strip_section(s: &SectionProps) -> SectionProps {
|
||||
SectionProps { fmt_change: None, headers: Default::default(), footers: Default::default(), ..s.clone() }
|
||||
@@ -457,13 +457,10 @@ pub fn resolve_row(r: &mut Row, accept: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept or reject a cell's changes. Merges are the table's structure, not formatting: they stay.
|
||||
/// A tracked merge or split of the cell is dropped either way, its cells left as they are (Word
|
||||
/// for Windows).
|
||||
/// Accept or reject a cell's change. Merges are the table's structure, not formatting: they stay.
|
||||
pub fn resolve_cell(c: &mut Cell, accept: bool) {
|
||||
c.props.merge_change = None;
|
||||
if let Some(ch) = c.props.fmt_change.take().filter(|_| !accept) {
|
||||
c.props = CellProps { fmt_change: None, merge_change: None, span: c.props.span, vmerge: c.props.vmerge, ..ch.old };
|
||||
c.props = CellProps { fmt_change: None, span: c.props.span, vmerge: c.props.vmerge, ..ch.old };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,11 +510,6 @@ pub fn row_diff(r: &RowProps) -> Vec<Value> {
|
||||
pub fn cell_diff(c: &CellProps) -> Vec<Value> {
|
||||
c.fmt_change
|
||||
.as_ref()
|
||||
.map(|ch| {
|
||||
diff(
|
||||
&CellProps { fmt_change: None, merge_change: None, ..ch.old.clone() },
|
||||
&CellProps { fmt_change: None, merge_change: None, ..c.clone() },
|
||||
)
|
||||
})
|
||||
.map(|ch| diff(&CellProps { fmt_change: None, ..ch.old.clone() }, &CellProps { fmt_change: None, ..c.clone() }))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -186,23 +186,6 @@ pub fn missing_fonts(doc: &Document, layout: &DocLayout) -> Vec<MissingFont> {
|
||||
out.into_values().collect()
|
||||
}
|
||||
|
||||
/// Core Word fonts that actually need a non-metric substitute in a PDF or first-page PNG.
|
||||
pub fn output_metric_font_notices(s: &Session, markup: bool, first_page_png: bool) -> Vec<(&'static str, String)> {
|
||||
if first_page_png {
|
||||
let layout = s.export_layout_with(markup);
|
||||
return metric_font_notices(layout.pages.get(..1).unwrap_or(&[]));
|
||||
}
|
||||
let opts = super::file::export_options(s, &json!({"markup": markup}));
|
||||
let out = super::references::output_fields(&s.doc);
|
||||
let doc = out.as_ref().unwrap_or(&s.doc);
|
||||
let layout = crate::strict::pdf_layout(doc, &crate::strict::pdf_options(&opts));
|
||||
metric_font_notices(&layout.pages)
|
||||
}
|
||||
|
||||
fn metric_font_notices(pages: &[wordcraft_layout::Page]) -> Vec<(&'static str, String)> {
|
||||
DocLayout::metric_font_notices_on(pages).into_iter().map(|(core, face)| (core, face.family.clone())).collect()
|
||||
}
|
||||
|
||||
/// A font name as [`missing_fonts`] lists it: as layout records it (at most 256 characters),
|
||||
/// trimmed.
|
||||
fn shown_name(font: &str) -> &str {
|
||||
|
||||
@@ -956,28 +956,17 @@ pub fn state(s: &Session) -> Value {
|
||||
(*cached_state(s)).clone()
|
||||
}
|
||||
|
||||
/// The common East Asian family shown by the font controls. A theme slot without a face uses
|
||||
/// the run's ordinary font, as layout does. Resolve each theme slot once per selection.
|
||||
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> (Option<&'a str>, bool) {
|
||||
/// The common East Asian family shown by the font controls. If a slot has no face, keep
|
||||
/// showing the named font. Resolve each theme slot once even for a selection with many runs.
|
||||
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> Option<&'a str> {
|
||||
let mut themes = HashMap::new();
|
||||
let mut fonts = runs.iter().map(|run| match run.font_ea_theme {
|
||||
Some(slot) => {
|
||||
let face = *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run));
|
||||
(Some(face.unwrap_or(&run.font)), face.is_some())
|
||||
}
|
||||
None => {
|
||||
let face = run.font_ea.as_deref();
|
||||
(face, face.is_some_and(|name| !name.trim().is_empty()))
|
||||
}
|
||||
let mut fonts = runs.iter().map(|run| {
|
||||
run.font_ea_theme
|
||||
.and_then(|slot| *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run)))
|
||||
.or(run.font_ea.as_deref())
|
||||
});
|
||||
let Some((Some(first), mut named)) = fonts.next() else { return (None, false) };
|
||||
for (font, from_named_face) in fonts {
|
||||
if font != Some(first) {
|
||||
return (None, false);
|
||||
}
|
||||
named |= from_named_face;
|
||||
}
|
||||
(Some(first), named)
|
||||
let first = fonts.next().flatten()?;
|
||||
fonts.all(|font| font == Some(first)).then_some(first)
|
||||
}
|
||||
|
||||
fn compute_state(s: &Session) -> Value {
|
||||
@@ -997,12 +986,10 @@ fn compute_state(s: &Session) -> Value {
|
||||
// characters the substitute lacks. `font.missing` lists every face the shown text is drawn
|
||||
// in, fallback faces too, and which fonts change the layout.
|
||||
let shown_as = font.as_str().and_then(|f| crate::cmd::font::shown_as(&s.doc, f));
|
||||
let (font_ea, named_east_asian) = selection_east_asian_font(&s.doc, &all);
|
||||
json!({
|
||||
"font": font,
|
||||
"fontShownAs": shown_as,
|
||||
"fontEastAsia": font_ea,
|
||||
"namedEastAsianFont": named_east_asian,
|
||||
"fontEastAsia": selection_east_asian_font(&s.doc, &all),
|
||||
"size": same(&|r| json!(r.size)),
|
||||
"bold": all.iter().all(shown_bold),
|
||||
"italic": all.iter().all(shown_italic),
|
||||
|
||||
@@ -9,8 +9,6 @@ use wordcraft_doc::para::InlineObject;
|
||||
use wordcraft_doc::props::{CharProps, TabAlign, TabLeader, TabStop};
|
||||
use wordcraft_doc::section::SectionStart;
|
||||
use wordcraft_doc::{Block, Paragraph, Path, Pos, StoryRef};
|
||||
use wordcraft_layout::para::ClKind;
|
||||
use wordcraft_layout::{DocLayout, Placed, ViewMode};
|
||||
|
||||
use super::references::{FieldCode, field_arg, leader, page_at, page_formats, page_text};
|
||||
use super::sel_result;
|
||||
@@ -138,98 +136,6 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
|
||||
})
|
||||
}
|
||||
|
||||
fn laid_out_leader(layout: &DocLayout, path: Path, offset: usize) -> Option<TabLeader> {
|
||||
layout.index.get(&(StoryRef::Body, path))?.iter().find_map(|&(page, item)| {
|
||||
let Placed::Lines { para, l0, l1, .. } = layout.pages.get(page)?.items.get(item)? else { return None };
|
||||
para.lines.get(*l0..*l1)?.iter().find_map(|line| {
|
||||
let tab = (line.c0..line.c1).find(|&i| para.clusters.get(i).is_some_and(|c| c.start == offset && c.kind == ClKind::Tab))?;
|
||||
Some(line.leaders.iter().find(|&&(i, _)| i == tab).map_or(TabLeader::None, |&(_, leader)| leader))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Read the leader of the first page-number tab that is laid out. Layout chooses the next
|
||||
/// stop after the text, including inherited and non-right stops.
|
||||
fn entry_leader(s: &mut Session, tabs: &[(usize, usize)]) -> Option<TabLeader> {
|
||||
if tabs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let from_layout = |layout: &DocLayout| tabs.iter().find_map(|&(block, offset)| laid_out_leader(layout, Path::top(block), offset));
|
||||
// A screen view can reflow the index to a different width or hide its result.
|
||||
if !s.view.read_mode
|
||||
&& s.view.mode == ViewMode::Print
|
||||
&& !s.view.field_codes
|
||||
&& let Some(leader) = from_layout(&s.layout())
|
||||
{
|
||||
return Some(leader);
|
||||
}
|
||||
if let Some(leader) = from_layout(&s.output_layout_of(&s.doc, false, false)) {
|
||||
return Some(leader);
|
||||
}
|
||||
// Measure hidden separators without revealing other hidden text, which could move the tab
|
||||
// past a different stop. The measurement leaves the document and view unchanged.
|
||||
let mut measurement = s.doc.clone();
|
||||
for &(block, offset) in tabs {
|
||||
if let Ok(p) = measurement.para_mut(StoryRef::Body, &Path::top(block)) {
|
||||
let _ = p.format(offset, offset + 1, &|props| props.hidden = Some(false));
|
||||
}
|
||||
}
|
||||
if let Some(leader) = from_layout(&s.output_layout_of(&measurement, false, false)) {
|
||||
return Some(leader);
|
||||
}
|
||||
// If the tab is still absent, retain an unambiguous saved leader.
|
||||
let mut saved = tabs
|
||||
.iter()
|
||||
.filter_map(|&(block, _)| s.doc.body.get(block)?.as_para())
|
||||
.flat_map(|p| s.doc.styles.resolve_para(&p.props).tabs)
|
||||
.map(|tab| tab.leader);
|
||||
let leader = saved.next()?;
|
||||
saved.all(|other| other == leader).then_some(leader)
|
||||
}
|
||||
|
||||
fn inline_entry_leader(s: &mut Session, i: usize) -> Option<TabLeader> {
|
||||
let tabs: Vec<_> = s
|
||||
.doc
|
||||
.body
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(i + 1)
|
||||
.map_while(|(j, b)| Some((j, b.as_para().filter(|p| super::citations::is_list_entry(p))?)))
|
||||
.filter_map(|(j, p)| p.text.rfind('\t').map(|offset| (j, offset)))
|
||||
.collect();
|
||||
entry_leader(s, &tabs)
|
||||
}
|
||||
|
||||
/// Read the leader before replacing a wrapped INDEX result, within the field's bounds.
|
||||
pub(in crate::cmd) fn wrapped_entry_leader(s: &mut Session, i: usize, start: usize, last: usize, end: usize) -> Option<TabLeader> {
|
||||
let tabs: Vec<_> = (i..=last)
|
||||
.filter_map(|j| {
|
||||
let p = s.doc.body.get(j)?.as_para()?;
|
||||
let from = if j == i { start } else { 0 };
|
||||
let to = if j == last { end } else { p.len() };
|
||||
p.text.get(from..to)?.rfind('\t').map(|offset| (j, from + offset))
|
||||
})
|
||||
.collect();
|
||||
entry_leader(s, &tabs)
|
||||
}
|
||||
|
||||
/// The index Insert Index will update and the leader its current result shows.
|
||||
pub fn index_settings(s: &mut Session) -> Option<(FieldCode, Option<TabLeader>)> {
|
||||
if let Some((i, instr)) = index_field(s) {
|
||||
let leader = inline_entry_leader(s, i);
|
||||
return Some((FieldCode::parse(&instr), leader));
|
||||
}
|
||||
|
||||
(0..s.doc.body.len()).find_map(|i| {
|
||||
let (instr, start, last, end) = super::citations::wrapped_list(s, i)?;
|
||||
let field = FieldCode::parse(&instr);
|
||||
if field.name != "INDEX" {
|
||||
return None;
|
||||
}
|
||||
Some((field, wrapped_entry_leader(s, i, start, last, end)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an INDEX field (a plain one or a range field, as Word files hold it) sits in the main
|
||||
/// text's own paragraphs (`main`), or anywhere else a reader sees: a table cell, a text box, a
|
||||
/// header or a footer in use. Stored headers and footers no page shows (a first-page header
|
||||
@@ -282,7 +188,6 @@ fn range_index_after_text(s: &Session) -> bool {
|
||||
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let instr = index_instr(v);
|
||||
check_index_reachable(s)?;
|
||||
let leader = p::str(v, "tabLeader").map(leader).or_else(|| index_settings(s).and_then(|(_, leader)| leader)).unwrap_or(TabLeader::Dot);
|
||||
// An index Word wrote as a range field is first made a plain field in its own paragraph, as
|
||||
// Update Index makes it, so it takes the new settings rather than a second index being added
|
||||
// beside it (#8034).
|
||||
@@ -308,7 +213,7 @@ fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
None => super::citations::generated_list(s, &instr, "Index")?,
|
||||
}
|
||||
if let Some((i, _)) = index_field(s) {
|
||||
rebuild(s, i, Some(leader))?;
|
||||
rebuild(s, i, p::str(v, "tabLeader").map(leader))?;
|
||||
}
|
||||
s.clamp_selection();
|
||||
sel_result(s)
|
||||
@@ -434,18 +339,16 @@ pub fn rebuild(s: &mut Session, i: usize, leader: Option<TabLeader>) -> Result<(
|
||||
pub fn rebuild_from(s: &mut Session, i: usize, leader: Option<TabLeader>, instr: String) -> Result<(), CmdError> {
|
||||
let f = FieldCode::parse(&instr);
|
||||
// Old entries go; keep their leader and the section their columns had.
|
||||
let leader = leader.or_else(|| inline_entry_leader(s, i)).unwrap_or(TabLeader::Dot);
|
||||
let old_len = s.doc.body.len();
|
||||
let mut old_leader = None;
|
||||
let mut old_sect = None;
|
||||
while let Some(p) = s.doc.body.get(i + 1).and_then(|b| b.as_para()).filter(|p| super::citations::is_list_entry(p)) {
|
||||
while let Some(p) = s.doc.body.get(i + 1).and_then(|b| b.as_para()).filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE)) {
|
||||
old_leader = old_leader.or_else(|| p.props.tabs.as_ref().and_then(|t| t.last()).map(|t| t.leader));
|
||||
if p.section.is_some() {
|
||||
old_sect = p.section.clone();
|
||||
}
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
|
||||
}
|
||||
if s.doc.body.len() != old_len {
|
||||
s.touch();
|
||||
}
|
||||
let leader = leader.or(old_leader).unwrap_or(TabLeader::Dot);
|
||||
let cols = f.arg('c').and_then(|c| c.trim().parse::<u32>().ok()).unwrap_or(1).clamp(1, 4);
|
||||
let sep = f.arg('e').map(str::to_string).unwrap_or_else(|| ", ".into());
|
||||
let run_in = f.has('r');
|
||||
@@ -642,86 +545,6 @@ mod tests {
|
||||
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_keeps_the_leader_used_by_the_page_number_tab() {
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
|
||||
s.run("references.markEntry", &json!({"entry": "Kilns"})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({"rightAlign": true, "headings": false, "tabLeader": "hyphen"})).unwrap();
|
||||
let (i, _) = index_field(&s).unwrap();
|
||||
let path = Path::top(i + 1);
|
||||
assert_eq!(s.doc.para(StoryRef::Body, &path).unwrap().plain_text(), "Kilns\t1");
|
||||
|
||||
for (align, leader, inherit_later_stop) in
|
||||
[(TabAlign::Left, TabLeader::Underscore, false), (TabAlign::Right, TabLeader::Hyphen, true), (TabAlign::Left, TabLeader::None, true)]
|
||||
{
|
||||
let generated_pos = s.doc.para(StoryRef::Body, &path).unwrap().props.tabs.as_ref().unwrap()[0].pos;
|
||||
Arc::make_mut(&mut s.doc.styles).get_mut(ENTRY_STYLE).unwrap().para.tabs =
|
||||
inherit_later_stop.then(|| vec![TabStop { pos: generated_pos + 0.75, align: TabAlign::Right, leader: TabLeader::Dot }]);
|
||||
let entry = s.doc.para_mut(StoryRef::Body, &path).unwrap();
|
||||
// The text already runs past the first stop. The next one wins over the later style stop.
|
||||
entry.props.tabs = Some(vec![TabStop { pos: 5.0, align: TabAlign::Right, leader: TabLeader::Dot }, TabStop { pos: 90.0, align, leader }]);
|
||||
entry.touch();
|
||||
s.touch();
|
||||
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(leader), "{align:?}, {inherit_later_stop}");
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(leader), "kept on update: {align:?}, {inherit_later_stop}");
|
||||
}
|
||||
|
||||
// Updating an imported field consumes the result, so its tab must be read before conversion.
|
||||
let (_, instr) = index_field(&s).unwrap();
|
||||
let header = s.doc.para_mut(StoryRef::Body, &Path::top(i)).unwrap();
|
||||
let offset = header.object_offsets()[0];
|
||||
header.delete(0, offset).unwrap();
|
||||
header.objects[0] = InlineObject::FieldStart { instr, locked: false, dirty: false };
|
||||
header.touch();
|
||||
let entry = s.doc.para_mut(StoryRef::Body, &path).unwrap();
|
||||
entry.props.tabs = Some(vec![TabStop { pos: 90.0, align: TabAlign::Center, leader: TabLeader::Hyphen }]);
|
||||
entry.insert_object(entry.len(), InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
s.touch();
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(TabLeader::Hyphen));
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
assert!(s.doc.field_ranges(StoryRef::Body).is_empty());
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(TabLeader::Hyphen), "kept through wrapped field conversion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_keeps_the_page_number_leader_when_the_first_tab_is_hidden() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns and wheels."));
|
||||
s.view.marks = false;
|
||||
s.prefs.marks.hidden = false;
|
||||
for entry in ["Kilns", "Wheels"] {
|
||||
s.run("references.markEntry", &json!({"entry": entry})).unwrap();
|
||||
}
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({"rightAlign": true, "headings": false, "tabLeader": "hyphen"})).unwrap();
|
||||
let (i, _) = index_field(&s).unwrap();
|
||||
assert_eq!(index_lines(&s), ["Kilns\t1", "Wheels\t1"]);
|
||||
|
||||
for (first, second, hide_second, expected) in [
|
||||
(TabLeader::Dot, TabLeader::Hyphen, false, TabLeader::Hyphen),
|
||||
(TabLeader::Hyphen, TabLeader::Hyphen, true, TabLeader::Hyphen),
|
||||
(TabLeader::Hyphen, TabLeader::None, false, TabLeader::None),
|
||||
] {
|
||||
for (block, leader, hidden) in [(i + 1, first, true), (i + 2, second, hide_second)] {
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(block)).unwrap();
|
||||
p.props.tabs.as_mut().unwrap()[0].leader = leader;
|
||||
let tab = p.text.rfind('\t').unwrap();
|
||||
p.format(tab, tab + 1, &|props| props.hidden = Some(hidden)).unwrap();
|
||||
}
|
||||
s.touch();
|
||||
let l = s.layout();
|
||||
assert_eq!(laid_out_leader(&l, Path::top(i + 1), "Kilns".len()), None, "the hidden tab has no layout leader");
|
||||
assert_eq!(laid_out_leader(&l, Path::top(i + 2), "Wheels".len()), (!hide_second).then_some(second));
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(expected));
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(expected), "kept on update");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3670: an index in a table cell or a text box (as imported documents have it) can't be
|
||||
/// rebuilt where it is, so Insert and Update Index say so, and Insert Index doesn't add a
|
||||
/// second index at the caret.
|
||||
|
||||
@@ -14,7 +14,7 @@ mod links;
|
||||
mod objects;
|
||||
|
||||
pub(crate) use header_footer::saved_copy;
|
||||
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, remove_first_hf, strip_headers};
|
||||
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
|
||||
pub use items::{
|
||||
DropCapState, default_date_picture, default_time_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in,
|
||||
format_date_parts, format_date_parts_in,
|
||||
@@ -86,7 +86,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("insert.closeHeader", "Close Header and Footer", "Header & Footer", |s, _| {
|
||||
// Back where the caret was in the body, as Word does, not on page 1.
|
||||
let back = s.hf_return.take().filter(|_| s.in_header_footer());
|
||||
s.hf_section = None;
|
||||
if !new_empty_headers(s).is_empty() {
|
||||
// Its own undo step; a protected document keeps it, and the caret still leaves.
|
||||
let _ = s.run("insert.removeEmptyHeaders", &json!({}));
|
||||
@@ -103,9 +102,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.removeHeader", "Remove Header", "Insert › Header & Footer › Header", |s, _| {
|
||||
if remove_first_hf(s, true)? {
|
||||
return sel_result(s);
|
||||
}
|
||||
s.doc.last_section.headers = Default::default();
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
if s.doc.para(StoryRef::Body, &path).is_some_and(|p| p.section.is_some())
|
||||
@@ -118,9 +114,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.removeFooter", "Remove Footer", "Insert › Header & Footer › Footer", |s, _| {
|
||||
if !remove_first_hf(s, false)? {
|
||||
s.doc.last_section.footers = Default::default();
|
||||
}
|
||||
s.doc.last_section.footers = Default::default();
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.dateTime", "Date & Time", "Insert › Text", date_time).params(r#"{"format"?: "M/d/yyyy", "update"?: bool, "language"?: "en-US|pt-BR"}"#),
|
||||
|
||||
@@ -3,44 +3,6 @@ use super::{
|
||||
json, p, para_block,
|
||||
};
|
||||
|
||||
fn slot_of(slot: wordcraft_layout::HfSlot, set: &wordcraft_doc::section::HeaderSet) -> Option<u32> {
|
||||
match slot {
|
||||
wordcraft_layout::HfSlot::First => set.first,
|
||||
wordcraft_layout::HfSlot::Even => set.even,
|
||||
wordcraft_layout::HfSlot::Default => set.default,
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_of_mut(slot: wordcraft_layout::HfSlot, set: &mut wordcraft_doc::section::HeaderSet) -> &mut Option<u32> {
|
||||
match slot {
|
||||
wordcraft_layout::HfSlot::First => &mut set.first,
|
||||
wordcraft_layout::HfSlot::Even => &mut set.even,
|
||||
wordcraft_layout::HfSlot::Default => &mut set.default,
|
||||
}
|
||||
}
|
||||
|
||||
/// The header (or footer) shown on the caret's page/section (including an inherited one from an
|
||||
/// earlier section), or a newly created one in the caret's section if none exists yet (#5855).
|
||||
pub(super) fn shown_or_create_hf_part(s: &mut Session, header: bool) -> u32 {
|
||||
let sec = crate::cmd::page::hf_section_of_focus(s);
|
||||
let slot = {
|
||||
let layout = s.layout();
|
||||
let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) };
|
||||
page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default()
|
||||
};
|
||||
let sections = s.doc.sections();
|
||||
if let Some(id) = sections
|
||||
.iter()
|
||||
.take(sec + 1)
|
||||
.rev()
|
||||
.find_map(|(_, sp)| slot_of(slot, if header { &sp.headers } else { &sp.footers }))
|
||||
.filter(|id| s.doc.parts.contains_key(id))
|
||||
{
|
||||
return id;
|
||||
}
|
||||
hf_part(s, header)
|
||||
}
|
||||
|
||||
/// The header (or footer) of the caret's section in the slot the caret's page uses (first page,
|
||||
/// even page or the default), made when there is none: with Different First Page on, a header
|
||||
/// inserted on page 1 is the one page 1 shows (#2826).
|
||||
@@ -49,15 +11,22 @@ pub(super) fn hf_part(s: &mut Session, header: bool) -> u32 {
|
||||
let layout = s.layout();
|
||||
let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) };
|
||||
let slot = page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default();
|
||||
let sect = s.doc.section_mut(block).clone();
|
||||
let existing = slot_of(slot, if header { §.headers } else { §.footers });
|
||||
fn slot_of(slot: wordcraft_layout::HfSlot, set: &mut wordcraft_doc::section::HeaderSet) -> &mut Option<u32> {
|
||||
match slot {
|
||||
wordcraft_layout::HfSlot::First => &mut set.first,
|
||||
wordcraft_layout::HfSlot::Even => &mut set.even,
|
||||
wordcraft_layout::HfSlot::Default => &mut set.default,
|
||||
}
|
||||
}
|
||||
let mut sect = s.doc.section_mut(block).clone();
|
||||
let existing = *slot_of(slot, if header { &mut sect.headers } else { &mut sect.footers });
|
||||
if let Some(id) = existing.filter(|id| s.doc.parts.contains_key(id)) {
|
||||
return id;
|
||||
}
|
||||
let style = if header { "Header" } else { "Footer" };
|
||||
let id = s.doc.add_part(if header { PartKind::Header } else { PartKind::Footer }, vec![para_block(Paragraph::new().styled(style))]);
|
||||
let sect = s.doc.section_mut(block);
|
||||
*slot_of_mut(slot, if header { &mut sect.headers } else { &mut sect.footers }) = Some(id);
|
||||
*slot_of(slot, if header { &mut sect.headers } else { &mut sect.footers }) = Some(id);
|
||||
id
|
||||
}
|
||||
|
||||
@@ -119,7 +88,6 @@ pub(super) fn header_footer(s: &mut Session, v: &Value, header: bool) -> CmdResu
|
||||
Ok(json!({"story": id}))
|
||||
}
|
||||
|
||||
/// Edit the header or footer shown on `page`, or at the caret's current body position.
|
||||
pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
let mut page = p::u64(v, "page").map(|page| usize::try_from(page).unwrap_or(usize::MAX));
|
||||
if page.is_none() && s.sel.focus.story == StoryRef::Body {
|
||||
@@ -145,46 +113,13 @@ pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
return s.run(cmd, ¶ms);
|
||||
};
|
||||
if let Some(page) = page {
|
||||
// The page's section is what section commands act on; the body position Close Header and
|
||||
// Footer returns to stays where it was (#3331).
|
||||
s.page_hint = page;
|
||||
let sec = s.layout().pages.get(page).map(|pg| pg.section);
|
||||
s.hf_section = sec.map(|sec| sec.min(s.doc.sections().len().saturating_sub(1)));
|
||||
}
|
||||
s.touch();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Part(id)));
|
||||
Ok(json!({"story": id}))
|
||||
}
|
||||
|
||||
/// Remove the first-page variant while it is being edited, keeping the other page variants.
|
||||
pub(super) fn remove_first_hf(s: &mut Session, header: bool) -> Result<bool, CmdError> {
|
||||
let StoryRef::Part(story) = s.sel.focus.story else { return Ok(false) };
|
||||
let page = s.page_hint;
|
||||
let layout = s.layout();
|
||||
let Some(page) = layout.pages.get(page) else { return Ok(false) };
|
||||
let shown = if header { page.header_story } else { page.footer_story };
|
||||
if page.hf_slot != wordcraft_layout::HfSlot::First || shown != Some(story) {
|
||||
return Ok(false);
|
||||
}
|
||||
let index = page.section;
|
||||
let sections = s.doc.sections();
|
||||
let Some(&(end, _)) = sections.get(index) else { return Ok(false) };
|
||||
let last = index + 1 == sections.len();
|
||||
let inherits_first = sections[..index].iter().any(|(_, sec)| if header { sec.headers.first.is_some() } else { sec.footers.first.is_some() });
|
||||
// An absent slot would show the previous section's first-page story again.
|
||||
let replacement = if inherits_first {
|
||||
let (kind, style) = if header { (PartKind::Header, "Header") } else { (PartKind::Footer, "Footer") };
|
||||
Some(s.doc.try_add_part(kind, vec![para_block(Paragraph::new().styled(style))])?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let section = if last { &mut s.doc.last_section } else { s.doc.section_mut(end) };
|
||||
let set = if header { &mut section.headers } else { &mut section.footers };
|
||||
set.first = replacement;
|
||||
s.sel = s.hf_return.take().unwrap_or_else(|| Selection::caret(s.doc.start_of(StoryRef::Body)));
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The header (or footer) page `page` shows, if any; an error for a page that isn't there.
|
||||
fn shown_hf(s: &mut Session, page: usize, header: bool) -> Result<Option<u32>, CmdError> {
|
||||
let layout = s.layout();
|
||||
@@ -193,14 +128,11 @@ fn shown_hf(s: &mut Session, page: usize, header: bool) -> Result<Option<u32>, C
|
||||
Ok(shown.filter(|id| s.doc.parts.contains_key(id)))
|
||||
}
|
||||
|
||||
/// Create and edit a header or footer on `page`, or in the caret's section.
|
||||
pub(super) fn create_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
let id = match p::u64(v, "page") {
|
||||
Some(page) => {
|
||||
let page = usize::try_from(page).unwrap_or(usize::MAX);
|
||||
let sec = s.layout().pages.get(page).map(|pg| pg.section).ok_or_else(|| CmdError::Params(format!("no page {page}")))?;
|
||||
s.page_hint = page;
|
||||
s.hf_section = Some(sec.min(s.doc.sections().len().saturating_sub(1)));
|
||||
page_hf_part(s, page, header)?
|
||||
}
|
||||
None => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::PartKind;
|
||||
use super::header_footer::shown_or_create_hf_part;
|
||||
use super::header_footer::hf_part;
|
||||
use super::{
|
||||
Align, Block, CharProps, CmdError, CmdResult, InlineObject, Paragraph, Rgb, Selection, Session, StoryRef, TabAlign, TabStop, TextColor, Value,
|
||||
delete_selection, json, p, para_block, sel_result, type_text, type_text_with_lang,
|
||||
@@ -85,7 +85,7 @@ pub(super) fn page_number(s: &mut Session, v: &Value) -> CmdResult {
|
||||
return sel_result(s);
|
||||
}
|
||||
let header = position == "top";
|
||||
let id = shown_or_create_hf_part(s, header);
|
||||
let id = hf_part(s, header);
|
||||
let story = StoryRef::Part(id);
|
||||
let style = if header { "Header" } else { "Footer" };
|
||||
let mut para = page_number_paragraph(style, align, x_of_y)?;
|
||||
|
||||
@@ -133,108 +133,6 @@ fn different_first_page_header_is_reachable_from_page_one() {
|
||||
assert_eq!((s.doc.last_section.footers.first, s.doc.last_section.footers.default), (Some(foot), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_first_page_header_or_footer_keeps_the_default() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
for (cmd, page, text) in [
|
||||
("insert.editHeader", 0, "Cover header"),
|
||||
("insert.editHeader", 1, "Default header"),
|
||||
("insert.editFooter", 0, "Cover footer"),
|
||||
("insert.editFooter", 1, "Default footer"),
|
||||
] {
|
||||
s.run(cmd, &json!({"page": page})).unwrap();
|
||||
s.run("text.insert", &json!({"text": text})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
}
|
||||
let page_stories = |s: &mut Session| {
|
||||
let pages = &s.layout().pages;
|
||||
assert_eq!(pages.len(), 2);
|
||||
[(pages[0].header_story, pages[0].footer_story), (pages[1].header_story, pages[1].footer_story)]
|
||||
};
|
||||
let [first, default] = page_stories(&mut s);
|
||||
assert!(first.0.is_some() && first.1.is_some());
|
||||
assert!(default.0.is_some() && default.1.is_some());
|
||||
assert_ne!(first, default);
|
||||
|
||||
s.run("insert.editHeader", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.removeHeader", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [(None, first.1), default]);
|
||||
assert_eq!(s.sel.focus.story, StoryRef::Body);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [first, default]);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.removeFooter", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [(first.0, None), default]);
|
||||
assert_eq!(s.sel.focus.story, StoryRef::Body);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [first, default]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_first_page_removal_keeps_the_selection_for_close_header_and_footer() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
for (edit, text) in [("insert.editHeader", "Cover header"), ("insert.editFooter", "Cover footer")] {
|
||||
s.run(edit, &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": text})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
}
|
||||
s.run("select.text", &json!({"text": "Two"})).unwrap();
|
||||
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let body_selection = s.sel.clone();
|
||||
assert_eq!(s.selected_text(), "Two");
|
||||
let before = s.doc.clone();
|
||||
|
||||
for (edit, remove) in [("insert.editHeader", "insert.removeHeader"), ("insert.editFooter", "insert.removeFooter")] {
|
||||
s.run(edit, &json!({"page": 0})).unwrap();
|
||||
let editing = s.sel.clone();
|
||||
assert!(s.in_header_footer());
|
||||
let error = s.run(remove, &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("only the editable regions"), "{error}");
|
||||
assert_eq!(s.doc, before);
|
||||
assert_eq!(s.sel, editing, "the refusal leaves the editor in the first-page story");
|
||||
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, body_selection, "explicit Close returns to the saved selection after {remove}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_an_inherited_first_page_header_keeps_the_previous_section() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
let first = s.run("insert.editHeader", &json!({"page": 0})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("text.insert", &json!({"text": "Cover header"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Section two"})).unwrap();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
// Start with a linked first-page slot in the later section.
|
||||
s.doc.last_section.headers.first = None;
|
||||
s.touch();
|
||||
let page = s.layout().pages.iter().position(|page| page.section == 1).unwrap();
|
||||
assert_eq!(s.layout().pages[page].header_story, Some(first));
|
||||
s.run("insert.editHeader", &json!({"page": page})).unwrap();
|
||||
s.run("insert.removeHeader", &json!({})).unwrap();
|
||||
let blank = s.doc.last_section.headers.first.unwrap();
|
||||
assert_ne!(blank, first);
|
||||
assert_eq!(s.layout().pages[0].header_story, Some(first));
|
||||
assert_eq!(s.layout().pages[page].header_story, Some(blank));
|
||||
assert!(s.doc.para(StoryRef::Part(blank), &Path(vec![0])).unwrap().text.is_empty());
|
||||
|
||||
let saved = wordcraft_docx::write(&s.doc).unwrap();
|
||||
let mut reopened = Session::new(wordcraft_docx::read(&saved).unwrap());
|
||||
let reopened_layout = reopened.layout();
|
||||
let cover = reopened_layout.pages[0].header_story.unwrap();
|
||||
let blank = reopened_layout.pages.iter().find(|page| page.section == 1).unwrap().header_story.unwrap();
|
||||
assert_eq!(reopened.doc.para(StoryRef::Part(cover), &Path(vec![0])).unwrap().text.as_str(), "Cover header");
|
||||
assert!(reopened.doc.para(StoryRef::Part(blank), &Path(vec![0])).unwrap().text.is_empty());
|
||||
}
|
||||
|
||||
fn two_pages() -> Session {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("text.insert", &json!({"text": "One"})).unwrap();
|
||||
@@ -316,24 +214,6 @@ fn new_header_links_to_previous_and_even_pages_edit_what_they_show() {
|
||||
assert_eq!(s.doc.sections()[0].1.headers.even, None, "nothing made");
|
||||
}
|
||||
|
||||
/// Edit Header from the body on a later section's page makes the header in the first section,
|
||||
/// linked through to every page, as on main: the caret's page selects the page, not the section.
|
||||
#[test]
|
||||
fn edit_header_from_the_body_links_to_previous_sections() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Three"})).unwrap();
|
||||
let pages = s.layout().pages.len();
|
||||
assert!(pages >= 3 && s.layout().pages[pages - 1].section == 1, "a second section");
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
let id = s.run("insert.editHeader", &json!({})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("text.insert", &json!({"text": "Draft"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert!(s.layout().pages.iter().all(|p| p.header_story == Some(id)), "every page shows it");
|
||||
assert_eq!(s.doc.sections()[0].1.headers.default, Some(id), "made in the first section");
|
||||
assert_eq!(s.doc.sections()[1].1.headers.default, None, "the later section inherits it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_round_trip() {
|
||||
let data = b"hello world!?";
|
||||
@@ -538,54 +418,6 @@ fn local_civil_date_follows_the_utc_offset() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Close Header and Footer restores the body selection, with or without a page argument.
|
||||
#[test]
|
||||
fn close_header_preserves_original_body_selection() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("First paragraph.\nSecond paragraph with more text."));
|
||||
// Place caret at offset 7 in the second paragraph.
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path::top(1), 7));
|
||||
let original = s.sel.clone();
|
||||
|
||||
// Edit footer from ribbon without a page argument.
|
||||
s.run("insert.editFooter", &json!({})).unwrap();
|
||||
assert!(s.in_header_footer());
|
||||
|
||||
// Close header and footer.
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, original, "original body selection was preserved without page argument");
|
||||
|
||||
// Edit footer explicitly specifying the page of the current section.
|
||||
s.sel = original.clone();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
assert!(s.in_header_footer());
|
||||
|
||||
// Close header and footer.
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, original, "original body selection was preserved with same-section page argument");
|
||||
}
|
||||
|
||||
/// Entering a header or footer on another section's page leaves the body caret that Close Header
|
||||
/// and Footer returns to where it was (#3331); the page only picks the section commands act on.
|
||||
#[test]
|
||||
fn closing_a_header_on_another_sections_page_returns_to_the_body_caret() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
// The body caret stays in the first section, page 1 belongs to the second.
|
||||
let before = Selection::caret(Pos::new(StoryRef::Body, Path::top(0), 2));
|
||||
s.sel = before.clone();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
// A click into the footer on page 1's page, while the footer is open.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert!(s.in_header_footer());
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_base64_preserves_command_payload_bytes() {
|
||||
for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
|
||||
|
||||
@@ -33,9 +33,7 @@ pub(crate) use select::select_object;
|
||||
pub(crate) use select::{edit_obj, has_shape_or_canvas};
|
||||
#[cfg(test)]
|
||||
use select::{has_group, holds_ink, obj_size, with_obj};
|
||||
pub use select::{
|
||||
has_picture_format_target, min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects,
|
||||
};
|
||||
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
|
||||
#[cfg(test)]
|
||||
use shape::can_link;
|
||||
pub(crate) use shape::set_text_body;
|
||||
|
||||
@@ -24,22 +24,8 @@ pub(super) fn bounds(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// A size not given stays as it is: a move must not give a level line (0 high) a height.
|
||||
let w = p::f32(v, "width").map_or(w0, |w| w.clamp(min, MAX_OFFSET));
|
||||
let h = p::f32(v, "height").map_or(h0, |h| h.clamp(min, MAX_OFFSET));
|
||||
// A size given sets that side outright, in place of a share of the page or a margin (#6770),
|
||||
// even one equal to the object's own size, which the share hid.
|
||||
let shared = obj.frame().map_or((false, false), |(_, _, f)| (f.rel_w.is_some(), f.rel_h.is_some()));
|
||||
let (set_w, set_h) = (p::f32(v, "width").is_some() && shared.0, p::f32(v, "height").is_some() && shared.1);
|
||||
if (w, h) != (w0, h0) || set_w || set_h {
|
||||
with_obj(s, |o| {
|
||||
o.set_size(w, h);
|
||||
if let Some(f) = o.float_mut() {
|
||||
if set_w {
|
||||
f.rel_w = None;
|
||||
}
|
||||
if set_h {
|
||||
f.rel_h = None;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
if (w, h) != (w0, h0) {
|
||||
with_obj(s, |o| o.set_size(w, h))?;
|
||||
}
|
||||
let pos = match (to, in_text) {
|
||||
(Some((x, y)), _) => move_object(s, pos, p::u64(v, "page"), x, y, (w, h))?,
|
||||
|
||||
@@ -116,13 +116,8 @@ pub(super) fn group(s: &mut Session, _: &Value) -> CmdResult {
|
||||
GroupChild { x: x - x0, y: y - y0, obj }
|
||||
})
|
||||
.collect();
|
||||
// The group takes the first member's placement, not its size as a share of the page or a
|
||||
// margin (the group's box is the one around its members); its members keep their own alt text.
|
||||
let mut float = found
|
||||
.first()
|
||||
.and_then(|(o, _)| o.frame())
|
||||
.map(|(_, _, f)| Float { alt: Default::default(), rel_w: None, rel_h: None, ..f.clone() })
|
||||
.unwrap_or_default();
|
||||
// The group takes the first member's placement; its members keep their own alt text.
|
||||
let mut float = found.first().and_then(|(o, _)| o.frame()).map(|(_, _, f)| Float { alt: Default::default(), ..f.clone() }).unwrap_or_default();
|
||||
float.set_spin(Spin::default());
|
||||
let grouped = InlineObject::Group { w, h, float, ch_w: w, ch_h: h, children, canvas: None };
|
||||
// Take the members out, last first so the earlier positions hold, and put the group where
|
||||
@@ -164,13 +159,7 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> CmdResult {
|
||||
};
|
||||
let obj = s.doc.para_at(&pos).and_then(|p| p.object_at(pos.off)).cloned().ok_or_else(|| CmdError::Failed("object vanished".into()))?;
|
||||
let Some((w, h, float)) = obj.frame() else { return Err(CmdError::Failed("object vanished".into())) };
|
||||
// A group sized as a share of the page or a margin shows its members at the size it is drawn
|
||||
// at; they take their places and sizes there, not the share (each would be all of it).
|
||||
let (w, h) = match (float.rel_w.is_some() || float.rel_h.is_some()).then(|| s.layout().object(&pos, s.page_hint)).flatten() {
|
||||
Some(hit) => (hit.rect.w, hit.rect.h),
|
||||
None => (w, h),
|
||||
};
|
||||
let float = Float { rel_w: None, rel_h: None, ..float.clone() };
|
||||
let float = float.clone();
|
||||
// Each member where the group shows it: the group's turn moves its centre about the group's
|
||||
// centre and adds to its own turn.
|
||||
let members: Vec<InlineObject> = shown_members(&obj, [0.0, 0.0, w, h])
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::select::{edit_obj, has_picture, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
|
||||
use super::select::{edit_obj, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
@@ -70,10 +70,9 @@ pub fn cropped_original_size(s: &Session, o: &InlineObject) -> Option<(f32, f32)
|
||||
Some((orig.w * part(crop[0], crop[2]), orig.h * part(crop[1], crop[3])))
|
||||
}
|
||||
|
||||
fn planned_size(s: &mut Session, pos: &Pos, o: &InlineObject, v: &Value) -> Result<(f32, f32), CmdError> {
|
||||
fn planned_size(s: &Session, o: &InlineObject, v: &Value) -> Result<(f32, f32), CmdError> {
|
||||
let lock = p::bool(v, "lockAspect").unwrap_or(true);
|
||||
let has_share = o.frame().is_some_and(|(_, _, f)| f.rel_w.is_some() || f.rel_h.is_some());
|
||||
let (w0, h0) = if has_share { s.layout().object(pos, s.page_hint).map_or_else(|| obj_size(o), |r| (r.rect.w, r.rect.h)) } else { obj_size(o) };
|
||||
let (w0, h0) = obj_size(o);
|
||||
let (mut w, mut h) = (w0, h0);
|
||||
let scale = p::f32(v, "scale");
|
||||
let original = p::bool(v, "original").unwrap_or(false);
|
||||
@@ -129,35 +128,15 @@ fn size_matching(s: &mut Session, v: &Value, pred: impl Fn(&InlineObject) -> boo
|
||||
if targets.is_empty() {
|
||||
return Err(CmdError::Disabled(empty_msg.into()));
|
||||
}
|
||||
let mut planned = Vec::with_capacity(targets.len());
|
||||
for (pos, o) in targets {
|
||||
let (w, h) = planned_size(s, &pos, &o, v)?;
|
||||
planned.push((pos, w, h));
|
||||
}
|
||||
let lock = p::bool(v, "lockAspect").unwrap_or(true);
|
||||
let (has_w, has_h) = (p::f32(v, "width").is_some(), p::f32(v, "height").is_some());
|
||||
let both = p::bool(v, "original").unwrap_or(false) || p::f32(v, "scale").is_some() || (lock && (has_w || has_h));
|
||||
let (clear_w, clear_h) = (both || has_w, both || has_h);
|
||||
let planned: Vec<(Pos, f32, f32)> =
|
||||
targets.into_iter().map(|(pos, o)| planned_size(s, &o, v).map(|(w, h)| (pos, w, h))).collect::<Result<Vec<_>, _>>()?;
|
||||
// Any drawing: a group's members scale with its frame (its child space is kept); a chart or
|
||||
// SmartArt graphic lays itself out again at the new size.
|
||||
let theme = s.doc.settings.theme_colors.clone();
|
||||
let mut last = Value::Null;
|
||||
for (pos, w, h) in &planned {
|
||||
let o = edit_obj(s, pos, |o| {
|
||||
let saved = o.frame().map(|(_, _, f)| (f.rel_w, f.rel_h));
|
||||
o.set_size(*w, *h);
|
||||
if let Some(f) = o.float_mut() {
|
||||
if clear_w {
|
||||
f.rel_w = None;
|
||||
} else if let Some((rw, _)) = saved {
|
||||
f.rel_w = rw;
|
||||
}
|
||||
if clear_h {
|
||||
f.rel_h = None;
|
||||
} else if let Some((_, rh)) = saved {
|
||||
f.rel_h = rh;
|
||||
}
|
||||
}
|
||||
crate::cmd::chart::redraw(o, &theme);
|
||||
crate::cmd::smart_art::redraw(o, &theme);
|
||||
})?;
|
||||
@@ -211,7 +190,7 @@ pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) {
|
||||
/// Ctrl+click, #8832), one undo step. The selection is as it was afterwards.
|
||||
pub(super) fn each_picture(s: &mut Session, run: impl Fn(&mut Session) -> CmdResult) -> CmdResult {
|
||||
let picks = target_objects(s, |o| matches!(o, InlineObject::Image { .. }));
|
||||
if picks.is_empty() || (picks.len() == 1 && has_picture(s).is_none()) {
|
||||
if picks.len() < 2 {
|
||||
return run(s);
|
||||
}
|
||||
let (sel, also) = (s.sel.clone(), s.also_selected.clone());
|
||||
|
||||
@@ -7,17 +7,6 @@ pub(super) fn has_picture(s: &Session) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether commands that already format multiple pictures have a target. A secondary
|
||||
/// picture can be in the text range or among explicitly picked objects.
|
||||
pub fn has_picture_format_target(s: &Session) -> bool {
|
||||
has_picture(s).is_none()
|
||||
|| ((!s.sel.is_collapsed() || !s.also_selected.is_empty()) && !target_objects(s, |o| matches!(o, InlineObject::Image { .. })).is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn has_any_picture(s: &Session) -> Option<&'static str> {
|
||||
(!has_picture_format_target(s)).then_some("select a picture first")
|
||||
}
|
||||
|
||||
/// Guard returning `None` when a picture, shape, or active text box is selected.
|
||||
pub(super) fn has_object(s: &Session) -> Option<&'static str> {
|
||||
if selected_or_text_box(s).is_some() { None } else { Some("select a picture or shape first") }
|
||||
|
||||
@@ -4,9 +4,9 @@ use super::picture::{
|
||||
adjust, adjust_media, clear_lum, crop, each_picture, original_media, recolor, relook, remove_background, reset, shape_size, size,
|
||||
};
|
||||
use super::select::{
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_picture, has_any_shape, has_floating, has_group, has_movable, has_object,
|
||||
has_picture, has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box,
|
||||
target_objects, with_float, with_floats_matching, with_movable_floats, with_obj,
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
|
||||
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
|
||||
with_float, with_floats_matching, with_movable_floats, with_obj,
|
||||
};
|
||||
use super::shape::{NO_TEXT_BOX, can_link, has_text_box, link_text_box, set_text_body, shape_effects, text_box_target};
|
||||
use super::{CmdError, CommandSpec, InlineObject, Pos, Rgb, Selection, Spin, TextVert, VAlign, Wrap, WrapText, json, p, sel_result};
|
||||
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"brightness"?: -100..100, "contrast"?: -100..100, "sharpen"?: -100..100}"#)
|
||||
.when(has_any_picture),
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.color", "Color", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
|
||||
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"mode": "grayscale|sepia|washout|blackAndWhite|saturation|tint", "saturation"?: 0..400}"#)
|
||||
.when(has_any_picture),
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.iconColor", "Icon Color", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"color": "RRGGBB"}"#)
|
||||
.when(has_any_picture),
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.effects", "Artistic Effects", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
// One effect at a time, as in Word: a second one replaces the first (#2052).
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate|none"} (replaces the picture's effect)"#)
|
||||
.when(has_any_picture),
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.transparency", "Transparency", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
|
||||
@@ -148,7 +148,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"percent": 0..100}"#)
|
||||
.when(has_any_picture),
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.removeBackground", "Remove Background", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
|
||||
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"tolerance"?: 0..255}"#)
|
||||
.when(has_any_picture),
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.compress", "Compress Pictures", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
|
||||
@@ -164,8 +164,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"maxPixels"?: n}"#)
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_any_picture),
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_picture),
|
||||
CommandSpec::new("picture.change", "Change Picture", "Picture Format › Adjust", |s, v| {
|
||||
let bytes = if let Some(d) = p::str(v, "data") {
|
||||
crate::cmd::insert::base64_decode(d).ok_or_else(|| CmdError::Params("bad base64".into()))?
|
||||
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"} (replaces the picture's style and border)"#)
|
||||
.when(has_any_picture),
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.border", "Picture Border", "Picture Format › Picture Styles", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
|
||||
@@ -220,7 +220,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
|
||||
.when(has_any_picture),
|
||||
.when(has_picture),
|
||||
CommandSpec::new("arrange.rotate", "Rotate", "Layout › Arrange", |s, v| {
|
||||
// Turns and flips are the object's angle and mirroring (DrawingML `a:xfrm`): the
|
||||
// picture's pixels are never rewritten. A flip mirrors what is on the page, so a
|
||||
|
||||
@@ -432,105 +432,6 @@ fn two_inserted_pictures_in_a_row_are_both_kept() {
|
||||
assert_eq!(s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_border_uses_picked_pictures_even_when_a_shape_is_primary() {
|
||||
for (picked, expected) in
|
||||
[(&[2, 0][..], [true, false]), (&[2, 0, 1][..], [true, true]), (&[0, 2, 1][..], [true, true]), (&[2][..], [false, false])]
|
||||
{
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
for w in [20, 24] {
|
||||
let data = super::super::insert::base64_encode(&png(w, 10));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
}
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
for index in picked {
|
||||
s.run("select.addObject", &json!({"index": index})).unwrap();
|
||||
}
|
||||
let selection = s.sel.clone();
|
||||
let extras = s.also_selected.clone();
|
||||
let undo = s.undo_depth();
|
||||
let shape = |s: &Session| {
|
||||
let (_, object) = all_objects(s).into_iter().find(|(_, o)| matches!(o, InlineObject::Shape { .. })).unwrap();
|
||||
serde_json::to_value(object).unwrap()
|
||||
};
|
||||
let shape_before = shape(&s);
|
||||
let borders = |s: &Session| {
|
||||
all_objects(s)
|
||||
.into_iter()
|
||||
.filter_map(|(_, o)| match o {
|
||||
InlineObject::Image { media, .. } => Some(s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let result = s.run("picture.border", &json!({"width": 3}));
|
||||
if expected == [false, false] {
|
||||
assert!(result.is_err(), "a shape alone cannot take a picture border");
|
||||
assert_eq!(s.undo_depth(), undo);
|
||||
} else {
|
||||
result.unwrap();
|
||||
assert_eq!(s.undo_depth(), undo + 1);
|
||||
}
|
||||
assert_eq!(s.sel, selection);
|
||||
assert_eq!(s.also_selected, extras);
|
||||
assert_eq!(shape(&s), shape_before);
|
||||
assert_eq!(borders(&s), expected);
|
||||
if expected != [false, false] {
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(borders(&s), [false, false]);
|
||||
assert_eq!(shape(&s), shape_before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_border_uses_pictures_in_a_text_range_in_either_order() {
|
||||
let data = super::super::insert::base64_encode(&png(20, 10));
|
||||
for (order, picture_first) in
|
||||
[(&["insert.shape", "insert.picture"][..], false), (&["insert.picture", "insert.shape"][..], true), (&["insert.shape"][..], false)]
|
||||
{
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Lead "));
|
||||
for command in order {
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
let params = if *command == "insert.shape" { json!({"kind": "rectangle"}) } else { json!({"data": data}) };
|
||||
s.run(command, ¶ms).unwrap();
|
||||
}
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("text.insert", &json!({"text": " tail"})).unwrap();
|
||||
let focus = s.doc.end_of(StoryRef::Body);
|
||||
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": focus})).unwrap();
|
||||
let selection = s.sel.clone();
|
||||
assert!(s.also_selected.is_empty());
|
||||
assert!(object_selection(&s).is_none(), "this selects ordinary text as well as the object anchors");
|
||||
let shape = |s: &Session| all_objects(s).into_iter().find(|(_, o)| matches!(o, InlineObject::Shape { .. })).map(|(_, o)| o).unwrap();
|
||||
let media =
|
||||
|s: &Session| all_objects(s).into_iter().find_map(|(_, o)| if let InlineObject::Image { media, .. } = o { Some(media) } else { None });
|
||||
let before = (shape(&s), media(&s), s.undo_depth());
|
||||
if !picture_first {
|
||||
assert!(matches!(s.run("picture.crop", &json!({"left": 0.1})), Err(CmdError::Disabled(_))));
|
||||
}
|
||||
let result = s.run("picture.border", &json!({"width": 3}));
|
||||
assert_eq!(s.sel, selection);
|
||||
assert!(s.also_selected.is_empty());
|
||||
assert_eq!(shape(&s), before.0);
|
||||
if let Some(original) = &before.1 {
|
||||
result.unwrap();
|
||||
let image = media(&s).unwrap();
|
||||
assert!(s.picture_looks.get(&image).is_some_and(|l| l.border.is_some()));
|
||||
assert_eq!(s.undo_depth(), before.2 + 1);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(media(&s).as_ref(), Some(original));
|
||||
assert_eq!(shape(&s), before.0);
|
||||
assert_eq!(s.sel, selection);
|
||||
} else {
|
||||
assert!(matches!(result, Err(CmdError::Disabled(_))));
|
||||
assert_eq!(s.undo_depth(), before.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #8832: a picture command on several selected pictures changes each, in one undo step.
|
||||
#[test]
|
||||
fn picture_border_applies_to_every_selected_picture() {
|
||||
@@ -2366,173 +2267,3 @@ fn shape_size_and_rotation_only_affect_shapes_in_mixed_selection() {
|
||||
assert_eq!(objs2[1].1.frame().unwrap().0, 180.0);
|
||||
assert_eq!(objs2[2].1.frame().unwrap().0, 180.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_format_commands_stay_enabled_when_shape_is_selected_first() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
|
||||
// Shape clicked first, then one picture added.
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
s.run("picture.border", &json!({"color": "FF0000", "width": 3})).unwrap();
|
||||
assert!(matches!(
|
||||
&all_objects(&s)[1].1,
|
||||
InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.border.is_some())
|
||||
));
|
||||
|
||||
// Shape clicked first, then two pictures added.
|
||||
s.run("select.addObject", &json!({"index": 2})).unwrap();
|
||||
s.run("picture.style", &json!({"style": "rounded"})).unwrap();
|
||||
let objs = all_objects(&s);
|
||||
for idx in [1, 2] {
|
||||
assert!(
|
||||
matches!(&objs[idx].1, InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.style.as_deref() == Some("rounded"))),
|
||||
"picture {idx} should get rounded style"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_object_picture_commands_need_the_picture_selected_first() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
|
||||
// Shape clicked first, then the picture added: Crop, Change Picture and Alt Text would act on the shape.
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
for (cmd, args) in [("picture.crop", json!({"left": 0.1})), ("picture.altText", json!({"text": "x"})), ("picture.change", json!({"data": data}))]
|
||||
{
|
||||
assert!(matches!(s.run(cmd, &args), Err(CmdError::Disabled(_))), "{cmd}");
|
||||
}
|
||||
|
||||
// Picture first: enabled.
|
||||
s.run("select.objects", &json!({"index": 1})).unwrap();
|
||||
s.run("picture.crop", &json!({"left": 0.1})).unwrap();
|
||||
}
|
||||
|
||||
/// #6770: an object's size as a share of the page or a margin stays its own: a size set by
|
||||
/// dragging replaces it (even the object's own size, which the share hid), a group made with it
|
||||
/// first doesn't take it, and ungrouping a group sized so leaves each member the size it showed.
|
||||
#[test]
|
||||
fn a_share_of_the_page_stays_with_its_object() {
|
||||
use wordcraft_doc::para::{RelSize, SizeFrom};
|
||||
let quarter = Some(RelSize { from: SizeFrom::Page, pct: 25_000 });
|
||||
let share_of = |s: &Session| selected(s).and_then(|(_, o)| o.frame().map(|(_, _, f)| (f.rel_w, f.rel_h)));
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("document.setText", &json!({"text": "one\ntwo"})).unwrap();
|
||||
let page_w = s.doc.last_section.page_w;
|
||||
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap();
|
||||
s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 150})).unwrap();
|
||||
super::select::with_obj(&mut s, |o| {
|
||||
if let Some(f) = o.float_mut() {
|
||||
f.rel_w = quarter;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
s.touch();
|
||||
let (pos, _) = selected(&s).unwrap();
|
||||
assert!((rect_of(&mut s, &pos)[2] - page_w / 4.0).abs() < 0.5);
|
||||
// Dragged to 100 pt wide, its own width: that is the width it shows now.
|
||||
s.run("arrange.bounds", &json!({"width": 100, "height": 50})).unwrap();
|
||||
assert_eq!(share_of(&s), Some((None, None)));
|
||||
let (pos, _) = selected(&s).unwrap();
|
||||
assert!((rect_of(&mut s, &pos)[2] - 100.0).abs() < 0.5);
|
||||
// Grouped first with another: the group's box is the one around them, not a share.
|
||||
super::select::with_obj(&mut s, |o| {
|
||||
if let Some(f) = o.float_mut() {
|
||||
f.rel_w = quarter;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
s.touch();
|
||||
s.run("select.collapse", &json!({"end": true})).unwrap();
|
||||
s.run("insert.shape", &json!({"kind": "ellipse", "width": 60, "height": 40})).unwrap();
|
||||
s.run("arrange.bounds", &json!({"page": 0, "x": 300, "y": 200})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 0})).unwrap();
|
||||
let g = s.run("arrange.group", &json!({})).unwrap();
|
||||
let gpos: Pos = serde_json::from_value(g["pos"].clone()).unwrap();
|
||||
assert_eq!(share_of(&s), Some((None, None)));
|
||||
assert!(near(rect_of(&mut s, &gpos), [100.0, 150.0, 260.0, 90.0]), "{:?}", rect_of(&mut s, &gpos));
|
||||
// A group sized as half the page: ungrouped, its members keep the places and sizes it showed
|
||||
// them at, none of them half the page.
|
||||
super::select::with_obj(&mut s, |o| {
|
||||
if let Some(f) = o.float_mut() {
|
||||
f.rel_w = Some(RelSize { from: SizeFrom::Page, pct: 50_000 });
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
s.touch();
|
||||
let shown = rect_of(&mut s, &gpos);
|
||||
assert!((shown[2] - page_w / 2.0).abs() < 0.5, "{shown:?}");
|
||||
s.run("arrange.ungroup", &json!({})).unwrap();
|
||||
let list = all_objects(&s);
|
||||
assert_eq!(list.len(), 2);
|
||||
for (_, o) in &list {
|
||||
assert_eq!(o.frame().map(|(_, _, f)| (f.rel_w, f.rel_h)), Some((None, None)));
|
||||
}
|
||||
let rects: Vec<[f32; 4]> = list.iter().map(|(p, _)| rect_of(&mut s, p)).collect();
|
||||
let (x0, x1) = rects.iter().fold((f32::MAX, f32::MIN), |(a, b), r| (a.min(r[0]), b.max(r[0] + r[2])));
|
||||
assert!((x0 - shown[0]).abs() < 0.5 && (x1 - (shown[0] + shown[2])).abs() < 0.5, "{rects:?} in {shown:?}");
|
||||
}
|
||||
|
||||
/// #9802: `picture.size` / `shape.size` work from the drawn size when a share applies, and clear
|
||||
/// the share of any side they set even when the new value equals the object's hidden own size.
|
||||
#[test]
|
||||
fn size_command_uses_drawn_size_and_clears_share_even_at_own_size() {
|
||||
use wordcraft_doc::para::{RelSize, SizeFrom};
|
||||
let half_page = Some(RelSize { from: SizeFrom::Page, pct: 50_000 });
|
||||
let share_of = |s: &Session| selected(s).and_then(|(_, o)| o.frame().map(|(_, _, f)| (f.rel_w, f.rel_h)));
|
||||
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("document.setText", &json!({"text": "one"})).unwrap();
|
||||
let (page_w, page_h) = (s.doc.last_section.page_w, s.doc.last_section.page_h);
|
||||
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap();
|
||||
s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 150})).unwrap();
|
||||
super::select::with_obj(&mut s, |o| {
|
||||
if let Some(f) = o.float_mut() {
|
||||
f.rel_w = half_page;
|
||||
f.rel_h = half_page;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
s.touch();
|
||||
let (pos, _) = selected(&s).unwrap();
|
||||
assert!((rect_of(&mut s, &pos)[2] - page_w / 2.0).abs() < 0.5);
|
||||
assert!((rect_of(&mut s, &pos)[3] - page_h / 2.0).abs() < 0.5);
|
||||
|
||||
// Scaling by 50% scales from the drawn half-page size, not the hidden 100x50 own size.
|
||||
s.run("shape.size", &json!({"scale": 50})).unwrap();
|
||||
assert_eq!(share_of(&s), Some((None, None)));
|
||||
let (pos, _) = selected(&s).unwrap();
|
||||
let scaled = rect_of(&mut s, &pos);
|
||||
assert!((scaled[2] - page_w / 4.0).abs() < 0.5, "{scaled:?}");
|
||||
assert!((scaled[3] - page_h / 4.0).abs() < 0.5, "{scaled:?}");
|
||||
|
||||
// Setting width to the hidden own width (100) with lockAspect=false clears rel_w while keeping rel_h.
|
||||
s.run("shape.size", &json!({"width": 100, "height": 50, "lockAspect": false})).unwrap();
|
||||
super::select::with_obj(&mut s, |o| {
|
||||
if let Some(f) = o.float_mut() {
|
||||
f.rel_w = half_page;
|
||||
f.rel_h = half_page;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
s.touch();
|
||||
s.run("shape.size", &json!({"width": 100, "lockAspect": false})).unwrap();
|
||||
assert_eq!(share_of(&s), Some((None, half_page)));
|
||||
let (pos, _) = selected(&s).unwrap();
|
||||
let resized = rect_of(&mut s, &pos);
|
||||
assert!((resized[2] - 100.0).abs() < 0.5, "{resized:?}");
|
||||
assert!((resized[3] - page_h / 2.0).abs() < 0.5, "{resized:?}");
|
||||
}
|
||||
|
||||
@@ -287,39 +287,9 @@ fn prepare_custom_dictionary(s: &Session, setting: Option<&str>) -> Result<(Opti
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's home folder: `USERPROFILE` first on Windows, `HOME` first elsewhere, skipping
|
||||
/// empty values. The recent list reads it in the same order (#8865), so `~/…` means one folder.
|
||||
fn home_dir() -> Option<std::path::PathBuf> {
|
||||
home_from(std::env::var_os("HOME"), std::env::var_os("USERPROFILE"))
|
||||
}
|
||||
|
||||
/// [`home_dir`] without the environment: the order the two values are read in depends on the
|
||||
/// platform, so it takes them as they are read.
|
||||
fn home_from(home: Option<std::ffi::OsString>, userprofile: Option<std::ffi::OsString>) -> Option<std::path::PathBuf> {
|
||||
let set = |v: Option<std::ffi::OsString>| v.filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
|
||||
let (first, second) = if cfg!(windows) { (userprofile, home) } else { (home, userprofile) };
|
||||
set(first).or_else(|| set(second))
|
||||
}
|
||||
|
||||
/// Expand a file or folder path under the home folder with the saved settings' platform-specific prefix.
|
||||
fn expand_home(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<std::path::PathBuf, CmdError> {
|
||||
let prefix = if cfg!(windows) && f.starts_with("~\\") { "~\\" } else { "~/" };
|
||||
let Some(rest) = f.strip_prefix(prefix) else { return Ok(std::path::PathBuf::from(f)) };
|
||||
let Some(home) = home else {
|
||||
return Err(CmdError::Params(format!("`{key}`: cannot expand `{prefix}` because HOME or USERPROFILE is not set")));
|
||||
};
|
||||
// A Windows drive, device or root in the suffix would replace the home path on join.
|
||||
if prefix == "~\\"
|
||||
&& matches!(std::path::Path::new(rest).components().next(), Some(std::path::Component::Prefix(_) | std::path::Component::RootDir))
|
||||
{
|
||||
return Err(CmdError::Params(format!("`{key}`: {f:?} must be relative to the home folder")));
|
||||
}
|
||||
Ok(home.join(rest))
|
||||
}
|
||||
|
||||
/// A folder setting (`dictionariesFolder`, `userTemplatesFolder`): `auto` (or nothing) forgets
|
||||
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
|
||||
/// With `local_only`, a network folder is refused before anything looks at it (#2852): even checking
|
||||
/// 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
|
||||
/// that it exists would make Windows authenticate to that host.
|
||||
fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>, CmdError> {
|
||||
let f = f.trim();
|
||||
@@ -329,7 +299,11 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
|
||||
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
|
||||
return Err(CmdError::Params(format!("`{key}` isn't a folder path")));
|
||||
}
|
||||
let path = expand_home(key, f, home_dir().as_deref())?;
|
||||
let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
|
||||
let path = match (f.strip_prefix("~/"), home) {
|
||||
(Some(rest), Some(h)) => h.join(rest),
|
||||
_ => std::path::PathBuf::from(f),
|
||||
};
|
||||
if local_only && (super::templates::is_network_path(f) || super::templates::is_network_path(&path.to_string_lossy())) {
|
||||
return Err(CmdError::Params(format!("`{key}` can't be a network folder")));
|
||||
}
|
||||
@@ -345,12 +319,8 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
|
||||
}
|
||||
|
||||
/// A file setting (`customDictionary`): `auto` (or nothing) forgets it; otherwise an existing
|
||||
/// file, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
|
||||
/// file, given as an absolute path or one starting with `~/`.
|
||||
fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
|
||||
file_setting_in(key, f, home_dir().as_deref())
|
||||
}
|
||||
|
||||
fn file_setting_in(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<Option<String>, CmdError> {
|
||||
let f = f.trim();
|
||||
if f.is_empty() || f.eq_ignore_ascii_case("auto") {
|
||||
return Ok(None);
|
||||
@@ -358,7 +328,15 @@ fn file_setting_in(key: &str, f: &str, home: Option<&std::path::Path>) -> Result
|
||||
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 path = expand_home(key, f, home)?;
|
||||
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")));
|
||||
}
|
||||
@@ -377,90 +355,3 @@ fn file_setting_in(key: &str, f: &str, home: Option<&std::path::Path>) -> Result
|
||||
pub fn use_dictionaries_folder(folder: Option<&str>) {
|
||||
wordcraft_proof::set_dictionaries_folder(folder.map(std::path::PathBuf::from));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{expand_home, file_setting_in, home_from};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn os(s: &str) -> Option<OsString> {
|
||||
Some(OsString::from(s))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_home_folder_is_the_profile_folder_on_windows_and_home_elsewhere() {
|
||||
let home = home_from(os("/home/u"), os("C:\\Users\\u"));
|
||||
let expected = if cfg!(windows) { PathBuf::from("C:\\Users\\u") } else { PathBuf::from("/home/u") };
|
||||
assert_eq!(home, Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_home_folder_is_skipped_for_the_other_one() {
|
||||
assert_eq!(home_from(os(""), os("C:\\Users\\u")), Some(PathBuf::from("C:\\Users\\u")));
|
||||
assert_eq!(home_from(os(""), None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_home_folder_at_all_expands_to_nothing() {
|
||||
assert_eq!(home_from(None, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tilde_path_expands_under_the_home_folder() {
|
||||
let home = Path::new("/home/u");
|
||||
assert_eq!(expand_home("dictionariesFolder", "~/dic", Some(home)).unwrap(), PathBuf::from("/home/u/dic"));
|
||||
assert_eq!(expand_home("dictionariesFolder", "/abs/dic", Some(home)).unwrap(), PathBuf::from("/abs/dic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tilde_path_without_a_home_folder_is_refused() {
|
||||
let err = expand_home("dictionariesFolder", "~/dic", None).unwrap_err();
|
||||
assert!(format!("{err:?}").contains("cannot expand"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_expands_tilde_with_the_same_platform_prefix() {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
struct TempHome(PathBuf);
|
||||
impl TempHome {
|
||||
fn remove(self) -> std::io::Result<()> {
|
||||
let res = std::fs::remove_dir_all(&self.0);
|
||||
std::mem::forget(self);
|
||||
res
|
||||
}
|
||||
}
|
||||
impl Drop for TempHome {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
let dir = loop {
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let candidate = std::env::temp_dir().join(format!("wc-options-home-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break TempHome(candidate),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => panic!("temp dir {}: {e}", candidate.display()),
|
||||
}
|
||||
};
|
||||
let dic = dir.0.join("custom.dic");
|
||||
std::fs::write(&dic, "wordcraftdictionary\n").unwrap();
|
||||
let expected = dic.to_string_lossy().into_owned();
|
||||
|
||||
assert_eq!(file_setting_in("customDictionary", "~/custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
|
||||
let missing_home = file_setting_in("customDictionary", "~/custom.dic", None).unwrap_err();
|
||||
assert!(format!("{missing_home:?}").contains("cannot expand"), "{missing_home:?}");
|
||||
if cfg!(windows) {
|
||||
assert_eq!(file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
|
||||
let drive = file_setting_in("customDictionary", r"~\C:\custom.dic", Some(&dir.0)).unwrap_err();
|
||||
assert!(format!("{drive:?}").contains("relative to the home folder"), "{drive:?}");
|
||||
} else {
|
||||
let backslash = file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap_err();
|
||||
assert!(format!("{backslash:?}").contains("isn't a full path"), "{backslash:?}");
|
||||
}
|
||||
dir.remove().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::packs::{Backend, FixedBackend};
|
||||
|
||||
/// Tests that set the process-wide backend or packs directory share the dictionary test lock.
|
||||
use crate::custom_dict::DICT_TEST_LOCK as LOCK;
|
||||
/// Tests that set the process-wide backend take turns.
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Puts the process back to no backend and no background thread when dropped, even when
|
||||
/// the test panicked.
|
||||
|
||||
@@ -51,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
s.push_ui_request(json!({"open": "pageSetup"}));
|
||||
Ok(serde_json::to_value(sect(s)).unwrap_or(Value::Null))
|
||||
})
|
||||
.params(r#"{"section"?: SectionProps} (replaces the whole section, headers and footers included; checked like Size, Margins, Columns, Line Numbers, Footnotes and Page Borders: non-finite numbers and margins that leave no room for text are refused; negative marginTop/marginBottom are kept as exact margins and counted by their magnitude while negative marginLeft/marginRight clamp to 0; page sides 7.2–1584 pt, 1–12 columns with 0–300 pt gaps, header/footer/gutter 0–1584 pt, page border width 0.25–6 pt and distance 0–31 pt, note start 1–32767, line numbers start 1–32767, countBy 1–100, distance 0–1584 pt are clamped)"#),
|
||||
.params(r#"{"section"?: SectionProps} (replaces the whole section, headers and footers included; checked like Size, Margins, Columns, Line Numbers, Footnotes and Page Borders: non-finite numbers and margins that leave no room for text are refused; page sides 7.2–1584 pt, 1–12 columns with 0–300 pt gaps, header/footer/gutter 0–1584 pt, page border width 0.25–6 pt and distance 0–31 pt, note start 1–32767, line numbers start 1–32767, countBy 1–100, distance 0–1584 pt are clamped)"#),
|
||||
CommandSpec::new("layout.verticalAlign", "Vertical Alignment", "Layout › Page Setup › Layout", |s, v| {
|
||||
let va = wordcraft_doc::section::PageVAlign::parse(p::str(v, "value").unwrap_or_default());
|
||||
with_sect(s, |x| x.valign = va)
|
||||
@@ -224,51 +224,8 @@ fn manual_hyphenation(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(best.map(|(_, v)| v).unwrap_or_else(|| json!({"done": true})))
|
||||
}
|
||||
|
||||
/// Whether `sec` displays header/footer part `id` (directly or inherited from an earlier section).
|
||||
pub(crate) fn section_uses_hf_part(sections: &[(usize, &SectionProps)], sec: usize, id: u32) -> bool {
|
||||
let slice = sections.get(..=sec).unwrap_or(sections);
|
||||
[
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.headers.default),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.headers.first),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.headers.even),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.footers.default),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.footers.first),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.footers.even),
|
||||
]
|
||||
.contains(&Some(id))
|
||||
}
|
||||
|
||||
/// Resolve the section index associated with a header, footer, or note part `id`.
|
||||
pub(crate) fn section_of_part(s: &Session, id: u32) -> usize {
|
||||
let sections = s.doc.sections();
|
||||
if s.doc.parts.get(&id).is_some_and(|p| matches!(p.kind, wordcraft_doc::PartKind::Header | wordcraft_doc::PartKind::Footer)) {
|
||||
let uses_hf = |sec: usize| section_uses_hf_part(§ions, sec, id);
|
||||
// The section of the page whose header or footer was opened decides: a footer inherited from
|
||||
// an earlier section still belongs to the later section that shows it. It is kept apart
|
||||
// from the page hint because a taller footer can repaginate the pages under it.
|
||||
if let Some(sec) = s.hf_section.map(|sec| sec.min(sections.len().saturating_sub(1)))
|
||||
&& uses_hf(sec)
|
||||
{
|
||||
return sec;
|
||||
}
|
||||
// Entered without a page (Insert › Header, a page number): the page the hint names.
|
||||
if let Some(pg) = s.cached_layout().and_then(|l| l.pages.get(s.page_hint)) {
|
||||
let sec = pg.section.min(sections.len().saturating_sub(1));
|
||||
if uses_hf(sec) {
|
||||
return sec;
|
||||
}
|
||||
}
|
||||
// Neither names a section that uses it (a stale page hint): the body position the header
|
||||
// was entered from.
|
||||
if let Some(ret) = &s.hf_return
|
||||
&& ret.focus.story == wordcraft_doc::StoryRef::Body
|
||||
{
|
||||
let sec = s.doc.section_index_of(ret.focus.path.0.first().copied().unwrap_or(0) as usize);
|
||||
if uses_hf(sec) {
|
||||
return sec;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, (_, sp)) in sections.iter().enumerate() {
|
||||
if [sp.headers.default, sp.headers.first, sp.headers.even, sp.footers.default, sp.footers.first, sp.footers.even].contains(&Some(id)) {
|
||||
return i;
|
||||
@@ -332,15 +289,8 @@ fn selected_section_ends(s: &Session) -> Vec<usize> {
|
||||
(first..=last).map(|k| ends.get(k).copied().unwrap_or(0)).collect()
|
||||
}
|
||||
|
||||
/// Apply a mutation to each section touched by the current selection.
|
||||
///
|
||||
/// When the caret or selection is outside the body (such as in a header, footer, or note),
|
||||
/// refreshes the layout so the section resolved from the cached layout reflects the current
|
||||
/// document state before mutating section properties.
|
||||
/// Apply to the section(s) of the selection.
|
||||
pub(crate) fn with_sect(s: &mut Session, f: impl Fn(&mut SectionProps)) -> CmdResult {
|
||||
if s.sel.focus.story != wordcraft_doc::StoryRef::Body {
|
||||
let _ = s.layout();
|
||||
}
|
||||
for block in selected_section_ends(s) {
|
||||
f(s.doc.section_mut(block));
|
||||
}
|
||||
@@ -505,7 +455,8 @@ fn validate_section(x: &mut SectionProps) -> Result<(), CmdError> {
|
||||
if x.page_w != x.page_h {
|
||||
x.landscape = x.page_w > x.page_h;
|
||||
}
|
||||
// Negative top/bottom margins encode Word's exact (fixed) margins and must survive round-trips.
|
||||
x.margin_top = x.margin_top.max(0.0);
|
||||
x.margin_bottom = x.margin_bottom.max(0.0);
|
||||
x.margin_left = x.margin_left.max(0.0);
|
||||
x.margin_right = x.margin_right.max(0.0);
|
||||
x.header = x.header.clamp(0.0, x.page_h);
|
||||
@@ -514,8 +465,7 @@ fn validate_section(x: &mut SectionProps) -> Result<(), CmdError> {
|
||||
// A page narrower than the usual text room (the smallest is 0.1") needs only margins that
|
||||
// leave the whole of it: zero margins, gutter included.
|
||||
let room = |side: f32| MIN_TEXT_ROOM.min(side);
|
||||
if x.margin_left + x.margin_right + x.gutter > x.page_w - room(x.page_w) || x.margin_top.abs() + x.margin_bottom.abs() > x.page_h - room(x.page_h)
|
||||
{
|
||||
if x.margin_left + x.margin_right + x.gutter > x.page_w - room(x.page_w) || x.margin_top + x.margin_bottom > x.page_h - room(x.page_h) {
|
||||
return Err(CmdError::Params("margins leave no room for text".into()));
|
||||
}
|
||||
x.columns.space = x.columns.space.clamp(0.0, 300.0);
|
||||
@@ -564,31 +514,26 @@ fn border_sides_mut(b: &mut Borders) -> impl Iterator<Item = &mut Border> {
|
||||
|
||||
fn margins(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let preset = p::str(v, "preset");
|
||||
if s.sel.focus.story != wordcraft_doc::StoryRef::Body {
|
||||
let _ = s.layout();
|
||||
}
|
||||
let (t, b, l, r) = match preset {
|
||||
Some(x) => match MARGIN_PRESETS.iter().find(|(id, _)| *id == x) {
|
||||
Some((_, [t, b, l, r])) => (*t, *b, *l, *r),
|
||||
None => return Err(CmdError::Params(format!("unknown preset `{x}`"))),
|
||||
},
|
||||
None => {
|
||||
// A negative margin given counts as zero; one left out keeps its value, so an exact
|
||||
// (negative) top or bottom from the file stays exact when another side changes, as
|
||||
// in Word.
|
||||
let c = sect(s);
|
||||
let given = |k: &str| p::f32(v, k).map(|m| m.max(0.0));
|
||||
(
|
||||
given("top").unwrap_or(c.margin_top),
|
||||
given("bottom").unwrap_or(c.margin_bottom),
|
||||
given("left").unwrap_or(c.margin_left.max(0.0)),
|
||||
given("right").unwrap_or(c.margin_right.max(0.0)),
|
||||
p::f32(v, "top").unwrap_or(c.margin_top),
|
||||
p::f32(v, "bottom").unwrap_or(c.margin_bottom),
|
||||
p::f32(v, "left").unwrap_or(c.margin_left),
|
||||
p::f32(v, "right").unwrap_or(c.margin_right),
|
||||
)
|
||||
}
|
||||
};
|
||||
// Negative margins count as zero before the fit check, so one can't offset another.
|
||||
let (t, b, l, r) = (t.max(0.0), b.max(0.0), l.max(0.0), r.max(0.0));
|
||||
let gutter = p::f32(v, "gutter").map(|g| g.max(0.0));
|
||||
let cur = sect(s);
|
||||
if !margins_fit((cur.page_w, cur.page_h), (t.abs(), b.abs(), l, r), gutter.unwrap_or(cur.gutter)) {
|
||||
if !margins_fit((cur.page_w, cur.page_h), (t, b, l, r), gutter.unwrap_or(cur.gutter)) {
|
||||
return Err(CmdError::Params("margins leave no room for text".into()));
|
||||
}
|
||||
// A preset picks mirrored or not, as does `mirror` (Page Setup's Multiple pages); plain numbers
|
||||
@@ -624,7 +569,6 @@ pub fn margins_fit(page: (f32, f32), (t, b, l, r): (f32, f32, f32, f32), gutter:
|
||||
pub const MIN_PAGE_SIDE: f32 = 7.2;
|
||||
pub const MAX_PAGE_SIDE: f32 = 1584.0;
|
||||
|
||||
/// Change paper size of the selected section(s) to the given dimensions or preset name.
|
||||
fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (w, h) = if let Some(n) = p::str(v, "name") {
|
||||
let (_, w, h) = wordcraft_geom::PAPER_SIZES
|
||||
@@ -639,15 +583,12 @@ fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (w, h) = (w.clamp(MIN_PAGE_SIDE, MAX_PAGE_SIDE), h.clamp(MIN_PAGE_SIDE, MAX_PAGE_SIDE));
|
||||
// Each section keeps its orientation: the long side across in landscape, down in portrait.
|
||||
let oriented = |x: &SectionProps| if x.landscape { (w.max(h), w.min(h)) } else { (w.min(h), w.max(h)) };
|
||||
if s.sel.focus.story != wordcraft_doc::StoryRef::Body {
|
||||
let _ = s.layout();
|
||||
}
|
||||
let sections = s.doc.sections();
|
||||
let fits = |block: usize| {
|
||||
sections
|
||||
.iter()
|
||||
.find(|(e, _)| *e == block)
|
||||
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top.abs(), x.margin_bottom.abs(), x.margin_left, x.margin_right), x.gutter))
|
||||
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top, x.margin_bottom, x.margin_left, x.margin_right), x.gutter))
|
||||
};
|
||||
if !selected_section_ends(s).into_iter().all(fits) {
|
||||
return Err(CmdError::Params(MARGINS_DONT_FIT.into()));
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use super::*;
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
|
||||
fn doc() -> Session {
|
||||
Session::new(wordcraft_doc::Document::from_text("one\ntwo\nthree"))
|
||||
@@ -44,7 +43,7 @@ fn page_setup_section_is_validated() {
|
||||
v["pageH"] = json!(100.0);
|
||||
v["marginTop"] = json!(-10.0);
|
||||
v["marginBottom"] = json!(0.0);
|
||||
v["marginLeft"] = json!(-10.0);
|
||||
v["marginLeft"] = json!(0.0);
|
||||
v["marginRight"] = json!(0.0);
|
||||
v["header"] = json!(-3.0);
|
||||
v["footer"] = json!(1e6);
|
||||
@@ -62,8 +61,7 @@ fn page_setup_section_is_validated() {
|
||||
.unwrap();
|
||||
let x = sect(&s);
|
||||
assert_eq!((x.page_w, x.page_h), (100.0, 100.0));
|
||||
assert_eq!(x.margin_top, -10.0);
|
||||
assert_eq!(x.margin_left, 0.0);
|
||||
assert_eq!(x.margin_top, 0.0);
|
||||
assert_eq!(x.header, 0.0);
|
||||
assert_eq!(x.footer, x.page_h, "a footer distance stays on the page");
|
||||
assert_eq!(x.columns.count, 12);
|
||||
@@ -144,26 +142,6 @@ fn page_setup_section_allows_a_tiny_page_without_margins() {
|
||||
assert_eq!((sect(&s).page_w, sect(&s).page_h), (7.2, 20.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_setup_section_keeps_exact_vertical_margins_and_checks_their_sizes() {
|
||||
let mut s = doc();
|
||||
s.doc.last_section.margin_top = -54.0;
|
||||
s.doc.last_section.margin_bottom = -48.0;
|
||||
|
||||
let mut roundtrip = s.run("layout.pageSetup", &json!({})).unwrap();
|
||||
roundtrip["marginLeft"] = json!(60.0);
|
||||
s.run("layout.pageSetup", &json!({"section": roundtrip})).unwrap();
|
||||
let x = sect(&s);
|
||||
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-54.0, -48.0, 60.0));
|
||||
|
||||
let too_tall = with_section(|v| {
|
||||
v["pageH"] = json!(100.0);
|
||||
v["marginTop"] = json!(-40.0);
|
||||
v["marginBottom"] = json!(-40.0);
|
||||
});
|
||||
assert!(s.run("layout.pageSetup", &too_tall).is_err(), "exact vertical margins whose sizes leave too little room must be refused");
|
||||
}
|
||||
|
||||
/// Layout › Text Direction turns the section, or the table cell the caret is in; one undo step.
|
||||
#[test]
|
||||
fn text_direction_turns_the_section_or_the_cell() {
|
||||
@@ -439,6 +417,7 @@ fn hyphenation_options_and_manual_hyphenation() {
|
||||
/// section" (#1113).
|
||||
#[test]
|
||||
fn page_number_format_keeps_or_clears_the_start() {
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
let mut s = doc();
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "upperRoman", "start": 3})).unwrap();
|
||||
let x = sect(&s);
|
||||
@@ -453,458 +432,4 @@ fn page_number_format_keeps_or_clears_the_start() {
|
||||
let back = s.run("layout.pageNumberFormat", &json!({"format": "decimal", "start": 1})).unwrap();
|
||||
assert_eq!(back["pageNumFormat"], "decimal");
|
||||
assert_eq!(back["pageNumStart"], 1);
|
||||
|
||||
// #5855: from a linked footer on a later section's page, `sect` and `layout.pageNumberFormat`
|
||||
// read and update that page's section, not the earlier section that defined the footer.
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 5})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(5)));
|
||||
assert_eq!(s.layout().pages[1].number, 5);
|
||||
}
|
||||
|
||||
/// Section commands from an inherited footer target the active section rather than section 0.
|
||||
#[test]
|
||||
fn section_command_from_inherited_footer_targets_active_section() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert!(!secs[0].1.landscape);
|
||||
assert!(secs[1].1.landscape);
|
||||
|
||||
// layout.size also targets the active section from an inherited footer.
|
||||
s.run("layout.size", &json!({"name": "A5"})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
let a5 = wordcraft_geom::PAPER_SIZES.iter().find(|(n, _, _)| *n == "A5").unwrap();
|
||||
assert_ne!((secs[0].1.page_w, secs[0].1.page_h), (a5.1.max(a5.2), a5.1.min(a5.2)));
|
||||
assert_eq!((secs[1].1.page_w, secs[1].1.page_h), (a5.1.max(a5.2), a5.1.min(a5.2)));
|
||||
}
|
||||
|
||||
/// Inserting a page number while editing an inherited footer preserves the inherited content
|
||||
/// and keeps both sections sharing the footer part without unlinking.
|
||||
#[test]
|
||||
fn inherited_footer_preserves_content_when_numbering_from_inherited_footer() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Edit the inherited footer from section 1's page.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Insert page number at bottom of page.
|
||||
s.run("insert.pageNumber", &json!({"position": "bottom", "align": "right"})).unwrap();
|
||||
|
||||
// Verify footer text retains "Footer on sec 0" as well as the PAGE field.
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!(secs[1].1.footers.default, None, "section 1 continues to inherit footer from section 0");
|
||||
let fid = secs[0].1.footers.default.expect("section 0 footer exists");
|
||||
let footer_text = s.doc.plain_text(wordcraft_doc::StoryRef::Part(fid));
|
||||
assert!(footer_text.contains("Footer on sec 0"), "inherited footer content was preserved");
|
||||
let has_page_field = s.doc.story(wordcraft_doc::StoryRef::Part(fid)).is_some_and(|blocks| {
|
||||
blocks.iter().any(|b| match &**b {
|
||||
wordcraft_doc::Block::Para(p) => p.objects.iter().any(|obj| match obj {
|
||||
wordcraft_doc::InlineObject::Field { instr, .. } | wordcraft_doc::InlineObject::FieldStart { instr, .. } => {
|
||||
instr.split_whitespace().next().is_some_and(|name| name.eq_ignore_ascii_case("PAGE"))
|
||||
}
|
||||
_ => false,
|
||||
}),
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
assert!(has_page_field, "footer contains the PAGE field");
|
||||
|
||||
// Both page 0 and page 1 render the shared footer with page numbers.
|
||||
let l = s.layout();
|
||||
assert_eq!(l.pages[0].footer_story, Some(fid));
|
||||
assert_eq!(l.pages[1].footer_story, Some(fid));
|
||||
}
|
||||
|
||||
/// Inserting a page number into the footer while editing an inherited header preserves the
|
||||
/// inherited footer content and keeps both sections sharing the footer part without unlinking.
|
||||
#[test]
|
||||
fn inherited_footer_preserves_content_when_numbering_from_inherited_header() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
|
||||
// Set up header and footer in section 0.
|
||||
s.run("insert.editHeader", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Header on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Edit the inherited header from section 1's page.
|
||||
s.run("insert.editHeader", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Insert page number at bottom of page (into the footer).
|
||||
s.run("insert.pageNumber", &json!({"position": "bottom", "align": "right"})).unwrap();
|
||||
|
||||
// Verify footer text retains "Footer on sec 0" as well as the PAGE field.
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!(secs[1].1.footers.default, None, "section 1 continues to inherit footer from section 0");
|
||||
let fid = secs[0].1.footers.default.expect("section 0 footer exists");
|
||||
let footer_text = s.doc.plain_text(wordcraft_doc::StoryRef::Part(fid));
|
||||
assert!(footer_text.contains("Footer on sec 0"), "inherited footer content was preserved");
|
||||
let has_page_field = s.doc.story(wordcraft_doc::StoryRef::Part(fid)).is_some_and(|blocks| {
|
||||
blocks.iter().any(|b| match &**b {
|
||||
wordcraft_doc::Block::Para(p) => p.objects.iter().any(|obj| match obj {
|
||||
wordcraft_doc::InlineObject::Field { instr, .. } | wordcraft_doc::InlineObject::FieldStart { instr, .. } => {
|
||||
instr.split_whitespace().next().is_some_and(|name| name.eq_ignore_ascii_case("PAGE"))
|
||||
}
|
||||
_ => false,
|
||||
}),
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
assert!(has_page_field, "footer contains the PAGE field");
|
||||
|
||||
// Both page 0 and page 1 render the shared footer with page numbers.
|
||||
let l = s.layout();
|
||||
assert_eq!(l.pages[0].footer_story, Some(fid));
|
||||
assert_eq!(l.pages[1].footer_story, Some(fid));
|
||||
}
|
||||
|
||||
/// When a shared footer grows and repagination causes the preceding section to expand
|
||||
/// onto the hinted page, the active section being edited is preserved rather than
|
||||
/// reverting to the preceding section.
|
||||
#[test]
|
||||
fn repagination_during_shared_footer_edit_preserves_active_section() {
|
||||
// Determine the line count that exactly fills 1 page with a single-line footer.
|
||||
let mut n_lines: usize = 10;
|
||||
while n_lines < 100 {
|
||||
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
if s.layout().pages.len() == 1 {
|
||||
n_lines += 1;
|
||||
} else {
|
||||
n_lines = n_lines.saturating_sub(3);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Section 1 body"})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Verify initial layout: Section 0 is on page 0, Section 1 is on page 1.
|
||||
let l = s.layout();
|
||||
assert_eq!(l.pages.len(), 2);
|
||||
assert_eq!(l.pages[0].section, 0);
|
||||
assert_eq!(l.pages[1].section, 1);
|
||||
|
||||
// Edit inherited footer from section 1's page.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Expand the shared footer so section 0 no longer fits on 1 page and spills onto page 1.
|
||||
for _ in 0..8 {
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Expanded footer row"})).unwrap();
|
||||
}
|
||||
|
||||
// Verify repagination: Section 0 now occupies page 0 and page 1; Section 1 is pushed to page 2.
|
||||
let l = s.layout();
|
||||
assert!(l.pages.len() >= 3);
|
||||
assert_eq!(l.pages[0].section, 0);
|
||||
assert_eq!(l.pages[1].section, 0, "page 1 now occupied by section 0");
|
||||
assert_eq!(l.pages[2].section, 1, "section 1 pushed to page 2");
|
||||
|
||||
// The active section being edited remains section 1 despite page 1 now holding section 0.
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Formatting page numbers updates section 1 rather than section 0.
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 10})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(10)));
|
||||
}
|
||||
|
||||
/// Section commands follow the page whose header or footer is open, not the body caret's section.
|
||||
#[test]
|
||||
fn section_commands_follow_the_page_being_edited() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
let body_end = s.doc.end_of(StoryRef::Body);
|
||||
s.sel = Selection::caret(body_end.clone());
|
||||
// Page 0 is the first section's, page 1 the second's.
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on the first section"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, Selection::caret(body_end), "close returns to the body caret");
|
||||
// Editing page 1's footer (inherited) acts on section 1...
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
// ...and going back to page 0's own footer acts on section 0, though the body caret is in 1.
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 0);
|
||||
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert!(secs[0].1.landscape, "the section whose footer is open");
|
||||
assert!(!secs[1].1.landscape);
|
||||
}
|
||||
|
||||
/// #5855: an out-of-range `insert.createFooter` page leaves the active header/footer section intact.
|
||||
#[test]
|
||||
fn create_footer_out_of_range_page_preserves_active_hf_section() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Edit page 1's inherited footer (active section 1), then fail `insert.createFooter` with an
|
||||
// out-of-range page number.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
assert!(s.run("insert.createFooter", &json!({"page": 99})).is_err());
|
||||
|
||||
// Section targeting still points at section 1 rather than falling back to section 0.
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 7})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(7)));
|
||||
}
|
||||
|
||||
/// #5855: `take_view`/`put_view` preserves `hf_section` when section structure matches, and clears
|
||||
/// it when a section break is added or removed across another edit.
|
||||
#[test]
|
||||
fn take_view_put_view_tracks_hf_section_across_revisions_and_section_breaks() {
|
||||
// Build a two-section document whose expanded shared footer causes section 0 to spill onto
|
||||
// page 1 and push section 1 to page 2.
|
||||
let mut n_lines: usize = 10;
|
||||
while n_lines < 100 {
|
||||
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
if s.layout().pages.len() == 1 {
|
||||
n_lines += 1;
|
||||
} else {
|
||||
n_lines = n_lines.saturating_sub(3);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Section 1 body"})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Open section 1's inherited footer on page 1, then expand the footer so page 1 belongs to
|
||||
// section 0 while `hf_section` still targets section 1.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
for _ in 0..8 {
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Expanded footer row"})).unwrap();
|
||||
}
|
||||
assert_eq!(s.layout().pages[1].section, 0);
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Same revision (`current == true`): `put_view` restores `hf_section`.
|
||||
let same_rev_view = s.take_view();
|
||||
s.put_view(same_rev_view);
|
||||
assert_eq!(section_index_of_focus(&s), 1, "same-revision view swap keeps hf_section");
|
||||
|
||||
// Revision changed without changing section breaks: `put_view` still preserves `hf_section`.
|
||||
let view_before_format = s.take_view();
|
||||
s.run("select.text", &json!({"text": "Line 0"})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.put_view(view_before_format);
|
||||
assert_eq!(section_index_of_focus(&s), 1, "unchanged section breaks preserve hf_section across revision bump");
|
||||
|
||||
// Revision changed with a section break added: stale `hf_section` is cleared and resolution
|
||||
// falls back to `page_hint` (page 1 -> section 0) once layout is refreshed.
|
||||
let view_before_added_break = s.take_view();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Section 2"})).unwrap();
|
||||
s.put_view(view_before_added_break);
|
||||
assert_eq!(s.hf_section, None);
|
||||
let _ = s.layout();
|
||||
assert_eq!(section_index_of_focus(&s), 0, "adding a section break clears stale hf_section");
|
||||
|
||||
// Revision changed with a section break removed in a 3-section document: stale `hf_section`
|
||||
// (`Some(2)`) is cleared rather than clamping onto section 1, both before and after relayout.
|
||||
let mut s3 = Session::new(wordcraft_doc::Document::from_text("s0\ns1\ns2"));
|
||||
s3.run("select.text", &json!({"text": "s0"})).unwrap();
|
||||
s3.run("caret.end", &json!({})).unwrap();
|
||||
s3.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s3.run("select.text", &json!({"text": "s1"})).unwrap();
|
||||
s3.run("caret.end", &json!({})).unwrap();
|
||||
s3.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s3.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s3.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s3.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s3.run("caret.docStart", &json!({})).unwrap();
|
||||
s3.run("insert.editFooter", &json!({"page": 2})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s3), 2);
|
||||
let view3 = s3.take_view();
|
||||
s3.run("select.all", &json!({})).unwrap();
|
||||
s3.run("text.insert", &json!({"text": "a"})).unwrap();
|
||||
s3.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s3.run("text.insert", &json!({"text": "b"})).unwrap();
|
||||
s3.put_view(view3);
|
||||
assert_eq!(s3.hf_section, None);
|
||||
assert_eq!(section_index_of_focus(&s3), 0, "stale cached layout does not clamp onto section 1");
|
||||
let _ = s3.layout();
|
||||
assert_eq!(section_index_of_focus(&s3), 0, "removing a section break clears stale hf_section");
|
||||
}
|
||||
|
||||
/// #5855: `preview_layout` copies the active header/footer section context so previews target the
|
||||
/// section whose inherited footer is being edited.
|
||||
#[test]
|
||||
fn preview_layout_formats_active_inherited_section_footer() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.pageNumber", &json!({"position": "bottom"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
let (doc, _sel, layout) = s.preview_layout("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 7})).unwrap();
|
||||
let secs = doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(7)));
|
||||
let page1_footer: String = layout.pages[1]
|
||||
.footer
|
||||
.iter()
|
||||
.flat_map(|it| match it {
|
||||
crate::layout::Placed::Lines { para, .. } => para.shown.iter().map(|part| part.1.clone()).collect::<Vec<_>>(),
|
||||
_ => Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
assert!(page1_footer.contains("vii"), "preview renders section 1 footer as vii, got {page1_footer:?}");
|
||||
}
|
||||
|
||||
/// #5855: Moving the caret into a linked footer on another page (via click or keyboard without
|
||||
/// re-running `editFooter`) updates `hf_section` so section commands target that page's section.
|
||||
#[test]
|
||||
fn linked_footer_caret_move_updates_hf_section_without_edit_footer() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
|
||||
// Enter footer on page 0 (section 0) and insert a page number; section 1 inherits it.
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.pageNumber", &json!({"position": "bottom"})).unwrap();
|
||||
assert_eq!(s.hf_section, Some(0));
|
||||
assert_eq!(section_index_of_focus(&s), 0);
|
||||
|
||||
// Move caret into the same linked footer on page 1 without calling `insert.editFooter`.
|
||||
let (x, y) = {
|
||||
let l = s.layout();
|
||||
let c = l.caret_on(&s.sel.focus, 1).expect("linked footer laid out on page 1");
|
||||
(c.x, c.top + c.height * 0.5)
|
||||
};
|
||||
let story = match s.sel.focus.story {
|
||||
wordcraft_doc::StoryRef::Part(id) => format!("part:{id}"),
|
||||
wordcraft_doc::StoryRef::Body => "body".to_string(),
|
||||
};
|
||||
s.run("caret.set", &json!({"page": 1, "x": x, "y": y, "story": story})).unwrap();
|
||||
assert_eq!(s.hf_section, Some(1));
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Formatting page numbers now updates section 1, leaving section 0 untouched.
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 5})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(5)));
|
||||
}
|
||||
|
||||
/// #5855: `layout.margins` refreshes layout before reading existing edges when editing a header/footer.
|
||||
#[test]
|
||||
fn margins_from_inherited_footer_targets_active_section() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("layout.margins", &json!({"top": 108.0})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
s.run("layout.margins", &json!({"left": 90.0})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!(secs[0].1.margin_left, SectionProps::default().margin_left);
|
||||
assert_eq!(secs[1].1.margin_left, 90.0);
|
||||
assert_eq!(secs[1].1.margin_top, 108.0);
|
||||
}
|
||||
|
||||
/// An exact (negative) top or bottom margin survives Margins and Orientation: changing another
|
||||
/// margin keeps it exact, and turning the page moves its size, as a plain margin, to the side it
|
||||
/// goes to.
|
||||
#[test]
|
||||
fn exact_margins_survive_margins_and_orientation() {
|
||||
let mut s = doc();
|
||||
s.doc.last_section.margin_top = -60.0;
|
||||
s.doc.last_section.margin_bottom = -40.0;
|
||||
s.run("layout.margins", &json!({"left": 80.0})).unwrap();
|
||||
let x = &s.doc.last_section;
|
||||
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-60.0, -40.0, 80.0));
|
||||
// A negative margin given still counts as zero.
|
||||
s.run("layout.margins", &json!({"top": -30.0})).unwrap();
|
||||
assert_eq!((s.doc.last_section.margin_top, s.doc.last_section.margin_bottom), (0.0, -40.0));
|
||||
s.doc.last_section.margin_top = -60.0;
|
||||
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
|
||||
let x = &s.doc.last_section;
|
||||
assert!(x.margin_left >= 0.0 && x.margin_right >= 0.0, "{x:?}");
|
||||
let mut sides = [x.margin_left, x.margin_right];
|
||||
sides.sort_by(f32::total_cmp);
|
||||
assert_eq!(sides, [40.0, 60.0], "the exact margins' sizes go to the sides");
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ pub(super) fn outline_step(s: &mut Session, promote: bool) -> CmdResult {
|
||||
// Outline view: the headings hidden under a collapsed heading move a level with it.
|
||||
let carried = crate::cmd::outline::hidden_subheadings(s);
|
||||
let (a, b) = s.sel.ordered();
|
||||
let paths = if s.cell_range().is_some_and(|range| !range.stream) { crate::cmd::selected_paths(s) } else { s.doc.paths_between(&a, &b) };
|
||||
let paths = s.doc.paths_between(&a, &b);
|
||||
// The heading before the selection, for promoted body text.
|
||||
let before = s
|
||||
.doc
|
||||
|
||||
@@ -187,224 +187,12 @@ pub(super) fn create_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"id": id}))
|
||||
}
|
||||
|
||||
/// Deserialize `T` from `v`, rejecting unknown fields on `T` and any nested structs (#9203, #9291).
|
||||
fn deserialize_strict<T: serde::de::DeserializeOwned>(section: &str, v: &Value) -> Result<T, CmdError> {
|
||||
use serde::de::{DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor};
|
||||
|
||||
struct StrictDe<'a> {
|
||||
value: &'a Value,
|
||||
path: String,
|
||||
}
|
||||
struct StrictSeq<'a> {
|
||||
iter: std::slice::Iter<'a, Value>,
|
||||
path: &'a str,
|
||||
index: usize,
|
||||
}
|
||||
struct StrictMap<'a> {
|
||||
iter: serde_json::map::Iter<'a>,
|
||||
path: &'a str,
|
||||
current_key: Option<&'a str>,
|
||||
pending: Option<&'a Value>,
|
||||
}
|
||||
struct StrictEnum<'a> {
|
||||
variant: &'a str,
|
||||
value: &'a Value,
|
||||
path: String,
|
||||
}
|
||||
|
||||
fn format_expected(fields: &[&str]) -> String {
|
||||
match fields {
|
||||
[] => "there are no fields".into(),
|
||||
[one] => format!("expected `{one}`"),
|
||||
[a, b] => format!("expected `{a}` or `{b}`"),
|
||||
_ => {
|
||||
let list = fields.iter().map(|f| format!("`{f}`")).collect::<Vec<_>>().join(", ");
|
||||
format!("expected one of {list}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Internally tagged enums buffer their fields before decoding them, bypassing StrictMap.
|
||||
fn validate_text_fill(path: &str, fill: &Value) -> Result<(), serde_json::Error> {
|
||||
let fill_path = format!("{path}.fill");
|
||||
let tag = fill.get("type").or_else(|| fill.get(0));
|
||||
// Serde's numeric variant indices follow the TextFill declaration order.
|
||||
let fields: &[_] = match (tag.and_then(Value::as_str), tag.and_then(Value::as_u64)) {
|
||||
(Some("none"), _) | (_, Some(0)) => &["type"],
|
||||
(Some("solid"), _) | (_, Some(1)) => &["type", "color", "transparency"],
|
||||
(Some("gradient"), _) | (_, Some(2)) => &["type", "stops", "angle"],
|
||||
_ => return Ok(()), // The regular decoder reports missing or unknown tags.
|
||||
};
|
||||
let stops = if let Some(map) = fill.as_object() {
|
||||
if let Some(key) = map.keys().find(|key| !fields.contains(&key.as_str())) {
|
||||
return Err(serde::de::Error::custom(format!("`{fill_path}`: unknown field `{key}`, {}", format_expected(fields))));
|
||||
}
|
||||
map.get("stops")
|
||||
} else if fields.contains(&"stops") {
|
||||
fill.get(1)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(stops) = stops.and_then(Value::as_array) {
|
||||
for (i, stop) in stops.iter().enumerate() {
|
||||
let stop_path = format!("{fill_path}.stops[{i}]");
|
||||
<wordcraft_doc::wordart::GradStop as serde::Deserialize>::deserialize(StrictDe { value: stop, path: stop_path.clone() })
|
||||
.map_err(|e| with_path(&stop_path, e))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_path_prefix(msg: &str, path: &str) -> bool {
|
||||
msg.strip_prefix('`').and_then(|rest| rest.strip_prefix(path)).is_some_and(|rest| matches!(rest.chars().next(), Some('`' | '.' | '[')))
|
||||
}
|
||||
|
||||
fn with_path(path: &str, err: serde_json::Error) -> serde_json::Error {
|
||||
let msg = err.to_string();
|
||||
if has_path_prefix(&msg, path) { err } else { serde::de::Error::custom(format!("`{path}`: {msg}")) }
|
||||
}
|
||||
|
||||
impl<'de> SeqAccess<'de> for StrictSeq<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn next_element_seed<S: DeserializeSeed<'de>>(&mut self, seed: S) -> Result<Option<S::Value>, Self::Error> {
|
||||
let Some(v) = self.iter.next() else { return Ok(None) };
|
||||
let idx = self.index;
|
||||
self.index += 1;
|
||||
let child = format!("{}[{idx}]", self.path);
|
||||
seed.deserialize(StrictDe { value: v, path: child.clone() }).map(Some).map_err(|e| with_path(&child, e))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> MapAccess<'de> for StrictMap<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> {
|
||||
let Some((k, v)) = self.iter.next() else { return Ok(None) };
|
||||
self.current_key = Some(k.as_str());
|
||||
self.pending = Some(v);
|
||||
seed.deserialize(k.as_str().into_deserializer()).map(Some)
|
||||
}
|
||||
fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, Self::Error> {
|
||||
let v = self.pending.take().ok_or_else(|| serde::de::Error::custom("missing map value"))?;
|
||||
let key = self.current_key.take().unwrap_or("");
|
||||
let child = format!("{}.{key}", self.path);
|
||||
seed.deserialize(StrictDe { value: v, path: child.clone() }).map_err(|e| with_path(&child, e))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> VariantAccess<'de> for StrictEnum<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn unit_variant(self) -> Result<(), Self::Error> {
|
||||
serde::Deserialize::deserialize(self.value)
|
||||
}
|
||||
fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, Self::Error> {
|
||||
let child = format!("{}.{}", self.path, self.variant);
|
||||
seed.deserialize(StrictDe { value: self.value, path: child.clone() }).map_err(|e| with_path(&child, e))
|
||||
}
|
||||
fn tuple_variant<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
let child = format!("{}.{}", self.path, self.variant);
|
||||
serde::Deserializer::deserialize_tuple(StrictDe { value: self.value, path: child.clone() }, len, visitor)
|
||||
.map_err(|e| with_path(&child, e))
|
||||
}
|
||||
fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> {
|
||||
let child = format!("{}.{}", self.path, self.variant);
|
||||
serde::Deserializer::deserialize_struct(StrictDe { value: self.value, path: child.clone() }, "", fields, visitor)
|
||||
.map_err(|e| with_path(&child, e))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> EnumAccess<'de> for StrictEnum<'_> {
|
||||
type Error = serde_json::Error;
|
||||
type Variant = Self;
|
||||
fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> {
|
||||
let val = seed.deserialize(self.variant.into_deserializer()).map_err(|e| with_path(&self.path, e))?;
|
||||
Ok((val, self))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserializer<'de> for StrictDe<'_> {
|
||||
type Error = serde_json::Error;
|
||||
|
||||
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
match self.value {
|
||||
Value::Null => visitor.visit_unit(),
|
||||
Value::Bool(b) => visitor.visit_bool(*b),
|
||||
Value::Number(n) => n.deserialize_any(visitor),
|
||||
Value::String(s) => visitor.visit_str(s),
|
||||
Value::Array(arr) => visitor.visit_seq(StrictSeq { iter: arr.iter(), path: &self.path, index: 0 }),
|
||||
Value::Object(map) => visitor.visit_map(StrictMap { iter: map.iter(), path: &self.path, current_key: None, pending: None }),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
if self.value.is_null() { visitor.visit_none() } else { visitor.visit_some(self) }
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V: Visitor<'de>>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error> {
|
||||
match self.value {
|
||||
Value::String(s) => visitor.visit_enum(s.as_str().into_deserializer()).map_err(|e| with_path(&self.path, e)),
|
||||
Value::Object(map) if map.len() == 1 => {
|
||||
if let Some((k, v)) = map.iter().next() {
|
||||
visitor.visit_enum(StrictEnum { variant: k, value: v, path: self.path })
|
||||
} else {
|
||||
self.deserialize_any(visitor)
|
||||
}
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_struct<V: Visitor<'de>>(
|
||||
self,
|
||||
name: &'static str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error> {
|
||||
if name == "TextEffects" {
|
||||
let fill = match self.value {
|
||||
Value::Array(values) => fields.iter().position(|&field| field == "fill").and_then(|index| values.get(index)),
|
||||
_ => self.value.get("fill"),
|
||||
};
|
||||
if let Some(fill) = fill {
|
||||
validate_text_fill(&self.path, fill)?;
|
||||
}
|
||||
}
|
||||
if let Value::Object(map) = self.value {
|
||||
for key in map.keys() {
|
||||
if !fields.contains(&key.as_str()) {
|
||||
return Err(serde::de::Error::custom(format!("`{}`: unknown field `{key}`, {}", self.path, format_expected(fields))));
|
||||
}
|
||||
}
|
||||
return visitor.visit_map(StrictMap { iter: map.iter(), path: &self.path, current_key: None, pending: None });
|
||||
}
|
||||
self.deserialize_any(visitor)
|
||||
}
|
||||
|
||||
serde::forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
|
||||
unit unit_struct seq tuple tuple_struct map identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
T::deserialize(StrictDe { value: v, path: section.to_string() }).map_err(|e| {
|
||||
let msg = e.to_string();
|
||||
if has_path_prefix(&msg, section) { CmdError::Params(msg) } else { CmdError::Params(format!("`{section}`: {msg}")) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Modify a style's character and paragraph formatting, display name or next-paragraph style.
|
||||
pub(super) fn modify_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let id = style_id(s, p::req_str(v, "style")?)?;
|
||||
let chr: Option<CharProps> = v.get("chr").map(|c| deserialize_strict("chr", c)).transpose()?;
|
||||
let para: Option<ParaProps> = v.get("para").map(|c| deserialize_strict("para", c)).transpose()?;
|
||||
let chr: Option<CharProps> = v.get("chr").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
let para: Option<ParaProps> =
|
||||
v.get("para").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
let next = p::str(v, "next").map(str::to_string);
|
||||
let name = p::str(v, "name").map(str::to_string);
|
||||
let d = &s.doc.styles.default_chr;
|
||||
@@ -599,20 +387,3 @@ pub(super) fn set_visibility(s: &mut Session, v: &Value) -> CmdResult {
|
||||
touch_all(s);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nested_type_and_enum_errors_include_full_path() {
|
||||
let err = deserialize_strict::<ParaProps>("para", &json!({"lineSpacing": {"rule": "bogus"}})).unwrap_err();
|
||||
assert!(matches!(err, CmdError::Params(ref msg) if msg.contains("`para.lineSpacing.rule`")), "{err:?}");
|
||||
|
||||
let err = deserialize_strict::<ParaProps>("para", &json!({"borders": {"top": {"width": "bad"}}})).unwrap_err();
|
||||
assert!(matches!(err, CmdError::Params(ref msg) if msg.contains("`para.borders.top.width`")), "{err:?}");
|
||||
|
||||
let err = deserialize_strict::<ParaProps>("para", &json!({"tabs": [{"pos": "bad"}]})).unwrap_err();
|
||||
assert!(matches!(err, CmdError::Params(ref msg) if msg.contains("`para.tabs[0].pos`")), "{err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,8 +20,7 @@ use fields::caption;
|
||||
#[cfg(test)]
|
||||
use fields::output_fields_with;
|
||||
pub use fields::{
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, caption_preview, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in,
|
||||
update_seq,
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq,
|
||||
};
|
||||
pub(crate) use fields::{page_at, page_formats, page_label, page_text};
|
||||
pub(super) use notes::note_options;
|
||||
|
||||
@@ -27,29 +27,12 @@ pub const CHAPTER_SEPARATORS: [&str; 5] = ["-", ".", ":", "\u{2014}", "\u{2013}"
|
||||
/// a chapter number (`STYLEREF n \s` and a separator) and a `SEQ label \* format \s n` number
|
||||
/// (ECMA-376 §17.16.5.56, §17.16.5.59).
|
||||
pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let text = p::str(v, "text").unwrap_or("");
|
||||
s.doc.insert_block(story, &at, Block::Para(caption_paragraph(v, text)?))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story, path: at, off });
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Number a prospective caption at its insertion site without changing the document or selection.
|
||||
pub fn caption_preview(s: &Session, v: &Value) -> Result<String, CmdError> {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let mut doc = s.doc.clone();
|
||||
doc.insert_block(story, &at, Block::Para(caption_paragraph(v, "")?))?;
|
||||
update_seq_in(&mut doc)?;
|
||||
Ok(doc.para(story, &at).map_or_else(String::new, Paragraph::plain_text))
|
||||
}
|
||||
|
||||
fn caption_paragraph(v: &Value, text: &str) -> Result<Paragraph, CmdError> {
|
||||
let label: String = p::str(v, "label").unwrap_or("Figure").chars().filter(|c| !matches!(c, '"' | '\\') && !c.is_control()).take(40).collect();
|
||||
let label = if label.trim().is_empty() { "Figure".to_string() } else { label.trim().to_string() };
|
||||
// SEQ identifiers are one word: Word joins a multi-word label with underscores.
|
||||
let ident = label.split_whitespace().collect::<Vec<_>>().join("_");
|
||||
let text = p::str(v, "text").unwrap_or("").to_string();
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let format = seq_format(p::str(v, "format").unwrap_or("ARABIC"));
|
||||
let chapter = p::u64(v, "chapter").filter(|l| (1..=9).contains(l));
|
||||
let sep = p::str(v, "separator").and_then(|x| CHAPTER_SEPARATORS.iter().find(|s| **s == x)).copied().unwrap_or("-");
|
||||
@@ -68,15 +51,10 @@ fn caption_paragraph(v: &Value, text: &str) -> Result<Paragraph, CmdError> {
|
||||
if !text.is_empty() {
|
||||
para.insert_text(para.len(), &format!(": {text}"), &CharProps::default())?;
|
||||
}
|
||||
Ok(para)
|
||||
}
|
||||
|
||||
fn caption_site(s: &Session, v: &Value) -> (StoryRef, Path) {
|
||||
// A selected picture, shape or chart: next to the paragraph holding it, in the same cell or
|
||||
// text box (#1230). Otherwise next to the caret's top-level block: a paragraph, or the whole
|
||||
// table it is in.
|
||||
let f = &s.sel.focus;
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let f = s.sel.focus.clone();
|
||||
let at = match crate::cmd::objects::object_selection(s) {
|
||||
Some((pos, _)) => {
|
||||
let k = pos.path.last();
|
||||
@@ -87,7 +65,11 @@ fn caption_site(s: &Session, v: &Value) -> (StoryRef, Path) {
|
||||
Path::top(if above { top } else { top.saturating_add(1) })
|
||||
}
|
||||
};
|
||||
(f.story, at)
|
||||
s.doc.insert_block(f.story, &at, Block::Para(para))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(f.story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story: f.story, path: at, off });
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Renumber the body's SEQ fields in document order, honouring `\* format`, `\s level` (restart
|
||||
@@ -96,15 +78,11 @@ fn caption_site(s: &Session, v: &Value) -> (StoryRef, Path) {
|
||||
/// the last level-n heading's number, or its count when the heading isn't numbered) and the
|
||||
/// text or number of the nearest paragraph of a style.
|
||||
pub fn update_seq(s: &mut Session) -> Result<(), CmdError> {
|
||||
update_seq_in(&mut s.doc)
|
||||
}
|
||||
|
||||
fn update_seq_in(doc: &mut wordcraft_doc::Document) -> Result<(), CmdError> {
|
||||
// Numbers first: a STYLEREF to a heading that holds a SEQ field shows its new number.
|
||||
let numbers = seq_results(doc);
|
||||
apply_results(doc, numbers)?;
|
||||
let refs = styleref_results(doc);
|
||||
apply_results(doc, refs)
|
||||
let numbers = seq_results(&s.doc);
|
||||
apply_results(&mut s.doc, numbers)?;
|
||||
let refs = styleref_results(&s.doc);
|
||||
apply_results(&mut s.doc, refs)
|
||||
}
|
||||
|
||||
/// A field's fresh result: its story and paragraph, its object index there and the text.
|
||||
|
||||
@@ -44,17 +44,11 @@ fn in_merged_cell(doc: &wordcraft_doc::Document, path: &Path) -> bool {
|
||||
pub(super) fn para_numbers(doc: &wordcraft_doc::Document) -> std::collections::HashMap<Path, ParaNumber> {
|
||||
let mut counters = Counters::default();
|
||||
let mut out = std::collections::HashMap::new();
|
||||
// The paragraph before ended a section: the lists that start over there do (#7382).
|
||||
let mut section_ended = false;
|
||||
for path in doc.para_paths(StoryRef::Body) {
|
||||
if std::mem::take(&mut section_ended) {
|
||||
counters.section_break(&doc.numbering);
|
||||
}
|
||||
let Some(p) = doc.para(StoryRef::Body, &path) else { continue };
|
||||
section_ended = p.section.is_some();
|
||||
if in_merged_cell(doc, &path) {
|
||||
continue;
|
||||
}
|
||||
let Some(p) = doc.para(StoryRef::Body, &path) else { continue };
|
||||
let Some(n) = p.props.numbering.or_else(|| doc.styles.resolve_para(&p.props).numbering).filter(|n| n.num != 0) else { continue };
|
||||
let Some((_, def)) = counters.next_label(&doc.numbering, n.num, n.level) else { continue };
|
||||
if def.format == NumFormat::Bullet {
|
||||
|
||||
@@ -1129,36 +1129,6 @@ fn a_missing_references_error_is_in_the_interface_language() {
|
||||
assert_eq!(shown, [french, "Target"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_context_ref_keeps_an_ancestor_when_the_label_contains_literal_percent_zero() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::numbering::Level;
|
||||
use wordcraft_doc::props::NumRef;
|
||||
use wordcraft_doc::{Document, ListKind};
|
||||
|
||||
for (template, own, full) in [("%0-%2.", "%0-1", "1%0-1"), ("%1-%2.", "1-1", "1-1"), ("(%2).", "(1)", "1(1)")] {
|
||||
let mut doc = Document::from_text("Parent\nTarget\nRefs ");
|
||||
let numbering = Arc::make_mut(&mut doc.numbering);
|
||||
let num = numbering.add_list(ListKind::Numbered);
|
||||
numbering.nums[0].level_overrides = vec![(1, Level { text: template.into(), ..Default::default() })];
|
||||
for level in 0..=1u8 {
|
||||
doc.para_mut(StoryRef::Body, &Path::top(usize::from(level))).unwrap().props.numbering = Some(NumRef { num, level });
|
||||
}
|
||||
|
||||
let mut s = Session::new(doc);
|
||||
s.run("select.text", &json!({"text": "Target"})).unwrap();
|
||||
s.run("insert.bookmark", &json!({"name": "Mark"})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
for instr in [r"REF Mark \n", r"REF Mark \w"] {
|
||||
s.run("insert.field", &json!({"instr": instr})).unwrap();
|
||||
s.run("text.insert", &json!({"text": " "})).unwrap();
|
||||
}
|
||||
let refs = stale_last_paragraph(&mut s, "stale");
|
||||
update_fields(&mut s).unwrap();
|
||||
assert_eq!(results_in(&s.doc, &refs), [own, full], "{template}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A REF showing the bookmarked paragraph's number (`\r`, `\n`, `\w`), which output doesn't
|
||||
/// compute, keeps its stored number when printed or exported rather than show the paragraph's
|
||||
/// text; a plain REF to the same bookmark is filled in.
|
||||
|
||||
@@ -121,14 +121,8 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
// Every numbered paragraph advances the list counters, so an entry carries the number its
|
||||
// heading shows (`1.1`), followed by the level's separator, as Word writes it.
|
||||
let mut counters = Counters::default();
|
||||
// The paragraph before ended a section: the lists that start over there do (#7382).
|
||||
let mut section_ended = false;
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
if std::mem::take(&mut section_ended) {
|
||||
counters.section_break(&s.doc.numbering);
|
||||
}
|
||||
let Some(p) = s.doc.para(StoryRef::Body, &path) else { continue };
|
||||
section_ended = p.section.is_some();
|
||||
let number = p
|
||||
.props
|
||||
.numbering
|
||||
|
||||
@@ -14,12 +14,11 @@ mod comments;
|
||||
mod proofing;
|
||||
pub use proofing::thesaurus_word;
|
||||
|
||||
pub(crate) use changes::ReviewTarget;
|
||||
pub(crate) use changes::StyleTarget;
|
||||
pub use changes::{
|
||||
DELETION_TEXT_CHARS, DeletionBalloon, deletion_balloons, format_changes, has_deletions, has_format_changes, move_changes, tracking_json,
|
||||
};
|
||||
use changes::{list_changes, nav_change, resolve_all_then, resolve_sel_then, tracking_options};
|
||||
pub use comments::resolve_comment_target;
|
||||
pub use comments::{comment_list, comment_range_at_caret};
|
||||
use comments::{comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, resolve_comment};
|
||||
use proofing::{all_issues, issue_at, next_issue, suggestions, thesaurus, word_count};
|
||||
|
||||
@@ -107,7 +107,7 @@ fn resolve_cell(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, ac
|
||||
let row = t.rows.get(r);
|
||||
t.props.fmt_change.is_some()
|
||||
|| row.is_some_and(|x| x.props.fmt_change.is_some())
|
||||
|| row.and_then(|x| x.cells.get(c)).is_some_and(|x| x.props.fmt_change.is_some() || x.props.merge_change.is_some())
|
||||
|| row.and_then(|x| x.cells.get(c)).is_some_and(|x| x.props.fmt_change.is_some())
|
||||
});
|
||||
if !has {
|
||||
return Ok(false);
|
||||
@@ -138,112 +138,45 @@ fn resolve_styles_sel(s: &mut Session, whole_body: bool, accept: bool) -> Result
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The change Next / Previous Change selected when the selection alone can't say which one it is,
|
||||
/// for the Accept or Reject that follows, while the selection stays where the navigation left it:
|
||||
/// a style-definition change (`style`; every one sits at the same collapsed anchor at the start
|
||||
/// of the document, #2697), or a table's, row's or cell's change (`style` `None`: formatting, or
|
||||
/// a cell's tracked merge or split, at the start of the cell, where tracked text may start too).
|
||||
/// The style-definition change Next / Previous Change selected (#2697). Every style change sits
|
||||
/// at the same collapsed anchor at the start of the document, so the selection alone can't say
|
||||
/// which one it is: this does, for the Accept or Reject that follows, while the selection stays
|
||||
/// where the navigation left it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct ReviewTarget {
|
||||
pub(crate) struct StyleTarget {
|
||||
document: u64,
|
||||
sel: Selection,
|
||||
style: Option<String>,
|
||||
style: String,
|
||||
rev: u32,
|
||||
/// For a table's, row's or cell's change, which one: several share the cell's start, and
|
||||
/// one revision may have made more than one of them.
|
||||
pub(crate) scope: Option<Scope>,
|
||||
}
|
||||
|
||||
/// Which of the changes at the start of a table cell a change is: the table's formatting, its
|
||||
/// row's, the cell's, or the cell's tracked merge or split.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Scope {
|
||||
Table,
|
||||
Row,
|
||||
Cell,
|
||||
Merge,
|
||||
}
|
||||
|
||||
/// The navigated style change, when the selection is still the one navigation made.
|
||||
fn navigated_target(s: &Session) -> Option<ReviewTarget> {
|
||||
s.review_target.clone().filter(|t| t.document == s.document_id() && t.sel == s.sel)
|
||||
fn navigated_style(s: &Session) -> Option<StyleTarget> {
|
||||
s.review_style.clone().filter(|t| t.document == s.document_id() && t.sel == s.sel)
|
||||
}
|
||||
|
||||
/// Accept or reject the navigated style change alone: that revision in that style. Returns whether
|
||||
/// it was still there.
|
||||
fn resolve_style_change(s: &mut Session, style: &str, rev: u32, accept: bool) -> bool {
|
||||
fn resolve_style_change(s: &mut Session, t: &StyleTarget, accept: bool) -> bool {
|
||||
let revs = |st: &wordcraft_doc::styles::Style| [st.para_change.as_ref().map(|c| c.rev), st.chr_change.as_ref().map(|c| c.rev)];
|
||||
if !s.doc.styles.styles.iter().any(|st| st.id == style && revs(st).contains(&Some(rev))) {
|
||||
if !s.doc.styles.styles.iter().any(|st| st.id == t.style && revs(st).contains(&Some(t.rev))) {
|
||||
return false;
|
||||
}
|
||||
for st in std::sync::Arc::make_mut(&mut s.doc.styles).styles.iter_mut().filter(|st| st.id == style) {
|
||||
fmt_revisions::resolve_style_rev(st, rev, accept);
|
||||
for st in std::sync::Arc::make_mut(&mut s.doc.styles).styles.iter_mut().filter(|st| st.id == t.style) {
|
||||
fmt_revisions::resolve_style_rev(st, t.rev, accept);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Select change `c` and remember which style or table change it is, if it is one.
|
||||
/// Select change `c` and remember which style change it is, if it is one.
|
||||
fn select_change(s: &mut Session, c: &Change) {
|
||||
s.sel = Selection { anchor: c.a.clone(), focus: c.b.clone() };
|
||||
s.review_target = c.rev.filter(|_| c.style.is_some() || c.scope.is_some()).map(|rev| ReviewTarget {
|
||||
document: s.document_id(),
|
||||
sel: s.sel.clone(),
|
||||
style: c.style.clone(),
|
||||
rev,
|
||||
scope: c.scope,
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether `c` is the change target `t` names.
|
||||
fn is_target(c: &Change, t: &ReviewTarget) -> bool {
|
||||
c.rev == Some(t.rev) && c.style == t.style && c.scope == t.scope && (t.style.is_some() || c.a == t.sel.anchor)
|
||||
}
|
||||
|
||||
/// Accept or reject the one table, row or cell change `scope` of the table cell `path` is in.
|
||||
/// Returns whether it was still there.
|
||||
fn resolve_scope(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, scope: Scope, accept: bool) -> Result<bool, CmdError> {
|
||||
let Some((tp, r, c)) = path.cell() else { return Ok(false) };
|
||||
let Some(t) = s.doc.table(story, &tp) else { return Ok(false) };
|
||||
let cell = t.rows.get(r).and_then(|x| x.cells.get(c));
|
||||
let there = match scope {
|
||||
Scope::Table => t.props.fmt_change.is_some(),
|
||||
Scope::Row => t.rows.get(r).is_some_and(|x| x.props.fmt_change.is_some()),
|
||||
Scope::Cell => cell.is_some_and(|x| x.props.fmt_change.is_some()),
|
||||
Scope::Merge => cell.is_some_and(|x| x.props.merge_change.is_some()),
|
||||
};
|
||||
if !there {
|
||||
return Ok(false);
|
||||
}
|
||||
let t = s.doc.table_mut(story, &tp)?;
|
||||
match scope {
|
||||
Scope::Table => fmt_revisions::resolve_table(t, accept),
|
||||
Scope::Row => {
|
||||
if let Some(row) = t.rows.get_mut(r) {
|
||||
fmt_revisions::resolve_row(row, accept);
|
||||
}
|
||||
}
|
||||
// The cell's formatting alone: a tracked merge it also has is a change of its own.
|
||||
Scope::Cell => {
|
||||
if let Some(cell) = t.rows.get_mut(r).and_then(|x| x.cells.get_mut(c)) {
|
||||
let merge = cell.props.merge_change.take();
|
||||
fmt_revisions::resolve_cell(cell, accept);
|
||||
cell.props.merge_change = merge;
|
||||
}
|
||||
}
|
||||
// Accepted or rejected alike, only the record goes: the cells stay as they are (Word).
|
||||
Scope::Merge => {
|
||||
if let Some(cell) = t.rows.get_mut(r).and_then(|x| x.cells.get_mut(c)) {
|
||||
cell.props.merge_change = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
s.review_style = c.style.clone().zip(c.rev).map(|(style, rev)| StyleTarget { document: s.document_id(), sel: s.sel.clone(), style, rev });
|
||||
}
|
||||
|
||||
/// A tracked change, for navigation and the Reviewing Pane: its range, kind (`insert`,
|
||||
/// `delete`, `format`, `cellMerge`, `cellSplit`), revision, and for a formatting change the
|
||||
/// properties it set; for a style-definition change, the style's id; whether it is a table's,
|
||||
/// row's or cell's (resolved with the cell, [`resolve_cell`]).
|
||||
/// `delete`, `format`), revision, and for a formatting change the properties it set; for a
|
||||
/// style-definition change, the style's id.
|
||||
struct Change {
|
||||
a: Pos,
|
||||
b: Pos,
|
||||
@@ -251,12 +184,11 @@ struct Change {
|
||||
rev: Option<u32>,
|
||||
props: Vec<Value>,
|
||||
style: Option<String>,
|
||||
pub(crate) scope: Option<Scope>,
|
||||
}
|
||||
|
||||
impl Change {
|
||||
fn format(a: Pos, b: Pos, rev: u32, props: Vec<Value>) -> Change {
|
||||
Change { a, b, kind: "format", rev: Some(rev), props, style: None, scope: None }
|
||||
Change { a, b, kind: "format", rev: Some(rev), props, style: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,7 +206,7 @@ fn mark_change(s: &Session, story: StoryRef, path: &wordcraft_doc::Path) -> Opti
|
||||
} else {
|
||||
a.clone()
|
||||
};
|
||||
Some(Change { a, b, kind, rev: p.mark.ins.or(p.mark.del), props: Vec::new(), style: None, scope: None })
|
||||
Some(Change { a, b, kind, rev: p.mark.ins.or(p.mark.del), props: Vec::new(), style: None })
|
||||
}
|
||||
|
||||
/// The kind of an insertion / deletion change: `insert`, `delete`, or for one end of a move
|
||||
@@ -332,7 +264,8 @@ fn resolve_loose_blocks(blocks: &mut wordcraft_doc::Blocks, accept: bool) -> Res
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Byte offset after resolving the runs in the endpoint's original paragraph.
|
||||
/// Byte offset after resolving the runs in the endpoint's original paragraph. Only apply it
|
||||
/// when paragraph removal or joining also moves the endpoint.
|
||||
fn resolved_offset(s: &Session, end: &Pos, accept: bool) -> usize {
|
||||
let Some(para) = s.doc.para_at(end) else { return end.off };
|
||||
let removed: usize = para
|
||||
@@ -374,8 +307,6 @@ fn remap_after_middle_paragraph(s: &mut Session, story: StoryRef, path: &wordcra
|
||||
|
||||
fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let mut offsets = [&s.sel.anchor, &s.sel.focus].map(|end| resolved_offset(s, end, accept));
|
||||
s.sel.anchor.off = offsets[0];
|
||||
s.sel.focus.off = offsets[1];
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st).into_iter().rev() {
|
||||
@@ -388,11 +319,10 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let prefix_len = resolve_para(s, st, &path, (0, len), (true, true), accept)?;
|
||||
if trailing && remove_trailing_para(s, st, &path)? {
|
||||
// Selection ends in the removed paragraph go to the end of the one before it;
|
||||
// keep that offset through any later remapping when earlier edits resolve.
|
||||
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(&mut offsets) {
|
||||
// clamping later would keep their offsets in that paragraph's text (#8500).
|
||||
for end in [&mut s.sel.anchor, &mut s.sel.focus] {
|
||||
if end.story == st && end.path == path {
|
||||
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
|
||||
*offset = end.off;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -585,14 +515,8 @@ fn remap_row_props(mut r: &mut wordcraft_doc::props::RowProps, remap: &[Option<u
|
||||
changed
|
||||
}
|
||||
|
||||
// A cell's tracked merge, in the cell's properties as they are and in any it had before a
|
||||
// formatting change (one is built without it, but one from elsewhere may hold it).
|
||||
fn collect_cell_props(mut c: &wordcraft_doc::props::CellProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
loop {
|
||||
if let Some(m) = c.merge_change {
|
||||
f(m.rev);
|
||||
}
|
||||
let Some(ch) = c.fmt_change.as_deref() else { break };
|
||||
while let Some(ch) = c.fmt_change.as_deref() {
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
@@ -602,15 +526,7 @@ fn collect_cell_props(mut c: &wordcraft_doc::props::CellProps, f: &mut impl FnMu
|
||||
|
||||
fn remap_cell_props(mut c: &mut wordcraft_doc::props::CellProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
loop {
|
||||
if let Some(m) = c.merge_change {
|
||||
let next = lookup_rev(m.rev, remap).map(|rev| wordcraft_doc::props::CellMergeChange { rev, ..m });
|
||||
if next != c.merge_change {
|
||||
c.merge_change = next;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
let Some(old) = step_prop_change(&mut c.fmt_change, remap, &mut changed) else { break };
|
||||
while let Some(old) = step_prop_change(&mut c.fmt_change, remap, &mut changed) {
|
||||
c = old;
|
||||
}
|
||||
changed
|
||||
@@ -1046,21 +962,12 @@ fn revision_span(p: &Paragraph, off: usize) -> Option<std::ops::Range<usize>> {
|
||||
fn resolve_sel(s: &mut Session, accept: bool, next: bool) -> CmdResult {
|
||||
// The style change Next / Previous Change selected: that one alone. A caret put at the
|
||||
// document start any other way resolves no style change.
|
||||
let navigated = navigated_target(s);
|
||||
s.review_target = None;
|
||||
if let Some(t) = navigated {
|
||||
let done = match &t.style {
|
||||
Some(style) => resolve_style_change(s, style, t.rev, accept),
|
||||
// A table's, row's or cell's change: that one, not the cell's others nor tracked text
|
||||
// that starts there too.
|
||||
None => match t.scope {
|
||||
Some(scope) => resolve_scope(s, t.sel.anchor.story, &t.sel.anchor.path, scope, accept)?,
|
||||
None => false,
|
||||
},
|
||||
};
|
||||
if done {
|
||||
return if next { select_next_unresolved(s) } else { sel_result(s) };
|
||||
}
|
||||
let navigated = navigated_style(s);
|
||||
s.review_style = None;
|
||||
if let Some(t) = navigated
|
||||
&& resolve_style_change(s, &t, accept)
|
||||
{
|
||||
return if next { select_next_unresolved(s) } else { sel_result(s) };
|
||||
}
|
||||
let (a, b) = s.sel.ordered();
|
||||
// Capture this before text revisions are resolved: accepting a deletion or rejecting an
|
||||
@@ -1131,39 +1038,19 @@ fn changes(s: &Session) -> Vec<Change> {
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
let Some(p) = s.doc.para(StoryRef::Body, &path) else { continue };
|
||||
// A table's, row's and cell's changes sit at the start of the cell's first paragraph.
|
||||
// At the cell's first paragraph of its own: after a nested table that starts the cell, say.
|
||||
if let Some((tp, r, c)) = path.cell()
|
||||
if path.last() == 0
|
||||
&& let Some((tp, r, c)) = path.cell()
|
||||
&& let Some(t) = s.doc.table(StoryRef::Body, &tp)
|
||||
&& let Some(cell) = t.rows.get(r).and_then(|x| x.cells.get(c))
|
||||
&& cell.blocks.iter().position(|b| b.as_para().is_some()) == Some(path.last())
|
||||
{
|
||||
let row = t.rows.get(r);
|
||||
let cell = Some(cell);
|
||||
let cell = row.and_then(|x| x.cells.get(c));
|
||||
let found = [
|
||||
(r == 0 && c == 0)
|
||||
.then(|| t.props.fmt_change.as_ref().map(|ch| (Scope::Table, ch.rev, fmt_revisions::table_diff(&t.props))))
|
||||
.flatten(),
|
||||
(c == 0)
|
||||
.then(|| row.and_then(|x| x.props.fmt_change.as_ref().map(|ch| (Scope::Row, ch.rev, fmt_revisions::row_diff(&x.props)))))
|
||||
.flatten(),
|
||||
cell.and_then(|x| x.props.fmt_change.as_ref().map(|ch| (Scope::Cell, ch.rev, fmt_revisions::cell_diff(&x.props)))),
|
||||
(r == 0 && c == 0).then(|| t.props.fmt_change.as_ref().map(|ch| (ch.rev, fmt_revisions::table_diff(&t.props)))).flatten(),
|
||||
(c == 0).then(|| row.and_then(|x| x.props.fmt_change.as_ref().map(|ch| (ch.rev, fmt_revisions::row_diff(&x.props))))).flatten(),
|
||||
cell.and_then(|x| x.props.fmt_change.as_ref().map(|ch| (ch.rev, fmt_revisions::cell_diff(&x.props)))),
|
||||
];
|
||||
for (scope, rev, props) in found.into_iter().flatten() {
|
||||
out.push(Change { scope: Some(scope), ..Change::format(mk(&path, 0), mk(&path, 0), rev, props) });
|
||||
}
|
||||
// A tracked merge or split of the cell: merged cells when the cell is in a merge after
|
||||
// it, else split cells (Word for Windows).
|
||||
if let Some(m) = cell.and_then(|x| x.props.merge_change) {
|
||||
let kind = if m.v_merge.is_some() { "cellMerge" } else { "cellSplit" };
|
||||
out.push(Change {
|
||||
a: mk(&path, 0),
|
||||
b: mk(&path, 0),
|
||||
kind,
|
||||
rev: Some(m.rev),
|
||||
props: Vec::new(),
|
||||
style: None,
|
||||
scope: Some(Scope::Merge),
|
||||
});
|
||||
for (rev, props) in found.into_iter().flatten() {
|
||||
out.push(Change::format(mk(&path, 0), mk(&path, 0), rev, props));
|
||||
}
|
||||
}
|
||||
if let Some(ch) = &p.props.fmt_change {
|
||||
@@ -1172,22 +1059,13 @@ fn changes(s: &Session) -> Vec<Change> {
|
||||
for (r, c) in p.run_ranges() {
|
||||
let kind = run_kind(&s.doc, c.ins, c.del);
|
||||
if !kind.is_empty() {
|
||||
out.push(Change {
|
||||
a: mk(&path, r.start),
|
||||
b: mk(&path, r.end),
|
||||
kind,
|
||||
rev: c.ins.or(c.del),
|
||||
props: Vec::new(),
|
||||
style: None,
|
||||
scope: None,
|
||||
});
|
||||
out.push(Change { a: mk(&path, r.start), b: mk(&path, r.end), kind, rev: c.ins.or(c.del), props: Vec::new(), style: None });
|
||||
}
|
||||
let Some(ch) = &c.fmt_change else { continue };
|
||||
let props = fmt_revisions::char_diff(c);
|
||||
// Neighbouring runs changed the same way by the same revision are one change.
|
||||
if let Some(last) = out
|
||||
.last_mut()
|
||||
.filter(|l| l.kind == "format" && l.scope.is_none() && l.rev == Some(ch.rev) && l.b == mk(&path, r.start) && l.props == props)
|
||||
if let Some(last) =
|
||||
out.last_mut().filter(|l| l.kind == "format" && l.rev == Some(ch.rev) && l.b == mk(&path, r.start) && l.props == props)
|
||||
{
|
||||
last.b = mk(&path, r.end);
|
||||
} else {
|
||||
@@ -1334,7 +1212,7 @@ pub(super) fn nav_change(s: &mut Session, dir: i32) -> CmdResult {
|
||||
let list = changes(s);
|
||||
let caret = s.sel.ordered();
|
||||
// From a navigated style change, the one next to it in the list (they share their anchor).
|
||||
let at = navigated_target(s).and_then(|t| list.iter().position(|c| is_target(c, &t)));
|
||||
let at = navigated_style(s).and_then(|t| list.iter().position(|c| c.style.as_deref() == Some(t.style.as_str()) && c.rev == Some(t.rev)));
|
||||
let t = match at {
|
||||
Some(i) if dir > 0 && i + 1 < list.len() => list.get(i + 1),
|
||||
Some(i) if dir < 0 && i > 0 => list.get(i - 1),
|
||||
@@ -1375,11 +1253,6 @@ pub(super) fn list_changes(s: &mut Session, _: &Value) -> CmdResult {
|
||||
v["description"] = json!(fmt_revisions::describe(&c.props));
|
||||
v["props"] = json!(c.props);
|
||||
}
|
||||
match c.kind {
|
||||
"cellMerge" => v["description"] = json!("Merged cells"),
|
||||
"cellSplit" => v["description"] = json!("Split cells"),
|
||||
_ => {}
|
||||
}
|
||||
// One end of a move: its name links it with the other end.
|
||||
if let Some(name) = rev.and_then(|r| r.move_name.as_deref()).filter(|_| c.kind.starts_with("move")) {
|
||||
v["move"] = json!(name);
|
||||
|
||||
@@ -186,21 +186,12 @@ fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
|
||||
ids
|
||||
}
|
||||
|
||||
/// Validates `review.resolveComment` parameters and resolves the target comment id (#9389).
|
||||
pub fn resolve_comment_target(s: &Session, v: &Value) -> Result<u32, CmdError> {
|
||||
validate_comment_id(v)?;
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
|
||||
if !s.doc.comments.contains_key(&id) {
|
||||
return Err(CmdError::Params("no such comment".into()));
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Resolve or reopen the whole discussion, even when the target is a reply. A toggle uses
|
||||
/// the target's state, matching its Resolve/Reopen button even in a mixed-state file.
|
||||
pub(super) fn resolve_comment(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let id = resolve_comment_target(s, v)?;
|
||||
let c = &s.doc.comments[&id];
|
||||
validate_comment_id(v)?;
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
|
||||
let c = s.doc.comments.get(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
|
||||
let resolved = p::bool(v, "value").unwrap_or(!c.resolved);
|
||||
let mut root = id;
|
||||
let mut seen = BTreeSet::new();
|
||||
|
||||
@@ -566,73 +566,6 @@ fn horizontal_arrows_distinguish_hidden_deletions_from_hidden_move_sources() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_moves_follow_layout_visibility_for_balloons_and_hidden_marks() {
|
||||
use wordcraft_doc::{Path, Pos, Revision, RevisionKind, StoryRef};
|
||||
|
||||
let mut s = Session::new(Document::from_text("one del two"));
|
||||
let id = s.run("insert.header", &json!({"text": "one del two"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
let header = StoryRef::Part(id);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
let del_start = "one ".len();
|
||||
let two_start = "one del ".len();
|
||||
for story in [StoryRef::Body, header] {
|
||||
s.run("select.range", &json!({"anchor": Pos::new(story, Path::top(0), del_start), "focus": Pos::new(story, Path::top(0), two_start)}))
|
||||
.unwrap();
|
||||
s.run("text.delete", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
s.run("review.trackingOptions", &json!({"balloons": "revisions"})).unwrap();
|
||||
assert!(s.revisions_in_balloons());
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, 0)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, two_start), "Body in balloons skips deleted word on Ctrl+Right");
|
||||
s.run("caret.wordLeft", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0), "Body in balloons skips deleted word on Ctrl+Left");
|
||||
|
||||
s.run("caret.set", &json!({"pos": Pos::new(header, Path::top(0), 0)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::new(header, Path::top(0), del_start), "Header inline keeps deleted word stop on Ctrl+Right");
|
||||
|
||||
s.run("view.commentsPane", &json!({"value": true})).unwrap();
|
||||
assert!(!s.revisions_in_balloons());
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, 0)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, del_start), "Body stops at deleted word once revisions move inline");
|
||||
|
||||
let mut doc = Document::from_text("one del mov two");
|
||||
let deletion = Revision::new(RevisionKind::Delete, "Author", "");
|
||||
let source = Revision { move_name: Some("Move1".into()), ..deletion.clone() };
|
||||
let destination = Revision { kind: RevisionKind::Insert, ..source.clone() };
|
||||
doc.revisions.extend([deletion, source, destination]);
|
||||
let mov_start = "one del ".len();
|
||||
let end_two_start = "one del mov ".len();
|
||||
doc.format_range(&Pos::body(0, del_start), &Pos::body(0, mov_start), &|c| c.del = Some(0)).unwrap();
|
||||
doc.format_range(&Pos::body(0, mov_start), &Pos::body(0, end_two_start), &|c| c.del = Some(1)).unwrap();
|
||||
doc.format_range(&Pos::body(0, end_two_start), &Pos::body(0, "one del mov two".len()), &|c| c.ins = Some(2)).unwrap();
|
||||
let mut s = Session::new(doc);
|
||||
|
||||
for (delete_mark, move_from_mark, right_from, right_to, left_to) in [
|
||||
("strikethrough", "strikethrough", del_start, mov_start, mov_start),
|
||||
("hidden", "strikethrough", 0, mov_start, mov_start),
|
||||
("strikethrough", "hidden", del_start, end_two_start, del_start),
|
||||
("hidden", "hidden", 0, end_two_start, 0),
|
||||
] {
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": delete_mark, "moveFromMark": move_from_mark})).unwrap();
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, right_from)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, right_to), "Ctrl+Right ({delete_mark}, {move_from_mark})");
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, end_two_start)})).unwrap();
|
||||
s.run("caret.wordLeft", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, left_to), "Ctrl+Left ({delete_mark}, {move_from_mark})");
|
||||
}
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": "hidden", "moveFromMark": "strikethrough"})).unwrap();
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, mov_start)})).unwrap();
|
||||
s.run("caret.wordLeft", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left from mov skips hidden del");
|
||||
}
|
||||
|
||||
fn body_para(s: &Session) -> &wordcraft_doc::Paragraph {
|
||||
s.doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap()
|
||||
}
|
||||
@@ -2157,288 +2090,3 @@ fn accept_and_reject_all_reach_fixed_point_with_buried_rev_in_invalid_outer_chan
|
||||
assert_eq!(s.doc, after_first, "{cmd} mixed: second pass must be a no-op");
|
||||
}
|
||||
}
|
||||
|
||||
/// wordcraft#7207: a tracked merge or split of a cell (`w:cellMerge`) is listed as Word for Windows
|
||||
/// lists it, keeps naming its revision when other changes are resolved, and accepting or rejecting
|
||||
/// it drops only the record: the cells stay as they are.
|
||||
#[test]
|
||||
fn a_tracked_cell_merge_is_listed_and_resolved_as_word_does() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::{CellMergeChange, MergeMark, VMerge};
|
||||
use wordcraft_doc::table::Table;
|
||||
use wordcraft_doc::{Block, Path, Pos, Revision, RevisionKind, StoryRef};
|
||||
let merges = |s: &Session| -> Vec<Option<CellMergeChange>> {
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).expect("table");
|
||||
t.rows.iter().flat_map(|r| r.cells.iter().map(|c| c.props.merge_change)).collect()
|
||||
};
|
||||
for (accept, one, all) in [(true, "review.accept", "review.acceptAll"), (false, "review.reject", "review.rejectAll")] {
|
||||
let mut d = Document::from_text("Intro\nafter");
|
||||
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
|
||||
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", "2020-03-01T12:00:00Z"));
|
||||
d.format_range(&Pos::body(0, 0), &Pos::body(0, 5), &|c| c.ins = Some(0)).unwrap();
|
||||
let mut t = Table::new(2, 2, 288.0);
|
||||
// The right column merged down: resolving the records leaves it so.
|
||||
t.rows[0].cells[1].props.vmerge = VMerge::Restart;
|
||||
t.rows[1].cells[1].props.vmerge = VMerge::Continue;
|
||||
t.rows[1].cells[0].props.merge_change =
|
||||
Some(CellMergeChange { rev: 1, v_merge: Some(MergeMark::Continue), v_merge_orig: Some(MergeMark::Restart) });
|
||||
t.rows[1].cells[1].props.merge_change = Some(CellMergeChange { rev: 1, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
|
||||
d.body.insert(1, Arc::new(Block::Table(t)));
|
||||
let mut s = Session::new(d);
|
||||
|
||||
let list = s.run("review.changes", &json!({})).unwrap();
|
||||
let cells: Vec<(String, String, String)> = list
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|c| c["kind"].as_str().is_some_and(|k| k.starts_with("cell")))
|
||||
.map(|c| (c["kind"].as_str().unwrap().into(), c["description"].as_str().unwrap_or("").into(), c["author"].as_str().unwrap_or("").into()))
|
||||
.collect();
|
||||
let want = |k: &str, d: &str| (k.to_string(), d.to_string(), "Reviewer".to_string());
|
||||
assert_eq!(cells, [want("cellMerge", "Merged cells"), want("cellSplit", "Split cells")]);
|
||||
|
||||
// The insertion alone: the records still name the reviewer's revision.
|
||||
s.sel = crate::Selection { anchor: Pos::body(0, 0), focus: Pos::body(0, 5) };
|
||||
s.run(one, &json!({})).unwrap();
|
||||
let named: Vec<Option<&str>> =
|
||||
merges(&s).into_iter().flatten().map(|m| s.doc.revisions.get(m.rev as usize).map(|r| r.author.as_str())).collect();
|
||||
assert_eq!(named, [Some("Reviewer"), Some("Reviewer")], "accept {accept}");
|
||||
|
||||
// The caret in the split cell: its record alone goes; the cells keep their merges.
|
||||
let table = s.doc.body.iter().position(|b| b.as_table().is_some()).unwrap();
|
||||
s.sel = crate::Selection::caret(Pos { story: StoryRef::Body, path: Path(vec![table as u32, 1, 1, 0]), off: 0 });
|
||||
s.run(one, &json!({})).unwrap();
|
||||
assert_eq!(merges(&s).iter().map(Option::is_some).collect::<Vec<_>>(), [false, false, true, false], "accept {accept}");
|
||||
s.run(all, &json!({})).unwrap();
|
||||
assert!(merges(&s).iter().all(Option::is_none));
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
let vmerges: Vec<VMerge> = t.rows.iter().flat_map(|r| &r.cells).map(|c| c.props.vmerge).collect();
|
||||
assert_eq!(vmerges, [VMerge::None, VMerge::Restart, VMerge::None, VMerge::Continue], "the cells stay as they are");
|
||||
assert!(s.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
|
||||
assert!(s.doc.revisions.is_empty(), "{:?}", s.doc.revisions);
|
||||
}
|
||||
}
|
||||
|
||||
/// wordcraft#7207: pasted content keeps its tracked cell merges naming the revisions it brings.
|
||||
#[test]
|
||||
fn an_adopted_tracked_cell_merge_names_its_revision() {
|
||||
use wordcraft_doc::props::{CellMergeChange, MergeMark};
|
||||
use wordcraft_doc::table::Table;
|
||||
use wordcraft_doc::{Block, Path, Revision, RevisionKind, StoryRef};
|
||||
let mut ours = Document::from_text("ours");
|
||||
ours.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
|
||||
let mut theirs = Document::from_text("theirs");
|
||||
theirs.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
|
||||
let mut t = Table::new(2, 1, 144.0);
|
||||
t.rows[1].cells[0].props.merge_change = Some(CellMergeChange { rev: 0, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
|
||||
// One naming a revision theirs doesn't have is dropped.
|
||||
t.rows[0].cells[0].props.merge_change = Some(CellMergeChange { rev: 7, ..CellMergeChange::default() });
|
||||
theirs.insert_block(StoryRef::Body, &Path::top(0), Block::Table(t)).unwrap();
|
||||
let frag = ours.adopt(theirs);
|
||||
let Some(Block::Table(t)) = frag.blocks.first() else { panic!("{:?}", frag.blocks) };
|
||||
assert_eq!(t.rows[0].cells[0].props.merge_change, None);
|
||||
let m = t.rows[1].cells[0].props.merge_change.expect("kept");
|
||||
assert_eq!(m.v_merge_orig, Some(MergeMark::Continue));
|
||||
assert_eq!(ours.revisions.get(m.rev as usize).map(|r| r.author.as_str()), Some("Reviewer"));
|
||||
}
|
||||
|
||||
/// wordcraft#7207: a tracked cell merge Accept All leaves (in a table nested past the depth it
|
||||
/// resolves) keeps naming its revision when the revisions are compacted.
|
||||
#[test]
|
||||
fn a_tracked_cell_merge_left_by_accept_all_keeps_its_revision() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::{CellMergeChange, MergeMark};
|
||||
use wordcraft_doc::table::Table;
|
||||
use wordcraft_doc::{Block, Paragraph, Pos, Revision, RevisionKind};
|
||||
let mut d = Document::from_text("Intro\nafter");
|
||||
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
|
||||
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
|
||||
d.format_range(&Pos::body(0, 0), &Pos::body(0, 5), &|c| c.ins = Some(0)).unwrap();
|
||||
let mut t = Table::new(1, 1, 144.0);
|
||||
t.rows[0].cells[0].props.merge_change = Some(CellMergeChange { rev: 1, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
|
||||
// A formatting change whose properties before it hold a merge record too.
|
||||
d.revisions.push(Revision::new(RevisionKind::Format, "Earlier", ""));
|
||||
let old = wordcraft_doc::props::CellProps { merge_change: Some(CellMergeChange { rev: 2, ..CellMergeChange::default() }), ..Default::default() };
|
||||
t.rows[0].cells[0].props.fmt_change = wordcraft_doc::props::PropChange::boxed(1, old);
|
||||
for _ in 0..20 {
|
||||
let mut outer = Table::new(1, 1, 144.0);
|
||||
outer.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
|
||||
t = outer;
|
||||
}
|
||||
d.body.insert(1, Arc::new(Block::Table(t)));
|
||||
let mut s = Session::new(d);
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
let mut t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
while let Some(inner) = t.rows[0].cells[0].blocks.iter().find_map(|b| b.as_table()) {
|
||||
t = inner;
|
||||
}
|
||||
let m = t.rows[0].cells[0].props.merge_change.expect("past the depth Accept All resolves");
|
||||
assert_eq!(s.doc.revisions.get(m.rev as usize).map(|r| r.author.as_str()), Some("Reviewer"), "{:?}", s.doc.revisions);
|
||||
let before = t.rows[0].cells[0].props.fmt_change.as_ref().and_then(|c| c.old.merge_change).expect("kept with the formatting change");
|
||||
assert_eq!(s.doc.revisions.get(before.rev as usize).map(|r| r.author.as_str()), Some("Earlier"));
|
||||
}
|
||||
|
||||
/// wordcraft#7207 review: Next Change on a cell's tracked split, where tracked text starts the
|
||||
/// cell too, then Reject resolves the split, not the text. A cell that starts with a nested table
|
||||
/// lists its tracked merge at its own first paragraph, which resolves it.
|
||||
#[test]
|
||||
fn a_navigated_cell_merge_is_the_one_resolved() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::{CellMergeChange, MergeMark};
|
||||
use wordcraft_doc::table::Table;
|
||||
use wordcraft_doc::{Block, CharProps, Paragraph, Path, Pos, Revision, RevisionKind, StoryRef};
|
||||
let mut d = Document::from_text("before\nafter");
|
||||
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
|
||||
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
|
||||
let mut t = Table::new(1, 2, 288.0);
|
||||
t.rows[0].cells[0].props.merge_change = Some(CellMergeChange { rev: 1, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
|
||||
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("new", CharProps { ins: Some(0), ..Default::default() })))];
|
||||
t.rows[0].cells[1].props.merge_change = Some(CellMergeChange { rev: 1, v_merge: Some(MergeMark::Continue), v_merge_orig: None });
|
||||
t.rows[0].cells[1].blocks = vec![Arc::new(Block::Table(Table::new(1, 1, 100.0))), Arc::new(Block::Para(Paragraph::new()))];
|
||||
d.body.insert(1, Arc::new(Block::Table(t)));
|
||||
let mut s = Session::new(d);
|
||||
let kinds = |s: &mut Session| -> Vec<String> {
|
||||
let list = s.run("review.changes", &json!({})).unwrap();
|
||||
list.as_array().unwrap().iter().map(|c| c["kind"].as_str().unwrap_or("").to_string()).collect()
|
||||
};
|
||||
// The inserted text and its paragraph mark are two insertions.
|
||||
assert_eq!(kinds(&mut s), ["cellSplit", "insert", "insert", "cellMerge"]);
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
s.run("review.nextChange", &json!({})).unwrap();
|
||||
s.run("review.reject", &json!({})).unwrap();
|
||||
assert_eq!(kinds(&mut s), ["insert", "insert", "cellMerge"], "the split's record went, the inserted text stays");
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
assert_eq!(t.rows[0].cells[0].blocks[0].as_para().map(|p| p.plain_text()), Some("new".to_string()));
|
||||
|
||||
s.sel = crate::Selection::caret(Pos { story: StoryRef::Body, path: Path(vec![1, 0, 1, 1]), off: 0 });
|
||||
s.run("review.accept", &json!({})).unwrap();
|
||||
assert_eq!(kinds(&mut s), ["insert", "insert"]);
|
||||
}
|
||||
|
||||
/// wordcraft#9768 review: a table's and its first cell's formatting changes from one revision share
|
||||
/// the cell's start; Next Change steps from one to the other and on, without sticking.
|
||||
#[test]
|
||||
fn next_change_steps_through_changes_sharing_a_cells_start() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::{CellProps, PropChange, TableProps};
|
||||
use wordcraft_doc::table::Table;
|
||||
use wordcraft_doc::{Block, Path, Pos, Revision, RevisionKind};
|
||||
let mut d = Document::from_text("before\nafter");
|
||||
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
|
||||
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
|
||||
d.format_range(&Pos::body(1, 0), &Pos::body(1, 5), &|c| c.ins = Some(0)).unwrap();
|
||||
let mut t = Table::new(1, 1, 144.0);
|
||||
t.props.fmt_change = PropChange::boxed(1, TableProps::default());
|
||||
t.rows[0].cells[0].props.fmt_change = PropChange::boxed(1, CellProps::default());
|
||||
d.body.insert(1, Arc::new(Block::Table(t)));
|
||||
let mut s = Session::new(d);
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
let mut seen = Vec::new();
|
||||
for _ in 0..3 {
|
||||
s.run("review.nextChange", &json!({})).unwrap();
|
||||
seen.push((s.sel.anchor.path.clone(), s.review_target.as_ref().and_then(|t| t.scope)));
|
||||
}
|
||||
use super::changes::Scope;
|
||||
let cell = Path(vec![1, 0, 0, 0]);
|
||||
assert_eq!(seen, [(cell.clone(), Some(Scope::Table)), (cell, Some(Scope::Cell)), (Path::top(2), None)]);
|
||||
}
|
||||
|
||||
/// wordcraft#9768 review: Reject on a navigated tracked merge resolves that record alone, not the
|
||||
/// cell's formatting change from another revision nor tracked text at the cell's start. A click
|
||||
/// elsewhere and back ends the navigation: Reject then takes the text, as at any caret.
|
||||
#[test]
|
||||
fn a_navigated_merge_resolves_alone_until_a_click_elsewhere() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::{CellMergeChange, CellProps, MergeMark, PropChange};
|
||||
use wordcraft_doc::table::Table;
|
||||
use wordcraft_doc::{Block, CharProps, Paragraph, Path, Pos, Revision, RevisionKind, StoryRef};
|
||||
let doc = || {
|
||||
let mut d = Document::from_text("before\nafter");
|
||||
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
|
||||
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
|
||||
d.revisions.push(Revision::new(RevisionKind::Format, "Formatter", ""));
|
||||
let mut t = Table::new(1, 1, 144.0);
|
||||
let cell = &mut t.rows[0].cells[0];
|
||||
cell.props.fmt_change = PropChange::boxed(2, CellProps::default());
|
||||
cell.props.merge_change = Some(CellMergeChange { rev: 1, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
|
||||
cell.blocks = vec![Arc::new(Block::Para(Paragraph::with_text("new", CharProps { ins: Some(0), ..Default::default() })))];
|
||||
d.body.insert(1, Arc::new(Block::Table(t)));
|
||||
Session::new(d)
|
||||
};
|
||||
let cell_of = |s: &Session| s.doc.body.iter().find_map(|b| b.as_table()).map(|t| t.rows[0].cells[0].clone()).unwrap();
|
||||
let start = Pos { story: StoryRef::Body, path: Path(vec![1, 0, 0, 0]), off: 0 };
|
||||
|
||||
let mut s = doc();
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
// The cell's formatting change, then its merge.
|
||||
s.run("review.nextChange", &json!({})).unwrap();
|
||||
s.run("review.nextChange", &json!({})).unwrap();
|
||||
s.run("review.reject", &json!({})).unwrap();
|
||||
let cell = cell_of(&s);
|
||||
assert!(cell.props.merge_change.is_none(), "the merge record went");
|
||||
assert!(cell.props.fmt_change.is_some(), "the other revision's formatting stays");
|
||||
assert_eq!(cell.blocks[0].as_para().map(|p| p.plain_text()), Some("new".to_string()), "the text stays");
|
||||
|
||||
let mut s = doc();
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
s.run("review.nextChange", &json!({})).unwrap();
|
||||
s.run("review.nextChange", &json!({})).unwrap();
|
||||
s.set_selection(crate::Selection::caret(Pos::body(0, 2)));
|
||||
s.set_selection(crate::Selection::caret(start));
|
||||
s.run("review.reject", &json!({})).unwrap();
|
||||
let cell = cell_of(&s);
|
||||
assert!(cell.props.merge_change.is_some(), "no longer the navigated merge");
|
||||
assert_eq!(cell.blocks[0].as_para().map(|p| p.plain_text()), Some(String::new()), "the tracked text at the caret was rejected");
|
||||
}
|
||||
|
||||
/// #9768 review: a command that moves the selection away from a navigated cell change (Next
|
||||
/// Comment here) ends it, as a click or caret command does; coming back to it is not navigating.
|
||||
#[test]
|
||||
fn a_selection_moving_command_ends_the_navigated_change() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::{CellMergeChange, MergeMark};
|
||||
use wordcraft_doc::table::Table;
|
||||
use wordcraft_doc::{Block, Pos, Revision, RevisionKind};
|
||||
let mut d = Document::from_text("before\nafter");
|
||||
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
|
||||
let mut t = Table::new(1, 1, 144.0);
|
||||
t.rows[0].cells[0].props.merge_change = Some(CellMergeChange { rev: 0, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
|
||||
d.body.insert(1, Arc::new(Block::Table(t)));
|
||||
let mut s = Session::new(d);
|
||||
s.sel = crate::Selection { anchor: Pos::body(0, 0), focus: Pos::body(0, 6) };
|
||||
s.run("review.newComment", &json!({"text": "A note."})).unwrap();
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
s.run("review.nextChange", &json!({})).unwrap();
|
||||
assert!(s.review_target.is_some(), "the merge is the navigated change");
|
||||
s.run("review.nextComment", &json!({})).unwrap();
|
||||
assert!(s.review_target.is_none(), "Next Comment moved the selection: {:?}", s.sel);
|
||||
}
|
||||
|
||||
/// #9768 review: a cell's formatting change and its first run's, from one revision setting the
|
||||
/// same property, stay two changes: the run's is not folded into the cell's.
|
||||
#[test]
|
||||
fn a_cells_and_its_first_runs_formatting_changes_stay_apart() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::{CellProps, PropChange};
|
||||
use wordcraft_doc::table::Table;
|
||||
use wordcraft_doc::{Block, CharProps, Paragraph, Revision, RevisionKind, Rgb};
|
||||
let mut d = Document::from_text("before\nafter");
|
||||
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
|
||||
let shade = Some(Rgb(0xFF, 0xC0, 0));
|
||||
let mut t = Table::new(1, 1, 144.0);
|
||||
let cell = &mut t.rows[0].cells[0];
|
||||
// The cell as it was differs only in its shading, as the run does.
|
||||
let old = CellProps { ..cell.props.clone() };
|
||||
cell.props.shading = shade;
|
||||
cell.props.fmt_change = PropChange::boxed(0, old);
|
||||
let run = CharProps { shading: shade, fmt_change: PropChange::boxed(0, CharProps::default()), ..Default::default() };
|
||||
let mut p = Paragraph::with_text("Shaded", run);
|
||||
p.mark = CharProps::default();
|
||||
cell.blocks = vec![Arc::new(Block::Para(p))];
|
||||
d.body.insert(1, Arc::new(Block::Table(t)));
|
||||
let mut s = Session::new(d);
|
||||
let list = s.run("review.changes", &json!({})).unwrap();
|
||||
let formats = list.as_array().unwrap().iter().filter(|c| c["kind"] == "format").count();
|
||||
assert_eq!(formats, 2, "{list}");
|
||||
}
|
||||
|
||||
@@ -123,12 +123,12 @@ pub(super) fn insert(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.push_undo("AutoFormat", doc, sel);
|
||||
// Undo right after it makes the capitalised word an exception.
|
||||
let depth = s.undo_steps_so_far();
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.commit_depth(depth);
|
||||
if let Some(c) = s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
|
||||
c.depth = depth;
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
s.set_ime_edit_outcome(outcome);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -87,35 +87,22 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
|
||||
}
|
||||
if f.off > 0 {
|
||||
let a = Pos { off: para.backspace_from(f.off), ..f.clone() };
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.note_backspace(&a, &f);
|
||||
}
|
||||
let carried = deleted_char_props(s, &a, &f);
|
||||
let (content_changed, state_changed, transformed) = if let Some(start) =
|
||||
s.autocap.as_ref().and_then(|c| c.pronoun_before_separator(&a, &f, s.undo_steps_so_far()))
|
||||
&& matches!(para.text.get(start.off..f.off), Some("I " | "I," | "I." | "I;" | "I:" | "I!" | "I?"))
|
||||
{
|
||||
// This restores a letter in place. Ordinary typing over a selection removes its link.
|
||||
let props = para.props_of_char(start.off);
|
||||
let linked_letter = props.link.as_ref().map(|_| props.clone());
|
||||
s.sel = Selection { anchor: start.clone(), focus: f.clone() };
|
||||
let pending = std::mem::replace(&mut s.pending, linked_letter);
|
||||
let effect = crate::cmd::type_text_effect(s, "i");
|
||||
s.pending = pending;
|
||||
let effect = effect?;
|
||||
if let Some(c) = &mut s.autocap {
|
||||
c.note_backspace(&start, &f);
|
||||
}
|
||||
(effect.content_changed, effect.state_changed, true)
|
||||
} else {
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.note_backspace(&a, &f);
|
||||
}
|
||||
s.sel = Selection { anchor: a.clone(), focus: f };
|
||||
let effect = delete_selection_effect(s)?;
|
||||
(effect.content_changed, effect.state_changed, false)
|
||||
};
|
||||
s.set_ime_edit_outcome(crate::ImeEditOutcome { classified: true, content_changed, state_changed, transformed, selection_changed: false });
|
||||
s.sel = Selection { anchor: a.clone(), focus: f };
|
||||
let effect = delete_selection_effect(s)?;
|
||||
s.set_ime_edit_outcome(crate::ImeEditOutcome {
|
||||
classified: true,
|
||||
content_changed: effect.content_changed,
|
||||
state_changed: effect.state_changed,
|
||||
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 content_changed && s.sel.is_collapsed() && s.sel.focus == a {
|
||||
if effect.content_changed && s.sel.is_collapsed() && s.sel.focus == a {
|
||||
s.pending_at = carried.as_ref().map(|_| a.clone());
|
||||
s.pending = carried;
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
|
||||
if let Some((doc, sel)) = plain {
|
||||
// Removes the marks, then AutoCorrects the word as without them.
|
||||
crate::cmd::tools::autocorrect_word(s, true)?;
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
let (done_doc, done_sel) = (std::mem::replace(&mut s.doc, doc), std::mem::replace(&mut s.sel, sel));
|
||||
let new = split_para(s, &at)?;
|
||||
let c = s.doc.para_at(&new).map(|p| p.mark.clone()).unwrap_or_default();
|
||||
@@ -165,7 +165,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
|
||||
return Ok(());
|
||||
}
|
||||
crate::cmd::tools::autocorrect_word(s, true)?;
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
at = s.sel.focus.clone();
|
||||
}
|
||||
let new = split_para(s, &at)?;
|
||||
|
||||
@@ -268,16 +268,6 @@ fn plain_word(w: &str) -> bool {
|
||||
!w.trim().is_empty() && w.chars().count() <= MAX_FROM && !w.contains(|c: char| c.is_whitespace() || c == '\u{FFFC}')
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct PronounCap {
|
||||
depth: u64,
|
||||
story: wordcraft_doc::StoryRef,
|
||||
path: wordcraft_doc::Path,
|
||||
start: usize,
|
||||
caret: usize,
|
||||
backspaced: bool,
|
||||
}
|
||||
|
||||
/// The newest automatic capitalisation (a sentence capital, a TWo INitial CApitals fix), kept so
|
||||
/// that undoing it, or backspacing it and typing the word again, makes an exception (#1857).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -293,78 +283,11 @@ pub struct AutoCap {
|
||||
pub(super) prev: String,
|
||||
/// The TWo INitial CApitals word as typed ("TWo").
|
||||
pub(super) two_caps: Option<String>,
|
||||
/// The English replacement of lowercase i with uppercase I, kept alongside an earlier sentence
|
||||
/// capital so an automatic `I` does not wipe the pending first-letter exception.
|
||||
pub(super) pronoun: Option<PronounCap>,
|
||||
/// The user backspaced into the word after the change.
|
||||
pub(super) backspaced: bool,
|
||||
}
|
||||
|
||||
impl AutoCap {
|
||||
pub(crate) fn commit_depth(&mut self, depth: u64) {
|
||||
if self.depth == u64::MAX {
|
||||
self.depth = depth;
|
||||
}
|
||||
if let Some(p) = self.pronoun.as_mut().filter(|p| p.depth == u64::MAX) {
|
||||
p.depth = depth;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clear_uncommitted(slot: &mut Option<Self>) {
|
||||
if let Some(c) = slot.as_mut() {
|
||||
if c.pronoun.as_ref().is_some_and(|p| p.depth == u64::MAX) {
|
||||
c.pronoun = None;
|
||||
}
|
||||
if c.depth == u64::MAX {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn record_pronoun(slot: &mut Option<Self>, story: wordcraft_doc::StoryRef, path: wordcraft_doc::Path, start: usize, caret: usize) {
|
||||
let pronoun = PronounCap { depth: u64::MAX, story, path: path.clone(), start, caret, backspaced: false };
|
||||
if let Some(c) = slot.as_mut().filter(|c| !c.prev.is_empty() || c.two_caps.is_some()) {
|
||||
c.pronoun = Some(pronoun);
|
||||
} else {
|
||||
*slot =
|
||||
Some(Self { depth: u64::MAX, story, path, start, prev: String::new(), two_caps: None, pronoun: Some(pronoun), backspaced: false });
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn take_backspaced_pronoun(slot: &mut Option<Self>, english: bool, word: &str, f: &Pos, start: usize) -> bool {
|
||||
let Some(c) = slot.as_mut() else { return false };
|
||||
let Some(p) = c.pronoun.take() else { return false };
|
||||
if c.prev.is_empty() && c.two_caps.is_none() {
|
||||
*slot = None;
|
||||
}
|
||||
english && word == "i" && p.backspaced && p.story == f.story && p.path == f.path && p.start == start
|
||||
}
|
||||
|
||||
/// The start of a just-corrected I when Backspace removes the separator after it.
|
||||
pub(crate) fn pronoun_before_separator(&self, a: &Pos, f: &Pos, undo_steps: u64) -> Option<Pos> {
|
||||
let p = self.pronoun.as_ref()?;
|
||||
(!p.backspaced
|
||||
&& p.story == f.story
|
||||
&& p.path == f.path
|
||||
&& p.start.checked_add(1) == Some(a.off)
|
||||
&& p.depth.checked_add(1) == Some(undo_steps))
|
||||
.then(|| Pos { off: p.start, ..f.clone() })
|
||||
}
|
||||
|
||||
/// Drop the pending pronoun restore once the caret moves away or a selection is made (#9392).
|
||||
pub(crate) fn drop_stale_pronoun(&mut self, sel: &crate::Selection) {
|
||||
if let Some(p) = &self.pronoun
|
||||
&& !p.backspaced
|
||||
&& (!sel.is_collapsed() || sel.focus.story != p.story || sel.focus.path != p.path || sel.focus.off != p.caret)
|
||||
{
|
||||
self.pronoun = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.prev.is_empty() && self.two_caps.is_none() && self.pronoun.is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn add_exceptions(self, ac: &mut AutoCorrectPrefs) {
|
||||
if ac.auto_add_first_letter && !self.prev.is_empty() {
|
||||
ac.add_exception(self.prev);
|
||||
@@ -381,14 +304,6 @@ impl AutoCap {
|
||||
if f.story == self.story && f.path == self.path && a.off <= self.start && f.off > self.start {
|
||||
self.backspaced = true;
|
||||
}
|
||||
if let Some(p) = &mut self.pronoun
|
||||
&& f.story == p.story
|
||||
&& f.path == p.path
|
||||
&& a.off <= p.start
|
||||
&& f.off > p.start
|
||||
{
|
||||
p.backspaced = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -311,7 +311,6 @@ fn strip_block_revisions(b: &mut Block) {
|
||||
}
|
||||
for cell in &mut row.cells {
|
||||
cell.props.fmt_change = None;
|
||||
cell.props.merge_change = None;
|
||||
stack.extend(cell.blocks.iter_mut().map(Arc::make_mut));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,41 +70,6 @@ fn resolving_a_middle_paragraph_keeps_the_caret_with_its_text() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolving_all_keeps_selection_with_surviving_multibyte_text_in_the_same_paragraph() {
|
||||
for (cmd, initial) in [("review.acceptAll", "雪漢字Q"), ("review.rejectAll", "漢字Q")] {
|
||||
let mut original = Session::new(Document::from_text(initial));
|
||||
let removed = "雪".len();
|
||||
let first_kept = "漢".len();
|
||||
original.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
if cmd == "review.acceptAll" {
|
||||
original.sel = Selection { anchor: Pos::body(0, 0), focus: Pos::body(0, removed) };
|
||||
original.run("text.delete", &json!({})).unwrap();
|
||||
} else {
|
||||
original.sel = Selection::caret(Pos::body(0, 0));
|
||||
original.run("text.insert", &json!({"text": "雪"})).unwrap();
|
||||
}
|
||||
assert_eq!(original.doc.plain_text(StoryRef::Body), "雪漢字Q");
|
||||
|
||||
for (before, after, typed) in [
|
||||
(Selection::caret(Pos::body(0, removed)), Selection::caret(Pos::body(0, 0)), "!漢字Q"),
|
||||
(
|
||||
Selection { anchor: Pos::body(0, removed + first_kept), focus: Pos::body(0, removed) },
|
||||
Selection { anchor: Pos::body(0, first_kept), focus: Pos::body(0, 0) },
|
||||
"!字Q",
|
||||
),
|
||||
] {
|
||||
let mut s = Session::new(original.doc.clone());
|
||||
s.sel = before;
|
||||
s.run(cmd, &json!({"stopTracking": true})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "漢字Q", "{cmd}");
|
||||
assert_eq!(s.sel, after, "{cmd}");
|
||||
s.run("text.insert", &json!({"text": "!"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), typed, "{cmd}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepting_a_middle_paragraph_join_keeps_the_backward_selection() {
|
||||
let mut s = Session::new(Document::from_text("A\néDROP\nX🙂B\nC"));
|
||||
@@ -198,20 +163,19 @@ fn compare_terminal_deleted_paragraph_resolves_fully() {
|
||||
|
||||
#[test]
|
||||
fn resolving_a_selected_terminal_paragraph_puts_the_caret_before_it() {
|
||||
let keep = "A\nKeep this";
|
||||
// Both endpoints of the removed paragraph go to the preceding paragraph's end (#8500),
|
||||
// even if removing another paragraph subsequently shifts that paragraph up (#8913).
|
||||
for (changed, last) in [("A\nKeep this\nNEW", 2), ("A\nEarlier\nKeep this\nNEW", 3)] {
|
||||
for (orig, revised, cmd) in [(keep, changed, "review.rejectAll"), (changed, keep, "review.acceptAll")] {
|
||||
let mut s = Session::new(Document::from_text(orig));
|
||||
s.run("review.compare", &json!({"text": revised})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": Pos::body(last, 0), "focus": Pos::body(last, 3)})).unwrap();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), keep, "{cmd}, last block {last}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}, last block {last}");
|
||||
s.run("text.insert", &json!({"text": "Z"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}, last block {last}");
|
||||
}
|
||||
// A selection inside the terminal paragraph that Reject All (insertion) or Accept All
|
||||
// (deletion) removes ends as a caret at the end of the paragraph before it, not over the
|
||||
// same offsets of that paragraph's text (#8500).
|
||||
let cases = [("A\nKeep this", "A\nKeep this\nNEW", "review.rejectAll"), ("A\nKeep this\nOLD", "A\nKeep this", "review.acceptAll")];
|
||||
for (orig, revised, cmd) in cases {
|
||||
let mut s = Session::new(Document::from_text(orig));
|
||||
s.run("review.compare", &json!({"text": revised})).unwrap();
|
||||
s.sel = Selection { anchor: Pos::body(2, 0), focus: Pos::body(2, 3) };
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep this", "{cmd}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}");
|
||||
s.run("text.insert", &json!({"text": "Z"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,6 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
&& letters.chars().nth(1).is_some_and(char::is_uppercase)
|
||||
&& letters.chars().next().is_some_and(char::is_uppercase))
|
||||
.then(|| letters.clone()),
|
||||
pronoun: None,
|
||||
backspaced: false,
|
||||
});
|
||||
let fixed: String = reps.concat();
|
||||
@@ -85,9 +84,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
// A whole-word replacement, else "wait..." → "wait…". Proofing decides what is English the
|
||||
// same way (#835); every English (en-GB, en-CA…) counts (#1281).
|
||||
let english = s.doc.para_at(&f).is_none_or(|_| wordcraft_proof::ProofLang::from_tag(lang.as_deref()).is_english());
|
||||
// A rejected pronoun is kept at this occurrence only, including at the start of a sentence.
|
||||
let keep_i = AutoCap::take_backspaced_pronoun(&mut s.autocap, english, &word, &f, start);
|
||||
let found = if ac.replace_text && !keep_i { ac.replacement_in(&word, english) } else { None };
|
||||
let found = if ac.replace_text { ac.replacement_in(&word, english) } else { None };
|
||||
let (from, rep) = match found {
|
||||
Some(r) => (start, Some(r)),
|
||||
None if ac.replace_text && word.len() > 3 && word.ends_with("...") => (start + word.len() - 3, Some("…".to_string())),
|
||||
@@ -109,9 +106,6 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
para.insert_text(from, &rep, &props)?;
|
||||
caret = (f.off + rep.len()).saturating_sub(end - from);
|
||||
s.sel = Selection::caret(Pos { off: caret, ..f.clone() });
|
||||
if english && word == "i" && rep == "I" {
|
||||
AutoCap::record_pronoun(&mut s.autocap, f.story, f.path.clone(), start, caret);
|
||||
}
|
||||
}
|
||||
let end = caret.saturating_sub(trigger);
|
||||
let Some(word) = s.doc.para_at(&f).and_then(|p| p.text.get(start..end)).map(str::to_string) else { return Ok(()) };
|
||||
@@ -153,7 +147,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
} else {
|
||||
last
|
||||
};
|
||||
let mut sentence = !keep_i && sentence_on && starts_sentence(before_word, &exceptions) && should_capitalize(first, next);
|
||||
let mut sentence = sentence_on && starts_sentence(before_word, &exceptions) && should_capitalize(first, next);
|
||||
let prev = if sentence { prev_token(before_word) } else { String::new() };
|
||||
// Typing the word again after backspacing an automatic capital: the user doesn't want it
|
||||
// (Word's "Automatically add words to list"); an exception, so no capital this time either.
|
||||
@@ -179,16 +173,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
match s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
|
||||
Some(c) => c.prev = prev,
|
||||
None => {
|
||||
s.autocap = Some(AutoCap {
|
||||
depth: u64::MAX,
|
||||
story: f.story,
|
||||
path: f.path,
|
||||
start,
|
||||
prev,
|
||||
two_caps: None,
|
||||
pronoun: None,
|
||||
backspaced: false,
|
||||
});
|
||||
s.autocap = Some(AutoCap { depth: u64::MAX, story: f.story, path: f.path, start, prev, two_caps: None, backspaced: false })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,15 +52,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
Ok(json!({"paperColor": color}))
|
||||
}).params(r#"{"value": "document" | "green" | "cream" | "gray"}"#).pure(),
|
||||
// How the edges of page text are smoothed on screen. Screen only; never in the document.
|
||||
CommandSpec::new("view.textSmoothing", "Screen Text Smoothing", "View › Display", |s, v| {
|
||||
let smoothing: TextSmoothing = serde_json::from_value(v.get("value").cloned().unwrap_or(Value::Null))
|
||||
.map_err(|_| CmdError::Params("screen text smoothing must be system, grayscale, or subpixel".into()))?;
|
||||
s.prefs.text_smoothing = smoothing;
|
||||
Ok(json!({"textSmoothing": smoothing}))
|
||||
})
|
||||
.params(r#"{"value": "system" | "grayscale" | "subpixel"}"#)
|
||||
.pure(),
|
||||
// Print Layout: hide the white space (margins, headers, footers) between pages. Screen only.
|
||||
CommandSpec::new("view.hideWhiteSpace", "Hide White Space", "View › Show", |s, v| toggle(s, v, |x| &mut x.hide_white_space))
|
||||
.params(r#"{"value"?: bool}"#)
|
||||
@@ -358,35 +349,6 @@ fn read_line_spacing(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"spacing": spacing}))
|
||||
}
|
||||
|
||||
/// How the edges of page text are smoothed on screen, saved with user preferences, never in the
|
||||
/// document. Exports, prints and PDFs are not affected.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TextSmoothing {
|
||||
/// As the system is set: subpixel where it asks for it (ClearType on Windows, `rgba`
|
||||
/// antialiasing on a Linux desktop) and the screen is not a high-density one, else
|
||||
/// greyscale. macOS never asks for it.
|
||||
#[default]
|
||||
System,
|
||||
/// Greyscale antialiasing: grey edges, no colour.
|
||||
Grayscale,
|
||||
/// Subpixel (LCD) antialiasing, whatever the system says: edges three times as fine
|
||||
/// sideways, with faint colour in them. In the system's stripe order, RGB when it gives none.
|
||||
Subpixel,
|
||||
}
|
||||
|
||||
impl TextSmoothing {
|
||||
pub const ALL: [Self; 3] = [Self::System, Self::Grayscale, Self::Subpixel];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "Use system setting",
|
||||
Self::Grayscale => "Grayscale",
|
||||
Self::Subpixel => "Subpixel (LCD)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Screen-only paper presets, saved with user preferences, never in the document.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -273,7 +273,7 @@ pub fn save_custom_dictionary(path: &Path, removed: &[String]) -> Result<(), Str
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use tests::{DICT_TEST_LOCK, TestDir, dict_test_lock};
|
||||
pub(crate) use tests::{DICT_TEST_LOCK, TestDir};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -282,11 +282,6 @@ mod tests {
|
||||
/// Test lock serializing tests that access the global proofing dictionary.
|
||||
pub(crate) static DICT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Acquire [`DICT_TEST_LOCK`], recovering cleanly if an earlier test panicked while holding it.
|
||||
pub(crate) fn dict_test_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
DICT_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// RAII guard for temporary directories in dictionary tests.
|
||||
pub(crate) struct TestDir(pub(crate) std::path::PathBuf);
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
|
||||
//! `/work`), exactly: on Windows what exists is resolved to its real case first.
|
||||
//! `/work`), without regard to case on Windows.
|
||||
//! - Writing replaces or removes a directory entry, so for write access the entry itself (its
|
||||
//! folder's links followed, its own name as it stands) must lie inside the root as well: a link
|
||||
//! folder's links followed, its own name as given) must lie inside the root as well: a link
|
||||
//! outside the root that leads into it is not a way to write outside (#3735).
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
//!
|
||||
@@ -76,12 +76,6 @@ impl AutomationRoots {
|
||||
Ok(Some(Arc::new(Self { read, write })))
|
||||
}
|
||||
|
||||
/// Roots that grant no access at all: what an agent gets when its folders can't be used, so it
|
||||
/// is refused rather than left unconfined.
|
||||
pub fn none() -> Arc<Self> {
|
||||
Arc::new(Self { read: None, write: None })
|
||||
}
|
||||
|
||||
/// The read root, absolute with its links followed.
|
||||
pub fn read_root(&self) -> Option<&Path> {
|
||||
self.read.as_ref().map(|r| r.shown.as_path())
|
||||
@@ -220,57 +214,16 @@ fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
resolve_absolute(path, &absolute)
|
||||
}
|
||||
|
||||
/// Whether `before` and `after` refer to the same filesystem entry.
|
||||
fn same_entry(before: &std::fs::Metadata, after: &std::fs::Metadata) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
(before.dev(), before.ino()) == (after.dev(), after.ino())
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = (before, after);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Only accept `canonicalize` (for on-disk case/normalization) when `canon` stays in
|
||||
/// `resolved_folder` and refers to the same entry (#9292, #9368, #9396). On Unix, file identity
|
||||
/// (`(dev, ino)`) covers non-ASCII case folding and Unicode normalization; elsewhere, compare
|
||||
/// Unicode-lowercased names.
|
||||
fn accept_canonical_entry(resolved_folder: &Path, name: &std::ffi::OsStr, entry_meta: &std::fs::Metadata, canon: &Path) -> bool {
|
||||
accept_canonical_entry_with(resolved_folder, name, entry_meta, canon, cfg!(unix))
|
||||
}
|
||||
|
||||
fn accept_canonical_entry_with(resolved_folder: &Path, name: &std::ffi::OsStr, entry_meta: &std::fs::Metadata, canon: &Path, is_unix: bool) -> bool {
|
||||
let name_ok = is_unix || canon.file_name().is_some_and(|c| c.to_string_lossy().to_lowercase() == name.to_string_lossy().to_lowercase());
|
||||
canon.parent() == Some(resolved_folder)
|
||||
&& name_ok
|
||||
&& std::fs::symlink_metadata(canon).is_ok_and(|canon_meta| !canon_meta.file_type().is_symlink() && same_entry(entry_meta, &canon_meta))
|
||||
}
|
||||
|
||||
/// The directory entry `path` names: its folder resolved as [`resolve`] resolves it, then its own
|
||||
/// name as given, so a link there is the entry itself, not what it leads to. That entry is what
|
||||
/// replacing or removing the file changes. What exists and isn't a link gets its real case, which
|
||||
/// is how the root is spelled when another spelling of the root is named.
|
||||
/// replacing or removing the file changes.
|
||||
fn resolve_entry(path: &str) -> Result<PathBuf, String> {
|
||||
resolve_entry_with(path, |p| std::fs::canonicalize(p))
|
||||
}
|
||||
|
||||
fn resolve_entry_with(path: &str, canonicalize: impl FnOnce(&Path) -> std::io::Result<PathBuf>) -> Result<PathBuf, String> {
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?;
|
||||
let (Some(folder), Some(name)) = (absolute.parent(), absolute.file_name()) else {
|
||||
return Err(format!("automation path rejected: not a file name: {path}"));
|
||||
};
|
||||
let resolved_folder = resolve_absolute(path, folder)?;
|
||||
let entry = resolved_folder.join(name);
|
||||
if let Ok(entry_meta) = std::fs::symlink_metadata(&entry)
|
||||
&& !entry_meta.file_type().is_symlink()
|
||||
&& let Ok(canon) = canonicalize(&entry)
|
||||
&& accept_canonical_entry(resolved_folder.as_path(), name, &entry_meta, &canon)
|
||||
{
|
||||
return Ok(canon);
|
||||
}
|
||||
let mut entry = resolve_absolute(path, folder)?;
|
||||
entry.push(name);
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
@@ -311,19 +264,30 @@ fn resolve_absolute(path: &str, absolute: &Path) -> Result<PathBuf, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component? Exactly, on Windows too: what
|
||||
/// exists has its real case from [`resolve`], and a folder that doesn't exist yet may be a different
|
||||
/// one from the root where a parent folder is case sensitive.
|
||||
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
|
||||
/// Windows, whose file systems ignore it)?
|
||||
fn inside(path: &Path, root: &Path) -> bool {
|
||||
let mut path = path.components();
|
||||
root.components().all(|r| path.next() == Some(r))
|
||||
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension or a colon), which names no file.
|
||||
fn same_component(a: Component, b: Component) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if !cfg!(windows) {
|
||||
return false;
|
||||
}
|
||||
match (a.as_os_str().to_str(), b.as_os_str().to_str()) {
|
||||
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
|
||||
fn is_device_name(component: &str) -> bool {
|
||||
let stem = component.split(['.', ':']).next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered =
|
||||
|prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"));
|
||||
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
|
||||
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
|
||||
}
|
||||
|
||||
@@ -417,7 +381,6 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A root and a path reached through links are compared after the links are followed.
|
||||
#[test]
|
||||
fn links_are_followed_before_comparing() {
|
||||
let (base, roots) = folders("links");
|
||||
@@ -465,143 +428,20 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A name that differs in case is another name until the file system says otherwise.
|
||||
#[test]
|
||||
fn names_are_compared_exactly() {
|
||||
let root = Path::new("/work/In");
|
||||
assert!(inside(Path::new("/work/In/new/a.docx"), root));
|
||||
assert!(!inside(Path::new("/work/IN/a.docx"), root));
|
||||
assert!(!inside(Path::new("/WORK/In/a.docx"), root));
|
||||
assert!(!inside(Path::new("/work/in\u{212A}/a.docx"), Path::new("/work/ink")), "the Kelvin sign folds to k");
|
||||
if cfg!(windows) {
|
||||
let root = Path::new(r"C:\work\In");
|
||||
assert!(inside(Path::new(r"c:\work\In\a.docx"), root), "a drive letter is one drive in either case");
|
||||
assert!(!inside(Path::new(r"C:\work\IN\a.docx"), root));
|
||||
}
|
||||
}
|
||||
|
||||
/// In a case-sensitive folder, `IN` beside the root `in` is another folder, there or not yet.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_case_sensitive_folder_keeps_a_differently_cased_name_out() {
|
||||
let base = std::env::temp_dir().join(format!("wc-file-access-case-sensitive-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let set = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&base).arg("enable").output();
|
||||
if !set.as_ref().is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: a case-sensitive folder can't be made here: {set:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
std::fs::create_dir(base.join("in")).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("in"))).unwrap().unwrap();
|
||||
assert_eq!(roots.check(&s(base.join("in/new.docx")), Access::Write), Ok(()));
|
||||
let e = roots.check(&s(base.join("IN/new.docx")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
std::fs::create_dir(base.join("IN")).unwrap();
|
||||
std::fs::write(base.join("IN/secret.docx"), "x").unwrap();
|
||||
let e = roots.check(&s(base.join("IN/secret.docx")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// On Windows a path finds its real case on disk, and device names are refused.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_finds_the_real_case_and_refuses_devices() {
|
||||
fn windows_ignores_case_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
let upper = s(base.join("IN/A.SVG"));
|
||||
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
|
||||
assert_eq!(roots.check(&s(base.join("In/Sub/New.docx")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT/New.docx")), Access::Write), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT")), Access::Write), Ok(()), "the root itself, in another spelling");
|
||||
let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err());
|
||||
let e = roots.check(&s(base.join("out/COM¹.txt")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// If a symlink is swapped in between `symlink_metadata` and `canonicalize`, `resolve_entry`
|
||||
/// ignores any canonical path that leaves the entry's folder or changes its name (#9292, #9397).
|
||||
#[test]
|
||||
fn canonicalize_leaving_the_folder_is_not_accepted_by_resolve_entry() {
|
||||
let (base, roots) = folders("canonicalize-race");
|
||||
let outside_file = base.join("outside/Doc.txt");
|
||||
std::fs::write(&outside_file, "x").unwrap();
|
||||
let canon_outside = std::fs::canonicalize(base.join("outside")).unwrap();
|
||||
let canon_out = std::fs::canonicalize(base.join("out")).unwrap();
|
||||
|
||||
let outside_str = s(outside_file);
|
||||
// Simulate canonicalize following a newly swapped symlink into `out/`: must still resolve to `outside/Doc.txt`.
|
||||
let swapped_into_out = canon_out.join("Doc.txt");
|
||||
let resolved = super::resolve_entry_with(&outside_str, |_| Ok(swapped_into_out.clone())).unwrap();
|
||||
assert_eq!(resolved, canon_outside.join("Doc.txt"));
|
||||
assert!(!super::inside(&resolved, &canon_out));
|
||||
assert!(roots.check(&outside_str, Access::Write).is_err());
|
||||
|
||||
// Same folder, same file identity: `resolve_entry` accepts the canonical path.
|
||||
let same_entry = canon_outside.join("Doc.txt");
|
||||
let resolved_same = super::resolve_entry_with(&outside_str, |_| Ok(same_entry.clone())).unwrap();
|
||||
assert_eq!(resolved_same, same_entry);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// #9368: on Unix, `accept_canonical_entry` accepts non-ASCII case and NFC/NFD differences
|
||||
/// when `canon` is the same filesystem entry (`(dev, ino)`).
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn accept_canonical_entry_allows_non_ascii_and_unicode_normalization_for_same_entry() {
|
||||
let (base, _roots) = folders("unicode-case");
|
||||
let dir = base.join("über");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let entry_meta = std::fs::symlink_metadata(&dir).unwrap();
|
||||
let resolved_folder = std::fs::canonicalize(&base).unwrap();
|
||||
let canon = std::fs::canonicalize(&dir).unwrap();
|
||||
assert!(accept_canonical_entry(&resolved_folder, std::ffi::OsStr::new("ÜBER"), &entry_meta, &canon));
|
||||
assert!(accept_canonical_entry(&resolved_folder, std::ffi::OsStr::new("u\u{0308}ber"), &entry_meta, &canon));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// #9368 / #9776: the non-Unix branch of `accept_canonical_entry` accepts Unicode-lowercased
|
||||
/// names (`ÜBER` vs `über`) and refuses a different name on all platforms.
|
||||
#[test]
|
||||
fn non_unix_accept_canonical_entry_checks_unicode_lowercase_name() {
|
||||
let (base, _roots) = folders("non-unix-unicode-case");
|
||||
let dir = base.join("über");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let entry_meta = std::fs::symlink_metadata(&dir).unwrap();
|
||||
let resolved_folder = std::fs::canonicalize(&base).unwrap();
|
||||
let canon = std::fs::canonicalize(&dir).unwrap();
|
||||
assert!(super::accept_canonical_entry_with(&resolved_folder, std::ffi::OsStr::new("ÜBER"), &entry_meta, &canon, false));
|
||||
assert!(!super::accept_canonical_entry_with(&resolved_folder, std::ffi::OsStr::new("other"), &entry_meta, &canon, false));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// On a case-sensitive filesystem, swapping a sibling `OUT` directory for a symlink `OUT -> out`
|
||||
/// between `symlink_metadata` and `canonicalize` must not be accepted as the write root (#9396).
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_swapped_case_variant_symlink_is_not_accepted_as_canonical_entry() {
|
||||
let (base, _roots) = folders("case-swap");
|
||||
let sibling = base.join("OUT");
|
||||
if std::fs::create_dir(&sibling).is_ok() {
|
||||
let entry_meta = std::fs::symlink_metadata(&sibling).unwrap();
|
||||
std::fs::remove_dir(&sibling).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("out"), &sibling).unwrap();
|
||||
let resolved_folder = std::fs::canonicalize(&base).unwrap();
|
||||
let canon = std::fs::canonicalize(&sibling).unwrap();
|
||||
assert!(
|
||||
!accept_canonical_entry(&resolved_folder, std::ffi::OsStr::new("OUT"), &entry_meta, &canon),
|
||||
"swapped case-variant symlink should be rejected by file identity check"
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Scopes nest, and a scope applies only on the thread that set it.
|
||||
#[test]
|
||||
fn scopes_nest_and_stay_on_their_thread() {
|
||||
let (base, roots) = folders("scopes");
|
||||
@@ -623,13 +463,12 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// What is a device name, with superscript digits and a name before a colon, and what isn't.
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.docx", "NUL ", "COM¹", "Lpt²", "lpt³.txt", "COM1:", "nul:x", "COM¹:"] {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.docx", "NUL "] {
|
||||
assert!(is_device_name(d), "{d}");
|
||||
}
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.docx", "nul-x", "COM⁴", "com¹0", "lpt¹x", "console:x"] {
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.docx", "nul-x"] {
|
||||
assert!(!is_device_name(f), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
+2
-96
@@ -876,64 +876,6 @@ pub fn package_title(path: &std::path::Path, max_file: u64, max_part: u64) -> Op
|
||||
wordcraft_docx::package_title(std::io::BufReader::new(file), max_part)
|
||||
}
|
||||
|
||||
/// How a file looks on disk without reading it: its size and last-modified time. Another
|
||||
/// program's write changes one or both, so a document compares the stamp it took when it read or
|
||||
/// saved the file with the file's stamp now before AutoSave writes over it (#7069). A writer
|
||||
/// that keeps both (same size, and the modified time set back) goes unseen: the check reads no
|
||||
/// content, so AutoSave costs no read of the file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct FileStamp {
|
||||
len: u64,
|
||||
modified: Option<std::time::SystemTime>,
|
||||
}
|
||||
|
||||
/// The [`FileStamp`] of the file at `path`, `None` when there is none (or it can't be looked at).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn file_stamp(path: &std::path::Path) -> Option<FileStamp> {
|
||||
std::fs::metadata(path).ok().filter(std::fs::Metadata::is_file).map(|meta| FileStamp::of(&meta))
|
||||
}
|
||||
|
||||
impl FileStamp {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn of(meta: &std::fs::Metadata) -> FileStamp {
|
||||
FileStamp { len: meta.len(), modified: meta.modified().ok() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a save that may write only over an unchanged file ([`save_path_checked`]) wrote nothing.
|
||||
#[derive(Debug)]
|
||||
struct ChangedOnDisk(String);
|
||||
|
||||
impl std::fmt::Display for ChangedOnDisk {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{} was changed or removed by another program after it was opened or saved here", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ChangedOnDisk {}
|
||||
|
||||
/// Write `bytes` to `path` as [`save_path_with`] does, and return the written file's stamp. With
|
||||
/// `unchanged`, only while the file at `path` still has that stamp, checked once the new bytes
|
||||
/// are ready, just before they replace it (AutoSave, #7069): otherwise nothing is written.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_checked(path: &std::path::Path, bytes: &[u8], unchanged: Option<FileStamp>) -> Result<FileStamp, String> {
|
||||
let name = || path.file_name().map_or_else(|| path.to_string_lossy(), |n| n.to_string_lossy()).to_string();
|
||||
let check = || match unchanged {
|
||||
Some(stamp) if file_stamp(path) != Some(stamp) => Err(std::io::Error::other(ChangedOnDisk(name()))),
|
||||
_ => Ok(()),
|
||||
};
|
||||
match safe_save::write_checked(path, bytes, check) {
|
||||
Ok(meta) => Ok(FileStamp::of(&meta)),
|
||||
Err(e) if e.get_ref().is_some_and(|inner| inner.is::<ChangedOnDisk>()) => Err(e.to_string()),
|
||||
Err(e) => Err(format!("{}: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn file_stamp(_path: &std::path::Path) -> Option<FileStamp> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Rename without replacing another file, respecting both automation access roots.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn rename_file(source: &std::path::Path, destination: &std::path::Path) -> Result<(), String> {
|
||||
@@ -998,22 +940,9 @@ pub fn save_path(path: &std::path::Path, doc: &Document) -> Result<(), String> {
|
||||
/// [`save_path`], encrypted with `password` as [`save_bytes_with`] does.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn save_path_with(path: &std::path::Path, doc: &Document, password: Option<&str>, opts: &ExportOptions) -> Result<(), String> {
|
||||
save_path_checked(path, doc, password, opts, None).map(|_| ())
|
||||
}
|
||||
|
||||
/// [`save_path_with`], returning the written file's stamp; with `unchanged`, writing only over a
|
||||
/// file that still has that stamp (see [`write_checked`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn save_path_checked(
|
||||
path: &std::path::Path,
|
||||
doc: &Document,
|
||||
password: Option<&str>,
|
||||
opts: &ExportOptions,
|
||||
unchanged: Option<FileStamp>,
|
||||
) -> Result<FileStamp, String> {
|
||||
crate::file_access::check_write(&path.to_string_lossy())?;
|
||||
let bytes = save_bytes_with(&path.to_string_lossy(), doc, password, opts)?;
|
||||
write_checked(path, &bytes, unchanged)
|
||||
safe_save::write(path, &bytes).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Saves a document to `path` with optional password and export options on web targets.
|
||||
@@ -1025,15 +954,8 @@ pub fn save_path_with(path: &std::path::Path, _doc: &Document, _password: Option
|
||||
/// Write `text` to `path` as it is (a Markdown file's own text), as safely as [`save_path_with`].
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn save_text_path(path: &std::path::Path, text: &str) -> Result<(), String> {
|
||||
save_text_path_checked(path, text, None).map(|_| ())
|
||||
}
|
||||
|
||||
/// [`save_text_path`], returning the written file's stamp; with `unchanged`, writing only over a
|
||||
/// file that still has that stamp (see [`write_checked`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn save_text_path_checked(path: &std::path::Path, text: &str, unchanged: Option<FileStamp>) -> Result<FileStamp, String> {
|
||||
crate::file_access::check_write(&path.to_string_lossy())?;
|
||||
write_checked(path, text.as_bytes(), unchanged)
|
||||
safe_save::write(path, text.as_bytes()).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Write `text` to `path` as it is (a Markdown file's own text), as safely as [`save_path_with`].
|
||||
@@ -1042,22 +964,6 @@ pub fn save_text_path(path: &std::path::Path, _text: &str) -> Result<(), String>
|
||||
Err(format!("{}: files are saved through the browser on the web", path.display()))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn save_text_path_checked(path: &std::path::Path, _text: &str, _unchanged: Option<FileStamp>) -> Result<FileStamp, String> {
|
||||
Err(format!("{}: files are saved through the browser on the web", path.display()))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn save_path_checked(
|
||||
path: &std::path::Path,
|
||||
_doc: &Document,
|
||||
_password: Option<&str>,
|
||||
_opts: &ExportOptions,
|
||||
_unchanged: Option<FileStamp>,
|
||||
) -> Result<FileStamp, String> {
|
||||
Err(format!("{}: files are saved through the browser on the web", path.display()))
|
||||
}
|
||||
|
||||
/// Decode text bytes: UTF-8 (with or without BOM), UTF-16 LE/BE (BOM or sniffed), else the
|
||||
/// legacy encoding they look like — GBK, Big5, Shift_JIS, Windows-1252… (see
|
||||
/// [`wordcraft_formats::txt::decode`]).
|
||||
|
||||
@@ -15,13 +15,6 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
/// temporary file. If the destination's folder refuses the temporary file, a new file
|
||||
/// is created directly and removed on failure; an existing file is left untouched.
|
||||
pub(super) fn write(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
write_checked(path, bytes, || Ok(())).map(|_| ())
|
||||
}
|
||||
|
||||
/// [`write`], calling `check` once the new bytes are ready, just before they replace (or create)
|
||||
/// the destination: an error from it leaves the destination as it was. Returns the new file's
|
||||
/// metadata as it was put in place (a rename keeps its size and modified time).
|
||||
pub(super) fn write_checked(path: &Path, bytes: &[u8], check: impl FnOnce() -> io::Result<()>) -> io::Result<fs::Metadata> {
|
||||
let permissions = match fs::metadata(path) {
|
||||
Ok(meta) if meta.is_file() => Some(meta.permissions()),
|
||||
Ok(_) => None,
|
||||
@@ -31,7 +24,7 @@ pub(super) fn write_checked(path: &Path, bytes: &[u8], check: impl FnOnce() -> i
|
||||
// A new document gets the usual mode (0666 less the umask); a replaced one keeps its own,
|
||||
// and its temporary file stays private until that mode is applied.
|
||||
let private = permissions.is_some();
|
||||
let written = replace_with(path, private, check, |file| {
|
||||
let written = replace_with(path, private, |file| {
|
||||
file.write_all(bytes)?;
|
||||
if let Some(permissions) = permissions {
|
||||
keep_permissions(file.set_permissions(permissions))?;
|
||||
@@ -101,25 +94,16 @@ fn not_supported(e: &io::Error) -> bool {
|
||||
e.kind() == io::ErrorKind::Unsupported || e.raw_os_error().is_some_and(|code| CODES.contains(&code))
|
||||
}
|
||||
|
||||
fn replace_with(
|
||||
path: &Path,
|
||||
private: bool,
|
||||
check: impl FnOnce() -> io::Result<()>,
|
||||
prepare: impl FnOnce(&mut File) -> io::Result<()>,
|
||||
) -> io::Result<fs::Metadata> {
|
||||
fn replace_with(path: &Path, private: bool, prepare: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
|
||||
let mut temp = match Temporary::create(path, private) {
|
||||
Ok(temp) => temp,
|
||||
// macOS only lets an app write the file picked in the Save panel inside a protected
|
||||
// folder (Desktop, Documents, Downloads, iCloud Drive), not a sibling temporary file
|
||||
// (#2138); a read-only folder refuses it too.
|
||||
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
|
||||
check()?;
|
||||
return create_directly(path, e, prepare);
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => return create_directly(path, e, prepare),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
prepare(temp.file()?)?;
|
||||
check()?;
|
||||
temp.commit(path)
|
||||
}
|
||||
|
||||
@@ -127,7 +111,7 @@ fn replace_with(
|
||||
/// yet is created directly (there is no previous version to lose) and removed again if the save
|
||||
/// fails. Anything already at `path` is left untouched: overwriting it in place could destroy the
|
||||
/// only copy, so the error says how to save safely instead.
|
||||
fn create_directly(path: &Path, refused: io::Error, prepare: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<fs::Metadata> {
|
||||
fn create_directly(path: &Path, refused: io::Error, prepare: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
|
||||
// `create_new` never opens an existing file or follows a link, so it can't touch one.
|
||||
let mut file = match OpenOptions::new().write(true).create_new(true).open(path) {
|
||||
Ok(file) => file,
|
||||
@@ -140,13 +124,8 @@ fn create_directly(path: &Path, refused: io::Error, prepare: impl FnOnce(&mut Fi
|
||||
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => return Err(guided(e, "WordCraft can't create files in this folder.")),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
// Closed before its metadata is read: Windows settles a file's last-write time only then.
|
||||
let failed = match prepare(&mut file) {
|
||||
Ok(()) => {
|
||||
drop(file);
|
||||
return fs::metadata(path);
|
||||
}
|
||||
Err(failed) => failed,
|
||||
let Err(failed) = prepare(&mut file) else {
|
||||
return Ok(());
|
||||
};
|
||||
drop(file);
|
||||
match fs::remove_file(path) {
|
||||
@@ -232,15 +211,12 @@ impl Temporary {
|
||||
self.file.as_mut().ok_or_else(|| io::Error::other("save temporary file is closed"))
|
||||
}
|
||||
|
||||
/// Put the file in place of `destination`; returns its metadata as it went in. It is closed
|
||||
/// first, before replacement and before the metadata is read: Windows settles a file's
|
||||
/// last-write time only once its writing handles close, and a rename keeps it.
|
||||
fn commit(mut self, destination: &Path) -> io::Result<fs::Metadata> {
|
||||
fn commit(mut self, destination: &Path) -> io::Result<()> {
|
||||
// Close before replacement, including on Windows.
|
||||
drop(self.file.take());
|
||||
let meta = fs::metadata(&self.path)?;
|
||||
fs::rename(&self.path, destination)?;
|
||||
self.committed = true;
|
||||
Ok(meta)
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,15 +260,10 @@ mod tests {
|
||||
let d = Scratch::new();
|
||||
let path = d.target();
|
||||
fs::write(&path, b"Original bytes.").unwrap();
|
||||
let err = replace_with(
|
||||
&path,
|
||||
true,
|
||||
|| Ok(()),
|
||||
|file| {
|
||||
file.write_all(if partial { b"Partial" } else { b"Complete replacement bytes." })?;
|
||||
Err(io::Error::other("injected preparation failure"))
|
||||
},
|
||||
)
|
||||
let err = replace_with(&path, true, |file| {
|
||||
file.write_all(if partial { b"Partial" } else { b"Complete replacement bytes." })?;
|
||||
Err(io::Error::other("injected preparation failure"))
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("injected"));
|
||||
assert_eq!(fs::read(&path).unwrap(), b"Original bytes.");
|
||||
@@ -342,29 +313,19 @@ mod tests {
|
||||
let d = Scratch::new();
|
||||
let path = d.target();
|
||||
fs::write(&path, b"Original bytes.").unwrap();
|
||||
replace_with(
|
||||
&path,
|
||||
true,
|
||||
|| Ok(()),
|
||||
|file| {
|
||||
file.write_all(b"Saved on the share.")?;
|
||||
keep_permissions(Err(io::Error::from(io::ErrorKind::Unsupported)))?;
|
||||
file.sync_all()
|
||||
},
|
||||
)
|
||||
replace_with(&path, true, |file| {
|
||||
file.write_all(b"Saved on the share.")?;
|
||||
keep_permissions(Err(io::Error::from(io::ErrorKind::Unsupported)))?;
|
||||
file.sync_all()
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"Saved on the share.");
|
||||
assert_eq!(fs::read_dir(&d.0).unwrap().count(), 1);
|
||||
|
||||
let err = replace_with(
|
||||
&path,
|
||||
true,
|
||||
|| Ok(()),
|
||||
|file| {
|
||||
file.write_all(b"Refused.")?;
|
||||
keep_permissions(Err(io::Error::from(io::ErrorKind::PermissionDenied)))
|
||||
},
|
||||
)
|
||||
let err = replace_with(&path, true, |file| {
|
||||
file.write_all(b"Refused.")?;
|
||||
keep_permissions(Err(io::Error::from(io::ErrorKind::PermissionDenied)))
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert_eq!(fs::read(&path).unwrap(), b"Saved on the share.");
|
||||
@@ -422,15 +383,10 @@ mod tests {
|
||||
let path = d.target();
|
||||
fs::write(&path, b"Original bytes.").unwrap();
|
||||
let Some(result) = in_read_only(&d.0, || {
|
||||
replace_with(
|
||||
&path,
|
||||
true,
|
||||
|| Ok(()),
|
||||
|file| {
|
||||
file.write_all(b"Partial")?;
|
||||
Err(io::Error::other("injected partial write failure"))
|
||||
},
|
||||
)
|
||||
replace_with(&path, true, |file| {
|
||||
file.write_all(b"Partial")?;
|
||||
Err(io::Error::other("injected partial write failure"))
|
||||
})
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -10,10 +10,6 @@ pub struct Prefs {
|
||||
/// On-screen paper for pages without a document background; excluded from saved documents.
|
||||
#[serde(deserialize_with = "lenient_paper_color")]
|
||||
pub paper_color: crate::cmd::view::PaperColor,
|
||||
/// How the edges of page text are smoothed on screen (`view.textSmoothing`); excluded from
|
||||
/// saved documents.
|
||||
#[serde(deserialize_with = "lenient_text_smoothing")]
|
||||
pub text_smoothing: crate::cmd::view::TextSmoothing,
|
||||
/// Track Changes Options: what markup shows and how revisions are drawn (per user, as in
|
||||
/// Word).
|
||||
pub markup: wordcraft_layout::display::MarkupOptions,
|
||||
@@ -76,7 +72,6 @@ impl Default for Prefs {
|
||||
fn default() -> Self {
|
||||
Prefs {
|
||||
paper_color: Default::default(),
|
||||
text_smoothing: Default::default(),
|
||||
count_notes: true,
|
||||
markup: Default::default(),
|
||||
print_markup: false,
|
||||
@@ -124,12 +119,6 @@ fn lenient_paper_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::
|
||||
Ok(serde_json::from_value(value).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Ignore an invalid saved text smoothing without discarding other preferences.
|
||||
fn lenient_text_smoothing<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::TextSmoothing, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
Ok(serde_json::from_value(value).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Ignore an invalid saved Page Color without discarding other preferences.
|
||||
fn lenient_read_page_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::ReadPageColor, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
|
||||
@@ -59,10 +59,6 @@ pub struct Session {
|
||||
/// 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>,
|
||||
/// How `path` looked on disk (size and modified time) when the document was read from it or
|
||||
/// last saved to it: AutoSave writes it only while it still looks so (#7069). `None` when the
|
||||
/// document didn't come from that file here.
|
||||
pub disk_stamp: Option<crate::io::FileStamp>,
|
||||
/// Name given to a document not saved yet (File › Info › Rename): what Save suggests. A file
|
||||
/// name, not document metadata, so it is not part of the document or its undo history.
|
||||
pub file_name: Option<String>,
|
||||
@@ -112,14 +108,10 @@ pub struct Session {
|
||||
pub new_header_parts: Vec<u32>,
|
||||
/// The body selection a command left for a header or footer: `insert.closeHeader` puts it back.
|
||||
pub hf_return: Option<Selection>,
|
||||
/// The section of the page whose header or footer is open, which section commands act on
|
||||
/// (#5855). Kept apart from `page_hint`, which stops naming that section once a taller footer
|
||||
/// repaginates the pages, and from `hf_return`, which stays the body position to go back to.
|
||||
pub(crate) hf_section: Option<usize>,
|
||||
/// The style-definition change Next / Previous Change selected, for the Accept or Reject that
|
||||
/// follows (`cmd::review`). It names its document and selection, so it is shared by the open
|
||||
/// documents and stops counting once either changes.
|
||||
pub(crate) review_target: Option<crate::cmd::review::ReviewTarget>,
|
||||
pub(crate) review_style: Option<crate::cmd::review::StyleTarget>,
|
||||
/// Undo and redo steps. Shared so `run` can snapshot both stacks cheaply (a pointer per
|
||||
/// step) and put them back exactly when a command fails.
|
||||
history: Vec<Arc<Undo>>,
|
||||
@@ -306,20 +298,4 @@ impl Session {
|
||||
}
|
||||
self.findings.as_ref().map_or(&[], |(_, findings)| findings.as_slice())
|
||||
}
|
||||
|
||||
/// Update `page_hint` and, when editing a header or footer, keep `hf_section` aligned
|
||||
/// with the section of `page` if that section displays the active part.
|
||||
pub fn set_page_hint(&mut self, page: usize) {
|
||||
self.page_hint = page;
|
||||
if let StoryRef::Part(id) = self.sel.focus.story
|
||||
&& self.doc.parts.get(&id).is_some_and(|p| matches!(p.kind, wordcraft_doc::PartKind::Header | wordcraft_doc::PartKind::Footer))
|
||||
&& let Some(sec) = self.cached_layout().and_then(|l| l.pages.get(page)).map(|pg| pg.section)
|
||||
{
|
||||
let sections = self.doc.sections();
|
||||
let sec = sec.min(sections.len().saturating_sub(1));
|
||||
if crate::cmd::page::section_uses_hf_part(§ions, sec, id) {
|
||||
self.hf_section = Some(sec);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,6 @@ pub struct DocState {
|
||||
pub(super) pending: Option<CharProps>,
|
||||
pub(super) pending_at: Option<Pos>,
|
||||
pub(super) path: Option<PathBuf>,
|
||||
pub(super) disk_stamp: Option<crate::io::FileStamp>,
|
||||
pub(super) file_name: Option<String>,
|
||||
pub(super) dirty: bool,
|
||||
pub(super) pending_move: Option<crate::cmd::moves::PendingMove>,
|
||||
@@ -54,7 +53,6 @@ pub struct DocState {
|
||||
pub(super) page_hint: usize,
|
||||
pub(super) new_header_parts: Vec<u32>,
|
||||
pub(super) hf_return: Option<Selection>,
|
||||
pub(super) hf_section: Option<usize>,
|
||||
pub(super) history: Vec<Arc<Undo>>,
|
||||
pub(super) undo_evicted: u64,
|
||||
pub(super) redo: Vec<Arc<Undo>>,
|
||||
@@ -104,7 +102,6 @@ impl DocState {
|
||||
pending: None,
|
||||
pending_at: None,
|
||||
path: None,
|
||||
disk_stamp: None,
|
||||
file_name: None,
|
||||
dirty: false,
|
||||
pending_move: None,
|
||||
@@ -113,7 +110,6 @@ impl DocState {
|
||||
page_hint: 0,
|
||||
new_header_parts: Vec::new(),
|
||||
hf_return: None,
|
||||
hf_section: None,
|
||||
history: Vec::new(),
|
||||
undo_evicted: 0,
|
||||
redo: Vec::new(),
|
||||
@@ -210,7 +206,6 @@ impl Session {
|
||||
pending: _,
|
||||
pending_at: _,
|
||||
path: _,
|
||||
disk_stamp: _,
|
||||
file_name: _,
|
||||
dirty: _,
|
||||
pending_move: _,
|
||||
@@ -219,7 +214,6 @@ impl Session {
|
||||
page_hint: _,
|
||||
new_header_parts: _,
|
||||
hf_return: _,
|
||||
hf_section: _,
|
||||
history: _,
|
||||
undo_evicted: _,
|
||||
redo: _,
|
||||
@@ -257,7 +251,7 @@ impl Session {
|
||||
go_back_step: _,
|
||||
// Shared by every open document.
|
||||
// Names the document it belongs to, so it never applies to another one.
|
||||
review_target: _,
|
||||
review_style: _,
|
||||
user_dict_path: _,
|
||||
default_user_dict_path: _,
|
||||
clipboard: _,
|
||||
@@ -317,7 +311,6 @@ impl Session {
|
||||
pending,
|
||||
pending_at,
|
||||
path,
|
||||
disk_stamp,
|
||||
file_name,
|
||||
dirty,
|
||||
pending_move,
|
||||
@@ -326,7 +319,6 @@ impl Session {
|
||||
page_hint,
|
||||
new_header_parts,
|
||||
hf_return,
|
||||
hf_section,
|
||||
history,
|
||||
undo_evicted,
|
||||
redo,
|
||||
@@ -369,7 +361,6 @@ impl Session {
|
||||
swap(&mut self.pending, pending);
|
||||
swap(&mut self.pending_at, pending_at);
|
||||
swap(&mut self.path, path);
|
||||
swap(&mut self.disk_stamp, disk_stamp);
|
||||
swap(&mut self.file_name, file_name);
|
||||
swap(&mut self.dirty, dirty);
|
||||
swap(&mut self.pending_move, pending_move);
|
||||
@@ -378,7 +369,6 @@ impl Session {
|
||||
swap(&mut self.page_hint, page_hint);
|
||||
swap(&mut self.new_header_parts, new_header_parts);
|
||||
swap(&mut self.hf_return, hf_return);
|
||||
swap(&mut self.hf_section, hf_section);
|
||||
swap(&mut self.history, history);
|
||||
swap(&mut self.undo_evicted, undo_evicted);
|
||||
swap(&mut self.redo, redo);
|
||||
|
||||
@@ -13,11 +13,6 @@ impl Session {
|
||||
self.layout_with(typing)
|
||||
}
|
||||
|
||||
/// Most recently computed layout for the current document revision, if any.
|
||||
pub(crate) fn cached_layout(&self) -> Option<&DocLayout> {
|
||||
self.layout.iter().flatten().find(|e| e.0.0 == self.rev).map(|e| &*e.5)
|
||||
}
|
||||
|
||||
fn revision_layout_options(&self) -> LayoutOptions {
|
||||
LayoutOptions {
|
||||
hide_deleted: !self.view.show_markup,
|
||||
@@ -161,8 +156,6 @@ impl Session {
|
||||
copy.column = self.column.clone();
|
||||
copy.widened = self.widened.clone();
|
||||
copy.view = self.view.clone();
|
||||
copy.page_hint = self.page_hint;
|
||||
copy.hf_section = self.hf_section;
|
||||
copy.prefs = self.prefs.clone();
|
||||
copy.path = self.path.clone();
|
||||
copy.file_name = self.file_name.clone();
|
||||
@@ -307,7 +300,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
|
||||
let _dict_guard = crate::custom_dict::dict_test_lock();
|
||||
let mut session = Session::new(Document::new());
|
||||
let first = session.layout();
|
||||
let first_weak = Arc::downgrade(&first);
|
||||
|
||||
@@ -43,7 +43,6 @@ impl Session {
|
||||
pending,
|
||||
pending_at,
|
||||
path,
|
||||
disk_stamp,
|
||||
file_name,
|
||||
dirty,
|
||||
pending_move,
|
||||
@@ -52,7 +51,6 @@ impl Session {
|
||||
page_hint,
|
||||
new_header_parts,
|
||||
hf_return,
|
||||
hf_section,
|
||||
history,
|
||||
undo_evicted,
|
||||
redo,
|
||||
@@ -97,7 +95,6 @@ impl Session {
|
||||
pending_at,
|
||||
last_highlight: wordcraft_doc::props::Highlight::Yellow,
|
||||
path,
|
||||
disk_stamp,
|
||||
file_name,
|
||||
user_dict_path: None,
|
||||
default_user_dict_path: None,
|
||||
@@ -119,8 +116,7 @@ impl Session {
|
||||
status: String::new(),
|
||||
new_header_parts,
|
||||
hf_return,
|
||||
hf_section,
|
||||
review_target: None,
|
||||
review_style: None,
|
||||
history,
|
||||
undo_evicted,
|
||||
redo,
|
||||
|
||||
@@ -266,28 +266,13 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn drop_stale_pronoun(&mut self) {
|
||||
if let Some(c) = self.autocap.as_mut() {
|
||||
c.drop_stale_pronoun(&self.sel);
|
||||
if c.is_empty() {
|
||||
self.autocap = 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) {
|
||||
// A click elsewhere ends the change Next / Previous Change selected, as a caret command
|
||||
// does: coming back to it is not navigating to it.
|
||||
if sel != self.sel {
|
||||
self.review_target = None;
|
||||
}
|
||||
self.sel = sel;
|
||||
self.drop_stale_carried();
|
||||
self.drop_stale_pronoun();
|
||||
}
|
||||
|
||||
/// Drop formatting Backspace carried over, wherever the caret is: it is for typing, and a
|
||||
|
||||
@@ -62,12 +62,9 @@ impl Session {
|
||||
|
||||
/// A navigated style change is for the Accept or Reject that follows: a command that edits
|
||||
/// or moves the selection forgets it.
|
||||
fn forget_review_target(&mut self, id: &str, mutates: bool) {
|
||||
if (mutates && !matches!(id, "review.accept" | "review.reject" | "review.acceptAndNext" | "review.rejectAndNext"))
|
||||
|| id.starts_with("caret.")
|
||||
|| id.starts_with("select.")
|
||||
{
|
||||
self.review_target = None;
|
||||
fn forget_review_style(&mut self, id: &str, mutates: bool) {
|
||||
if (mutates && !matches!(id, "review.accept" | "review.reject")) || id.starts_with("caret.") || id.starts_with("select.") {
|
||||
self.review_style = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,26 +80,13 @@ impl Session {
|
||||
// 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();
|
||||
self.drop_stale_pronoun();
|
||||
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 sel_before = self.sel.clone();
|
||||
let result = self.run_command(id, params);
|
||||
// A command that moves the selection (a caret or select command, Next Comment, Find…)
|
||||
// ends the change Next / Previous Change selected, unless it is that navigation or the
|
||||
// Accept or Reject that follows it, which set or end it themselves.
|
||||
if self.sel != sel_before
|
||||
&& !matches!(
|
||||
id,
|
||||
"review.nextChange" | "review.previousChange" | "review.accept" | "review.reject" | "review.acceptAndNext" | "review.rejectAndNext"
|
||||
)
|
||||
{
|
||||
self.review_target = None;
|
||||
}
|
||||
if result.is_ok() {
|
||||
self.settle_carried(carried_before);
|
||||
} else if self.document_id == document_before {
|
||||
@@ -132,7 +116,7 @@ impl Session {
|
||||
let ime_text_join = self.ime_text_join.take();
|
||||
let reg = self.registry.clone();
|
||||
let Some(spec) = reg.get(id) else { return Err(CmdError::Unknown(id.to_string())) };
|
||||
self.forget_review_target(id, spec.mutates);
|
||||
self.forget_review_style(id, spec.mutates);
|
||||
let join = join
|
||||
|| (equation_join && matches!(id, "equation.type" | "equation.backspace"))
|
||||
|| (id == "text.insert" && ime_text_join.as_ref().is_some_and(|sel| sel == &self.sel));
|
||||
@@ -171,8 +155,6 @@ impl Session {
|
||||
// Commands may leave an equation (a whole-body replacement) even after they fail; put
|
||||
// the editing session back with the document.
|
||||
let math_before = spec.mutates.then(|| self.math.clone());
|
||||
// A header or footer edit can take its saved body selection before the protection check.
|
||||
let hf_return_before = spec.mutates.then(|| self.hf_return.clone()).flatten();
|
||||
let before_doc: Option<RunSnapshot> = if spec.mutates {
|
||||
Some((
|
||||
self.doc.clone(),
|
||||
@@ -318,7 +300,6 @@ impl Session {
|
||||
if let Some((d, s, h, r, t, ev, c)) = before_doc {
|
||||
self.doc = d;
|
||||
self.sel = s;
|
||||
self.hf_return = hf_return_before;
|
||||
self.history = h;
|
||||
self.redo = r;
|
||||
self.typing_open = t;
|
||||
@@ -359,7 +340,6 @@ impl Session {
|
||||
self.pending_at = Some(self.sel.focus.clone());
|
||||
}
|
||||
self.drop_stale_carried();
|
||||
self.drop_stale_pronoun();
|
||||
}
|
||||
|
||||
fn finish_success(&mut self, context: SuccessContext<'_>) {
|
||||
@@ -462,10 +442,6 @@ impl Session {
|
||||
}
|
||||
if sel_before.focus.story == StoryRef::Body && self.in_header_footer() {
|
||||
self.hf_return = Some(sel_before.clone());
|
||||
} else if sel_before.focus.story != StoryRef::Body && !self.in_header_footer() {
|
||||
// Back in the body: a header or footer entered next starts its own return position
|
||||
// and section, so a stale one cannot steer its section commands.
|
||||
self.hf_section = None;
|
||||
}
|
||||
// A selection command that moves the insertion point ends the typing group, like
|
||||
// caret movement: typing, Select, typing are two undo steps (#419).
|
||||
|
||||
@@ -19,8 +19,6 @@ impl Session {
|
||||
self.doc.ensure_nonempty();
|
||||
self.password = None;
|
||||
self.file_name = None;
|
||||
// The file the old document was read from or saved to is not this one's (file.open stamps its own).
|
||||
self.disk_stamp = None;
|
||||
// The old document's equation is gone: its editing session cannot carry over.
|
||||
self.math = None;
|
||||
self.sel = Selection::caret(self.doc.start_of(StoryRef::Body));
|
||||
@@ -35,7 +33,6 @@ impl Session {
|
||||
self.edit_marks.clear();
|
||||
self.new_header_parts.clear();
|
||||
self.hf_return = None;
|
||||
self.hf_section = None;
|
||||
self.go_back_step = 0;
|
||||
self.view.outline.collapsed.clear();
|
||||
self.view.follow_prefs(&self.prefs);
|
||||
@@ -79,8 +76,6 @@ impl Session {
|
||||
pending_at,
|
||||
last_highlight: _,
|
||||
path: _,
|
||||
// How the file looked when read or saved: like the file path, not an edit.
|
||||
disk_stamp: _,
|
||||
file_name: _,
|
||||
// The custom dictionary file, like the file path: host wiring, not an edit.
|
||||
user_dict_path: _,
|
||||
@@ -105,9 +100,8 @@ impl Session {
|
||||
// Headers just created to edit: closing checks they still exist and are empty.
|
||||
new_header_parts: _,
|
||||
hf_return: _,
|
||||
hf_section: _,
|
||||
// Which navigated style change Accept/Reject acts on: it checks the selection itself.
|
||||
review_target: _,
|
||||
review_style: _,
|
||||
history,
|
||||
undo_evicted,
|
||||
redo,
|
||||
|
||||
@@ -20,8 +20,6 @@ pub struct WindowView {
|
||||
goal_x: Option<f32>,
|
||||
page_hint: usize,
|
||||
hf_return: Option<Selection>,
|
||||
hf_section: Option<usize>,
|
||||
section_ends: Vec<usize>,
|
||||
typing_open: bool,
|
||||
join_next: bool,
|
||||
equation_join_next: bool,
|
||||
@@ -69,8 +67,6 @@ impl Session {
|
||||
goal_x: self.goal_x.take(),
|
||||
page_hint: take(&mut self.page_hint),
|
||||
hf_return: self.hf_return.take(),
|
||||
hf_section: self.hf_section.take(),
|
||||
section_ends: self.doc.sections().into_iter().map(|(end, _)| end).collect(),
|
||||
typing_open: take(&mut self.typing_open),
|
||||
join_next: take(&mut self.join_next),
|
||||
equation_join_next: take(&mut self.equation_join_next),
|
||||
@@ -96,8 +92,6 @@ impl Session {
|
||||
goal_x: self.goal_x,
|
||||
page_hint: self.page_hint,
|
||||
hf_return: self.hf_return.clone(),
|
||||
hf_section: self.hf_section,
|
||||
section_ends: self.doc.sections().into_iter().map(|(end, _)| end).collect(),
|
||||
// The new window hasn't typed: its first key starts an undo step of its own.
|
||||
typing_open: false,
|
||||
join_next: false,
|
||||
@@ -129,8 +123,6 @@ impl Session {
|
||||
goal_x,
|
||||
page_hint,
|
||||
hf_return,
|
||||
hf_section,
|
||||
section_ends,
|
||||
typing_open,
|
||||
join_next,
|
||||
equation_join_next,
|
||||
@@ -158,7 +150,6 @@ impl Session {
|
||||
self.member = None;
|
||||
if current {
|
||||
self.hf_return = hf_return;
|
||||
self.hf_section = hf_section;
|
||||
self.typing_open = typing_open;
|
||||
self.join_next = join_next;
|
||||
self.equation_join_next = equation_join_next;
|
||||
@@ -170,8 +161,6 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
self.hf_return = hf_return.map(|s| Selection { anchor: self.doc.clamp(&s.anchor), focus: self.doc.clamp(&s.focus) });
|
||||
self.hf_section =
|
||||
(document_id == self.document_id && self.doc.sections().into_iter().map(|(end, _)| end).eq(section_ends)).then_some(hf_section).flatten();
|
||||
self.typing_open = false;
|
||||
self.join_next = false;
|
||||
self.equation_join_next = false;
|
||||
|
||||
@@ -211,15 +211,10 @@ pub(crate) fn png_display() -> DisplayOptions {
|
||||
opts.display
|
||||
}
|
||||
|
||||
/// The document's PDF output layout, shared by strict checks and font notices.
|
||||
pub(crate) fn pdf_layout(doc: &Document, pdf: &wordcraft_pdf::PdfOptions) -> DocLayout {
|
||||
wordcraft_layout::layout(doc, &mut LayoutCache::new(), &pdf.layout_options())
|
||||
}
|
||||
|
||||
/// The strict report of a PDF export of `doc`: every page, laid out as the export lays it out.
|
||||
pub(crate) fn pdf_report(doc: &Document, opts: &ExportOptions) -> StrictReport {
|
||||
let pdf = pdf_options(opts);
|
||||
let lay = pdf_layout(doc, &pdf);
|
||||
let lay = wordcraft_layout::layout(doc, &mut LayoutCache::new(), &pdf.layout_options());
|
||||
strict_report(doc, &lay, &pdf.display_options(), None, StrictOutput::Pdf)
|
||||
}
|
||||
|
||||
@@ -230,7 +225,7 @@ pub(crate) fn export_pdf(doc: &Document, opts: &ExportOptions) -> Result<Vec<u8>
|
||||
if !opts.strict {
|
||||
return wordcraft_pdf::export(doc, &pdf).map_err(|e| e.to_string());
|
||||
}
|
||||
let lay = pdf_layout(doc, &pdf);
|
||||
let lay = wordcraft_layout::layout(doc, &mut LayoutCache::new(), &pdf.layout_options());
|
||||
let report = strict_report(doc, &lay, &pdf.display_options(), None, StrictOutput::Pdf);
|
||||
if !report.passed() {
|
||||
return Err(report.refusal());
|
||||
|
||||
+75
-422
@@ -312,9 +312,6 @@ fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_thei
|
||||
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");
|
||||
std::fs::write(&outside, "outsideword\n").unwrap();
|
||||
assert!(confined(&mut s, "file.options", json!({"customDictionary": outside})).is_err());
|
||||
assert_eq!(s.prefs.custom_dictionary, None);
|
||||
for key in ["dictionariesFolder", "userTemplatesFolder"] {
|
||||
assert!(confined(&mut s, "file.options", json!({key: base.join("outside").to_string_lossy()})).is_err(), "{key}");
|
||||
}
|
||||
@@ -410,6 +407,33 @@ fn custom_dictionary_freestanding_file_option() {
|
||||
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());
|
||||
@@ -4508,14 +4532,6 @@ fn tracked_style_definition_changes_are_recorded_and_resolved() {
|
||||
run(&mut s, "review.acceptAll", json!({}));
|
||||
assert_eq!(s.doc.styles.get("Heading1").unwrap().chr.bold, Some(true), "accepting keeps the change");
|
||||
assert!(s.doc.revisions.is_empty());
|
||||
|
||||
for (command, italic) in [("review.rejectAndNext", None), ("review.acceptAndNext", Some(true))] {
|
||||
run(&mut s, "styles.modify", json!({"style": "Heading1", "chr": {"italic": true}}));
|
||||
run(&mut s, "review.nextChange", json!({}));
|
||||
run(&mut s, command, json!({}));
|
||||
assert_eq!(s.doc.styles.get("Heading1").unwrap().chr.italic, italic, "{command} resolves the navigated style definition");
|
||||
assert_eq!(run(&mut s, "review.changes", json!({})), json!([]), "{command} leaves no style change behind");
|
||||
}
|
||||
}
|
||||
|
||||
/// #2697 review: Update Style to Match Selection also rewrites the selected paragraph. Its body
|
||||
@@ -4583,7 +4599,7 @@ fn a_whole_body_selection_resolves_style_changes_after_text_shrinks() {
|
||||
/// #2697 review: change navigation selects the collapsed style-change anchor, where an
|
||||
/// individual Reject resolves it.
|
||||
#[test]
|
||||
fn a_navigated_target_change_can_be_resolved_at_its_anchor() {
|
||||
fn a_navigated_style_change_can_be_resolved_at_its_anchor() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "body"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
@@ -4604,7 +4620,7 @@ fn a_navigated_target_change_can_be_resolved_at_its_anchor() {
|
||||
/// put at the document start by other means resolves none of them; Accept/Reject All still
|
||||
/// resolve them all.
|
||||
#[test]
|
||||
fn a_navigated_target_change_is_resolved_alone() {
|
||||
fn a_navigated_style_change_is_resolved_alone() {
|
||||
for (command, accept) in [("review.accept", true), ("review.reject", false)] {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "body"}));
|
||||
@@ -8439,173 +8455,6 @@ fn styles_apply_multi_paragraph_selection() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9203: `styles.modify` rejects unknown keys in `para` and `chr` (such as snake_case names)
|
||||
/// instead of silently dropping them, while applying camelCase `ParaProps` fields.
|
||||
#[test]
|
||||
fn styles_modify_rejects_unknown_para_and_chr_fields() {
|
||||
let mut s = s();
|
||||
let err = s
|
||||
.run("styles.modify", &json!({"style": "Heading1", "para": {"space_before": 123, "page_break_before": true}, "chr": {"size": 33}}))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error, got {err:?}");
|
||||
let h1 = s.doc.styles.get("Heading1").unwrap();
|
||||
assert_ne!(h1.chr.size, Some(33.0), "rejected para block must not partially apply chr");
|
||||
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "chr": {"unknownKey": true}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error, got {err:?}");
|
||||
|
||||
// #9291: unknown keys inside nested structs (such as Borders / Border) are rejected too,
|
||||
// naming the path and expected fields (#9411).
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "para": {"borders": {"Top": {"width": 1.0}}}})).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, crate::CmdError::Params(ref msg) if msg.contains("`para.borders`") && msg.contains("`Top`") && msg.contains("`top`")),
|
||||
"{err:?}"
|
||||
);
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "para": {"borders": {"top": {"bogus": 1.0}}}})).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, crate::CmdError::Params(ref msg) if msg.contains("`para.borders.top`") && msg.contains("`bogus`") && msg.contains("`width`")),
|
||||
"{err:?}"
|
||||
);
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "para": {"lineSpacing": {"Multiple": 1.5}}})).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, crate::CmdError::Params(ref msg) if msg.contains("`para.lineSpacing`") && msg.contains("`Multiple`") && msg.contains("expected `rule` or `value`")),
|
||||
"{err:?}"
|
||||
);
|
||||
// #9635: type/missing errors inside gradient stops keep the full `textEffects.fill.stops[i].field` path (#9663).
|
||||
let err = s
|
||||
.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "gradient", "stops": [{"pos": "bad"}]}}}}))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref msg) if msg.contains("`chr.textEffects.fill.stops[0].pos`")), "{err:?}");
|
||||
|
||||
s.run(
|
||||
"styles.modify",
|
||||
&json!({"style": "Heading1", "para": {"spaceBefore": 123.0, "pageBreakBefore": true, "borders": {"top": {"width": 1.5, "style": "single"}}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let h1 = s.doc.styles.get("Heading1").unwrap();
|
||||
assert_eq!(h1.para.space_before, Some(123.0));
|
||||
assert_eq!(h1.para.page_break_before, Some(true));
|
||||
assert!(h1.para.borders.as_ref().and_then(|b| b.top).is_some_and(|t| (t.width - 1.5).abs() < 0.01));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_modify_checks_tagged_text_fill_fields_before_changing_the_style() {
|
||||
use wordcraft_doc::wordart::TextFill;
|
||||
|
||||
let mut s = s();
|
||||
let before = s.doc.styles.get("Heading1").unwrap().clone();
|
||||
let gradient_stops = json!([{"pos": 0, "color": "112233"}, {"pos": 100, "color": "445566", "transparency": 25}]);
|
||||
for (fill, field) in [
|
||||
(json!({"type": "solid", "color": "FF0000", "bogus": 1}), "bogus"),
|
||||
(json!({"type": "none", "color": "FF0000"}), "color"),
|
||||
(json!({"type": "gradient", "stops": gradient_stops, "color": "FF0000"}), "color"),
|
||||
(json!({"type": "gradient", "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}), "bogus"),
|
||||
] {
|
||||
let err = s
|
||||
.run(
|
||||
"styles.modify",
|
||||
&json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": {"textEffects": {"fill": fill}}}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains(field)), "{err:?}");
|
||||
assert_eq!(s.doc.styles.get("Heading1"), Some(&before), "rejected fill must leave the style unchanged");
|
||||
}
|
||||
|
||||
let fill = |s: &Session| s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.clone().unwrap();
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "solid", "color": "FF0000"}}}})).unwrap();
|
||||
assert_eq!(fill(&s), TextFill::Solid { color: wordcraft_doc::Rgb(255, 0, 0), transparency: 0.0 });
|
||||
s.run(
|
||||
"styles.modify",
|
||||
&json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "gradient", "angle": 45, "stops": gradient_stops}}}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(fill(&s), TextFill::Gradient { stops, angle } if angle == 45.0 && stops.len() == 2 && stops[1].transparency == 25.0));
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "none"}}}})).unwrap();
|
||||
assert_eq!(fill(&s), TextFill::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_modify_checks_text_fills_in_positional_arguments() {
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::wordart::TextFill;
|
||||
|
||||
let chr_with = |text_effects: Value, positional: bool| {
|
||||
if positional {
|
||||
// CharProps puts textEffects after the first 30 optional fields.
|
||||
let mut fields = vec![Value::Null; 30];
|
||||
fields.push(text_effects);
|
||||
Value::Array(fields)
|
||||
} else {
|
||||
json!({"textEffects": text_effects})
|
||||
}
|
||||
};
|
||||
let mut s = s();
|
||||
let stops = json!([{"pos": 0, "color": "112233"}, [100, "445566", 25]]);
|
||||
for (positional_chr, positional_effects) in [(false, false), (false, true), (true, false), (true, true)] {
|
||||
let effects = |fill: Value| if positional_effects { json!([fill]) } else { json!({"fill": fill}) };
|
||||
let before = s.doc.styles.get("Heading1").unwrap().clone();
|
||||
for fill in [
|
||||
json!({"type": "solid", "color": "FF0000", "bogus": 1}),
|
||||
json!({"type": "gradient", "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}),
|
||||
json!(["gradient", [{"pos": 0, "color": "112233", "bogus": 1}], 45]),
|
||||
] {
|
||||
let chr = chr_with(effects(fill), positional_chr);
|
||||
let params = json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": chr});
|
||||
let err = s.run("styles.modify", ¶ms).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
|
||||
assert_eq!(s.doc.styles.get("Heading1"), Some(&before));
|
||||
}
|
||||
for fill in [json!({"type": "gradient", "stops": stops, "angle": 45}), json!(["gradient", stops, 45])] {
|
||||
let chr = chr_with(effects(fill), positional_chr);
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": chr})).unwrap();
|
||||
let fill = s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.as_ref().unwrap();
|
||||
assert!(matches!(fill, TextFill::Gradient { stops, angle } if *angle == 45.0 && stops.len() == 2 && stops[1].transparency == 25.0));
|
||||
}
|
||||
}
|
||||
|
||||
let before = s.doc.styles.get("Heading1").unwrap().clone();
|
||||
let old = chr_with(json!([{"type": "solid", "color": "FF0000", "bogus": 1}]), true);
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "chr": {"fmtChange": {"rev": 0, "old": old}}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
|
||||
assert_eq!(s.doc.styles.get("Heading1"), Some(&before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_modify_checks_numeric_text_fill_tags() {
|
||||
let mut refused = s();
|
||||
let before = refused.doc.styles.get("Heading1").unwrap().clone();
|
||||
for fill in [
|
||||
json!({"type": 0, "bogus": 1}),
|
||||
json!({"type": 1, "color": "FF0000", "bogus": 1}),
|
||||
json!({"type": 2, "stops": [{"pos": 0, "color": "112233"}], "bogus": 1}),
|
||||
json!({"type": 2, "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}),
|
||||
json!([2, [{"pos": 0, "color": "112233", "bogus": 1}], 45]),
|
||||
] {
|
||||
let err = refused
|
||||
.run("styles.modify", &json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": {"textEffects": [fill]}}))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
|
||||
assert_eq!(refused.doc.styles.get("Heading1"), Some(&before));
|
||||
}
|
||||
|
||||
let stops = json!([{"pos": 0, "color": "112233"}, [100, "445566", 25]]);
|
||||
for (fill, named) in [
|
||||
(json!({"type": 0}), json!({"type": "none"})),
|
||||
(json!([0]), json!({"type": "none"})),
|
||||
(json!({"type": 1, "color": "FF0000"}), json!({"type": "solid", "color": "FF0000", "transparency": 0.0})),
|
||||
(json!([1, "FF0000", 0]), json!({"type": "solid", "color": "FF0000", "transparency": 0.0})),
|
||||
(json!({"type": 2, "stops": stops, "angle": 45}), json!({"type": "gradient", "stops": stops, "angle": 45})),
|
||||
(json!([2, stops, 45]), json!({"type": "gradient", "stops": stops, "angle": 45})),
|
||||
] {
|
||||
let set_fill = |fill| {
|
||||
let mut s = s();
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": fill}}})).unwrap();
|
||||
s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.clone().unwrap()
|
||||
};
|
||||
assert_eq!(set_fill(fill), set_fill(named));
|
||||
}
|
||||
}
|
||||
|
||||
/// #865: `styles.modify` takes a colour the way `format.color` does (`RRGGBB`, `#RRGGBB`, `auto`),
|
||||
/// still reads the serialized forms, and rejects a bad colour without touching the style.
|
||||
#[test]
|
||||
@@ -12041,17 +11890,19 @@ fn next_footnote_skips_endnotes() {
|
||||
assert_eq!(s.sel.focus.off, 9);
|
||||
}
|
||||
|
||||
/// Tests that read or mutate process-wide proofing dictionaries take turns through `DICT_TEST_LOCK`.
|
||||
/// Tests that install a test dictionary wait for the dictionaries-folder test, which changes the
|
||||
/// folder and then reads what each language reports: an install in between reports no file.
|
||||
static DICTIONARIES: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn dictionaries_turn() -> std::sync::MutexGuard<'static, ()> {
|
||||
crate::custom_dict::dict_test_lock()
|
||||
DICTIONARIES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// A tiny synthetic Polish Hunspell dictionary (written for these tests). Real dictionaries are
|
||||
/// installed on the system, never bundled; every Polish test installs this same one.
|
||||
fn polish_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
fn polish_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
wordcraft_proof::pl::install_dictionary(POLISH_TEST_AFF, POLISH_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
const POLISH_TEST_AFF: &str = "SET UTF-8\nTRY aioeznrwcyszżtkpdmłjlubąęgh\nMAP 2\nMAP oó\nMAP zż\nREP 2\nREP ż rz\nREP rz ż\n";
|
||||
@@ -12059,10 +11910,9 @@ const POLISH_TEST_DIC: &str = "12\npłynie\nrzeka\na\nto\nwiem\nże\ntak\nw\nog
|
||||
|
||||
/// A tiny synthetic Portuguese Hunspell dictionary (written for these tests). Real dictionaries
|
||||
/// are installed on the system, never bundled; every Portuguese test installs this same one.
|
||||
fn portuguese_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
fn portuguese_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
wordcraft_proof::pt::install_dictionary(PORTUGUESE_TEST_AFF, PORTUGUESE_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
const PORTUGUESE_TEST_AFF: &str =
|
||||
@@ -12137,7 +11987,7 @@ fn dictionaries_folder_option_is_saved_searched_and_reported() {
|
||||
/// grammar, suggestions come from it, and a suggestion fixes the text.
|
||||
#[test]
|
||||
fn portuguese_proofing_through_the_review_commands() {
|
||||
let _turn = portuguese_test_dictionary();
|
||||
portuguese_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Saudade coraçao, e ele ele disse."}));
|
||||
// English by default: the Portuguese words are English misspellings.
|
||||
@@ -12168,10 +12018,9 @@ fn portuguese_proofing_through_the_review_commands() {
|
||||
assert_eq!(left.as_array().unwrap().len(), 1, "{left}");
|
||||
}
|
||||
|
||||
fn indonesian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
fn indonesian_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
wordcraft_proof::id::install_dictionary(INDONESIAN_TEST_AFF, INDONESIAN_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
// Hand-written synthetic fixture (no system dictionary data).
|
||||
@@ -12182,7 +12031,7 @@ const INDONESIAN_TEST_DIC: &str = "8\nrumah\nsekolah\nanak\nbermain\ndi\nmakan/A
|
||||
/// Dictionary.
|
||||
#[test]
|
||||
fn indonesian_proofing_through_the_review_commands() {
|
||||
let _turn = indonesian_test_dictionary();
|
||||
indonesian_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Saya di sekolha, anak anak bermain."}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12237,7 +12086,6 @@ fn english_dialects_through_the_review_commands() {
|
||||
if no_language_data("english_dialects_through_the_review_commands") {
|
||||
return;
|
||||
}
|
||||
let _turn = dictionaries_turn();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "The colour of the center."}));
|
||||
// US English by default: the British spelling is flagged, the American one isn't.
|
||||
@@ -12345,20 +12193,19 @@ const SPANISH_TEST_AFF: &str =
|
||||
const SPANISH_TEST_DIC: &str = "10\nesto\nes\nuna\nprueba/S\ndel\ncorrector\ntambién\nhabéis\nvenido\ndecir\n";
|
||||
const URUGUAYAN_TEST_DIC: &str = "10\nesto\nes\nuna\nprueba/S\ndel\ncorrector\ntambién\ntener\nvenir\ndecir\n";
|
||||
|
||||
fn spanish_test_dictionaries() -> std::sync::MutexGuard<'static, ()> {
|
||||
fn spanish_test_dictionaries() {
|
||||
use wordcraft_proof::ProofLang;
|
||||
let turn = dictionaries_turn();
|
||||
let _turn = dictionaries_turn();
|
||||
for (lang, dic) in [(ProofLang::Es, SPANISH_TEST_DIC), (ProofLang::EsUy, URUGUAYAN_TEST_DIC)] {
|
||||
wordcraft_proof::es::install_dictionary(lang, SPANISH_TEST_AFF, dic).unwrap();
|
||||
}
|
||||
turn
|
||||
}
|
||||
|
||||
/// #3553: Spanish proofing through the same commands as Review, F7, Change and Add to
|
||||
/// Dictionary: `prueva` and `corector` are flagged with `prueba` and `corrector` offered.
|
||||
#[test]
|
||||
fn spanish_proofing_through_the_review_commands() {
|
||||
let _turn = spanish_test_dictionaries();
|
||||
spanish_test_dictionaries();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "esto es una prueva del corector. Habéis venido?"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12389,7 +12236,7 @@ fn spanish_proofing_through_the_review_commands() {
|
||||
/// bytes.
|
||||
#[test]
|
||||
fn add_and_ignore_all_accept_both_normalization_forms() {
|
||||
let _turn = spanish_test_dictionaries();
|
||||
spanish_test_dictionaries();
|
||||
let mut s = s();
|
||||
let text = "esto zqanade\u{301}do y zqignora\u{301}do";
|
||||
run(&mut s, "document.setText", json!({"text": text}));
|
||||
@@ -12418,7 +12265,7 @@ fn add_and_ignore_all_accept_both_normalization_forms() {
|
||||
/// Uruguayan Spanish accepts the `vos` forms, imperatives included, that Spain's flags.
|
||||
#[test]
|
||||
fn uruguayan_spanish_accepts_vos_forms() {
|
||||
let _turn = spanish_test_dictionaries();
|
||||
spanish_test_dictionaries();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Vení, decime qué tenés."}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12437,7 +12284,7 @@ fn uruguayan_spanish_accepts_vos_forms() {
|
||||
/// Czech proofing through the same commands as Review, F7, Change and Add to Dictionary.
|
||||
#[test]
|
||||
fn czech_proofing_through_the_review_commands() {
|
||||
let _turn = czech_test_dict::install();
|
||||
czech_test_dict::install();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Město pocitac, škola škola."}));
|
||||
assert!(run(&mut s, "review.issues", json!({})).as_array().unwrap().len() >= 3);
|
||||
@@ -12476,10 +12323,9 @@ fn czech_proofing_through_the_review_commands() {
|
||||
const ITALIAN_TEST_AFF: &str = "SET UTF-8\nTRY aeiortnsclcaffèéè\nMAP 2\nMAP aà\nMAP eéè\nREP 1\nREP caffe caffè\n";
|
||||
const ITALIAN_TEST_DIC: &str = "6\ncasa\ncaffè\nroma\ndisse\ne\nper\n";
|
||||
|
||||
fn italian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
fn italian_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
wordcraft_proof::it::install_dictionary(ITALIAN_TEST_AFF, ITALIAN_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
/// Review › Language and the proofing commands work in Italian end to end: the language makes
|
||||
@@ -12487,7 +12333,7 @@ fn italian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
/// suggestions come from it, and a suggestion fixes the text.
|
||||
#[test]
|
||||
fn italian_proofing_through_the_review_commands() {
|
||||
let _turn = italian_test_dictionary();
|
||||
italian_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Casa caffe, e roma roma disse."}));
|
||||
// English by default: the Italian words are English misspellings.
|
||||
@@ -12520,7 +12366,7 @@ fn italian_proofing_through_the_review_commands() {
|
||||
|
||||
#[test]
|
||||
fn polish_proofing_through_the_review_commands() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Płynie żeka, a wogóle to wiem że tak."}));
|
||||
// English by default: the Polish words are English misspellings.
|
||||
@@ -12560,7 +12406,6 @@ fn turkish_proofing_through_the_review_commands() {
|
||||
if !crate::proof::tr::has_dictionary() {
|
||||
return;
|
||||
}
|
||||
let _turn = dictionaries_turn();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Bana bazen gelenler oldu ise de. Sana olacaklardan sonra sorna"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12588,7 +12433,7 @@ fn turkish_proofing_through_the_review_commands() {
|
||||
/// no parameters keep the old meaning (US English), and `default` needs a language.
|
||||
#[test]
|
||||
fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Hello wrold"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12609,7 +12454,6 @@ fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
// A language without proofing tools: no marks. `zxx` (no linguistic content) never has
|
||||
// them; a real language such as fr-FR does wherever its system Hunspell dictionary is installed.
|
||||
run(&mut s, "review.language", json!({"lang": "zxx"}));
|
||||
assert_eq!(run(&mut s, "format.state", json!({}))["lang"], "zxx");
|
||||
assert_eq!(run(&mut s, "review.issues", json!({})), json!([]));
|
||||
}
|
||||
|
||||
@@ -12617,7 +12461,7 @@ fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
/// the caret, not the document's default, so what is typed in them is proofed in that language.
|
||||
#[test]
|
||||
fn a_new_table_is_in_the_language_at_the_caret() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let cell_langs = |s: &Session| -> Vec<Option<String>> {
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
t.rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).map(|p| p.mark.lang.clone()).collect()
|
||||
@@ -12661,7 +12505,7 @@ fn a_new_table_is_in_the_language_at_the_caret() {
|
||||
/// a document with changes never does, and templates stay English.
|
||||
#[test]
|
||||
fn new_documents_follow_the_editing_language() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let mut s = s();
|
||||
s.set_editing_language(Some("pl-PL"));
|
||||
assert_eq!(s.doc.styles.default_chr.lang.as_deref(), Some("pl-PL"), "the untouched blank document switches");
|
||||
@@ -12767,7 +12611,7 @@ fn rejected_default_proofing_language_does_not_survive_a_restart() {
|
||||
/// English run (`w:lang`) come back, and so does the proofing.
|
||||
#[test]
|
||||
fn proofing_languages_survive_a_docx_round_trip() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Płynie żeka. Hello wrold."}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -15211,7 +15055,7 @@ fn export_png_refuses_a_path_that_is_not_png() {
|
||||
#[test]
|
||||
fn ime_body_epoch_marks_body_replacements_not_edits() {
|
||||
let mut s = s();
|
||||
let document_id = s.document_id();
|
||||
let id = s.document_id();
|
||||
run(&mut s, "text.insert", json!({"text": "one"}));
|
||||
let first = s.ime_body_epoch();
|
||||
run(&mut s, "text.insert", json!({"text": " two"}));
|
||||
@@ -15220,7 +15064,7 @@ fn ime_body_epoch_marks_body_replacements_not_edits() {
|
||||
run(&mut s, "document.setText", json!({"text": "same text"}));
|
||||
let replaced = s.ime_body_epoch();
|
||||
assert!(replaced > first, "setText replaces the body under the same document id");
|
||||
assert_eq!(s.document_id(), document_id, "the document id itself is unchanged");
|
||||
assert_eq!(s.document_id(), id, "the document id itself is unchanged");
|
||||
|
||||
// The same text again still replaces the body: a composition must not survive on content
|
||||
// equality.
|
||||
@@ -15612,37 +15456,6 @@ fn export_png_rejects_a_page_number_that_does_not_fit() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_text_smoothing_is_a_persistent_preference_not_document_formatting() {
|
||||
use crate::cmd::view::TextSmoothing;
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "Screen text test", "raw": true}));
|
||||
let before = serde_json::to_value(&s.doc).unwrap();
|
||||
let docx_before = wordcraft_docx::write(&s.doc).unwrap();
|
||||
s.dirty = false;
|
||||
assert_eq!(s.prefs.text_smoothing, TextSmoothing::System, "follows the system until the user chooses");
|
||||
for (value, expected) in [("subpixel", TextSmoothing::Subpixel), ("grayscale", TextSmoothing::Grayscale), ("system", TextSmoothing::System)] {
|
||||
let r = run(&mut s, "view.textSmoothing", json!({"value": value}));
|
||||
assert_eq!(r["textSmoothing"], value);
|
||||
assert_eq!(s.prefs.text_smoothing, expected);
|
||||
assert_eq!(serde_json::to_value(&s.doc).unwrap(), before);
|
||||
assert!(!s.dirty);
|
||||
assert_eq!(wordcraft_docx::write(&s.doc).unwrap(), docx_before);
|
||||
let restored: crate::Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
|
||||
assert_eq!(restored.text_smoothing, expected);
|
||||
}
|
||||
run(&mut s, "view.textSmoothing", json!({"value": "subpixel"}));
|
||||
for v in [json!({}), json!({"value": "lcd"}), json!({"value": 42}), json!({"value": null}), json!({"value": ["subpixel"]})] {
|
||||
assert!(s.run("view.textSmoothing", &v).is_err(), "{v}");
|
||||
assert_eq!(s.prefs.text_smoothing, TextSmoothing::Subpixel, "a refused value changes nothing");
|
||||
}
|
||||
let legacy: crate::Prefs = serde_json::from_value(json!({})).unwrap();
|
||||
assert_eq!(legacy.text_smoothing, TextSmoothing::System);
|
||||
let future: crate::Prefs = serde_json::from_value(json!({"textSmoothing":"future", "countNotes":false})).unwrap();
|
||||
assert_eq!(future.text_smoothing, TextSmoothing::System);
|
||||
assert!(!future.count_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_paper_color_is_a_persistent_preference_not_document_formatting() {
|
||||
use crate::cmd::view::PaperColor;
|
||||
@@ -16036,47 +15849,36 @@ fn page_down_and_up_move_by_a_page_in_the_continuous_views() {
|
||||
|
||||
#[test]
|
||||
fn page_down_and_up_never_stay_on_a_line_in_the_continuous_views() {
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
// The text area is less than an inch high, so the views use a 72 pt step. A step can cross
|
||||
// different numbers of 30 pt lines in the two directions. Start inside the document so the
|
||||
// test exercises movement in both directions without running into the first line.
|
||||
let lead_in = 12;
|
||||
let long = "Lorem ipsum dolor sit amet ".repeat(2);
|
||||
let text = format!("{}{long}{}", "a\n".repeat(lead_in), "\na".repeat(60));
|
||||
// A page with less than an inch of text area: the views move by the one-inch minimum. The
|
||||
// caret ends a long line and the paragraphs after it are narrow (a large right indent): the
|
||||
// line a page away, not the one the caret is on, is where Page Down goes, however far right
|
||||
// of it the caret is.
|
||||
for view in ["view.draft", "view.outline", "view.webLayout"] {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&text));
|
||||
let mut s = s();
|
||||
run(&mut s, "layout.margins", json!({"top": 370, "bottom": 370}));
|
||||
for (i, path) in s.doc.para_paths(StoryRef::Body).iter().enumerate() {
|
||||
let p = s.doc.para_mut(StoryRef::Body, path).unwrap();
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(30.0));
|
||||
if i != lead_in {
|
||||
p.props.indent_right = Some(700.0);
|
||||
let long = "Lorem ipsum dolor sit amet ".repeat(2);
|
||||
run(&mut s, "text.insert", json!({"text": long}));
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "para.indents", json!({"right": 700}));
|
||||
for i in 0..60 {
|
||||
if i > 0 {
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
}
|
||||
run(&mut s, "text.insert", json!({"text": "a"}));
|
||||
}
|
||||
run(&mut s, view, json!({}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"block": lead_in}}));
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "caret.end", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(lead_in, long.len()), "{view}: the long paragraph is one line");
|
||||
assert_eq!(s.sel.focus.off, long.chars().count(), "{view}: the first paragraph is one line");
|
||||
let mut at = s.sel.focus.clone();
|
||||
let layout = s.layout();
|
||||
let start = layout.caret(&at).unwrap();
|
||||
let first = layout.caret(&Pos::body(0, 0)).unwrap();
|
||||
assert!(start.top - first.top > 3.0 * 72.0, "{view}: there is room above the long line for all three reverse steps");
|
||||
for step in 0..3 {
|
||||
run(&mut s, "caret.pageDown", json!({}));
|
||||
assert!(s.sel.focus.path > at.path, "{view}: Page Down {step} moves to a later paragraph from {at:?}");
|
||||
assert!(s.sel.focus > at, "{view}: Page Down {step} moves on from {at:?}");
|
||||
at = s.sel.focus.clone();
|
||||
if step == 0 {
|
||||
let next = s.layout().caret(&at).unwrap();
|
||||
assert!(next.x < start.x, "{view}: the destination line ends left of the starting caret");
|
||||
}
|
||||
}
|
||||
for step in 0..3 {
|
||||
run(&mut s, "caret.pageUp", json!({}));
|
||||
assert!(s.sel.focus.path < at.path, "{view}: Page Up {step} moves to an earlier paragraph from {at:?}");
|
||||
assert!(s.sel.focus < at, "{view}: Page Up {step} moves back from {at:?}");
|
||||
at = s.sel.focus.clone();
|
||||
}
|
||||
}
|
||||
@@ -16165,48 +15967,6 @@ fn replace_all_replaces_in_every_story() {
|
||||
assert!(story_text(&t, StoryRef::Part(ids[0])).contains("Jane"));
|
||||
}
|
||||
|
||||
/// #9063: With Track Changes on, Replace All must not leave the caret in another story (e.g. a
|
||||
/// header or footnote) when the caret's original story had no match.
|
||||
#[test]
|
||||
fn replace_all_with_track_changes_keeps_caret_when_original_story_has_no_match() {
|
||||
use wordcraft_doc::StoryRef;
|
||||
let mut t = s();
|
||||
run(&mut t, "document.setText", json!({"text": "Main text only."}));
|
||||
let header_id = run(&mut t, "insert.header", json!({"text": "Header: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
t.sel = crate::session::Selection::caret(Pos::body(0, 0));
|
||||
let before = t.sel.clone();
|
||||
assert_eq!(before.focus.story, StoryRef::Body);
|
||||
|
||||
run(&mut t, "review.trackChanges", json!({"enabled": true}));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 1, "{r}");
|
||||
assert_eq!(t.sel, before);
|
||||
assert!(!t.in_header_footer());
|
||||
assert!(
|
||||
t.doc.para_at(&wordcraft_doc::Pos::new(StoryRef::Part(header_id), wordcraft_doc::Path::top(0), 0)).is_some_and(|p| p.text.contains("Jane"))
|
||||
);
|
||||
}
|
||||
|
||||
/// #9186: With Track Changes on, Replace All must keep the caret in its original story even when
|
||||
/// both that story and the main text have matches.
|
||||
#[test]
|
||||
fn replace_all_with_track_changes_keeps_caret_in_original_story_when_both_match() {
|
||||
use wordcraft_doc::StoryRef;
|
||||
let mut t = s();
|
||||
run(&mut t, "document.setText", json!({"text": "Body: [NAME]."}));
|
||||
let header_id = run(&mut t, "insert.header", json!({"text": "Header: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
let header_story = StoryRef::Part(header_id);
|
||||
t.sel = crate::session::Selection::caret(Pos::new(header_story, wordcraft_doc::Path::top(0), 0));
|
||||
|
||||
run(&mut t, "review.trackChanges", json!({"enabled": true}));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 2, "{r}");
|
||||
assert_eq!(t.sel.focus.story, header_story, "caret must stay in the header story");
|
||||
assert!(t.in_header_footer());
|
||||
assert!(t.doc.plain_text(StoryRef::Body).contains("Jane"));
|
||||
assert!(t.doc.plain_text(header_story).contains("Jane"));
|
||||
}
|
||||
|
||||
/// #9064: Replace All skips stories nothing shows any more (a removed header, a footnote whose
|
||||
/// reference was deleted without tracking) and does not count them.
|
||||
#[test]
|
||||
@@ -16819,110 +16579,3 @@ fn opening_open_document_files_reports_section_conversion_errors_without_replaci
|
||||
assert_eq!(text(&s), "Incoming document", "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #7069: AutoSave's save (`ifUnchanged`) leaves the document's own file alone once another
|
||||
/// program has changed or removed it since the document was opened or saved here. A save the user
|
||||
/// asks for still writes it, and AutoSave goes on from there.
|
||||
#[test]
|
||||
fn an_if_unchanged_save_leaves_a_file_another_program_changed() {
|
||||
use serde_json::json;
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-7069-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("shared.docx");
|
||||
let p = path.to_string_lossy().to_string();
|
||||
let theirs = crate::io::save_bytes("shared.docx", &wordcraft_doc::Document::from_text("Theirs, newer")).unwrap();
|
||||
// Another program writes the file, each time later than any stamp before (whatever the clock
|
||||
// or file system resolution).
|
||||
let ahead = std::cell::Cell::new(10u64);
|
||||
let write_theirs = || {
|
||||
std::fs::write(&path, &theirs).unwrap();
|
||||
ahead.set(ahead.get() + 10);
|
||||
let later = std::time::SystemTime::now() + std::time::Duration::from_secs(ahead.get());
|
||||
std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap();
|
||||
};
|
||||
let mut s = crate::Session::new(wordcraft_doc::Document::from_text("Mine"));
|
||||
s.run("file.save", &json!({"path": p})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "more "})).unwrap();
|
||||
s.run("file.save", &json!({"ifUnchanged": true})).expect("the file is as we saved it");
|
||||
assert!(!s.dirty);
|
||||
|
||||
write_theirs();
|
||||
s.run("text.insert", &json!({"text": "again "})).unwrap();
|
||||
let err = s.run("file.save", &json!({"ifUnchanged": true})).unwrap_err().to_string();
|
||||
assert!(err.contains("shared.docx") && err.contains("another program"), "{err}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), theirs, "their version stays");
|
||||
assert!(s.dirty);
|
||||
// Removed by another program: not written back either.
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert!(s.run("file.save", &json!({"ifUnchanged": true})).is_err());
|
||||
assert!(!path.exists());
|
||||
|
||||
// The user's own Save writes it, and AutoSave goes on from there.
|
||||
write_theirs();
|
||||
s.run("file.save", &json!({})).unwrap();
|
||||
assert_ne!(std::fs::read(&path).unwrap(), theirs);
|
||||
s.run("text.insert", &json!({"text": "on "})).unwrap();
|
||||
s.run("file.save", &json!({"ifUnchanged": true})).expect("saved here last");
|
||||
// A copy written over the file is the file now: AutoSave goes on from it.
|
||||
s.run("file.save", &json!({"path": p, "copy": true})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "copied "})).unwrap();
|
||||
s.run("file.save", &json!({"ifUnchanged": true})).expect("the copy is the file now");
|
||||
// Without a record of how the file looked, no conditional write; the user's own save writes.
|
||||
s.disk_stamp = None;
|
||||
s.run("text.insert", &json!({"text": "unknown "})).unwrap();
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
assert!(s.run("file.save", &json!({"ifUnchanged": true})).is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
s.run("file.save", &json!({})).unwrap();
|
||||
s.run("file.save", &json!({"ifUnchanged": true})).expect("saved here again");
|
||||
|
||||
// A document opened from the file: the stamp is the one it was read with.
|
||||
let mut o = crate::Session::new(wordcraft_doc::Document::new());
|
||||
o.run("file.open", &json!({"path": p})).unwrap();
|
||||
write_theirs();
|
||||
o.run("text.insert", &json!({"text": "edit "})).unwrap();
|
||||
assert!(o.run("file.save", &json!({"ifUnchanged": true})).is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), theirs);
|
||||
// Renamed after another program changed it: still changed (a rename keeps the file as it is).
|
||||
let mut r = crate::Session::new(wordcraft_doc::Document::new());
|
||||
r.run("file.open", &json!({"path": p})).unwrap();
|
||||
write_theirs();
|
||||
r.run("file.rename", &json!({"name": "renamed"})).unwrap();
|
||||
r.run("text.insert", &json!({"text": "edit "})).unwrap();
|
||||
assert!(r.run("file.save", &json!({"ifUnchanged": true})).is_err());
|
||||
assert_eq!(std::fs::read(dir.join("renamed.docx")).unwrap(), theirs);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #7069 review: the check a save that may write only over an unchanged file makes once its new
|
||||
/// bytes are ready, just before they replace the file; the stamp it returns is the written file's.
|
||||
#[test]
|
||||
fn a_checked_save_writes_only_over_the_file_it_expects() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-7069-checked-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("shared.docx");
|
||||
let theirs = |bytes: &[u8]| {
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
|
||||
std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap();
|
||||
};
|
||||
std::fs::write(&path, b"first").unwrap();
|
||||
let first = crate::io::file_stamp(&path).unwrap();
|
||||
theirs(b"theirs, newer");
|
||||
let doc = wordcraft_doc::Document::from_text("Mine");
|
||||
let opts = crate::io::ExportOptions::default();
|
||||
let err = crate::io::save_path_checked(&path, &doc, None, &opts, Some(first)).unwrap_err();
|
||||
assert!(err.contains("shared.docx") && err.contains("another program"), "{err}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"theirs, newer");
|
||||
let err = crate::io::save_text_path_checked(&path, "mine", Some(first)).unwrap_err();
|
||||
assert!(err.contains("another program"), "{err}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"theirs, newer");
|
||||
|
||||
let now = crate::io::file_stamp(&path).unwrap();
|
||||
let stamp = crate::io::save_path_checked(&path, &doc, None, &opts, Some(now)).unwrap();
|
||||
assert_ne!(std::fs::read(&path).unwrap(), b"theirs, newer");
|
||||
assert_eq!(crate::io::file_stamp(&path), Some(stamp), "the stamp of the file written");
|
||||
let stamp = crate::io::save_text_path_checked(&path, "mine", Some(stamp)).unwrap();
|
||||
assert_eq!(crate::io::file_stamp(&path), Some(stamp));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -54,8 +54,6 @@ to
|
||||
zqzakázané/F
|
||||
";
|
||||
|
||||
pub fn install() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = super::dictionaries_turn();
|
||||
pub fn install() {
|
||||
super::install_dictionary(AFF, DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
@@ -7,31 +7,24 @@ use crate::Session;
|
||||
use crate::cmd::insert::base64_encode;
|
||||
|
||||
#[test]
|
||||
fn format_state_reports_the_east_asian_theme_face_and_per_run_fallbacks() {
|
||||
fn format_state_reports_the_east_asian_theme_face_and_keeps_unresolved_and_mixed_controls() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::ThemeFont;
|
||||
use wordcraft_doc::{Document, Path, StoryRef};
|
||||
|
||||
let first = "漢".len();
|
||||
let second = "漢字".len();
|
||||
let mut doc = Document::from_text("漢字文");
|
||||
let defaults = &mut Arc::make_mut(&mut doc.styles).default_chr;
|
||||
defaults.font = Some("Example Latin".into());
|
||||
defaults.font_ea = Some("Times New Roman".into());
|
||||
let para = doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
para.format(0, second, &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia)).unwrap();
|
||||
para.format(first, second, &|props| props.font = Some("Other Latin".into())).unwrap();
|
||||
let mut doc = Document::from_text("漢字");
|
||||
Arc::make_mut(&mut doc.styles).default_chr.font_ea = Some("Times New Roman".into());
|
||||
doc.para_mut(StoryRef::Body, &Path::top(0))
|
||||
.unwrap()
|
||||
.format(0, "漢".len(), &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia))
|
||||
.unwrap();
|
||||
let mut fallback = Session::new(doc.clone());
|
||||
for (start, end, family) in [(0, first, "Example Latin"), (first, second, "Other Latin")] {
|
||||
fallback.run("select.range", &json!({"anchor": Pos::body(0, start), "focus": Pos::body(0, end)})).unwrap();
|
||||
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], family);
|
||||
}
|
||||
fallback.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, second)})).unwrap();
|
||||
assert!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the unresolved slot uses each run's own font");
|
||||
fallback.run("select.all", &json!({})).unwrap();
|
||||
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Times New Roman");
|
||||
|
||||
doc.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tExample CJK Face\n".to_vec()));
|
||||
let mut s = Session::new(doc);
|
||||
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, second)})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, "漢".len())})).unwrap();
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Example CJK Face");
|
||||
s.run("select.all", &json!({})).unwrap();
|
||||
assert!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the theme face and named face differ");
|
||||
|
||||
@@ -3171,98 +3171,6 @@ fn undoing_a_replacement_adds_no_exception() {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So teh and the ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspacing_an_automatic_i_keeps_the_retyped_word_lowercase() {
|
||||
let mut s = typed("so i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I ");
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i");
|
||||
typ(&mut s, " want this and i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i want this and I ");
|
||||
|
||||
let mut s = typed("so i ");
|
||||
typ(&mut s, "\u{8}\u{8}i want this and i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i want this and I ");
|
||||
|
||||
let s = typed("i \u{8}\u{8}i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "i ");
|
||||
|
||||
let s = typed("so I \u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_i_keeps_pending_first_letter_exception_from_earlier_sentence_capital() {
|
||||
let mut s = typed("hello there. so i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. So I ");
|
||||
// Backspacing back to "hello there. " and retyping "so " still learns "there.".
|
||||
typ(&mut s, "\u{8}\u{8}\u{8}\u{8}\u{8}so ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. so ");
|
||||
assert_eq!(first_letter_list(&s), ["there."]);
|
||||
|
||||
// Restoring lowercase "i" first still leaves the earlier sentence-capital record intact.
|
||||
let mut s = typed("hello there. so i ");
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. So i");
|
||||
typ(&mut s, " \u{8}\u{8}\u{8}\u{8}\u{8}so ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. so ");
|
||||
assert_eq!(first_letter_list(&s), ["there."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_a_lowercase_i_preserves_the_deleted_separators_formatting_for_typing() {
|
||||
let mut s = typed("so ");
|
||||
run(&mut s, "format.bold", json!({"value": true}));
|
||||
typ(&mut s, "i");
|
||||
run(&mut s, "format.bold", json!({"value": false}));
|
||||
typ(&mut s, " ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I ");
|
||||
assert!(bold_at(&s, 3) && !bold_at(&s, 4));
|
||||
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i");
|
||||
assert!(bold_at(&s, 3));
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
|
||||
typ(&mut s, "x");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So ix");
|
||||
assert!(!bold_at(&s, 4), "the deleted separator was plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_caret_away_and_back_drops_the_pending_lowercase_i_restore() {
|
||||
let mut s = typed("so i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I ");
|
||||
run(&mut s, "caret.left", json!({}));
|
||||
run(&mut s, "caret.right", json!({}));
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I", "caret move via command clears pronoun restore");
|
||||
|
||||
let mut s = typed("so i ");
|
||||
let after = s.sel.clone();
|
||||
let start = crate::Selection::caret(Pos { off: 0, ..after.focus.clone() });
|
||||
s.set_selection(start);
|
||||
s.set_selection(after);
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I", "caret move via set_selection clears pronoun restore");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_a_lowercase_i_keeps_its_hyperlink() {
|
||||
let mut s = typed("so ");
|
||||
run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "ab"}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 4}}));
|
||||
typ(&mut s, " i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So a I b");
|
||||
assert_eq!(links(&s), [("a I b".into(), false)]);
|
||||
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So a ib");
|
||||
assert_eq!(links(&s), [("a ib".into(), false)]);
|
||||
typ(&mut s, "x");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So a ixb");
|
||||
assert_eq!(links(&s), [("a ib".into(), false)], "the next letter uses the unlinked separator formatting");
|
||||
}
|
||||
|
||||
/// Checked in Word for Mac: the same rule as First Letter.
|
||||
#[test]
|
||||
fn undoing_an_initial_caps_fix_adds_an_initial_caps_exception() {
|
||||
@@ -3517,53 +3425,6 @@ fn backspace_deletes_selected_columns_and_delete_clears_them() {
|
||||
assert_eq!(table_cells(&s), [["a1", "", "c1"], ["a2", "", "c2"], ["a3", "", "c3"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promote_and_demote_only_change_list_levels_in_selected_cells() {
|
||||
for (command, changed_level) in [("para.promote", 0), ("para.demote", 2)] {
|
||||
let mut s = table_between(0, 1);
|
||||
let num = Arc::make_mut(&mut s.doc.numbering).try_add_list(wordcraft_doc::ListKind::Numbered).unwrap();
|
||||
let story = StoryRef::Body;
|
||||
for path in s.doc.para_paths(story) {
|
||||
s.doc.para_mut(story, &path).unwrap().props.numbering = Some(wordcraft_doc::props::NumRef { num, level: 1 });
|
||||
}
|
||||
|
||||
run(&mut s, "table.selectColumn", json!({}));
|
||||
let range = s.cell_range().unwrap().clone();
|
||||
assert_eq!((range.rows, range.cols), ((0, 2), (1, 1)));
|
||||
let selected = s.sel.clone();
|
||||
run(&mut s, command, json!({}));
|
||||
assert_eq!(s.sel, selected);
|
||||
for path in s.doc.para_paths(story) {
|
||||
let expected = if path.cell().is_some_and(|(_, _, col)| col == 1) { changed_level } else { 1 };
|
||||
let actual = s.doc.para(story, &path).unwrap().props.numbering;
|
||||
assert_eq!(actual, Some(wordcraft_doc::props::NumRef { num, level: expected }), "{command}: {path:?}");
|
||||
}
|
||||
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
for path in s.doc.para_paths(story) {
|
||||
assert_eq!(
|
||||
s.doc.para(story, &path).unwrap().props.numbering,
|
||||
Some(wordcraft_doc::props::NumRef { num, level: 1 }),
|
||||
"undo {command}: {path:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promote_keeps_the_heading_at_the_end_of_a_text_selection_in_scope() {
|
||||
let mut s = typed("First\nSecond\nThird");
|
||||
for index in 0..3 {
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(index, 0)}));
|
||||
run(&mut s, "para.style", json!({"style": "Heading2"}));
|
||||
}
|
||||
assert_eq!(wordcraft_layout::outline::levels(&s.doc), [2, 2, 2]);
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 1), "focus": Pos::body(1, 0)}));
|
||||
assert!(s.cell_range().is_none());
|
||||
run(&mut s, "para.promote", json!({}));
|
||||
assert_eq!(wordcraft_layout::outline::levels(&s.doc), [1, 1, 2]);
|
||||
}
|
||||
|
||||
/// The first top-level table's cells, row by row, one entry per block: a paragraph's text, or
|
||||
/// `<table>` for a nested table.
|
||||
fn cell_blocks(s: &Session) -> Vec<Vec<Vec<String>>> {
|
||||
@@ -5015,81 +4876,3 @@ fn enter_in_a_drop_cap_paragraph_makes_a_normal_paragraph() {
|
||||
assert_eq!(second.drop_cap_font, None, "{position}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8986: Up/Down step along vertical lines and Left/Right cross stacked lines (preserving
|
||||
/// goal distance, collapsing or extending selections, and falling back along the line when
|
||||
/// there is no adjacent line in the flow) for both `tbRl` (`"down"`) and `btLr` (`"up"`).
|
||||
#[test]
|
||||
fn arrow_keys_navigate_vertical_text() {
|
||||
use wordcraft_doc::Path;
|
||||
|
||||
let set = |s: &mut Session, anchor: Pos, focus: Pos| {
|
||||
s.sel = crate::Selection { anchor, focus };
|
||||
s.goal_x = None;
|
||||
};
|
||||
|
||||
// 1. Top-to-bottom (`tbRl`): Down advances, Up retreats; Left goes to next line, Right to previous.
|
||||
let mut doc = typed("abcd\nx\nabcd");
|
||||
run(&mut doc, "layout.textDirection", json!({"value": "down"}));
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(0, 1));
|
||||
run(&mut doc, "caret.down", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 2), "tbRl Down advances along the line");
|
||||
run(&mut doc, "caret.up", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 1), "tbRl Up moves back along the line");
|
||||
|
||||
set(&mut doc, Pos::body(0, 3), Pos::body(0, 3));
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(1, 1), "tbRl Left steps to the shorter next line");
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(2, 3), "tbRl Left keeps goal distance across the short middle line");
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(1, 1), "tbRl Right steps to the previous line");
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 3), "tbRl Right returns to offset 3 with preserved goal distance");
|
||||
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(2, 2));
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert!(doc.sel.is_collapsed() && doc.sel.focus == Pos::body(2, 2), "tbRl Left collapses selection to end");
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(2, 2));
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert!(doc.sel.is_collapsed() && doc.sel.focus == Pos::body(0, 1), "tbRl Right collapses selection to start");
|
||||
|
||||
set(&mut doc, Pos::body(1, 1), Pos::body(1, 1));
|
||||
run(&mut doc, "caret.left", json!({"extend": true}));
|
||||
assert_eq!((&doc.sel.anchor, &doc.sel.focus), (&Pos::body(1, 1), &Pos::body(2, 1)), "extend=true keeps anchor across lines");
|
||||
|
||||
// 2. Bottom-to-top (`btLr`): Up advances, Down retreats; Right goes to next line, Left to previous.
|
||||
run(&mut doc, "layout.textDirection", json!({"value": "up"}));
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(0, 1));
|
||||
run(&mut doc, "caret.up", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 2), "btLr Up advances along the line");
|
||||
run(&mut doc, "caret.down", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 1), "btLr Down moves back along the line");
|
||||
|
||||
set(&mut doc, Pos::body(0, 3), Pos::body(0, 3));
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(1, 1), "btLr Right steps to the shorter next line");
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(2, 3), "btLr Right keeps goal distance across the short middle line");
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(1, 1), "btLr Left steps to the previous line");
|
||||
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(2, 2));
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert!(doc.sel.is_collapsed() && doc.sel.focus == Pos::body(0, 1), "btLr Left collapses selection to start");
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(2, 2));
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert!(doc.sel.is_collapsed() && doc.sel.focus == Pos::body(2, 2), "btLr Right collapses selection to end");
|
||||
|
||||
// 3. Single-line vertical table cell fallback: Left/Right stay inside the cell and step along its text.
|
||||
let mut tbl = s();
|
||||
run(&mut tbl, "insert.table", json!({"rows": 1, "cols": 2}));
|
||||
run(&mut tbl, "text.insert", json!({"text": "abc"}));
|
||||
run(&mut tbl, "table.textDirection", json!({"value": "down"}));
|
||||
let cell0 = |off| Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, 0]), off };
|
||||
set(&mut tbl, cell0(2), cell0(2));
|
||||
run(&mut tbl, "caret.left", json!({}));
|
||||
assert_eq!(tbl.sel.focus, cell0(1), "single-line vertical cell Left falls back backwards along text");
|
||||
run(&mut tbl, "caret.right", json!({}));
|
||||
assert_eq!(tbl.sel.focus, cell0(2), "single-line vertical cell Right falls back forwards along text");
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ mod lookup;
|
||||
mod names;
|
||||
|
||||
use face::{BUNDLED, FontBytes};
|
||||
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, UnscaledMetrics, bundled, bundled_inter};
|
||||
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled, bundled_inter};
|
||||
#[cfg(test)]
|
||||
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -386,13 +386,12 @@ impl FontFace {
|
||||
v.dedup_by_key(|x| x.0);
|
||||
v
|
||||
}
|
||||
/// Unscaled glyph metrics for repeated advance lookups on this face.
|
||||
pub fn unscaled_metrics(&self) -> UnscaledMetrics<'_> {
|
||||
UnscaledMetrics { metrics: self.skrifa().map(|f| f.glyph_metrics(Size::unscaled(), self.location())), fallback: self.upem * 0.5 }
|
||||
}
|
||||
/// Advance width of glyph `gid` in font units.
|
||||
pub fn advance(&self, gid: u32) -> f64 {
|
||||
self.unscaled_metrics().advance(gid)
|
||||
self.skrifa()
|
||||
.and_then(|f| f.glyph_metrics(Size::unscaled(), self.location()).advance_width(GlyphId::new(gid)))
|
||||
.map(|a| a as f64)
|
||||
.unwrap_or(self.upem * 0.5)
|
||||
}
|
||||
/// Glyph id for `c` (0 = .notdef).
|
||||
pub fn glyph_for(&self, c: char) -> u32 {
|
||||
@@ -439,19 +438,6 @@ impl FontFace {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unscaled glyph metrics for a [`FontFace`], built once and reused across glyph lookups.
|
||||
pub struct UnscaledMetrics<'a> {
|
||||
metrics: Option<skrifa::metrics::GlyphMetrics<'a>>,
|
||||
fallback: f64,
|
||||
}
|
||||
|
||||
impl UnscaledMetrics<'_> {
|
||||
/// Advance width of glyph `gid` in font units.
|
||||
pub fn advance(&self, gid: u32) -> f64 {
|
||||
self.metrics.as_ref().and_then(|gm| gm.advance_width(GlyphId::new(gid))).map(|a| a as f64).unwrap_or(self.fallback)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tokens identifying known sans-serif font families by naming convention (#5672).
|
||||
const SANS_TOKENS: &[&str] = &[
|
||||
"sans",
|
||||
|
||||
@@ -483,16 +483,3 @@ fn named_instances_and_collection_members_are_capped() {
|
||||
// (under 0.1 s on a loaded machine) only backs up "read once", with room for a busy CI.
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_calibri_without_carlito_reports_the_drawn_fallback() {
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
db.faces.write().unwrap().retain(|face| !face.family.eq_ignore_ascii_case("Carlito"));
|
||||
assert!(!db.has_family("Carlito"));
|
||||
|
||||
let word = crate::word::core_metric_font("Calibri").unwrap();
|
||||
let resolved = crate::word::resolve_with_db(&db, word, false, false);
|
||||
assert!(!crate::word::metric_compatible(word, &resolved.face.family));
|
||||
assert!(db.has_family(&resolved.face.family), "the notice names the face actually drawn");
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user