Compare commits

..
Author SHA1 Message Date
Martin BallandClaude Opus 5.5 5796c665b9 ci(sonar): ignore S8707 path traversal in crates/validate developer scripts (#7994)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:38:04 +00:00
FredApps e74e627a38 parity: headless column from the engine registry (RFC-0052) (#7969) 2026-11-28 00:01:17 +01:00
FredApps e9286c9487 Merge pull request #7183 from alehel/codex/7172-native-about
macOS: open the WordCraft About dialog from the application menu
2026-11-27 23:27:51 +01:00
FredApps b7057e56f6 Merge pull request #6800 from gmrmad1/fix/6265-print-preview-numeral
Print preview: refresh the cached layout and textures when numerals change (#6265)
2026-11-27 23:27:24 +01:00
FredApps 784e4c3c35 Merge pull request #6772 from RickiNano/fix/6767-arrow-stroke-inside-head
Shapes: a thick line's stroke ends inside its arrowheads (#6767)
2026-11-27 23:26:58 +01:00
FredApps 188be727b7 Merge pull request #5887 from batistalucasv/fix/5847-justified-tab-shrink
Layout: a justified line with a tab shrinks the spaces after its last tab (#5847)
2026-11-27 23:26:05 +01:00
FredApps 05dc3214ea Merge pull request #5870 from batistalucasv/fix/5842-compare-footnotes-endnotes
Compare: diff footnote and endnote content (#5842)
2026-11-27 23:25:36 +01:00
Dylan M. TaylorandFredApps 72ca96a27c ci: notify artcraft-services on release state changes (#7923)
* ci: notify artcraft-services on release state changes

* ci: pass only the dispatch token to the notify-services workflow

secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-27 09:17:48 -05:00
RickiNano b7819874c8 #6767: file-format parity names the ends that can't move their full inset 2026-11-27 06:42:48 +01:00
RickiNano 9cf6a33374 Merge remote-tracking branch 'origin/main' into fix/6767-arrow-stroke-inside-head
# Conflicts:
#	docs/file-format-parity.md
2026-11-27 06:42:37 +01:00
batistalucasv 29bb5a4f44 Merge upstream/main and resolve ROADMAP conflict (#5847) 2026-11-26 23:22:59 -03:00
batistalucasv aae46e1274 Merge upstream/main and resolve conflicts (#5842) 2026-11-26 23:07:51 -03:00
batistalucasv 9d78c95517 Layout: restrict tab space shrinking to left/default tabs (#5847) 2026-11-26 12:16:48 -03:00
batistalucasv 6ea92c6b93 Layout: restore justify module visibility and guard shrink_line_spaces (#5847) 2026-11-26 12:14:59 -03:00
batistalucasv 7905692c1f Layout: restore layout parity table formatting and strengthen compat-mode tests (#5847) 2026-11-26 12:14:59 -03:00
batistalucasv 7416d36aeb Layout: a justified line with a tab shrinks the spaces after its last tab (#5847) 2026-11-26 12:14:29 -03:00
alehelandClaude Opus 5.5 9e68fdb76a macOS: show the translated About label in the application menu (#7172)
mac_layout looks the label up as `About {app}`, which no WordCraft catalog
has, so the menu stayed English. Use the existing `About WordCraft` entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:03:54 +01:00
alehelandClaude Opus 5.5 d63de66920 Merge main into codex/7172-native-about
Resolve main.rs against the nightly session work and use
NativeMenu::sync_with, which replaced sync in the craft-libs rev on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:03:35 +01:00
batistalucasv bee50afd8f Compare: copy and remap media when adopting revised notes 2026-11-24 15:51:06 -03:00
batistalucasv a1a3b53f74 Compare: diff footnote and endnote content (#5842) 2026-11-24 14:59:46 -03:00
RickiNano 8ff9bdb1a1 #6767: a short straight line's lone arrowhead takes the room its other end doesn't need
An arrowed end moved at most half way along the line, even when the other
end had no arrowhead and stayed put, so on a straight line shorter than
twice the inset the stroke still stuck out of the head. The two ends of a
single straight segment now share its length in proportion to their
insets. Elbow and curved connectors keep the half-way limit.
2026-11-24 07:45:17 +01:00
Madhav Agarwal 694ac7810d Merge main into fix/6265-print-preview-numeral 2026-11-24 10:41:12 +05:30
RickiNano 1441c64970 Merge remote-tracking branch 'origin/main' into fix/6767-arrow-stroke-inside-head
# Conflicts:
#	docs/file-format-parity.md
2026-11-23 16:10:30 +01:00
alehel 3b94750945 ci: retrigger checks for #7183 2026-11-21 08:32:07 +01:00
alehel 376411a22b macOS: open the WordCraft About dialog from the application menu (#7172) 2026-11-21 07:26:10 +01:00
Martin Ball 932f5b4748 Merge branch 'main' into fix/6767-arrow-stroke-inside-head 2026-11-17 09:23:03 +01:00
Martin Ball 011a46c677 Merge branch 'main' into fix/6767-arrow-stroke-inside-head 2026-11-17 05:34:58 +01:00
Martin Ball 4239458948 Merge branch 'main' into fix/6767-arrow-stroke-inside-head 2026-11-17 03:02:09 +01:00
Madhav Agarwal b4219f9745 Print preview: refresh the cached layout and textures when numerals change (#6265) 2026-11-15 22:17:05 +05:30
RickiNanoandClaude Opus 5.5 37e5849e58 #6767: a thick line's stroke ends inside its arrowheads
A line's or connector's stroke ran all the way to each arrowhead's tip,
so a thick line's body and cap stuck out of the narrow end of the head.
Each arrowed end now stops where the head is as wide as the stroke, and a
square or round cap's reach further back. An end moves at most half way
to its neighbouring point, so elbow and curved connectors keep their
shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:25:02 +01:00
27 changed files with 3572 additions and 114 deletions
+9 -9
View File
@@ -35,7 +35,7 @@ jobs:
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -44,10 +44,10 @@ jobs:
- name: Install the system libraries the GUI links
run: sudo apt-get update && sudo apt-get install -y pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
@@ -121,17 +121,17 @@ jobs:
shell: pwsh
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
@@ -181,17 +181,17 @@ jobs:
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: wordcraft
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: wordcraft
+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+2 -2
View File
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -58,7 +58,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+1
View File
@@ -74,5 +74,6 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
- Contributor credits: `docs/contributors.md`.
+2
View File
@@ -203,6 +203,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
- 2026-11-08: Layout: a turned inline picture whose file keeps no room for the turn (no or a zero `wp:effectExtent`, as other tools write) keeps its line to its frame and overhangs it, cut at the line's top and bottom, as Word does: the frame as it is in Word 2007 layout, with width and height exchanged from 45° to 135° and 225° to 315° in Word 2013+ layout. Such a file saves the same way. Pictures with the room recorded (Word's own files) still take their rotated bounds. Readiness unchanged.
- 2026-11-08: XML text and CDATA read with their line ends normalised (XML 1.0 §2.11): CR LF and a lone CR are one line feed, `&#13;` stays a CR, so a line break inside `w:t` in a file saved with Windows line ends is one space, not two (#5897); readiness estimates unchanged.
- 2026-11-08: Layout: contextual spacing drops the space after a table cell's last paragraph when that paragraph is in the Normal style, the end-of-cell mark counting as a Normal paragraph next to it; a last paragraph in another style keeps its space after. The rule is inferred from docxide-pdf's notes and its `cell-end-*` fixtures (`cell-end-text-context`, `cell-end-empty-context`); a Word comparison that tells it apart from the neighbouring paragraph's style is still open. Readiness unchanged.
- 2026-11-07: Justified paragraphs that start with a tab or contain tabs shrink the spaces after their last tab in Word 2013+ compatibility mode (mode 15), matching Word (#5847). Spaces before the line's last tab remain at their natural width.
- 2026-11-07: An in-line picture lowered past its own height (`w:position`) lowers its line as far, as in Word; all 156 synthetic lines measured for #3984 match Word (#5796). Exact spacing keeps the line's baseline.
- 2026-11-07: DOCX: a VML text box keeps its text direction: `mso-layout-flow-alt:bottom-to-top` reads as Rotate all text 270° whatever `layout-flow` says, and otherwise `layout-flow:vertical` (or `vertical-ideographic`) as 90°, so the turned text box in a compatibility-mode document's header is drawn turned, as in Word. (#5193)
- 2026-11-07: Newly opened secondary windows constrain their initial viewport dimensions to the monitor's usable area with margins for system panels, preventing new windows from exceeding screen width on high-DPI scaled displays (#5871).
@@ -1530,6 +1531,7 @@ MATH glyphs that reference the same construction now share its immutable variant
| 2026-10-10 | major | Full re-measure; progress docs restructured (stage banner, two numbers, dimensions, languages, upcoming, progress log); parity tables moved to `docs/target-app-parity.md`, milestones to `docs/roadmap.md` |
| 2026-10-09 | minor | Recently landed: RTL, Ukrainian and Brazilian Portuguese |
| 2026-10-06 | major | First honest estimate: 88% catalog, ~62% real parity, alpha ~85% of the way |
| 2026-11-07 | trivial | Progress log: a justified line with a tab shrinks the spaces after it (#5847) |
> 2026-10-27 · Technical synchronization: existing Proofing pane hooks and regression tests follow the extracted engine/UI modules on main `436d444`; compact context menus remain upstream. New-SHA validation is pending; readiness unchanged.
> 2026-10-23 · cu20we review follow-up: Only paragraph-relative box floats use the pre-spacing origin. Line-relative floats and page/margin fallbacks in cells and text boxes keep the text-top origin. Synthetic controls compare zero and 24 pt space-before across all four box contexts. New cap conversion helpers and regression tests document their contracts; readiness estimates unchanged.
+11
View File
@@ -889,6 +889,17 @@ fn parity_markdown(p: &Value) -> String {
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
}
let h = &p["headless"];
s += &format!(
"\n**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n",
h["yes"],
h["no"]["window"].as_u64().unwrap_or(0) + h["no"]["os"].as_u64().unwrap_or(0) + h["no"]["engine-gap"].as_u64().unwrap_or(0),
h["no"]["window"],
h["no"]["os"],
h["no"]["engine-gap"],
h["partial"],
h["unknown"]
);
s += "\n## Missing\n\n";
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
let m = t["missing"].as_array().cloned().unwrap_or_default();
+1 -1
View File
@@ -57,7 +57,7 @@ winresource = "0.1"
[target.'cfg(target_os = "macos")'.dependencies]
# Finder double-click, Open With, Dock drops and `open -a WordCraft letter.docx` arrive as a
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
craft = { workspace = true, features = ["platform-apple-events"] }
craft = { workspace = true, features = ["platform-apple-events", "menu"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
+78 -4
View File
@@ -20,6 +20,8 @@ mod build_flavor;
mod control_server;
mod default_apps;
mod launch_profile;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod prefs;
mod process_identity;
@@ -54,6 +56,8 @@ use wordcraft_ui_egui::{Services, WordApp, prefs::Prefs};
/// exit, the print spool it waits for at exit and the control server it stops at exit.
struct App {
app: WordApp,
#[cfg(target_os = "macos")]
native_menu: Option<craft::menu::NativeMenu>,
/// The native panels behind the file service the app reaches through `Host::files`.
panels: FilePanels,
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
@@ -71,10 +75,22 @@ struct App {
}
impl App {
fn before_input(&mut self, ctx: &egui::Context) {
#[cfg(target_os = "macos")]
if let Some(menu) = &mut self.native_menu {
menu.poll(ctx);
}
embed::before_input(ctx, |out| self.app.frame_input(out));
}
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
self.app.logic(ctx);
#[cfg(target_os = "macos")]
if let Some(menu) = &mut self.native_menu {
native_menu::update(menu, &mut self.app, ctx);
}
self.panels.pump_with(self.app.dialog_host_mut(), frame);
// A quit that waits for nothing (the documents are answered for) closes the root window.
if self.app.quit_requested && !self.app.printing.busy() {
@@ -123,7 +139,7 @@ impl eframe::App for App {
if !files.is_empty() {
self.drops.dropped(files);
}
embed::before_input(ctx, |out| self.app.frame_input(out));
self.before_input(ctx);
}
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
self.logic_pass(ctx, Some(frame));
@@ -798,6 +814,8 @@ fn main() -> eframe::Result {
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
drops,
@@ -1014,14 +1032,29 @@ mod smoke {
let drops = intake.sender();
let session = Session::new(wordcraft_doc::Document::new());
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
Run { app: App { app, panels, drops, settings, spool, control: None, exit: None }, frames, ctx, sender }
Run {
app: App {
#[cfg(target_os = "macos")]
native_menu: None,
app,
panels,
drops,
settings,
spool,
control: None,
exit: None,
},
frames,
ctx,
sender,
}
}
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
/// Returns whether the frame sent a close command.
fn step(&mut self, events: Vec<egui::Event>) -> bool {
let Run { app, frames, ctx, .. } = self;
embed::before_input(ctx, |out| app.app.frame_input(out));
app.before_input(ctx);
let mut first = true;
frames.frame_without_input(events, |ui| {
if std::mem::take(&mut first) {
@@ -1044,7 +1077,7 @@ mod smoke {
/// cancelling the close.
fn close_request_is_let_through(&mut self) -> bool {
let Run { app, ctx, .. } = self;
embed::before_input(ctx, |out| app.app.frame_input(out));
app.before_input(ctx);
let mut input =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 920.0))), ..Default::default() };
input.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { events: vec![egui::ViewportEvent::Close], ..Default::default() });
@@ -1118,6 +1151,47 @@ mod smoke {
assert!(closed, "Don't Save lets the close through");
}
}
/// A native menu selection reaches the hosted About dialog, including its credits, and Escape
/// dismisses it without changing the document. The fake backend supplies the OS selection.
#[cfg(target_os = "macos")]
#[test]
fn native_about_shows_credits_and_closes_with_escape() {
use craft::menu::{Backend, Dispatch, Event, ItemRole, MenuBar, NativeMenu};
struct Selection(Vec<Event>);
impl Backend for Selection {
fn sync(&mut self, _: &MenuBar) {}
fn attach(&mut self, _: Dispatch) {}
fn drain(&mut self) -> Vec<Event> {
std::mem::take(&mut self.0)
}
}
let mut run = Run::new();
run.app.app.start_screen();
run.settle();
let before = run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
let layout = native_menu::layout(&str::to_owned);
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().command.clone();
run.app.native_menu = Some(NativeMenu::new(Box::new(Selection(vec![Event::Click(about)]))));
run.settle();
assert!(run.app.app.dialog_host_mut().shows_modal());
let tree = run.frames.tree();
for label in ["WordCraft", "Contributors", "Models", "Language data"] {
assert!(tree.keys().into_iter().any(|key| craft::ui::testing::access::name(&tree, key) == Some(label)), "About exposes {label}");
}
run.step(vec![egui::Event::Key {
key: egui::Key::Escape,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
}]);
run.settle();
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
}
}
#[cfg(test)]
+64
View File
@@ -0,0 +1,64 @@
//! The macOS application menu uses the same About dialog as File › About.
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
use serde_json::json;
use wordcraft_ui_egui::{WordApp, i18n};
const APP_NAME: &str = "WordCraft";
const ABOUT: &str = "About WordCraft";
/// The application menu, with `tr` the translation of an English string.
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
// WordCraft's document menus live in its ribbon; keep only the application menu.
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
layout
}
fn lang(app: &WordApp) -> i18n::Lang {
i18n::Lang::from_pref(&app.ui.language)
}
fn layout_in(lang: i18n::Lang) -> Layout {
layout(&|s| i18n::tr(lang, s).to_owned())
}
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if menu.is_none() {
log::warn!("the WordCraft application menu could not be installed");
}
menu
}
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
for command in menu.take_clicks(ctx) {
if let Err(error) = app.run(&command.id, command.params) {
log::warn!("application menu: {error}");
}
}
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
let lang = lang(app);
for clash in menu.sync_with(lang.code(), || layout_in(lang)) {
log::warn!("application menu: {clash:?}");
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The catalogs translate "About WordCraft" and have no "About {app}" row.
#[test]
fn about_shows_the_catalogs_translation() {
let translate = |s: &'static str| if s == "About WordCraft" { "Über WordCraft".to_owned() } else { s.to_owned() };
let layout = layout(&translate);
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
assert_eq!(about.label, "Über WordCraft");
}
}
+48 -27
View File
@@ -647,6 +647,20 @@ fn remap_media_block(b: &mut Block, map: &BTreeMap<String, String>) {
});
}
/// Remaps media references across `blocks` and any text box stories in `parts`.
fn remap_media_in(blocks: &mut [Block], parts: &mut BTreeMap<u32, Part>, map: &BTreeMap<String, String>) {
if map.is_empty() {
return;
}
for b in blocks {
remap_media_block(b, map);
}
for part in parts.values_mut() {
for b in &mut part.blocks {
remap_media_block(Arc::make_mut(b), map);
}
}
}
/// Visit `(index, item)` in forward (`!last`) or reverse (`last`) order, returning the first `Some`.
fn find_in_slice<T>(slice: &[T], last: bool, mut f: impl FnMut(usize, &T) -> Option<Path>) -> Option<Path> {
if last { slice.iter().enumerate().rev().find_map(|(i, x)| f(i, x)) } else { slice.iter().enumerate().find_map(|(i, x)| f(i, x)) }
@@ -688,7 +702,6 @@ fn trim_para(para: &Paragraph, from: usize, to: usize, clear_section: bool) -> P
}
p
}
impl Document {
/// Convert notes between footnotes and endnotes: footnotes (`foot`) become endnotes and
/// endnotes (`end`) footnotes, both at once to swap them. Each note's kind changes, as do its
@@ -1643,13 +1656,41 @@ impl Document {
Some(id)
}
/// The blocks of `frag`, a fragment of another document, with every text box given a new
/// story of its own here copied from the fragment's parts (as a paste does), to place them
/// in this document; a box the fragment has no story for keeps none.
/// Copies `media` into `self.media`, returning a remap for keys whose bytes differ from an
/// existing entry under the same key.
fn adopt_media(&mut self, media: &BTreeMap<String, Arc<Vec<u8>>>) -> BTreeMap<String, String> {
let mut media_remap = BTreeMap::new();
for (k, v) in media {
if let Some(existing) = self.media.get(k) {
if existing.as_slice() != v.as_slice() {
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
let new_key = self.add_media((**v).clone(), ext);
media_remap.insert(k.clone(), new_key);
}
} else {
self.media.insert(k.clone(), v.clone());
}
}
media_remap
}
/// The blocks of `frag`, a fragment of another document, with its media copied (remapping
/// conflicting keys) and every text box given a new story of its own here copied from the
/// fragment's parts (as a paste does), to place them in this document; a box the fragment
/// has no story for keeps none.
pub fn adopt_fragment(&mut self, frag: &Fragment) -> Vec<Block> {
let media_remap = self.adopt_media(&frag.media);
let mut blocks = frag.blocks.clone();
let mut remapped_parts;
let parts = if media_remap.is_empty() {
&frag.parts
} else {
remapped_parts = frag.parts.clone();
remap_media_in(&mut blocks, &mut remapped_parts, &media_remap);
&remapped_parts
};
let mut budget = BoxBudget { local: false, ..BoxBudget::new() };
self.adopt_text_boxes(&mut blocks, &frag.parts, 0, &mut budget);
self.adopt_text_boxes(&mut blocks, parts, 0, &mut budget);
if budget.skipped > 0 {
log::warn!(
"{} text boxes are left empty; their stories are past what one copy brings ({MAX_PASTED_BOXES} stories, {MAX_PASTED_BOX_BYTES} bytes)",
@@ -1661,18 +1702,7 @@ impl Document {
/// Insert a fragment at `pos`; returns the position after the pasted content.
pub fn insert_fragment(&mut self, pos: &Pos, frag: &Fragment) -> Result<Pos> {
let mut media_remap = BTreeMap::new();
for (k, v) in &frag.media {
if let Some(existing) = self.media.get(k) {
if existing.as_slice() != v.as_slice() {
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
let new_key = self.add_media((**v).clone(), ext);
media_remap.insert(k.clone(), new_key);
}
} else {
self.media.insert(k.clone(), v.clone());
}
}
let media_remap = self.adopt_media(&frag.media);
// Tables that would nest deeper than the limit here become their paragraphs (#1596).
let room = MAX_TABLE_DEPTH.saturating_sub(pos.path.depth());
let mut blocks = Vec::with_capacity(frag.blocks.len());
@@ -1689,16 +1719,7 @@ impl Document {
let table_para = table_style_para(self, pos);
let destination_shading = self.styles.resolve_para_in(&dest_para.props, table_para.as_ref()).shading;
let mut parts = frag.parts.clone();
if !media_remap.is_empty() {
for b in &mut blocks {
remap_media_block(b, &media_remap);
}
for part in parts.values_mut() {
for b in &mut part.blocks {
remap_media_block(Arc::make_mut(b), &media_remap);
}
}
}
remap_media_in(&mut blocks, &mut parts, &media_remap);
// Pasted text boxes get stories of their own (never shared with the copy's source).
let mut budget = BoxBudget::new();
self.adopt_text_boxes(&mut blocks, &parts, 0, &mut budget);
+55
View File
@@ -1192,6 +1192,61 @@ fn insert_fragment_remaps_conflicting_media_keys() {
assert_eq!(remapped, other_key);
}
#[test]
fn adopt_fragment_copies_and_remaps_conflicting_media_in_blocks_and_text_boxes() {
let mut d = doc(&["destination"]);
d.media.insert("image1.png".into(), Arc::new(vec![1, 1, 1]));
let mut frag_media = std::collections::BTreeMap::new();
frag_media.insert("image1.png".into(), Arc::new(vec![2, 2, 2]));
frag_media.insert("missing.png".into(), Arc::new(vec![3, 3, 3]));
let img = |key: &str| InlineObject::Image {
media: key.into(),
w: 10.0,
h: 10.0,
alt: String::new(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
let mut tb_para = Paragraph::with_text(&crate::para::OBJ.to_string(), CharProps::default());
tb_para.objects.push(img("image1.png"));
let mut parts = std::collections::BTreeMap::new();
parts.insert(7, Part { kind: PartKind::TextBox, blocks: vec![para_block(tb_para)], body: Default::default() });
let mut top_para = Paragraph::with_text(&format!("{}{}", crate::para::OBJ, crate::para::OBJ), CharProps::default());
top_para.objects.push(img("missing.png"));
top_para.objects.push(InlineObject::Shape {
kind: crate::para::ShapeKind::TextBox,
w: 40.0,
h: 40.0,
fill: None,
stroke: None,
stroke_width: 1.0,
float: Default::default(),
story: Some(7),
freeform: None,
effects: Default::default(),
extra: Default::default(),
});
let frag = Fragment { blocks: vec![Block::Para(top_para)], parts, media: frag_media };
let adopted = d.adopt_fragment(&frag);
assert_eq!(d.media["image1.png"].as_slice(), &[1, 1, 1]);
assert_eq!(d.media["missing.png"].as_slice(), &[3, 3, 3]);
let remapped_key = d.media.keys().find(|k| k.as_str() != "image1.png" && k.as_str() != "missing.png").unwrap();
assert_eq!(d.media[remapped_key].as_slice(), &[2, 2, 2]);
let adopted_para = adopted[0].as_para().unwrap();
assert!(matches!(&adopted_para.objects[0], InlineObject::Image { media, .. } if media == "missing.png"));
let adopted_tb_id = adopted_para.objects[1].text_box().unwrap();
let adopted_tb_para = d.parts[&adopted_tb_id].blocks[0].as_para().unwrap();
assert!(matches!(&adopted_tb_para.objects[0], InlineObject::Image { media, .. } if media == remapped_key));
}
/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first
/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged.
#[test]
+137 -1
View File
@@ -532,6 +532,98 @@ Tools|Templates|Templates and Add-ins|tools.templates
Tools|Views|Full Screen View|view.fullScreenView
";
/// RFC-0052 hand marks for catalog features with no engine command: `id|headless|reach|why`.
///
/// `headless` is `no` or `partial`, `reach` is `window` (needs a desktop window, dialog or
/// pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could
/// be an engine command, isn't one yet). `yes` is never written here: a feature is `yes` only when
/// its id is in the engine registry that `wordcraft-cli` and the MCP server load, and a mark on such
/// an id is stale (`headless_errors`). A missing feature with no mark is `unknown`.
pub const HEADLESS: &str = "\
tools.dictate|no|os|speech recognition service
insert.onlinePicture|no|os|online image search service
insert.model3d|no|engine-gap|3-D model files could be inserted by a command
insert.screenshot|no|os|screen capture of other windows
addins.get|no|os|add-in store service
insert.video|no|os|online video service
insert.inkEquation|no|window|drawn with a pen or pointer
draw.inkToMath|no|os|handwriting recognition service
review.translate|no|os|online translation service
review.blockAuthors|no|os|co-authoring service
view.readLayout|no|window|Read Mode window layout
";
/// One feature's RFC-0052 `headless:` value and, for `no`/`partial`, its `reach:` and reason.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Headless {
pub value: &'static str,
pub reach: Option<&'static str>,
pub why: &'static str,
}
const REACHES: [&str; 3] = ["window", "os", "engine-gap"];
/// Parsed `HEADLESS`-format marks: (id, value, reach, why). A malformed line is an error.
pub fn headless_marks(src: &'static str) -> Result<Vec<(&'static str, Headless)>, String> {
let mut out = Vec::new();
for line in src.lines().filter(|l| !l.trim().is_empty()) {
let f: Vec<&'static str> = line.splitn(4, '|').collect();
let [id, value, reach, why] = f[..] else {
return Err(format!("headless mark `{line}`: want `id|headless|reach|why`"));
};
if !matches!(value, "no" | "partial") {
return Err(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
}
if !REACHES.contains(&reach) {
return Err(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap"));
}
if out.iter().any(|(m, _)| *m == id) {
return Err(format!("headless mark `{id}` is written twice"));
}
out.push((id, Headless { value, reach: Some(reach), why }));
}
Ok(out)
}
/// The `headless:` value of a catalog feature: `yes` when the engine registry has its id, else its
/// hand mark, else `unknown`.
pub fn headless_of(id: &str, live: bool, marks: &[(&'static str, Headless)]) -> Headless {
if live {
return Headless { value: "yes", reach: None, why: "" };
}
marks.iter().find(|(m, _)| *m == id).map(|(_, h)| *h).unwrap_or(Headless { value: "unknown", reach: None, why: "" })
}
/// Problems with the marks against the catalog and the registry's ids: unknown ids, and marks on
/// ids the engine registry has (they would hide a `yes`).
pub fn headless_errors(src: &'static str, catalog: &[(&str, &str, &str, &str)], live: impl Fn(&str) -> bool) -> Vec<String> {
let marks = match headless_marks(src) {
Ok(m) => m,
Err(e) => return vec![e],
};
let mut errs = Vec::new();
for (id, _) in &marks {
if !catalog.iter().any(|e| e.3 == *id) {
errs.push(format!("headless mark `{id}` is not a catalog id"));
} else if live(id) {
errs.push(format!("headless mark `{id}` is stale: the engine registry has it, so it is `yes`"));
}
}
errs
}
/// Headless counts in the RFC-0052 summary shape.
fn headless_summary(values: &[Headless]) -> Value {
let count = |v: &str| values.iter().filter(|h| h.value == v).count();
let no = |r: &str| values.iter().filter(|h| h.value == "no" && h.reach == Some(r)).count();
json!({
"yes": count("yes"),
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
"partial": count("partial"),
"unknown": count("unknown"),
})
}
/// Catalog entries: (tab, group, feature, id).
pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)> {
CATALOG
@@ -546,9 +638,13 @@ pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)
/// Parity summary: per tab and overall, with the missing features.
pub fn parity(reg: &Registry) -> Value {
let e = entries();
let marks = headless_marks(HEADLESS).unwrap_or_default();
let mut values = Vec::with_capacity(e.len());
let mut tabs: Vec<(&str, usize, usize, Vec<String>)> = Vec::new();
for (tab, group, label, id) in &e {
let have = reg.get(id).is_some();
let h = headless_of(id, have, &marks);
values.push(h);
let t = match tabs.iter_mut().find(|t| t.0 == *tab) {
Some(t) => t,
None => {
@@ -564,7 +660,8 @@ pub fn parity(reg: &Registry) -> Value {
if have {
t.1 += 1;
} else {
t.3.push(format!("{group} › {label} (`{id}`)"));
let reach = h.reach.map(|r| format!(", reach: {r} ({})", h.why)).unwrap_or_default();
t.3.push(format!("{group} › {label} (`{id}`): headless: {}{reach}", h.value));
}
}
let live = tabs.iter().map(|t| t.1).sum::<usize>();
@@ -573,6 +670,7 @@ pub fn parity(reg: &Registry) -> Value {
"live": live,
"total": total,
"percent": if total == 0 { 0.0 } else { (live as f64 * 1000.0 / total as f64).round() / 10.0 },
"headless": headless_summary(&values),
"tabs": tabs.iter().map(|t| json!({"tab": t.0, "live": t.1, "total": t.2, "missing": t.3})).collect::<Vec<_>>(),
})
}
@@ -597,6 +695,44 @@ mod tests {
assert!(pct >= 90.4, "parity {pct}%");
}
#[test]
fn headless_marks_are_current() {
let reg = crate::cmd::registry();
let errs = headless_errors(HEADLESS, &entries(), |id| reg.get(id).is_some());
assert!(errs.is_empty(), "{errs:?}");
}
#[test]
fn headless_yes_comes_only_from_the_registry() {
let marks = headless_marks("a.b|no|window|pointer\n").unwrap();
assert_eq!(headless_of("a.b", true, &marks).value, "yes", "a live id is yes whatever the mark says");
assert_eq!(headless_of("a.b", false, &marks).reach, Some("window"));
assert_eq!(headless_of("c.d", false, &marks).value, "unknown");
assert!(headless_marks("a.b|yes|window|x\n").is_err(), "a hand-written yes is refused");
assert!(headless_marks("a.b|no|desk|x\n").is_err(), "reach must be window, os or engine-gap");
assert!(headless_marks("a.b|no\n").is_err());
assert!(headless_marks("a.b|no|os|x\na.b|partial|os|y\n").is_err(), "one mark per id");
}
#[test]
fn headless_errors_flag_stale_and_unknown_marks() {
let cat = [("T", "G", "F", "a.b"), ("T", "G", "H", "c.d")];
let errs = headless_errors("a.b|no|os|x\nz.z|no|os|y\n", &cat, |id| id == "a.b");
assert!(errs.iter().any(|e| e.contains("`a.b` is stale")), "{errs:?}");
assert!(errs.iter().any(|e| e.contains("`z.z` is not a catalog id")), "{errs:?}");
assert!(headless_errors("bad\n", &cat, |_| false).len() == 1);
}
#[test]
fn parity_counts_every_feature_once_in_the_headless_summary() {
let p = parity(&crate::cmd::registry());
let h = &p["headless"];
let n = |v: &Value| v.as_u64().unwrap_or(0);
let no = n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]);
assert_eq!(n(&h["yes"]) + no + n(&h["partial"]) + n(&h["unknown"]), n(&p["total"]));
assert_eq!(n(&h["yes"]), n(&p["live"]), "every live feature is an engine command here");
}
#[test]
fn read_mode_view_menu_is_catalogued() {
let e = entries();
+1 -1
View File
@@ -21,7 +21,7 @@ mod typing;
pub use autocorrect::{AUTOCORRECT, AutoCap, AutoCorrectPrefs, lenient_autocorrect};
#[cfg(test)]
use compare::{Op, collapse_noise_matches, lcs_ops};
use compare::{Op, collapse_noise_matches, lcs_len, lcs_ops};
pub use specs::specs;
pub use typing::{INITIAL_CAPS_EXCEPTIONS, autocorrect, autocorrect_word, emphasis_autoformat, has_emphasis};
pub(crate) use typing::{is_turkic, lower_char, upper_char};
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+80 -15
View File
@@ -1,7 +1,7 @@
use super::options::DisplayOptions;
use super::paint::{Paint, paint_for};
use super::{BezPath, Document, Draw, FaceRef, Graphic, GraphicItem, GraphicKind, InlineObject, PathSeg, Rect, Rgb, ShapeKind, Spin, TextAlign};
use wordcraft_doc::connector::ArrowStyle;
use wordcraft_doc::connector::{ArrowStyle, LineCap};
/// The draws of a chart or diagram's items inside `rect` (page coordinates). The items were built
/// for the size `g.w` × `g.h` (0: `rect`'s own size), so they are scaled to `rect`; strokes and text
@@ -294,9 +294,14 @@ fn line_draws(
out: &mut Vec<Draw>,
) {
use wordcraft_doc::connector::{connector_segs, end_direction};
let start_dir = end_direction(kind, rect.w, rect.h, false);
let end_dir = end_direction(kind, rect.w, rect.h, true);
// An arrowed end stops inside its head, which the stroke would otherwise stick out of.
let inset = |on: bool, style| if on && stroke.is_some() { arrow_inset(stroke_width, style, extra.cap) } else { 0.0 };
let ends = [(inset(extra.arrow_start, extra.start_style), start_dir), (inset(extra.arrow_end, extra.end_style), end_dir)];
match connector_segs(kind, rect.w, rect.h) {
Some(segs) => {
let segs = segs
let mut segs: Vec<PathSeg> = segs
.into_iter()
.map(|s| match s {
PathSeg::Move(x, y) => PathSeg::Move(rect.x + x, rect.y + y),
@@ -305,32 +310,92 @@ fn line_draws(
PathSeg::Close => PathSeg::Close,
})
.collect();
shorten_ends(&mut segs, ends);
let width = path_stroke_width(stroke_width);
out.push(Draw::Path { segs, fill: None, stroke, stroke_width: width, dash: extra.dash.pattern(width), cap: extra.cap });
}
None => out.push(Draw::Shape {
rect,
kind,
fill: None,
stroke,
stroke_width,
effects,
corner: None,
dash: extra.dash.pattern(stroke_width),
cap: extra.cap,
}),
None => {
// A line's frame is its diagonal, top left to bottom right: shortened, it stays one.
let mut segs = [PathSeg::Move(rect.x, rect.y), PathSeg::Line(rect.right(), rect.bottom())];
shorten_ends(&mut segs, ends);
let line = match segs {
[PathSeg::Move(x0, y0), PathSeg::Line(x1, y1)] => Rect::new(x0.min(x1), y0.min(y1), (x1 - x0).abs(), (y1 - y0).abs()),
_ => rect,
};
out.push(Draw::Shape {
rect: line,
kind,
fill: None,
stroke,
stroke_width,
effects,
corner: None,
dash: extra.dash.pattern(stroke_width),
cap: extra.cap,
});
}
}
let Some(color) = stroke else { return };
// A line runs from the top-left corner to the bottom-right, as it is drawn (DrawingML's
// `line`), and so do connectors; flips are the frame's turn.
let (start, end) = ((rect.x, rect.y), (rect.right(), rect.bottom()));
for (on, tip, at_end, style) in [(extra.arrow_start, start, false, extra.start_style), (extra.arrow_end, end, true, extra.end_style)] {
for (on, tip, dir, style) in [(extra.arrow_start, start, start_dir, extra.start_style), (extra.arrow_end, end, end_dir, extra.end_style)] {
if on {
out.push(arrowhead(tip, end_direction(kind, rect.w, rect.h, at_end), stroke_width, style, color));
out.push(arrowhead(tip, dir, stroke_width, style, color));
}
}
}
/// How far short of an arrowhead's tip a line `stroke_width` wide with `cap` ends stops, so that
/// none of its stroke shows outside the head (#6767): where the head is as wide as the stroke,
/// plus what the cap reaches past the end. A head is at least twice as wide as its line, so this
/// is inside the head; never past its base.
fn arrow_inset(stroke_width: f32, style: ArrowStyle, cap: LineCap) -> f32 {
let width = path_stroke_width(stroke_width);
let (len, wide) = style.dims(stroke_width);
let reach = if cap == LineCap::Flat { 0.0 } else { width / 2.0 };
(len * width / wide.max(f32::EPSILON) + reach).clamp(0.0, len)
}
/// Draw the path `segs` (a line's or connector's, from its start to its end) short of its ends:
/// each end by its distance, back against its unit direction (where its arrowhead points). An end
/// moves at most half way to its neighbouring point, so the path keeps its shape, and a curve its
/// direction at the end. The two ends of a single straight segment share its length in proportion
/// to their distances instead, so an end without an arrowhead leaves its share to the other.
fn shorten_ends(segs: &mut [PathSeg], [(start, start_dir), (end, end_dir)]: [(f32, (f32, f32)); 2]) {
let distance = |by: f32| if by.is_finite() { by.max(0.0) } else { 0.0 };
let (start, end) = (distance(start), distance(end));
let share = |by: f32| match segs {
[PathSeg::Move(..), PathSeg::Line(..)] => by / (start + end).max(f32::EPSILON),
_ => 0.5,
};
let (start_share, end_share) = (share(start), share(end));
let pull = |(x, y): (f32, f32), toward: Option<(f32, f32)>, by: f32, share: f32, (dx, dy): (f32, f32)| {
let room = toward.map_or(0.0, |(tx, ty)| (tx - x).hypot(ty - y) * share);
let by = if room.is_finite() { by.min(room) } else { 0.0 };
(x - dx * by, y - dy * by)
};
// The points next to each end, before either moves.
let after_first = match segs.get(1) {
Some(PathSeg::Line(x, y) | PathSeg::Cubic(x, y, ..)) => Some((*x, *y)),
_ => None,
};
let before_last = match segs.len().checked_sub(1).map(|i| segs.split_at(i)) {
Some((_, [PathSeg::Cubic(_, _, x, y, ..)])) => Some((*x, *y)),
Some((head, [PathSeg::Line(..)])) => match head.last() {
Some(PathSeg::Move(x, y) | PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) => Some((*x, *y)),
_ => None,
},
_ => None,
};
if let Some(PathSeg::Move(x, y)) = segs.first_mut() {
(*x, *y) = pull((*x, *y), after_first, start, start_share, start_dir);
}
if let Some(PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) = segs.last_mut() {
(*x, *y) = pull((*x, *y), before_last, end, end_share, end_dir);
}
}
pub fn seg_path(segs: &[PathSeg]) -> BezPath {
let mut p = BezPath::new();
for s in segs {
+56
View File
@@ -488,4 +488,60 @@ mod tests {
}
assert_eq!(lookup_family(&d, "No Such Roman Font"), MISSING_ROMAN_FONT);
}
/// #5847: shrink_line_spaces is a no-op when there are no spaces after the line's last tab,
/// guarding against division by zero, negative room, or shifting pre-tab clusters.
#[test]
fn shrink_line_spaces_with_no_spaces_after_last_tab_is_noop() {
crate::test_fonts();
let chr = CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let mut d = Document::new();
d.settings.compat_mode = 15;
let fields = FieldCtx::default();
let env = ParaEnv {
doc: &d,
fields: &fields,
width: 468.0,
label: None,
show_hidden: false,
hide_deleted: Default::default(),
table: None,
proofing: None,
typing_word: None,
field_codes: false,
grid: Grid::default(),
exclusions: &[],
eq_number: 0,
numeral: Default::default(),
read_line_spacing: None,
fit_objects: false,
fitted: &[],
joined: false,
};
let mut p = Paragraph::with_text("n n n n\tWordWithoutSpaces", chr);
p.props = ParaProps {
align: Some(Align::Justify),
tabs: Some(vec![TabStop { pos: 150.0, align: TabAlign::Left, leader: Default::default() }]),
..Default::default()
};
let mut pl = layout_para(&p, &env);
let mark_style = pl.clusters[0].style;
break_lines(&mut pl, &env, mark_style, None);
let c0 = pl.lines[0].c0;
let c1 = pl.lines[0].c1;
let last_tab = (c0..c1).rev().find(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Tab)).unwrap();
let from = last_tab + 1;
let spaces_after = (from..c1).filter(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Space)).count();
assert_eq!(spaces_after, 0);
let orig_xs = pl.lines[0].xs.clone();
let content_end = *orig_xs.last().unwrap();
for slack in [-20.0, 0.0, f32::NEG_INFINITY] {
let mut xs = orig_xs.clone();
justify::shrink_line_spaces(&pl, &mut xs, (c0, from), c1, content_end, slack);
assert_eq!(xs, orig_xs, "slack {slack} with 0 post-tab spaces must not shift any cluster");
}
}
}
+12 -6
View File
@@ -22,23 +22,29 @@ pub(super) fn space_room(spaces: f32, word: f32) -> f32 {
(spaces * MAX_SPACE_SHRINK).min(word.max(0.0) * MAX_WORD_OVERRUN)
}
/// Take `-slack` (an overflow) out of the line's inner spaces, in proportion to their widths and
/// never more than [`MAX_SPACE_SHRINK`] of them. Trailing spaces hang and are left alone.
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], c0: usize, c1: usize, content_end: f32, slack: f32) {
let spaces: Vec<(usize, f32)> = (c0..c1)
/// Take `-slack` (an overflow) out of the line's inner spaces from `from` on (after the line's last
/// left/default tab), in proportion to their widths and never more than [`MAX_SPACE_SHRINK`] of them.
/// Trailing spaces hang and are left alone.
///
/// `c0` is the first cluster on the line, and `from` is where space shrinking begins (the cluster
/// following the line's last tab, or `c0` when there are no tabs on the line). `c1` is the end of
/// the line's cluster range.
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], (c0, from): (usize, usize), c1: usize, content_end: f32, slack: f32) {
let from = from.max(c0);
let spaces: Vec<(usize, f32)> = (from..c1)
.filter_map(|k| {
let c = pl.clusters.get(k).filter(|c| c.kind == ClKind::Space)?;
(xs.get(k - c0).copied().unwrap_or(f32::MAX) < content_end - 0.01).then_some((k, c.adv))
})
.collect();
let total: f32 = spaces.iter().map(|s| s.1).sum();
if total <= 0.0 || !slack.is_finite() {
if !total.is_finite() || total <= 0.0 || !slack.is_finite() {
return;
}
let ratio = (-slack / total).clamp(0.0, MAX_SPACE_SHRINK);
let mut take = 0.0;
let mut next = spaces.iter().peekable();
for k in c0..c1 {
for k in from..c1 {
if let Some(v) = xs.get_mut(k - c0) {
*v -= take;
}
+22 -9
View File
@@ -25,7 +25,7 @@ struct Breaker<'e> {
/// Where default tab stops are counted from (see [`next_tab`]).
tab_origin: f32,
/// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its
/// spaces (`space_room`); never on lines with tabs.
/// spaces (`space_room`); on a line with tabs, only the spaces after a final left/default tab.
shrink_spaces: bool,
/// Word 2003's indent rules (`w:doNotSuppressIndentation`) before Word 2013's layout, for an
/// unnumbered paragraph: a row starts right after a floating object before the indent.
@@ -100,9 +100,13 @@ struct Scan {
pending_tab: Option<(usize, TabStop, f32)>,
/// The text after a pending decimal tab looked at so far for its '.'.
decimal: Option<DecimalScan>,
/// The width of the spaces so far on this line.
/// The width of the spaces so far on this line, after its last tab.
space_w: f32,
has_tab: bool,
/// Whether spaces after the last tab so far may shrink (true initially and after left/default
/// tabs; false after right, center, or decimal tabs whose anchors use unshrunk widths).
shrink_tab: bool,
/// Tab cluster indices on this line whose alignment is not `TabAlign::Left`.
non_left_tabs: Vec<usize>,
/// The first word doesn't fit a span narrowed by a floating object: it moves on whole.
skip: bool,
}
@@ -306,7 +310,8 @@ impl<'e> Breaker<'e> {
pending_tab: None,
decimal: None,
space_w: 0.0,
has_tab: false,
shrink_tab: true,
non_left_tabs: Vec::new(),
skip: false,
}
}
@@ -603,10 +608,12 @@ impl<'e> Breaker<'e> {
// A line ending in a manual line break is stretched too, unless `doNotExpandShiftReturn` says not to.
let stretch_end = sc.end == LineEnd::Wrap || (sc.end == LineEnd::LineBreak && self.expand_break);
let justify = display.is_none() && ((align == Align::Justify && stretch_end) || align == Align::Distribute);
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too.
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && last_tab.is_none();
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too,
// unless its last tab is a non-left tab whose anchor was resolved with unshrunk widths.
let can_shrink_tab = last_tab.is_none_or(|k| !sc.non_left_tabs.contains(&k));
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && can_shrink_tab;
if shrink {
shrink_line_spaces(pl, &mut sc.xs, c0, c1, content_end, slack);
shrink_line_spaces(pl, &mut sc.xs, (c0, align_from), c1, content_end, slack);
} else if justify && slack > 0.0 {
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), align == Align::Distribute);
}
@@ -834,7 +841,8 @@ impl Scan {
/// A tab: its stop, and the room to it. True when the line ends before it.
fn tab(&mut self, bk: &mut Breaker, pl: &mut ParaLayout) -> bool {
let j = self.j;
self.has_tab = true;
// Only the spaces after a line's last tab shrink (measured in Word for Mac).
self.space_w = 0.0;
resolve_tab(pl, &mut self.pending_tab, &mut self.xs, self.c0, self.x, &mut self.x);
let rp = &bk.rp;
let ptab = pl.ptabs.iter().find(|t| t.0 == j).map(|&(_, a, b, l)| ptab_stop(a, b, l, bk.width, (rp.indent_left, rp.indent_right)));
@@ -877,6 +885,10 @@ impl Scan {
/// decimal tab).
fn place_tab(&mut self, pl: &mut ParaLayout, stop: TabStop) {
let j = self.j;
self.shrink_tab = stop.align == TabAlign::Left;
if !self.shrink_tab {
self.non_left_tabs.push(j);
}
match stop.align {
TabAlign::Left | TabAlign::Bar | TabAlign::Clear => {
let w = (stop.pos - self.x).max(0.0);
@@ -917,7 +929,7 @@ impl Scan {
// each segment's font, glyphs and position for painting.
let advance = pl.atomic_advance(j);
let absorbs = self.absorbs(pl, advance);
let shrink = if bk.shrink_spaces && !self.has_tab {
let shrink = if bk.shrink_spaces && self.shrink_tab {
space_room(self.space_w, self.x + advance - pl.auto_space_after(j) - self.word_from)
} else {
0.0
@@ -1057,6 +1069,7 @@ impl Scan {
self.last_break = Some(tj - 1);
self.pending_tab = None;
self.leaders.retain(|(k, _)| *k < tj);
self.non_left_tabs.retain(|&k| k < tj);
}
}
+560 -1
View File
@@ -4738,7 +4738,147 @@ fn a_lines_arrowheads_sit_at_its_ends() {
_ => None,
})
.collect();
assert_eq!(tips, [(rect.x, rect.y), (rect.right(), rect.bottom())]);
let [(x0, y0), (x1, y1)] = tips[..] else { panic!("two arrowheads: {tips:?}") };
assert!((x1 - x0 - 60.0).abs() < 0.01 && (y1 - y0 - 40.0).abs() < 0.01, "tips at the frame's corners: {tips:?}");
// The line, drawn short of its arrowed ends (#6767), runs along the same diagonal.
assert!(rect.x > x0 && rect.y > y0 && rect.right() < x1 && rect.bottom() < y1, "{rect:?} between {tips:?}");
assert!(((rect.x - x0) / 60.0 - (rect.y - y0) / 40.0).abs() < 0.001, "{rect:?} on the diagonal from {tips:?}");
assert!(((x1 - rect.right()) / 60.0 - (y1 - rect.bottom()) / 40.0).abs() < 0.001, "{rect:?} on the diagonal to {tips:?}");
}
#[test]
fn a_thick_lines_stroke_ends_inside_its_arrowheads() {
// #6767: the stroke stopped at each arrowhead's tip, so a thick line's body and cap stuck out
// of the narrow head. Each arrowed end now stops where the head is as wide as the stroke (and
// its cap's reach before that), for lines and every connector.
use wordcraft_doc::connector::{LineCap, ShapeExtra};
use wordcraft_doc::para::{Float, ShapeKind};
use wordcraft_doc::props::Rgb;
let width = 6.0;
let kinds = [ShapeKind::Line, ShapeKind::StraightConnector, ShapeKind::ElbowConnector, ShapeKind::CurvedConnector];
for kind in kinds {
for cap in [LineCap::Flat, LineCap::Square, LineCap::Round] {
let shape = InlineObject::Shape {
kind,
w: 120.0,
h: 60.0,
fill: None,
stroke: Some(Rgb::BLACK),
stroke_width: width,
float: Float::default(),
story: None,
freeform: None,
effects: Default::default(),
extra: ShapeExtra { arrow_start: true, arrow_end: true, cap, ..Default::default() },
};
let (ends, heads, draws) = line_ends_and_heads(shape);
assert_eq!((ends.len(), heads.len()), (2, 2), "{kind:?} {cap:?}: {draws:?}");
for (end, head) in ends.iter().zip(&heads) {
for corner in stroke_end_corners(*end, *head, width, cap) {
assert!(in_triangle(corner, *head), "{kind:?} {cap:?}: stroke corner {corner:?} outside the head {head:?}");
}
}
}
}
}
#[test]
fn a_short_lines_lone_arrowhead_takes_the_room_its_other_end_does_not_need() {
// #6767: an arrowed end moved at most half way along a straight line, even when the other end
// had no arrowhead and stayed put, so a short thick line's stroke still stuck out of its head.
use wordcraft_doc::connector::{LineCap, ShapeExtra};
use wordcraft_doc::para::{Float, ShapeKind};
use wordcraft_doc::props::Rgb;
let width = 6.0;
// Each is shorter than twice its inset (6 pt flat, 9 pt with the cap's reach) but no shorter
// than one inset, so the head can cover the stroke: 8 pt and 10 pt diagonals.
for (cap, (w, h)) in [(LineCap::Flat, (6.4, 4.8)), (LineCap::Square, (8.0, 6.0)), (LineCap::Round, (8.0, 6.0))] {
for kind in [ShapeKind::Line, ShapeKind::StraightConnector] {
for at_start in [true, false] {
let shape = InlineObject::Shape {
kind,
w,
h,
fill: None,
stroke: Some(Rgb::BLACK),
stroke_width: width,
float: Float::default(),
story: None,
freeform: None,
effects: Default::default(),
extra: ShapeExtra { arrow_start: at_start, arrow_end: !at_start, cap, ..Default::default() },
};
let (ends, heads, draws) = line_ends_and_heads(shape);
let (&[start, end], &[head]) = (&ends[..], &heads[..]) else { panic!("{kind:?} {cap:?}: {draws:?}") };
let tip = head[0];
let (near, far) = if at_start { (start, end) } else { (end, start) };
// The end without an arrowhead stays where it was.
let other = if at_start { (tip.0 + w, tip.1 + h) } else { (tip.0 - w, tip.1 - h) };
assert!((far.0 - other.0).abs() < 0.01 && (far.1 - other.1).abs() < 0.01, "{kind:?} {cap:?}: {far:?} moved from {other:?}");
for corner in stroke_end_corners(near, head, width, cap) {
assert!(in_triangle(corner, head), "{kind:?} {cap:?} start={at_start}: stroke corner {corner:?} outside the head {head:?}");
}
}
}
}
}
/// The ends of the stroked line or connector `shape` draws, from its start to its end, its
/// arrowheads (each tip first), and all its draws.
fn line_ends_and_heads(shape: InlineObject) -> (Vec<(f32, f32)>, Vec<[(f32, f32); 3]>, Vec<display::Draw>) {
use wordcraft_doc::graphic::PathSeg;
use wordcraft_doc::para::ShapeKind;
let mut doc = Document::from_text("Scan");
doc.insert_object(&Pos::body(0, 0), shape, &Default::default()).unwrap();
let draws = flat(display::page_display(&doc, &lay(&doc).pages[0], &Default::default()));
let mut ends = Vec::new();
let mut heads = Vec::new();
for d in &draws {
match d {
display::Draw::Shape { rect, kind: ShapeKind::Line, .. } => ends.extend([(rect.x, rect.y), (rect.right(), rect.bottom())]),
display::Draw::Path { fill: None, stroke: Some(_), segs, .. } => {
let point = |s: &PathSeg| match *s {
PathSeg::Move(x, y) | PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y) => Some((x, y)),
PathSeg::Close => None,
};
ends.extend(segs.first().and_then(point));
ends.extend(segs.last().and_then(point));
}
display::Draw::Path { fill: Some(_), segs, .. } => {
if let [PathSeg::Move(tx, ty), PathSeg::Line(ax, ay), PathSeg::Line(bx, by), PathSeg::Close] = segs[..] {
heads.push([(tx, ty), (ax, ay), (bx, by)]);
}
}
_ => {}
}
}
(ends, heads, draws)
}
/// The corners of a `width` stroke's `end` under arrowhead `head`, its `cap` included (a round
/// cap lies inside them).
fn stroke_end_corners(end: (f32, f32), head: [(f32, f32); 3], width: f32, cap: wordcraft_doc::connector::LineCap) -> [(f32, f32); 2] {
let [tip, a, b] = head;
let base = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0);
let len = (tip.0 - base.0).hypot(tip.1 - base.1);
// The head's direction, and across it.
let (dx, dy) = ((tip.0 - base.0) / len, (tip.1 - base.1) / len);
let (nx, ny) = (-dy, dx);
let reach = if cap == wordcraft_doc::connector::LineCap::Flat { 0.0 } else { width / 2.0 };
[-1.0, 1.0].map(|side| (end.0 + dx * reach + nx * side * width / 2.0, end.1 + dy * reach + ny * side * width / 2.0))
}
/// Whether `p` lies inside (or within 0.01 pt of) triangle `t`.
fn in_triangle(p: (f32, f32), t: [(f32, f32); 3]) -> bool {
let edge = |(ax, ay): (f32, f32), (bx, by): (f32, f32)| {
let len = (bx - ax).hypot(by - ay);
((bx - ax) * (p.1 - ay) - (by - ay) * (p.0 - ax)) / len
};
let sides = [edge(t[0], t[1]), edge(t[1], t[2]), edge(t[2], t[0])];
sides.iter().all(|s| *s >= -0.01) || sides.iter().all(|s| *s <= 0.01)
}
#[test]
@@ -7385,6 +7525,425 @@ fn justified_spaces_shrink_a_quarter_at_most_and_by_the_word() {
}
}
/// Measured in Word for Mac (compatibility mode 15, synthetic justified paragraphs that start
/// with a label and a tab, or with words and then a left tab): a line with a tab shrinks its
/// spaces too, but only those after its last tab. WordCraft never shrank a line with a tab, so a
/// numbered paragraph's first line wrapped a word earlier than Word's (#4845, #5847).
#[test]
fn justified_line_with_a_tab_shrinks_only_the_spaces_after_it() {
use wordcraft_doc::props::{TabAlign, TabStop};
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let word = "nnnn";
let (lead, n) = ("n n n n n n n n n n n n", 12);
let tab_at = 200.0;
let para = |text: &str, right: f32| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps {
align: Some(Align::Justify),
indent_right: Some(right),
tabs: Some(vec![TabStop { pos: tab_at, align: TabAlign::Left, leader: Default::default() }]),
..Default::default()
};
d.body = vec![wordcraft_doc::para_block(p)];
d
};
// Words after the tab on the first line.
let after_tab = |d: &Document| {
let l = lay(d);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let line = &pl.lines[0];
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
};
let probe = para(&format!("{word} {word}"), 0.0);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
// Room from the n spaces after the tab alone; the eleven before it would allow more.
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let all_room = (0.25 * (n + 11) as f32 * sw).min(0.355 * (w + sw));
assert!(all_room > room + 0.5, "the test needs the spaces before the tab to matter: {room} vs {all_room}");
let text = format!("{lead}\t{}", vec![word; 3 * n].join(" "));
let full = probe.last_section.text_width();
let width = |overrun: f32| tab_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
let d = para(&text, full - width(overrun));
assert_eq!(after_tab(&d), words, "overrun {overrun:.2} of {room:.2} allowed");
}
// Verify rendered positions: spaces after the tab shrink in the allowed-overrun case,
// while positions before the tab remain unchanged.
let shrunk_doc = para(&text, full - width(room - 0.1));
let unconstrained_doc = para(&text, 0.0);
let l_shrunk = lay(&shrunk_doc);
let l_unconstrained = lay(&unconstrained_doc);
let pl_shrunk = l_shrunk.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let pl_unconstrained =
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
// Characters in `lead` and the tab's start position must have identical positions.
for k in 0..=lead.len() {
assert_eq!(pl_shrunk.x_of(0, k), pl_unconstrained.x_of(0, k), "char {k} before tab must not move when spaces after tab shrink");
}
// Text after the tab starts at tab_at.
assert!((pl_shrunk.x_of(0, lead.len() + 1).unwrap() - tab_at).abs() < 0.01, "tab position");
// Text after the tab is shifted left compared to its natural (un-shrunk) positions:
// for each word k after the tab on line 0, natural position is tab_at + k * (w + sw).
let natural_x = |k: usize| tab_at + k as f32 * (w + sw);
for k in 1..=n {
let char_pos = lead.len() + 1 + k * (word.len() + 1);
let x = pl_shrunk.x_of(0, char_pos).expect("word position on shrunk line");
assert!(x < natural_x(k), "word {k} after tab at {x} must be shifted left from natural {}", natural_x(k));
}
}
/// #5847: a justified line with multiple tabs shrinks spaces only after its last tab.
/// Spaces before the first tab and between tabs retain their natural width and positions,
/// and only spaces after the last tab count toward space_room.
#[test]
fn justified_line_with_multiple_tabs_shrinks_only_spaces_after_last_tab() {
use wordcraft_doc::props::{TabAlign, TabStop};
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let word = "nnnn";
let (lead1, lead2, n) = ("n n n n n n", "n n n n n n", 12);
let tab1_at = 120.0;
let tab2_at = 240.0;
let para = |text: &str, right: f32| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps {
align: Some(Align::Justify),
indent_right: Some(right),
tabs: Some(vec![
TabStop { pos: tab1_at, align: TabAlign::Left, leader: Default::default() },
TabStop { pos: tab2_at, align: TabAlign::Left, leader: Default::default() },
]),
..Default::default()
};
d.body = vec![wordcraft_doc::para_block(p)];
d
};
// Words after the second tab on the first line.
let after_second_tab = |d: &Document| {
let l = lay(d);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let line = &pl.lines[0];
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
text.split('\t').nth(2).unwrap_or("").split_whitespace().count()
};
let probe = para(&format!("{word} {word}"), 0.0);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
// Room from the n spaces after the second tab alone; spaces before tab 1 or between tabs would allow more.
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let all_room = (0.25 * (n + 10) as f32 * sw).min(0.355 * (w + sw));
assert!(all_room > room + 0.5, "the test needs the spaces before the last tab to matter: {room} vs {all_room}");
let text = format!("{lead1}\t{lead2}\t{}", vec![word; 3 * n].join(" "));
let full = probe.last_section.text_width();
let width = |overrun: f32| tab2_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
let d = para(&text, full - width(overrun));
assert_eq!(after_second_tab(&d), words, "overrun {overrun:.2} of {room:.2} allowed");
}
// Verify rendered positions: spaces after the last tab shrink in the allowed-overrun case,
// while positions before tab 1 and between tabs remain completely unchanged.
let shrunk_doc = para(&text, full - width(room - 0.1));
let unconstrained_doc = para(&text, 0.0);
let l_shrunk = lay(&shrunk_doc);
let l_unconstrained = lay(&unconstrained_doc);
let pl_shrunk = l_shrunk.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let pl_unconstrained =
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
// Characters in `lead1`, tab 1, and `lead2` up to the second tab must have identical positions.
let pre_last_tab_len = lead1.len() + 1 + lead2.len();
for k in 0..=pre_last_tab_len {
assert_eq!(pl_shrunk.x_of(0, k), pl_unconstrained.x_of(0, k), "char {k} before last tab must not move when spaces after last tab shrink");
}
// Text after the second tab starts at tab2_at.
assert!((pl_shrunk.x_of(0, pre_last_tab_len + 1).unwrap() - tab2_at).abs() < 0.01, "second tab position");
// Text after the second tab is shifted left compared to its natural (un-shrunk) positions:
let natural_x = |k: usize| tab2_at + k as f32 * (w + sw);
for k in 1..=n {
let char_pos = pre_last_tab_len + 1 + k * (word.len() + 1);
let x = pl_shrunk.x_of(0, char_pos).expect("word position on shrunk line");
assert!(x < natural_x(k), "word {k} after last tab at {x} must be shifted left from natural {}", natural_x(k));
}
}
/// #5847: a tabbed line with no spaces after its last tab has zero shrink room.
/// Space shrinking is a no-op, guarding against division by zero, negative room,
/// or shifting pre-tab clusters when there are no spaces to shrink after the tab.
#[test]
fn justified_line_with_tab_and_no_spaces_after_it_does_not_shrink() {
use wordcraft_doc::props::{TabAlign, TabStop};
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let lead = "n n n n n n n n";
let word = "OverlongWordWithoutAnySpace";
let tab_at = 200.0;
let para = |text: &str, right: f32| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps {
align: Some(Align::Justify),
indent_right: Some(right),
tabs: Some(vec![TabStop { pos: tab_at, align: TabAlign::Left, leader: Default::default() }]),
..Default::default()
};
d.body = vec![wordcraft_doc::para_block(p)];
d
};
let probe = para(word, 0.0);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let word_w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let text = format!("{lead}\t{word}");
let full = probe.last_section.text_width();
// Constrain the line so that `word` overruns the right edge by 2.0 pt.
// Because there are no spaces after the tab, shrink room is 0 and the word
// must wrap to line 1 rather than shrinking onto line 0.
let tight_doc = para(&text, full - (tab_at + word_w - 2.0));
let l_tight = lay(&tight_doc);
let pl_tight = l_tight.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
assert_eq!(pl_tight.lines.len(), 2, "word with no spaces after tab must wrap when it overruns the line");
// When the word fits within the line, characters before the tab and the word after the tab
// remain at their exact natural positions (no pre-tab shift, no shrink).
let fit_doc = para(&text, full - (tab_at + word_w + 50.0));
let unconstrained_doc = para(&text, 0.0);
let l_fit = lay(&fit_doc);
let l_unconstrained = lay(&unconstrained_doc);
let pl_fit = l_fit.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let pl_unconstrained =
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
for k in 0..=text.len() {
assert_eq!(
pl_fit.x_of(0, k),
pl_unconstrained.x_of(0, k),
"char {k} position must be unchanged when there are no spaces to shrink after the tab"
);
}
}
/// #5847: justified paragraphs starting with a tab shrink spaces on the first line in Word 2013+
/// mode, fitting more text than legacy mode 14 just as non-tab lines do.
#[test]
fn justified_lines_with_tab_shrink_spaces_in_word_2013_mode() {
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let word = "nnnn";
let n = 12;
let tab_at = 36.0; // default 0.5" tab stop
let para = |text: &str, right: f32, mode: u32| {
let mut d = Document::new();
d.settings.compat_mode = mode;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), ..Default::default() };
d.body = vec![wordcraft_doc::para_block(p)];
d
};
let first = |d: &Document| {
let l = lay(d);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let line = &pl.lines[0];
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
};
let probe = para(&format!("{word} {word}"), 0.0, 15);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let text = format!("\t{}", vec![word; 3 * n].join(" "));
let full = probe.last_section.text_width();
let width = tab_at + (n + 1) as f32 * w + n as f32 * sw - (room - 0.1);
// Verify on the tabbed first line that mode 15 fits the extra word via space shrinking
// while legacy mode 14 does not shrink spaces, wrapping the extra word to the next line.
let modern_doc = para(&text, full - width, 15);
let legacy_doc = para(&text, full - width, 14);
assert_eq!(first(&modern_doc), n + 1, "mode 15 with leading tab fits extra word within allowable overrun");
assert_eq!(first(&legacy_doc), n, "mode 14 with leading tab does not shrink spaces and wraps extra word");
// Multi-line justified paragraph with leading tab also fits more lines overall in mode 15.
let text_full = format!("\t{}", "We tie the spend to a pipe and to the books, so it is in an ad hoc view of all of it. ".repeat(40));
let (modern, ends) = justified_lines(&text_full, 15, Align::Justify);
let (legacy, legacy_ends) = justified_lines(&text_full, 14, Align::Justify);
assert!(modern < legacy, "mode 15 with leading tab fits more per line: {modern} vs {legacy} lines");
for e in ends.iter().chain(&legacy_ends) {
assert!(*e <= 540.0 + 0.05, "line ends past the right margin: {e}");
}
for e in &ends[..ends.len() - 1] {
assert!((*e - 540.0).abs() < 0.05, "justified line ends at {e}");
}
}
/// #5847: leading tab on a justified line shrinks spaces after the tab when fitting words.
#[test]
fn justified_line_with_leading_tab_shrinks_spaces() {
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let word = "nnnn";
let n = 12;
let tab_at = 36.0; // default 0.5" tab stop
let para = |text: &str, right: f32| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), ..Default::default() };
d.body = vec![wordcraft_doc::para_block(p)];
d
};
let first = |d: &Document| {
let l = lay(d);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let line = &pl.lines[0];
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
};
let probe = para(&format!("{word} {word}"), 0.0);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let text = format!("\t{}", vec![word; 3 * n].join(" "));
let full = probe.last_section.text_width();
let width = |overrun: f32| tab_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
let d = para(&text, full - width(overrun));
assert_eq!(first(&d), words, "leading tab overrun {overrun:.2} of {room:.2} allowed");
}
}
/// #5847: fit-time and final space compression apply only after left/default tabs, not after
/// right, center, or decimal tabs whose anchors are resolved with unshrunk widths.
#[test]
fn justified_line_with_non_left_tab_preserves_anchor_and_does_not_shrink() {
use wordcraft_doc::props::{TabAlign, TabStop};
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let para = |text: &str, right: f32, tabs: Vec<TabStop>| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), tabs: Some(tabs), ..Default::default() };
d.body = vec![wordcraft_doc::para_block(p)];
d
};
let first_pl = |d: &Document| {
let l = lay(d);
l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap()
};
// 1. Right tab past the usable right edge: multiword run is absorbed against the stop and
// must keep its final edge at the stop rather than shrinking left of it.
let right_text = "lead\tnnnn nnnn nnnn";
let right_stop = 280.0;
let right_edge = 240.0;
let right_tabs = vec![TabStop { pos: right_stop, align: TabAlign::Right, leader: Default::default() }];
let right_unconstrained = para(right_text, 0.0, right_tabs.clone());
let full = right_unconstrained.last_section.text_width();
let pl_right_unconstrained = first_pl(&right_unconstrained);
let pl_right = first_pl(&para(right_text, full - right_edge, right_tabs));
assert_eq!(pl_right.lines.len(), 1, "absorbed multiword run after right tab stays on line 0");
assert!(
(pl_right.x_of(0, right_text.len()).unwrap() - right_stop).abs() < 0.01,
"right-tabbed multiword run must remain aligned to stop {right_stop}, got {:?}",
pl_right.x_of(0, right_text.len())
);
for k in 0..=right_text.len() {
assert_eq!(pl_right.x_of(0, k), pl_right_unconstrained.x_of(0, k), "char {k} after right tab must not shrink");
}
// 2. Decimal tab on an overfull line: spaces before the decimal point must not shrink and
// pull the decimal point left of its stop.
let dec_text = "\t12 34.56789";
let dec_stop = 200.0;
let dec_tabs = vec![TabStop { pos: dec_stop, align: TabAlign::Decimal, leader: Default::default() }];
let dec_unconstrained = para(dec_text, 0.0, dec_tabs.clone());
let pl_dec_unconstrained = first_pl(&dec_unconstrained);
let dot_idx = dec_text.find('.').unwrap();
let dec_end = pl_dec_unconstrained.x_of(0, dec_text.len()).unwrap();
let pl_dec = first_pl(&para(dec_text, full - (dec_end - 5.0), dec_tabs));
assert_eq!(pl_dec.lines.len(), 1, "decimal-tabbed run stays on line 0");
assert_eq!(
pl_dec.x_of(0, dot_idx),
pl_dec_unconstrained.x_of(0, dot_idx),
"decimal point must keep its unconstrained anchor on an overfull line"
);
for k in 0..=dec_text.len() {
assert_eq!(pl_dec.x_of(0, k), pl_dec_unconstrained.x_of(0, k), "char {k} after decimal tab must not shrink");
}
// 3. Center tab:
// (a) Overfull center-tabbed line must not run final compression and shift off its stop.
let center_overfull_text = "\taaaaaaaaaa bbbbbbbbbb";
let center_overfull_stop = 250.0;
let center_overfull_tabs = vec![TabStop { pos: center_overfull_stop, align: TabAlign::Center, leader: Default::default() }];
let center_unconstrained = para(center_overfull_text, 0.0, center_overfull_tabs.clone());
let pl_center_unconstrained = first_pl(&center_unconstrained);
let pl_center_overfull = first_pl(&para(center_overfull_text, full - 260.0, center_overfull_tabs));
assert_eq!(pl_center_overfull.lines.len(), 1, "overfull center-tabbed line stays on line 0");
let mid = (pl_center_overfull.x_of(0, 1).unwrap() + pl_center_overfull.x_of(0, center_overfull_text.len()).unwrap()) / 2.0;
assert!((mid - center_overfull_stop).abs() < 0.01, "centered midpoint {mid} must stay at {center_overfull_stop}");
for k in 0..=center_overfull_text.len() {
assert_eq!(pl_center_overfull.x_of(0, k), pl_center_unconstrained.x_of(0, k), "char {k} after center tab must not shrink");
}
// (b) Fit-time compression must not pull an overflowing trailing word onto a non-left-tabbed line.
let probe = para("n n i", 0.0, Vec::new());
let pl_probe = first_pl(&probe);
let sw = pl_probe.x_of(0, 2).unwrap() - pl_probe.x_of(0, 1).unwrap();
let w_i = pl_probe.x_of(0, 5).unwrap() - pl_probe.x_of(0, 4).unwrap();
let prefix = "n ".repeat(12);
let fit_text = format!("\t{prefix}i");
let pl_prefix = first_pl(&para(&prefix, 0.0, Vec::new()));
let w_pre = pl_prefix.x_of(0, prefix.len()).unwrap();
let room = (0.25 * 12.0 * sw).min(0.355 * (sw + w_i));
let fit_edge = w_pre + w_i - (room - 0.1);
for align in [TabAlign::Right, TabAlign::Center, TabAlign::Decimal] {
let pl_fit = first_pl(&para(&fit_text, full - fit_edge, vec![TabStop { pos: 3.0, align, leader: Default::default() }]));
assert_eq!(pl_fit.lines.len(), 2, "{align:?} tab must not use fit-time space shrinking to accept 'i'");
}
// 4. Right tab followed by a left tab: spaces after the final left tab still shrink while the
// earlier right tab keeps its anchor.
let word = "nnnn";
let n = 12;
let right_seg = "aa bb";
let pl_w = first_pl(&para(&format!("{word} {word}"), 0.0, Vec::new()));
let w = pl_w.x_of(0, word.len()).unwrap();
let left_room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let mixed_text = format!("\t{right_seg}\t{}", vec![word; 3 * n].join(" "));
let mixed_right_stop = 120.0;
let mixed_left_stop = 160.0;
let mixed_width = mixed_left_stop + (n + 1) as f32 * w + n as f32 * sw - (left_room - 0.1);
let pl_mixed = first_pl(&para(
&mixed_text,
full - mixed_width,
vec![
TabStop { pos: mixed_right_stop, align: TabAlign::Right, leader: Default::default() },
TabStop { pos: mixed_left_stop, align: TabAlign::Left, leader: Default::default() },
],
));
assert!(
(pl_mixed.x_of(0, 1 + right_seg.len()).unwrap() - mixed_right_stop).abs() < 0.01,
"earlier right tab must keep its stop {mixed_right_stop}"
);
let first_line_words = mixed_text[pl_mixed.lines[0].start..pl_mixed.lines[0].stop].split('\t').nth(2).unwrap_or("").split_whitespace().count();
assert_eq!(first_line_words, n + 1, "spaces after final left tab still shrink");
}
#[test]
fn space_shrinking_is_only_for_justified_text() {
crate::test_fonts();
+29 -4
View File
@@ -155,13 +155,14 @@ fn markup_key(app: &WordApp) -> MarkupKey {
/// What the preview's layout is made from besides the document's text: the document id, the
/// revision, Print Markup and Track Changes Options, the file name and path FILENAME fields show
/// (#6282: Save As and Rename change them without an edit), and the font database generation the
/// app has seen (#6283: `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, u64, MarkupKey, (String, String), u64);
/// (#6282: Save As and Rename change them without an edit), the numeral mode (#6265: it changes
/// the display without an edit or a revision), and the font database generation the app has seen
/// (#6283: `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, u64, MarkupKey, wordcraft_layout::NumeralMode, (String, String), u64);
/// The [`LayoutKey`] now.
fn layout_key(app: &WordApp) -> LayoutKey {
(app.session.document_id(), app.session.rev(), markup_key(app), app.session.resolved_filenames(), app.font_generation)
(app.session.document_id(), app.session.rev(), markup_key(app), app.session.view.numeral, app.session.resolved_filenames(), app.font_generation)
}
/// The output layout, kept in `cache` while what it is made from ([`LayoutKey`]) is unchanged.
@@ -496,6 +497,30 @@ mod tests {
}
}
/// Numeral display changes layout and pixels without changing the document revision
/// (#6265): the preview must not reuse either cache.
#[test]
fn preview_refreshes_layout_and_texture_when_the_numeral_mode_changes() {
let session = Session::new(wordcraft_doc::Document::from_text("2026 Report"));
let mut app = WordApp::new(session, Services::default());
let mut cache = None;
let rev = app.session.rev();
let mut previous = None;
for mode in ["arabic", "hindi", "arabic"] {
app.session.run("view.numeral", &json!({ "value": mode })).unwrap();
let layout = layout_of(&app, &mut cache);
assert!(Arc::ptr_eq(&layout, &layout_of(&app, &mut cache)), "unchanged layout is reused");
let revision = preview::inputs(&app);
assert_eq!(revision, preview::inputs(&app));
if let Some((old_layout, old_revision)) = previous.take() {
assert!(!Arc::ptr_eq(&layout, &old_layout));
assert_ne!(revision, old_revision, "the sheet is drawn again");
}
previous = Some((layout, revision));
assert_eq!(app.session.rev(), rev);
}
}
/// A one-page synthetic document in a fresh preview.
fn synthetic_app() -> (WordApp, egui::Context) {
let session = Session::new(wordcraft_doc::Document::from_text("Synthetic print preview"));
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -31,7 +31,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic
| Line breaking (UAX #14 with Word's exceptions: no break after `/`, a break after `-` before a digit, before another `-` (a row of hyphens wraps at any hyphen), or before a slash and a letter (`Dataprotection-` / `/Secrecyviolation` in the #3408 report's Word PDF; `fitness-/1589` stays whole in the arabic_rice_benefits_article reference), no break between `.` and `(`) | ✅ | `layout::tests::no_line_break_right_after_a_slash`, `layout::tests::a_hyphen_before_digits_is_a_break_opportunity_like_word`, `layout::tests::a_hyphen_before_a_slash_is_a_break_opportunity_like_word`, `layout::tests::a_row_of_hyphens_wraps_at_any_hyphen_like_word`, `layout::tests::a_full_stop_before_a_parenthesis_is_no_break`, `layout::tests::a_bookmark_is_no_line_break_opportunity` | — |
| A break before a slash that starts a word (" /word" wraps whole; not after a no-break space) | 🟡 | `layout::tests::a_word_after_a_slash_wraps_whole`, `layout::tests::a_no_break_space_before_a_slash_still_holds`; behaviour from the #2963 report, not compared with Word yet | — |
| Narrow table cells | ✅ | `layout::tests::narrow_cells_keep_their_width`: usable widths below 12 pt wrap without expansion; oversized glyphs still make progress | 0 |
| Justification, Word 2013+ space shrinking (compat mode 15) | ✅ | #109; spaces before a line's first character (paragraph indented with spaces, after a line break or a tab, a bookmark, hidden text or a floating object's anchor before them) keep their width in justified and distributed lines, `layout::tests::leading_spaces_keep_their_width_in_justified_lines` | — |
| Justification, Word 2013+ space shrinking (compat mode 15) | ✅ | #109, #5847. A line with a tab shrinks too, counting only the spaces after its last tab, measured in Word for Mac (`layout::tests::justified_line_with_a_tab_shrinks_only_the_spaces_after_it`); spaces before a line's first character (paragraph indented with spaces, after a line break or a tab, a bookmark, hidden text or a floating object's anchor before them) keep their width in justified and distributed lines (`layout::tests::leading_spaces_keep_their_width_in_justified_lines`) | — |
| Spaces at the end of a line hang past the right margin instead of wrapping; the caret after them stays at the margin, in the body and in headers and footers | ✅ | `layout::tests::caret_after_hanging_spaces_stays_at_the_margin` (#2146): a letter typed after them wraps to the next line | — |
| Complex scripts (Myanmar, Khmer, Indic): shaped per script run with OpenType fallback fonts, one cluster per syllable, Myanmar wraps between syllables | 🟡 | `layout::tests::complex` (#604). Khmer, Thai and Lao still wrap only at spaces (need a dictionary) | 4–8 |
| Cursive joining (Arabic, Syriac, Mongolian, N'Ko…) across runs: a letter takes its form from the text shown beside it, across a change of formatting, past a vowel sign in a run of its own and past hidden or tracked-deleted text left out of the view; a tab, break, object or drop cap still stops the join | ✅ | `layout::tests::bidi::letters_join_across_a_change_of_formatting`, `letters_join_past_text_left_out_of_the_layout`, `letters_join_past_a_mark_in_a_run_of_its_own`, `letters_stay_apart_where_nothing_joins_them` (#4093); not compared with Word on this machine | 0 |
@@ -558,6 +558,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc
| 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) |
| 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller |
| 2026-11-12 | minor | Added layout.fitOnePage: heuristic search over discrete font half-point steps and spacing compression with anti-clutter safeguards (line-spacing floor and font-size floor) to condense multi-page documents by one page while preserving hierarchy |
| 2026-11-07 | trivial | A justified line with a tab shrinks its spaces to fit more text, counting only the spaces after the line's last tab, measured in Word for Mac; WordCraft never shrank a line with a tab, so a numbered paragraph's first line wrapped a word early (#5847) |
| 2026-10-31 | trivial | Web addresses: no line break after the `?` of a query (`/?type=`) or after a slash before an underscore (`/portal/_back`). Word for Mac 16.93 kept such an address whole and moved it to the next line; WordCraft broke it there (UAX #14 allows both). With the address moved along the line one word at a time (60 paragraphs, Times New Roman 12pt), WordCraft's lines now match Word's line for line; 23 (query) and 19 (underscore) paragraphs broke inside the address before. A `?` keeps its break before anything but an ASCII letter, digit or underscore (CJK text), and a path after a space (`caption /_back`) wraps whole. `layout::tests::no_line_break_inside_a_query_address`, `a_path_after_a_space_wraps_whole`, `a_question_mark_in_cjk_text_keeps_its_break` |
Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box
+14 -12
View File
@@ -32,35 +32,37 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-
| Editing | 41 | 41 |
| Tools | 7 | 7 |
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 510 yes, 12 no (window 3, os 8, engine-gap 1), 0 partial, 0 unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.
## Missing
### Home
- Voice › Dictate (`tools.dictate`)
- Voice › Dictate (`tools.dictate`): headless: no, reach: os (speech recognition service)
### Insert
- Illustrations › Online Pictures (`insert.onlinePicture`)
- Illustrations › 3D Models (`insert.model3d`)
- Illustrations › Screenshot (`insert.screenshot`)
- Add-ins › Get Add-ins (`addins.get`)
- Media › Online Video (`insert.video`)
- Symbols › Ink Equation (`insert.inkEquation`)
- Illustrations › Online Pictures (`insert.onlinePicture`): headless: no, reach: os (online image search service)
- Illustrations › 3D Models (`insert.model3d`): headless: no, reach: engine-gap (3-D model files could be inserted by a command)
- Illustrations › Screenshot (`insert.screenshot`): headless: no, reach: os (screen capture of other windows)
- Add-ins › Get Add-ins (`addins.get`): headless: no, reach: os (add-in store service)
- Media › Online Video (`insert.video`): headless: no, reach: os (online video service)
- Symbols › Ink Equation (`insert.inkEquation`): headless: no, reach: window (drawn with a pen or pointer)
### Draw
- Convert › Ink to Math (`draw.inkToMath`)
- Convert › Ink to Math (`draw.inkToMath`): headless: no, reach: os (handwriting recognition service)
### Review
- Language › Translate (`review.translate`)
- Protect › Block Authors (`review.blockAuthors`)
- Language › Translate (`review.translate`): headless: no, reach: os (online translation service)
- Protect › Block Authors (`review.blockAuthors`): headless: no, reach: os (co-authoring service)
### Read Mode
- View › Layout (`view.readLayout`)
- View › Layout (`view.readLayout`): headless: no, reach: window (Read Mode window layout)
### Equation
- Tools › Ink Equation (`insert.inkEquation`)
- Tools › Ink Equation (`insert.inkEquation`): headless: no, reach: window (drawn with a pen or pointer)
+7 -1
View File
@@ -11,7 +11,7 @@ sonar.python.coverage.reportPaths=python-coverage.xml
# S4790 (weak hash): SHA-1 is a start-key and "SHA1/1K" checksum algorithm that ODF package
# encryption (ODF 1.3 Part 2 §4.16) names, and older office suites wrote it. It is needed to open
# those files, not chosen for new security: WordCraft writes a SHA-256 start key and checksum.
sonar.issue.ignore.multicriteria=odt_sha1
sonar.issue.ignore.multicriteria=odt_sha1,validate_py_paths
sonar.issue.ignore.multicriteria.odt_sha1.ruleKey=rust:S4790
sonar.issue.ignore.multicriteria.odt_sha1.resourceKey=crates/formats/src/odt/crypt.rs
@@ -22,3 +22,9 @@ sonar.issue.ignore.multicriteria.odt_sha1.resourceKey=crates/formats/src/odt/cry
# os_window, control-key). process_identity.rs is Windows-only (the taskbar AUMID) and cannot run
# on the Linux runner either.
sonar.coverage.exclusions=packaging/**,apps/wordcraft/src/main.rs,apps/wordcraft-cli/src/main.rs,apps/wordcraft/src/process_identity.rs
# S8707 (path traversal): the crates/validate *.py scripts are developer tools run by hand to
# regenerate checked-in files; reading and writing the paths given on their command line is
# their purpose, and nothing passes them untrusted input.
sonar.issue.ignore.multicriteria.validate_py_paths.ruleKey=pythonsecurity:S8707
sonar.issue.ignore.multicriteria.validate_py_paths.resourceKey=crates/validate/**/*.py