Merge upstream/main into control-mcp-delivery-1326-1331

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
vangel76
2026-11-07 11:38:09 +01:00
co-authored by Claude Sonnet 5.5
80 changed files with 4643 additions and 361 deletions
+28
View File
@@ -0,0 +1,28 @@
name: House rules
on:
push:
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
pull_request:
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: house-rules-${{ github.ref }}
cancel-in-progress: true
jobs:
house-rules:
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
with:
rust: true
+57 -4
View File
@@ -1,10 +1,62 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
10. **Keep secrets and personal details out** of the repository, logs and requests.
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
## Licence allowlist
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
- `ISC`
- `MIT`
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
- `CC0-1.0`
- `CC-BY-4.0`
- `CC-BY-SA-4.0`
- `LicenseRef-Public-Domain`
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
<!-- craft-house-rules:end -->
# WordCraft — instructions for agents
WordCraft is a clean-room, open-source, Rust-native word processor targeting Microsoft Word parity — and going further on speed, openness and agent control. It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign).
## Start every session here
1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. `plan/` is gitignored (local only); if it's missing, start from `ROADMAP.md`, `docs/gaps.md` and `docs/roadmap.md` (Current focus).
2. Follow the autonomous operation protocol (`plan/execution-plan.md` §5). Don't stop to ask unless a decision is genuinely the owner's (licensing, publishing, pushing to new remotes, secrets).
Read [`ROADMAP.md`](ROADMAP.md), [`docs/gaps.md`](docs/gaps.md) and [`docs/roadmap.md`](docs/roadmap.md). `plan/` is an optional gitignored notebook. Do not ask for it and do not stop when it is absent.
## Never crash
People trust WordCraft with their writing; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it.
@@ -28,7 +80,7 @@ People trust WordCraft with their writing; a crash loses their work. **This outr
- Never read, disassemble or copy anything inside the Word bundle (file names/listings only). Never commit files produced by Word. Never copy Microsoft wording beyond feature names.
- File formats come from public specs: ECMA-376 / ISO 29500 (OOXML), the published RTF spec, OASIS ODF 1.3. Never copy GPL/LGPL/AGPL code (LibreOffice, AbiWord, pandoc…).
## Architecture (see `plan/architecture.md`)
## Architecture
| Layer | Crate | Job |
|---|---|---|
| L0 | `geom` | units, rects, measurement parsing |
@@ -44,7 +96,6 @@ People trust WordCraft with their writing; a crash loses their work. **This outr
- **Everything is a command.** User-visible behaviour = a `CommandSpec` in `crates/engine/src/cmd/*.rs` (id, label, ribbon location, shortcut, params doc, `enabled`, `run`) + tests. UI-only commands (`ui.*`) live in `crates/ui-egui/src/lib.rs`. The ribbon, shortcuts, command search, CLI, control channel and MCP all dispatch by id. Programmatic calls never open dialogs.
- **Parity is measured:** `crates/engine/src/catalog.rs` lists Word's ribbon/menu features with command ids. `cargo xtask parity` writes `docs/parity-checklist.md`; a test enforces a floor that only rises. Implement missing ids to raise it.
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. The UI is thin and reads `Session` state; colours come from `theme::Tokens`.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math). A crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
## Quality gates
@@ -85,3 +136,5 @@ Progress docs: `ROADMAP.md` (stage, headline numbers, progress log), `docs/targe
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
+1 -71
View File
@@ -1,71 +1 @@
# WordCraft — instructions for agents
WordCraft is a clean-room, open-source, Rust-native word processor targeting Microsoft Word parity — and going further on speed, openness and agent control. It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign).
## Start every session here
1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. `plan/` is gitignored (local only); if it's missing, start from `ROADMAP.md`, `docs/gaps.md` and `docs/roadmap.md` (Current focus).
2. Follow the autonomous operation protocol (`plan/execution-plan.md` §5). Don't stop to ask unless a decision is genuinely the owner's (licensing, publishing, pushing to new remotes, secrets).
## Never crash
People trust WordCraft with their writing; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it.
- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`).
- **Errors are `Result<T, E>`** through the crate's error type and `?`. An unfinished feature returns an error or is disabled; it never panics.
- **Input-derived numbers are hostile** (files, commands, MCP/control params): `get()` instead of `[i]`, slice strings only at char boundaries, checked/saturating arithmetic, clamp sizes, cap allocations, bound recursion.
- **Last-resort guard:** `Session::run` turns an escaped panic into an error and restores the document. It's a safety net, not a licence.
- **Prove it:** every crash fix lands with a regression test. `crates/engine/src/tests.rs::hostile_params_never_panic` runs every command with junk params — keep it green.
- Production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; new crates start with it and add `[lints]` with `workspace = true` to their `Cargo.toml`. Tests may `unwrap` (`clippy.toml`).
## Assets: absolutely no Microsoft (or Adobe/Avid/Autodesk) iconography or images
**This rule is non-negotiable.** Breaking it is the worst mistake you can make in this repo.
- Never copy, trace, screenshot-crop or recreate icons, images, templates, themes, clip art, fonts, cursors, sounds or any other asset from Microsoft Word/Office or any Microsoft, Adobe, Avid or Autodesk product. Not even "temporarily".
- Every asset must be **original** (drawn in code — prefer this: `crates/ui-egui/src/icons.rs`), **public domain / CC0**, **OSI open source**, or **Creative Commons that allows redistribution**, or licensed open source by a contributor who made it.
- **Every asset file has a row in [`ATTRIBUTION.md`](ATTRIBUTION.md)** (author, source, licence). `cargo xtask assets` (part of `cargo xtask ci`) fails otherwise. Add the row in the same commit as the file.
- Fonts: new font files go to [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts), never this repo; it's an optional build input (`CRAFT_FONTS_DIR`). Spelling word lists and hyphenation patterns live in [`storytold/craft-i18n`](https://github.com/storytold/craft-i18n) `language-data/`, never this repo; they are embedded from `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`, which CI checks out). Without it the app builds, but English spelling falls back to an installed Hunspell English or the built-in Moby word list (with no American/British variant table) and pattern hyphenation is off (Bulgarian, Turkish and Russian still hyphenate by rule), so proofing tests need it. Documents asking for proprietary fonts (Calibri, Aptos, Cambria…) are rendered with installed system fonts or metric-compatible open substitutes (`crates/fonts/src/word.rs`) — never bundle proprietary fonts.
- Templates, sample documents and themes are our own text and colours (`crates/engine/src/sample.rs`, `cmd/design.rs`). Demo images are public domain, with sources recorded.
## Clean room
- Microsoft Word is installed on the dev machine and may be **observed** black-box: run it, use its UI with synthetic documents, take screenshots **of its window only** (by window id — the machine runs other work; never capture the whole desktop) stored only under `plan/word/screenshots/` (gitignored, never committed).
- Never read, disassemble or copy anything inside the Word bundle (file names/listings only). Never commit files produced by Word. Never copy Microsoft wording beyond feature names.
- File formats come from public specs: ECMA-376 / ISO 29500 (OOXML), the published RTF spec, OASIS ODF 1.3. Never copy GPL/LGPL/AGPL code (LibreOffice, AbiWord, pandoc…).
## Architecture (see `plan/architecture.md`)
| Layer | Crate | Job |
|---|---|---|
| L0 | `geom` | units, rects, measurement parsing |
| L1 | `doc`, `fonts` | document model + edit primitives; font DB, shaping, Word font substitution |
| L2 | `layout`, `docx`, `formats` | line breaking, pagination, tables, headers/footers, hit testing; OOXML I/O; TXT/MD/HTML/RTF/ODT |
| L3 | `render`, `pdf` | vello_cpu rasteriser; krilla PDF |
| L4 | `engine` | Session, undo, **command registry**, Word feature catalog, samples, I/O dispatch |
| L5 | `mcp` | MCP server (headless or bridged to the app) |
| L6 | `ui-egui` | Word-style egui front end (swappable) |
| apps | `apps/wordcraft`, `apps/wordcraft-cli`, `apps/wordcraft-web` | binaries |
| external | `craft-proof` (craft-libs, used as `wordcraft-proof`, sits at L1) | proofing: spelling, grammar, hyphenation; its word lists and patterns are craft-i18n's `language-data/` (`CRAFT_I18N_DIR`) |
- **Everything is a command.** User-visible behaviour = a `CommandSpec` in `crates/engine/src/cmd/*.rs` (id, label, ribbon location, shortcut, params doc, `enabled`, `run`) + tests. UI-only commands (`ui.*`) live in `crates/ui-egui/src/lib.rs`. The ribbon, shortcuts, command search, CLI, control channel and MCP all dispatch by id. Programmatic calls never open dialogs.
- **Parity is measured:** `crates/engine/src/catalog.rs` lists Word's ribbon/menu features with command ids. `cargo xtask parity` writes `docs/parity-checklist.md`; a test enforces a floor that only rises. Implement missing ids to raise it.
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. The UI is thin and reads `Session` state; colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
## Quality gates
Before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every arc of work that builds, with a task id in the message (`M2.1: line spacing dialog`).
## Typing behaves like Word
Typing, Enter, Backspace, Tab, lists, AutoCorrect and AutoFormat follow Word's observed behaviour in [`docs/typing-parity.md`](docs/typing-parity.md), pinned by `crates/engine/src/tests/typing.rs` (keys go through the same commands as the keyboard). Change behaviour, doc and tests together; a typing fix lands with a test there. Compare headlessly (`ui_shot`); don't drive GUIs with keystrokes on the shared machine.
## Running and looking at the app
- `cargo run --release -p wordcraft -- --sample --control 7981` (sample document + control channel).
- Drive it with JSON lines on `127.0.0.1:7981`, each with the window's key from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), e.g. `{"id":1,"key":"…","method":"engine.execute","params":{"command":"text.insert","params":{"text":"Hello"}}}` then `{"id":2,"key":"…","method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`; docs: `docs/control-protocol.md` (Keys).
- **Headless window screenshots** (no focus stealing, works with a locked screen): `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl` (see the example's header).
- **For UI work, look at the result** (screenshot, read the PNG) and compare with Word side by side.
- CLI: `wordcraft-cli convert in.docx out.pdf`, `wordcraft-cli run --template sample --cmd 'select.text={"text":"Studio"}' --cmd format.bold --save out.docx`, `wordcraft-cli commands`, `wordcraft-cli parity`.
- MCP: `wordcraft-cli mcp` (headless) or `wordcraft-cli mcp --connect 127.0.0.1:7981` (drives the running app). See `docs/mcp.md`.
- Shell gotcha: `mv`/`cp` may be aliased interactive — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk).
## Roadmap
Progress docs: `ROADMAP.md` (stage, headline numbers, progress log), `docs/target-app-parity.md` (the assessment), `docs/gaps.md` (ranked work list), `docs/roadmap.md` (milestones, Current focus), `docs/architecture.md`, and the parity checklists `docs/file-format-parity.md`, `docs/layout-parity.md`, `docs/typing-parity.md`, `docs/ui-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. When work lands, update the gap, the parity doc and the progress log, and bump each touched doc's status line and revision history.
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
@AGENTS.md
Generated
+4 -1
View File
@@ -1090,9 +1090,10 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=a3e0b5a9440d18f19422a9dca13516747b7d3181#a3e0b5a9440d18f19422a9dca13516747b7d3181"
dependencies = [
"craft-winprint-gdi",
"log",
"miniz_oxide 0.9.1",
"roxmltree",
"tempfile",
@@ -6814,7 +6815,9 @@ dependencies = [
"open",
"pollster 1.0.1",
"rfd",
"serde",
"serde_json",
"tempfile",
"windows",
"winit",
"winresource",
+46 -1
View File
File diff suppressed because one or more lines are too long
+5 -1
View File
@@ -22,6 +22,8 @@ wordcraft-control-key = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "wayland", "x11", "links"] }
egui = { workspace = true }
serde_json = { workspace = true }
serde = { workspace = true }
tempfile = "3"
log = { workspace = true }
chrono = { workspace = true }
@@ -77,7 +79,9 @@ windows = { version = "0.62", features = ["UI_ViewManagement", "System_UserProfi
clipboard-win = { version = "5.4", features = ["std"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
# Pinned apart from craft-ui, which doesn't depend on it: `printer_queues`, the printer list that
# asks no driver (#5710, storytold/craft-libs#618), and `submit_cancellable` (storytold/craft-libs#622).
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a3e0b5a9440d18f19422a9dca13516747b7d3181" }
rfd = { workspace = true }
# Waits for an `rfd::AsyncFileDialog` on a background thread (the dialogs don't block the UI, #94);
# rfd itself already depends on it.
+5
View File
@@ -337,6 +337,7 @@ fn services(file_dialog: file_dialogs::Hook, ctx: &egui::Context) -> Services {
file_dialog: Some(file_dialog),
printers: Some(print::discover()),
print_native: Some(print::submit()),
cancel_print: Some(print::cancel()),
clipboard_picture: Some(Box::new(clipboard::picture)),
make_default_app: default_apps::hook(),
// Personal templates live in `Templates` in the settings folder (#2852), made on first save.
@@ -439,6 +440,10 @@ fn open_non_unicode(app: &mut WordApp, path: &std::path::Path) {
/// geometry, opens requested documents or the Start screen, starts the control server when
/// asked, and runs the eframe event loop.
fn main() -> eframe::Result {
#[cfg(windows)]
if let Some(code) = print::isolated::helper_mode() {
std::process::exit(code);
}
// Windows: the update helper is a copy of this program started with `--finish-update`.
#[cfg(windows)]
if let Some(result) = craft_update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
+116 -20
View File
@@ -1,13 +1,21 @@
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
#[cfg(any(windows, test))]
pub(crate) mod isolated;
use wordcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
/// Returns a discovery callback that enumerates spooler printers on a named worker thread and
/// sends the list through a channel, keeping spooler calls off the UI thread.
///
/// The Print panel needs only names and the default, so the list comes from
/// `craft_print::printer_queues`, which asks no printer driver anything: on Windows a networked
/// printer in power save can hold a driver's capability query for a long time, and the list must
/// not wait on it (#5710). Submission still checks the job's options with the driver.
pub fn discover() -> Discover {
Box::new(|| {
let (sender, receiver) = std::sync::mpsc::channel();
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
let printers = craft_print::printers()
let printers = craft_print::printer_queues()
.into_iter()
.map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })
.collect();
@@ -17,22 +25,59 @@ pub fn discover() -> Discover {
})
}
/// A submission worker and how to stop its job: `true` when it will never be sent, `false` when
/// it was already being sent.
struct Job {
worker: std::thread::JoinHandle<()>,
cancel: Box<dyn Fn() -> bool + Send>,
// Acknowledged helper cancellation permits joining it to reap the process and its input PDF.
isolated: bool,
}
// Keep submission workers reachable until normal app shutdown; dropping a JoinHandle would
// let process exit end an in-process Windows job or the CUPS hand-off before the spooler has it.
static JOBS: std::sync::Mutex<Vec<std::thread::JoinHandle<()>>> = std::sync::Mutex::new(Vec::new());
static JOBS: std::sync::Mutex<Vec<Job>> = std::sync::Mutex::new(Vec::new());
fn jobs() -> std::sync::MutexGuard<'static, Vec<Job>> {
JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Waits for the jobs already being sent, so the spooler has them before the process exits. A
/// job still waiting (on a sleeping printer's driver, say: #5710) is cancelled instead, so it is
/// never sent and quitting doesn't wait on the driver.
pub fn finish_pending_jobs() {
let workers = std::mem::take(&mut *JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner));
for worker in workers {
if worker.join().is_err() {
let pending = std::mem::take(&mut *jobs());
// Cancel them all first: a job left waiting while another is joined could start sending.
let finishing: Vec<_> = pending
.into_iter()
.filter(|job| {
let cancelled = (job.cancel)();
job.isolated || !cancelled
})
.collect();
for job in finishing {
if job.worker.join().is_err() {
log::error!("the print worker stopped unexpectedly during shutdown");
}
}
}
/// The Print page's Cancel: stops the job being submitted (the Print page submits one at a
/// time, the latest) unless it has started reaching the spooler. `true` when it will never be
/// sent. A job that has finished sending answers `false`, so its receipt is still shown.
pub fn cancel() -> Box<dyn Fn() -> bool> {
Box::new(|| jobs().last().is_none_or(|job| (job.cancel)()))
}
/// Submit off the UI thread, isolating Windows drivers while retaining CUPS token cancellation.
pub fn submit() -> Submit {
Box::new(|bytes, settings: Settings, collate, options| {
let (sender, receiver) = std::sync::mpsc::channel();
#[cfg(not(windows))]
let cancel = craft_print::Cancel::new();
#[cfg(windows)]
let cancel = isolated::Submission::new();
let token = cancel.clone();
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
let job = craft_print::Job {
printer: Some(settings.printer),
@@ -48,12 +93,16 @@ pub fn submit() -> Submit {
title: "WordCraft document".into(),
options,
};
let _ = sender.send(craft_print::submit(&bytes, &job).map_err(|error| error.to_string()));
#[cfg(not(windows))]
let sent = craft_print::submit_cancellable(&bytes, &job, &mut |_, _| {}, &token).map_err(|error| error.to_string());
#[cfg(windows)]
let sent = token.submit(&bytes, &job);
let _ = sender.send(sent);
});
if let Ok(worker) = worker {
let mut jobs = JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
jobs.retain(|job| !job.is_finished());
jobs.push(worker);
let mut jobs = jobs();
jobs.retain(|job| !job.worker.is_finished());
jobs.push(Job { worker, cancel: Box::new(move || cancel.cancel()), isolated: cfg!(windows) });
}
receiver
})
@@ -62,20 +111,67 @@ pub fn submit() -> Submit {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shutdown_waits_for_pending_submission_workers() {
/// A worker that waits until released, then reports that it finished.
fn worker() -> (std::thread::JoinHandle<()>, std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>) {
let (release, wait) = std::sync::mpsc::channel();
let (completed, completion) = std::sync::mpsc::channel();
let worker = std::thread::spawn(move || {
wait.recv().unwrap();
completed.send(()).unwrap();
let _ = wait.recv();
let _ = completed.send(());
});
JOBS.lock().unwrap().push(worker);
let shutdown = std::thread::spawn(finish_pending_jobs);
assert!(completion.try_recv().is_err(), "the print worker is still pending");
release.send(()).unwrap();
shutdown.join().unwrap();
completion.recv().unwrap();
assert!(JOBS.lock().unwrap().is_empty(), "workers were joined before shutdown returned");
(worker, release, completion)
}
/// A cancel action that records when it was asked and answers `stops`.
fn asked(stops: bool) -> (Box<dyn Fn() -> bool + Send>, std::sync::Arc<std::sync::atomic::AtomicBool>) {
let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let set = flag.clone();
let cancel = Box::new(move || {
set.store(true, std::sync::atomic::Ordering::SeqCst);
stops
});
(cancel, flag)
}
/// Shutdown waits for a job already being sent, so the spooler has it before the process
/// exits, but not for one still waiting on a driver (a sleeping printer, #5710): that one is
/// cancelled, so it is never sent, and quitting doesn't hang on it. Every job is cancelled
/// before any is waited for, so a waiting job can't start sending meanwhile. The Print page's
/// Cancel asks only the latest job. One test, because JOBS is global.
#[test]
fn shutdown_waits_for_jobs_being_sent_and_cancels_the_rest() {
let (sending, release_sending, sent) = worker();
let (stuck, release_stuck, _) = worker();
let (stop_sending, sending_asked) = asked(false);
let (stop_stuck, cancelled) = asked(true);
// The job being sent comes first, so a one-at-a-time shutdown would join it before
// cancelling the waiting one.
*JOBS.lock().unwrap() =
vec![Job { worker: sending, cancel: stop_sending, isolated: false }, Job { worker: stuck, cancel: stop_stuck, isolated: false }];
// Cancel from the Print page asks the latest job only.
assert!(cancel()(), "the latest job was still waiting: never sent");
assert!(!sending_asked.load(std::sync::atomic::Ordering::SeqCst), "an earlier job isn't the one being submitted");
cancelled.store(false, std::sync::atomic::Ordering::SeqCst);
let (finished, shutdown) = std::sync::mpsc::channel();
std::thread::spawn(move || {
finish_pending_jobs();
let _ = finished.send(());
});
let wait = std::time::Duration::from_millis(200);
assert!(shutdown.recv_timeout(wait).is_err(), "shutdown waits for the job being sent");
assert!(cancelled.load(std::sync::atomic::Ordering::SeqCst), "the waiting job was cancelled before the wait");
release_sending.send(()).unwrap();
assert!(shutdown.recv_timeout(std::time::Duration::from_secs(10)).is_ok(), "shutdown doesn't wait for the stuck job");
sent.recv().unwrap();
assert!(JOBS.lock().unwrap().is_empty(), "shutdown took every job");
// A job that has already been sent answers false, so the Print page keeps its receipt.
let (done, release_done, finished) = worker();
release_done.send(()).unwrap();
finished.recv().unwrap();
*JOBS.lock().unwrap() = vec![Job { worker: done, cancel: Box::new(|| false), isolated: false }];
assert!(!cancel()(), "a sent job isn't reported as cancelled");
JOBS.lock().unwrap().clear();
// The stuck worker was left behind without blocking shutdown; let it end.
release_stuck.send(()).unwrap();
}
}
+592
View File
@@ -0,0 +1,592 @@
//! One Windows driver submission per process: a cancelled driver cannot retain another
//! job's provider lock. The child acknowledges its Cancel token before it exits.
use std::{
io::{BufRead, BufReader, Read, Write},
path::Path,
process::{Child, ChildStdin, Command, Stdio},
sync::{Arc, Condvar, Mutex},
time::Duration,
};
use serde::{Deserialize, Serialize};
#[cfg(windows)]
const FLAG: &str = "--wordcraft-print-worker";
const PREFIX: &str = "WORDCRAFT_PRINT:";
const MAX_MESSAGE: u64 = 64 * 1024;
const MAX_PDF: u64 = 512 * 1024 * 1024;
const CANCELLED: &str = "the print job was cancelled before anything was sent to the printer";
#[derive(Serialize, Deserialize)]
enum Duplex {
Off,
LongEdge,
ShortEdge,
}
#[derive(Serialize, Deserialize)]
struct Request {
printer: Option<String>,
copies: u32,
collate: bool,
duplex: Option<Duplex>,
grayscale: bool,
shrink: bool,
title: String,
options: Vec<(String, String)>,
}
impl Request {
/// Preserve all spooler options in a platform-independent wire representation.
fn from_job(job: &craft_print::Job) -> Self {
Self {
printer: job.printer.clone(),
copies: job.copies,
collate: job.collate,
duplex: job.duplex.map(|d| match d {
craft_print::Duplex::Off => Duplex::Off,
craft_print::Duplex::LongEdge => Duplex::LongEdge,
craft_print::Duplex::ShortEdge => Duplex::ShortEdge,
}),
grayscale: job.grayscale,
shrink: job.scaling == craft_print::Scaling::ShrinkToFit,
title: job.title.clone(),
options: job.options.clone(),
}
}
/// Restore the job without substituting printer defaults or changing copy semantics.
fn job(self) -> craft_print::Job {
craft_print::Job {
printer: self.printer,
copies: self.copies,
collate: self.collate,
duplex: self.duplex.map(|d| match d {
Duplex::Off => craft_print::Duplex::Off,
Duplex::LongEdge => craft_print::Duplex::LongEdge,
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
}),
grayscale: self.grayscale,
scaling: if self.shrink { craft_print::Scaling::ShrinkToFit } else { craft_print::Scaling::Exact },
title: self.title,
options: self.options,
}
}
}
#[derive(Serialize, Deserialize)]
enum Event {
Ready,
Cancelled,
Sending,
Done(Result<String, String>),
}
enum State {
Starting,
Waking(Arc<Mutex<Child>>),
Running(ChildStdin),
Sending(ChildStdin),
Cancelled,
Finished,
}
#[derive(Clone)]
pub(crate) struct Submission(Arc<(Mutex<State>, Condvar)>);
impl Submission {
/// Create one submission whose driver cannot run until the parent grants startup.
pub(crate) fn new() -> Self {
Self(Arc::new((Mutex::new(State::Starting), Condvar::new())))
}
/// Recover the lifecycle state after poisoning without invoking another driver call.
fn state(&self) -> std::sync::MutexGuard<'_, State> {
self.0.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Only an acknowledgement of the child's token can cancel a running helper. A timeout
/// is a refusal, never permission to kill a process that may already be sending.
pub(crate) fn cancel(&self) -> bool {
let mut state = self.state();
match &mut *state {
State::Starting => {
*state = State::Cancelled;
return true;
}
State::Waking(child) => {
let _ = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner).kill();
*state = State::Cancelled;
return true;
}
State::Cancelled => return true,
State::Finished | State::Sending(_) => return false,
State::Running(input) => {
if input.write_all(b"cancel\n").and_then(|_| input.flush()).is_err() {
return false;
}
}
}
let (state, _) = self
.0
.1
.wait_timeout_while(state, Duration::from_secs(1), |s| matches!(s, State::Running(_)))
.unwrap_or_else(std::sync::PoisonError::into_inner);
matches!(*state, State::Cancelled)
}
#[cfg(windows)]
/// Submit through this executable's private helper mode and await its final receipt.
pub(crate) fn submit(&self, pdf: &[u8], job: &craft_print::Job) -> Result<String, String> {
self.submit_with(pdf, job, |directory| {
let mut command = Command::new(std::env::current_exe()?);
command.arg(FLAG).arg(directory);
Ok(command)
})
}
/// Publish a terminal state on every result, waking a cancellation caller awaiting an ack.
fn submit_with(&self, pdf: &[u8], job: &craft_print::Job, command: impl FnOnce(&Path) -> std::io::Result<Command>) -> Result<String, String> {
let result = self.run(pdf, job, command);
let mut state = self.state();
if !matches!(*state, State::Cancelled) {
*state = State::Finished;
}
self.0.1.notify_all();
if matches!(*state, State::Cancelled) { Err(CANCELLED.into()) } else { result }
}
/// Own the private inputs and child until receipt, acknowledged cancellation or failure.
fn run(&self, pdf: &[u8], job: &craft_print::Job, command: impl FnOnce(&Path) -> std::io::Result<Command>) -> Result<String, String> {
if matches!(*self.state(), State::Cancelled) {
return Err(CANCELLED.into());
}
if pdf.len() as u64 > MAX_PDF {
return Err("the print PDF exceeds the 512 MiB helper limit".into());
}
let request = serde_json::to_vec(&Request::from_job(job)).map_err(error)?;
if request.len() as u64 > MAX_MESSAGE {
return Err("the print settings exceed the helper message limit".into());
}
let directory = tempfile::tempdir().map_err(error)?;
std::fs::write(directory.path().join("job.json"), request).map_err(error)?;
std::fs::write(directory.path().join("input.pdf"), pdf).map_err(error)?;
let child =
command(directory.path()).map_err(error)?.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().map_err(error)?;
let child = Arc::new(Mutex::new(child));
let outcome = (|| {
let (input, output) = {
let mut process = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
(process.stdin.take().ok_or("print helper has no input pipe")?, process.stdout.take().ok_or("print helper has no output pipe")?)
};
{
let mut state = self.state();
if matches!(*state, State::Cancelled) {
return Err(CANCELLED.into());
}
*state = State::Waking(child.clone());
}
let mut output = BufReader::new(output);
loop {
let message = line(&mut output)?.ok_or("the print helper stopped before it was ready")?;
let Some((_, json)) = message.split_once(PREFIX) else { continue };
if !matches!(serde_json::from_str::<Event>(json).map_err(error)?, Event::Ready) {
return Err("the print helper did not acknowledge startup".into());
}
break;
}
{
let mut state = self.state();
if matches!(*state, State::Cancelled) {
return Err(CANCELLED.into());
}
*state = State::Running(input);
if let State::Running(input) = &mut *state {
input.write_all(b"start\n").and_then(|_| input.flush()).map_err(error)?;
}
}
while let Some(line) = line(&mut output)? {
let Some((_, json)) = line.split_once(PREFIX) else { continue };
match serde_json::from_str::<Event>(json).map_err(error)? {
Event::Ready => return Err("the print helper repeated its startup acknowledgement".into()),
Event::Cancelled => {
*self.state() = State::Cancelled;
self.0.1.notify_all();
return Err(CANCELLED.into());
}
Event::Sending => {
let mut state = self.state();
let previous = std::mem::replace(&mut *state, State::Finished);
*state = match previous {
State::Running(input) | State::Sending(input) => State::Sending(input),
other => other,
};
self.0.1.notify_all();
}
Event::Done(result) => return result,
}
}
Err("the print helper stopped without a receipt".into())
})();
// A cancelled child has acknowledged that it cannot send. Other outcomes are terminal
// receipts or a broken protocol/pipe; reap the process and its private input files.
if outcome.is_err() {
let _ = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner).kill();
}
let status = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner).wait().map_err(error)?;
if outcome.is_ok() && !status.success() {
return Err("the print helper failed after its receipt".into());
}
outcome
}
}
/// Keep helper transport failures distinct from a printer's own error message.
fn error(error: impl std::fmt::Display) -> String {
format!("print helper: {error}")
}
/// Read at most one byte beyond the cap so oversized files fail without unbounded allocation.
fn bounded(mut input: impl Read, limit: u64) -> Result<Vec<u8>, String> {
let mut bytes = Vec::new();
input.by_ref().take(limit.saturating_add(1)).read_to_end(&mut bytes).map_err(error)?;
if bytes.len() as u64 > limit { Err("print helper input exceeds its limit".into()) } else { Ok(bytes) }
}
/// Read one bounded UTF-8 protocol record, distinguishing EOF from an oversized message.
fn line(input: &mut impl BufRead) -> Result<Option<String>, String> {
let mut bytes = Vec::new();
input.take(MAX_MESSAGE + 1).read_until(b'\n', &mut bytes).map_err(error)?;
if bytes.len() as u64 > MAX_MESSAGE {
return Err("print helper message exceeds its limit".into());
}
if bytes.is_empty() { Ok(None) } else { String::from_utf8(bytes).map(|s| Some(s.trim_end().to_owned())).map_err(error) }
}
/// Serialize complete events under stdout's lock so the driver and listener cannot interleave.
fn emit(event: &Event) -> Result<(), String> {
let mut output = std::io::stdout().lock();
write!(output, "{PREFIX}").map_err(error)?;
serde_json::to_writer(&mut output, event).map_err(error)?;
writeln!(output).and_then(|_| output.flush()).map_err(error)
}
/// Remove both plaintext inputs even when one fails; already-removed inputs count as success.
fn remove_inputs(directory: &Path) -> Result<(), String> {
let mut first_error = None;
for name in ["job.json", "input.pdf"] {
if let Err(failure) = std::fs::remove_file(directory.join(name))
&& failure.kind() != std::io::ErrorKind::NotFound
{
first_error.get_or_insert_with(|| error(format!("could not remove {name}: {failure}")));
}
}
first_error.map_or(Ok(()), Err)
}
/// Load and erase the private inputs before driver work, while an independent listener can cancel.
fn helper(
directory: &Path,
cancel_request: impl Fn(&craft_print::Cancel) -> bool + Send + 'static,
submit: impl FnOnce(&[u8], &craft_print::Job, &craft_print::Cancel) -> Result<String, String>,
) -> Result<(), String> {
let mut input = BufReader::new(std::io::stdin());
emit(&Event::Ready)?;
if line(&mut input)?.as_deref() != Some("start") {
return Err("print helper requires a start acknowledgement".into());
}
let cancel = craft_print::Cancel::new();
let listener = cancel.clone();
std::thread::Builder::new()
.name("print-cancel".into())
.spawn(move || {
loop {
match line(&mut input) {
Ok(Some(command)) if command == "cancel" => {
if cancel_request(&listener) {
let _ = emit(&Event::Cancelled);
std::process::exit(0);
}
if emit(&Event::Sending).is_err() {
break;
}
}
_ => break,
}
}
// If the parent disappears, never leave a waiting driver process behind. Sending
// jobs finish normally so the OS gets their pages even if the UI has gone away.
if cancel_request(&listener) {
std::process::exit(0);
}
})
.map_err(error)?;
let request: Request =
serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_MESSAGE)?).map_err(error)?;
let pdf = bounded(std::fs::File::open(directory.join("input.pdf")).map_err(error)?, MAX_PDF)?;
remove_inputs(directory)?;
let result = submit(&pdf, &request.job(), &cancel);
emit(&Event::Done(result))
}
#[cfg(windows)]
/// Handle only the private first-argument flag, before logging or GUI initialization.
pub(crate) fn helper_mode() -> Option<i32> {
let mut args = std::env::args_os().skip(1);
if args.next().as_deref() != Some(std::ffi::OsStr::new(FLAG)) {
return None;
}
let result = args.next().ok_or_else(|| "print helper directory missing".to_owned()).and_then(|dir| {
helper(Path::new(&dir), craft_print::Cancel::cancel, |pdf, job, cancel| {
craft_print::submit_cancellable(pdf, job, &mut |_, _| {}, cancel).map_err(error)
})
});
if let Err(message) = &result {
let _ = emit(&Event::Done(Err(message.clone())));
}
Some(i32::from(result.is_err()))
}
#[cfg(test)]
mod tests {
use super::*;
/// A real test child exercises production pipes, token handling and process cleanup.
#[test]
#[ignore = "launched by the process protocol tests"]
fn helper_process() {
let Some(directory) = std::env::var_os("WORDCRAFT_TEST_PRINT_DIR") else { return };
if std::env::var("WORDCRAFT_TEST_PRINT_MODE").as_deref() == Ok("waking") {
std::fs::write(Path::new(&directory).join("waking"), b"starting").unwrap();
loop {
std::thread::park();
}
}
let result = helper(
Path::new(&directory),
|token| {
if std::env::var("WORDCRAFT_TEST_PRINT_MODE").as_deref() == Ok("sending") { false } else { token.cancel() }
},
|pdf, job, _token| {
assert_eq!(pdf, b"synthetic PDF");
assert_eq!(job.printer.as_deref(), Some("test queue"));
match std::env::var("WORDCRAFT_TEST_PRINT_MODE").as_deref() {
Ok("held") => {
let _provider = Mutex::new(());
let _held = _provider.lock().unwrap();
std::fs::write(Path::new(&directory).join("held"), b"driver entered").unwrap();
loop {
std::thread::park();
}
}
Ok("crash") => std::process::exit(7),
Ok("sending") => {
std::fs::write(Path::new(&directory).join("sending"), b"sending").unwrap();
while !Path::new(&directory).join("release").exists() {
std::thread::sleep(Duration::from_millis(5));
}
Ok("spooled synthetic job".into())
}
_ => Ok("spooled synthetic job".into()),
}
},
);
std::process::exit(i32::from(result.is_err()));
}
/// Launch just the ignored helper entry, without invoking printer hardware.
fn command(directory: &Path, mode: &str) -> std::io::Result<Command> {
let mut command = Command::new(std::env::current_exe()?);
let name = module_path!().split_once("::").map_or(module_path!(), |(_, name)| name);
command.args(["--ignored", "--exact", &format!("{name}::helper_process"), "--nocapture"]);
command.env("WORDCRAFT_TEST_PRINT_DIR", directory).env("WORDCRAFT_TEST_PRINT_MODE", mode);
Ok(command)
}
/// Give the child a literal printer identity to verify transport.
fn job() -> craft_print::Job {
craft_print::Job { printer: Some("test queue".into()), ..Default::default() }
}
#[test]
/// Cancelling before submission cannot launch a driver process.
fn cancelled_start_never_launches_a_helper() {
let submission = Submission::new();
assert!(submission.cancel());
let result = submission.submit_with(b"synthetic PDF", &job(), |_| Err(std::io::Error::other("must not launch")));
assert_eq!(result, Err(CANCELLED.into()));
}
#[test]
/// A cancellation during creation withholds the start grant and removes private inputs.
fn cancellation_during_startup_never_starts_the_driver() {
let submission = Submission::new();
let worker = submission.clone();
let (started, starting) = std::sync::mpsc::channel();
let (release, wait) = std::sync::mpsc::channel();
let running = std::thread::spawn(move || {
worker.submit_with(b"synthetic PDF", &job(), |directory| {
started.send(directory.to_path_buf()).unwrap();
wait.recv().unwrap();
command(directory, "held")
})
});
let directory = starting.recv_timeout(Duration::from_secs(10)).unwrap();
assert!(submission.cancel());
release.send(()).unwrap();
assert_eq!(running.join().unwrap(), Err(CANCELLED.into()));
assert!(!directory.exists(), "startup cancellation reaps the child and removes its inputs");
}
#[test]
/// A hung startup has no permission to send and can be killed without a token ack.
fn an_unresponsive_starting_process_can_be_stopped_without_an_acknowledgement() {
let submission = Submission::new();
let worker = submission.clone();
let (path_tx, path_rx) = std::sync::mpsc::channel();
let running = std::thread::spawn(move || {
worker.submit_with(b"synthetic PDF", &job(), |dir| {
path_tx.send(dir.to_path_buf()).unwrap();
command(dir, "waking")
})
});
let directory = path_rx.recv_timeout(Duration::from_secs(10)).unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while !directory.join("waking").exists() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(directory.join("waking").exists());
assert!(submission.cancel(), "a process without a start grant cannot send anything");
assert_eq!(running.join().unwrap(), Err(CANCELLED.into()));
assert!(!directory.exists());
}
#[test]
/// Job transport preserves every explicit setting, including Unicode and duplex direction.
fn job_options_survive_the_process_boundary() {
let expected = craft_print::Job {
printer: Some("Office λ".into()),
copies: 3,
collate: false,
duplex: Some(craft_print::Duplex::ShortEdge),
grayscale: true,
scaling: craft_print::Scaling::ShrinkToFit,
title: "A document".into(),
options: vec![("media".into(), "iso_a4_210x297mm".into())],
};
let bytes = serde_json::to_vec(&Request::from_job(&expected)).unwrap();
let received: Request = serde_json::from_slice(&bytes).unwrap();
assert_eq!(received.job(), expected);
}
#[test]
/// Retry succeeds immediately after cancellation, before joining the old worker.
fn cancelled_driver_does_not_block_the_next_process() {
let submission = Submission::new();
let worker = submission.clone();
let (path_tx, path_rx) = std::sync::mpsc::channel();
let running = std::thread::spawn(move || {
worker.submit_with(b"synthetic PDF", &job(), |dir| {
path_tx.send(dir.to_path_buf()).unwrap();
command(dir, "held")
})
});
let directory = path_rx.recv_timeout(Duration::from_secs(10)).unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while !directory.join("held").exists() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(directory.join("held").exists(), "the child is held inside its driver");
assert!(!directory.join("input.pdf").exists(), "the stalled driver retains no plaintext PDF");
assert!(!directory.join("job.json").exists(), "loaded settings were erased before driver work");
assert!(submission.cancel(), "a stalled driver still acknowledges cancellation");
let next = Submission::new();
assert_eq!(next.submit_with(b"synthetic PDF", &job(), |dir| command(dir, "ready")), Ok("spooled synthetic job".into()));
assert_eq!(running.join().unwrap(), Err(CANCELLED.into()));
assert!(!directory.exists(), "the reaped helper's PDF and settings were removed");
assert!(!next.cancel(), "a completed job keeps its receipt");
}
#[test]
/// A refused cancellation keeps the sending process alive until its receipt.
fn cancellation_refusal_preserves_the_sending_job() {
let submission = Submission::new();
let worker = submission.clone();
let (path_tx, path_rx) = std::sync::mpsc::channel();
let running = std::thread::spawn(move || {
worker.submit_with(b"synthetic PDF", &job(), |dir| {
path_tx.send(dir.to_path_buf()).unwrap();
command(dir, "sending")
})
});
let directory = path_rx.recv_timeout(Duration::from_secs(10)).unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while !directory.join("sending").exists() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(directory.join("sending").exists());
assert!(!submission.cancel(), "a sending job refuses cancellation");
assert!(matches!(*submission.state(), State::Sending(_)));
assert!(!running.is_finished(), "the child is retained until it finishes sending");
std::fs::write(directory.join("release"), b"continue").unwrap();
assert_eq!(running.join().unwrap(), Ok("spooled synthetic job".into()));
assert!(!directory.exists());
}
#[test]
/// Closing the parent's pipe stops a waiting driver and permits parent-side cleanup.
fn parent_disconnect_stops_a_waiting_driver() {
let submission = Submission::new();
let worker = submission.clone();
let (path_tx, path_rx) = std::sync::mpsc::channel();
let running = std::thread::spawn(move || {
worker.submit_with(b"synthetic PDF", &job(), |dir| {
path_tx.send(dir.to_path_buf()).unwrap();
command(dir, "held")
})
});
let directory = path_rx.recv_timeout(Duration::from_secs(10)).unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while !directory.join("held").exists() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(directory.join("held").exists());
*submission.state() = State::Finished; // Drops the parent's pipe as on process exit.
assert_eq!(running.join().unwrap(), Err("the print helper stopped without a receipt".into()));
assert!(!directory.exists());
}
#[test]
/// Helper failure removes its input directory; input limits reject oversize data.
fn helper_crashes_are_errors_and_inputs_are_bounded() {
let submission = Submission::new();
let mut inputs = None;
assert_eq!(
submission.submit_with(b"synthetic PDF", &job(), |dir| {
inputs = Some(dir.to_path_buf());
command(dir, "crash")
}),
Err("the print helper stopped without a receipt".into())
);
assert!(!inputs.unwrap().exists(), "a helper crash removes the PDF and settings");
assert_eq!(bounded(&b"abcd"[..], 3), Err("print helper input exceeds its limit".into()));
assert_eq!(bounded(&b"abc"[..], 3), Ok(b"abc".to_vec()));
}
/// Cleanup is repeatable and reports real failures while still attempting both inputs.
#[test]
fn input_cleanup_tolerates_missing_files_and_reports_failures() {
let directory = tempfile::tempdir().unwrap();
std::fs::write(directory.path().join("job.json"), b"settings").unwrap();
std::fs::write(directory.path().join("input.pdf"), b"private PDF").unwrap();
assert_eq!(remove_inputs(directory.path()), Ok(()));
assert_eq!(remove_inputs(directory.path()), Ok(()));
assert!(!directory.path().join("input.pdf").exists());
std::fs::create_dir(directory.path().join("job.json")).unwrap();
std::fs::write(directory.path().join("input.pdf"), b"private PDF").unwrap();
let error = remove_inputs(directory.path()).unwrap_err();
assert!(error.contains("could not remove job.json"), "{error}");
assert!(!directory.path().join("input.pdf").exists(), "a settings cleanup failure does not retain the PDF");
}
}
+1 -1
View File
@@ -1 +1 @@
9d6d54d6d9ff603cc41e12e5f6ba51af3554ab66
1e515422afdda2f317af430c1f9d68a5f83935b4
+46
View File
@@ -769,6 +769,30 @@ pub fn autocorrect(root: &mut Arg, pos: &MathPos) -> Option<MathPos> {
Some(MathPos { path: pos.path, off: pos.off - name.chars().count() })
}
/// The character just before the caret is an n-ary operator (∫, ∑…) in plain math text, as
/// AutoCorrect leaves `\int` or `\sum`.
pub fn nary_before(root: &Arg, pos: &MathPos) -> bool {
let pos = clamp(root, pos);
let Some(a) = arg_at(root, &pos.path) else { return false };
let (i, k) = match locate(a, pos.off) {
Loc::Inside(i, k) => (i, k),
Loc::Before(i) => match i.checked_sub(1).and_then(|i| a.get(i).map(|n| (i, node_units(n)))) {
Some(at) => at,
None => return false,
},
};
let Some(MNode::Run(r)) = a.get(i) else { return false };
!r.nor && !r.lit && k.checked_sub(1).and_then(|k| r.text.chars().nth(k)).is_some_and(crate::math::is_nary_char)
}
/// The node just before the caret is a built n-ary operator.
pub fn nary_node_before(root: &Arg, pos: &MathPos) -> bool {
let pos = clamp(root, pos);
let Some(a) = arg_at(root, &pos.path) else { return false };
let Loc::Before(i) = locate(a, pos.off) else { return false };
i.checked_sub(1).and_then(|i| a.get(i)).is_some_and(|n| matches!(n, MNode::Nary { .. }))
}
/// Characters that make typed linear text build up into structures.
fn builds(s: &str) -> bool {
s.chars().any(|c| {
@@ -872,6 +896,28 @@ pub fn build_up(root: &mut Arg, pos: &MathPos, latex: bool) -> Option<MathPos> {
Some(clamp(root, &out))
}
/// Typing that just built an n-ary operator without its operand (`∫_0^1` then Space) goes on in
/// the empty operand, as after inserting one from the gallery, so what is typed next is
/// integrated or summed (#4917). An operator whose operand ends with another (`∫∫`) leads to the
/// innermost one. Other carets, and moves or Enter that build up, stay put.
pub fn into_empty_operand(root: &Arg, pos: &MathPos) -> MathPos {
let mut path = pos.path.clone();
let mut off = pos.off;
while path.len() < MAX_DEPTH
&& let Some(a) = arg_at(root, &path)
&& let Loc::Before(i) = locate(a, off)
&& let Some(k) = i.checked_sub(1)
&& let Some(MNode::Nary { e, .. }) = a.get(k)
{
path.push((k, 2));
if e.is_empty() {
return MathPos { path, off: 0 };
}
off = units(e);
}
pos.clone()
}
/// A top-level `#` numbers the equation: wrap it as a one-row equation array.
pub fn number_equation(root: &mut Arg) -> bool {
if has_number_mark(root) && !matches!(root.as_slice(), [MNode::EqArr { .. }]) {
+19 -5
View File
@@ -316,20 +316,34 @@ impl InlineObject {
/// A group's members placed in a `w` × `h` box at (`x`, `y`): each member's rectangle
/// (x, y, w, h) and the member. Empty for anything else.
pub fn group_rects(&self, x: f32, y: f32, w: f32, h: f32) -> Vec<([f32; 4], &InlineObject)> {
let InlineObject::Group { ch_w, ch_h, children, .. } = self else { return Vec::new() };
let InlineObject::Group { children, .. } = self else { return Vec::new() };
self.member_rects(x, y, w, h).into_iter().filter_map(|(i, r)| Some((r, &children.get(i)?.obj))).collect()
}
/// [`InlineObject::group_rects`] with each member's index in `children` instead of the member.
pub fn member_rects(&self, x: f32, y: f32, w: f32, h: f32) -> Vec<(usize, [f32; 4])> {
let InlineObject::Group { children, .. } = self else { return Vec::new() };
let (sx, sy) = self.group_scale(w, h);
let fin = |v: f32| if v.is_finite() { v } else { 0.0 };
let sx = if fin(*ch_w) > 0.0 { fin(w) / ch_w } else { 1.0 };
let sy = if fin(*ch_h) > 0.0 { fin(h) / ch_h } else { 1.0 };
children
.iter()
.take(MAX_GROUP_CHILDREN)
.filter_map(|c| {
.enumerate()
.filter_map(|(i, c)| {
let (cw, chh, _) = c.obj.frame()?;
let r = [x + fin(c.x) * sx, y + fin(c.y) * sy, (fin(cw) * sx).clamp(0.0, 4000.0), (fin(chh) * sy).clamp(0.0, 4000.0)];
(!matches!(c.obj, InlineObject::Group { .. })).then_some((r, &c.obj))
(!matches!(c.obj, InlineObject::Group { .. })).then_some((i, r))
})
.collect()
}
/// How much a group drawn `w` × `h` scales its members' space (x, y): 1 for a canvas, whose
/// members keep their size.
pub fn group_scale(&self, w: f32, h: f32) -> (f32, f32) {
let InlineObject::Group { ch_w, ch_h, .. } = self else { return (1.0, 1.0) };
let fin = |v: f32| if v.is_finite() { v } else { 0.0 };
let sx = if fin(*ch_w) > 0.0 { fin(w) / ch_w } else { 1.0 };
let sy = if fin(*ch_h) > 0.0 { fin(h) / ch_h } else { 1.0 };
(sx, sy)
}
/// A legacy form field's definition (`FORMCHECKBOX`, `FORMTEXT`, `FORMDROPDOWN`), read from
/// the `w:ffData` it keeps; `None` for anything else.
pub fn legacy_form(&self) -> Option<crate::legacy_form::LegacyForm> {
+6 -1
View File
@@ -169,6 +169,9 @@ pub(crate) fn delete_selection_effect(s: &mut Session) -> Result<SelectionDelete
if a == b {
return Ok(SelectionDelete { at: a, content_changed: false, state_changed: false });
}
if canvas::selected_member(s).is_some() {
return Err(CmdError::Disabled("a shape inside a drawing canvas is selected".into()));
}
controls::check_delete(s, &a, &b)?;
let effect = if s.doc.settings.track_changes {
if !track_delete_would_change(s, &a, &b) {
@@ -186,7 +189,9 @@ pub(crate) fn delete_selection_effect(s: &mut Session) -> Result<SelectionDelete
Ok(effect)
}
/// Delete the selection (respecting track changes); returns the collapsed position.
/// Delete the selection (respecting track changes); returns the collapsed position. With a
/// Drawing Canvas member picked (#2637) the selection is the whole canvas, which a command that
/// replaces the selection (Insert › Table, Equation, Symbol, Field…) would take away: refused.
pub fn delete_selection(s: &mut Session) -> Result<Pos, CmdError> {
delete_selection_effect(s).map(|e| e.at)
}
+320
View File
@@ -5,6 +5,10 @@
//! top-left corner, unscaled). While a canvas is selected, Insert › Pictures, Shapes and Text Box
//! put the new object inside it ([`add_member`]). Fit, Expand and Scale Drawing change its frame;
//! Shape Fill and Shape Outline colour its background and border.
//!
//! A member can be picked on its own (#2637, `select.member`; a click on it does this): Shape
//! Format, Size, Rotate, Alt Text, Delete, Cut and Copy then act on that member, and Move or
//! Resize and Nudge move it inside the canvas. The canvas stays the selection in the text.
use serde_json::{Value, json};
use wordcraft_doc::para::{CanvasStyle, Float, GroupChild, InlineObject, MAX_GROUP_CHILDREN};
@@ -14,6 +18,29 @@ use super::objects::object_selection;
use super::{delete_selection, sel_result};
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
/// A member of the selected canvas picked on its own: its index, and the selection it was picked
/// in (it counts only while that selection stands).
#[derive(Clone, Debug, PartialEq)]
pub struct CanvasMember {
sel: Selection,
pub index: usize,
}
/// The canvas member picked on its own: the canvas's position, the member's index and the member.
pub fn selected_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
let m = s.member.as_ref().filter(|m| m.sel == s.sel)?;
let (pos, canvas) = selected_canvas(s)?;
let InlineObject::Group { children, .. } = canvas else { return None };
let c = children.get(m.index).filter(|c| pickable(c))?;
Some((pos, m.index, &c.obj))
}
/// Whether a member can be picked on its own: a picture, shape or text box that is drawn (a
/// group inside a canvas isn't, nor a hidden member).
pub fn pickable(c: &GroupChild) -> bool {
c.obj.is_drawing() && !matches!(c.obj, InlineObject::Group { .. }) && !c.obj.frame().is_some_and(|(_, _, f)| f.hidden)
}
/// Largest canvas side and member offset, points (well past any page).
const MAX_SIDE: f32 = 4000.0;
/// Smallest canvas side, points.
@@ -47,6 +74,10 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("canvas.scale", "Scale Drawing", "Shape Format › Drawing Canvas", scale)
.params(r#"{"factor": number (0.1–10)} (scales the frame and every member together)"#)
.when(has_canvas),
CommandSpec::new("select.member", "Select Canvas Member", "Shape Format › Drawing Canvas", select_member)
.params(r#"{"index": n | null} (picks member `index` of the selected drawing canvas on its own: Shape Format, Size, Rotate, Alt Text, Delete, Cut and Copy then act on it, and Move or Resize and Nudge move it inside the canvas; null: the canvas itself again)"#)
.when(has_canvas)
.pure(),
CommandSpec::new("canvas.member", "Canvas Member", "Shape Format › Drawing Canvas", member)
.params(r#"{"index": n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; with no change, returns the members)"#)
.when(has_canvas),
@@ -224,9 +255,171 @@ fn member(s: &mut Session, v: &Value) -> CmdResult {
c.obj.set_size(nw.unwrap_or(w0).clamp(1.0, MAX_SIDE), nh.unwrap_or(h0).clamp(1.0, MAX_SIDE));
}
})?;
// The indices after a removed member shift down, so a picked member would name another one.
if delete {
s.member = None;
}
result(&o)
}
/// `select.member`: pick a member of the selected canvas on its own, or (`null`) the canvas again.
fn select_member(s: &mut Session, v: &Value) -> CmdResult {
let Some((_, InlineObject::Group { children, .. })) = selected_canvas(s) else {
return Err(CmdError::Disabled("select a drawing canvas first".into()));
};
let index = match v.get("index") {
None | Some(Value::Null) => None,
Some(_) => {
Some(p::u64(v, "index").and_then(|i| usize::try_from(i).ok()).ok_or_else(|| CmdError::Params("`index` is a member number".into()))?)
}
};
let Some(i) = index else {
s.member = None;
return sel_result(s);
};
let count = children.len();
let c = children.get(i).ok_or_else(|| CmdError::Params(format!("no member {i} (the canvas has {count})")))?;
if !pickable(c) {
return Err(CmdError::Params(format!("member {i} can't be selected on its own")));
}
let (w, h) = c.obj.frame().map(|(w, h, _)| (w, h)).unwrap_or((0.0, 0.0));
let out = json!({"index": i, "x": c.x, "y": c.y, "width": w, "height": h, "object": serde_json::to_value(&c.obj).unwrap_or(Value::Null)});
s.member = Some(CanvasMember { sel: s.sel.clone(), index: i });
Ok(out)
}
/// Delete, Backspace (and their word forms), Cut and Copy with a member picked act on the member
/// alone; the canvas stays selected. Typing and pasting, which would replace the whole canvas,
/// are disabled. `None`: another command, or no member picked.
pub(crate) fn member_command(s: &mut Session, id: &str, _: &Value) -> Option<CmdResult> {
let replaces = (id.starts_with("text.") && id != "text.overtype")
|| matches!(
id,
"edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteSpecial" | "edit.pasteClipboardItem" | "edit.pasteAllClipboard"
);
if !replaces && !matches!(id, "edit.cut" | "edit.copy") {
return None;
}
let (pos, index, _) = selected_member(s)?;
Some(match id {
"edit.copy" => copy_member(s, &pos, index),
"edit.cut" => copy_member(s, &pos, index).and_then(|r| remove_member(s, &pos, index).map(|_| r)),
"text.delete" | "text.backspace" | "text.deleteWordBack" | "text.deleteWordForward" => {
remove_member(s, &pos, index).and_then(|_| sel_result(s))
}
_ => Err(CmdError::Disabled("a shape inside a drawing canvas is selected".into())),
})
}
/// Copy member `index` of the canvas at `pos` alone: pasted, it is a picture or shape of its own.
fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
let end = Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos.clone() };
let mut f = s.doc.copy_range(pos, &end);
let mut copied = false;
for b in &mut f.blocks {
let wordcraft_doc::Block::Para(p) = b else { continue };
for o in &mut p.objects {
if let InlineObject::Group { children, canvas: Some(_), .. } = o
&& let Some(c) = children.get(index)
{
*o = c.obj.clone();
copied = true;
}
}
}
if !copied {
return Err(CmdError::Failed("the member vanished".into()));
}
s.clipboard_text = f.clipboard_text();
s.clip_history.push(&f, &s.clipboard_text);
s.clipboard = Some(f);
Ok(super::edit::copy_result(s))
}
/// Take member `index` out of the canvas at `pos`; the canvas stays selected.
fn remove_member(s: &mut Session, pos: &Pos, index: usize) -> Result<(), CmdError> {
edit_canvas(s, pos, |_, _, children| {
if index < children.len() {
children.remove(index);
}
})?;
s.member = None;
Ok(())
}
/// Move or Resize with a member picked: `x`/`y` (the page point of its top-left, as dragging its
/// frame gives it) and the size become its place and size in the canvas. `None`: no member.
pub(crate) fn member_bounds(s: &mut Session, v: &Value) -> Option<CmdResult> {
let (pos, index, obj) = selected_member(s)?;
let (w0, h0, _) = obj.frame()?;
let min = super::objects::min_size(obj);
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
(Some(x), Some(y)) => Some((x, y)),
(None, None) => None,
_ => return Some(Err(CmdError::Params("`x` and `y` go together".into()))),
};
// `x`/`y` are on the canvas's page: a drop on another page would put the member outside it.
if to.is_some()
&& let Some(page) = p::u64(v, "page").and_then(|n| usize::try_from(n).ok())
&& s.layout().object(&pos, s.page_hint).is_some_and(|o| o.page != page)
{
return Some(Err(CmdError::Disabled("a shape can't leave its drawing canvas".into())));
}
let (nw, nh) = (p::f32(v, "width"), p::f32(v, "height"));
Some(edit_member(s, &pos, index, |frame, (sx, sy), c| {
if let Some((x, y)) = to {
c.x = ((x - frame.x) / sx).clamp(-MAX_SIDE, MAX_SIDE);
c.y = ((y - frame.y) / sy).clamp(-MAX_SIDE, MAX_SIDE);
}
let w = nw.map_or(w0, |w| w / sx).clamp(min, MAX_SIDE);
let h = nh.map_or(h0, |h| h / sy).clamp(min, MAX_SIDE);
if (w, h) != (w0, h0) {
c.obj.set_size(w, h);
}
}))
}
/// Nudge with a member picked: it moves inside the canvas. `None`: no member.
pub(crate) fn member_nudge(s: &mut Session, dx: f32, dy: f32) -> Option<CmdResult> {
let (pos, index, _) = selected_member(s)?;
Some(edit_member(s, &pos, index, |_, (sx, sy), c| {
c.x = (c.x + dx / sx).clamp(-MAX_SIDE, MAX_SIDE);
c.y = (c.y + dy / sy).clamp(-MAX_SIDE, MAX_SIDE);
}))
}
/// Change member `index` of the canvas at `pos`: `f` gets the canvas's frame on the page, the
/// scale of its members' space and the member.
fn edit_member(s: &mut Session, pos: &Pos, index: usize, f: impl FnOnce(wordcraft_geom::Rect, (f32, f32), &mut GroupChild)) -> CmdResult {
let frame = s.layout().object(pos, s.page_hint).ok_or_else(|| CmdError::Failed("the drawing canvas isn't laid out".into()))?.rect;
let canvas =
s.doc.para_at(pos).and_then(|p| p.object_at(pos.off)).cloned().ok_or_else(|| CmdError::Failed("the drawing canvas vanished".into()))?;
let scale = canvas.group_scale(frame.w, frame.h);
let mut f = Some(f);
let canvas = edit_canvas(s, pos, |_, _, children| {
if let (Some(c), Some(f)) = (children.get_mut(index), f.take()) {
f(frame, scale, c);
}
})?;
let InlineObject::Group { children, .. } = &canvas else { return result(&canvas) };
let member = children.get(index).map(|c| serde_json::to_value(&c.obj).unwrap_or(Value::Null)).unwrap_or(Value::Null);
Ok(json!({"object": member, "pos": super::pos_json(pos), "member": index}))
}
/// Change the picked member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
/// canvas. `None`: no member picked there.
pub(crate) fn edit_member_object(s: &mut Session, pos: &Pos, f: impl Fn(&mut InlineObject)) -> Option<Result<InlineObject, CmdError>> {
let (at, index, _) = selected_member(s).filter(|(at, ..)| at == pos)?;
let mut out = None;
let r = edit_canvas(s, &at, |_, _, children| {
if let Some(c) = children.get_mut(index) {
f(&mut c.obj);
out = Some(c.obj.clone());
}
});
Some(r.and_then(|_| out.ok_or_else(|| CmdError::Failed("the member vanished".into()))))
}
/// Shape Fill and Shape Outline on a selected canvas colour its background and border.
pub fn style_mut(o: &mut InlineObject) -> Option<&mut CanvasStyle> {
match o {
@@ -327,4 +520,131 @@ mod tests {
fn canvas_in_text(s: &Session) -> InlineObject {
s.doc.body.first().and_then(|b| b.as_para()).and_then(|p| p.objects.first()).cloned().unwrap()
}
fn member_fill(o: &InlineObject, i: usize) -> Option<wordcraft_doc::fill::Fill> {
let InlineObject::Group { children, .. } = o else { panic!("{o:?}") };
match &children[i].obj {
InlineObject::Shape { fill, .. } => fill.clone(),
o => panic!("{o:?}"),
}
}
/// #2637: a shape inside a drawing canvas can be picked on its own, as in Word. Shape Format,
/// Move or Resize, Nudge, Delete and Copy then act on it rather than on the whole canvas,
/// which stays the selection in the text; the commands that place an object in the text
/// (wrapping, position) don't apply to it.
#[test]
fn a_canvas_member_is_selected_and_changed_on_its_own() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.canvas", &json!({"width": 400, "height": 300})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 40})).unwrap();
s.run("insert.shape", &json!({"kind": "ellipse", "width": 50, "height": 50})).unwrap();
s.run("canvas.member", &json!({"index": 0, "x": 40, "y": 30})).unwrap();
s.run("canvas.member", &json!({"index": 1, "x": 200, "y": 100})).unwrap();
let canvas_sel = s.sel.clone();
assert!(s.run("select.member", &json!({"index": 5})).is_err(), "no such member");
s.run("select.member", &json!({"index": 1})).unwrap();
assert_eq!(selected_member(&s).map(|(_, i, _)| i), Some(1));
assert_eq!(s.sel, canvas_sel, "the canvas stays the selection in the text");
// Shape Fill colours the member, not the canvas or the other member.
let other = member_fill(&canvas(&s), 0);
s.run("shape.fill", &json!({"color": "FF0000"})).unwrap();
let c = canvas(&s);
assert_eq!(member_fill(&c, 1), wordcraft_doc::props::Rgb::parse("FF0000").map(wordcraft_doc::fill::Fill::solid));
assert_eq!(member_fill(&c, 0), other);
assert_eq!(c.canvas_style().and_then(|st| st.fill.clone()), None);
assert!(selected_member(&s).is_some(), "still picked after a change");
// Dragging its frame: the page point becomes its place in the canvas.
let frame = s.layout().object(&selected_canvas(&s).unwrap().0, 0).unwrap().rect;
s.run("arrange.bounds", &json!({"page": 0, "x": frame.x + 10.0, "y": frame.y + 20.0, "width": 60, "height": 30})).unwrap();
assert_eq!(members(&canvas(&s))[1], (10.0, 20.0, 60.0, 30.0));
assert_eq!(canvas(&s).frame().map(|(w, h, _)| (w, h)), Some((400.0, 300.0)), "the canvas keeps its frame");
s.run("arrange.nudge", &json!({"dx": 6, "dy": -6})).unwrap();
assert_eq!(members(&canvas(&s))[1], (16.0, 14.0, 60.0, 30.0));
assert!(s.run("arrange.wrap", &json!({"wrap": "square"})).is_err(), "the canvas places its members");
// Copy puts the member alone on the clipboard; Delete takes it out of the canvas.
s.run("edit.copy", &json!({})).unwrap();
let clip = s.clipboard.clone().unwrap();
let copied: Vec<&InlineObject> = clip.blocks.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).collect();
assert!(matches!(copied.as_slice(), [InlineObject::Shape { kind: wordcraft_doc::para::ShapeKind::Ellipse, .. }]), "{copied:?}");
s.run("text.delete", &json!({})).unwrap();
assert_eq!(members(&canvas(&s)), [(40.0, 30.0, 100.0, 40.0)]);
assert!(selected_member(&s).is_none());
assert_eq!(s.sel, canvas_sel, "the canvas is still selected");
// Undo puts the member back.
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(members(&canvas_in_text(&s)).len(), 2);
// Picking the canvas again (or anything else) ends the member's selection.
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.member", &json!({"index": 0})).unwrap();
s.run("select.member", &json!({"index": null})).unwrap();
assert!(selected_member(&s).is_none());
s.run("select.member", &json!({"index": 0})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
assert!(selected_member(&s).is_none());
// Pasted outside the canvas, the copied member is a shape of its own in the text.
s.run("edit.paste", &json!({})).unwrap();
let para = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert!(matches!(para.objects.last(), Some(InlineObject::Shape { kind: wordcraft_doc::para::ShapeKind::Ellipse, .. })), "{:?}", para.objects);
}
#[test]
fn typing_or_removing_a_member_never_hits_another_shape_or_the_canvas() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.canvas", &json!({"width": 400, "height": 300})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 40})).unwrap();
s.run("insert.shape", &json!({"kind": "ellipse", "width": 50, "height": 50})).unwrap();
s.run("select.member", &json!({"index": 1})).unwrap();
// Typing or pasting would replace the whole canvas: refused, and the member stays picked.
for (id, v) in [
("text.insert", json!({"text": "x"})),
("text.newParagraph", json!({})),
("edit.paste", json!({"text": "x"})),
("edit.pasteText", json!({"text": "x"})),
] {
assert!(matches!(s.run(id, &v), Err(CmdError::Disabled(_))), "{id}");
assert_eq!(members(&canvas(&s)).len(), 2, "{id}");
}
assert_eq!(selected_member(&s).map(|(_, i, _)| i), Some(1));
// Ctrl+Backspace removes the member alone, like Backspace.
s.run("text.deleteWordBack", &json!({})).unwrap();
let sizes: Vec<(f32, f32)> = members(&canvas(&s)).iter().map(|m| (m.2, m.3)).collect();
assert_eq!(sizes, [(100.0, 40.0)], "the ellipse went, the rectangle stays");
assert!(selected_member(&s).is_none());
// Removing an earlier member through `canvas.member` drops the pick: its index would now
// name the next member.
s.run("insert.shape", &json!({"kind": "ellipse", "width": 50, "height": 50})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle", "width": 20, "height": 20})).unwrap();
s.run("select.member", &json!({"index": 1})).unwrap();
s.run("canvas.member", &json!({"index": 0, "delete": true})).unwrap();
assert!(selected_member(&s).is_none(), "the pick doesn't slide onto the member that moved up");
// Commands that replace the selection (the whole canvas) are refused too.
s.run("select.member", &json!({"index": 0})).unwrap();
for (id, v) in [
("insert.table", json!({"rows": 1, "cols": 1})),
("table.quick", json!({})),
("insert.equation", json!({})),
("insert.symbol", json!({"char": "§"})),
("insert.field", json!({"instr": "AUTHOR"})),
("insert.pageBreak", json!({})),
] {
assert!(s.run(id, &v).is_err(), "{id}");
assert_eq!(members(&canvas(&s)).len(), 2, "{id}: the canvas and its members stay");
}
// Moving the member: on the canvas's page it moves; a drop on another page is refused.
let frame = s.layout().object(&selected_canvas(&s).unwrap().0, 0).unwrap();
let before = members(&canvas(&s));
let other = frame.page + 1;
assert!(matches!(s.run("arrange.bounds", &json!({"page": other, "x": 100, "y": 100})), Err(CmdError::Disabled(_))));
assert_eq!(members(&canvas(&s)), before);
s.run("arrange.bounds", &json!({"page": frame.page, "x": frame.rect.x + 5.0, "y": frame.rect.y + 5.0})).unwrap();
assert_ne!(members(&canvas(&s)), before);
}
}
+23 -3
View File
@@ -201,7 +201,11 @@ pub(super) fn bib_order(doc: &Document, st: &CiteStyle, lang: Option<String>) ->
let mut idx: Vec<usize> = if cited.is_empty() {
(0..doc.sources.len()).collect()
} else if st.order == Order::Cited {
cited.iter().filter_map(|t| doc.sources.iter().position(|x| &x.tag == t)).collect()
let mut by_tag = std::collections::HashMap::new();
for (i, source) in doc.sources.iter().enumerate() {
by_tag.entry(source.tag.as_str()).or_insert(i);
}
cited.iter().filter_map(|t| by_tag.get(t.as_str()).copied()).collect()
} else {
let cited: std::collections::HashSet<&str> = cited.iter().map(String::as_str).collect();
doc.sources.iter().enumerate().filter(|(_, x)| cited.contains(x.tag.as_str())).map(|(i, _)| i).collect()
@@ -233,6 +237,21 @@ pub fn update_citations(s: &mut Session) -> Result<(), CmdError> {
fn refresh_citations(s: &mut Session) -> Result<(), CmdError> {
let st = style(&s.bib_style);
let order = bib_order(&s.doc, st, crate::cmd::default_lang(s));
// Native data can repeat tags: keep the first source record and, independently, the first
// bibliography position with that tag. Own the keys so paragraph writes don't borrow sources.
let fallback = order.len().saturating_add(1);
let mut by_tag = std::collections::HashMap::new();
for (i, source) in s.doc.sources.iter().enumerate() {
by_tag.entry(source.tag.clone()).or_insert((i, fallback));
}
for (n, &i) in order.iter().enumerate() {
if let Some(source) = s.doc.sources.get(i)
&& let Some((_, number)) = by_tag.get_mut(&source.tag)
&& *number == fallback
{
*number = n.saturating_add(1);
}
}
for path in s.doc.para_paths(StoryRef::Body) {
let Some(p) = s.doc.para(StoryRef::Body, &path) else { continue };
let updates: Vec<(usize, String)> = p
@@ -242,8 +261,9 @@ fn refresh_citations(s: &mut Session) -> Result<(), CmdError> {
.filter_map(|(k, o)| match o {
InlineObject::Field { instr, .. } => {
let (tag, pages) = citation_field(instr)?;
let src = s.doc.sources.iter().find(|x| x.tag == tag)?;
Some((k, cite(src, st.name, number_of(&s.doc, &order, tag), pages)))
let &(i, number) = by_tag.get(tag)?;
let src = s.doc.sources.get(i)?;
Some((k, cite(src, st.name, number, pages)))
}
_ => None,
})
+115
View File
@@ -785,3 +785,118 @@ fn gost_numbers_follow_its_name_or_title_sort() {
assert_eq!(find_style("Harvard - Anglia 2008").map(|x| x.name), Some("Harvard (Anglia)"));
assert!(find_style("").is_none() && find_style("Vancouver").is_none());
}
fn lookup_session(tags: &[&str]) -> Session {
let mut p = Paragraph::new();
for tag in tags {
p.insert_object(
p.len(),
InlineObject::Field {
instr: format!("CITATION {tag}"),
result: "Original cache".into(),
locked: false,
dirty: true,
code: false,
form: String::new(),
},
&CharProps::default(),
)
.unwrap();
}
let mut doc = Document::new();
doc.body = vec![wordcraft_doc::para_block(p)];
Session::new(doc)
}
#[test]
fn citation_source_lookups_keep_first_duplicates_case_and_style_order() {
let mut s = lookup_session(&["A", "B", "missing", "a", "B"]);
s.doc.sources = [
("B", "Zed, Zo", "Zulu"),
("A", "Able, Ann", "Alpha"),
("B", "Baker, Ben", "Beta duplicate"),
("a", "Middle, May", "Middle"),
("unused", "Other, One", "Unused"),
]
.into_iter()
.map(|(tag, author, title)| Source { tag: tag.into(), author: author.into(), title: title.into(), year: "2024".into(), ..Default::default() })
.collect();
let original = s.doc.clone();
for st in &STYLES {
s.bib_style = st.name.into();
let expected = if st.order == Order::Cited { vec![1, 0, 3] } else { vec![1, 2, 3, 0] };
assert_eq!(sources::bib_order(&s.doc, st, None), expected, "{}", st.name);
update_citations(&mut s).unwrap();
let p = s.doc.para(StoryRef::Body, &Path::top(0)).unwrap();
for (k, (source, number)) in [(1, 1), (0, 2), (usize::MAX, 0), (3, 3), (0, 2)].into_iter().enumerate() {
let InlineObject::Field { instr, result, locked, dirty, code, form } = &p.objects[k] else { panic!() };
let InlineObject::Field { instr: before, .. } = &original.para(StoryRef::Body, &Path::top(0)).unwrap().objects[k] else { panic!() };
assert_eq!(instr, before);
let expected = original.sources.get(source).map(|x| cite(x, st.name, number, "")).unwrap_or_else(|| "Original cache".into());
assert_eq!(result, &expected, "{}: {instr}", st.name);
assert!(!locked && *dirty && !code && form.is_empty());
}
assert_eq!(s.doc.sources, original.sources);
}
// Without citations even duplicate and unused source records remain in the bibliography.
s.doc.body.clear();
assert_eq!(sources::bib_order(&s.doc, style("IEEE"), None), vec![0, 1, 2, 3, 4]);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn citation_refresh_source_lookup_work_scales_with_document_size() {
fn doc(n: usize) -> Session {
let mut p = Paragraph::new();
p.text = wordcraft_doc::para::OBJ.to_string().repeat(n);
p.runs = vec![wordcraft_doc::Run { len: p.text.len(), props: CharProps::default() }];
p.objects = (0..n)
.rev()
.map(|i| InlineObject::Field {
instr: format!("CITATION T{i}"),
result: String::new(),
locked: false,
dirty: false,
code: false,
form: String::new(),
})
.collect();
let mut d = Document::new();
d.body = vec![wordcraft_doc::para_block(p)];
d.sources = (0..n).map(|i| Source { tag: format!("T{i}"), ..Default::default() }).collect();
let mut s = Session::new(d);
s.bib_style = "IEEE".into();
s
}
// Use the running thread's CPU time on Linux; scheduler pauses are not lookup work.
fn cost(f: &mut impl FnMut()) -> f64 {
let ran = || std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse::<u64>().ok();
let (t, before) = (std::time::Instant::now(), ran());
f();
match (before, ran()) {
(Some(a), Some(b)) if b > a => (b - a) as f64 * 1e-9,
_ => t.elapsed().as_secs_f64(),
}
}
const SCALE: usize = 8;
let (mut small, mut big) = (doc(2_000), doc(SCALE * 2_000));
update_citations(&mut small).unwrap();
update_citations(&mut big).unwrap();
let (mut a, mut b) = (f64::INFINITY, f64::INFINITY);
for _ in 0..5 {
a = a.min(
cost(&mut || {
for _ in 0..SCALE {
update_citations(&mut small).unwrap();
}
}) / SCALE as f64,
);
b = b.min(cost(&mut || {
update_citations(&mut big).unwrap();
}));
}
let ratio = b / a.max(1e-9);
assert!(ratio < 32.0, "citation refresh: {a:.6}s -> {b:.6}s, {ratio:.1}x for {SCALE}x input");
let p = big.doc.para(StoryRef::Body, &Path::top(0)).unwrap();
assert!(p.objects.iter().enumerate().all(|(i, o)| matches!(o, InlineObject::Field { result, .. } if result == &format!("[{}]", i + 1))));
}
+1 -1
View File
@@ -361,7 +361,7 @@ impl ClipHistory {
self.items.is_empty()
}
fn push(&mut self, f: &Fragment, text: &str) {
pub(crate) fn push(&mut self, f: &Fragment, text: &str) {
// Text plus per-paragraph overhead; pictures are references into the document.
let paras = text.matches('\n').count().saturating_add(f.blocks.len()).saturating_add(f.parts.len()).saturating_add(1);
let bytes = text.len().saturating_mul(2).saturating_add(paras.saturating_mul(256));
+16 -2
View File
@@ -326,8 +326,14 @@ fn type_text(s: &mut Session, v: &Value) -> CmdResult {
pos = p;
changed = true;
}
if let Some(p) = me::build_up(&mut math.nodes, &pos, latex) {
pos = p;
// As in Word, `\int` + Space leaves ∫ waiting for its limits: `_a^b` and then
// Space, or Space alone, builds the operator (#4917).
let waits = changed && c == ' ' && me::nary_before(&math.nodes, &pos);
// Only an operator this build-up makes takes the caret: one already there (from
// the gallery, say) keeps it after it.
let built_before = me::nary_node_before(&math.nodes, &pos);
if !waits && let Some(p) = me::build_up(&mut math.nodes, &pos, latex) {
pos = if built_before { p } else { me::into_empty_operand(&math.nodes, &p) };
changed = true;
}
if changed {
@@ -336,6 +342,14 @@ fn type_text(s: &mut Session, v: &Value) -> CmdResult {
if c == ' ' && changed {
continue;
}
} else if !style.nor && !latex && !c.is_alphanumeric() {
// Word corrects `\name` on any character that can't continue it (`\int_`,
// `\alpha+`), keeps that character and builds nothing up yet. LaTeX input keeps
// its commands (`\sqrt{`).
if let Some(p) = me::autocorrect(&mut math.nodes, &pos) {
pos = p;
transformed = true;
}
}
pos = me::insert_text(&mut math.nodes, &pos, &c.to_string(), style);
}
+109
View File
@@ -530,3 +530,112 @@ fn equation_delete_surrounding_moves_the_caret_for_a_one_step_delete() {
assert_eq!(linear(&s), "bc");
assert_eq!(s.math.as_ref().unwrap().pos, MathPos::new(Vec::new(), 0));
}
/// The n-ary operator in the equation, with its limits (shown or not) and operand as text.
fn nary_of(s: &Session) -> Option<(char, Option<String>, Option<String>, String)> {
nodes_of(s, &s.math.as_ref()?.at)?.iter().find_map(|n| match n {
MNode::Nary { chr, sub_hide, sup_hide, sub, sup, e, .. } => {
Some((*chr, (!sub_hide).then(|| to_linear(sub)), (!sup_hide).then(|| to_linear(sup)), to_linear(e)))
}
_ => None,
})
}
#[test]
fn an_autocorrected_operator_waits_for_its_limits() {
// #4917: as in Word, `\int` + Space gives a ∫ that `_x^y` then Space decorates; the
// operand typed next goes inside the operator.
let typed = |keys: &[&str]| {
let mut s = session();
s.run("insert.equation", &json!({})).unwrap();
for t in keys {
s.run("equation.type", &json!({"text": t})).unwrap();
}
s
};
let s = typed(&[r"\int", " "]);
assert_eq!(linear(&s), "∫", "the operator waits, not yet built");
assert!(nary_of(&s).is_none());
let s = typed(&[r"\int", " ", "_x^y", " ", "f"]);
assert_eq!(nary_of(&s), Some(('∫', Some("x".into()), Some("y".into()), "f".into())));
let s = typed(&[r"\sum", " ", "_(k=1)^n", " ", "k"]);
assert_eq!(nary_of(&s), Some(('∑', Some("k=1".into()), Some("n".into()), "k".into())));
// Only a lower limit.
let s = typed(&[r"\prod", " ", "_i", " ", "a"]);
assert_eq!(nary_of(&s), Some(('∏', Some("i".into()), None, "a".into())));
// Space alone builds it without limits, the caret in its operand.
let s = typed(&[r"\int", " ", " ", "x"]);
assert_eq!(nary_of(&s), Some(('∫', None, None, "x".into())));
// Typing the operand straight after it, as before.
let s = typed(&[r"\int", " ", "x", " "]);
assert_eq!(nary_of(&s), Some(('∫', None, None, "x".into())));
// Enter builds the operator and leaves the caret after it; Right builds it and, at the
// equation's end, leaves the equation, both as before.
let mut s = typed(&[r"\int", " ", "_0^1"]);
s.run("equation.enter", &json!({})).unwrap();
assert_eq!(nary_of(&s), Some(('∫', Some("0".into()), Some("1".into()), String::new())));
assert_eq!(s.math.as_ref().unwrap().pos, MathPos::new(Vec::new(), 1));
let mut s = typed(&[r"\int", " ", "_0^1"]);
let at = s.math.as_ref().unwrap().at.clone();
s.run("equation.move", &json!({"dir": "right"})).unwrap();
assert!(s.math.is_none(), "Right at the end leaves the equation");
assert!(matches!(nodes_of(&s, &at).as_deref(), Some([MNode::Nary { e, .. }]) if e.is_empty()));
// One undo step takes the whole typing away, leaving the empty equation.
let mut s = typed(&[r"\int", " ", "_0^1", " ", "t"]);
let at = s.math.as_ref().unwrap().at.clone();
s.run("equation.exit", &json!({})).unwrap();
s.run("edit.undo", &json!({})).unwrap();
let left = s.doc.para_at(&at).and_then(|p| p.object_at(at.off)).map(|o| o.plain_text().to_string());
assert_eq!(left.as_deref(), Some(""), "the equation is there, empty");
// An operator ending another one's operand (`∫∫`) takes what is typed next.
let s = typed(&[r"\int", " ", r"\int", " ", " ", "f"]);
let inner = nary_of(&s).and_then(|_| {
nodes_of(&s, &s.math.as_ref()?.at)?.iter().find_map(|n| match n {
MNode::Nary { e, .. } => match e.as_slice() {
[MNode::Nary { e, .. }] => Some(to_linear(e)),
_ => None,
},
_ => None,
})
});
assert_eq!(inner.as_deref(), Some("f"), "f is the inner operator's operand");
// Space after an operator that was already there (from the gallery, its operand left empty)
// doesn't send the caret back into it: what is typed next follows the operator.
let mut s = session();
s.run("insert.equation", &json!({})).unwrap();
s.run("equation.insertStructure", &json!({"id": "nary.sumLimits"})).unwrap();
s.run("equation.type", &json!({"text": "k"})).unwrap();
if let Some(m) = s.math.as_mut() {
m.pos = MathPos::new(Vec::new(), 1);
}
s.run("equation.type", &json!({"text": " x"})).unwrap();
assert_eq!(nary_of(&s).map(|n| n.3), Some(String::new()), "the operand stays empty");
assert_eq!(s.math.as_ref().unwrap().pos.path, Vec::new(), "the caret stays after the operator");
}
#[test]
fn a_math_name_is_corrected_by_any_character_that_cannot_continue_it() {
// Observed in Word for Windows (#4938): `\int_0^1` typed in one go gives ∫ as soon as `_` is
// typed, so Space then builds the integral with its limits; `\alpha` + `+` gives α+, and a
// letter or digit leaves the name as typed.
let typed = |keys: &[&str]| {
let mut s = session();
s.run("insert.equation", &json!({})).unwrap();
for t in keys {
s.run("equation.type", &json!({"text": t})).unwrap();
}
s
};
let s = typed(&[r"\int_0^1", " ", "x"]);
assert_eq!(nary_of(&s), Some(('∫', Some("0".into()), Some("1".into()), "x".into())));
let s = typed(&[r"\alpha+\beta\gamma1"]);
assert_eq!(linear(&s), r"α+β\gamma1");
let s = typed(&[r"\alpha(x)"]);
assert_eq!(linear(&s), "α(x)");
// LaTeX input keeps its commands until they are built up.
let mut s = session();
s.run("equation.inputFormat", &json!({"format": "latex"})).unwrap();
s.run("insert.equation", &json!({})).unwrap();
s.run("equation.type", &json!({"text": r"\alpha+"})).unwrap();
assert_eq!(linear(&s), r"\alpha+");
}
+19 -6
View File
@@ -1,16 +1,18 @@
use super::filter::refresh_shown;
use super::{CmdError, CmdResult, Session, Value, json, p};
/// Parse CSV (RFC 4180-ish: quotes, doubled quotes, commas/semicolons/tabs).
/// The field separator: whichever of `,` `;` and tab the first non-blank line (outside quotes) uses most.
/// The field separator: whichever of `,` `;` and tab the first non-blank record (outside quotes) uses most.
fn csv_separator(text: &str) -> char {
let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or("");
let mut quoted = false;
let mut unquoted = String::new();
for c in first.chars() {
// A quoted header may span physical lines; infer from the first complete record.
for c in text.split_inclusive(['\n', '\r']).skip_while(|line| line.trim().is_empty()).flat_map(str::chars) {
if c == '"' {
quoted = !quoted;
} else if !quoted {
if c == '\n' || c == '\r' {
break;
}
unquoted.push(c);
}
}
@@ -26,6 +28,7 @@ fn push_csv_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>) {
}
}
/// Parse CSV (RFC 4180-ish: quotes, doubled quotes, commas/semicolons/tabs).
pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
let sep = csv_separator(text);
let mut rows = Vec::new();
@@ -112,13 +115,23 @@ fn table_from_rows(fields: Option<&Vec<Value>>, arr: &[Value]) -> Result<(Vec<St
Ok((headers, rows))
}
/// Skip unquoted blank prefix lines only when a text recipient list has a header.
/// Headerless lists and the shared CSV reader keep whitespace records.
fn recipient_csv(text: &str, headers: bool) -> Vec<Vec<String>> {
let prefix = text
.split_inclusive(['\n', '\r'])
.take_while(|line| headers && line.trim().is_empty())
.fold(0_usize, |bytes, line| bytes.saturating_add(line.len()));
parse_csv(text.get(prefix..).unwrap_or_default())
}
pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
let mut sheet = Value::Null;
let (headers, rows) = if let Some(arr) = v.get("rows").and_then(Value::as_array) {
table_from_rows(v.get("fields").and_then(Value::as_array), arr)?
} else {
let all = if let Some(c) = p::str(v, "csv") {
parse_csv(c)
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))
} else {
let (bytes, ext) = if let Some(d) = p::str(v, "data") {
let b = crate::cmd::insert::base64_decode(d.trim()).ok_or_else(|| CmdError::Params("`data` isn't valid base64".into()))?;
@@ -175,7 +188,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
sheet = json!(chosen);
rows
} else {
parse_csv(&decode(&bytes, v)?)
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))
}
};
header_split(all, p::bool(v, "headers").unwrap_or(true))?
+70
View File
@@ -46,6 +46,76 @@ fn finishing_a_merge_to_a_file_is_not_an_edit() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn csv_delimiter_reads_complete_header_record() {
for sep in [',', ';', '\t'] {
for newline in ["\n", "\r\n", "\r"] {
// All candidate separators and doubled quotes occur on both sides of the newline.
// The real separators follow the closing quote, beyond the first physical line.
let header = format!("Name,;\t \"given\"{newline}family,;\t \"last\"");
let quoted = header.replace('"', "\"\"");
let text = format!("\"{quoted}\"{sep}City{sep}{sep}\r\nAda{sep}Paris{sep}{sep}\nBo{sep}Oslo{sep}{sep}");
assert_eq!(
parse_csv(&text),
vec![vec![header.as_str(), "City", "", ""], vec!["Ada", "Paris", "", ""], vec!["Bo", "Oslo", "", ""]],
"separator {sep:?}, embedded newline {newline:?}"
);
// A multiline field after an ordinary column must not end detection either.
let text = format!("ID{sep}\"{quoted}\"{sep}City\n1{sep}Ada{sep}Paris\n2{sep}Bo{sep}Oslo");
assert_eq!(parse_csv(&text), vec![vec!["ID", header.as_str(), "City"], vec!["1", "Ada", "Paris"], vec!["2", "Bo", "Oslo"]]);
}
}
}
#[test]
fn csv_delimiter_reads_multiline_headers_after_blank_lines() {
for sep in [',', ';', '\t'] {
for newline in ["\n", "\r\n", "\r"] {
let header = format!("Given{newline}Family");
for prefix in ["\n\r\n", "\r", "\r\r"] {
let text = format!("{prefix}\"{header}\"{sep}City\rAda{sep}Paris");
assert_eq!(parse_csv(&text), vec![vec![header.as_str(), "City"], vec!["Ada", "Paris"]]);
}
}
}
}
#[test]
fn recipient_csv_blank_prefix_keeps_columns_without_dropping_literal_records() {
let mut s = Session::new(Document::new());
for sep in [',', ';', '\t'] {
for newline in ["\n", "\r\n", "\r"] {
let header = format!("First{newline}Name");
let csv = format!(" \t{newline}\"{header}\"{sep}Email{newline}Ada{sep}[email protected]");
let result = s.run("mailings.recipients", &json!({"csv": csv})).unwrap();
assert_eq!(result, json!({"fields": [header, "Email"], "records": 1}));
assert_eq!(s.run("mailings.editRecipients", &json!({})).unwrap()["rows"], json!([["Ada", "[email protected]"]]));
}
}
s.run("mailings.recipients", &json!({"csv": " \nName,Email\nAda,[email protected]", "headers": false})).unwrap();
assert_eq!(s.run("mailings.editRecipients", &json!({})).unwrap()["rows"], json!([[" ", ""], ["Name", "Email"], ["Ada", "[email protected]"]]));
s.run("mailings.recipients", &json!({"csv": "\" \",Email\nAda,[email protected]"})).unwrap();
assert_eq!(s.run("mailings.editRecipients", &json!({})).unwrap()["rows"], json!([["Ada", "[email protected]"]]));
let rows = s.merge.rows.clone();
assert!(s.run("mailings.recipients", &json!({"csv": " \t\r\n \r"})).is_err());
assert_eq!(s.merge.rows, rows, "an empty headered list must not replace existing recipients");
assert_eq!(parse_csv(" \nName,Email\nAda,[email protected]")[0], vec![" "], "the shared CSV reader keeps literal whitespace rows");
}
#[test]
fn csv_delimiter_keeps_record_boundaries_and_ties() {
// Later records cannot choose the header's delimiter.
assert_eq!(parse_csv("Name;City\rAda;Paris,,,,\rBo;Oslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris,,,,"], vec!["Bo", "Oslo"]]);
// Existing ties prefer tab, then semicolon, then comma.
assert_eq!(parse_csv("A,B;C\n1,2;3"), vec![vec!["A,B", "C"], vec!["1,2", "3"]]);
assert_eq!(parse_csv("A;B\tC\n1;2\t3"), vec![vec!["A;B", "C"], vec!["1;2", "3"]]);
assert_eq!(parse_csv("Name\nAda,Paris;Oslo"), vec![vec!["Name"], vec!["Ada,Paris;Oslo"]]);
assert!(parse_csv("").is_empty());
assert_eq!(parse_csv("\nName\nAda"), vec![vec!["Name"], vec!["Ada"]]);
// The reader remains permissive about an unterminated quoted cell.
assert_eq!(parse_csv("Name,City\nAda,\"Paris\nOslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris\nOslo"]]);
}
#[test]
fn csv_delimiter_ignores_quoted_text() {
let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n");
+7 -3
View File
@@ -6,6 +6,9 @@ pub(super) const MAX_OFFSET: f32 = 4000.0;
/// Resize and/or move the selected object (dragging its frame or handles).
pub(super) fn bounds(s: &mut Session, v: &Value) -> CmdResult {
if let Some(r) = crate::cmd::canvas::member_bounds(s, v) {
return r;
}
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
(Some(x), Some(y)) => Some((x, y)),
@@ -58,7 +61,7 @@ fn landing(s: &Session, pos: &Pos, to: &Pos) -> Result<Pos, CmdError> {
/// Move the In Line with Text object at `pos` to the text position `to`, where it stays In Line
/// with Text, keeping its character formatting: Word's drag of an inline picture, which lands
/// where its dashed insertion cursor was (#2233, #2234). Dropped on itself, nothing changes.
/// where its insertion cursor was (#2233, #2234). Dropped on itself, nothing changes.
/// Returns the object's position afterwards.
fn move_in_text(s: &mut Session, pos: Pos, to: &Pos) -> Result<Pos, CmdError> {
let to = landing(s, &pos, to)?;
@@ -161,8 +164,9 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
Some(path) => (Pos { story, path, off: 0 }, false),
None => (nearest_line(&layout, page, y, story).ok_or_else(|| CmdError::Params("no text on that page to anchor to".into()))?, true),
};
// Move its character to the anchor (unless it's already in that paragraph).
let at = if anchor.story == pos.story && anchor.path == pos.path && !on_page {
// Move its character to the anchor, unless it's already in that paragraph and drawn on this
// page (one anchored on a later page of it is drawn there, #4250).
let at = if anchor.story == pos.story && anchor.path == pos.path && !on_page && layout.object(pos, page).is_some_and(|o| o.page == page) {
pos.clone()
} else {
let obj = s.doc.para_at(pos).and_then(|p| p.object_at(pos.off)).cloned().ok_or_else(|| CmdError::Failed("object vanished".into()))?;
+24 -2
View File
@@ -12,6 +12,10 @@ pub(super) fn has_object(s: &Session) -> Option<&'static str> {
}
pub(super) fn has_floating(s: &Session) -> Option<&'static str> {
// A canvas member moves inside its canvas.
if crate::cmd::canvas::selected_member(s).is_some() {
return None;
}
match selected(s) {
Some((_, InlineObject::Graphic { .. })) => Some(FROZEN),
Some((_, o)) if o.is_floating() => None,
@@ -51,6 +55,15 @@ pub(super) fn has_movable(s: &Session) -> Option<&'static str> {
}
}
/// `has_movable` for what places an object in the text (wrapping, position, alignment, Move with
/// Text): not for a member picked inside a drawing canvas, which the canvas places.
pub(super) fn has_placeable(s: &Session) -> Option<&'static str> {
if crate::cmd::canvas::selected_member(s).is_some() {
return Some("a shape inside a drawing canvas is placed by the canvas");
}
has_movable(s)
}
/// Word's own ink in a group is kept in the form a group member takes; it can't stand on its own
/// yet, so such a group stays whole.
pub(super) const INK_GROUP: &str = "a group holding Word ink can't be ungrouped yet";
@@ -99,7 +112,9 @@ pub fn object_selection(s: &Session) -> Option<(Pos, &InlineObject)> {
o.is_drawing().then_some((a, o))
}
/// The first picture/shape in the selection, or just before a collapsed caret.
/// The first picture/shape in the selection, or just before a collapsed caret. With a canvas
/// member picked ([`crate::cmd::canvas::selected_member`]), that member, at its canvas's position:
/// the commands that change it go through [`edit_obj`], which changes the member.
pub fn selected(s: &Session) -> Option<(Pos, InlineObject)> {
selected_all(s, 1).into_iter().next()
}
@@ -107,6 +122,9 @@ pub fn selected(s: &Session) -> Option<(Pos, InlineObject)> {
/// The pictures and shapes in the selection (at most `max`), or the one just before a collapsed
/// caret.
pub fn selected_all(s: &Session, max: usize) -> Vec<(Pos, InlineObject)> {
if let Some((pos, _, member)) = crate::cmd::canvas::selected_member(s) {
return vec![(pos, member.clone())];
}
let mut out = Vec::new();
let (a, b) = s.sel.ordered();
let max = if a == b { 1 } else { max };
@@ -175,8 +193,12 @@ pub(super) fn with_obj(s: &mut Session, f: impl Fn(&mut InlineObject)) -> CmdRes
Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)}))
}
/// Change the object at `pos`; returns it afterwards.
/// Change the object at `pos`; returns it afterwards. With a member of the canvas at `pos`
/// picked, the member changes.
pub(crate) fn edit_obj(s: &mut Session, pos: &Pos, f: impl Fn(&mut InlineObject)) -> Result<InlineObject, CmdError> {
if let Some(r) = crate::cmd::canvas::edit_member_object(s, pos, &f) {
return r;
}
let para = s.doc.para_mut(pos.story, &pos.path)?;
let o = para.object_at_mut(pos.off).ok_or_else(|| CmdError::Failed("object vanished".into()))?;
f(o);
+13 -10
View File
@@ -2,8 +2,8 @@ use super::arrange::{MAX_OFFSET, bounds, copy_to, move_with_text, unalign};
use super::group::{add_object, group, ungroup};
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, size};
use super::select::{
all_objects, alt_text, can_group, edit_obj, has_floating, has_group, has_movable, has_object, has_picture, has_shape, has_shape_or_canvas,
has_sizable, obj_size, objects_list, selected, with_float, with_obj,
all_objects, alt_text, can_group, edit_obj, has_floating, has_group, has_movable, has_object, has_picture, has_placeable, has_shape,
has_shape_or_canvas, has_sizable, obj_size, objects_list, selected, with_float, 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};
@@ -193,17 +193,17 @@ pub fn specs() -> Vec<CommandSpec> {
with_float(s, |f| f.wrap = wrap)
})
.params(r#"{"wrap": "inline|square|tight|through|topAndBottom|behindText|inFrontOfText"}"#)
.when(has_movable),
.when(has_placeable),
CommandSpec::new("arrange.wrapText", "Wrap Text Sides", "Layout › Arrange", |s, v| {
let side = p::str(v, "side").unwrap_or("bothSides");
let side = WrapText::from_ooxml(side).ok_or_else(|| CmdError::Params(format!("unknown side {side:?}")))?;
with_float(s, |f| f.wrap_text = side)
})
.params(r#"{"side": "bothSides|left|right|largest"} (the sides of the selected Square, Tight or Through object text flows on; largest: the wider side, line by line)"#)
.when(has_movable),
.when(has_placeable),
CommandSpec::new("arrange.moveWithText", "Move with Text", "Layout › Arrange › Wrap Text", |s, v| move_with_text(s, p::bool(v, "value").unwrap_or(true)))
.params(r#"{"value": bool} (true: Move with Text, the floating object's vertical position follows its paragraph; false: Fix Position on Page. It stays where it is)"#)
.when(has_floating),
.when(|s| has_placeable(s).or_else(|| has_floating(s))),
CommandSpec::new("arrange.position", "Position", "Layout › Arrange", |s, v| {
let preset = p::str(v, "preset").unwrap_or("middleCenter").to_string();
let (x, y) = (p::f32(v, "x"), p::f32(v, "y"));
@@ -224,9 +224,9 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"preset"?: "topLeft|topCenter|topRight|middleLeft|middleCenter|middleRight|bottomLeft|bottomCenter|bottomRight", "x"?: pt, "y"?: pt}"#)
.when(has_movable),
CommandSpec::new("arrange.bringForward", "Bring Forward", "Layout › Arrange", |s, _| with_float(s, |f| f.wrap = Wrap::InFrontOfText)).when(has_movable),
CommandSpec::new("arrange.sendBackward", "Send Backward", "Layout › Arrange", |s, _| with_float(s, |f| f.wrap = Wrap::BehindText)).when(has_movable),
.when(has_placeable),
CommandSpec::new("arrange.bringForward", "Bring Forward", "Layout › Arrange", |s, _| with_float(s, |f| f.wrap = Wrap::InFrontOfText)).when(has_placeable),
CommandSpec::new("arrange.sendBackward", "Send Backward", "Layout › Arrange", |s, _| with_float(s, |f| f.wrap = Wrap::BehindText)).when(has_placeable),
CommandSpec::new("arrange.align", "Align", "Layout › Arrange", |s, v| {
let h = p::str(v, "value").unwrap_or("center").to_string();
let tw = crate::cmd::page::sect(s).text_width();
@@ -245,17 +245,20 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"value": "left|center|right"}"#)
.when(has_movable),
.when(has_placeable),
CommandSpec::new("arrange.selectionPane", "Selection Pane", "Layout › Arrange", objects_list).pure(),
CommandSpec::new("arrange.bounds", "Move or Resize", "Layout › Arrange", bounds)
.params(r#"{"width"?: pt, "height"?: pt, "x"?: pt, "y"?: pt, "page"?: n, "to"?: Pos} (x/y: the top-left on page `page` (0-based, default its page); moving an inline object by x/y floats it. to: an In Line with Text object moves to that text position and stays inline, as a drag does)"#)
.when(has_movable),
CommandSpec::new("arrange.copyTo", "Copy to", "Layout › Arrange", copy_to)
.params(r#"{"x": pt, "y": pt, "page"?: n} | {"to": Pos} (Ctrl+drag: a copy of the selected object lands with its top-left there, or an In Line with Text one at the text position `to`, and is selected; the original and the clipboard stay as they were)"#)
.when(has_movable),
.when(has_placeable),
CommandSpec::new("arrange.nudge", "Nudge", "Layout › Arrange", |s, v| {
let d = |k| p::f32(v, k).unwrap_or(0.0).clamp(-MAX_OFFSET, MAX_OFFSET);
let (dx, dy) = (d("dx"), d("dy"));
if let Some(r) = crate::cmd::canvas::member_nudge(s, dx, dy) {
return r;
}
unalign(s)?;
with_float(s, |f| {
f.x = (f.x + dx).clamp(-MAX_OFFSET, MAX_OFFSET);
+63
View File
@@ -14,6 +14,69 @@ fn object_area(s: &mut Session) -> wordcraft_layout::hit::ObjectHit {
s.layout().find_object(0, |o| o.text_box.is_none()).unwrap()
}
/// #4250: a shape dragged into the middle of a page that only continues a long paragraph
/// stays there, as in Word: anchored at the line beside it, it's drawn on that page, not
/// thrown back to the page the paragraph starts on. One undo step puts it back.
#[test]
fn a_shape_dropped_on_a_page_a_paragraph_continues_onto_stays_there() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("text.insert", &json!({"text": "The quick brown fox jumps over the lazy dog. ".repeat(400)})).unwrap();
s.run("caret.docStart", &json!({})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 250, "width": 100, "height": 50})).unwrap();
assert!(s.layout().pages.len() > 2);
let before = (object_area(&mut s), s.undo_depth());
s.run("arrange.bounds", &json!({"page": 1, "x": 100, "y": 275})).unwrap();
let o = object_area(&mut s);
assert_eq!(o.page, 1, "on the page it was dropped on: {o:?}");
assert!((o.rect.x - 100.0).abs() < 0.5 && (o.rect.y - 275.0).abs() < 0.5, "where it was dropped: {:?}", o.rect);
assert_eq!(s.undo_depth(), before.1 + 1);
s.run("edit.undo", &json!({})).unwrap();
let back = object_area(&mut s);
assert_eq!((back.page, back.rect), (before.0.page, before.0.rect));
}
/// #4250: and dragged back onto the page the paragraph starts on, it stays there: its anchor
/// goes back to the paragraph's start rather than staying on the later page's line.
#[test]
fn a_shape_dragged_back_to_the_page_its_paragraph_starts_on_stays_there() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("text.insert", &json!({"text": "The quick brown fox jumps over the lazy dog. ".repeat(400)})).unwrap();
s.run("caret.docStart", &json!({})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
s.run("arrange.bounds", &json!({"page": 1, "x": 100, "y": 275, "width": 100, "height": 50})).unwrap();
let before = (object_area(&mut s), s.undo_depth());
assert!(before.0.page == 1 && before.0.off > 0, "anchored on page 2's line: {:?}", before.0);
s.run("arrange.bounds", &json!({"page": 0, "x": 120, "y": 300})).unwrap();
let o = object_area(&mut s);
assert_eq!((o.page, o.off), (0, 0), "on the page it was dropped on, anchored at the paragraph's start: {o:?}");
assert!((o.rect.x - 120.0).abs() < 0.5 && (o.rect.y - 300.0).abs() < 0.5, "where it was dropped: {:?}", o.rect);
assert_eq!(s.undo_depth(), before.1 + 1);
}
/// #4262: dropped beside the first line after a page break inside a paragraph, a shape stays
/// on the page it was dropped on, anchored in that line.
#[test]
fn a_shape_dropped_just_after_a_page_break_in_a_paragraph_stays_there() {
let mut s = Session::new(wordcraft_doc::Document::new());
let text = "The quick brown fox jumps over the lazy dog. ";
s.run("text.insert", &json!({"text": text.repeat(20)})).unwrap();
s.run("insert.pageBreak", &json!({})).unwrap();
s.run("text.insert", &json!({"text": text.repeat(40)})).unwrap();
assert_eq!(s.doc.body.len(), 1, "one paragraph");
s.run("caret.docStart", &json!({})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 250, "width": 100, "height": 50})).unwrap();
s.run("arrange.bounds", &json!({"page": 1, "x": 100, "y": 80})).unwrap();
let o = object_area(&mut s);
let after_break = text.len() * 20 + wordcraft_doc::para::PAGE_BREAK.len_utf8();
assert_eq!((o.page, o.off), (1, after_break), "on the page it was dropped on, anchored right after the break: {o:?}");
assert!((o.rect.x - 100.0).abs() < 0.5 && (o.rect.y - 80.0).abs() < 0.5, "where it was dropped: {:?}", o.rect);
}
/// What a click and a handle or body drag do in the editor (#142, #82): hit-test the object,
/// select it, then resize and move it with `arrange.bounds`.
fn click_resize_and_drag(insert: &str, params: Value) {
+22 -8
View File
@@ -652,19 +652,33 @@ pub(crate) fn typing_pos(s: &Session, p: &Pos) -> Pos {
if para.objects.is_empty() {
return p.clone();
}
let editable: Vec<u32> = s.doc.perm_ranges().iter().filter(|r| editable_by(r, &s.author)).map(|r| r.id).collect();
let is_start = |off: usize| matches!(para.object_at(off), Some(InlineObject::PermStart { id, .. }) if editable.contains(id));
let is_end = |off: usize| matches!(para.object_at(off), Some(InlineObject::PermEnd { id }) if editable.contains(id));
let Some(before) = para.text.get(..p.off) else { return p.clone() };
let Some(after) = para.text.get(p.off..) else { return p.clone() };
if !before.ends_with(OBJ) && !after.starts_with(OBJ) {
return p.clone();
}
let editable: HashSet<u32> = s.doc.perm_ranges().iter().filter(|r| editable_by(r, &s.author)).map(|r| r.id).collect();
// Count the preceding objects once. Each adjacent marker can then use the matching
// object directly, forwards for starts and backwards for ends, even with short storage.
let index = before.chars().filter(|c| *c == OBJ).count();
let w = OBJ.len_utf8();
let mut off = p.off;
if is_start(off) {
while is_start(off) {
off += w;
for (ch, object) in after.chars().zip(para.objects.iter().skip(index)) {
if ch != OBJ || !matches!(object, InlineObject::PermStart { id, .. } if editable.contains(id)) {
break;
}
off += w;
}
if off > p.off {
return Pos { off, ..p.clone() };
}
while off >= w && is_end(off - w) {
off -= w;
if let Some(objects) = para.objects.get(..index) {
for (ch, object) in before.chars().rev().zip(objects.iter().rev()) {
if ch != OBJ || !matches!(object, InlineObject::PermEnd { id } if editable.contains(id)) {
break;
}
off -= w;
}
}
Pos { off, ..p.clone() }
}
+156
View File
@@ -922,3 +922,159 @@ fn legacy_password_is_verified_and_unknown_forms_refused() {
assert!(e.to_string().contains(super::UNSUPPORTED_PASSWORD));
assert!(super::enforced(&s.doc));
}
/// Consecutive permission boundaries must not recount the paragraph prefix or search all
/// editable IDs once per marker. Both ends are used by typing and Enter.
#[test]
fn typing_boundary_many_permission_markers_is_not_quadratic() {
use wordcraft_doc::para::Run;
let cpu = || std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse::<u64>().ok();
let measure = |n: usize, at_end: bool| {
let mut p = wordcraft_doc::Paragraph::new();
p.text.push_str("λ prefix ");
let start = p.text.len();
for i in 0..n {
p.text.push(OBJ);
p.objects.push(InlineObject::PermStart { id: i as u32, group: "everyone".into(), editor: String::new() });
}
p.text.push_str("body");
let end = p.text.len();
for i in 0..n {
p.text.push(OBJ);
p.objects.push(InlineObject::PermEnd { id: i as u32 });
}
let after = p.text.len();
p.runs.push(Run { len: p.text.len(), props: CharProps::default() });
let mut doc = Document::new();
doc.body = vec![Block::Para(p).into()];
doc.settings.protection = Some("readOnly".into());
let s = Session::new(doc);
let at = Pos::body(0, if at_end { after } else { start });
let expected = Pos::body(0, if at_end { end } else { start + n * OBJ.len_utf8() });
let before = cpu();
for _ in 0..3 {
assert_eq!(typing_pos(std::hint::black_box(&s), &at), expected);
}
match (before, cpu()) {
(Some(a), Some(b)) if b > a => Some((b - a) as f64 * 1e-9),
_ => None,
}
};
for at_end in [false, true] {
let (small, large) = (measure(2_000, at_end), measure(16_000, at_end));
let (Some(a), Some(b)) = (small, large) else {
eprintln!("Typing boundary: CPU counter unavailable; semantic checks passed, timing assertion skipped");
continue;
};
eprintln!("Typing boundary end={at_end}: small={a:.9}s large={b:.9}s ratio={:.2}", b / a);
assert!(b < a * 24.0 + 0.005, "8x permission markers must not take quadratic boundary work: {a:.9}s -> {b:.9}s");
}
}
#[test]
fn typing_boundary_keeps_author_precedence_and_malformed_pairing() {
use wordcraft_doc::para::Run;
// Frozen boundary semantics from before the one-pass lookup. This oracle deliberately
// uses object_at independently of the new traversal, including malformed storage.
let original = |s: &Session, p: &Pos| {
if !matches!(s.doc.settings.protection.as_deref(), Some("readOnly" | "comments")) {
return p.clone();
}
let Some(para) = s.doc.para_at(p) else { return p.clone() };
if para.objects.is_empty() {
return p.clone();
}
let editable: Vec<u32> = s.doc.perm_ranges().iter().filter(|r| editable_by(r, &s.author)).map(|r| r.id).collect();
let start = |off| matches!(para.object_at(off), Some(InlineObject::PermStart { id, .. }) if editable.contains(id));
let end = |off| matches!(para.object_at(off), Some(InlineObject::PermEnd { id }) if editable.contains(id));
let mut off = p.off;
if start(off) {
while start(off) {
off += OBJ.len_utf8();
}
} else {
while off >= OBJ.len_utf8() && end(off - OBJ.len_utf8()) {
off -= OBJ.len_utf8();
}
}
Pos { off, ..p.clone() }
};
let objects = [
InlineObject::PermStart { id: 1, group: "everyone".into(), editor: String::new() },
InlineObject::PermStart { id: 2, group: String::new(), editor: " ALICE ".into() },
InlineObject::PermStart { id: 3, group: String::new(), editor: "alice".into() },
InlineObject::PermEnd { id: 1 },
InlineObject::PermEnd { id: 3 },
InlineObject::BookmarkStart { name: "Original".into() },
InlineObject::PermEnd { id: 7 },
InlineObject::PermStart { id: 7, group: String::new(), editor: "Bob".into() },
];
for text in
[format!("λ{}x{}終", OBJ.to_string().repeat(4), OBJ.to_string().repeat(4)), OBJ.to_string().repeat(9), format!("λ{OBJ}{OBJ}x{OBJ}{OBJ}{OBJ}")]
{
for count in 0..=objects.len() {
for mode in [None, Some("readOnly"), Some("comments"), Some("forms"), Some("trackedChanges")] {
let mut p = wordcraft_doc::Paragraph::new();
p.text = text.clone();
p.objects = objects[..count].to_vec();
p.runs.push(Run { len: p.text.len(), props: CharProps::default() });
let mut doc = Document::new();
doc.body = vec![Block::Para(p).into()];
doc.settings.protection = mode.map(str::to_string);
let mut s = Session::new(doc);
s.author = " Alice ".into();
for off in 0..=text.len() + 1 {
let at = Pos::body(0, off);
assert_eq!(typing_pos(&s, &at), original(&s, &at), "mode={mode:?} count={count} off={off} text={text:?}");
}
}
}
}
let mut s = Session::new(Document::from_text("outside"));
s.doc.settings.protection = Some("readOnly".into());
assert_eq!(typing_pos(&s, &Pos::body(99, 0)), Pos::body(99, 0));
}
#[test]
fn typing_boundary_keeps_duplicate_ids_across_stories_and_start_precedence() {
use wordcraft_doc::para::Run;
let paragraph = |text: String, objects| wordcraft_doc::Paragraph {
runs: vec![Run { len: text.len(), props: CharProps::default() }],
text,
objects,
..Default::default()
};
let mut doc = Document::new();
doc.body = vec![
Block::Para(paragraph(
format!("{OBJ}x{OBJ}"),
vec![InlineObject::PermStart { id: 1, group: String::new(), editor: "Bob".into() }, InlineObject::PermEnd { id: 1 }],
))
.into(),
];
doc.add_part(
wordcraft_doc::PartKind::Header,
vec![
Block::Para(paragraph(
format!("{OBJ}y{OBJ}"),
vec![InlineObject::PermStart { id: 1, group: "everyone".into(), editor: String::new() }, InlineObject::PermEnd { id: 1 }],
))
.into(),
],
);
doc.settings.protection = Some("comments".into());
let mut s = Session::new(doc);
s.author = "Alice".into();
// Preserve the existing document-wide ID membership, even for a duplicate in another story.
assert_eq!(typing_pos(&s, &Pos::body(0, 0)), Pos::body(0, OBJ.len_utf8()));
assert_eq!(typing_pos(&s, &Pos::body(0, 7)), Pos::body(0, 4));
s.doc.body = vec![
Block::Para(paragraph(
format!("{OBJ}{OBJ}x"),
vec![InlineObject::PermEnd { id: 1 }, InlineObject::PermStart { id: 1, group: "everyone".into(), editor: String::new() }],
))
.into(),
];
// A start to the right wins over an end to the left.
assert_eq!(typing_pos(&s, &Pos::body(0, 3)), Pos::body(0, 6));
}
+4
View File
@@ -219,6 +219,10 @@ pub struct Session {
/// More pictures and shapes selected along with the one the selection holds (Shift+click),
/// for Group. Cleared by any edit or selection change other than adding to it.
pub also_selected: Vec<Pos>,
/// The member of the selected Drawing Canvas picked on its own (#2637), which Shape Format,
/// Delete, Copy and the frame act on; see [`crate::cmd::canvas::selected_member`]. Cleared by
/// any selection change, caret movement or undo.
pub member: Option<crate::cmd::canvas::CanvasMember>,
/// Column (block) selection, if one was made (see [`Session::column_segments`]).
pub column: Option<ColumnBlock>,
/// Column selection mode (Ctrl+Shift+F8): caret movement extends the block.
+10
View File
@@ -276,6 +276,8 @@ impl Session {
ime_state_exhausted: _,
pending_ime_application_change: _,
ime_origin: _,
// A picked Drawing Canvas member is cleared by a switch, not kept per document.
member: _,
others: _,
order: _,
untitled_count: _,
@@ -376,6 +378,8 @@ impl Session {
swap(&mut self.widened, widened);
swap(&mut self.edit_marks, edit_marks);
swap(&mut self.go_back_step, go_back_step);
// A picked Drawing Canvas member (#2637) belongs to the document left behind.
self.member = None;
}
/// Make document `id` active without anything else a switch by the user does.
@@ -405,6 +409,12 @@ impl Session {
id == self.document_id || self.others.iter().any(|d| d.document_id == id)
}
/// Whether the open document `id` has changes that aren't written to a file yet: the
/// active document's own flag, or a background document's.
pub fn document_dirty(&self, id: u64) -> bool {
if id == self.document_id { self.dirty } else { self.others.iter().any(|d| d.document_id == id && d.dirty) }
}
/// Every open document in the order they were opened, the active one included.
pub fn documents(&self) -> Vec<DocInfo> {
self.order
+1
View File
@@ -150,6 +150,7 @@ impl Session {
math_latex: false,
math_normal_text: false,
also_selected,
member: None,
prefs: Prefs::default(),
system_region: Default::default(),
keymap: crate::KeyMap::default(),
+13 -1
View File
@@ -185,7 +185,10 @@ impl Session {
let mutates = spec.mutates;
let ime_caret_before = self.current_ime_caret_state();
let rev_before = self.rev;
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| crate::cmd::column::dispatch(self, id, mutates, run, params)));
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match crate::cmd::canvas::member_command(self, id, params) {
Some(r) => r,
None => crate::cmd::column::dispatch(self, id, mutates, run, params),
}));
let mut result = match result {
Ok(r) => r,
Err(p) => {
@@ -391,6 +394,15 @@ impl Session {
if !matches!(id, "select.addObject" | "arrange.ungroup" | "shape.fill" | "shape.effects") && (spec.mutates || self.sel != *sel_before) {
self.also_selected.clear();
}
// A canvas member stays picked while its canvas does and nothing else is selected.
if id != "select.member"
&& (self.sel != *sel_before
|| id.starts_with("select.")
|| id.starts_with("caret.")
|| matches!(id, "edit.undo" | "edit.undoTo" | "edit.redo"))
{
self.member = None;
}
self.note_typing(id, before_doc.as_ref().map(|b| &b.0), sel_before);
}
+3
View File
@@ -23,6 +23,7 @@ impl Session {
self.pending = None;
self.typing = None;
self.also_selected.clear();
self.member = None;
self.column = None;
self.column_mode = false;
self.widened = None;
@@ -155,6 +156,7 @@ impl Session {
#[cfg(not(target_arch = "wasm32"))]
recovery_slot: _,
also_selected: _,
member: _,
// Column selection and a widened selection's ends, like `sel`'s shape: valid only while
// `sel` matches them.
column: _,
@@ -211,6 +213,7 @@ impl Session {
self.doc = doc;
self.sel = sel;
self.also_selected.clear();
self.member = None;
self.history.truncate(history_len);
self.redo = redo;
self.typing_open = typing_open;
+2
View File
@@ -141,6 +141,8 @@ impl Session {
self.page_hint = page_hint;
self.column_mode = column_mode;
self.math = math;
// A picked Drawing Canvas member (#2637) is not part of a view's saved selection.
self.member = None;
if current {
self.hf_return = hf_return;
self.typing_open = typing_open;
+32 -2
View File
@@ -463,10 +463,26 @@ fn hhea_line(ascender: i16, descender: i16, line_gap: i16) -> (f64, f64) {
(f64::from(ascender) + f64::from(line_gap.max(0)), f64::from(descender).abs())
}
/// The line (ascent, descent) in units of an `upem` em that Word gives the classic PostScript
/// families: their Windows counterparts' spacing, though Apple's own Times and Courier are one em
/// tall (hhea 0.75 / -0.25, no gap). Measured in Word for Mac on synthetic documents (single
/// spacing, 11 and 20 pt): Times lines lie exactly as far apart as Times New Roman's (hhea 1825 /
/// -443, gap 87 per 2048), Courier's as Courier New's (1705 / -615, no gap). On Windows, Word
/// draws a "Times" document in Times New Roman anyway.
fn borrowed_line(family: &str, upem: f64) -> Option<(f64, f64)> {
let (a, d) = match family.trim().to_ascii_lowercase().as_str() {
"times" => hhea_line(1825, -443, 87),
"courier" => hhea_line(1705, -615, 0),
_ => return None,
};
Some((a * upem / 2048.0, d * upem / 2048.0))
}
/// Line metrics for a face in font units: (ascent, descent), both positive, the way word
/// processors measure single line spacing: the hhea values with the line gap above the ascent
/// (Word puts the first baseline that far below the line top), falling back to OS/2
/// usWinAscent/usWinDescent.
/// usWinAscent/usWinDescent; Times and Courier borrow their Windows counterparts' (see
/// [`borrowed_line`]).
pub fn line_metrics(face: &crate::FontFace) -> (f64, f64) {
static CACHE: OnceLock<Mutex<HashMap<u32, (f64, f64)>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
@@ -474,7 +490,9 @@ pub fn line_metrics(face: &crate::FontFace) -> (f64, f64) {
return *v;
}
let mut v = (face.ascent.max(1.0), face.descent.abs());
if let Some(f) = face.skrifa() {
if let Some(m) = borrowed_line(&face.family, face.upem) {
v = m;
} else if let Some(f) = face.skrifa() {
// hhea ascender + descender + line gap (Word on macOS), the gap above the ascent; OS/2
// win metrics only when the hhea values are missing, and never more than twice the em.
let hhea = f.hhea().ok().map(|h| hhea_line(h.ascender().to_i16(), h.descender().to_i16(), h.line_gap().to_i16()));
@@ -505,6 +523,18 @@ mod tests {
assert_eq!(hhea_line(1000, i16::MIN, 0), (1000.0, 32768.0));
}
#[test]
fn times_and_courier_take_their_windows_counterparts_line() {
// Apple's Times has 2048 units to the em, Times New Roman's line is 1.15 em.
assert_eq!(borrowed_line("Times", 2048.0), Some((1912.0, 443.0)));
assert_eq!(borrowed_line(" times ", 1000.0), Some((1912.0 / 2.048, 443.0 / 2.048)));
assert_eq!(borrowed_line("Courier", 2048.0), Some((1705.0, 615.0)));
// Only those two: the Windows fonts themselves, and other Mac fonts, keep their own.
for family in ["Times New Roman", "Courier New", "Helvetica", "Hoefler Text", "Palatino", ""] {
assert_eq!(borrowed_line(family, 2048.0), None, "{family}");
}
}
#[test]
fn family_cache_stays_bounded() {
for i in 0..(FAMILY_CACHE_MAX + 50) {
+12 -2
View File
@@ -332,7 +332,14 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
prev_end = push_para(&mut items, (story, &path), &pl, (0, pl.lines.len()), (0.0, y + lead), width, edges);
// Pictures, shapes and text boxes: drawn, their areas and text boxes' text.
if !p.objects.is_empty() {
let at = ObjFrame { page: frame, col: (0.0, width), para_y: para_top, table_chr: table.map(|t| &t.chr), pinned: Some(&pinned) };
let at = ObjFrame {
page: frame,
col: (0.0, width),
para_y: para_top,
table_chr: table.map(|t| &t.chr),
pinned: Some(&pinned),
late: None,
};
let (back, front) = place_objects(
ctx,
&ObjectPlacement {
@@ -616,7 +623,10 @@ pub(crate) fn joined(doc: &Document, blocks: &Blocks, i: usize, j: Option<usize>
/// The room a paragraph's top or bottom border takes in the text flow: its distance from the
/// text plus its width (Word).
fn border_room(b: Option<Border>) -> f32 {
b.filter(Border::is_visible).map_or(0.0, |b| b.space + b.width)
b.filter(Border::is_visible).map_or(0.0, |b| {
let extent = b.space + b.width;
if extent.is_finite() { extent.max(0.0) } else { 0.0 }
})
}
/// How a piece of a paragraph meets the paragraphs around it: the room taken by its top and
+197 -4
View File
@@ -275,14 +275,35 @@ fn cell_clip(clips: &Clips, story: StoryRef, path: &[u32]) -> Option<Rect> {
/// The text boxes among `items` whose text is warped (Text Effects › Transform, drawn bent): their
/// story, frame and warp. Empty, without a walk of the document, when none is.
fn warped_boxes(doc: &Document, items: &[Placed]) -> Vec<(u32, Rect, wordcraft_doc::wordart::TextWarp)> {
// Keep only requested offsets. A page may show a few boxes from a much longer paragraph,
// and several placements may share an offset or a text-box story.
let mut needed: HashMap<_, HashMap<_, Option<&wordcraft_doc::wordart::TextWarp>>> = HashMap::new();
for it in items {
if let Placed::Object { story, path, off, text_box: Some(_), .. } = it {
needed.entry((*story, path)).or_default().insert(*off, None);
}
}
for ((story, path), offsets) in &mut needed {
let Some(p) = doc.para(*story, path) else { continue };
offsets.retain(|off, _| p.text.get(*off..).is_some_and(|tail| tail.starts_with(wordcraft_doc::para::OBJ)));
let Some(last) = offsets.keys().max().copied() else { continue };
// Stop at the last requested byte offset, including when it precedes a long run of
// ordinary text. Pair markers and objects exactly as Paragraph::objects_with_offsets.
let markers = p.text.char_indices().take_while(|(off, _)| *off <= last).filter(|(_, c)| *c == wordcraft_doc::para::OBJ);
for ((off, _), object) in markers.zip(&p.objects) {
if let Some(warp) = offsets.get_mut(&off)
&& let InlineObject::Shape { extra, .. } = object
{
*warp = extra.warp.as_ref().filter(|w| !w.is_plain());
}
}
}
items
.iter()
.filter_map(|it| {
let Placed::Object { rect, story, path, off, text_box: Some(id), .. } = it else { return None };
match doc.para(*story, path)?.object_at(*off)? {
InlineObject::Shape { extra, .. } => extra.warp.clone().filter(|w| !w.is_plain()).map(|w| (*id, *rect, w)),
_ => None,
}
let warp = needed.get(&(*story, path))?.get(off)?.as_ref()?;
Some((*id, *rect, (*warp).clone()))
})
.collect()
}
@@ -556,3 +577,175 @@ mod tests_clips {
});
}
}
#[cfg(test)]
mod tests_warp_lookups {
use super::*;
use wordcraft_doc::para::{OBJ, ShapeKind};
use wordcraft_doc::wordart::TextWarp;
use wordcraft_doc::{Block, CharProps, Paragraph, Path};
fn shape(warp: Option<TextWarp>) -> InlineObject {
InlineObject::Shape {
kind: ShapeKind::Rectangle,
w: 100.0,
h: 30.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story: Some(7),
freeform: None,
effects: Default::default(),
extra: wordcraft_doc::connector::ShapeExtra { warp, ..Default::default() },
}
}
fn placed(story: StoryRef, path: Path, off: usize, id: Option<u32>) -> Placed {
Placed::Object {
rect: Rect::new(off as f32, 2.0, 100.0, 30.0),
spin: Default::default(),
story,
path,
off,
text_box: id,
wrap: Default::default(),
origin: Default::default(),
}
}
#[test]
fn text_box_warp_lookups_preserve_item_order_and_missing_objects() {
let arch = TextWarp::new("textArchUp").unwrap();
let wave = TextWarp::new("textWave1").unwrap();
let objects = vec![
InlineObject::BookmarkStart { name: "original".into() },
shape(None),
shape(TextWarp::new("textPlain")),
shape(Some(arch.clone())),
InlineObject::FieldEnd,
shape(Some(wave.clone())),
];
let mut p = Paragraph::new();
p.text = format!("é{}λ", OBJ.to_string().repeat(objects.len() + 1));
p.runs = vec![wordcraft_doc::para::Run { len: p.text.len(), props: CharProps::default() }];
p.objects = objects;
let mut d = Document::from_text("");
d.body = vec![Block::Para(p).into()];
let item = |index, id| placed(StoryRef::Body, Path::top(0), 2 + index * OBJ.len_utf8(), id);
let items = vec![
item(5, Some(11)),
item(0, Some(8)),
item(1, Some(9)),
item(2, Some(10)),
item(3, Some(11)),
item(3, Some(12)),
item(5, None),
item(6, Some(13)),
placed(StoryRef::Body, Path::top(0), 3, Some(14)),
placed(StoryRef::Body, Path::top(0), 0, Some(14)),
placed(StoryRef::Body, Path::top(1), 2, Some(14)),
placed(StoryRef::Part(7), Path::top(0), 2, Some(14)),
];
let got = warped_boxes(&d, &items);
assert_eq!(
got,
vec![
(11, Rect::new(17.0, 2.0, 100.0, 30.0), wave),
(11, Rect::new(11.0, 2.0, 100.0, 30.0), arch.clone()),
(12, Rect::new(11.0, 2.0, 100.0, 30.0), arch)
]
);
// Extra stored objects without a matching marker are not addressable.
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.text.truncate(2 + 4 * OBJ.len_utf8());
assert_eq!(warped_boxes(&d, &items), got[1..]);
assert!(warped_boxes(&d, &[]).is_empty());
}
#[test]
fn text_box_warp_lookups_keep_paragraph_and_story_keys_separate() {
let presets = ["textArchUp", "textWave1", "textArchDown", "textSlantUp"];
let para = |preset| {
let mut p = Paragraph::new();
p.text = OBJ.to_string();
p.runs = vec![wordcraft_doc::para::Run { len: p.text.len(), props: CharProps::default() }];
p.objects = vec![shape(TextWarp::new(preset))];
p
};
let mut d = Document::from_text("");
d.body = vec![Block::Para(para(presets[0])).into(), Block::Para(para(presets[1])).into()];
let mut table = wordcraft_doc::Table::new(1, 1, 100.0);
table.rows[0].cells[0].blocks = vec![Block::Para(para(presets[2])).into()];
d.body.push(Block::Table(table).into());
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![Block::Para(para(presets[3])).into()]);
let items = vec![
placed(StoryRef::Body, Path::top(0), 0, Some(1)),
placed(StoryRef::Body, Path::top(1), 0, Some(1)),
placed(StoryRef::Body, Path(vec![2, 0, 0, 0]), 0, Some(1)),
placed(StoryRef::Part(id), Path::top(0), 0, Some(1)),
];
assert_eq!(warped_boxes(&d, &items), presets.map(|p| (1, Rect::new(0.0, 2.0, 100.0, 30.0), TextWarp::new(p).unwrap())));
}
/// #3614: deciding whether text boxes have a warp is part of every page repaint,
/// including pages whose boxes are all plain. Measure discovery without shaping text.
#[test]
#[ignore = "performance regression; run explicitly"]
fn text_box_warp_lookups_do_not_rescan_the_paragraph_prefix() {
let make = |n: usize| {
let mut objects = Vec::new();
let mut items = Vec::new();
for i in 0..n {
objects.extend((0..16).map(|_| InlineObject::BookmarkEnd { name: "padding".into() }));
items.push(placed(StoryRef::Body, Path::top(0), objects.len() * OBJ.len_utf8(), Some(i as u32)));
objects.push(shape(None));
}
let mut p = Paragraph::new();
p.text = OBJ.to_string().repeat(objects.len());
p.runs = vec![wordcraft_doc::para::Run { len: p.text.len(), props: CharProps::default() }];
p.objects = objects;
let mut d = Document::from_text("");
d.body = vec![Block::Para(p).into()];
(d, items)
};
let (small, big) = (make(500), make(4000));
let scan = |(doc, items): &(Document, Vec<Placed>)| assert!(std::hint::black_box(warped_boxes(doc, items)).is_empty());
let (a, b, ratio) = crate::tests::cost_ratio(8, || scan(&small), || scan(&big));
eprintln!("text-box warp discovery: {a:.6}s -> {b:.6}s, {ratio:.2}x for 8x boxes");
assert!(ratio < 24.0, "text-box warp discovery rescanned paragraph prefixes: {ratio:.2}x");
}
/// #3614: an invalid request must not extend the prefix walk into unrelated trailing text.
#[test]
#[ignore = "performance regression; run explicitly"]
fn text_box_warp_lookups_stop_at_the_last_valid_requested_offset() {
let make = |suffix: usize| {
let mut p = Paragraph::new();
p.text = format!("{OBJ}{}", "x".repeat(suffix));
p.runs = vec![wordcraft_doc::para::Run { len: p.text.len(), props: CharProps::default() }];
p.objects = vec![shape(TextWarp::new("textArchUp"))];
let mut d = Document::from_text("");
d.body = vec![Block::Para(p).into()];
d
};
let (short, long) = (make(0), make(1_000_000));
let items = vec![
placed(StoryRef::Body, Path::top(0), 0, Some(7)),
placed(StoryRef::Body, Path::top(0), usize::MAX, Some(8)),
placed(StoryRef::Body, Path::top(0), 1, Some(9)),
placed(StoryRef::Body, Path::top(0), OBJ.len_utf8(), Some(10)),
];
let expected = vec![(7, Rect::new(0.0, 2.0, 100.0, 30.0), TextWarp::new("textArchUp").unwrap())];
assert_eq!(warped_boxes(&short, &items), expected);
assert_eq!(warped_boxes(&long, &items), expected);
let scan = |doc: &Document| {
for _ in 0..1000 {
std::hint::black_box(warped_boxes(doc, &items));
}
};
let (a, b, _) = crate::tests::cost_ratio(1, || scan(&short), || scan(&long));
eprintln!("text-box warp suffix: {a:.6}s -> {b:.6}s for 1000 calls with one million trailing bytes");
assert!(b <= a * 8.0 + 0.005, "text-box warp lookup scanned the suffix: {a:.6}s -> {b:.6}s");
}
}
+263 -12
View File
@@ -3,8 +3,8 @@ use super::page::{PageBuilder, PageFrame};
use super::placed::Placed;
use super::table_flow::footer_table_wraps;
use super::{
Anchor, Arc, CharProps, Document, Float, FloatAlign, HashMap, HideDeleted, InlineObject, Level, ParaLayout, Paragraph, Path, Point, Rect, Spin,
StoryRef, Wrap, WrapText, contour, display, para, textbox,
Anchor, Arc, CharProps, Document, Float, FloatAlign, HashMap, HideDeleted, InlineObject, Level, LineEnd, ParaLayout, Paragraph, Path, Point,
Rect, Spin, StoryRef, Wrap, WrapText, contour, display, para, textbox,
};
/// Which of `p`'s objects (by index) the layout leaves out ([`para::left_out`]): anchored in hidden
@@ -336,14 +336,133 @@ fn group_members(o: &InlineObject, rect: Rect) -> Vec<(Rect, &InlineObject)> {
/// page's wrap areas (its area as placed now). Without `place` (a later piece of the paragraph
/// broken again for another column) the floats stay where its first piece placed and drew them:
/// they aren't placed again in the new column, and their record for the page they are drawn on
/// ([`EarlyFloats`]) stands.
/// ([`EarlyFloats`]) stands. Floats anchored on a later page ([`late_floats`]), and those in
/// `force`, aren't placed here: the paragraph is laid out without them, and they're returned.
pub(crate) fn anchor_floats(
ctx: &mut Ctx,
pb: &mut PageBuilder,
anchor: FloatAnchor,
force: &[usize],
) -> (HashMap<usize, Rect>, Arc<ParaLayout>, Vec<para::Exclusion>, Vec<usize>) {
let FloatAnchor { p, block, y0, place, .. } = anchor;
ctx.fields.page = pb.number;
// Each layout of it here counts its automatic equation numbers from the same place.
let eq0 = ctx.eq_count;
let (rects, pl, rel) = anchor_floats_but(ctx, pb, anchor, force);
if !place || pb.web || p.objects.is_empty() {
return (rects, pl, rel, force.to_vec());
}
// Not those left out, nor those the page started with (#2048 settled them here).
let page = pb.pages.len().saturating_sub(1);
let seeded: Vec<usize> =
pb.early.get(&page).map(|v| v.iter().take(pb.seeded).filter(|(b, ..)| *b == block).map(|(_, k, _)| *k).collect()).unwrap_or_default();
let (bottom, more, col_top) = (pb.bottom, pb.cols.len().saturating_sub(pb.col + 1), pb.top);
let fit = |pl: &ParaLayout| fitting(pl, 0, y0 + pl.lines.first().map_or(0.0, |l| l.top.max(0.0)), bottom, (more, col_top));
let left_out = left_out_objects(ctx.doc, p, None, ctx.opts.show_hidden, ctx.hide_deleted);
let mut late: Vec<usize> =
late_floats(p, &pl, fit(&pl)).into_iter().chain(force.iter().copied()).filter(|oi| !left_out(*oi) && !seeded.contains(oi)).collect();
late.sort_unstable();
late.dedup();
if late.as_slice() == force {
return (rects, pl, rel, late);
}
ctx.eq_count = eq0;
let (rects, pl, rel) = anchor_floats_but(ctx, pb, anchor, &late);
// Without them in the way more of the paragraph may fit, and some of their anchors with it.
let still = late_floats(p, &pl, fit(&pl));
let fewer: Vec<usize> = late.iter().copied().filter(|oi| force.binary_search(oi).is_ok() || still.binary_search(oi).is_ok()).collect();
if fewer.len() == late.len() {
return (rects, pl, rel, late);
}
ctx.eq_count = eq0;
let (rects, pl, rel) = anchor_floats_but(ctx, pb, anchor, &fewer);
(rects, pl, rel, fewer)
}
/// The floating objects of `p` (laid out as `pl`) whose anchor line ([`anchor_lines`]) is at or
/// after `fit`, in order: Word draws them on the page their anchor line is on (#4250).
pub(crate) fn late_floats(p: &Paragraph, pl: &ParaLayout, fit: usize) -> Vec<usize> {
let lines = anchor_lines(p, pl);
let late =
|(oi, o): (usize, &InlineObject)| (floating(o).is_some() && lines.get(oi).copied().flatten().is_some_and(|li| li >= fit)).then_some(oi);
p.objects.iter().enumerate().filter_map(late).collect()
}
/// The end of the lines of `pl` from `l0` that fit on the page: line `l0`'s top at `top` in the
/// column, whose bottom is at `bottom`, then `more` columns from `col_top` (at least one line; a
/// page break ends them, a column break its column).
pub(crate) fn fitting(pl: &ParaLayout, l0: usize, top: f32, bottom: f32, (mut more, col_top): (usize, f32)) -> usize {
let Some(first) = pl.lines.get(l0) else { return l0 };
// A line's place in its column: `shift` plus its top.
let (mut shift, mut start, mut fit) = (top - first.top, l0, l0 + 1);
for (li, l) in pl.lines.iter().enumerate().skip(l0) {
if li > start && shift + l.top + l.height > bottom + 0.01 {
if more == 0 {
break;
}
(more, start, shift) = (more - 1, li, col_top - l.top);
}
fit = li + 1;
match l.end {
LineEnd::PageBreak => break,
LineEnd::ColumnBreak if more == 0 => break,
LineEnd::ColumnBreak => {
more -= 1;
start = li + 1;
shift = pl.lines.get(start).map_or(shift, |n| col_top - n.top);
}
_ => {}
}
}
fit
}
/// Place late float `oi` of body paragraph `p` ([`LateFloats`]) in the current column,
/// positioned from `top`, where the paragraph continues; its wrap area joins the page's.
pub(crate) fn place_late(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, oi: usize, top: f32, late: &mut LateFloats) {
let Some(o) = p.objects.get(oi) else { return };
let Some((w, h, float)) = floating(o) else { return };
let h = ctx.float_height(o, w, h);
let frame = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
let rect = float_rect(Some(frame), (pb.col_x(), pb.col_w()), top, w, h, float);
let outline = ctx.wrap_outline(o);
let area = wrap_area(rect, float, outline.as_deref().map(Vec::as_slice)).map(|a| {
let bounds = a.0;
pb.excl.push(a);
bounds
});
late.placed.insert(oi, Some(LatePlace { rect, top, spot: (pb.pages.len(), pb.col), drawn: false, area }));
}
/// The line of `pl` each object of `p` goes with (by object index; None if it isn't laid out):
/// the one holding its anchor, or for anchors on a line after a page or column break that holds
/// nothing taking room ([`para::takes_room`]: only anchors and markers such as bookmarks), the
/// break's: Word keeps them on the page before (a cover page's title box, #1632). With text after
/// them they are on the new page with it (#4262).
pub(crate) fn anchor_lines(p: &Paragraph, pl: &ParaLayout) -> Vec<Option<usize>> {
let mut out = vec![None; p.objects.len()];
for (li, l) in pl.lines.iter().enumerate() {
let clusters = pl.clusters.get(l.c0..l.c1).unwrap_or_default();
let lead = li.checked_sub(1).and_then(|k| pl.lines.get(k)).is_some_and(|l| matches!(l.end, LineEnd::PageBreak | LineEnd::ColumnBreak))
&& !clusters.iter().any(para::takes_room);
for c in clusters {
let para::ClKind::Object(oi) = c.kind else { continue };
if let Some(slot) = out.get_mut(oi).filter(|s| s.is_none()) {
*slot = Some(if lead { li.saturating_sub(1) } else { li });
}
}
}
out
}
/// [`anchor_floats`], leaving out the floats in `late` (in order).
fn anchor_floats_but(
ctx: &mut Ctx,
pb: &mut PageBuilder,
anchor: FloatAnchor,
late: &[usize],
) -> (HashMap<usize, Rect>, Arc<ParaLayout>, Vec<para::Exclusion>) {
let FloatAnchor { p, block, y0, before, excl_mark, label, place } = anchor;
ctx.fields.page = pb.number;
let (col_x, width) = (pb.col_x(), pb.col_w());
let mut rects = HashMap::new();
if !pb.web && place {
@@ -363,6 +482,10 @@ pub(crate) fn anchor_floats(
if left_out(oi) {
continue;
}
if late.binary_search(&oi).is_ok() {
ctx.floats_above.remove(&(block, oi));
continue;
}
let h = ctx.float_height(o, w, h);
// Positions relative to the paragraph start above its space before (Word for Windows).
let mut r = float_rect(Some(frame), (col_x, width), y0 - before, w, h, float);
@@ -414,6 +537,123 @@ pub(crate) struct ObjFrame<'a> {
/// Floats placed on the page from a header or footer cell (by object index, in page
/// coordinates): their items go to [`Ctx::pin`].
pub(crate) pinned: Option<&'a HashMap<usize, Rect>>,
/// A body paragraph's floats that go on a later page or column than its first piece.
pub(crate) late: Option<&'a LateFloats>,
}
/// Where a late float ([`LateFloats`]) was placed: its rect, the top it's positioned from, the
/// page and column, `(pages, col)`, whether it's drawn, and the bounds of its wrap area.
#[derive(Clone, Copy)]
pub(crate) struct LatePlace {
pub(crate) rect: Rect,
pub(crate) top: f32,
pub(crate) spot: (usize, usize),
pub(crate) drawn: bool,
pub(crate) area: Option<Rect>,
}
/// A body paragraph's floating objects anchored on a later page than its first line
/// ([`late_floats`]): Word draws them there, positioned from where the paragraph continues
/// (#4250). Each is placed when the paragraph gets there, and drawn with that piece.
pub(crate) struct LateFloats {
/// By object index, where it was placed, once it is.
pub(crate) placed: HashMap<usize, Option<LatePlace>>,
/// The page and column of the piece being placed.
pub(crate) piece: (usize, usize),
/// [`anchor_lines`], and the paragraph layout they're for.
pub(crate) lines: Option<(Arc<ParaLayout>, Vec<Option<usize>>)>,
/// Those a piece let go ([`LateFloats::release`]), and those it keeps all the same
/// ([`LateFloats::keep_back`]): (piece, object index).
pub(crate) held: Vec<((usize, usize), usize)>,
pub(crate) kept: Vec<((usize, usize), usize)>,
}
impl LateFloats {
pub(crate) fn new(late: &[usize]) -> Self {
LateFloats { placed: late.iter().map(|oi| (*oi, None)).collect(), piece: (0, 0), lines: None, held: Vec::new(), kept: Vec::new() }
}
/// [`anchor_lines`] for `pl`.
pub(crate) fn refresh(&mut self, p: &Paragraph, pl: &Arc<ParaLayout>) {
if !self.lines.as_ref().is_some_and(|(of, _)| Arc::ptr_eq(of, pl)) {
self.lines = Some((pl.clone(), anchor_lines(p, pl)));
}
}
/// The line object `oi` goes with ([`anchor_lines`]).
pub(crate) fn anchor(&self, oi: usize) -> Option<usize> {
self.lines.as_ref().and_then(|(_, v)| v.get(oi).copied().flatten())
}
/// Those placed with this piece whose anchor line is past `end` after all (notes, widow
/// control or a row kept together took lines [`fitting`] counted) wait for the next piece,
/// their wrap areas out of `excl`. Whether there were any.
pub(crate) fn release(&mut self, p: &Paragraph, pl: &Arc<ParaLayout>, end: usize, excl: &mut Vec<WrapArea>) -> bool {
self.refresh(p, pl);
let piece = self.piece;
let out: Vec<usize> = self
.placed
.iter()
.filter(|(oi, at)| at.is_some_and(|a| a.spot == piece && !a.drawn) && !self.kept.contains(&(piece, **oi)))
.filter(|(oi, _)| self.anchor(**oi).is_some_and(|li| li >= end))
.map(|(oi, _)| *oi)
.collect();
for oi in &out {
if let Some(Some(a)) = self.placed.insert(*oi, None)
&& let Some(k) = a.area.and_then(|r| excl.iter().rposition(|w| w.0 == r))
{
excl.remove(k);
}
self.held.push((piece, *oi));
}
!out.is_empty()
}
/// Those this piece let go whose anchor line came back into `lines` without them (their own
/// wrap pushed it on): kept with this piece after all, as before. Whether there were any.
pub(crate) fn keep_back(&mut self, p: &Paragraph, pl: &Arc<ParaLayout>, lines: std::ops::Range<usize>) -> bool {
self.refresh(p, pl);
let piece = self.piece;
let back: Vec<_> =
self.held.iter().filter(|(pc, oi)| *pc == piece && self.anchor(*oi).is_some_and(|li| lines.contains(&li))).copied().collect();
self.held.retain(|h| !back.contains(h));
self.kept.extend(&back);
!back.is_empty()
}
/// Those to place with this piece: not placed yet (nor let go by it), or placed for a column
/// the paragraph then didn't go into, with their anchor line in `lines`, in order.
pub(crate) fn due(&mut self, p: &Paragraph, pl: &Arc<ParaLayout>, lines: std::ops::Range<usize>) -> Vec<usize> {
self.refresh(p, pl);
let mut due: Vec<usize> = self
.placed
.iter()
.filter(|(_, at)| at.is_none_or(|a| a.spot != self.piece && !a.drawn))
.filter(|(oi, _)| !self.held.contains(&(self.piece, **oi)) && self.anchor(**oi).is_some_and(|li| lines.contains(&li)))
.map(|(oi, _)| *oi)
.collect();
due.sort_unstable();
due
}
/// Late float `oi` if it's drawn with this piece.
pub(crate) fn here(&self, oi: usize) -> Option<LatePlace> {
self.placed.get(&oi).copied().flatten().filter(|a| a.spot == self.piece && !a.drawn)
}
/// The lines holding the anchors of those drawn with this piece (an anchor right after a
/// break is on the line after its [`anchor_lines`] one).
pub(crate) fn lines_here(&self) -> Vec<usize> {
self.placed.keys().filter(|oi| self.here(**oi).is_some()).filter_map(|oi| self.anchor(*oi)).flat_map(|li| [li, li + 1]).collect()
}
/// Those drawn with this piece are drawn.
pub(crate) fn drew(&mut self) {
let piece = self.piece;
for a in self.placed.values_mut().flatten().filter(|a| a.spot == piece) {
a.drawn = true;
}
}
}
/// What [`anchor_floats`] anchors: paragraph `p` (body block `block`) starting at `y0` with
@@ -461,15 +701,15 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
let Some(fl) = pl.lines.get(l0) else { return (Vec::new(), Vec::new()) };
// Objects left out of the layout (hidden, or deleted in the final text) aren't placed.
let left_out = left_out_objects(ctx.doc, p, at.table_chr, ctx.opts.show_hidden, ctx.hide_deleted);
// A floating object belongs to its paragraph, not to its line: Word puts it on the page the
// paragraph starts on (a cover page is a paragraph holding a page break and then the text
// box with the title; the box stays on the cover). So the paragraph's first piece places
// every floating object, whichever of its lines holds the anchor, and later pieces none;
// inline objects go with their own line.
// The paragraph's first piece draws its floating objects, whichever of its lines holds the
// anchor, except those anchored on a later page (`at.late`): the piece there draws them
// (#4250). Inline objects go with their own line.
let first = l0 == 0;
let late = at.late.filter(|l| !l.placed.is_empty());
let late_lines = late.map(LateFloats::lines_here).unwrap_or_default();
for li in 0..pl.lines.len() {
let in_piece = (l0..l1).contains(&li);
if !in_piece && !first {
if !in_piece && !first && !late_lines.contains(&li) {
continue;
}
let Some(line) = pl.lines.get(li) else { continue };
@@ -482,12 +722,23 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
let Some(obj) = p.objects.get(oi) else { continue };
let Some((w, h, float)) = obj.frame() else { continue };
let floating = float.wrap != Wrap::Inline;
if if floating { !first } else { !in_piece } {
let is_late = floating && late.is_some_and(|l| l.placed.contains_key(&oi));
let late_here = late.and_then(|l| l.here(oi)).filter(|_| floating);
let skip = if is_late {
late_here.is_none()
} else if floating {
!first
} else {
!in_piece
};
if skip {
continue;
}
let pinned = at.pinned.and_then(|m| m.get(&oi)).copied().filter(|_| floating);
let rect = if let Some(r) = pinned {
r
} else if let Some(l) = late_here {
l.rect
} else if floating {
match floats.get(&oi) {
Some(r) => *r,
@@ -522,7 +773,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
off: c.start,
text_box: shown,
wrap: float.wrap,
origin: Point::new(at.col.0, at.para_y),
origin: Point::new(at.col.0, late_here.map_or(at.para_y, |l| l.top)),
});
// Its text (a group: its text boxes', each where the group's turn carries it; the
// text itself stays upright), unless the box budget says no (a box inside itself,
+123 -12
View File
@@ -1,7 +1,10 @@
use super::boxes::{BoxInput, BoxLayout, Edges, joined, layout_box, push_para};
use super::cache::has_page_number_fields;
use super::ctx::Ctx;
use super::floats::{FloatAnchor, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, place_objects};
use super::floats::{
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, late_floats, place_late,
place_objects,
};
use super::notes::{DECOR_STORY, NoteBox, para_notes};
use super::page::{PageBuilder, PageFrame, item_bottom};
use super::placed::Placed;
@@ -172,6 +175,15 @@ struct Flow<'a> {
wrap_relays: usize,
/// The first line not placed yet.
l0: usize,
/// Its floats anchored on a later page or column than its first piece (#4250).
late: LateFloats,
/// Whether the floats past the first piece were checked ([`Flow::recheck_late`]), and those
/// it held back.
rechecked: bool,
forced: Vec<usize>,
/// The space before it at the top of the piece being placed (a paragraph starting with a page
/// break has it on the new page): late floats there are positioned from above it.
space_here: f32,
}
impl<'a> Flow<'a> {
@@ -185,8 +197,8 @@ impl<'a> Flow<'a> {
let guess = pb.y + space_before;
let label = ctx.next_label(p);
let eq_start = ctx.eq_count;
let (float_rects, pl, rel) =
anchor_floats(ctx, pb, FloatAnchor { p, block, y0: guess, before: space_before, excl_mark, label: &label, place: true });
let (float_rects, pl, rel, late) =
anchor_floats(ctx, pb, FloatAnchor { p, block, y0: guess, before: space_before, excl_mark, label: &label, place: true }, &[]);
Flow {
p,
block,
@@ -206,6 +218,10 @@ impl<'a> Flow<'a> {
page_relays: 0,
wrap_relays: 0,
l0: 0,
late: LateFloats::new(&late),
rechecked: false,
forced: Vec::new(),
space_here: 0.0,
}
}
@@ -213,16 +229,19 @@ impl<'a> Flow<'a> {
self.pl.lines.len()
}
/// Place the floats and lay the paragraph out again from `y0`, `before` the space before it.
fn reanchor(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, (y0, before): (f32, f32)) {
let (rects, pl, rel) = again(ctx, self.eq_start, |ctx| {
/// Place the floats and lay the paragraph out again from `y0`, `before` the space before it,
/// leaving those in `force` for a later piece.
fn reanchor(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, (y0, before): (f32, f32), force: &[usize]) {
let (rects, pl, rel, late) = again(ctx, self.eq_start, |ctx| {
anchor_floats(
ctx,
pb,
FloatAnchor { p: self.p, block: self.block, y0, before, excl_mark: self.excl_mark, label: &self.label, place: true },
force,
)
});
(self.float_rects, self.pl, self.rel) = (rects, pl, rel);
self.late = LateFloats::new(&late);
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
}
@@ -305,7 +324,13 @@ impl<'a> Flow<'a> {
/// the space before applied (`before`, or what is left of it at the top of the next column).
fn keep_together(&self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms, before: f32) -> f32 {
let rp = &self.pl.rp;
let height = self.pl.height + rooms.top + rooms.bottom;
// A terminal page-break mark stays with the break and draws no bottom border there.
let break_mark = !pb.web
&& self.pl.lines.len() >= 2
&& self.pl.lines.get(self.pl.lines.len() - 2).is_some_and(|line| {
line.end == LineEnd::PageBreak && self.pl.lines.last().is_some_and(|mark| only_markers(self.p, mark.start..mark.stop))
});
let height = self.pl.height + rooms.top + if break_mark { 0.0 } else { rooms.bottom };
if !(rp.keep_lines || (rp.keep_next && pb.y + height <= pb.bottom + 0.01)) {
return before;
}
@@ -467,8 +492,10 @@ impl<'a> Flow<'a> {
pb.advance(self.block, self.body_top);
if self.l0 == 0 {
let y0 = pb.y;
self.reanchor(ctx, pb, (y0, 0.0));
self.reanchor(ctx, pb, (y0, 0.0), &[]);
self.anchor_y = y0;
// Its floats are checked again on the new page.
(self.rechecked, self.forced) = (false, Vec::new());
}
}
@@ -501,6 +528,13 @@ impl<'a> Flow<'a> {
}
let end = push_para(&mut items, (StoryRef::Body, &[self.block as u32]), &self.pl, (l0, l1), (x, y), self.width, edges);
pb.para_end = Some((pb.pages.len(), pb.col, end));
// Late floats whose anchor line came here after all are placed with these lines.
self.late.piece = (pb.pages.len(), pb.col);
if !pb.web && !self.late.placed.is_empty() {
let top = if l0 == 0 { self.anchor_y } else { y - self.space_here };
self.place_due(ctx, pb, 0..l1, top);
}
self.space_here = 0.0;
// Pictures, shapes and text boxes in these lines (web view: floats placed by this piece).
let at = ObjFrame {
page: Some(PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror }),
@@ -508,6 +542,7 @@ impl<'a> Flow<'a> {
para_y: if pb.web { y } else { self.anchor_y },
table_chr: None,
pinned: None,
late: Some(&self.late),
};
let (behind, front) = place_objects(
ctx,
@@ -523,6 +558,7 @@ impl<'a> Flow<'a> {
depth: 0,
},
);
self.late.drew();
items.extend(front);
items.extend(line_numbers(ctx, pb, &self.pl, (l0, l1), y));
add_items(pb, behind, items);
@@ -549,7 +585,8 @@ impl<'a> Flow<'a> {
}
Some(LineEnd::PageBreak) if starts_with_break && !pb.web => {
pb.new_page(block, body_top);
pb.y += self.pl.rp.space_before.max(0.0);
self.space_here = self.pl.rp.space_before.max(0.0);
pb.y += self.space_here;
}
Some(LineEnd::PageBreak) => pb.new_page(block, body_top),
Some(LineEnd::ColumnBreak) => {
@@ -572,8 +609,8 @@ impl<'a> Flow<'a> {
let y0 = pb.y;
// The floats were placed and drawn with the first piece: they stay there.
let (p, block, excl_mark, eq_start, label) = (self.p, self.block, self.excl_mark, self.eq_start, &self.label);
let (rects, relaid, relaid_rel) = with_page_map(ctx, &mut self.page_map, |ctx| {
again(ctx, eq_start, |ctx| anchor_floats(ctx, pb, FloatAnchor { p, block, y0, before: 0.0, excl_mark, label, place: false }))
let (rects, relaid, relaid_rel, _) = with_page_map(ctx, &mut self.page_map, |ctx| {
again(ctx, eq_start, |ctx| anchor_floats(ctx, pb, FloatAnchor { p, block, y0, before: 0.0, excl_mark, label, place: false }, &[]))
});
if let Some(k) = relaid.lines.iter().position(|l| l.start == resume) {
(self.float_rects, self.pl, self.rel) = (rects, relaid, relaid_rel);
@@ -583,6 +620,72 @@ impl<'a> Flow<'a> {
}
}
/// Late floats anchored in the lines that fit in this column are placed here, so these lines
/// are broken again around them ([`Flow::relay_wrap`]).
fn place_due_late(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder) {
if self.l0 == 0 || pb.web || self.late.placed.is_empty() {
return;
}
self.late.piece = (pb.pages.len(), pb.col);
let lines = self.l0..fitting(&self.pl, self.l0, pb.y, pb.bottom, (0, pb.top));
self.place_due(ctx, pb, lines, pb.y - self.space_here);
}
/// Place the late floats due with this piece whose anchor line is in `lines`, positioned from
/// `top`.
fn place_due(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, lines: std::ops::Range<usize>, top: f32) {
for oi in self.late.due(self.p, &self.pl, lines) {
place_late(ctx, pb, self.p, oi, top, &mut self.late);
}
}
/// Late floats placed for lines that went on after all (past `l1`) wait for the next piece;
/// one whose own wrap pushed its line on stays, as before. Whether the lines from `l0` are to
/// be broken again without them. Does nothing once the wrap relays are used up
/// ([`MAX_WRAP_RELAYS`]).
fn settle_late(&mut self, pb: &mut PageBuilder, l1: usize) -> bool {
let l0 = self.l0;
if l0 == 0 || pb.web || self.late.placed.is_empty() || self.wrap_relays >= MAX_WRAP_RELAYS {
return false;
}
let end = if l1 == l0 && pb.fresh() { l0 + 1 } else { l1 }; // what the overflow keeps
let moved = self.late.release(self.p, &self.pl, end, &mut pb.excl) || self.late.keep_back(self.p, &self.pl, l0..end);
moved && l1 > l0
}
/// The first piece's lines end at `l1` on this page. Floats anchored past them, on the next
/// page, though [`anchor_floats`] thought they would fit here (footnotes, widow control…),
/// are held back after all, once; and those held back whose anchor came back once they were
/// out of the way are placed here as before, with the text wrapping around them rather than
/// over it (before the notes of these lines are kept: the wrap can push their references on).
/// Whether the paragraph was laid out again.
fn recheck_late(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, l1: usize) -> bool {
if self.l0 != 0 || pb.web {
return false;
}
if l1 < self.n() && !self.rechecked && pb.col + 1 >= pb.cols.len() {
self.rechecked = true;
self.forced = late_floats(self.p, &self.pl, l1).into_iter().filter(|oi| !self.late.placed.contains_key(oi)).collect();
if !self.forced.is_empty() {
let mut force = self.forced.clone();
force.extend(self.late.placed.keys());
force.sort_unstable();
let top = (pb.y, pb.y - self.anchor_y);
self.reanchor(ctx, pb, top, &force);
return true;
}
}
let back = if self.forced.is_empty() { Vec::new() } else { self.late.due(self.p, &self.pl, 0..l1) };
if !back.iter().any(|oi| self.forced.contains(oi)) {
return false;
}
// The others are still held back.
self.forced.retain(|oi| !back.contains(oi));
let (keep, top) = (std::mem::take(&mut self.forced), (pb.y, pb.y - self.anchor_y));
self.reanchor(ctx, pb, top, &keep);
true
}
/// Leave the space after the paragraph, for the next one to merge with.
fn finish(&self, pb: &mut PageBuilder, rooms: Rooms) {
// A mark that stayed with its page break keeps its space after on that page too, and its
@@ -724,10 +827,11 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
// A different top only matters when there is something to wrap around.
if spot(pb) != placed_at || ((pb.y - f.guess).abs() > 0.01 && !pb.excl.is_empty()) {
let y0 = pb.y;
f.reanchor(ctx, pb, (y0, applied_before));
f.reanchor(ctx, pb, (y0, applied_before), &[]);
f.anchor_y = y0 - applied_before;
}
while f.l0 < f.n() {
f.place_due_late(ctx, pb);
f.relay_wrap(ctx, pb);
f.relay_pages(ctx, pb);
// What is laid out for these lines from here (their footnotes) is on this page.
@@ -738,6 +842,9 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
let notes = para_notes(ctx.doc, p, &f.pl);
let mut fit = f.fit_lines(ctx, pb, &notes, lead);
fit.l1 = f.settled_end(pb, &fit);
if f.settle_late(pb, fit.l1) {
continue;
}
if fit.l1 == f.l0 {
if !pb.fresh() {
f.move_on(ctx, pb);
@@ -745,6 +852,9 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
}
fit.l1 = f.l0 + 1; // can't fit even one line on an empty page: overflow
}
if f.recheck_late(ctx, pb, fit.l1) {
continue;
}
let (forced, mark_with_break) = (fit.forced, fit.mark_with_break);
f.emit(ctx, pb, rooms, (lead, fit, &notes));
f.after_lines(ctx, pb, forced, mark_with_break);
@@ -805,6 +915,7 @@ pub(crate) fn place_outline_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragr
para_y: y,
table_chr: None,
pinned: None,
late: None,
};
let (behind, front) = place_objects(
ctx,
+4
View File
@@ -72,6 +72,9 @@ pub struct ObjectHit {
pub wrap: Wrap,
/// Where column- and paragraph-relative offsets start (see [`Placed::Object`]).
pub origin: Point,
/// A member of a Drawing Canvas, by its index in the canvas, when the hit is that member
/// (its frame inside the canvas at `pos`) rather than the canvas. Layout gives `None`.
pub member: Option<usize>,
}
/// Object positions in one layout, retaining each page occurrence for page-hinted lookups.
@@ -149,6 +152,7 @@ fn objects_in(items: &[Placed], index: usize) -> impl Iterator<Item = ObjectHit>
text_box: *text_box,
wrap: *wrap,
origin: *origin,
member: None,
}),
_ => None,
})
+3
View File
@@ -38,6 +38,7 @@ pub(crate) use chars::{ligature_features, remap_range, thai_run_face};
pub use grid::{Exclusion, Grid, is_east_asian};
#[cfg(test)]
use lines::break_lines;
pub(crate) use lines::takes_room;
pub use model::{CellText, ClKind, Cluster, Enclosed, Glyph, Label, LabelRun, Line, LineEnd, PARA_MARK_WIDTH, ParaEnv, RubyLayout, StyleRun, VisCl};
pub use paragraph::layout_para;
#[cfg(test)]
@@ -80,6 +81,8 @@ pub struct ParaLayout {
pub drop_cap_w: f32,
/// Laid-out equations by object index.
pub maths: Vec<(usize, Arc<crate::math::MathLayout>)>,
/// The legacy check boxes among its objects (inline objects' indexes).
pub check_boxes: Vec<usize>,
/// Ruby (Phonetic Guide) text over base-text clusters, in cluster order.
pub rubies: Vec<RubyLayout>,
/// Display equations (on lines of their own): cluster index and justification.
+77 -21
View File
@@ -109,7 +109,7 @@ fn has_content(pl: &ParaLayout, c0: usize, j: usize) -> bool {
/// control's start, a bookmark) and floating objects' anchors take no room and don't count (Word:
/// a picture a little wider than the line, after an anchor, stays on the first line rather than
/// leaving the anchor a line of its own).
fn takes_room(c: &Cluster) -> bool {
pub(crate) fn takes_room(c: &Cluster) -> bool {
c.kind != ClKind::Marker && !(matches!(c.kind, ClKind::Object(_)) && c.adv == 0.0 && c.obj_h == 0.0)
}
@@ -407,7 +407,7 @@ impl<'e> Breaker<'e> {
/// tallest picture on it (which sits on the baseline).
fn extents(&self, pl: &ParaLayout, (c0, c1): (usize, usize)) -> Extents {
let rp = &self.rp;
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0 };
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false };
let mut any = false;
let dropped = pl.drop_cap.map_or(0, |d| d.0);
for (k, c) in pl.clusters.get(c0..c1).into_iter().flatten().enumerate() {
@@ -420,17 +420,27 @@ impl<'e> Breaker<'e> {
continue;
}
let Some(st) = pl.styles.get(c.style as usize) else { continue };
let object = if let ClKind::Object(o) = c.kind { Some(o) } else { None };
let math = object.is_some_and(|o| pl.maths.iter().any(|(k, _)| *k == o));
let check_box = object.is_some_and(|o| pl.check_boxes.contains(&o));
// A picture sits on the baseline of its run (raised or lowered by its position):
// the line keeps that font's ascent and descent, and grows to fit it.
let (a, d) = if matches!(c.kind, ClKind::Object(_)) && c.obj_h + c.obj_d > 0.0 {
if pl.maths.iter().any(|(k, _)| c.kind == ClKind::Object(*k)) {
let (a, d) = if check_box {
// Word sizes a line by a legacy check box as by text of the box's size (measured
// with Arial at 10 and 20 pt: a 20 pt box's line is 23 pt, times the spacing).
let (a, d) = st.line_extent();
let k = if st.ascent > 0.0 { c.obj_h / st.ascent } else { 1.0 };
(a * k, d * k)
} else if object.is_some() && c.obj_h + c.obj_d > 0.0 {
if math {
// Exact spacing keeps the run's baseline; tall math may overflow the
// fixed line box without moving adjacent text up by its denominator.
if matches!(rp.line_spacing, LineSpacing::Exactly(_)) { (st.ascent, st.descent) } else { (c.obj_h, c.obj_d) }
} else {
ex.obj_asc = ex.obj_asc.max(c.obj_h);
// A lowered picture reaches below the baseline: the line's descent grows.
(st.ascent, st.descent.max(c.obj_d))
// A lowered picture reaches below the baseline.
ex.obj_desc = ex.obj_desc.max(c.obj_d);
(st.ascent, st.descent)
}
} else {
// `obj_h` is set on text clusters only under ruby text, which the line grows to fit.
@@ -440,6 +450,9 @@ impl<'e> Breaker<'e> {
ex.asc = ex.asc.max(a);
ex.desc = ex.desc.max(d);
any = true;
// Text needs its descent below the line; so do inline math (an object with its own
// descent) and a check box. A line break ending the line is no text.
ex.text |= math || check_box || !matches!(c.kind, ClKind::Object(_) | ClKind::LineBreak | ClKind::PageBreak | ClKind::ColumnBreak);
}
if (!any || (ex.asc == 0.0 && ex.desc == 0.0))
&& let Some(st) = pl.styles.get(self.mark_style as usize)
@@ -453,10 +466,30 @@ impl<'e> Breaker<'e> {
/// The line's height, baseline and text extent.
fn measure(&self, pl: &ParaLayout, range: (usize, usize)) -> Measure {
let rp = &self.rp;
let Extents { mut asc, mut desc, obj_asc } = self.extents(pl, range);
let text_natural = asc + desc;
let Extents { mut asc, mut desc, obj_asc, obj_desc, text } = self.extents(pl, range);
let mut text_natural = asc + desc;
let font_desc = desc;
desc = desc.max(obj_desc);
let (text_asc, text_desc) = (asc.max(obj_asc), desc);
let text_pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
// With multiple spacing a line of only pictures (and spaces) is as tall as they reach,
// raised or lowered, and never less than its font's height, a list label's font counting
// too: they end at its bottom, and the spacing adds its share of the font's height. Beside
// text they take the text's ascent and descent too, each only where it reaches further.
// Word, measured with Arial at 10 and 20 pt, single, 1.15 and 1.5 spacing: a 30 pt picture
// alone takes 30, 30 + 0.15 and 30 + 0.5 times the font's height, lowered 10 or 30 pt or
// not; raised 10 pt, 10 more; a 6 pt one, the font's height; beside text and lowered
// 10 pt, 30. Not on a line lowered further than the picture's height, which layout limits
// to that height where Word's line keeps growing.
let spacing = if let LineSpacing::Multiple(m) = rp.line_spacing { Some(m) } else { None };
let pictures_alone = !text && obj_asc + obj_desc > 0.0 && spacing.is_some();
let below = if pictures_alone { obj_desc } else { desc };
let text_pictures = if pictures_alone {
obj_asc + obj_desc
} else if obj_asc > asc || obj_desc > font_desc {
asc.max(obj_asc) + desc
} else {
0.0
};
let mut label_extra = 0.0;
if self.first
&& let Some(lab) = &pl.label
@@ -466,6 +499,12 @@ impl<'e> Breaker<'e> {
// overflow adds room, unscaled by the automatic spacing multiplier.
label_extra = (lab.ascent - asc).max(0.0);
asc = asc.max(lab.ascent);
if pictures_alone {
let styles = lab.runs.iter().filter_map(|r| pl.styles.get(r.style as usize));
let (a, d) = styles.fold((asc, font_desc), |(a, d), st| (a.max(st.ascent), d.max(st.descent)));
text_natural = a + d;
label_extra = 0.0;
}
} else {
for st in lab.runs.iter().filter_map(|r| pl.styles.get(r.style as usize)) {
asc = asc.max(st.ascent);
@@ -473,10 +512,7 @@ impl<'e> Breaker<'e> {
}
}
}
// Keep the picture floor independent of list-label metrics and line-spacing multipliers.
// shortcut: Word leaves less than a full descent below a line of only pictures (0.5pt to
// 1.9pt in docxide-pdf's header fixtures case121/case123, where the descent is 3.3pt), and
// no rule tried so far (none, only the text's descent) matched both; it needs Word probes.
// Keep the picture floor independent of list-label metrics.
let natural = asc + desc;
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
// Document grid: the line takes whole line pitches, its text centred in them.
@@ -484,15 +520,17 @@ impl<'e> Breaker<'e> {
let (height, centred) = match (rp.line_spacing, grid) {
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
(LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures), false),
(LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures + (m - 1.0).max(0.0) * text_natural), false),
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
(LineSpacing::Exactly(v), _) => (v, false),
};
let baseline = if centred {
let up = asc.max(obj_asc);
self.top + ((height - up - desc) / 2.0).max(0.0) + up
} else if let Some(m) = spacing.filter(|_| pictures_alone) {
self.top + (text_natural * m.min(1.0) - text_pictures).max(0.0) + obj_asc
} else {
self.top + baseline_offset(rp.line_spacing, asc, height, desc).max(obj_asc.min(height - desc))
self.top + baseline_offset(rp.line_spacing, asc, height, below).max(obj_asc.min(height - below))
};
Measure { height, baseline, text_asc, text_desc }
}
@@ -651,6 +689,10 @@ struct Extents {
asc: f32,
desc: f32,
obj_asc: f32,
/// How far its lowest picture reaches below the baseline.
obj_desc: f32,
/// Whether the line holds text besides its pictures (spaces and tabs don't count).
text: bool,
}
/// A line's height and baseline, and the extent of its text.
@@ -682,16 +724,30 @@ fn content_end(pl: &ParaLayout, sc: &Scan, c1: usize) -> f32 {
/// Stretch the line to its right edge: its spaces widen by `slack` between them, or all its
/// clusters by an equal share when `distribute` (or there are no spaces).
fn justify_line(pl: &ParaLayout, xs: &mut [f32], (c0, c1, align_from): (usize, usize, usize), (content_end, slack): (f32, f32), distribute: bool) {
// Spaces inside the content (after the last tab).
let spaces: Vec<usize> = (align_from..c1)
// Spaces before the line's first character (after the last tab) keep their width, as in Word:
// text indented with spaces stays where the spaces put it. Zero-width markers (a bookmark,
// hidden text), floating objects' anchors and the break a line ends with don't count as a
// character.
let blank = |k: usize| {
pl.clusters.get(k).is_some_and(|c| {
matches!(c.kind, ClKind::Space | ClKind::Marker | ClKind::LineBreak | ClKind::PageBreak | ClKind::ColumnBreak)
|| (matches!(c.kind, ClKind::Object(_)) && c.adv == 0.0 && c.obj_h == 0.0)
})
};
let text_from = (align_from..c1).find(|k| !blank(*k)).unwrap_or(c1);
// Spaces inside the content.
let spaces: Vec<usize> = (text_from..c1)
.filter(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Space) && xs.get(k - c0).copied().unwrap_or(f32::MAX) < content_end - 0.01)
.collect();
if distribute || spaces.is_empty() {
let cnt = (c1 - align_from).saturating_sub(1).max(1) as f32;
// Distributed across the gaps between the first and last characters: spaces hanging at
// the line's end take none, so the last character reaches the margin.
let text_to = (text_from..c1).rev().find(|k| !blank(*k)).map_or(text_from, |k| k + 1);
let cnt = (text_to - text_from).saturating_sub(1).max(1) as f32;
if distribute {
let per = slack / cnt;
for (q, v) in xs.iter_mut().enumerate().skip(align_from - c0) {
let k = (q + c0 - align_from) as f32;
for (q, v) in xs.iter_mut().enumerate().skip(text_from - c0) {
let k = (q + c0 - text_from) as f32;
*v += per * k.min(cnt);
}
}
@@ -700,7 +756,7 @@ fn justify_line(pl: &ParaLayout, xs: &mut [f32], (c0, c1, align_from): (usize, u
let per = slack / spaces.len() as f32;
let mut add = 0.0;
let mut si = 0;
for k in align_from..c1 {
for k in text_from..c1 {
if let Some(v) = xs.get_mut(k - c0) {
*v += add;
}
+5 -1
View File
@@ -71,6 +71,7 @@ struct Shaped<'a> {
drop_cap: Option<(usize, u8, f32)>,
drop_cap_w: f32,
maths: Vec<(usize, Arc<crate::math::MathLayout>)>,
check_boxes: Vec<usize>,
enclosures: Vec<(usize, Enclosed)>,
rubies: Vec<RubyLayout>,
displays: Vec<(usize, wordcraft_doc::math::MathJc)>,
@@ -176,6 +177,7 @@ impl<'a> Shaped<'a> {
drop_cap: None,
drop_cap_w: 0.0,
maths: Vec::new(),
check_boxes: Vec::new(),
enclosures: Vec::new(),
rubies: Vec::new(),
displays: Vec::new(),
@@ -406,6 +408,7 @@ impl<'a> Shaped<'a> {
let scale = size.map_or(1.0, |sz| sz / rc.size.max(0.5));
let (a, d) = (a * scale, d * scale);
self.b.clusters.push(slot.cluster(ClKind::Object(k), a + d, (a.max(0.01), d)));
self.check_boxes.push(k);
}
fn field_result(&mut self, cx: &Cx, (instr, result): (&str, &str), slot: Slot, rc: &Arc<ResolvedChar>) {
@@ -624,7 +627,7 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
mark_break_opportunities(&mut sh.b.clusters, &bt, &rp);
let label = list_label(&cx, &mut sh.b, mark_style);
let joined_cluster_starts = joined_cluster_starts(p, &sh.b.clusters);
let Shaped { b, has_page_fields, notes, drop_cap, drop_cap_w, maths, enclosures, rubies, displays, ptabs, left, runs, .. } = sh;
let Shaped { b, has_page_fields, notes, drop_cap, drop_cap_w, maths, check_boxes, enclosures, rubies, displays, ptabs, left, runs, .. } = sh;
let mut pl = ParaLayout {
rp,
substituted: b.substituted,
@@ -645,6 +648,7 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
bidi_levels: b.levels,
drop_cap_w,
maths,
check_boxes,
rubies,
displays,
ptabs,
+662 -10
View File
@@ -5416,9 +5416,11 @@ fn line_spacing_does_not_scale_pictures() {
let l = lay(&d);
let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!() };
let line = &para.lines[0];
let desc = para.styles[0].descent;
// Word: the picture plus the font's descent, not (picture + descent) x 1.15.
assert!((line.height - (144.0 + desc)).abs() < 0.01, "line {} for a 144pt picture (descent {desc})", line.height);
let natural = para.styles[0].ascent + para.styles[0].descent;
// Word, measured (Aptos, Arial, Times; 10 and 20 pt; single, 1.15, 1.5): a line of only a
// picture is the picture plus the spacing's share of the text's height, with no descent below
// it, not (picture + descent) x 1.15.
assert!((line.height - (144.0 + 0.15 * natural)).abs() < 0.01, "line {} for a 144pt picture (text {natural})", line.height);
assert!((line.baseline - line.top - 144.0).abs() < 0.01, "the picture stands on the baseline");
}
@@ -5470,8 +5472,17 @@ fn list_label_does_not_inflate_an_inline_picture_floor() {
let l = lay(&d);
let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!() };
let line = &para.lines[0];
let desc = para.styles[para.clusters[0].style as usize].descent;
assert!((line.height - (144.0 + desc)).abs() < 0.01, "{spacing:?}: {}", line.height);
let st = &para.styles[para.clusters[0].style as usize];
let label = para.label.as_ref().unwrap().runs.iter().map(|r| &para.styles[r.style as usize]);
let (a, d) = label.fold((st.ascent, st.descent), |(a, d), s| (a.max(s.ascent), d.max(s.descent)));
// Multiple spacing: the picture plus its share of the font's height, the label's being a
// font too (Word, measured: 144 pt at 1.25 with a 24 pt label takes 144 + 0.25 * 27.6);
// at least: the picture and the descent.
let want = match spacing {
LineSpacing::Multiple(m) => 144.0 + (m - 1.0) * (a + d),
_ => 144.0 + st.descent,
};
assert!((line.height - want).abs() < 0.01, "{spacing:?}: {} (want {want})", line.height);
assert!((line.baseline - line.top - 144.0).abs() < 0.01);
}
}
@@ -5479,7 +5490,7 @@ fn list_label_does_not_inflate_an_inline_picture_floor() {
#[test]
fn a_line_of_only_pictures_keeps_its_fonts_height_in_odt_documents() {
// The standard has no line-height algorithm: as in Word, the line keeps the font's height, and
// its descent below a taller picture.
// takes a taller picture's.
let height = |h: f32| {
let mut d = Document::from_text("");
d.settings.odf = Some(wordcraft_doc::OdfLayout::default());
@@ -5493,7 +5504,7 @@ fn a_line_of_only_pictures_keeps_its_fonts_height_in_odt_documents() {
para.lines[0].height
};
assert!(height(3.5) > 10.0);
assert!(height(40.0) > 42.0);
assert!((height(40.0) - 40.0).abs() < 0.01, "{}", height(40.0));
}
#[test]
@@ -5771,6 +5782,56 @@ fn justified_lines_shrink_spaces_in_word_2013_mode() {
}
}
/// Spaces before a line's first character keep their width in justified and distributed lines:
/// Thai official letters indent their paragraphs with a run of spaces. Measured in Word (left,
/// `both`, `distribute` and `thaiDistribute`, Thai and Latin text, spaces at the paragraph start,
/// after a line break and after a tab): the first character sits where it does left-aligned, and
/// only the spaces between words stretch. WordCraft stretched the leading spaces too, so the
/// first character of a justified line moved right by up to the line's whole slack. A
/// distributed line also counted the space it wrapped at, so its text stopped short of the margin.
#[test]
fn leading_spaces_keep_their_width_in_justified_lines() {
let spaces = " ".repeat(20);
let body = "We tie the spend to a pipe and to the books, so it is in an ad hoc view of all of it. ".repeat(4);
// `hidden` (zero-width hidden text before the spaces) and `float` (a floating shape anchored
// before them): Word ignores those, and a bookmark, there too; the first character is still
// the one after the spaces.
let first_x = |align: Align, hidden: &str, float: bool| {
let mut d = Document::from_text(&format!("{hidden}{spaces}{body}"));
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.align = Some(align)).unwrap();
if !hidden.is_empty() {
d.format_range(&Pos::body(0, 0), &Pos::body(0, hidden.len()), &|c| c.hidden = Some(true)).unwrap();
}
if float {
d.insert_object(&Pos::body(0, 0), rect_shape(20.0, 20.0, page_float(400.0, 600.0)), &Default::default()).unwrap();
}
let text = d.body[0].as_para().unwrap().text.clone();
let lead = text.len() - body.len();
let l = lay(&d);
let (para, x0) =
l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, x, .. } = it { Some((para.clone(), *x)) } else { None }).unwrap();
assert!(para.lines.len() > 1, "the paragraph wraps");
let line = &para.lines[0];
// The first line's last character (ASCII here): its index and left and right positions.
let end = line.start + text[line.start..line.stop].trim_end().len();
(para.x_of(0, lead).unwrap(), end, para.x_of(0, end - 1).unwrap() + x0, para.x_of(0, end).unwrap() + x0)
};
for (hidden, float) in [("", false), ("hidden", false), ("", true)] {
let (left, left_end, left_from, left_to) = first_x(Align::Left, hidden, float);
for align in [Align::Justify, Align::Distribute] {
let (x, end, from, _) = first_x(align, hidden, float);
let case = format!("{align:?} hidden {hidden:?} float {float}");
assert!((x - left).abs() < 0.01, "{case}: the first character is at {x}, left-aligned at {left}");
assert_eq!(end, left_end, "{case}: the line breaks where it does left-aligned");
assert!(from > left_from + 1.0, "{case}: the line is still stretched ({from} vs {left_from})");
// The line ends with the space it wrapped at; its last character, keeping its own
// advance, still ends at the margin: no gap is left after it.
let ink_end = from + (left_to - left_from);
assert!((ink_end - 540.0).abs() < 0.05, "{case}: the line's last character ends at {ink_end}, not the margin");
}
}
}
/// Measured in Word for Mac (compatibility mode 15, justified paragraphs of one repeated word,
/// the right indent leaving room for N words plus one more that fits only if the spaces shrink):
/// the spaces give up at most a quarter of their width, and a word with the space before it may
@@ -5860,6 +5921,30 @@ fn justified_line_ending_in_line_break_is_stretched() {
assert!(kept[0] < 400.0, "doNotExpandShiftReturn keeps the line before the break short: {}", kept[0]);
}
/// A distributed line that ends in a manual line break stretches its characters to the margin, as
/// in Word (measured with a synthetic `distribute` paragraph): the break itself takes no gap.
#[test]
fn distributed_line_ending_in_line_break_reaches_the_margin() {
let first = "We tie the spend";
let text = format!("{first}\nto a pipe");
// The left edge of the first line's last character and the position after it, on the page.
let last = |align: Align| {
let mut d = Document::from_text("");
let mut p = wordcraft_doc::Paragraph::with_text(&text, Default::default());
p.props = ParaProps { align: Some(align), ..Default::default() };
d.body = vec![wordcraft_doc::para_block(p)];
let l = lay(&d);
let (para, x) =
l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, x, .. } = it { Some((para.clone(), *x)) } else { None }).unwrap();
(para.x_of(0, first.len() - 1).unwrap() + x, para.x_of(0, first.len()).unwrap() + x)
};
let (left_from, left_to) = last(Align::Left);
let (from, _) = last(Align::Distribute);
// The last character keeps its own advance and ends at the margin: no gap is left after it.
let ink_end = from + (left_to - left_from);
assert!((ink_end - 540.0).abs() < 0.05, "the line's last character ends at {ink_end}, not the margin");
}
#[test]
fn lines_with_tabs_never_shrink() {
let text = "Item\tWe tie the spend to a pipe and to the books, so it is in an ad hoc view of all of it. ".repeat(30);
@@ -5951,9 +6036,8 @@ fn float_follows_its_paragraph_to_the_next_page() {
assert!(para.lines[0].left >= 144.0, "text wraps beside it: {}", para.lines[0].left);
}
/// A floating object belongs to its paragraph, not to the line holding its anchor: Word draws
/// it on the page the paragraph starts on. A Word cover page is one paragraph holding a page
/// break and then the page-anchored text box with the title; the box stays on the cover.
/// A Word cover page is one paragraph holding a page break and then the page-anchored text box
/// with the title: with nothing after its anchor, the box stays on the cover.
#[test]
fn a_float_anchored_after_a_page_break_stays_on_its_paragraph_s_first_page() {
let mut d = Document::from_text(&format!("{}\nAfter the cover", wordcraft_doc::para::PAGE_BREAK));
@@ -5966,6 +6050,347 @@ fn a_float_anchored_after_a_page_break_stays_on_its_paragraph_s_first_page() {
assert!(shapes(&l.pages[1].items).is_empty(), "and not again on page two");
}
/// #4262: a bookmark after the box's anchor (or a comment's end, a field's) takes no room: the box
/// still stays on the cover. An inline picture after it does take room: it goes on to page two,
/// and the box with it.
#[test]
fn a_cover_box_stays_on_the_cover_with_a_bookmark_after_it_but_not_with_a_picture() {
let cover = |after: InlineObject| {
let mut d = Document::from_text(&format!("{}\nAfter the cover", wordcraft_doc::para::PAGE_BREAK));
d.insert_object(&Pos::body(0, 1), after, &Default::default()).unwrap();
d.insert_object(&Pos::body(0, 1), rect_shape(200.0, 100.0, page_float(100.0, 300.0)), &Default::default()).unwrap();
let l = lay(&d);
// The floating box; the inline picture is 20 pt wide.
let boxes = |pi: usize| shapes(&l.pages[pi].items).iter().filter(|r| r.w > 100.0).count();
(boxes(0), boxes(1))
};
assert_eq!(cover(InlineObject::BookmarkEnd { name: "_GoBack".into() }), (1, 0), "with a bookmark: on the cover");
assert_eq!(cover(rect_shape(20.0, 20.0, Default::default())), (0, 1), "with an inline picture: on page two");
}
/// #4262: with text after the anchor, though, the line after the break is on the next page, and
/// so is the float anchored at its start. Observed in Word for Mac: a shape dragged beside the
/// first line after a page break inside a paragraph is anchored right after the break and stays
/// on the new page, positioned from the paragraph's top there.
#[test]
fn a_float_anchored_before_text_after_a_page_break_is_drawn_on_the_next_page() {
use wordcraft_doc::para::{Anchor, Float, Wrap};
let text = "The quick brown fox jumps over the lazy dog. ";
let mut d = Document::from_text(&format!("{}{}{}", text.repeat(5), wordcraft_doc::para::PAGE_BREAK, text.repeat(5)));
let at = text.len() * 5 + wordcraft_doc::para::PAGE_BREAK.len_utf8();
let f = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 60.0, y: 1.0, ..Default::default() };
d.insert_object(&Pos::body(0, at), rect_shape(100.0, 50.0, f), &Default::default()).unwrap();
let l = lay(&d);
assert_eq!(l.pages.len(), 2);
assert!(shapes(&l.pages[0].items).is_empty(), "not on page one");
let (top, ..) = lines_on(&l, 1)[0];
assert_eq!(shapes(&l.pages[1].items).len(), 1, "drawn once");
let r = shapes(&l.pages[1].items)[0];
assert!((r.y - (top + 1.0)).abs() < 0.5, "1 pt below the paragraph's top on page two ({top}): {r:?}");
}
/// The lines of body paragraph 0 on page `pi`: each one's (top on the page, left, start).
fn lines_on(l: &DocLayout, pi: usize) -> Vec<(f32, f32, usize)> {
let mut out = Vec::new();
for it in &l.pages[pi].items {
if let Placed::Lines { para, l0, l1, y, story: StoryRef::Body, path, .. } = it
&& path.0 == [0]
{
let first = para.lines[*l0].top;
out.extend(para.lines[*l0..*l1].iter().map(|li| (y + li.top - first, li.left, li.start)));
}
}
out
}
/// #4250: a floating object anchored in a line of a long paragraph on a later page is drawn on
/// that page, as Word does (its anchor line's page), not on the page the paragraph starts on.
/// That page's text wraps around it; the page before is laid out as without it.
#[test]
fn a_float_anchored_on_a_later_page_of_its_paragraph_is_drawn_on_that_page() {
use wordcraft_doc::para::Wrap;
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(400));
let plain = lay(&d);
assert!(plain.pages.len() >= 3, "pages {}", plain.pages.len());
let anchor = lines_on(&plain, 1)[5].2;
let f = wordcraft_doc::para::Float { wrap: Wrap::Square, ..page_float(72.0, 300.0) };
d.insert_object(&Pos::body(0, anchor), rect_shape(100.0, 50.0, f), &Default::default()).unwrap();
let l = lay(&d);
assert!(shapes(&l.pages[0].items).is_empty(), "not on the page the paragraph starts on");
assert_eq!(l.pages.iter().map(|p| shapes(&p.items).len()).sum::<usize>(), 1, "drawn once");
let on_two = shapes(&l.pages[1].items);
assert_eq!(on_two.len(), 1, "{on_two:?}");
assert!((on_two[0].x - 72.0).abs() < 0.5 && (on_two[0].y - 300.0).abs() < 0.5, "{:?}", on_two[0]);
let beside: Vec<_> = lines_on(&l, 1).into_iter().filter(|(y, ..)| *y > 300.0 && *y < 350.0).collect();
assert!(!beside.is_empty() && beside.iter().all(|(_, left, _)| *left >= 100.0), "the text beside it wraps: {beside:?}");
let starts = |l: &DocLayout| lines_on(l, 0).iter().map(|(_, left, start)| (*left, *start)).collect::<Vec<_>>();
assert_eq!(starts(&l), starts(&plain), "page one is as without it");
// Its hit area is there too, for selecting and dragging it.
let hit = l.object(&Pos::body(0, anchor), 0).expect("laid out");
assert_eq!(hit.page, 1);
}
/// #4250: positioned from its paragraph, a float anchored on a later page of the paragraph is
/// measured from where the paragraph continues on that page (Word saves such a picture dragged
/// onto page two as `relativeFrom="paragraph"` with its offset from that page's top line).
#[test]
fn a_float_from_its_paragraph_on_a_later_page_is_measured_from_the_paragraph_s_top_there() {
use wordcraft_doc::para::{Anchor, Float, Wrap};
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(400));
let plain = lay(&d);
let (top, _, _) = lines_on(&plain, 1)[0];
let anchor = lines_on(&plain, 1)[8].2;
let f = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 120.0, y: 150.0, dist: 9.0, ..Default::default() };
d.insert_object(&Pos::body(0, anchor), rect_shape(130.0, 100.0, f), &Default::default()).unwrap();
let l = lay(&d);
assert!(shapes(&l.pages[0].items).is_empty());
let r = shapes(&l.pages[1].items)[0];
assert!((r.y - (top + 150.0)).abs() < 0.5, "150 pt below the paragraph's top on page two ({top}): {r:?}");
assert!((r.x - 192.0).abs() < 0.5, "{r:?}");
let hit = l.object(&Pos::body(0, anchor), 1).expect("laid out");
assert!((hit.origin.y - top).abs() < 0.5, "dragging measures from there too: {:?}", hit.origin);
}
/// #4250: a paragraph starting with a page break has its space before on the new page; a float
/// from its paragraph anchored there is still measured from the paragraph's top, above that
/// space, as on its first page.
#[test]
fn a_float_after_a_leading_page_break_is_measured_from_above_the_space_before() {
use wordcraft_doc::para::{Anchor, Float, Wrap};
let text = format!("Page one.\n{}{}", wordcraft_doc::para::PAGE_BREAK, "The quick brown fox jumps over the lazy dog. ".repeat(20));
let mut d = Document::from_text(&text);
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(std::sync::Arc::make_mut) {
p.props.space_before = Some(24.0);
}
let f = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: 150.0, dist: 9.0, ..Default::default() };
d.insert_object(&Pos::body(1, 200), rect_shape(130.0, 100.0, f), &Default::default()).unwrap();
let l = lay(&d);
assert!(shapes(&l.pages[0].items).is_empty());
let r = shapes(&l.pages[1].items)[0];
assert!((r.y - (72.0 + 150.0)).abs() < 0.5, "150 pt below the top margin: {r:?}");
}
/// #4250, as observed in Word for Mac: lines added at the top of page one push the text down,
/// but a picture positioned from its paragraph on page two stays where it is there.
#[test]
fn text_added_on_page_one_leaves_a_float_on_page_two_where_it_is() {
use wordcraft_doc::para::{Anchor, Float, Wrap};
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(400));
let anchor = lines_on(&lay(&d), 1)[8].2;
let f = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: 150.0, ..Default::default() };
d.insert_object(&Pos::body(0, anchor), rect_shape(130.0, 100.0, f), &Default::default()).unwrap();
let before = shapes(&lay(&d).pages[1].items);
for _ in 0..3 {
d.body.insert(0, wordcraft_doc::para_block(wordcraft_doc::Paragraph::new()));
}
let l = lay(&d);
assert!(shapes(&l.pages[0].items).is_empty());
assert_eq!(shapes(&l.pages[1].items), before);
}
/// #4250: anchored on the third page of a paragraph, a float is drawn on the third page.
#[test]
fn a_float_anchored_two_pages_into_its_paragraph_is_drawn_on_that_page() {
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(600));
let plain = lay(&d);
assert!(plain.pages.len() >= 4, "pages {}", plain.pages.len());
let anchor = lines_on(&plain, 2)[3].2;
let f = wordcraft_doc::para::Float { wrap: wordcraft_doc::para::Wrap::Square, ..page_float(72.0, 300.0) };
d.insert_object(&Pos::body(0, anchor), rect_shape(100.0, 50.0, f), &Default::default()).unwrap();
let l = lay(&d);
let per_page: Vec<usize> = l.pages.iter().map(|p| shapes(&p.items).len()).collect();
assert_eq!(&per_page[..3], [0, 0, 1], "{per_page:?}");
assert_eq!(per_page.iter().sum::<usize>(), 1);
}
/// A long paragraph with a long footnote on page one, and a page-placed square float anchored at
/// line `k` of page two as laid out without it.
fn footnoted_float(k: usize) -> DocLayout {
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(400));
let mut note = wordcraft_doc::Paragraph::with_text(&"The note text runs on for a while. ".repeat(30), Default::default()).styled("FootnoteText");
note.props.space_after = Some(0.0);
let id = d.add_part(wordcraft_doc::PartKind::Footnote, vec![wordcraft_doc::para_block(note)]);
d.insert_object(
&Pos::body(0, 4),
InlineObject::NoteRef { kind: wordcraft_doc::para::NoteKind::Footnote, id, custom: String::new() },
&Default::default(),
)
.unwrap();
let anchor = lines_on(&lay(&d), 1)[k].2;
let f = wordcraft_doc::para::Float { wrap: wordcraft_doc::para::Wrap::Square, ..page_float(72.0, 300.0) };
d.insert_object(&Pos::body(0, anchor), rect_shape(100.0, 50.0, f), &Default::default()).unwrap();
lay(&d)
}
/// #4250: a footnote on page one leaves less room there than its lines alone suggest; a float
/// anchored a few lines into page two is drawn on page two all the same.
#[test]
fn a_float_anchored_just_past_a_page_of_footnotes_is_drawn_on_the_next_page() {
let l = footnoted_float(3);
assert!(shapes(&l.pages[0].items).is_empty(), "not on page one");
assert_eq!(shapes(&l.pages[1].items).len(), 1);
}
/// #4250: anchored in page two's first line, which goes back to page one once the float no longer
/// wraps the text there, a float stays on page one with the text wrapping around it, not over it.
#[test]
fn a_float_whose_anchor_comes_back_to_page_one_stays_there_with_the_text_around_it() {
let l = footnoted_float(0);
assert_eq!(l.pages.iter().map(|p| shapes(&p.items).len()).collect::<Vec<_>>()[..2], [1, 0]);
let beside: Vec<_> = lines_on(&l, 0).into_iter().filter(|(y, ..)| *y > 300.0 && *y < 350.0).collect();
assert!(!beside.is_empty() && beside.iter().all(|(_, left, _)| *left >= 100.0), "the text wraps around it: {beside:?}");
}
/// #4250: the text wrapping around that float again pushes a footnote reference beside its anchor
/// back to page two; the note goes with it, once, not left on page one as well.
#[test]
fn a_footnote_pushed_on_by_a_float_coming_back_is_on_its_reference_s_page_only() {
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(400));
let note = |text: &str| {
let mut p = wordcraft_doc::Paragraph::with_text(text, Default::default()).styled("FootnoteText");
p.props.space_after = Some(0.0);
vec![wordcraft_doc::para_block(p)]
};
let noteref = |id| InlineObject::NoteRef { kind: wordcraft_doc::para::NoteKind::Footnote, id, custom: String::new() };
let long = d.add_part(wordcraft_doc::PartKind::Footnote, note(&"The note text runs on for a while. ".repeat(30)));
d.insert_object(&Pos::body(0, 4), noteref(long), &Default::default()).unwrap();
let anchor = lines_on(&lay(&d), 1)[0].2;
let short = d.add_part(wordcraft_doc::PartKind::Footnote, note("A short note."));
d.insert_object(&Pos::body(0, anchor), noteref(short), &Default::default()).unwrap();
let f = wordcraft_doc::para::Float { wrap: wordcraft_doc::para::Wrap::Square, ..page_float(72.0, 300.0) };
d.insert_object(&Pos::body(0, anchor), rect_shape(100.0, 50.0, f), &Default::default()).unwrap();
let l = lay(&d);
assert_eq!(shapes(&l.pages[0].items).len(), 1, "the float stays on page one");
let at = anchor + wordcraft_doc::para::OBJ.len_utf8();
let ref_page = (0..l.pages.len()).rfind(|&pi| lines_on(&l, pi).first().is_some_and(|f| f.2 <= at));
assert_eq!(ref_page, Some(1), "the reference is pushed on to page two");
let notes: Vec<usize> = l
.pages
.iter()
.map(|pg| pg.items.iter().filter(|i| matches!(i, Placed::Lines { story: StoryRef::Part(p), .. } if *p == short)).count())
.collect();
assert_eq!(notes[..2], [0, 1], "the note is on its reference's page, once");
}
/// #4250: of two floats held back for page two, the one whose anchor comes back to page one stays
/// there; the other is still drawn on page two.
#[test]
fn of_two_floats_held_back_only_the_one_whose_anchor_comes_back_stays_on_page_one() {
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(400));
let mut note = wordcraft_doc::Paragraph::with_text(&"The note text runs on for a while. ".repeat(30), Default::default()).styled("FootnoteText");
note.props.space_after = Some(0.0);
let id = d.add_part(wordcraft_doc::PartKind::Footnote, vec![wordcraft_doc::para_block(note)]);
let noteref = InlineObject::NoteRef { kind: wordcraft_doc::para::NoteKind::Footnote, id, custom: String::new() };
d.insert_object(&Pos::body(0, 4), noteref, &Default::default()).unwrap();
let lines = lines_on(&lay(&d), 1);
let f = |y| wordcraft_doc::para::Float { wrap: wordcraft_doc::para::Wrap::Square, ..page_float(72.0, y) };
d.insert_object(&Pos::body(0, lines[3].2), rect_shape(100.0, 50.0, f(400.0)), &Default::default()).unwrap();
d.insert_object(&Pos::body(0, lines[0].2), rect_shape(100.0, 50.0, f(300.0)), &Default::default()).unwrap();
let l = lay(&d);
let ys = |pi: usize| shapes(&l.pages[pi].items).iter().map(|r| r.y).collect::<Vec<_>>();
assert_eq!((ys(0).len(), ys(1).len()), (1, 1), "one on each page: {:?} {:?}", ys(0), ys(1));
}
/// #4250: a footnote referenced on page two leaves less room there than its lines alone suggest;
/// a float anchored on the first line it pushes on to page three is drawn on page three.
#[test]
fn a_float_anchored_on_a_line_a_footnote_pushes_on_is_drawn_on_the_next_page() {
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(600));
let mut note = wordcraft_doc::Paragraph::with_text(&"The note text runs on for a while. ".repeat(30), Default::default()).styled("FootnoteText");
note.props.space_after = Some(0.0);
let id = d.add_part(wordcraft_doc::PartKind::Footnote, vec![wordcraft_doc::para_block(note)]);
let noteref = InlineObject::NoteRef { kind: wordcraft_doc::para::NoteKind::Footnote, id, custom: String::new() };
let at = lines_on(&lay(&d), 1)[1].2;
d.insert_object(&Pos::body(0, at), noteref, &Default::default()).unwrap();
// A word into the line: an anchor at its very start goes with the line before.
let anchor = lines_on(&lay(&d), 2)[0].2 + "The ".len();
let f = wordcraft_doc::para::Float { wrap: wordcraft_doc::para::Wrap::Square, ..page_float(72.0, 300.0) };
d.insert_object(&Pos::body(0, anchor), rect_shape(100.0, 50.0, f), &Default::default()).unwrap();
let l = lay(&d);
let anchor_page = (0..l.pages.len()).rfind(|&pi| lines_on(&l, pi).first().is_some_and(|f| f.2 <= anchor));
let per_page: Vec<usize> = l.pages.iter().map(|p| shapes(&p.items).len()).collect();
assert_eq!(anchor_page, Some(2), "the anchor is on page three");
assert_eq!(&per_page[..3], [0, 0, 1], "{per_page:?}");
let beside: Vec<_> = lines_on(&l, 1).into_iter().filter(|(y, ..)| *y > 300.0 && *y < 350.0).collect();
assert!(!beside.is_empty() && beside.iter().all(|(_, left, _)| *left < 1.0), "page two doesn't wrap around it: {beside:?}");
}
/// #4250: widow control takes the line before a paragraph's last on to the next page with it; a
/// float anchored there is drawn on that page.
#[test]
fn a_float_anchored_on_a_line_widow_control_takes_on_is_drawn_on_the_next_page() {
// A paragraph of three pages whose last two lines are on the third only by widow control.
let (mut d, l) = (150..300)
.map(|k| Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(k)))
.map(|d| {
let l = lay(&d);
(d, l)
})
.find(|(_, l)| l.pages.len() == 3 && lines_on(l, 2).len() == 2 && lines_on(l, 1).len() < lines_on(l, 0).len())
.expect("a paragraph ending in a widow");
let anchor = lines_on(&l, 2)[0].2 + "The ".len();
d.insert_object(&Pos::body(0, anchor), rect_shape(100.0, 50.0, page_float(72.0, 300.0)), &Default::default()).unwrap();
let per_page: Vec<usize> = lay(&d).pages.iter().map(|p| shapes(&p.items).len()).collect();
assert_eq!(per_page, [0, 0, 1]);
}
/// #4250: a float whose own wrap pushes its anchor line on to the next page stays on the page
/// whose lines it was placed with, as before, with the text there wrapping around it.
#[test]
fn a_float_whose_wrap_pushes_its_own_line_on_stays_with_the_text_around_it() {
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(600));
let last = *lines_on(&lay(&d), 1).last().unwrap();
let anchor = last.2 + "The ".len();
let f = wordcraft_doc::para::Float { wrap: wordcraft_doc::para::Wrap::Square, ..page_float(72.0, 300.0) };
d.insert_object(&Pos::body(0, anchor), rect_shape(200.0, 100.0, f), &Default::default()).unwrap();
let l = lay(&d);
let anchor_page = (0..l.pages.len()).rfind(|&pi| lines_on(&l, pi).first().is_some_and(|f| f.2 <= anchor));
assert_eq!(anchor_page, Some(2), "its wrap pushes the anchor on to page three");
let per_page: Vec<usize> = l.pages.iter().map(|p| shapes(&p.items).len()).collect();
assert_eq!(&per_page[..3], [0, 1, 0], "{per_page:?}");
let beside: Vec<_> = lines_on(&l, 1).into_iter().filter(|(y, ..)| *y > 300.0 && *y < 400.0).collect();
assert!(!beside.is_empty() && beside.iter().all(|(_, left, _)| *left >= 200.0), "the text wraps around it: {beside:?}");
}
/// #4250: holding back a float for a later page lays its paragraph out again; its automatic
/// equation numbers aren't counted twice: they read (1), (2).
#[test]
fn a_paragraph_with_a_float_for_a_later_page_keeps_its_equation_numbers() {
let eq = |s: &str| InlineObject::Equation {
linear: s.into(),
display: true,
math: wordcraft_doc::math::Math { nodes: wordcraft_doc::math::parse_linear(s), ..Default::default() },
};
let mut d = Document::from_text(&format!("{}\n", "The quick brown fox jumps over the lazy dog. ".repeat(400)));
let anchor = lines_on(&lay(&d), 1)[5].2;
let f = wordcraft_doc::para::Float { wrap: wordcraft_doc::para::Wrap::Square, ..page_float(72.0, 300.0) };
d.insert_object(&Pos::body(0, anchor), rect_shape(100.0, 50.0, f), &Default::default()).unwrap();
let n = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().len();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().insert_object(n, eq("a=b#"), &Default::default()).unwrap();
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().insert_object(0, eq("c=d#"), &Default::default()).unwrap();
let l = lay(&d);
assert_eq!(shapes(&l.pages[1].items).len(), 1, "held back for page two");
assert_eq!(equation_numbers(&l), ["(1)", "(2)"]);
}
/// #4250: in two columns, a float anchored where the paragraph continues in the second column of
/// the same page is placed with its first piece, as before, so the first column wraps around it.
#[test]
fn a_float_anchored_in_the_next_column_of_the_page_stays_with_its_first_piece() {
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(120));
d.last_section.columns.count = 2;
let plain = lay(&d);
let lines = lines_on(&plain, 0);
let second = lines.iter().position(|w| w.0 < lines[0].0 + 0.5 && w.2 > 0).expect("a second column on page one");
let anchor = lines[second + 2].2;
let f = wordcraft_doc::para::Float { wrap: wordcraft_doc::para::Wrap::Square, ..page_float(72.0, 200.0) };
d.insert_object(&Pos::body(0, anchor), rect_shape(100.0, 50.0, f), &Default::default()).unwrap();
let l = lay(&d);
assert_eq!(shapes(&l.pages[0].items).len(), 1, "on page one");
let beside: Vec<_> = lines_on(&l, 0).into_iter().filter(|(y, left, start)| *y > 200.0 && *y < 250.0 && *start < anchor && *left >= 0.0).collect();
assert!(!beside.is_empty() && beside.iter().all(|(_, left, _)| *left >= 100.0), "the first column wraps around it: {beside:?}");
}
/// Floating objects are drawn in their stacking order (`relativeHeight`), not in the order of
/// their anchors: a panel anchored after the text box it frames, but lower in the stack, is
/// drawn first so the box stays visible over it. Objects without an order keep theirs.
@@ -12441,6 +12866,135 @@ fn caret_height_ignores_line_spacing() {
}
}
#[test]
fn bottom_border_reserves_gap() {
use wordcraft_doc::props::{BorderStyle, Borders};
for part in [None, Some(wordcraft_doc::PartKind::Header), Some(wordcraft_doc::PartKind::Footer)] {
let mut positions = Vec::new();
for style in [BorderStyle::None, BorderStyle::Single] {
let mut d = Document::from_text("First\nNext");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().props.borders =
Some(Borders { bottom: Some(Border { style, width: 0.5, space: 2.0, color: None }), ..Default::default() });
if let Some(kind) = part {
let id = d.add_part(kind, d.body.clone());
d.body = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Body", Default::default()))];
match kind {
wordcraft_doc::PartKind::Header => d.last_section.headers.default = Some(id),
_ => d.last_section.footers.default = Some(id),
}
}
let l = lay(&d);
let items = match part {
Some(wordcraft_doc::PartKind::Header) => &l.pages[0].header,
Some(_) => &l.pages[0].footer,
None => &l.pages[0].items,
};
let top = |block| {
items
.iter()
.find_map(|it| match it {
Placed::Lines { path, y, .. } if *path == Path::top(block) => Some(*y),
_ => None,
})
.unwrap()
};
positions.push(top(1) - top(0));
}
assert!((positions[1] - positions[0] - 2.5).abs() < 0.01, "{part:?}: {positions:?}");
}
}
#[test]
fn bottom_border_keeps_chain() {
use wordcraft_doc::props::LineSpacing;
const LINE_HEIGHT: f32 = 12.0;
for bordered in [1, 2] {
for style in [BorderStyle::None, BorderStyle::Single] {
let mut d = Document::from_text("Filler\nHeading\nRuled\nBody");
// Four 12pt lines fit; the border band makes the kept chain exceed the remainder.
d.last_section.page_h = d.last_section.margin_top + d.last_section.margin_bottom + 4.0 * LINE_HEIGHT + 1.0;
for block in 0..4 {
let p = d.para_mut(StoryRef::Body, &Path::top(block)).unwrap();
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
p.props.line_spacing = Some(LineSpacing::Exactly(LINE_HEIGHT));
p.props.keep_next = Some(block == 1 || block == 2);
if block == bordered {
p.props.borders = Some(Borders { bottom: Some(Border { style, width: 0.5, space: 2.0, color: None }), ..Default::default() });
}
}
let laid = lay(&d);
let heading_page = laid
.pages
.iter()
.position(|page| page.items.iter().any(|item| matches!(item, Placed::Lines { path, .. } if *path == Path::top(1))))
.unwrap();
assert_eq!(heading_page, usize::from(style == BorderStyle::Single), "bordered={bordered}, {style:?}");
}
}
}
#[test]
fn border_break_keeps_preflight() {
use wordcraft_doc::para::PAGE_BREAK;
use wordcraft_doc::props::LineSpacing;
const BODY_HEIGHT: f32 = 160.0;
const MARGIN: f32 = 20.0;
const LINE_HEIGHT: f32 = 10.0;
const BORDER_GAP: f32 = 20.0;
let make_para = |text: &str| {
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(10.0), ..Default::default() };
let mut p = Paragraph::with_text(text, chr);
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
p.props.line_spacing = Some(LineSpacing::Exactly(LINE_HEIGHT));
p.props.keep_lines = Some(true);
p.props.keep_next = Some(false);
p.props.borders =
Some(Borders { bottom: Some(Border { style: BorderStyle::Single, width: 1.0, space: BORDER_GAP, color: None }), ..Default::default() });
p
};
let fitting = format!("One{PAGE_BREAK}");
let tall = format!("One\nTwo{PAGE_BREAK}");
let mut measured = Document::new();
measured.body = vec![wordcraft_doc::para_block(make_para(&fitting))];
let l = lay(&measured);
let room = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Lines { para, .. } => Some(para.height),
_ => None,
})
.unwrap();
assert!(room > 0.0 && room + BORDER_GAP + 1.0 < BODY_HEIGHT);
for (text, expected) in [(fitting.as_str(), 0), (tall.as_str(), 1), ("One", 1)] {
let mut d = Document::new();
d.last_section.margin_top = MARGIN;
d.last_section.margin_bottom = MARGIN;
d.last_section.page_h = BODY_HEIGHT + 2.0 * MARGIN;
let mut filler = Paragraph::with_text("Filler", Default::default());
filler.props.space_before = Some(0.0);
filler.props.space_after = Some(0.0);
filler.props.line_spacing = Some(LineSpacing::Exactly(BODY_HEIGHT - room));
let mut after = Paragraph::with_text("After", Default::default());
after.props.space_before = Some(0.0);
after.props.space_after = Some(0.0);
after.props.line_spacing = Some(LineSpacing::Exactly(LINE_HEIGHT));
d.body = vec![wordcraft_doc::para_block(filler), wordcraft_doc::para_block(make_para(text)), wordcraft_doc::para_block(after)];
let l = lay(&d);
assert_eq!(l.caret(&Pos::body(1, 0)).unwrap().page, expected, "{text:?}: omit only the terminal break border extent");
let pieces: Vec<_> = l
.pages
.iter()
.enumerate()
.filter_map(|(page, p)| p.items.iter().any(|it| matches!(it, Placed::Lines { path, .. } if *path == Path::top(1))).then_some(page))
.collect();
assert_eq!(pieces, vec![expected], "{text:?}: keep the paragraph whole");
}
}
enum SpanWidth {
Preferred,
Automatic,
@@ -13122,6 +13676,104 @@ fn horizontal_rules_take_their_line() {
assert!(measured(100.0) < 150.0, "{}", measured(100.0));
}
/// A line's height with pictures raised or lowered and with legacy check boxes, in Word's numbers
/// (Arial at 10 and 20 pt, single, 1.15 and 1.5 spacing).
#[test]
fn lowered_pictures_and_check_boxes_take_words_line_heights() {
use wordcraft_doc::props::LineSpacing;
// A paragraph at `m` spacing from a lead, a picture and how far its run is raised: the line's
// height, its picture's top under the line's, and the font's height.
let line_of = |lead: &str, m: f32, h: f32, raise: f32| {
let mut d = Document::from_text(lead);
let props = wordcraft_doc::CharProps { position: Some(raise), ..Default::default() };
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.props.line_spacing = Some(LineSpacing::Multiple(m));
let at = p.len();
p.insert_object(at, picture(40.0, h, Default::default()), &props).unwrap();
let l = lay(&d);
let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!() };
let c = para.clusters.iter().find(|c| matches!(c.kind, para::ClKind::Object(_))).unwrap();
let (line, st) = (&para.lines[0], &para.styles[c.style as usize]);
(line.height, line.baseline - c.obj_h - line.top, st.ascent + st.descent)
};
for m in [1.0, 1.15, 1.5] {
let share = |font: f32| (m - 1.0) * font;
// Alone, lowered or not: the picture's height and the spacing's share, its top the line's.
for lowered in [0.0, 10.0, 30.0] {
let (h, top, font) = line_of("", m, 30.0, -lowered);
assert!((h - 30.0 - share(font)).abs() < 0.01 && top.abs() < 0.01, "lowered {lowered} at {m}: {h}, {top}");
}
// Raised: as far as it reaches.
let (h, top, font) = line_of("", m, 30.0, 10.0);
assert!((h - 40.0 - share(font)).abs() < 0.01 && top.abs() < 0.01, "raised at {m}: {h}, {top}");
// Shorter than the font: the font's height, and it ends at the font's bottom.
for (raise, reach) in [(0.0, 6.0), (-3.0, 6.0), (3.0, 9.0)] {
let (h, top, font) = line_of("", m, 6.0, raise);
assert!((h - font * m).abs() < 0.01 && (top - (font - reach)).abs() < 0.01, "{raise} at {m}: {h}, {top}");
}
// Beside text, lowered: the text's ascent is no matter, the picture reaching further.
let (h, top, font) = line_of("x", m, 30.0, -10.0);
assert!((h - 30.0 - share(font)).abs() < 0.01 && top.abs() < 0.01, "beside text at {m}: {h}, {top}");
}
// A check box sizes its line as text of its size, alone or beside text.
let box_line = |lead: &str, m: f32, size: u32| {
let mut d = Document::from_text(lead);
let form = format!(r#"<w:ffData><w:name w:val="Box"/><w:checkBox><w:size w:val="{size}"/></w:checkBox></w:ffData>"#);
let field = InlineObject::Field { instr: "FORMCHECKBOX".into(), result: String::new(), locked: false, dirty: false, code: false, form };
let props = wordcraft_doc::CharProps { size: Some(10.0), ..Default::default() };
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.props.line_spacing = Some(LineSpacing::Multiple(m));
let at = p.len();
p.insert_object(at, field, &props).unwrap();
let l = lay(&d);
let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!() };
let c = para.clusters.iter().find(|c| matches!(c.kind, para::ClKind::Object(_))).unwrap();
let st = &para.styles[c.style as usize];
(para.lines[0].height, st.ascent + st.descent)
};
for m in [1.0, 1.5] {
let (h, font) = box_line("", m, 40);
assert!((h - font * 2.0 * m).abs() < 0.01, "a 20 pt box in 10 pt text at {m}: {h}, font {font}");
}
}
/// A line of only a picture (and spaces) ends at the picture's bottom; with text beside the
/// picture the text's descent goes below it too (Word, measured with Aptos, Arial and Times New
/// Roman at 10 and 20 pt: a 30 pt picture alone or after spaces takes 30 pt at single spacing,
/// after a word 30 pt plus the descent).
#[test]
fn a_line_of_only_pictures_takes_no_descent() {
use wordcraft_doc::props::LineSpacing;
let line_of = |lead: &str| {
let mut d = Document::from_text(lead);
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(0).map(std::sync::Arc::make_mut) {
p.props.line_spacing = Some(LineSpacing::Multiple(1.0));
let at = p.len();
p.insert_object(at, picture(60.0, 30.0, Default::default()), &Default::default()).unwrap();
}
let l = lay(&d);
let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!() };
(para.lines[0].height, para.lines[0].baseline - para.lines[0].top, para.styles[0].descent)
};
for lead in ["", " "] {
let (h, base, _) = line_of(lead);
assert!((h - 30.0).abs() < 0.01 && (base - 30.0).abs() < 0.01, "{lead:?}: line {h}, baseline {base}");
}
let (h, base, desc) = line_of("Text ");
assert!((h - (30.0 + desc)).abs() < 0.01 && (base - 30.0).abs() < 0.01, "with text: line {h}, baseline {base}");
// A line break ending the picture's line is no text.
let mut d = Document::from_text("");
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(0).map(std::sync::Arc::make_mut) {
p.props.line_spacing = Some(LineSpacing::Multiple(1.0));
p.insert_object(0, picture(60.0, 30.0, Default::default()), &Default::default()).unwrap();
let at = p.len();
p.insert_text(at, &format!("{}Next", wordcraft_doc::para::LINE_BREAK), &Default::default()).unwrap();
}
let l = lay(&d);
let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!() };
assert!(para.lines.len() == 2 && (para.lines[0].height - 30.0).abs() < 0.01, "picture, then a line break: {}", para.lines[0].height);
}
/// A kept-together paragraph starting a continuous section low on a page, with room there for
/// one of its lines, moves whole to the next page, where it fits (#3907 review).
#[test]
+14
View File
@@ -324,6 +324,20 @@ fn floating_box_that_resizes_to_fit_takes_its_texts_height() {
assert!((shrunk.h - grown.h).abs() < 0.5, "{shrunk:?} {grown:?}");
}
/// #4250: on a later page of its paragraph, a floating box that resizes to fit its text takes its
/// text's height too.
#[test]
fn a_floating_box_on_a_later_page_of_its_paragraph_fits_its_text() {
let mut d = Document::from_text(&"The quick brown fox jumps over the lazy dog. ".repeat(400));
let float = wordcraft_doc::para::Float { wrap: wordcraft_doc::para::Wrap::Square, ..Default::default() };
let id = text_box_with(&mut d, 0, "Inside", 144.0, 1.0, TextBody { auto_fit: true, ..Default::default() }, float);
let l = lay(&d);
assert!(l.pages.len() >= 3, "pages {}", l.pages.len());
let hit = l.find_object(0, |o| o.text_box == Some(id)).unwrap();
assert!(hit.page > 0, "drawn on the page of its anchor");
assert!(hit.rect.h > 15.0 && hit.rect.h < 30.0, "one line and the margins: {:?}", hit.rect);
}
#[test]
fn a_turned_linked_box_turns_only_its_own_lines() {
// Linked boxes show the first box's story; turning the second box turns the lines it shows,
+1 -1
View File
@@ -19,7 +19,7 @@ mod input;
mod pictures;
mod prefs;
pub(crate) use commands::{discards_document, works_without_document};
pub(crate) use commands::works_without_document;
pub(crate) use input::control_click_as_secondary;
impl WordApp {
+12 -4
View File
@@ -44,10 +44,9 @@ impl WordApp {
self.dialog = dialogs::Dialog::open(name, self);
return Ok(json!({"pending": name}));
}
if (self.session.dirty || self.save_unconfirmed() || refused.is_some())
&& discards_document(id, &params)
&& !self.closes_only_its_window(id, &params)
{
// The same unsaved work the control channel's refusal covers, so the prompt and the
// refusal can't drift apart (#3274).
if (self.document_unsaved() || refused.is_some()) && discards_document(id, &params) && !self.closes_only_its_window(id, &params) {
let name = self.prompt_name();
self.dialog = Some(dialogs::Dialog::SaveChanges {
name,
@@ -119,6 +118,13 @@ impl WordApp {
if id == "file.close" {
return self.close_document(&params);
}
// `file.closeDocument` closes the document its `id` names (the active one by default):
// the same unsaved work would go with it, so it needs the same explicit `force` (#3274).
if id == "file.closeDocument"
&& let Some(e) = crate::control::close_refused(self, id, &params)
{
return Err(e.into());
}
if id == "file.autosave" {
return self.set_autosave(&params);
}
@@ -746,6 +752,7 @@ impl WordApp {
// Native printing submits the selected queue on a worker; the browser owns its dialog.
"ui.printSettings" => return Some(printing::settings(&mut self.printing, p, self.services.printers.as_ref())),
"ui.print" | "ui.printSubmit" => return Some(self.print_to_system(p)),
"ui.printCancel" => return Some(printing::cancel(self)),
// File › Options › General › Make WordCraft the default… changes the user's system
// default apps (Linux) or opens system settings (Windows), so only a click on that
// button does it ([`WordApp::make_default_app`]); scripts, the control channel and
@@ -1054,6 +1061,7 @@ pub(crate) fn works_without_document(id: &str) -> bool {
| "ui.language"
| "ui.saveChanges"
| "ui.openFileDialog"
| "ui.printCancel"
| "ui.fileBrowser"
| "ui.makeDefaultApp"
| "ui.discord"
+9
View File
@@ -81,6 +81,15 @@ impl WordApp {
self.saves_in_flight.iter().any(|s| s.marked_saved && s.document == document)
}
/// Whether the shown document has work that isn't saved yet: changes that aren't written
/// to a file, or a save that hasn't come back. The Save Changes prompt appears for a
/// command that would replace the document; a programmatic call (control channel, MCP
/// bridge), which never prompts, refuses the command instead — so both paths guard the
/// same work (#1268, #3274).
pub(crate) fn document_unsaved(&self) -> bool {
self.document_unsaved_by_id(self.session.document_id())
}
/// The document's name as the Save Changes prompt shows it: its file's name, else its title.
pub(super) fn prompt_name(&self) -> String {
self.session.path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| self.title_stem())
+5
View File
@@ -2121,6 +2121,11 @@ fn an_agent_cannot_close_the_document_over_a_pending_comment_draft() {
assert!(crate::control::close_refused(h.state(), "file.close", &json!({})).is_some());
assert!(crate::control::close_refused(h.state(), "file.close", &json!({"force": true})).is_none());
assert!(crate::control::close_refused(h.state(), "text.insert", &json!({"text": "x"})).is_none());
// The same for the command that names the document it closes (#3274).
let doc = h.state().session.document_id();
assert!(crate::control::close_refused(h.state(), "file.closeDocument", &json!({})).is_some());
assert!(crate::control::close_refused(h.state(), "file.closeDocument", &json!({"id": doc})).is_some());
assert!(crate::control::close_refused(h.state(), "file.closeDocument", &json!({"force": true})).is_none());
}
/// #1348: a comment edit typed, then refused (the document became read-only).
+63 -7
View File
@@ -81,19 +81,57 @@ fn click_events(app: &mut WordApp, pos: egui::Pos2, button: egui::PointerButton,
/// Programmatic calls never open the Save prompt, so closing unsaved work must be explicit:
/// save first, or pass `"force": true` (only a real boolean true counts) to discard it (#1268).
pub(crate) fn close_refused(app: &WordApp, id: &str, params: &Value) -> Option<&'static str> {
// `file.close` closes only the drawn window when another window shows the same document:
// the document and its work stay open, so nothing is lost and nothing is refused (the
// interactive path asks nothing either) (#3274).
if app.closes_only_its_window(id, params) {
return None;
}
// The document the command closes: `file.close` the shown one, `file.closeDocument` the one
// its `id` names (the active one by default) (#3274).
let target = match id {
"file.close" => app.session.document_id(),
"file.closeDocument" => match params.get("id") {
None | Some(Value::Null) => app.session.document_id(),
// An `id` that isn't a document is the engine's error to give.
Some(v) => v.as_u64()?,
},
_ => return None,
};
close_refused_for(app, target, params)
}
/// The refusal for closing the document `target` with unsaved work in it: the same work the
/// Save Changes prompt asks about, so the prompt and the refusal cover the same ground
/// (#1268, #3274).
fn close_refused_for(app: &WordApp, target: u64, params: &Value) -> Option<&'static str> {
let force = params.get("force").and_then(Value::as_bool) == Some(true);
if force {
return None;
}
if id == "file.close" && app.session.dirty {
if app.document_unsaved_by_id(target) {
return Some(UNSAVED);
}
// Comment text still being typed is unsaved work too (#1348): replacing the document would drop it.
(crate::discards_document(id, params) && crate::panes::has_comment_drafts(app))
.then_some("a comment is still being edited: finish it first, or pass {\"force\": true} to discard it")
// Comment text still being typed is unsaved work too (#1348): closing the document would
// drop it.
app.document_has_comment_drafts(target).then_some(COMMENT_UNSAVED)
}
const UNSAVED: &str = "the document has unsaved changes: save it first, or pass {\"force\": true} to discard them and close";
const COMMENT_UNSAVED: &str = "a comment is still being edited: finish it first, or pass {\"force\": true} to discard it";
/// Quitting closes every open document, so unsaved work needs the same explicit `force` as
/// `file.close` rather than going silently (#1268, #3274). The interactive path asks about
/// each document in turn; a programmatic call never prompts, so it refuses.
fn quit_refused(app: &WordApp, params: &Value) -> Option<&'static str> {
let force = params.get("force").and_then(Value::as_bool) == Some(true);
if force {
return None;
}
app.has_unsaved_documents().then_some(UNSAVED_QUIT)
}
const UNSAVED_QUIT: &str = "a document has unsaved changes: save it first, or pass {\"force\": true} to quit without saving";
/// The reply to a request that needs a document while none is open (#1129).
const NO_DOCUMENT: &str = "no document is open; create one (file.new) or open one (file.open) first";
@@ -150,15 +188,28 @@ fn handle_in(app: &mut WordApp, doc: u64, method: &str, p: &Value) -> Outcome {
}
// Close, with the same guard as the window's: unsaved changes need `force`.
if id == "file.close" {
let force = params.get("force").and_then(Value::as_bool) == Some(true);
if !force && app.session.documents().iter().any(|d| d.id == doc && d.dirty) {
return err(UNSAVED);
if let Some(e) = close_refused_for(app, doc, &params) {
return err(e);
}
return match app.session.close_document(doc) {
Ok(()) => ok(json!({"closed": true, "id": doc, "documents": app.session.documents()})),
Err(e) => err(e),
};
}
if id == "file.closeDocument" {
// The document it names, or the one the request addresses.
let target = match params.get("id") {
None | Some(Value::Null) => doc,
// An `id` that isn't a document is the engine's error to give.
Some(v) => match v.as_u64() {
Some(id) => id,
None => return err("`id` must be an open document's id"),
},
};
if let Some(e) = close_refused_for(app, target, &params) {
return err(e);
}
}
let r = app.session.with_document(doc, |s| s.run(id, &params));
// UI requests the command made carry `document`, so the window can tell they aren't
// about the document it shows.
@@ -342,6 +393,11 @@ pub fn handle(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest) -> O
ok(json!({}))
}
"app.quit" => {
// Quitting closes every open document, so unsaved work needs the same explicit
// `force` as `file.close` rather than going silently (#3274).
if let Some(e) = quit_refused(app, p) {
return err(e);
}
app.quit_requested = true;
ok(json!({}))
}
+2 -2
View File
@@ -269,12 +269,12 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
/// The cursor over a crop handle (or while dragging one).
pub fn cursor(app: &WordApp, layout: &DocLayout, pages: &[Rect], scale: f32, at: Pos2) -> Option<egui::CursorIcon> {
if let Some(d) = &app.canvas.crop_drag {
return Some(d.handle.cursor());
return Some(d.handle.cursor(0.0));
}
let (page, rect) = laid_out(app, layout)?;
let f = screen(pages, scale, page, rect)?;
match frame::handle_at(f, 0.0, at) {
Some(h) => Some(h.cursor()),
Some(h) => Some(h.cursor(0.0)),
None if f.contains(at) => Some(egui::CursorIcon::Default),
None => None,
}
+13 -22
View File
@@ -1,7 +1,7 @@
use super::bookmarks::{bookmark, enclose_preview, icons_body, macros};
use super::chrome::{buttons, color_field};
use super::find::{FindTab, SEARCH_SUGGESTIONS, command_matches, find_in_navigation_pane, goto_body, special_menu, swallow_shortcut_text};
use super::font::{apply_font, font_box, preview_size};
use super::font::{apply_font, font_box, font_sample_box, font_sample_props, sample_paper};
use super::forms::{cell_margins_dialog, custom_properties, table_properties};
use super::mailings::{ADDRESS_PARTS, recipient_list, rule_params};
use super::page_setup::{page_layout_commands, page_paper_group, page_valign_combo, page_valign_value, run_as_one_step};
@@ -120,23 +120,8 @@ fn font_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
else {
return false;
};
// Build the sample text format for the preview pane below.
let preview_size = preview_size(size);
let preview_color = wordcraft_doc::Rgb::parse(color).map(crate::theme::c32).unwrap_or_else(|| ui.visuals().text_color());
let mut fmt =
egui::TextFormat { font_id: egui::FontId::new(preview_size, egui::FontFamily::Proportional), color: preview_color, ..Default::default() };
if *bold {
fmt.font_id = crate::theme::semibold(preview_size);
}
if *italic {
fmt.italics = true;
}
if *underline {
fmt.underline = egui::Stroke::new(1.0, preview_color);
}
if *strike {
fmt.strikethrough = egui::Stroke::new(1.0, preview_color);
}
let sample_props =
font_sample_props(app, sample_paper(app), font, size, color, (*bold, *italic, *underline, *strike), (*small_caps, *caps, *hidden), *spacing);
crate::rtl::Table::new("fontdlg").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
// Word's two font boxes when East Asian text is in use: the Latin text font and
// the Asian text font, each with its own list (type to find a font).
@@ -235,8 +220,17 @@ fn font_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
r.cell(|ui| ui.checkbox(strike, tl!("Strikethrough")));
});
t.row(|r| {
// Superscript and Subscript exclude each other: the one just ticked wins.
let was_sup = *sup;
r.cell(|ui| ui.checkbox(sup, tl!("Superscript")));
r.cell(|ui| ui.checkbox(sub, tl!("Subscript")));
if *sup && *sub {
if was_sup {
*sup = false;
} else {
*sub = false;
}
}
});
t.row(|r| {
r.cell(|ui| ui.checkbox(small_caps, tl!("Small caps")));
@@ -249,10 +243,7 @@ fn font_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
// Live preview of the chosen font/size/colour/effects.
ui.separator();
ui.label(egui::RichText::new(tl!("Preview")).small().weak());
let sample = if *caps { tl!("AaBbYyZz").to_uppercase() } else { tl!("AaBbYyZz").to_string() };
let mut job = egui::text::LayoutJob::single_section(sample, fmt);
job.wrap.max_width = ui.available_width().min(400.0);
ui.label(job);
font_sample_box(app, ui, sample_paper(app), &sample_props, (*sup, *sub), *hidden);
let (ok, cancel) = buttons(ui, tl!("OK"));
if ok {
apply_font(app, d);
+90 -1
View File
@@ -1,4 +1,4 @@
use super::{Dialog, Value, WordApp, json};
use super::{Dialog, Ui, Value, WordApp, json, vec2};
/// The Font dialog preview's size: the Size box's points between 6 and 72, else 12. `"NaN"` and
/// `"inf"` parse as floats too, and a NaN font size trips epaint's glyph assertion (#3663).
@@ -6,6 +6,95 @@ pub(super) fn preview_size(size: &str) -> f32 {
size.trim().parse::<f32>().ok().filter(|pt| pt.is_finite()).unwrap_or(12.0).clamp(6.0, 72.0)
}
/// The page colour the sample sits on.
pub(super) fn sample_paper(app: &WordApp) -> wordcraft_doc::Rgb {
app.session.doc.settings.page_color.unwrap_or(wordcraft_doc::Rgb(255, 255, 255))
}
const SAMPLE_WIDTH: f32 = 300.0;
/// The sample's character properties: the dialog's fields as the document reads them.
#[allow(clippy::too_many_arguments)]
pub(super) fn font_sample_props(
app: &mut WordApp,
paper: wordcraft_doc::Rgb,
font: &str,
size: &str,
color: &str,
(bold, italic, underline, strike): (bool, bool, bool, bool),
(small_caps, caps, hidden): (bool, bool, bool),
spacing: f32,
) -> wordcraft_doc::props::CharProps {
use wordcraft_doc::props::{CharProps, TextColor, Underline};
// Automatic text is black, or white on a dark page.
let dark = u32::from(paper.0) * 299 + u32::from(paper.1) * 587 + u32::from(paper.2) * 114 < 128_000;
let auto = if dark { 255 } else { 0 };
let ink = wordcraft_doc::Rgb::parse(color).unwrap_or(wordcraft_doc::Rgb(auto, auto, auto));
// A hidden run is dotted, as Word draws hidden text when it is shown.
let line = if underline {
Underline::Single
} else if hidden {
Underline::Dotted
} else {
Underline::None
};
CharProps {
font: Some(app.previews.font_stored(font)),
size: Some(preview_size(size).min(40.0)),
bold: Some(bold),
italic: Some(italic),
underline: Some(line),
strike: Some(strike),
color: Some(TextColor::Rgb(ink)),
caps: Some(caps),
small_caps: Some(small_caps),
spacing: Some(spacing),
..Default::default()
}
}
/// Draws the Font dialog's sample. A raised or lowered "2" follows the text
/// when Superscript or Subscript is on.
pub(super) fn font_sample_box(
app: &mut WordApp,
ui: &mut Ui,
paper: wordcraft_doc::Rgb,
props: &wordcraft_doc::props::CharProps,
(sup, sub): (bool, bool),
hidden: bool,
) {
use wordcraft_doc::props::VertAlign;
let dark = app.session.view.dark_mode;
let mut render_options = crate::canvas::screen_render_options();
render_options.dark = dark;
render_options.dark_paper = wordcraft_render::DARK_PAPER;
let display_paper = render_options.paper_of(&app.session.doc);
let mark = if sup {
Some(VertAlign::Superscript)
} else if sub {
Some(VertAlign::Subscript)
} else {
None
};
// A fixed width: sizing it from the dialog's width would grow the dialog frame by frame.
let (w, h) = (SAMPLE_WIDTH, 56.0);
let ppp = ui.ctx().pixels_per_point();
let text = tl!("AaBbYyZz");
let key = format!("fontsample:{text}:{props:?}:{mark:?}:{paper:?}:{display_paper:?}:{dark}:{w}:{ppp}");
let tex = app.previews.get_or(ui.ctx(), &key, || crate::previews::font_sample(text, props, mark, (w, h, ppp), paper, dark));
let (r, _) = ui.allocate_exact_size(vec2(w + 4.0, h + 2.0), egui::Sense::hover());
let t = crate::theme::Tokens::get(ui.ctx());
let page = crate::theme::c32(display_paper);
ui.painter().rect(r, 6.0, page, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
if let Some(tex) = tex {
let full = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0));
ui.painter().image(tex.id(), egui::Rect::from_min_size(r.min, tex.size_vec2() / ppp), full, egui::Color32::WHITE);
}
if hidden {
ui.label(egui::RichText::new(tl!("Hidden text is not shown unless you display it.")).small().weak());
}
}
/// One of the Font dialog's font boxes: type to find a font, with the missing-font warning
/// `shown_as` (the families drawn instead of `current`, see [`WordApp::font_dialog_warning`]).
pub(super) fn font_box(
+37
View File
@@ -1916,3 +1916,40 @@ fn the_page_waits_for_the_keyboard_until_a_modal_dialog_closes() {
h.run_steps(2);
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "!", "the page has it after the dialog");
}
#[test]
fn font_sample_props_map_each_field_to_its_property() {
use super::font::font_sample_props;
use wordcraft_doc::props::Underline;
let mut app = app_with("Example");
let white = wordcraft_doc::Rgb(255, 255, 255);
let mut p = |fx: (bool, bool, bool, bool), sc: (bool, bool, bool)| font_sample_props(&mut app, white, "Serif", "12", "", fx, sc, 1.5);
let q = p((true, false, false, true), (true, false, false));
assert_eq!((q.bold, q.italic, q.strike), (Some(true), Some(false), Some(true)));
assert_eq!((q.small_caps, q.caps, q.spacing), (Some(true), Some(false), Some(1.5)));
let q = p((false, true, false, false), (false, true, false));
assert_eq!((q.italic, q.small_caps, q.caps), (Some(true), Some(false), Some(true)));
assert_eq!(p((false, false, false, false), (false, false, true)).underline, Some(Underline::Dotted));
assert_eq!(p((false, false, true, false), (false, false, true)).underline, Some(Underline::Single));
}
#[test]
fn font_dialog_opens_at_its_final_size() {
let mut app = app_with("Example");
app.dialog = Dialog::open("font", &mut app);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
use egui_kittest::kittest::Queryable;
let mut widths = Vec::new();
for _ in 0..8 {
h.step();
widths.push(h.get_by_label("OK").rect().min.x);
}
assert!(widths[2..].windows(2).all(|w| w[0] == w[1]), "the dialog keeps growing: {widths:?}");
}
+20 -4
View File
@@ -137,6 +137,24 @@ impl WordApp {
Ok(())
}
/// Whether the open document `id` has changes that aren't written to a file yet, or a save
/// the browser hasn't confirmed. The Save Changes prompt asks about the same work, so the
/// prompt and a programmatic refusal cannot drift apart (#1268, #3274).
pub(crate) fn document_unsaved_by_id(&self, id: u64) -> bool {
let dirty = self.session.document_dirty(id);
let unconfirmed = self.saves_in_flight.iter().any(|s| s.marked_saved && s.document == id);
dirty || unconfirmed
}
/// Whether the open document `id` has comment or reply text typed but not yet written to
/// it (#1348): closing the document would drop that text.
pub(crate) fn document_has_comment_drafts(&self, id: u64) -> bool {
if id == self.session.document_id() {
return panes::has_comment_drafts(self);
}
self.parked.get(&id).is_some_and(|p| !p.comment_drafts.is_empty())
}
/// The open documents with work that would be lost on quitting: the shown one first, then
/// the others in the order they were opened. Unsaved changes, a save the browser hasn't
/// confirmed, or comment text not yet written to the document. The Start screen's
@@ -144,13 +162,11 @@ impl WordApp {
fn unsaved_documents(&self) -> Vec<u64> {
let active = self.session.document_id();
let mut out = Vec::new();
if self.has_document() && (self.session.dirty || self.save_unconfirmed() || panes::has_comment_drafts(self)) {
if self.has_document() && (self.document_unsaved_by_id(active) || self.document_has_comment_drafts(active)) {
out.push(active);
}
for d in self.session.documents() {
let unconfirmed = || self.saves_in_flight.iter().any(|s| s.marked_saved && s.document == d.id);
let drafts = || self.parked.get(&d.id).is_some_and(|p| !p.comment_drafts.is_empty());
if d.id != active && Some(d.id) != self.no_document && (d.dirty || unconfirmed() || drafts()) {
if d.id != active && Some(d.id) != self.no_document && (self.document_unsaved_by_id(d.id) || self.document_has_comment_drafts(d.id)) {
out.push(d.id);
}
}
+42 -7
View File
@@ -49,11 +49,17 @@ impl Handle {
pub fn is_corner(self) -> bool {
self.x != 0 && self.y != 0
}
pub fn cursor(self) -> CursorIcon {
match (self.x, self.y) {
(0, _) => CursorIcon::ResizeVertical,
(_, 0) => CursorIcon::ResizeHorizontal,
(a, b) if a == b => CursorIcon::ResizeNwSe,
/// The resize arrow over it on a frame turned `deg`: its way out from the centre, turned with
/// the frame, to the nearest of the four arrows.
pub fn cursor(self, deg: f32) -> CursorIcon {
// Screen y points down, so the angle counts clockwise like `deg`; an arrow points both
// ways, so only the angle modulo 180° matters (opposite handles get the same arrow). The
// handle's own angle is a whole multiple of 45°: rounding it drops atan2's float error.
let a = f32::from(self.y).atan2(f32::from(self.x)).to_degrees().round() + wordcraft_geom::normalize_degrees(deg);
match (a.rem_euclid(180.0) / 45.0).round() as u8 % 4 {
0 => CursorIcon::ResizeHorizontal,
1 => CursorIcon::ResizeNwSe,
2 => CursorIcon::ResizeVertical,
_ => CursorIcon::ResizeNeSw,
}
}
@@ -87,10 +93,11 @@ pub enum Grab {
}
impl Grab {
pub fn cursor(self) -> CursorIcon {
/// The cursor over (or while dragging) what was grabbed on a frame turned `deg`.
pub fn cursor(self, deg: f32) -> CursorIcon {
match self {
Grab::Move => CursorIcon::Move,
Grab::Resize(h) => h.cursor(),
Grab::Resize(h) => h.cursor(deg),
Grab::Rotate => CursorIcon::Crosshair,
}
}
@@ -346,6 +353,34 @@ mod tests {
assert!(rotate_handle_at(f, 0.0, pos2(50.0, -22.0)) && !rotate_handle_at(f, 90.0, pos2(50.0, -22.0)));
}
#[test]
fn resize_arrows_turn_with_the_frame() {
use CursorIcon::{ResizeHorizontal as H, ResizeNeSw as NeSw, ResizeNwSe as NwSe, ResizeVertical as V};
// Unturned, clockwise from the top left.
let unturned: Vec<CursorIcon> = Handle::ALL.iter().map(|h| h.cursor(0.0)).collect();
assert_eq!(unturned, [NwSe, V, NeSw, H, NwSe, V, NeSw, H]);
let (top, right, corner) = (Handle { x: 0, y: -1 }, Handle { x: 1, y: 0 }, Handle { x: 1, y: 1 });
// Turned 90°: the top handle sits on the right and resizes left-right.
assert_eq!((top.cursor(90.0), right.cursor(90.0), corner.cursor(90.0)), (H, V, NeSw));
assert_eq!((top.cursor(-90.0), top.cursor(270.0), top.cursor(180.0)), (H, H, V));
// Turned 45°: the middle handles get diagonal arrows, the corners straight ones.
assert_eq!((top.cursor(45.0), right.cursor(45.0), corner.cursor(45.0)), (NeSw, NwSe, V));
assert_eq!((top.cursor(10.0), top.cursor(30.0), top.cursor(-30.0)), (V, NeSw, NwSe));
// Opposite handles share an arrow at any angle, also halfway between two arrows.
for deg in [22.5, 67.5, 112.5, -22.5, 350.0, 1000.0, -1e9] {
for h in Handle::ALL {
assert_eq!(h.cursor(deg), Handle { x: -h.x, y: -h.y }.cursor(deg), "{h:?} at {deg}°");
}
}
// A broken angle counts as unturned.
assert_eq!((top.cursor(f32::NAN), top.cursor(f32::INFINITY)), (V, V));
// A grabbed handle keeps the frame's arrow while it's dragged.
assert_eq!(
(Grab::Resize(top).cursor(90.0), Grab::Move.cursor(90.0), Grab::Rotate.cursor(90.0)),
(H, CursorIcon::Move, CursorIcon::Crosshair)
);
}
#[test]
fn moving_keeps_the_grab_point_under_the_pointer() {
let pages =
+1 -1
View File
@@ -111,7 +111,7 @@ mod services;
mod state;
use app::control_click_as_secondary;
pub(crate) use app::{discards_document, works_without_document};
pub(crate) use app::works_without_document;
pub use clock::now_ms;
pub use services::{HostSaveFn, Inbox, Services};
pub use state::{AutoSaveBlock, DefaultApp, SaveChoice, keeps_everything};
+174 -22
View File
@@ -9,8 +9,8 @@
//! was on is drawn again without it (see [`dragged_off_page`]), so it is not left behind where it
//! was. The drop is one command, one relayout.
//!
//! Dragging an In Line with Text object moves it within the text, as in Word: a dashed insertion
//! cursor follows the pointer through the text (#2233) and the drop puts it there, still inline
//! Dragging an In Line with Text object moves it within the text, as in Word: a bold insertion
//! cursor follows the pointer through the text (#2233, #4195) and the drop puts it there, still inline
//! (`arrange.bounds` / `arrange.copyTo` with `to`, #2234). A floating one goes where it's dropped.
//!
//! Moving a floating one snaps it to alignment guides ([`crate::guides`]): the page's edges and
@@ -19,6 +19,11 @@
//!
//! A selected connector shows a handle at each end instead of a frame: dragging one onto a shape
//! glues it to the nearest connection site there (`shape.connect`), elsewhere leaves it free.
//!
//! Inside a Drawing Canvas, a press on a member picks that member (`select.member`, #2637): it
//! gets the frame and handles, inside the canvas's frame, and is dragged, resized and turned on
//! its own; a press in a text box member's text puts the caret there. The canvas itself is
//! picked where no member is.
use egui::{Color32, Painter, Pos2, Rect, Ui};
use serde_json::json;
@@ -61,7 +66,7 @@ pub struct ObjectDrag {
/// The object drawn alone over its rotated bounds, for the preview: made once it moves.
preview: Option<egui::TextureHandle>,
/// Moving an In Line with Text object: the text position under the pointer, where it lands,
/// and the colour of the dashed insertion cursor drawn there.
/// and the colour of the bold insertion cursor drawn there.
drop_at: Option<(Pos, Color32)>,
}
@@ -128,22 +133,92 @@ fn active_story(app: &WordApp, layout: &DocLayout) -> StoryRef {
/// model for can be selected and deleted, not moved or resized, so it gets no handles, no move
/// cursor and no drag.
fn fixed(app: &WordApp, hit: &ObjectHit) -> bool {
let pos = hit.pos();
matches!(app.session.doc.para_at(&pos).and_then(|p| p.object_at(pos.off)), Some(InlineObject::Graphic { .. })) && !size_only(app, hit)
matches!(hit_object(app, hit), Some(InlineObject::Graphic { .. })) && !size_only(app, hit)
}
/// Whether the object under `hit` is a chart or SmartArt that WordCraft can edit: it takes
/// resize handles and is laid out again at the new size, but it can't be moved or turned.
fn size_only(app: &WordApp, hit: &ObjectHit) -> bool {
let pos = hit.pos();
matches!(
app.session.doc.para_at(&pos).and_then(|p| p.object_at(pos.off)),
hit_object(app, hit),
Some(InlineObject::Graphic { graphic, .. }) if graphic.chart.is_some() || graphic.smart_art.is_some()
)
}
/// The story of the selected text box.
/// The object a hit is: the object at its position, or the canvas member it names.
fn hit_object<'a>(app: &'a WordApp, hit: &ObjectHit) -> Option<&'a InlineObject> {
let pos = hit.pos();
let o = app.session.doc.para_at(&pos).and_then(|p| p.object_at(pos.off))?;
match (hit.member, o) {
(None, _) => Some(o),
(Some(i), InlineObject::Group { children, canvas: Some(_), .. }) => children.get(i).map(|c| &c.obj),
_ => None,
}
}
/// Member `index` of the canvas laid out at `canvas`, as a hit of its own: its frame where the
/// canvas draws it, its own turn. `None` when it isn't drawn, or the canvas is turned (its
/// members aren't picked on their own yet).
fn member_hit(app: &WordApp, canvas: &ObjectHit, index: usize) -> Option<ObjectHit> {
let (o, r) = (pickable_canvas(app, canvas)?, canvas.rect);
let (_, frame) = o.member_rects(r.x, r.y, r.w, r.h).into_iter().find(|(i, _)| *i == index)?;
member_with_frame(app, canvas, o, index, frame)
}
/// The canvas object of hit `canvas` when its members can be picked: a canvas, hit as a whole,
/// not turned.
fn pickable_canvas<'a>(app: &'a WordApp, canvas: &ObjectHit) -> Option<&'a InlineObject> {
let pos = canvas.pos();
let o = app.session.doc.para_at(&pos).and_then(|p| p.object_at(pos.off)).filter(|o| o.is_canvas())?;
(canvas.member.is_none() && canvas.spin.is_identity()).then_some(o)
}
/// [`member_hit`] for member `index` of canvas `o`, whose frame on the page (`[x, y, w, h]`) is
/// already worked out.
fn member_with_frame(app: &WordApp, canvas: &ObjectHit, o: &InlineObject, index: usize, [x, y, w, h]: [f32; 4]) -> Option<ObjectHit> {
let InlineObject::Group { children, .. } = o else { return None };
let member = children.get(index).filter(|c| wordcraft_engine::cmd::canvas::pickable(c))?;
let text_box = match &member.obj {
InlineObject::Shape { story: Some(id), .. } if app.session.doc.parts.get(id).is_some_and(|p| p.kind == PartKind::TextBox) => Some(*id),
_ => None,
};
Some(ObjectHit {
rect: wordcraft_geom::Rect::new(x, y, w, h),
spin: member.obj.frame().map(|(_, _, f)| f.spin()).unwrap_or_default(),
text_box,
// Placed by the canvas, not the text: dragging any handle may move its top-left.
wrap: Wrap::InFrontOfText,
member: Some(index),
..canvas.clone()
})
}
/// The member of the canvas hit `canvas` under the page point (x, y), topmost first; a text box
/// member is grabbed anywhere on it too (inside, [`in_text`] tells its text from its border).
/// The members' frames are worked out once for all of them.
fn member_at(app: &WordApp, canvas: &ObjectHit, x: f32, y: f32, edge: f32) -> Option<ObjectHit> {
let (o, r) = (pickable_canvas(app, canvas)?, canvas.rect);
// Members are drawn clipped to the canvas: only what shows is grabbed.
if !r.contains(wordcraft_geom::Point::new(x, y)) {
return None;
}
o.member_rects(r.x, r.y, r.w, r.h)
.into_iter()
.rev()
.filter_map(|(i, frame)| member_with_frame(app, canvas, o, i, frame))
.find(|m| m.rect.expand(edge).contains(m.unspin(x, y)))
}
/// Whether the page point (x, y) is in a text box member's text rather than on its border.
fn in_text(m: &ObjectHit, x: f32, y: f32, edge: f32) -> bool {
m.text_box.is_some() && m.rect.w.min(m.rect.h) > edge * 3.0 && m.rect.expand(-edge).contains(m.unspin(x, y))
}
/// The story of the selected text box (a picked canvas member too).
fn selected_text_box(app: &WordApp) -> Option<u32> {
if let Some((_, _, InlineObject::Shape { story: Some(id), .. })) = wordcraft_engine::cmd::canvas::selected_member(&app.session) {
return app.session.doc.parts.get(id).is_some_and(|p| p.kind == PartKind::TextBox).then_some(*id);
}
match selected(app)? {
(_, InlineObject::Shape { story: Some(id), .. }) if app.session.doc.parts.get(id).is_some_and(|p| p.kind == PartKind::TextBox) => Some(*id),
_ => None,
@@ -154,7 +229,11 @@ fn selected_text_box(app: &WordApp) -> Option<u32> {
pub fn active(app: &WordApp, layout: &DocLayout) -> Option<(ObjectHit, bool)> {
let hint = app.session.page_hint;
if let Some((pos, _)) = selected(app) {
return layout.object(&pos, hint).map(|o| (o, false));
let canvas = layout.object(&pos, hint)?;
if let Some((_, i, _)) = wordcraft_engine::cmd::canvas::selected_member(&app.session) {
return member_hit(app, &canvas, i).or(Some(canvas)).map(|o| (o, false));
}
return Some((canvas, false));
}
match app.session.sel.focus.story {
StoryRef::Part(id) if crate::canvas::in_text_box(app) => layout.text_box(id, hint).map(|o| (o, true)),
@@ -212,7 +291,7 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
}
if ui.input(|i| i.pointer.primary_down()) {
let shift = ui.input(|i| i.modifiers.shift);
d.copy = ui.input(|i| i.modifiers.command) && d.drag.grab == Grab::Move;
d.copy = ui.input(|i| i.modifiers.command) && d.drag.grab == Grab::Move && d.object.member.is_none();
if d.drag.grab == Grab::Rotate {
d.drag.turn_to(at, pages, scale, shift);
} else {
@@ -230,7 +309,12 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
if d.drag.grab == Grab::Move && d.drag.moved && !d.object.floating() {
// An inline one lands in the text: the insertion cursor follows the pointer.
d.drop_at = drop_point(app, layout, pages, scale, at, &d);
} else if d.drag.grab == Grab::Move && d.drag.moved && app.ui.alignment_guides && !ui.input(|i| i.modifiers.alt) {
} else if d.drag.grab == Grab::Move
&& d.drag.moved
&& d.object.member.is_none()
&& app.ui.alignment_guides
&& !ui.input(|i| i.modifiers.alt)
{
snap_move(layout, &mut d, scale, locked_axis);
}
}
@@ -279,6 +363,17 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
}
// Shift/Ctrl+click adds an object to the selected ones (or takes it out), for Group.
let adding = ui.input(|i| i.modifiers.shift || i.modifiers.command);
if let Some(index) = object.member.filter(|_| pressed && !adding) {
return press_member(app, layout, pages, scale, at, object, index, grab);
}
// Adding to the selection takes the whole canvas.
let object = match object.member {
Some(_) => match layout.object(&object.pos(), object.page) {
Some(o) => o,
None => return false,
},
None => object,
};
// Ctrl on the object that is already selected starts a copy-drag instead, including
// Ctrl+Shift for an aligned copy. Shift alone keeps its additive-selection behavior.
let again = selected(app).is_some_and(|(p, _)| p == object.pos())
@@ -339,13 +434,55 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
true
}
/// A press on member `index` of a canvas (`object` is the member's hit): in a text box member's
/// text it puts the caret there; elsewhere it picks the member (selecting its canvas first) and
/// starts dragging it, or the handle `grab`.
#[allow(clippy::too_many_arguments)]
fn press_member(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f32, at: Pos2, object: ObjectHit, index: usize, grab: Grab) -> bool {
let edge = EDGE / scale.max(0.01);
if grab == Grab::Move
&& let (Some(id), Some((page, x, y))) = (object.text_box, crate::canvas::page_at(pages, layout, scale, at))
&& in_text(&object, x, y, edge)
{
// A box linked from another shows (and edits) that box's story.
let id = app.session.doc.text_box_chain(id).and_then(|c| c.first().copied()).unwrap_or(id);
if let Some(pos) = layout.hit(page, x, y, StoryRef::Part(id)) {
let _ = app.run("caret.set", json!({"pos": pos}));
}
return true;
}
let pos = object.pos();
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
if app.run("select.member", json!({"index": index})).is_err() {
return true;
}
let Some(o) = hit_object(app, &object) else { return true };
let (min, picture) = (wordcraft_engine::cmd::objects::min_size(o), matches!(o, InlineObject::Image { .. }));
app.canvas.obj_drag = Some(ObjectDrag {
drag: Drag::new(grab, object.page, object.rect, object.spin.deg, at),
press_origin: pages.get(object.page).map_or(at, |p| p.min),
object,
min,
picture,
pending_behind: false,
end: None,
guides: Vec::new(),
preview: None,
copy: false,
drop_at: None,
});
true
}
/// The object a move has taken off its page (which page, and where it is in the document): the
/// page is rendered again without it while the preview follows the pointer, so the object is not
/// left behind where it was. Only for a move — resizing and turning show the object itself, and
/// dragging a connector's end onto a shape still shows that connector.
/// dragging a connector's end onto a shape still shows that connector. Nor for a member of a
/// drawing canvas: its position is the canvas's, and the canvas stays.
pub(crate) fn dragged_off_page(drag: Option<&ObjectDrag>) -> Option<(usize, Pos)> {
let d = drag?;
if !d.drag.moved || d.end.is_some() || d.drag.grab != Grab::Move {
if !d.drag.moved || d.end.is_some() || d.drag.grab != Grab::Move || d.object.member.is_some() {
return None;
}
Some((d.object.page, d.object.pos()))
@@ -480,15 +617,18 @@ fn grab_at(app: &WordApp, layout: &DocLayout, pages: &[Rect], scale: f32, at: Po
return selected_picture;
}
// Selectable: body objects (table cells too) or the header/footer's own objects;
// notes' objects aren't yet.
layout.object_at_in(page, x, y, EDGE / scale.max(0.01), story).map(|o| (o, Grab::Move))
// notes' objects aren't yet. Inside a canvas, the member there.
let edge = EDGE / scale.max(0.01);
let o = layout.object_at_in(page, x, y, edge, story)?;
Some((member_at(app, &o, x, y, edge).unwrap_or(o), Grab::Move))
})
}
/// Objects that can be dragged to a new place: those in the own paragraphs of the body or of a
/// header/footer.
fn movable(app: &WordApp, o: &ObjectHit) -> bool {
o.path.depth() == 0 && selectable_story(app, o.story)
// A canvas member moves inside its canvas, wherever the canvas is.
(o.member.is_some() || o.path.depth() == 0) && selectable_story(app, o.story)
}
/// Whether a Behind Text object of this kind is grabbed by pressing its body. Pictures, shapes and
@@ -541,7 +681,7 @@ fn preview_scale(px: f32, w: f32, h: f32, max_side: usize) -> f32 {
/// `o` drawn alone over its rotated bounds, as a texture, at the canvas's `scale` (screen points
/// per page point).
fn preview(app: &WordApp, ctx: &egui::Context, layout: &DocLayout, o: &ObjectHit, scale: f32) -> Option<egui::TextureHandle> {
let obj = app.session.doc.para_at(&o.pos()).and_then(|p| p.object_at(o.off))?;
let obj = hit_object(app, o)?;
let page = layout.pages.get(o.page)?;
let mut opts = crate::canvas::screen_render_options();
opts.dark = crate::canvas::dark_page(app);
@@ -668,6 +808,13 @@ pub fn paint(app: &WordApp, painter: &Painter, t: &Tokens, layout: &DocLayout, p
if let Some((o, editing)) = active(app, layout)
&& let Some(f) = screen(pages, scale, o.page, o.rect)
{
// A picked canvas member: the canvas's frame around it, without handles.
if o.member.is_some()
&& let Some(c) = layout.object(&o.pos(), o.page)
&& let Some(cf) = screen(pages, scale, c.page, c.rect)
{
frame::paint(painter, t, cf, c.spin.deg, false, false, false);
}
// Handles where it can be resized and turned (body and header/footer objects,
// not charts): else a plain frame.
let handles = selectable_story(app, o.story) && !fixed(app, &o);
@@ -675,12 +822,13 @@ pub fn paint(app: &WordApp, painter: &Painter, t: &Tokens, layout: &DocLayout, p
}
}
/// The dashed insertion cursor where a dragged In Line with Text object will land.
/// The insertion cursor where a dragged In Line with Text object will land: solid and twice as
/// wide as the caret, so it stands out as Word's does (#4195).
fn paint_drop_caret(d: &ObjectDrag, painter: &Painter, layout: &DocLayout, pages: &[Rect], scale: f32) {
let Some((pos, color)) = &d.drop_at else { return };
let Some(c) = layout.caret_on(pos, d.drag.to_page) else { return };
let Some(r) = screen(pages, scale, c.page, wordcraft_geom::Rect::new(c.x, c.top, 0.0, c.height)) else { return };
painter.extend(egui::Shape::dashed_line(&[r.left_top(), r.left_bottom()], egui::Stroke::new(1.5, *color), 2.0, 2.0));
painter.line_segment([r.left_top(), r.left_bottom()], egui::Stroke::new(3.0, *color));
}
/// A connector's end being dragged: a line from its other end to the pointer, and the connection
@@ -734,19 +882,23 @@ pub fn cursor(app: &WordApp, layout: &DocLayout, pages: &[Rect], scale: f32, at:
} else if d.copy && d.drag.moved {
egui::CursorIcon::Copy
} else {
d.drag.grab.cursor()
d.drag.grab.cursor(d.drag.deg)
});
}
if connector_end_at(app, layout, pages, scale, at).is_some() {
return Some(egui::CursorIcon::Crosshair);
}
grab_at(app, layout, pages, scale, at).map(|(o, g)| hover_cursor(app, &o, g))
let in_member_text = |o: &ObjectHit| {
crate::canvas::page_at(pages, layout, scale, at).is_some_and(|(_, x, y)| o.member.is_some() && in_text(o, x, y, EDGE / scale.max(0.01)))
};
grab_at(app, layout, pages, scale, at)
.map(|(o, g)| if g == Grab::Move && !fixed(app, &o) && in_member_text(&o) { egui::CursorIcon::Text } else { hover_cursor(app, &o, g) })
}
/// The cursor over part `g` of object `o`: none of a drag for an object that won't move there (a
/// fixed graphic, or the body of a chart or SmartArt, which only resizes).
fn hover_cursor(app: &WordApp, o: &ObjectHit, g: Grab) -> egui::CursorIcon {
if fixed(app, o) || (g == Grab::Move && size_only(app, o)) { egui::CursorIcon::Default } else { g.cursor() }
if fixed(app, o) || (g == Grab::Move && size_only(app, o)) { egui::CursorIcon::Default } else { g.cursor(o.spin.deg) }
}
/// Keys for a selected object: arrows nudge a floating one; typing or Enter goes into a text box.
+130 -1
View File
@@ -500,7 +500,7 @@ fn alt_pressed_during_a_drag_unsnaps_and_keeps_keytips_off() {
assert_eq!(h.state().ui.keytips, crate::keytips::Phase::Off, "Alt during a drag isn't a keytip tap");
}
/// #2233, #2234: dragging an In Line with Text picture into another paragraph shows a dashed
/// #2233, #2234: dragging an In Line with Text picture into another paragraph shows a bold
/// insertion cursor at the text under the pointer (no alignment guides), and the drop puts the
/// picture there, still inline and selected. Dropped back where it was, nothing changes.
#[test]
@@ -551,6 +551,13 @@ fn an_inline_picture_drags_to_the_insertion_cursor_and_stays_inline() {
let d = h.state().canvas.obj_drag.as_ref().expect("dragging");
assert_eq!(d.drop_at.as_ref().map(|(p, _)| p.clone()), Some(target.clone()), "the insertion cursor is at the text under the pointer");
assert!(d.guides.is_empty(), "an inline object doesn't snap to guides");
// #4195: solid and twice the caret's width, so it can be seen, as in Word.
let (top, bottom) = (at(&mut h, c.x, c.top), at(&mut h, c.x, c.top + c.height));
let bold = h.output().shapes.iter().any(|s| {
matches!(&s.shape, egui::Shape::LineSegment { points: [a, b], stroke }
if a.distance(top) < 0.5 && b.distance(bottom) < 0.5 && stroke.width == 3.0)
});
assert!(bold, "a bold insertion cursor from the line's top to its bottom");
button(&h, end, false);
steps(&mut h, 3);
assert!(h.state().canvas.obj_drag.is_none());
@@ -771,6 +778,41 @@ fn rotation_window(app: WordApp) -> crate::table_resize::tests::H {
h
}
/// #3932: over a shape turned 90° the pointer on a resize handle shows the arrow that handle
/// resizes along (its own top handle, now on the right, left-right), and keeps it while dragged.
#[test]
fn a_turned_shapes_handles_show_turned_resize_arrows() {
use crate::table_resize::tests::{H, button, steps};
let (mut app, _) = app_with(filled_shape());
app.run("view.commentsPane", json!({"value": false})).unwrap();
app.run("select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, OBJ.len_utf8())})).unwrap();
app.run("arrange.bounds", json!({"page": 0, "x": 150, "y": 180, "width": 200, "height": 100})).unwrap();
app.run("arrange.rotation", json!({"degrees": 90})).unwrap();
let mut h: H = rotation_window(app);
let o = h.state_mut().session.layout().object(&Pos::body(0, 0), 0).unwrap();
assert_eq!(o.spin.deg, 90.0);
let (cx, cy) = (o.rect.x + o.rect.w / 2.0, o.rect.y + o.rect.h / 2.0);
// Turned 90° clockwise, the frame's top handle is on the right and its right one at the bottom.
let top = crate::canvas::page_to_screen(h.state_mut(), 0, cx + o.rect.h / 2.0, cy).unwrap();
let right = crate::canvas::page_to_screen(h.state_mut(), 0, cx, cy + o.rect.w / 2.0).unwrap();
let cursor = |h: &H| h.output().platform_output.cursor_icon;
for (at, arrow) in [(top, egui::CursorIcon::ResizeHorizontal), (right, egui::CursorIcon::ResizeVertical)] {
h.event(egui::Event::PointerMoved(at));
steps(&mut h, 2);
assert_eq!(cursor(&h), arrow, "over the handle at {at:?}");
}
h.event(egui::Event::PointerMoved(top));
button(&h, top, true);
h.step();
h.event(egui::Event::PointerMoved(top + egui::vec2(20.0, 0.0)));
steps(&mut h, 2);
let d = h.state().canvas.obj_drag.as_ref().expect("resizing");
assert_eq!(d.drag.grab, Grab::Resize(frame::Handle { x: 0, y: -1 }));
assert_eq!(cursor(&h), egui::CursorIcon::ResizeHorizontal, "while the handle is dragged");
button(&h, top + egui::vec2(20.0, 0.0), false);
steps(&mut h, 3);
}
/// #2277: the actual picture pixels follow the rotation handle before release, including
/// pictures whose cached preview already contains a rotation and either reflection.
#[test]
@@ -975,3 +1017,90 @@ fn dragging_a_large_picture_renders_a_preview_within_the_gpu_texture_limit() {
let [width, height] = preview.size();
assert!(width <= max_side && height <= max_side, "preview is {width}×{height}, texture limit is {max_side}");
}
/// #2637: inside a Drawing Canvas the mouse works on the members, as in Word. A click on a
/// shape picks that shape (the canvas stays the selection in the text) and shows its frame;
/// dragging it moves it inside the canvas; a click in a text box member's text puts the
/// caret there. Before, the canvas took every click, as one static object.
#[test]
fn clicking_and_dragging_inside_a_canvas_works_on_its_members() {
use egui::{Event, PointerButton};
use wordcraft_engine::cmd::canvas::selected_member;
let mut a = WordApp::new(wordcraft_engine::Session::new(Document::new()), crate::Services::default());
a.run("view.commentsPane", json!({"value": false})).unwrap();
a.run("insert.canvas", json!({"width": 400, "height": 300})).unwrap();
a.run("insert.shape", json!({"kind": "rectangle", "width": 100, "height": 40})).unwrap();
a.run("canvas.member", json!({"index": 0, "x": 40, "y": 30})).unwrap();
a.run("insert.textBox", json!({"text": "Label"})).unwrap();
a.run("select.objects", json!({"index": 0})).unwrap();
a.run("canvas.member", json!({"index": 1, "x": 200, "y": 100, "width": 150, "height": 80})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
for _ in 0..6 {
h.step();
}
let frame = h.state_mut().session.layout().object(&Pos::body(0, 0), 0).expect("the canvas is laid out").rect;
let at = |h: &mut egui_kittest::Harness<'_, WordApp>, x: f32, y: f32| {
crate::canvas::page_to_screen(h.state_mut(), 0, frame.x + x, frame.y + y).unwrap()
};
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let members =
|h: &egui_kittest::Harness<'_, WordApp>| match h.state().session.doc.body.first().and_then(|b| b.as_para()).and_then(|p| p.objects.first()) {
Some(InlineObject::Group { children, .. }) => children.iter().map(|c| (c.x, c.y)).collect::<Vec<_>>(),
o => panic!("{o:?}"),
};
// A click on the rectangle picks it.
let on_rect = at(&mut h, 90.0, 50.0);
h.event(Event::PointerMoved(on_rect));
h.event(button(on_rect, true));
h.step();
h.event(button(on_rect, false));
for _ in 0..3 {
h.step();
}
assert_eq!(selected_member(&h.state().session).map(|(_, i, _)| i), Some(0), "the rectangle is picked, not the whole canvas");
let shown = {
let app = h.state_mut();
let layout = app.session.layout();
active(app, &layout).map(|(o, _)| (o.member, o.rect))
};
assert_eq!(shown, Some((Some(0), wordcraft_geom::Rect::new(frame.x + 40.0, frame.y + 30.0, 100.0, 40.0))), "its frame is the one shown");
// Dragged 50 pt right and 20 pt down, it moves inside the canvas; the canvas stays put.
let to = at(&mut h, 140.0, 70.0);
h.event(Event::PointerMoved(on_rect));
h.event(button(on_rect, true));
h.step();
for p in [on_rect + egui::vec2(0.0, 30.0), to + egui::vec2(0.0, 30.0), to] {
h.event(Event::PointerMoved(p));
h.step();
}
h.event(button(to, false));
for _ in 0..3 {
h.step();
}
let moved = members(&h);
let near = |(x, y): (f32, f32), (ex, ey): (f32, f32)| (x - ex).abs() < 0.01 && (y - ey).abs() < 0.01;
assert!(near(moved[0], (90.0, 50.0)) && near(moved[1], (200.0, 100.0)), "{moved:?}");
assert_eq!(h.state_mut().session.layout().object(&Pos::body(0, 0), 0).map(|o| o.rect), Some(frame));
// A click in the text box's text puts the caret in it.
let in_box = at(&mut h, 275.0, 140.0);
h.event(Event::PointerMoved(in_box));
h.event(button(in_box, true));
h.step();
h.event(button(in_box, false));
for _ in 0..3 {
h.step();
}
let story = h.state().session.sel.focus.story;
let is_box = matches!(story, StoryRef::Part(id) if h.state().session.doc.parts.get(&id).is_some_and(|p| p.kind == PartKind::TextBox));
assert!(is_box, "the caret is in the text box's text: {story:?}");
}
+26
View File
@@ -441,6 +441,32 @@ fn center_rows_on_ink(img: &egui::ColorImage, rows: usize) -> egui::ColorImage {
egui::ColorImage::new([w, rows], pixels)
}
/// The Font dialog's sample: `text` with `props`, then `mark` (a "2" raised or
/// lowered) when `vert` is set, drawn as the document draws text on `paper`.
pub fn font_sample(
text: &str,
props: &CharProps,
mark: Option<wordcraft_doc::props::VertAlign>,
(w, h, ppp): (f32, f32, f32),
paper: wordcraft_doc::Rgb,
dark: bool,
) -> Option<egui::ColorImage> {
let mut p = Paragraph::with_text(text, props.clone());
if let Some(v) = mark {
let tail = CharProps { vert_align: Some(v), ..props.clone() };
p.text.push('2');
p.runs.push(wordcraft_doc::Run { len: 1, props: tail });
}
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
p.props.line_spacing = Some(wordcraft_doc::props::LineSpacing::Multiple(1.0));
snippet_blocks(
&Document::new(),
vec![Block::Para(p)],
SnippetOptions { width: w, height: h, pixels_per_point: ppp, margin: 2.0, paper: Some(paper), dark },
)
}
/// Lay out `para` (with `base`'s styles) in a `w`×`h` pt box and rasterise it.
pub fn snippet(base: &Document, para: Paragraph, w: f32, h: f32, ppp: f32, margin: f32) -> Option<egui::ColorImage> {
snippet_blocks(base, vec![Block::Para(para)], SnippetOptions { width: w, height: h, pixels_per_point: ppp, margin, paper: None, dark: false })
+12
View File
@@ -381,3 +381,15 @@ fn font_menu_entries_take_the_theme_text_colour() {
assert_eq!(images, 1, "{theme:?}: the entry draws its rendered name");
}
}
#[test]
fn font_sample_shows_small_caps_and_the_script_mark() {
let white = wordcraft_doc::Rgb(255, 255, 255);
let plain = CharProps { size: Some(20.0), ..Default::default() };
let draw = |p: &CharProps, mark, dark| font_sample("AaBbYyZz", p, mark, (200.0, 40.0, 1.0), white, dark).map(|i| i.pixels);
let small = CharProps { small_caps: Some(true), ..plain.clone() };
assert_ne!(draw(&plain, None, false), draw(&small, None, false), "small caps change the sample");
let sup = Some(wordcraft_doc::props::VertAlign::Superscript);
assert_ne!(draw(&plain, None, false), draw(&plain, sup, false), "the mark is drawn");
assert_ne!(draw(&plain, None, false), draw(&plain, None, true), "Switch Modes transforms the preview");
}
+4
View File
@@ -208,6 +208,10 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
if let Some(discover) = &app.services.printers {
crate::printing::show(&mut app.printing, ui, discover, |label| crate::i18n::t(label).to_owned());
}
// A job can wait long on a sleeping printer's driver; Cancel frees the page.
if app.printing.busy() && app.services.cancel_print.is_some() && ui.button(tl!("Cancel printing")).clicked() {
let _ = app.run("ui.printCancel", serde_json::json!({}));
}
app.ui.print.copies = app.printing.settings.copies;
} else if hook {
ui.label(tl!("Send the document straight to the system print dialog, or save a copy in another format below."));
+25
View File
@@ -16,6 +16,9 @@ pub fn commands(app: &crate::WordApp) -> Vec<serde_json::Value> {
"enabled":true}),
json!({"id":"ui.printSubmit", "label":"Submit print job", "location":"File › Print", "shortcut":null, "params":submit_params, "enabled":enabled}),
json!({"id":"ui.print", "label":"Print (alias of ui.printSubmit)", "location":"File › Print", "shortcut":null, "params":submit_params, "enabled":enabled}),
json!({"id":"ui.printCancel", "label":"Cancel printing", "location":"File › Print", "shortcut":null,
"params":"none. Stops the job being submitted if it hasn't started reaching the spooler (it may wait on a sleeping printer's driver); returns cancelled: true when nothing will be sent, false when the job was already being sent (cancel it from the system's print queue).",
"enabled": app.services.cancel_print.is_some() && app.printing.busy()}),
]
}
@@ -127,6 +130,28 @@ pub fn feedback(message: &Feedback, translate: impl Fn(&str) -> String) -> Strin
}
}
/// `ui.printCancel`: stop the job being submitted before it reaches the spooler. A job can wait
/// a long time on a sleeping network printer's driver (#5710) with the print settings locked;
/// once cancelled it is never sent, so the panel is free again at once: printer list and
/// settings kept, the printers listed again.
pub fn cancel(app: &mut crate::WordApp) -> Result<serde_json::Value, String> {
if !app.printing.busy() {
return Err("no print job is being submitted".into());
}
let cancel = app.services.cancel_print.as_ref().ok_or("cancelling a print job isn't available here")?;
if !cancel() {
app.status(tl!("Cancellation could not be confirmed here. The printer driver may still be processing the job. If it appears in the system's print queue, cancel it there."));
return Ok(serde_json::json!({"cancelled": false}));
}
// The shared state keeps the job's receiver private: a fresh one drops it (the worker's
// answer, if it ever comes, goes nowhere) and keeps the user's settings.
let old = std::mem::take(&mut app.printing);
app.printing.settings = old.settings;
app.printing.printers = old.printers;
app.status(tl!("Printing cancelled. Nothing was sent to the printer."));
Ok(serde_json::json!({"cancelled": true}))
}
/// The IPP/PWG 5101.1 media name of a Layout › Size paper (the spooler's `media` option).
pub fn pwg_media(paper: &str) -> Option<&'static str> {
Some(match paper {
+51 -14
View File
@@ -70,7 +70,7 @@ use shape::shape_format;
use table::{table_design, table_layout};
#[cfg(test)]
use tabs::MIN_TAB_W;
use tabs::{MORE_TABS_W, reading_toolbar};
use tabs::{MORE_TABS_W, TAB_ENTRY_SECS, TAB_ENTRY_SLIDE, ease_out_cubic, note_contextual_tabs, reading_toolbar, tab_entry};
pub use tabs::{
StripPlan, TABS, TabSpec, contextual_tabs, fit_tabs, has_chart_selected, has_picture_selected, has_shape_selected, has_smart_art_selected,
in_table_public, plan_strip, resolve_tab,
@@ -130,6 +130,25 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
app.ui.tab = next.to_string();
}
}
let (now, animate) = (ui.input(|i| i.time), app.animations_on());
let leaving = {
let user_names: Vec<&str> = user_tabs.iter().filter(|e| e.custom).map(|e| e.name.as_str()).collect();
let contextual: Vec<(&str, usize)> = tabs
.iter()
.enumerate()
.map(|(i, (n, _))| (n.as_str(), i))
.filter(|(n, _)| wordcraft_engine::ribbon::CONTEXTUAL_TABS.contains(n) && !user_names.contains(n))
.collect();
note_contextual_tabs(ui.ctx(), &contextual, now, animate)
};
// A tab that just left stays in its former slot while it slides and fades away.
let ghosts: Vec<(String, usize, f64)> = leaving.iter().filter(|(n, ..)| !tabs.iter().any(|(t, _)| t == n)).cloned().collect();
if !ghosts.is_empty() {
ui.ctx().request_repaint();
}
for (name, at, _) in &ghosts {
tabs.insert((*at).min(tabs.len()), (name.clone(), false));
}
// Tab strip.
egui::Panel::top("tabs")
.exact_size(30.0)
@@ -236,26 +255,42 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
};
ui.with_layout(tabs_layout, |ui| {
// The tabs that don't fit go into a » menu at the end of the strip (#897, #2026).
for (i, ((tab, custom), _)) in tabs.iter().zip(&plan.fits).enumerate().filter(|(_, (_, fits))| **fits) {
for (i, ((tab, custom), _)) in tabs
.iter()
.zip(&plan.fits)
.enumerate()
.filter(|(_, ((tab, _), fits))| **fits || ghosts.iter().any(|(n, ..)| n == tab))
{
let (tab, custom) = (tab.as_str(), *custom);
let contextual = !custom && wordcraft_engine::ribbon::CONTEXTUAL_TABS.contains(&tab);
// A custom tab's name is the user's own text: shown as typed.
let shown = if custom { tab } else { tl!(tab) };
let w = plan.widths.get(i).copied().unwrap_or(0.0) - 2.0;
let cut = specs.get(i).is_some_and(|sp| sp.text_w + plan.pad > w + 0.5);
let (r, resp) = ui.allocate_exact_size(vec2(w, 30.0), Sense::click());
if app.ui.keytips == crate::keytips::Phase::Tabs {
let ghost = ghosts.iter().find(|(n, ..)| n == tab);
let (r, resp) = ui.allocate_exact_size(vec2(w, 30.0), if ghost.is_some() { Sense::hover() } else { Sense::click() });
if app.ui.keytips == crate::keytips::Phase::Tabs && ghost.is_none() {
crate::keytips::record_tab(r, tab, &app.ui.keytip_prefix, &mut app.keytip_rects);
} else if app.ui.keytips == crate::keytips::Phase::Legacy {
} else if app.ui.keytips == crate::keytips::Phase::Legacy && ghost.is_none() {
// Every tab: they only place the legacy keys' hint (#1697).
crate::keytips::record_tab(r, tab, "", &mut app.keytip_rects);
}
let active = app.ui.tab == tab && !app.ui.backstage;
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, active, shown));
if resp.hovered() && !active {
if resp.hovered() && !active && ghost.is_none() {
ui.painter().rect_filled(r.shrink2(vec2(0.0, 4.0)), 4.0, t.hover);
}
let color = if contextual || active { t.accent_text } else { t.text };
// Entering and departing contextual tabs move and fade without changing layout.
let entry = match ghost {
Some((_, _, left)) => {
ui.ctx().request_repaint();
1.0 - ease_out_cubic(((now - left) / TAB_ENTRY_SECS) as f32)
}
None if contextual => tab_entry(ui.ctx(), tab, now, animate),
None => 1.0,
};
let shift = vec2(-(1.0 - entry) * TAB_ENTRY_SLIDE, 0.0);
let color = (if contextual || active { t.accent_text } else { t.text }).gamma_multiply(entry);
if cut {
let mut job = egui::text::LayoutJob::single_section(
shown.to_string(),
@@ -268,20 +303,20 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
overflow_character: Some('…'),
};
let galley = ui.painter().layout_job(job);
ui.painter().galley(r.center() - galley.size() / 2.0, galley, color);
ui.painter().galley(r.center() + shift - galley.size() / 2.0, galley, color);
} else {
ui.painter().text(
r.center(),
r.center() + shift,
Align2::CENTER_CENTER,
shown,
if active { semibold(12.5) } else { medium(12.5) },
color,
);
}
let resp = if cut { resp.on_hover_text(shown) } else { resp };
let resp = if cut && ghost.is_none() { resp.on_hover_text(shown) } else { resp };
if active {
let u = Rect::from_center_size(pos2(r.center().x, r.max.y - 2.0), vec2(w - 16.0, 3.0));
ui.painter().rect_filled(u, 2.0, t.accent);
let u = Rect::from_center_size(pos2(r.center().x + shift.x, r.max.y - 2.0), vec2(w - 16.0, 3.0));
ui.painter().rect_filled(u, 2.0, t.accent.gamma_multiply(entry));
}
if resp.clicked() {
let _ = app.run("ui.tab", json!({"tab": tab}));
@@ -289,13 +324,15 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
if resp.double_clicked() && tab != "File" {
let _ = app.run("ui.collapseRibbon", json!({}));
}
resp.context_menu(|ui| crate::widgets::customize_menu_items(ui, app));
if ghost.is_none() {
resp.context_menu(|ui| crate::widgets::customize_menu_items(ui, app));
}
}
let left_out: Vec<(&str, &str)> = tabs
.iter()
.zip(&labels)
.zip(&plan.fits)
.filter(|(_, fits)| !**fits)
.filter(|(((tab, _), _), fits)| !**fits && !ghosts.iter().any(|(n, ..)| n == tab))
.map(|(((tab, _), shown), _)| (tab.as_str(), *shown))
.collect();
if !left_out.is_empty() {
+55 -1
View File
@@ -1,5 +1,5 @@
use super::language::mi_check;
use super::{Align2, Rect, Sense, Tokens, Ui, Value, WordApp, big, group, json, small, vec2};
use super::{Align2, MeasureExt, Rect, Sense, Tokens, Ui, Value, WordApp, big, group, json, small, vec2};
/// Custom groups (Customize Ribbon, #379): up to three commands as large buttons, more as small
/// labelled buttons in columns of three. Each shows the command's own icon and label.
@@ -65,6 +65,60 @@ pub(super) fn esc_cancelled(ui: &Ui, r: &egui::Response, id: egui::Id) -> bool {
ui.data(|d| d.get_temp::<u64>(esc_key)).is_some_and(|at| now.saturating_sub(at) <= 2)
}
/// A W or H field of Picture or Shape Format › Size, `pt` shown in the interface unit: a size
/// typed in any unit (`300 px` too, #1901) applies once typed (Enter, Tab or a click elsewhere;
/// Esc cancels), never per keystroke; a drag applies as it goes, one undo step. Returns the new
/// size in points to apply.
pub(super) fn size_field(ui: &mut Ui, app: &mut WordApp, label: &str, pt: f32, id: egui::Id, hint: &str) -> Option<f32> {
let unit = crate::options::unit();
let k = unit.pt_per_unit();
let (lo, hi) = (1.0 / k, 4000.0 / k);
let name = ui.label(egui::RichText::new(tl!(label)).small());
let was = pt / k;
let mut v = was;
// `picture.size`'s own range. Not `clamp_existing_to_range`: egui would clamp a size outside
// it (a 1 px picture, a thin line) and report it as a change, resizing the object unasked.
let field = egui::DragValue::new(&mut v).speed(1.0 / k).range(lo..=hi).clamp_existing_to_range(false).measure(unit).max_decimals(2);
let r = ui.add(field.update_while_editing(false)).labelled_by(name.id).on_hover_text(hint);
// Only a new value (Enter, Tab, a click elsewhere, a drag) resizes, and Esc cancels.
let cancelled = esc_cancelled(ui, &r, id);
// Left without typing, the field reads back the text it showed, the size rounded to two
// decimals and kept in range: no change (#4196 review). Only a field edited since it took
// focus (or dragged) applies, a size at the range's bound too. Text typed, pasted, cut,
// composed or deleted counts while the field has focus (egui 0.37 reports no change until the
// editing ends) and in the frame that ends the editing (a character and Enter in one frame).
let typed_key = id.with("typed");
if r.gained_focus() {
ui.data_mut(|d| d.insert_temp(typed_key, false));
}
let edits = ui.input(|i| {
i.events.iter().any(|e| {
matches!(
e,
egui::Event::Text(_)
| egui::Event::Paste(_)
| egui::Event::Cut
| egui::Event::Ime(egui::ImeEvent::Commit(_))
| egui::Event::Key { key: egui::Key::Backspace | egui::Key::Delete, pressed: true, .. }
)
})
});
if (r.has_focus() && (r.changed() || edits)) || (r.lost_focus() && edits) {
ui.data_mut(|d| d.insert_temp(typed_key, true));
}
let typed = ui.data(|d| d.get_temp::<bool>(typed_key)).unwrap_or(false);
if r.lost_focus() {
ui.data_mut(|d| d.remove_temp::<bool>(typed_key));
}
if !r.changed() || v == was || cancelled || !(typed || r.dragged()) {
return None;
}
if r.dragged() && !r.drag_started() {
app.session.join_next_undo();
}
Some(v * k)
}
pub(super) fn stack(ui: &mut Ui, add: impl FnOnce(&mut Ui)) {
crate::rtl::vertical(ui, |ui| {
ui.spacing_mut().item_spacing = vec2(1.0, 0.0);
+5 -29
View File
@@ -1,7 +1,7 @@
use super::arrange::{align_menu, group_menu, rotate_menu, rotation_field, wrap_menu};
use super::common::{esc_cancelled, mi, stack};
use super::common::{mi, size_field, stack};
use super::shape::alt_text_group;
use super::{MeasureExt, Target, Ui, WordApp, big, group, json, menu_button, small};
use super::{Target, Ui, WordApp, big, group, json, menu_button, small};
/// Draws the Picture Format tab's Adjust, Picture Styles, Accessibility (Alt Text), Arrange and
/// Size groups.
@@ -130,36 +130,12 @@ pub(super) fn picture_format(app: &mut WordApp, ui: &mut Ui) {
_ => (String::new(), 0, 0.0, 0.0, [0.0; 4], String::new()),
};
// `picture.size` locks the aspect ratio unless told otherwise, so one dimension suffices.
// The fields show the interface unit and take a size typed in any unit, pixels too
// (`300 px`, #1901), applied once typed (Enter, Tab or a click elsewhere; Esc cancels),
// never per keystroke; a drag applies as it goes, one undo step.
let unit = crate::options::unit();
let k = unit.pt_per_unit();
stack(ui, |ui| {
crate::widgets::row(ui, |ui| {
for (label, key, pt) in [("W:", "width", w0), ("H:", "height", h0)] {
let name = ui.label(egui::RichText::new(tl!(label)).small());
let was = pt / k;
let mut v = was;
// Not `clamp_existing_to_range`: egui would clamp a size outside the range (a 1 px
// picture is 0.75 pt) and report it as a change, resizing the picture unasked.
let field = egui::DragValue::new(&mut v)
.speed(1.0 / k)
.range(1.0 / k..=4000.0 / k)
.clamp_existing_to_range(false)
.measure(unit)
.max_decimals(2);
let r = ui.add(field.update_while_editing(false)).labelled_by(name.id).on_hover_text(tl!(
"Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions."
));
// While typing, the field reports each keystroke as a change; only a new
// value (Enter, Tab, a click elsewhere, a drag) resizes, and Esc cancels.
let cancelled = esc_cancelled(ui, &r, egui::Id::unique(("picture_size_field", key)));
if r.changed() && v != was && !cancelled {
if r.dragged() && !r.drag_started() {
app.session.join_next_undo();
}
let _ = app.run("picture.size", json!({key: v * k}));
let hint = tl!("Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions.");
if let Some(v) = size_field(ui, app, label, pt, egui::Id::unique(("picture_size_field", key)), hint) {
let _ = app.run("picture.size", json!({key: v}));
}
}
rotation_field(ui, app);
+4 -10
View File
@@ -1,5 +1,5 @@
use super::arrange::{align_menu, rotate_menu, rotation_field, wrap_menu};
use super::common::{mi, stack};
use super::common::{mi, size_field, stack};
use super::language::mi_check;
use super::{Target, Ui, WordApp, big, group, json, menu_button, small, vec2};
@@ -134,18 +134,12 @@ pub(super) fn shape_format(app: &mut WordApp, ui: &mut Ui) {
group(ui, "Size", None, app, |ui, app| {
let (w0, h0) =
wordcraft_engine::cmd::objects::selected(&app.session).and_then(|(_, o)| o.frame().map(|(w, h, _)| (w, h))).unwrap_or((0.0, 0.0));
// As Picture Format › Size, each side on its own.
stack(ui, |ui| {
crate::widgets::row(ui, |ui| {
for (label, key, v0) in [("W:", "width", w0), ("H:", "height", h0)] {
ui.label(egui::RichText::new(tl!(label)).small());
let mut v = v0;
// `picture.size`'s own range; a size outside it (a thin line) is shown as it
// is (clamped, egui would report a change and resize the shape unasked).
let r = ui.add(egui::DragValue::new(&mut v).speed(1.0).range(1.0..=4000.0).clamp_existing_to_range(false).suffix(" pt"));
if r.changed() && v != v0 {
if r.dragged() && !r.drag_started() {
app.session.join_next_undo();
}
let hint = tl!("Type a size in any unit, such as 3 cm or 300 px.");
if let Some(v) = size_field(ui, app, label, v0, egui::Id::unique(("shape_size_field", key)), hint) {
let _ = app.run("picture.size", json!({key: v, "lockAspect": false}));
}
}
+92
View File
@@ -148,6 +148,58 @@ pub fn resolve_tab<'a>(current: &'a str, available: &[&str]) -> &'a str {
/// Width of the » button that holds the tabs the strip has no room for.
pub(super) const MORE_TABS_W: f32 = 24.0;
/// How long a contextual tab takes to settle into place after it appears, seconds.
pub(super) const TAB_ENTRY_SECS: f64 = 0.35;
/// How far, in points, a new contextual tab starts to the left of its place.
pub(super) const TAB_ENTRY_SLIDE: f32 = 18.0;
/// Fast at first, then slowing to rest: 0 → 1.
pub(super) fn ease_out_cubic(p: f32) -> f32 {
1.0 - (1.0 - p.clamp(0.0, 1.0)).powi(3)
}
/// Track contextual tabs between frames and return those still animating out.
pub(super) fn note_contextual_tabs(ctx: &egui::Context, shown: &[(&str, usize)], now: f64, animate: bool) -> Vec<(String, usize, f64)> {
let (shown_id, leaving_id) = (egui::Id::unique("contextual_tabs_shown"), egui::Id::unique("contextual_tabs_leaving"));
let prev: Option<Vec<(String, usize)>> = ctx.data(|d| d.get_temp(shown_id));
let mut leaving: Vec<(String, usize, f64)> = ctx.data(|d| d.get_temp(leaving_id)).unwrap_or_default();
leaving.retain(|(n, _, start)| animate && now - start < TAB_ENTRY_SECS && !shown.iter().any(|(s, _)| s == n));
// Count retained ghosts when storing positions, so exits from different frames share one layout.
let shown_with_ghosts: Vec<(&str, usize)> = shown
.iter()
.map(|(tab, at)| {
let before = leaving.iter().filter(|(_, ghost_at, _)| ghost_at <= at).count();
(*tab, at + before)
})
.collect();
if let Some(prev) = prev {
for (tab, _) in shown_with_ghosts.iter().filter(|(t, _)| !prev.iter().any(|(p, _)| p == t)) {
ctx.data_mut(|d| d.insert_temp(egui::Id::unique(("contextual_tab_entry", *tab)), now));
}
for (tab, at) in prev.iter().filter(|(p, _)| animate && !shown_with_ghosts.iter().any(|(s, _)| s == p)) {
if !leaving.iter().any(|(n, _, _)| n == tab) {
leaving.push((tab.clone(), *at, now));
}
}
}
ctx.data_mut(|d| {
d.insert_temp(shown_id, shown_with_ghosts.iter().map(|(t, at)| (t.to_string(), *at)).collect::<Vec<_>>());
d.insert_temp(leaving_id, leaving.clone());
});
leaving
}
/// Return a newly shown contextual tab's progress, requesting frames until it settles.
pub(super) fn tab_entry(ctx: &egui::Context, tab: &str, now: f64, animate: bool) -> f32 {
let start: Option<f64> = ctx.data(|d| d.get_temp(egui::Id::unique(("contextual_tab_entry", tab))));
let Some(start) = start.filter(|_| animate) else { return 1.0 };
let p = ((now - start) / TAB_ENTRY_SECS).clamp(0.0, 1.0) as f32;
if p < 1.0 {
ctx.request_repaint();
}
ease_out_cubic(p)
}
/// Which tabs fit on a strip `avail` points wide (#897), from each tab's width and whether it must
/// stay. The others give way from the end, leaving `more` points for the » menu that holds them
/// (pure, tested).
@@ -255,3 +307,43 @@ pub fn plan_strip(tabs: &[TabSpec], buttons: [f32; 3], avail: f32, more: f32) ->
pub fn in_table_public(app: &WordApp) -> bool {
app.session.sel.focus.path.cell().is_some()
}
#[cfg(test)]
mod transition_tests {
use super::*;
/// Contextual tabs absent on the first frame do not animate; a newly shown one eases to rest.
#[test]
fn a_new_contextual_tab_eases_in() {
let ctx = egui::Context::default();
note_contextual_tabs(&ctx, &[("Table Design", 1)], 1.0, true);
assert_eq!(tab_entry(&ctx, "Table Design", 1.0, true), 1.0, "tabs already there do not slide");
note_contextual_tabs(&ctx, &[("Table Design", 1), ("Picture Format", 2)], 2.0, true);
let at = |secs: f64| tab_entry(&ctx, "Picture Format", 2.0 + secs, true);
assert_eq!(at(0.0), 0.0);
let (a, b, c) = (at(0.1), at(0.2), at(TAB_ENTRY_SECS));
assert!(0.0 < a && a < b && b < c && c == 1.0, "{a} {b} {c}");
assert!(a > 0.1 / TAB_ENTRY_SECS as f32, "faster than linear at the start: {a}");
assert!(c - b < b - a, "slower at the end: {a} {b} {c}");
assert_eq!(tab_entry(&ctx, "Picture Format", 2.0, false), 1.0, "animations off");
note_contextual_tabs(&ctx, &[("Table Design", 1), ("Picture Format", 2)], 3.0, true);
assert_eq!(tab_entry(&ctx, "Picture Format", 3.0, true), 1.0, "staying shown does not restart it");
}
/// A departing contextual tab remains for one exit and stops when motion is disabled.
#[test]
fn a_contextual_tab_that_goes_away_leaves_gently() {
let ctx = egui::Context::default();
let both = [("Table Design", 1), ("Picture Format", 2)];
assert!(note_contextual_tabs(&ctx, &both, 1.0, true).is_empty());
let leaving = note_contextual_tabs(&ctx, &both[..1], 2.0, true);
assert_eq!(leaving, vec![("Picture Format".to_string(), 2, 2.0)]);
assert_eq!(note_contextual_tabs(&ctx, &both[..1], 2.2, true).len(), 1, "still leaving");
assert!(note_contextual_tabs(&ctx, &both[..1], 2.0 + TAB_ENTRY_SECS + 0.01, true).is_empty(), "gone");
assert!(note_contextual_tabs(&ctx, &both, 4.0, true).is_empty());
assert!(note_contextual_tabs(&ctx, &both[..1], 5.0, false).is_empty(), "animations off");
note_contextual_tabs(&ctx, &both, 6.0, true);
note_contextual_tabs(&ctx, &both[..1], 7.0, true);
assert!(note_contextual_tabs(&ctx, &both, 7.1, true).is_empty(), "back again");
}
}
+105
View File
@@ -802,6 +802,111 @@ fn picture_width_typed_in_pixels_keeps_the_proportions() {
assert_eq!(size(h.state()), Some((15.0, 7.5)), "Esc cancels the typing");
}
/// #4196: Shape Format › Size shows the interface unit, in every unit, and takes a size typed in
/// any unit once typed (Enter, Tab), each side on its own, as one undo step; Esc throws it away.
/// A field focused and left without typing changes nothing, in Picture Format too, where the
/// size it shows is rounded.
#[test]
fn shape_size_fields_use_the_interface_unit() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let size = |a: &crate::WordApp| wordcraft_engine::cmd::objects::selected(&a.session).and_then(|(_, o)| o.frame().map(|(w, h, _)| (w, h)));
let harness = |units: &str, picture: Option<&str>, wh: Option<(f32, f32)>| {
let mut a = crate::WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
a.run("file.options", json!({"units": units})).unwrap();
if let Some(data) = picture {
a.run("insert.picture", json!({"data": data})).unwrap();
} else {
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
}
if let Some((w, h)) = wh {
a.run("picture.size", json!({"width": w, "height": h, "lockAspect": false})).unwrap();
}
a.run("ui.tab", json!({"tab": if picture.is_some() { "Picture Format" } else { "Shape Format" }})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(2560.0, 900.0)).build_ui_state(
|ui, app: &mut crate::WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
h
};
for (units, suffix) in [("centimeters", " cm"), ("inches", "\""), ("millimeters", " mm"), ("points", " pt"), ("picas", " pi")] {
let h = harness(units, None, None);
for side in ["W:", "H:"] {
let shown = h.get_by_role_and_label(Role::SpinButton, side).value().unwrap_or_default();
assert!(shown.ends_with(suffix), "{units}, {side} {shown:?}");
}
}
// Sizes the fields show rounded: 100×50 pt is 1.39"×0.69", a 3000×1 pt line's height
// shows 0.01" (below the fields' 1 pt), a 20×10 px picture is 0.21"×0.1".
for units in ["inches", "centimeters", "picas"] {
for (picture, wh) in [(false, Some((100.0, 50.0))), (false, Some((3000.0, 1.0))), (true, None)] {
let mut h = harness(units, picture.then(png_data).as_deref(), wh);
let (before, undo) = (size(h.state()), h.state().session.undo_depth());
assert!(wh.is_none() || before == wh, "showing the tab changes nothing: {before:?}");
for (side, key) in [("W:", egui::Key::Enter), ("H:", egui::Key::Tab)] {
h.get_by_role_and_label(Role::SpinButton, side).click();
h.run_steps(2);
h.key_press(key);
h.run_steps(3);
}
let after = (size(h.state()), h.state().session.undo_depth());
assert_eq!(after, (before, undo), "{units}, picture {picture}, {wh:?}: left without typing");
}
}
let mut h = harness("centimeters", None, None);
let (w0, h0) = size(h.state()).unwrap();
let undo = h.state().session.undo_depth();
for (side, typed, key, want) in [("W:", "3 cm", egui::Key::Enter, (85.04, h0)), ("H:", "300 px", egui::Key::Tab, (85.04, 225.0))] {
let before = size(h.state());
h.get_by_role_and_label(Role::SpinButton, side).click();
h.run_steps(2);
h.get_by_role_and_label(Role::SpinButton, side).type_text(typed);
h.run_steps(2);
assert_eq!(size(h.state()), before, "{side}: nothing applies while typing");
h.key_press(key);
h.run_steps(2);
let (w, ht) = size(h.state()).unwrap();
assert!((w - want.0).abs() < 0.01 && (ht - want.1).abs() < 0.01, "{side} {typed}: {w}×{ht}, want {want:?}");
}
assert_eq!(h.state().session.undo_depth(), undo + 2, "one undo step a side");
h.state_mut().run("edit.undo", json!({})).unwrap();
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(size(h.state()), Some((w0, h0)));
h.run_steps(2);
h.get_by_role_and_label(Role::SpinButton, "W:").click();
h.run_steps(2);
h.get_by_role_and_label(Role::SpinButton, "W:").type_text("10 cm");
h.key_press(egui::Key::Escape);
h.run_steps(2);
assert_eq!(size(h.state()), Some((w0, h0)), "Esc cancels the typing");
// A size typed at the range's bound applies although the field shows that bound: a 1×1 px
// picture (0.75 pt, below the fields' 1 pt) typed to 1 pt.
let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([0, 0, 0, 255]));
let mut png = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut h = harness("points", Some(&wordcraft_engine::cmd::insert::base64_encode(&png)), None);
assert_eq!(size(h.state()), Some((0.75, 0.75)));
h.get_by_role_and_label(Role::SpinButton, "W:").click();
h.run_steps(2);
h.get_by_role_and_label(Role::SpinButton, "W:").type_text("1");
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(size(h.state()), Some((1.0, 1.0)), "1 pt typed at the bound");
// A character and Enter in one frame (a slow frame, a paste and Enter) still apply.
h.get_by_role_and_label(Role::SpinButton, "H:").click();
h.run_steps(2);
let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
h.input_mut().events.extend([egui::Event::Text("2".into()), enter]);
h.step();
h.run_steps(2);
assert_eq!(size(h.state()), Some((2.0, 2.0)), "typed and confirmed in one frame");
}
/// #2573 review: showing Picture Format never resizes a picture whose size is outside the
/// fields' range (a 1×1 px spacer is 0.75 pt): egui clamps such a value by default and reports
/// it as a change.
+3
View File
@@ -8,6 +8,9 @@ pub struct Services {
pub printers: Option<printing::Discover>,
/// Desktop: submit the PDF with the chosen settings on a worker.
pub print_native: Option<printing::Submit>,
/// Desktop: stop the print job still waiting to be sent (on a sleeping printer's driver,
/// say). `true`: it will never be sent; `false`: it was already being sent.
pub cancel_print: Option<Box<dyn Fn() -> bool>>,
/// Pick a file to open; the argument says what for (`document`, `picture`).
pub pick_open: Option<Box<dyn Fn(&str) -> Option<String>>>,
/// Pick a path to save to, given a suggested name.
+175
View File
@@ -3582,6 +3582,65 @@ fn a_successful_native_print_returns_to_the_document() {
}
}
/// #5710: a job waiting on a sleeping network printer's driver locked the Print page until the
/// driver answered. `ui.printCancel` stops it before it is sent and frees the page at once,
/// keeping the chosen printer; a job already being sent can't be stopped, and the page says so.
#[test]
fn cancelling_a_waiting_print_job_frees_the_print_page() {
use printing::Printer;
for (never_sent, close_document) in [(true, false), (false, false), (true, true), (false, true)] {
let mut a = app();
a.printing.printers = vec![Printer { name: "Office".into(), label: String::new(), default: true }];
a.printing.settings.printer = "Office".into();
a.printing.settings.copies = 3;
// The worker never answers, as when the driver doesn't: keep its sender alive.
let held = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let senders = held.clone();
a.services.print_native = Some(Box::new(move |_, _, _, _| {
let (tx, rx) = std::sync::mpsc::channel();
senders.borrow_mut().push(tx);
rx
}));
let asked = std::rc::Rc::new(std::cell::Cell::new(0));
let cancels = asked.clone();
a.services.cancel_print = Some(Box::new(move || {
cancels.set(cancels.get() + 1);
never_sent
}));
for junk in [json!({}), json!(null), json!("all"), json!([1, 2]), json!({"cancel": -1, "job": "x"})] {
assert!(a.run("ui.printCancel", junk).is_err(), "nothing to cancel before a job is submitted");
}
a.run("ui.print", json!({})).unwrap();
assert!(a.printing.busy(), "the job waits");
if close_document {
a.execute("file.close", json!({})).unwrap();
assert!(!a.has_document(), "the last document closed");
assert!(a.printing.busy(), "closing the document keeps its pending print job");
}
let enabled = |a: &WordApp| printing::commands(a).iter().any(|c| c["id"] == "ui.printCancel" && c["enabled"] == true);
assert!(enabled(&a), "Cancel is offered while the job waits");
let reply = a.execute("ui.printCancel", json!({})).unwrap();
assert_eq!(reply["cancelled"], never_sent);
assert_eq!(asked.get(), 1, "the host was asked to stop the job");
assert_eq!(a.printing.busy(), !never_sent, "never_sent {never_sent}: whether the page is still locked");
assert_eq!(a.printing.settings.printer, "Office", "the chosen printer is kept");
assert_eq!(a.printing.settings.copies, 3, "the settings are kept");
assert_eq!(a.printing.printers.len(), 1, "the printer list is kept");
let said = a.status_msg.as_ref().map(|(text, _)| text.as_str()).unwrap_or_default();
let expected = if never_sent {
"Printing cancelled. Nothing was sent to the printer."
} else {
"Cancellation could not be confirmed here. The printer driver may still be processing the job. If it appears in the system's print queue, cancel it there."
};
assert_eq!(said, expected, "never_sent {never_sent}: the status bar says what happened");
assert_eq!(enabled(&a), !never_sent);
if never_sent {
assert_eq!(a.execute("ui.printCancel", json!({})).unwrap_err(), "no print job is being submitted");
}
assert_eq!(held.borrow().len(), 1);
}
}
/// #1156: the Print page's preview fills the pane beside the settings, zooms from its own
/// bar, scrolls both ways once the page outgrows the pane, and One Page fits it again.
#[test]
@@ -4698,6 +4757,20 @@ fn web_close_while_a_picker_save_is_in_flight_asks_first() {
assert!(body_text(&a).contains(UNSAVED), "nothing was replaced");
}
/// #3274: a save the browser's picker hasn't finished yet isn't written to a file, so a
/// programmatic `file.closeDocument` refuses it as unsaved work.
#[test]
fn programmatic_close_document_keeps_a_save_the_picker_hasnt_finished() {
let (mut a, _saves, _last) = web_picker_app();
a.execute("file.save", json!({})).unwrap();
a.session.dirty = false;
let r = control_execute(&mut a, json!({"command": "file.closeDocument"}));
assert_eq!(r["ok"], json!(false), "{r}");
let e = r["error"].as_str().unwrap_or("");
assert!(e.contains("unsaved") && e.contains("force"), "{e}");
assert!(a.session.is_open(a.session.document_id()), "the document stays open");
}
/// #1315: a save that ends after another document is shown neither runs the held-back Close
/// on that document nor marks it unsaved.
#[test]
@@ -4816,6 +4889,108 @@ fn programmatic_close_guard_covers_every_form() {
assert!(!a.has_document() && !a.quit_requested);
}
/// A programmatic `app.quit` closes every open document, so unsaved work needs the same
/// explicit `force` as `file.close` rather than going silently (#3274).
#[test]
fn programmatic_quit_keeps_unsaved_work() {
let ctx = egui::Context::default();
let send = |a: &mut WordApp, params: Value| match control::handle(a, &ctx, &ControlRequest::new("app.quit", params).0) {
control::Outcome::Done(v) => v,
_ => json!({"ok": false, "error": "not a reply"}),
};
let mut a = typed();
let r = send(&mut a, json!({}));
assert_eq!(r["ok"], json!(false), "{r}");
let e = r["error"].as_str().unwrap_or("");
assert!(e.contains("unsaved") && e.contains("force"), "{e}");
assert!(!a.quit_requested, "the app keeps running");
assert!(body_text(&a).contains(UNSAVED), "the work stays");
// Only a real boolean true counts as `force`.
for force in [json!("yes"), json!(1)] {
let mut a = typed();
let r = send(&mut a, json!({"force": force}));
assert_eq!(r["ok"], json!(false), "{force}: {r}");
assert!(!a.quit_requested, "{force}");
assert!(body_text(&a).contains(UNSAVED), "{force}");
}
let r = send(&mut a, json!({"force": true}));
assert_eq!(r["ok"], json!(true), "{r}");
assert!(a.quit_requested);
// A clean document quits straight away, without a `force`.
let mut clean = app();
let r = send(&mut clean, json!({}));
assert_eq!(r["ok"], json!(true), "{r}");
assert!(clean.quit_requested);
}
/// Unsaved work in a document that isn't the active one is work a quit would lose too.
#[test]
fn programmatic_quit_keeps_the_work_of_a_background_document() {
let ctx = egui::Context::default();
let mut a = typed();
let first = a.session.document_id();
assert_eq!(control_execute(&mut a, json!({"command": "file.new"}))["ok"], json!(true));
assert_ne!(a.session.document_id(), first);
let r = match control::handle(&mut a, &ctx, &ControlRequest::new("app.quit", json!({})).0) {
control::Outcome::Done(v) => v,
_ => json!({"ok": false, "error": "not a reply"}),
};
assert_eq!(r["ok"], json!(false), "{r}");
assert!(!a.quit_requested);
assert!(a.session.is_open(first), "the background document stays open");
}
/// #3274: `file.closeDocument` closes a document without a prompt, so the unsaved work in the
/// document it names needs the same explicit `force` as `file.close` rather than going
/// silently.
#[test]
fn programmatic_close_document_keeps_unsaved_work() {
let mut a = typed();
let first = a.session.document_id();
let r = control_execute(&mut a, json!({"command": "file.closeDocument"}));
assert_eq!(r["ok"], json!(false), "{r}");
let e = r["error"].as_str().unwrap_or("");
assert!(e.contains("unsaved") && e.contains("force"), "{e}");
assert!(a.session.is_open(first), "the document stays open");
assert!(body_text(&a).contains(UNSAVED), "the work stays");
// Only a real boolean true counts as `force`.
for force in [json!("yes"), json!(1)] {
let mut a = typed();
let r = control_execute(&mut a, json!({"command": "file.closeDocument", "params": {"force": force}}));
assert_eq!(r["ok"], json!(false), "{force}: {r}");
assert!(a.session.is_open(a.session.document_id()), "{force}");
}
let r = control_execute(&mut a, json!({"command": "file.closeDocument", "params": {"force": true}}));
assert_eq!(r["ok"], json!(true), "{r}");
}
/// #3274: `file.closeDocument` names the document it closes, so unsaved work in a document in
/// the background is refused too, and `force` closes it.
#[test]
fn programmatic_close_document_keeps_the_work_of_a_background_document() {
let mut a = typed();
let first = a.session.document_id();
assert_eq!(control_execute(&mut a, json!({"command": "file.new"}))["ok"], json!(true));
assert_ne!(a.session.document_id(), first);
let r = control_execute(&mut a, json!({"command": "file.closeDocument", "params": {"id": first}}));
assert_eq!(r["ok"], json!(false), "{r}");
let e = r["error"].as_str().unwrap_or("");
assert!(e.contains("unsaved") && e.contains("force"), "{e}");
assert!(a.session.is_open(first), "the background document stays open");
let r = control_execute(&mut a, json!({"command": "file.closeDocument", "params": {"id": first, "force": true}}));
assert_eq!(r["ok"], json!(true), "{r}");
assert!(!a.session.is_open(first), "the background document is closed");
}
const MAILINGS: [&str; 4] = ["mailings.envelopes", "mailings.labels", "mailings.finish", "mailings.printDocuments"];
/// What the user gave: Envelopes and Labels without anything open their dialogs (#407).
+36
View File
@@ -533,6 +533,42 @@ fn closing_one_of_two_windows_on_a_document_asks_nothing() {
assert!(a.quit_requested, "one prompt for the document");
}
/// #3274: a programmatic `file.close` on a document shown in two windows closes the window
/// alone, as the window's own close does: the document and its work stay open, so nothing is
/// lost and the control channel must not refuse it as unsaved work it would never lose.
#[test]
fn a_programmatic_close_of_one_of_two_windows_on_a_document_is_accepted() {
let ctx = backend();
let mut a = app("Kept");
let doc = a.session.document_id();
frames(&ctx, &mut a, 2);
a.run("view.newWindow", json!({})).unwrap();
frames(&ctx, &mut a, 2);
assert_eq!(a.window_count(), 2);
assert!(a.session.dirty, "the document has unsaved work");
// The control channel's refusal: it must not stand in the way of a close that keeps the
// document open.
let refused = crate::control::close_refused(&a, "file.close", &json!({}));
assert!(refused.is_none(), "closing a window alone loses nothing: {refused:?}");
// And the command itself runs, closing the window and leaving the document and its work.
let r = crate::control::handle(&mut a, &ctx, &crate::control::ControlRequest::new("engine.execute", json!({"command": "file.close"})).0);
let r = match r {
crate::control::Outcome::Done(v) => v,
_ => json!({"ok": false, "error": "not a reply"}),
};
assert_eq!(r["ok"], true, "{r}");
assert_eq!(a.window_count(), 1, "the window closed");
assert_eq!(a.session.document_id(), doc, "the document stays open");
assert!(a.session.dirty, "its work stays");
assert_eq!(text(&a), "Kept");
// The last window closes the document, so the same command is refused for its unsaved work.
let refused = crate::control::close_refused(&a, "file.close", &json!({}));
assert!(refused.is_some(), "closing the document would lose the work: {refused:?}");
}
/// Two windows, the second (focused) on an untouched blank document: an app whose host
/// answers file dialogs only when the test does, plus the dialog's answer channel.
fn blank_beside_a_document() -> (egui::Context, WordApp, Shown, u64) {
+29 -8
View File
@@ -162,17 +162,38 @@ an operation that depends on it; do not replay an edit simply because its effect
### Closing the document
`engine.execute` with `file.close` never shows the Save / Don't Save / Cancel prompt. On a
document with unsaved changes it replies with an error (the app keeps running and the edits
stay); save first (`file.save`), or pass `{"force": true}` to discard the changes and close.
The bare form `{"method": "file.close", "force": true}` (a method name that is a command id) is
guarded the same way, and only a boolean `true` counts as `force`. A document without unsaved
changes closes at once (#1268). Closing closes the document and its window, and the window
focused before it becomes the active one. The last window stays open with no page, and
`file.new` or `file.open` goes on from there (#1712); closing it doesn't quit the app. With
`engine.execute` never shows the Save / Don't Save / Cancel prompt, so a command that would
discard unsaved work is **refused with an error** (the app keeps running and the edits stay);
save first (`file.save`), or pass `{"force": true}` to discard the changes and go ahead.
`file.close` closes the shown document, so it is refused while that document has unsaved
changes; the bare form `{"method": "file.close", "force": true}` (a method name that is a
command id) is guarded the same way, and only a boolean `true` counts as `force`. A document
without unsaved changes closes at once (#1268). Closing closes the document and its window, and
the window focused before it becomes the active one. The last window stays open with no page,
and `file.new` or `file.open` goes on from there (#1712); closing it doesn't quit the app. With
`doc` naming a document in the background, `file.close` closes that document and its window under
the same rule (unsaved changes need `{"force": true}`), and the active window stays active.
When another window shows the same document, `file.close` closes only the window it is sent to:
the document and its unsaved work stay open, so nothing is lost and the command is **not**
refused (#3274).
`file.new`, `file.open`, `file.recover` (with `restore`) and the mailings merges open their
result as **another document beside** the open ones and leave the unsaved one alone, so they
lose nothing and are never refused.
`file.closeDocument` closes the document its `id` names (the active one when the `id` is
absent), so it is refused while that document has unsaved work: changes that aren't written to
a file, a save the browser's picker hasn't finished, or a comment still being typed. Pass
`{"force": true}` to discard that work and close the document; only a boolean `true` counts as
`force`. The refusal and the Save Changes prompt ask about the same work, so they cannot
disagree (#3274).
`app.quit` closes every open document, so it is refused while any of them has unsaved changes:
the app keeps running and the work stays. Save first, or pass `{"force": true}` to discard the
changes and quit. Only a boolean `true` counts as `force`.
### Native printing
`engine.execute` can call `ui.printSettings` with `{}` to inspect the printer list, selected
File diff suppressed because one or more lines are too long
+37 -7
View File
File diff suppressed because one or more lines are too long
+5 -1
View File
@@ -1,6 +1,6 @@
# Hardware parity with Microsoft Word
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-01 · **Change:** trivial (Linux Read Aloud: a sentence a screen reader cuts off is said again); previously trivial (ink page lookup work, #3614); previously trivial (only the PDF sent to the printer has no link annotations; Save these pages as PDF keeps them, #4734); previously trivial (a document with links prints: the print job's PDF has no link annotations, #4734; previously trivial: Pen / stylus row: two-stroke and closed-head arrows; previously trivial: Pen / stylus row: ink, eraser and Ink to Shape incl. arrows landed; previously trivial: a window too big for its screen shrinks to fit when it opens, #1215; previously trivial: 32-bit Windows starts on OpenGL; previously major: first version) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 and Word for Windows
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-06 · **Change:** trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (the printer list no longer waits on printer drivers, #5710); previously trivial (Linux Read Aloud: a sentence a screen reader cuts off is said again); previously trivial (ink page lookup work, #3614); previously trivial (only the PDF sent to the printer has no link annotations; Save these pages as PDF keeps them, #4734); previously trivial (a document with links prints: the print job's PDF has no link annotations, #4734; previously trivial: Pen / stylus row: two-stroke and closed-head arrows; previously trivial: Pen / stylus row: ink, eraser and Ink to Shape incl. arrows landed; previously trivial: a window too big for its screen shrinks to fit when it opens, #1215; previously trivial: 32-bit Windows starts on OpenGL; previously major: first version) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 and Word for Windows
> **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below.
@@ -28,6 +28,10 @@ File > Print offers 2, 4, 6, 9 or 16 logical pages per physical sheet side and l
| Date | Change | Summary |
|---|---|---|
| 2026-11-06 | trivial | Print helpers remove loaded PDF/settings files before driver work, tolerate prior removal and report cleanup errors; a held-driver regression checks the files are already absent (#5710) |
| 2026-11-06 | trivial | Windows print submissions use a separate helper per job, preserving provider serialization inside the helper. An acknowledged cancellation stops that helper, so a stalled cancelled driver cannot block a later job; normal shutdown reaps helpers and removes temporary PDFs. The helper erases its plaintext inputs before driver work; a hard app crash during startup can still leave private temporary files. Startup requires an explicit start grant; after sending begins, jobs complete (#5710) |
| 2026-11-06 | trivial | File › Print: before sending starts, Cancel printing (`ui.printCancel`) stops a waiting job and frees the Print page while keeping its settings, including after the last document closes; a successfully cancelled job is never sent. Quitting cancels waiting jobs and joins jobs already sending (#5710). On Windows, winprint repeats the DEVMODE conversion after sending starts. A stall during that repeat prevents cancellation and can keep shutdown waiting, even before a native job exists. |
| 2026-11-06 | trivial | On Windows the Print panel lists printers without asking their drivers anything, removing the driver query a networked printer in power save could hold, which kept the list empty with Refresh unavailable (#5710; likely also behind the long "Finding printers" waits of #5645 and #5413): discovery uses craft-print's `printer_queues` (storytold/craft-libs#618), and printing still checks the job's options with the driver; physical sleeping-printer output remains to be confirmed by the reporter |
| 2026-10-28 | trivial | Ink page lookup work, #3614. Drawing order, geometry and saved data retain their behavior; no readiness estimate change |
| 2026-11-01 | trivial | N-up and booklet print imposition (#641): integrate current print-job link handling (#4734), preserve markup preview and sheet/copy planning; readiness estimates unchanged. |
| 2026-10-30 | trivial | Only the PDF sent to the printer leaves out link annotations; Save these pages as PDF (`file.printPdf`) keeps them (#4734) |
+20 -3
View File
File diff suppressed because one or more lines are too long
+3 -2
View File
@@ -1,6 +1,6 @@
# WordCraft parity with Microsoft Word
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** trivial (Tables row: tables nest 18 deep at most, so a .json save reads back, #3618); previously trivial (Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** trivial (Equations: `\int` + Space leaves ∫ waiting for its limits, `_a^b` then Space builds them, and the operand typed next goes inside, observed in Word for Windows on #4938, #4917; no percentage change; previously trivial: Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Tables row: tables nest 18 deep at most, so a .json save reads back, #3618); previously trivial (Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
The authoritative assessment of how close WordCraft is to Microsoft Word. [`ROADMAP.md`](../ROADMAP.md)
summarizes it; [`gaps.md`](gaps.md) itemizes every shortfall; the deep checklists are
@@ -73,7 +73,7 @@ full parity for the area.
| Pictures, shapes, text boxes, WordArt | 6 | 60% | 60% | 20–30 | Insert, crop, recolour, styles, floating placement like Word (#136), wrap (square/top-bottom/behind/front), text boxes edit and overflow (#46), VML text boxes (#242), free rotation and flips with a rotation handle (#332), WordArt: text fill (solid, gradient, none), outline, shadow, glow and reflection with our own styles, and Transform warps along arch, circle, wave, slant, inflate/deflate, chevron and triangle (other presets kept and drawn flat), connectors (straight, elbow, curved, arrowheads) glued to shapes' connection sites and re-routed when those move (#416). Missing: tight/through contour wrap, rotated text-box text, group (#267 open), shape effects, WordArt 3-D/bevel and editing text in its bent form, connector routing around shapes, Drawing Canvas, Icons, online pictures, screenshot. |
| Mailings | 2 | 70% | 70% | 6–10 | Mail merge from CSV, fields, rules (IF, SKIPIF, NEXT, NEXTIF, evaluated alike in preview and merge), fields in headers/footers (one section per letter), preview, envelopes, labels. Select Recipients takes a typed list, CSV (#247) or a sheet of an Excel (.xlsx/.xlsm) or OpenDocument (.ods) workbook, with Select Table to pick the sheet (#334); no Outlook/Contacts/Access data sources, no email merge. |
| Pictures, shapes, text boxes, WordArt | 6 | 60% | 60% | 20–30 | Insert, crop, recolour, styles, floating placement like Word (#136), wrap (square/top-bottom/behind/front), text boxes edit and overflow (#46), VML text boxes (#242), free rotation and flips with a rotation handle (#332), text-box text direction (90°, 270°, stacked), Align Text and linked text boxes (#369), Icons: an original icon library drawn in code with a searchable picker, inserted as pictures and recoloured with Icon Color (#309), Drawing Canvas with Fit/Expand/Scale and DOCX `wpc:wpc` (#344; members edited by command, not yet dragged inside the canvas; the canvas rotates and flips as a whole). Missing: tight/through contour wrap, text in a freely rotated text box, group (#267 open), shape effects, WordArt, connectors, online pictures, screenshot. |
| Equations | 1 | 75% | 20% (with Draw) | 4–8 | OMML read/write, OpenType MATH layout, in-place editor with an Equation tab (#191). Missing: line breaking of long display equations, ink equations. |
| Equations | 1 | 75% | 20% (with Draw) | 4–8 | OMML read/write, OpenType MATH layout, in-place editor with an Equation tab (#191); typed `\int`, `\sum`… + Space wait for their limits (`_a^b`), any character that can't continue `\name` corrects it (`\int_0^1`), and an operator built without an operand takes the caret into it, as observed in Word for Windows on #4938 (#4917, `equation::tests::an_autocorrected_operator_waits_for_its_limits`). Missing: line breaking of long display equations, ink equations. |
| Charts, SmartArt, Draw/ink, 3D models, icons | 4 | 3% | (20% with equations) | 70–110 | Icons landed (#309; an original library drawn in code). Draw: pens, pencil, highlighter, stroke eraser and Hide Ink (#307), ink saved as DrawingML freeforms; Lasso Select (move, recolour, delete), Add Pen gallery, Ink to Shape (line, arrow, rectangle, ellipse, triangle, polygon) and Ink Replay (#395); Ink to Math, pressure and Word's own InkML missing; charts: Insert › Chart makes column, bar (clustered and stacked), line, area, pie, doughnut and scatter charts with Chart Design (change type, Edit Data grid, title, legend, data labels) and saves them as real chart parts (#409); charts from Word are drawn (#292) and kept on save (#319) but stay read-only; SmartArt is drawn and kept (#292, #319); Insert › SmartArt (#497) creates and edits list, process, cycle, hierarchy, pyramid, radial, matrix and Venn graphics with our own layouts, a Text Pane and the SmartArt Design tab, saved as diagram parts with the drawing; SmartArt from other programs stays read-only. |
| View (modes, zoom, panes, windows) | 3 | 72% | 70% | 6–10 | Print/web/draft/read/focus, dark page (#194), pages side by side when zoomed out (#251), navigation pane; Outline view with the Outlining tab: levels, promote/demote, moving with collapsed content, expand/collapse, Show Level, first line only, text formatting (#493). Missing: View Side by Side, Synchronous Scrolling, Arrange All, Switch Windows, Master Document, Immersive Reader depth. |
| Backstage, printing, options | 3 | 58% | 55% | 12–20 | New/Home pages (#254), save prompts (#151), web printing via the browser (#209). Desktop printing still goes through PDF; Options has a fraction of Word's panes. |
@@ -253,6 +253,7 @@ can be used without committing Word output.
| Date | Change | Summary |
|---|---|---|
| 2026-10-30 | trivial | Equations: `\int`, `\sum` and the other n-ary operators typed with AutoCorrect wait for their limits: `_x^y` then Space gives the operator its limits, Space alone builds it without, and the operand typed next goes inside it; any character that can't continue `\name` corrects it (`\int_0^1`); observed in Word for Windows on #4938 (#4917); no percentage change |
| 2026-10-30 | trivial | Tables row: tables nest 18 deep at most, so a `.json` save or AutoRecover snapshot reads back, rich content in the deepest cell included (it was 24, which a `.json` save could not reopen); the .docx reader and writer still keep 24 (#3618); no percentage change |
| 2026-10-29 | trivial | Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880). Filtered/sorted order, product geometry and single-label mode retained; readiness estimates unchanged. |
| 2026-10-18 | trivial | References: Insert Table of Figures dialog; a table of figures lists any caption label (`TOC \c`), without label and number (`\a`), without page numbers (`\n`) or with them after the text (`\p`); Word's switch order is recognised and the leader kept on update (#3013); no percentage change |
+12 -1
View File
File diff suppressed because one or more lines are too long
+11 -2
View File
File diff suppressed because one or more lines are too long
@@ -126,6 +126,6 @@ modules:
# the two equal).
- type: git
url: https://github.com/storytold/craft-i18n
commit: 9d6d54d6d9ff603cc41e12e5f6ba51af3554ab66
commit: 1e515422afdda2f317af430c1f9d68a5f83935b4
dest: craft-i18n
- cargo-sources.json