mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-29 21:59:14 +00:00
Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c0bab3515 | ||
|
|
85db2accf9 | ||
|
|
eeeb31d85f | ||
|
|
5796c665b9 | ||
|
|
e74e627a38 | ||
|
|
e9286c9487 | ||
|
|
b7057e56f6 | ||
|
|
784e4c3c35 | ||
|
|
188be727b7 | ||
|
|
05dc3214ea | ||
|
|
72ca96a27c | ||
|
|
f83d554322 | ||
|
|
0f4e80aedd | ||
|
|
bab08b77e1 | ||
|
|
2b407facd0 | ||
|
|
b7819874c8 | ||
|
|
9cf6a33374 | ||
|
|
29bb5a4f44 | ||
|
|
aae46e1274 | ||
|
|
9d78c95517 | ||
|
|
6ea92c6b93 | ||
|
|
7905692c1f | ||
|
|
7416d36aeb | ||
|
|
9e68fdb76a | ||
|
|
d63de66920 | ||
|
|
bee50afd8f | ||
|
|
a1a3b53f74 | ||
|
|
8ff9bdb1a1 | ||
|
|
694ac7810d | ||
|
|
1441c64970 | ||
|
|
3b94750945 | ||
|
|
376411a22b | ||
|
|
932f5b4748 | ||
|
|
011a46c677 | ||
|
|
4239458948 | ||
|
|
b4219f9745 | ||
|
|
37e5849e58 |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408489772,
|
||||
"producer_workflow_id": 429734489,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
|
||||
@@ -34,12 +34,26 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: wordcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the existing release environment (which trusts release and
|
||||
# nightly-signer) and export keys in its signing step.
|
||||
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: wordcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
@@ -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 }}
|
||||
@@ -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`.
|
||||
|
||||
@@ -172,6 +172,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
|
||||
- 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing.
|
||||
- 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged.
|
||||
- 2026-11-03: A picture inserted or pasted in a table cell fits the cell, as in Word, instead of running out of it; in text columns it fits the column, in a section with other margins that section's width (#5428).
|
||||
- 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed.
|
||||
|
||||
- 2026-11-15: Layout: from Word 2013's layout (compatibility mode 15), balancing the columns before a continuous break keeps the last two, three or five lines of a paragraph that began on the page before together, keeps a two- or three-line paragraph that begins the last page whole, and holds a paragraph with keep lines together (or keep with next) whole in the first column when the strict rules fit. Synthetic tests also cover a footnote and a float (#6821); mode 14 splits them as before. Readiness estimates unchanged.
|
||||
@@ -202,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, ` ` 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).
|
||||
@@ -993,6 +995,7 @@ MATH glyphs that reference the same construction now share its immutable variant
|
||||
| 2026-11-12 | trivial | Validator: exclude every glossary-typed part from main traversal and fallback assignment; multiple content-type fallback candidates are ambiguous, with no selected anchor (#5875). Synthetic controls; no parity estimate changed. |
|
||||
| 2026-11-12 | trivial | Validator: mixed Transitional/Strict entry points to the same target skip document checks with coverage in either order (#5875); distinct competing roots retain ambiguity treatment without evaluating the profile gate. No parity estimate changed. |
|
||||
| 2026-11-12 | trivial | Validator: competing official role targets produce coverage and suppress dependent findings; both-order, repeated-target, malformed-source and owner-isolation controls (#5875). No parity estimate changed. |
|
||||
| 2026-11-03 | trivial | Progress log: a picture inserted or pasted in a table cell fits the cell (#5428) |
|
||||
| 2026-11-10 | trivial | Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf (#6180) |
|
||||
| 2026-11-08 | trivial | Progress log: freestanding custom.dic dictionary file support in File › Options › Proofing (#5840) |
|
||||
| 2026-11-08 | trivial | Progress log: XML line ends in text normalised (#5897) |
|
||||
@@ -1528,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.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,9 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
if std::fs::metadata(&child).is_ok_and(|meta| !meta.is_dir()) {
|
||||
return Err(format!("the nightly {label} must be a directory"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
@@ -171,11 +174,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The app's exclusive create probe: a file only this process can have made, created and removed.
|
||||
pub fn probe_writable(dir: &Path) -> std::io::Result<()> {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
@@ -245,6 +293,8 @@ fn validate_for(
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 5] = ["recovery", "logs", "fonts", "Templates", "FontStore"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -341,6 +391,31 @@ mod tests {
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
+48
-27
@@ -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);
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -117,9 +117,9 @@ fn place_picture(s: &mut Session, bytes: Vec<u8>, width: Option<f32>, alt: &str)
|
||||
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, TIFF, WMF, EMF)".into())),
|
||||
},
|
||||
};
|
||||
// Fitted to the room where it goes: the table cell, the column, its own section (#5428).
|
||||
let max_w = s.room_at(&s.sel.ordered().0);
|
||||
let key = s.doc.add_media(bytes, ext);
|
||||
// Fitted to the text width.
|
||||
let max_w = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0);
|
||||
let (mut w, mut h) = (natural_w, natural_h);
|
||||
if let Some(want) = width {
|
||||
// At most 22 inches, as for icons: a huge width made the height of a tall picture infinite.
|
||||
|
||||
@@ -499,10 +499,23 @@ pub(crate) fn unlink_sections(blocks: &mut [Block]) {
|
||||
/// lists and styles it refers to (renumbered so they can't collide with ours).
|
||||
fn adopt(s: &mut Session, src: Document) -> Fragment {
|
||||
let mut frag = s.doc.adopt(src);
|
||||
// Pasted pictures fit our text width, like Insert › Pictures (layout keeps their size).
|
||||
let max_w = crate::io::text_width(&s.doc);
|
||||
// Pasted pictures fit the room where they go, like Insert › Pictures: the table cell, the
|
||||
// column, its own section (#5428; layout keeps their size). Measured (a layout) only when
|
||||
// the fragment holds an inline picture.
|
||||
let mut has_picture = false;
|
||||
for b in &mut frag.blocks {
|
||||
crate::io::fit_block_pictures(b, max_w);
|
||||
each_para(b, 0, &mut |p| {
|
||||
has_picture |= p
|
||||
.objects
|
||||
.iter()
|
||||
.any(|o| matches!(o, wordcraft_doc::InlineObject::Image { float, .. } if float.wrap == wordcraft_doc::para::Wrap::Inline));
|
||||
});
|
||||
}
|
||||
if has_picture {
|
||||
let max_w = s.room_at(&s.sel.ordered().0);
|
||||
for b in &mut frag.blocks {
|
||||
crate::io::fit_block_pictures(b, max_w);
|
||||
}
|
||||
}
|
||||
unlink_sections(&mut frag.blocks);
|
||||
frag
|
||||
|
||||
@@ -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
@@ -204,6 +204,43 @@ impl Session {
|
||||
Arc::new(wordcraft_layout::layout(doc, &mut LayoutCache::new(), &opts))
|
||||
}
|
||||
|
||||
/// How wide a picture put in at `pos` may be, as Word fits an inserted or pasted picture
|
||||
/// (#5428): the room its paragraph's lines have (the width available to its widest laid-out line,
|
||||
/// so the paragraph's indents are already taken out; inside a table cell, the innermost cell's
|
||||
/// text area, nested tables included; a turned cell isn't measured and falls back to the
|
||||
/// column width), never wider than the column it is in, of its own section. The narrowest
|
||||
/// section's text width ([`crate::io::text_width`]) when `pos` isn't laid out. It is measured on the pages, whatever the view: Web Layout and Read Mode reflow the
|
||||
/// text to the window, and a picture put in there keeps the size it gets in the document.
|
||||
pub(crate) fn room_at(&mut self, pos: &wordcraft_doc::Pos) -> f32 {
|
||||
let first = crate::io::text_width(&self.doc);
|
||||
let l =
|
||||
if !self.view.read_mode && self.view.mode == ViewMode::Print { self.layout() } else { self.output_layout_of(&self.doc, false, false) };
|
||||
let Some((caret, page)) = l.caret_on(pos, self.page_hint).and_then(|c| Some((c, l.pages.get(c.page)?))) else { return first };
|
||||
// A page can hold several continuous sections: the body's own comes from the position.
|
||||
let at = match (pos.story, pos.path.0.first()) {
|
||||
(StoryRef::Body, Some(b)) => self.doc.section_index_of(*b as usize),
|
||||
_ => page.section,
|
||||
};
|
||||
let section = self.doc.sections().get(at).map(|(_, sp)| (*sp).clone());
|
||||
let column = match (§ion, pos.story) {
|
||||
(Some(sp), StoryRef::Body) => {
|
||||
let boxes = sp.column_boxes();
|
||||
let x = caret.x - page.body.x;
|
||||
boxes.iter().find(|(cx, w)| x >= cx - 0.5 && x <= cx + w + 0.5).map_or_else(|| sp.text_width(), |(_, w)| *w)
|
||||
}
|
||||
(Some(sp), StoryRef::Part(_)) => sp.text_width(),
|
||||
(None, _) => first,
|
||||
};
|
||||
let lines = wordcraft_layout::hit::page_lines(page, pos.story)
|
||||
.iter()
|
||||
.filter(|h| *h.path == pos.path)
|
||||
.map(|h| h.right - h.left)
|
||||
.filter(|w| w.is_finite())
|
||||
.fold(0.0f32, f32::max);
|
||||
let room = if lines >= 1.0 { lines.min(column) } else { column };
|
||||
if room.is_finite() && room >= 1.0 { room } else { first }
|
||||
}
|
||||
|
||||
/// Invalidate the cached layout (fonts changed etc.).
|
||||
pub fn relayout(&mut self) {
|
||||
self.layout = Default::default();
|
||||
|
||||
@@ -14943,6 +14943,143 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
|
||||
/// (a nested cell's too), a column's, not the whole page's text width.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_inserted_or_pasted_picture_fits_where_it_goes() {
|
||||
let png = |w: u32, h: u32| {
|
||||
let mut b = Vec::new();
|
||||
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
cmd::insert::base64_encode(&b)
|
||||
};
|
||||
let widths = |s: &Session| {
|
||||
let mut v = Vec::new();
|
||||
for b in s.doc.body.iter() {
|
||||
let mut b = (**b).clone();
|
||||
cmd::paste::each_para(&mut b, 0, &mut |p| {
|
||||
for o in &p.objects {
|
||||
if let wordcraft_doc::InlineObject::Image { w, h, .. } = o {
|
||||
v.push((*w, *h));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
v
|
||||
};
|
||||
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
|
||||
let in_cell = |cols: u32| {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.table", json!({"rows": 1, "cols": cols}));
|
||||
assert!(s.sel.focus.path.depth() > 0, "the caret is in the first cell");
|
||||
s
|
||||
};
|
||||
// Insert › Pictures and Paste in a cell of a three-column table.
|
||||
let cell = text_w / 3.0;
|
||||
let mut s = in_cell(3);
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let mut p = in_cell(3);
|
||||
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
|
||||
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
|
||||
for (how, s) in [("inserted", &s), ("pasted", &p)] {
|
||||
let got = widths(s);
|
||||
let [(w, h)] = got.as_slice() else { panic!("{how}: {got:?}") };
|
||||
assert!(*w <= cell && *w > cell - 20.0, "{how}: {w} fits the cell's text area ({cell} less its margins)");
|
||||
assert!((h * 5.0 - w).abs() < 0.1, "{how}: proportions kept: {w} × {h}");
|
||||
}
|
||||
// A table in that cell: its own narrower cell.
|
||||
let mut s = in_cell(2);
|
||||
let outer = s.room_at(&s.sel.focus.clone());
|
||||
// (A table inserted in a cell takes the page's text width for its columns, so four columns
|
||||
// make its cells narrower than the outer one.)
|
||||
run(&mut s, "insert.table", json!({"rows": 1, "cols": 4}));
|
||||
assert!(s.sel.focus.path.depth() > 1, "the caret is in the nested cell");
|
||||
let nested = s.room_at(&s.sel.focus.clone());
|
||||
assert!(nested < outer - 50.0, "the nested cell ({nested}) is narrower than the outer one ({outer})");
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let w = widths(&s)[0].0;
|
||||
assert!((w - nested).abs() < 0.5 && w <= text_w / 4.0, "{w} fits the nested cell ({nested})");
|
||||
// Two text columns: one column's width.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "layout.columns", json!({"count": 2}));
|
||||
let column = s.doc.sections()[0].1.column_boxes()[0].1;
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let w = widths(&s)[0].0;
|
||||
assert!((w - column).abs() < 0.5, "{w} fits the column ({column})");
|
||||
// Body text keeps the full text width.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
assert!((widths(&s)[0].0 - text_w).abs() < 0.5);
|
||||
}
|
||||
|
||||
/// #5428 review: a page can hold several continuous sections; a picture goes by the section of the
|
||||
/// position, not of the page's first one (two columns, then a continuous single-column section).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_picture_after_a_continuous_break_fits_its_own_section() {
|
||||
let sect = |cols: &str, kind: &str| format!(r#"<w:sectPr>{kind}<w:pgSz w:w="11906" w:h="16838"/><w:cols {cols} w:space="708"/></w:sectPr>"#);
|
||||
let body = [
|
||||
"<w:p><w:r><w:t>one</w:t></w:r></w:p>".to_string(),
|
||||
format!("<w:p><w:pPr>{}</w:pPr></w:p>", sect(r#"w:num="2""#, "")),
|
||||
"<w:p><w:r><w:t>two</w:t></w:r></w:p>".to_string(),
|
||||
sect("", r#"<w:type w:val="continuous"/>"#),
|
||||
]
|
||||
.concat();
|
||||
let mut s = Session::new(wordcraft_docx::read(&docx_with_styles(&body, "")).unwrap());
|
||||
let last = s.doc.body.len() - 1;
|
||||
s.sel = crate::Selection::caret(Pos::body(last, 0));
|
||||
let room = s.room_at(&s.sel.focus.clone());
|
||||
let column = s.doc.sections()[0].1.column_boxes()[0].1;
|
||||
assert!(room > column + 50.0, "{room} is the single column's width, not the earlier two columns' ({column})");
|
||||
}
|
||||
|
||||
/// #5428 review: Web Layout and Read Mode reflow the text to the window, but a picture put in
|
||||
/// there is fitted to the page's text width, as in Print Layout: the size stays in the document.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_picture_put_in_in_web_layout_fits_the_page_not_the_window() {
|
||||
let png = |w: u32, h: u32| {
|
||||
let mut b = Vec::new();
|
||||
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
cmd::insert::base64_encode(&b)
|
||||
};
|
||||
let width = |s: &Session| {
|
||||
s.doc.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).find_map(|o| match o {
|
||||
wordcraft_doc::InlineObject::Image { w, .. } => Some(*w),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
|
||||
let web = || {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "view.webLayout", json!({}));
|
||||
// A narrow window, or a high zoom.
|
||||
s.view.web_width = 350.0;
|
||||
assert!(s.layout().pages[0].w < text_w, "the window is narrower than the page's text");
|
||||
s
|
||||
};
|
||||
let mut s = web();
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let mut p = web();
|
||||
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
|
||||
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
|
||||
for (how, s) in [("inserted", &s), ("pasted", &p)] {
|
||||
let w = width(s).unwrap();
|
||||
assert!((w - text_w).abs() < 0.5, "{how}: {w} fits the page's text width ({text_w})");
|
||||
}
|
||||
// Read Mode's narrow pages don't set it either.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "Read"}));
|
||||
run(&mut s, "view.readMode", json!({}));
|
||||
s.view.read_width = 240.0;
|
||||
let room = s.room_at(&s.sel.focus.clone());
|
||||
assert!((room - text_w).abs() < 0.5, "Read Mode: {room} is the page's text width ({text_w})");
|
||||
}
|
||||
|
||||
/// A picture an OpenDocument file gives no size is shown at its own, fitted to the text as other
|
||||
/// formats' are; one with a stated size keeps it, in line too.
|
||||
#[test]
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
@@ -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(¶(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(¶(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(¢er_unconstrained);
|
||||
let pl_center_overfull = first_pl(¶(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(¶(&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(¶(&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(¶(&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(¶(
|
||||
&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();
|
||||
|
||||
@@ -319,6 +319,7 @@ impl WordApp {
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
let lang = i18n::Lang::from_pref(&self.ui.language);
|
||||
if self.ctx.is_none() {
|
||||
theme::set_dark_text_curve(ctx);
|
||||
self.ctx = Some(ctx.clone());
|
||||
}
|
||||
updates_ui::tick(self, ctx);
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -8,7 +8,7 @@ use craft::ui::buttons::{Arrangement, Button, IconButton};
|
||||
use craft::ui::contract::{ActivateOn, BodyCx, CollectionEvent, Gap, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::display::Divider;
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::primitives::{HAlign, TextRun};
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
@@ -286,17 +286,69 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The recent and common characters as a grid of six per row; a click inserts the character, remembers it and closes
|
||||
/// The characters the grid offers after the recent ones, with their Unicode names (UnicodeData.txt). No Unicode-names
|
||||
/// crate is installed, and the one on crates.io is under Unicode-DFS-2016, which the licence allowlist lacks.
|
||||
const DEFAULT_SYMBOLS: &[(char, &str)] = &[
|
||||
('\u{A9}', "COPYRIGHT SIGN"),
|
||||
('\u{AE}', "REGISTERED SIGN"),
|
||||
('\u{2122}', "TRADE MARK SIGN"),
|
||||
('\u{A7}', "SECTION SIGN"),
|
||||
('\u{B6}', "PILCROW SIGN"),
|
||||
('\u{20AC}', "EURO SIGN"),
|
||||
('\u{A3}', "POUND SIGN"),
|
||||
('\u{A5}', "YEN SIGN"),
|
||||
('\u{B0}', "DEGREE SIGN"),
|
||||
('\u{B1}', "PLUS-MINUS SIGN"),
|
||||
('\u{2260}', "NOT EQUAL TO"),
|
||||
('\u{2264}', "LESS-THAN OR EQUAL TO"),
|
||||
('\u{2265}', "GREATER-THAN OR EQUAL TO"),
|
||||
('\u{F7}', "DIVISION SIGN"),
|
||||
('\u{D7}', "MULTIPLICATION SIGN"),
|
||||
('\u{221E}', "INFINITY"),
|
||||
('\u{B5}', "MICRO SIGN"),
|
||||
('\u{3B1}', "GREEK SMALL LETTER ALPHA"),
|
||||
('\u{3B2}', "GREEK SMALL LETTER BETA"),
|
||||
('\u{3C0}', "GREEK SMALL LETTER PI"),
|
||||
('\u{3A9}', "GREEK CAPITAL LETTER OMEGA"),
|
||||
('\u{2211}', "N-ARY SUMMATION"),
|
||||
('\u{221A}', "SQUARE ROOT"),
|
||||
('\u{2192}', "RIGHTWARDS ARROW"),
|
||||
('\u{2190}', "LEFTWARDS ARROW"),
|
||||
('\u{2713}', "CHECK MARK"),
|
||||
('\u{2605}', "BLACK STAR"),
|
||||
('\u{2665}', "BLACK HEART SUIT"),
|
||||
('\u{2014}', "EM DASH"),
|
||||
('\u{2026}', "HORIZONTAL ELLIPSIS"),
|
||||
];
|
||||
|
||||
/// A symbol's hover text: its Unicode name and code point (the code point alone, with its block, for a character
|
||||
/// not named above), then its font when it has one.
|
||||
pub(super) fn symbol_tip(glyph: &str, font: &str) -> String {
|
||||
let mut chars = glyph.chars();
|
||||
let tip = match (chars.next(), chars.next()) {
|
||||
(Some(c), None) => {
|
||||
let name = DEFAULT_SYMBOLS.iter().find(|(n, _)| *n == c).map(|(_, name)| *name);
|
||||
let block = crate::dialogs_insert::subset_of(c);
|
||||
match (name, block) {
|
||||
(Some(name), _) => format!("{name} (U+{:04X})", c as u32),
|
||||
(None, Some(block)) => format!("U+{:04X} ({block})", c as u32),
|
||||
(None, None) => format!("U+{:04X}", c as u32),
|
||||
}
|
||||
}
|
||||
_ => glyph.to_string(),
|
||||
};
|
||||
if font.is_empty() { tip } else { format!("{tip}, {font}") }
|
||||
}
|
||||
|
||||
/// The recent and common characters as a compact grid; a click inserts the character, remembers it and closes
|
||||
/// the menu.
|
||||
fn symbol_grid(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
// Recently used symbols first (their font on hover), then common ones.
|
||||
let mut items: Vec<(String, String)> = app.ui.recent_symbols.iter().map(|r| (r.ch.clone(), r.font.clone())).collect();
|
||||
for c in [
|
||||
"©", "®", "™", "§", "¶", "€", "£", "¥", "°", "±", "≠", "≤", "≥", "÷", "×", "∞", "µ", "α", "β", "π", "Ω", "∑", "√", "→", "←", "✓", "★", "♥",
|
||||
"—", "…",
|
||||
] {
|
||||
if !items.iter().any(|(ch, f)| ch == c && f.is_empty()) {
|
||||
items.push((c.to_string(), String::new()));
|
||||
for (c, _) in DEFAULT_SYMBOLS {
|
||||
let c = c.to_string();
|
||||
if !items.iter().any(|(ch, f)| *ch == c && f.is_empty()) {
|
||||
items.push((c, String::new()));
|
||||
}
|
||||
}
|
||||
items.truncate(30);
|
||||
@@ -304,20 +356,20 @@ fn symbol_grid(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
.select(SelectMode::None)
|
||||
.activate(ActivateOn::Click)
|
||||
.caption(CaptionPlace::None)
|
||||
.card_columns(6)
|
||||
.content_cells()
|
||||
// Small cells (#7165): a glyph needs no more room than the small thumbnail step.
|
||||
.thumb_size(ThumbSize::Small)
|
||||
// At most thirty symbols, all shown; the menu's body is the one scroll.
|
||||
.natural_height(true)
|
||||
.show_items(ui, &SymbolCells(items.len()), &mut |key, _| {
|
||||
let (c, font) = items.get(*key).cloned().unwrap_or_default();
|
||||
let glyph = c.clone();
|
||||
let (glyph, tip) = (c.clone(), symbol_tip(&c, &font));
|
||||
let tile = Tile::new(c).thumb(ThumbAspect::SQUARE, move |cx, rect| {
|
||||
let run = TextRun::new(glyph.as_str()).align(HAlign::Center);
|
||||
cx.with_draw(|d| {
|
||||
d.text_on_centre_line(rect, &run);
|
||||
});
|
||||
});
|
||||
if font.is_empty() { tile } else { tile.tooltip(font) }
|
||||
tile.tooltip(tip)
|
||||
});
|
||||
for event in &out.response.events {
|
||||
if let CollectionEvent::Activate(key) = event
|
||||
|
||||
@@ -959,92 +959,109 @@ fn unimplemented_stub_ribbon_buttons_are_disabled() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #7324, #7457: Table ribbon menu buttons (Styles, Borders, Select, Delete, AutoFit) bind their command IDs
|
||||
/// so they disable when editing is protected or when no table is active.
|
||||
#[test]
|
||||
fn table_ribbon_menu_buttons_disable_when_unselected_or_protected() {
|
||||
/// Is the ribbon button `name` disabled? (helpers for the table ribbon gate tests below.)
|
||||
fn table_button_disabled(h: &Harness, name: &str) -> bool {
|
||||
use egui::accesskit::Role;
|
||||
h.query_all(By::new().role(Role::Button).label(name)).next().unwrap_or_else(|| panic!("button {name} not found")).accesskit_node().is_disabled()
|
||||
}
|
||||
|
||||
let is_disabled = |h: &Harness, name: &str| {
|
||||
h.query_all(By::new().role(Role::Button).label(name))
|
||||
.next()
|
||||
.unwrap_or_else(|| panic!("button {name} not found"))
|
||||
.accesskit_node()
|
||||
.is_disabled()
|
||||
};
|
||||
fn table_button_hint(h: &Harness, name: &str) -> String {
|
||||
use egui::accesskit::Role;
|
||||
h.query_all(By::new().role(Role::Button).label(name))
|
||||
.next()
|
||||
.unwrap_or_else(|| panic!("button {name} not found"))
|
||||
.accesskit_node()
|
||||
.description()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
let description = |h: &Harness, name: &str| {
|
||||
h.query_all(By::new().role(Role::Button).label(name))
|
||||
.next()
|
||||
.unwrap_or_else(|| panic!("button {name} not found"))
|
||||
.accesskit_node()
|
||||
.description()
|
||||
.map(|s| s.to_string())
|
||||
};
|
||||
/// A 2x2 table app on `tab`; `protected` sets read-only protection.
|
||||
fn table_tab_harness(tab: &str, protected: bool) -> Harness {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
if protected {
|
||||
app.session.doc.settings.protection = Some("readOnly".into());
|
||||
}
|
||||
tab_harness(app, tab)
|
||||
}
|
||||
|
||||
// Configure Table Design & Table Layout as explicit ribbon tabs so they can be
|
||||
// displayed even when the cursor is outside a table.
|
||||
let make_table_tabs_app = |mut app: WordApp| {
|
||||
/// #7324, #7457: without an active table the Table ribbon menu buttons disable. The Table tabs are
|
||||
/// configured explicitly so they show with the cursor outside a table.
|
||||
#[test]
|
||||
fn table_ribbon_menu_buttons_disable_when_unselected() {
|
||||
for tab in ["Table Design", "Table Layout"] {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default());
|
||||
app.session.ribbon.tabs = vec![
|
||||
wordcraft_engine::ribbon::TabEntry { name: "Table Design".to_string(), custom: false, hidden: false, groups: Vec::new() },
|
||||
wordcraft_engine::ribbon::TabEntry { name: "Table Layout".to_string(), custom: false, hidden: false, groups: Vec::new() },
|
||||
];
|
||||
app
|
||||
};
|
||||
let h = tab_harness(app, tab);
|
||||
if tab == "Table Design" {
|
||||
assert!(table_button_disabled(&h, "Styles"), "Styles button should be disabled when not in table");
|
||||
assert!(table_button_disabled(&h, "Borders"), "Borders button should be disabled when not in table");
|
||||
} else {
|
||||
assert!(table_button_disabled(&h, "Select"), "Select button should be disabled when not in table");
|
||||
assert!(table_button_disabled(&h, "Delete"), "Delete button should be disabled when not in table");
|
||||
assert!(table_button_disabled(&h, "AutoFit"), "AutoFit button should be disabled when not in table");
|
||||
assert!(
|
||||
table_button_hint(&h, "Select").to_ascii_lowercase().contains("the cursor isn't in a table"),
|
||||
"Select should indicate outside table in disabled hint"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Without a table active:
|
||||
let app_no_table = make_table_tabs_app(WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default()));
|
||||
let h_design_empty = tab_harness(app_no_table, "Table Design");
|
||||
assert!(is_disabled(&h_design_empty, "Styles"), "Styles button should be disabled when not in table");
|
||||
assert!(is_disabled(&h_design_empty, "Borders"), "Borders button should be disabled when not in table");
|
||||
/// With an active, unprotected table the Table Design buttons are enabled.
|
||||
#[test]
|
||||
fn table_design_menu_buttons_enabled_in_table() {
|
||||
let h = table_tab_harness("Table Design", false);
|
||||
assert!(!table_button_disabled(&h, "Styles"), "Styles button should be enabled in table");
|
||||
assert!(!table_button_disabled(&h, "Borders"), "Borders button should be enabled in table");
|
||||
}
|
||||
|
||||
let app_no_table2 = make_table_tabs_app(WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default()));
|
||||
let h_layout_empty = tab_harness(app_no_table2, "Table Layout");
|
||||
assert!(is_disabled(&h_layout_empty, "Select"), "Select button should be disabled when not in table");
|
||||
assert!(is_disabled(&h_layout_empty, "Delete"), "Delete button should be disabled when not in table");
|
||||
assert!(is_disabled(&h_layout_empty, "AutoFit"), "AutoFit button should be disabled when not in table");
|
||||
assert!(
|
||||
description(&h_layout_empty, "Select").as_deref().unwrap_or("").to_ascii_lowercase().contains("the cursor isn't in a table"),
|
||||
"Select should indicate outside table in disabled hint"
|
||||
);
|
||||
/// With an active, unprotected table the Table Layout buttons are enabled and open their menus
|
||||
/// (the controls for the shut-menu checks under protection).
|
||||
#[test]
|
||||
fn table_layout_menu_buttons_enabled_in_table() {
|
||||
let mut h = table_tab_harness("Table Layout", false);
|
||||
assert!(!table_button_disabled(&h, "Select"), "Select button should be enabled in table");
|
||||
assert!(!table_button_disabled(&h, "Delete"), "Delete button should be enabled in table");
|
||||
assert!(!table_button_disabled(&h, "AutoFit"), "AutoFit button should be enabled in table");
|
||||
click_button(&mut h, "Delete");
|
||||
assert!(h.query_all(menu_row("Delete Rows")).next().is_some(), "an enabled Delete opens its menu");
|
||||
}
|
||||
|
||||
// 2. With an active table and no protection: buttons are enabled:
|
||||
let mut app_table = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_table.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let h_design = tab_harness(app_table, "Table Design");
|
||||
assert!(!is_disabled(&h_design, "Styles"), "Styles button should be enabled in table");
|
||||
assert!(!is_disabled(&h_design, "Borders"), "Borders button should be enabled in table");
|
||||
/// Positive control for the AutoFit shut-menu check under protection: an enabled AutoFit opens its menu.
|
||||
#[test]
|
||||
fn table_layout_autofit_opens_menu_in_table() {
|
||||
let mut h = table_tab_harness("Table Layout", false);
|
||||
click_button(&mut h, "AutoFit");
|
||||
assert!(h.query_all(menu_row("AutoFit Window")).next().is_some(), "an enabled AutoFit opens its menu");
|
||||
}
|
||||
|
||||
let mut app_table2 = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_table2.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let h_layout = tab_harness(app_table2, "Table Layout");
|
||||
assert!(!is_disabled(&h_layout, "Select"), "Select button should be enabled in table");
|
||||
assert!(!is_disabled(&h_layout, "Delete"), "Delete button should be enabled in table");
|
||||
assert!(!is_disabled(&h_layout, "AutoFit"), "AutoFit button should be enabled in table");
|
||||
/// Under read-only protection the Table Design buttons disable and say why.
|
||||
#[test]
|
||||
fn table_design_menu_buttons_disable_when_protected() {
|
||||
let h = table_tab_harness("Table Design", true);
|
||||
assert!(table_button_disabled(&h, "Styles"), "Styles button should be disabled under protection");
|
||||
assert!(table_button_disabled(&h, "Borders"), "Borders button should be disabled under protection");
|
||||
assert!(table_button_hint(&h, "Styles").contains("protected"), "Styles should indicate protection in disabled hint");
|
||||
}
|
||||
|
||||
// 3. With an active table under document protection (read-only): mutating buttons are disabled:
|
||||
let mut app_protected_design = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_protected_design.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
app_protected_design.session.doc.settings.protection = Some("readOnly".into());
|
||||
let h_prot_design = tab_harness(app_protected_design, "Table Design");
|
||||
assert!(is_disabled(&h_prot_design, "Styles"), "Styles button should be disabled under protection");
|
||||
assert!(is_disabled(&h_prot_design, "Borders"), "Borders button should be disabled under protection");
|
||||
assert!(
|
||||
description(&h_prot_design, "Styles").as_deref().unwrap_or("").contains("protected"),
|
||||
"Styles should indicate protection in disabled hint"
|
||||
);
|
||||
|
||||
let mut app_protected_layout = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_protected_layout.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
app_protected_layout.session.doc.settings.protection = Some("readOnly".into());
|
||||
let h_prot_layout = tab_harness(app_protected_layout, "Table Layout");
|
||||
assert!(!is_disabled(&h_prot_layout, "Select"), "Select button should remain enabled under protection");
|
||||
assert!(is_disabled(&h_prot_layout, "Delete"), "Delete button should be disabled under protection");
|
||||
assert!(is_disabled(&h_prot_layout, "AutoFit"), "AutoFit button should be disabled under protection");
|
||||
assert!(
|
||||
description(&h_prot_layout, "Delete").as_deref().unwrap_or("").contains("protected"),
|
||||
"Delete should indicate protection in disabled hint"
|
||||
);
|
||||
/// Under read-only protection the mutating Table Layout buttons disable, say why, and stay shut
|
||||
/// when clicked (C2-5, #7824).
|
||||
#[test]
|
||||
fn table_layout_menu_buttons_disable_when_protected() {
|
||||
let mut h = table_tab_harness("Table Layout", true);
|
||||
assert!(!table_button_disabled(&h, "Select"), "Select button should remain enabled under protection");
|
||||
assert!(table_button_disabled(&h, "Delete"), "Delete button should be disabled under protection");
|
||||
assert!(table_button_disabled(&h, "AutoFit"), "AutoFit button should be disabled under protection");
|
||||
assert!(table_button_hint(&h, "Delete").contains("protected"), "Delete should indicate protection in disabled hint");
|
||||
click_button(&mut h, "Delete");
|
||||
assert!(h.query_all(menu_row("Delete Rows")).next().is_none(), "a disabled Delete opens no menu");
|
||||
click_button(&mut h, "AutoFit");
|
||||
assert!(h.query_all(menu_row("AutoFit Window")).next().is_none(), "a disabled AutoFit opens no menu");
|
||||
}
|
||||
|
||||
/// #7374: the Decorative Text / WordArt Styles dropdown menu renders compact tiles (~40×36 pt)
|
||||
@@ -1322,3 +1339,37 @@ fn a_combo_field_reached_with_tab_shows_its_hint_after_a_delay() {
|
||||
}
|
||||
assert!(h.query_all_by_label("Font Size").count() >= 2, "hint must show after tooltip delay");
|
||||
}
|
||||
|
||||
/// #7165: the Symbol drop-down's cells are compact (a thumbnail-small step, not a card) and the hover text names
|
||||
/// the character, not just the glyph.
|
||||
#[test]
|
||||
fn symbol_menu_cells_are_compact_and_the_tooltip_names_the_character() {
|
||||
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Text")), crate::Services::default());
|
||||
let mut h = tab_harness(app, "Insert");
|
||||
click_button(&mut h, "Symbol");
|
||||
let cell_y = |h: &Harness| h.get_by_label("\u{A9}").rect().min.y;
|
||||
let cell = h.get_by_label("\u{A9}").rect();
|
||||
assert!(cell.width() <= 80.0 && cell.height() <= 80.0, "a symbol cell is compact, got {:?}", cell.size());
|
||||
// Eight symbols fit one row, so the menu does not cover the page.
|
||||
assert_eq!(h.get_by_label("\u{A5}").rect().min.y, cell_y(&h), "the eighth symbol is on the first row");
|
||||
h.get_by_label("\u{A9}").hover();
|
||||
crate::test_harness::frames(&mut h, 40);
|
||||
assert!(h.query_by_label_contains("COPYRIGHT SIGN (U+00A9)").is_some(), "the tooltip names the character");
|
||||
// A screen reader gets the name without hovering: the tile's label is the glyph, its description the name.
|
||||
let desc = h.get_by_label("\u{A9}").accesskit_node().description().map(|d| d.to_string()).unwrap_or_default();
|
||||
assert!(desc.contains("COPYRIGHT SIGN"), "the tile's accessible description names the character, got {desc:?}");
|
||||
}
|
||||
|
||||
/// Characters outside the common list still say what they are: code point and block.
|
||||
#[test]
|
||||
fn symbol_tip_names_known_characters_and_falls_back_to_the_code_point() {
|
||||
use super::insert::symbol_tip;
|
||||
let named = symbol_tip("\u{A9}", "");
|
||||
assert!(named.contains("COPYRIGHT SIGN") && named.contains("00A9"), "named character: {named}");
|
||||
let with_font = symbol_tip("\u{3B1}", "Symbol");
|
||||
assert!(with_font.contains("GREEK SMALL LETTER ALPHA") && with_font.contains("03B1") && with_font.contains("Symbol"), "{with_font}");
|
||||
assert!(!named.contains("Symbol"), "no font, none named");
|
||||
let unnamed = symbol_tip("\u{2602}", "");
|
||||
assert!(unnamed.contains("2602") && unnamed.contains("Miscellaneous Symbols"), "unnamed character: {unnamed}");
|
||||
assert_eq!(symbol_tip("", ""), "");
|
||||
}
|
||||
|
||||
@@ -3393,6 +3393,28 @@ fn check_spelling_off_in_a_second_window_stays_off_in_every_window() {
|
||||
assert!(!b.session.view.proofing && !b.session.prefs.check_spelling, "saved off, whichever window was drawn");
|
||||
}
|
||||
|
||||
/// #7841: in dark mode the app draws its interface text with its own lighter curve, not egui's dark default, and
|
||||
/// light mode keeps egui's light one.
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn dark_interface_text_uses_the_app_s_lighter_curve() {
|
||||
let ctx = crate::test_harness::context();
|
||||
let mut a = app();
|
||||
let curve = |a: &mut WordApp, theme: theme::Appearance| {
|
||||
a.ui.theme = theme;
|
||||
for _ in 0..2 {
|
||||
crate::test_harness::pass(&ctx, a, egui::RawInput::default());
|
||||
}
|
||||
ctx.global_style().visuals.text_options.color_transfer_function
|
||||
};
|
||||
let dark = curve(&mut a, theme::Appearance::Dark);
|
||||
let light = curve(&mut a, theme::Appearance::Light);
|
||||
let lighter = egui::epaint::FontColorTransferFunction::Gamma(0.8);
|
||||
assert_eq!(dark, lighter, "dark mode draws with the app's curve");
|
||||
assert_eq!(light, egui::Visuals::light().text_options.color_transfer_function, "light mode keeps egui's");
|
||||
assert_eq!(curve(&mut a, theme::Appearance::Dark), lighter, "back to dark gets the app's curve again");
|
||||
}
|
||||
|
||||
/// #1861: the registered Interface Theme command drives the same setting as Options:
|
||||
/// searchable in the registry, settable, toggling without a value, and surviving a restart.
|
||||
#[test]
|
||||
|
||||
@@ -712,6 +712,16 @@ pub fn apply_animations(ctx: &egui::Context, on: bool) {
|
||||
/// Coverage exponent for light-on-dark interface text on Linux and the BSDs (see [`visuals`]).
|
||||
const DARK_TEXT_GAMMA: f32 = 0.8;
|
||||
|
||||
/// Gives egui's dark style our lighter light-on-dark text curve on Linux and the BSDs (see [`visuals`]). The craft
|
||||
/// runtime's mode sync keeps an app's own curve for each mode (craft-libs#3589), so setting it once is enough (#7841).
|
||||
pub fn set_dark_text_curve(ctx: &egui::Context) {
|
||||
if cfg!(all(unix, not(target_os = "macos"))) {
|
||||
ctx.style_mut_of(egui::Theme::Dark, |s| {
|
||||
s.visuals.text_options.color_transfer_function = egui::epaint::FontColorTransferFunction::Gamma(DARK_TEXT_GAMMA);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// egui's visuals for one of our palettes.
|
||||
fn visuals(t: &Tokens) -> Visuals {
|
||||
let mut v = if t.dark { Visuals::dark() } else { Visuals::light() };
|
||||
|
||||
File diff suppressed because one or more lines are too long
+2
-1
File diff suppressed because one or more lines are too long
@@ -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
@@ -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)
|
||||
|
||||
|
||||
+27
-20
@@ -2,30 +2,30 @@
|
||||
|
||||
> **Validation status:** 2026-11-12 · minor · #5875 round 18: package entry and availability lookups carry explicit absence/unknown states; the observation gate resolves bounded helper/accessor aliases and pins completeness predicates and reader derives. Qualified standard macros and four inert attributes are supported; named-field bindings and trait bodies remain closed grammar. Synthetic controls only; independent endpoint review remains required and readiness estimates are unchanged.
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged); previously minor (M15: Arabic mirrored UI #1195; 28 UI languages; Hebrew UI and native IME acceptance remain open); previously trivial (HTML import keeps preformatted lines with CR, CRLF or LF input newlines (#4810); numeric character references retain their separate meaning; readiness estimates unchanged; previously trivial: egui 0.37 migration: 27 interface languages remain pinned by `craft-i18n.rev` (9205108…), and the input-method handling has synthetic regressions while managed CI passed and native acceptance (#155–#164) remains open; previously trivial: M6: Manage Sources imports Word's `Sources.xml`, #2640; previously minor: Czech proofing review fixes; previously minor: Portuguese proofing; previously minor: Polish interface and Polish proofing; previously trivial: M7: formatting revisions landed, #41; previously trivial: M5: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: alpha gate checked: six core workflows pass; previously major: milestones moved here from ROADMAP.md; Current focus set from the re-measured gaps) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-11-28 · **Last updated:** 2026-11-28 · **Change:** minor (beta distance re-measured after the craft-ui port: ~175–275 h, was ~150–230 h; ready for real work ~63%, was ~60%; see [`target-app-parity.md`](target-app-parity.md)); previously minor (Roadmap and parity summary refreshed against the 28 Nov parity run (#7969): catalog coverage 510 / 522 (97.7%), measured counts redone, craft-ui port (#7101) and its tracker (#7671) recorded; readiness estimates unchanged); previously minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged); previously minor (M15: Arabic mirrored UI #1195; 28 UI languages; Hebrew UI and native IME acceptance remain open); previously trivial (HTML import keeps preformatted lines with CR, CRLF or LF input newlines (#4810); numeric character references retain their separate meaning; readiness estimates unchanged; previously trivial: egui 0.37 migration: 27 interface languages remain pinned by `craft-i18n.rev` (9205108…), and the input-method handling has synthetic regressions while managed CI passed and native acceptance (#155–#164) remains open; previously trivial: M6: Manage Sources imports Word's `Sources.xml`, #2640; previously minor: Czech proofing review fixes; previously minor: Portuguese proofing; previously minor: Polish interface and Polish proofing; previously trivial: M7: formatting revisions landed, #41; previously trivial: M5: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: alpha gate checked: six core workflows pass; previously major: milestones moved here from ROADMAP.md; Current focus set from the re-measured gaps) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
|
||||
Forward-looking plan. The summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is
|
||||
[`gaps.md`](gaps.md); the numbers are in [`target-app-parity.md`](target-app-parity.md). Hours are
|
||||
Opus 5.5 agent wall-clock.
|
||||
|
||||
## Current focus (toward beta, ~150–230 h)
|
||||
## Current focus (as of 2026-11-28)
|
||||
|
||||
1. **Merge or close the ~45 open PRs** before starting overlapping work: many close catalog gaps
|
||||
(Clipboard pane #264, Manage Styles #270, Group #267), fix field bugs (Hebrew RTL #20, IME
|
||||
fixes #155–#164) or add languages (nb, nn, he). Owner review needed.
|
||||
2. **DOCX real-world corpus** (gap #1, 30–50 h): collect openly licensed real-world .docx files,
|
||||
open/render/round-trip them, compare with Word locally, fix what breaks. Omitted/empty
|
||||
paragraph defaults now have synthetic save/reopen coverage; the corpus gate remains open.
|
||||
3. **Preserve what we can't render** (gap #2, 10–15 h): remaining native ink forms and unsupported
|
||||
graphics survive a round trip. Drawing-level native ink now keeps its InkML and optional picture
|
||||
fallback alongside chart, SmartArt, OLE and drawing-canvas support.
|
||||
4. **Stability sweep** (gap #3, 20–30 h): the open crash, hang and write-failure issues, plus an
|
||||
autosave/recovery soak test. Local desktop recovery is implemented; cross-platform field
|
||||
validation and longer soak testing remain. See [recovery.md](recovery.md).
|
||||
5. **Pagination fidelity** (gap #4, 30–50 h): column balancing, footnote continuation, compat
|
||||
options, a local page-by-page comparison harness; an owner decision on an Aptos-metric font.
|
||||
6. **Formatting revisions and content controls** (gap #5, 12–18 h), **native printing** (gap #6,
|
||||
6–10 h), **dialog depth** (gap #7, 20–30 h).
|
||||
The craft-ui port (#7101) landed, and v0.18.0, v0.18.1 and v0.19.1 are released. The port left
|
||||
regressions. Epic #7671 is the live tracker: 59 sub-issues, 14 closed. Order of work:
|
||||
|
||||
1. **Finish #7671.** First the two P0s: multi-window data loss (#7822, closing a window can close
|
||||
the wrong document and the save prompt can lock up) and screen readers (#7823). Then the 27 Nov
|
||||
comparison batch (#7970–#7989, #8017–#8022), which is in review.
|
||||
2. **One craft-libs repin PR.** craft-libs fixes now land on craft-libs `main`; `next` is gone.
|
||||
WordCraft gets them through a single `rev` move, then a small PR switches on the new options.
|
||||
3. **Then the beta gaps.** With #7671 (~25–45 h) they put beta ~175–275 h away (estimated,
|
||||
re-measured 2026-11-28 against main `6fbf780789`; ready for real work is ~63%, beta is ~75%):
|
||||
DOCX real-world corpus (gap #1), preserving unrendered content (gap #2), a stability sweep
|
||||
(gap #3), pagination fidelity (gap #4), formatting revisions and content controls (gap #5),
|
||||
print dialog depth (gap #6; native printing itself landed, #783) and dialog depth (gap #7). Details and hours are in
|
||||
[`gaps.md`](gaps.md).
|
||||
|
||||
Open PRs: 1,535 as of 2026-11-28 (`gh api search/issues` with `repo:storytold/wordcraft is:pr is:open`, `total_count`). Owner review is the bottleneck.
|
||||
|
||||
## Alpha gate (core workflows)
|
||||
|
||||
@@ -45,6 +45,11 @@ every day, checked end to end on the main platform (macOS desktop), including sa
|
||||
**Result: passes.** Every core workflow completes on macOS and the work saves and reopens; the
|
||||
partial rows are fidelity gaps (beta work), not broken workflows. WordCraft stays **alpha**.
|
||||
|
||||
**Not re-verified.** This table was checked before the craft-ui port (#7101). It has not been
|
||||
re-run on main. It needs re-checking after the P0s in #7671 are fixed. Multi-window risk (#7822):
|
||||
closing a window can close the wrong document, so the "Write and format" and "Share or print"
|
||||
rows (save, close, reopen) are at risk until it is fixed.
|
||||
|
||||
## Milestones
|
||||
|
||||
| # | Milestone | State | Remaining |
|
||||
@@ -63,8 +68,8 @@ partial rows are fidelity gaps (beta work), not broken workflows. WordCraft stay
|
||||
| M11 | Draw and objects | text wrap, text boxes, canvas handles, rotation (#332), ink pens and eraser (#307), contour wrap (#354), lasso, Add Pen, Ink to Shape and Ink Replay (#395) done; Ink to Math, grouping missing | 35–55 h |
|
||||
| M12 | Formats breadth (PDF, ODT, RTF, HTML, MD, TXT, LaTeX, `.doc` import) | done (first versions); `.doc` write, encryption, minor formats missing | 60–100 h |
|
||||
| M13 | Performance budgets | on track (1.4 ms relayout); large real-world documents unmeasured | 10–20 h |
|
||||
| M14 | 1.0 polish, packaging, signing | releases v0.1.0–v0.4.0 published (signed macOS, Windows MSI x64/x86/arm64, Linux, FreeBSD, web) | — |
|
||||
| M15 | Localization (12 key languages, RTL interface, proofing languages) | 28 UI languages from the shared catalogs pinned by `craft-i18n.rev` (Arabic mirrored UI #1195); proofing: English, Polish, Portuguese, Italian, Croatian, Turkish, Russian, Czech, Indonesian and Spanish, plus Bulgarian and German hyphenation only; Hebrew UI, native-speaker review and native IME acceptance (#155–#164) remain open | 55–95 h |
|
||||
| M14 | 1.0 polish, packaging, signing | releases v0.1.0–v0.19.1 published (latest v0.19.1, 2026-11-25; signed macOS, Windows MSI x64/x86/arm64, Linux, FreeBSD, web) | — |
|
||||
| M15 | Localization (12 key languages, RTL interface, proofing languages) | 36 locales with a `wordcraft.tsv` in the shared catalogs pinned by `craft-i18n.rev` (counted with `git ls-tree` at that rev, 2026-11-28; Arabic mirrored UI #1195); proofing: English, Polish, Portuguese, Italian, Croatian, Turkish, Russian, Czech, Indonesian and Spanish, plus Bulgarian and German hyphenation only; Hebrew UI, native-speaker review and native IME acceptance (#155–#164) remain open | 55–95 h |
|
||||
| M16 | Right-to-left and East Asian typography | RTL paragraphs done (#207) | 30–45 h |
|
||||
|
||||
## Next after beta
|
||||
@@ -76,6 +81,8 @@ languages, screen-reader access, ecosystem decisions (VBA, add-ins, cloud), an i
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-28 | minor | Current focus: beta distance re-measured after the craft-ui port, ~175–275 h (was ~150–230 h): the #7671 work (~25–45 h) added to the beta gaps; ready for real work ~63% (was ~60%) |
|
||||
| 2026-11-28 | minor | Current focus rewritten: craft-ui port (#7101) landed, epic #7671 first, then one craft-libs repin, then the beta gaps; open PR count restated (1,535); alpha gate marked not re-verified since the port; M14 releases and M15 locale count updated. Readiness estimates unchanged. |
|
||||
| 2026-11-12 | minor | #5875 round 18: package entry and availability lookups carry explicit absence/unknown states; the observation gate resolves bounded helper/accessor aliases and pins completeness predicates and reader derives. Qualified standard macros and four inert attributes are supported; named-field bindings and trait bodies remain closed grammar. Synthetic controls only; independent endpoint review remains required and readiness estimates are unchanged. |
|
||||
| 2026-11-03 | trivial | DOCX text-frame anchor locks survive JSON and two save/reopen cycles, including position and size edits |
|
||||
| 2026-11-03 | minor | M15: Arabic mirrored interface (#1195); 28 UI languages from craft-i18n; Hebrew UI, native-speaker review and native IME acceptance (#155–#164) remain open |
|
||||
|
||||
+97
-84
@@ -1,6 +1,6 @@
|
||||
# WordCraft parity with Microsoft Word
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** trivial (Proofing: freestanding custom dictionary file support, #5840; previously trivial: Equations: `\int` + Space leaves ∫ waiting for its limits, `_a^b` then Space builds them, and the operand typed next goes inside, observed in Word for Windows on #4938, #4917; no percentage change; previously trivial: Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Tables row: tables nest 18 deep at most, so a .json save reads back, #3618); previously trivial (Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-11-28 · **Last updated:** 2026-11-28 · **Change:** minor (Readiness estimates re-measured against main `6fbf780789` after the craft-ui port (#7101, #7671): full ~60% → ~63%, mainstream ~55% → ~56%, essentials ~63% → ~62%; feature-area and dimension scores re-scored with evidence); previously minor (Roadmap and parity summary refreshed against the 28 Nov parity run (#7969): catalog coverage 510 / 522 (97.7%), measured counts redone, craft-ui port (#7101) and its tracker (#7671) recorded; readiness estimates unchanged); previously trivial (Proofing: freestanding custom dictionary file support, #5840; previously trivial: Equations: `\int` + Space leaves ∫ waiting for its limits, `_a^b` then Space builds them, and the operand typed next goes inside, observed in Word for Windows on #4938, #4917; no percentage change; previously trivial: Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Tables row: tables nest 18 deep at most, so a .json save reads back, #3618); previously trivial (Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
|
||||
The authoritative assessment of how close WordCraft is to Microsoft Word. [`ROADMAP.md`](../ROADMAP.md)
|
||||
summarizes it; [`gaps.md`](gaps.md) itemizes every shortfall; the deep checklists are
|
||||
@@ -11,23 +11,25 @@ The generated ribbon checklist is [`parity-checklist.md`](parity-checklist.md).
|
||||
|
||||
Labels → New Document with one label per recipient continues across sheets for all selected recipients (#4880). The final sheet leaves unused labels blank; address mapping, fixed-text and single-label modes stay unchanged. This is label generation, not a new Update Labels or Finish & Merge template workflow. Readiness estimates are unchanged.
|
||||
|
||||
## Headline (2026-10-10, origin/main `a99dddc`, v0.4.0 + ~90 merged PRs)
|
||||
## Headline (2026-11-28, origin/main `6fbf780789`, v0.19.1 + later merges)
|
||||
|
||||
| Number | Value | Kind |
|
||||
|---|---|---|
|
||||
| Ribbon/menu catalog coverage | **487 / 502 (97.0%)** | **measured**: `cargo xtask parity` (re-derived this pass from `crates/engine/src/catalog.rs` against every `CommandSpec::new` id in the source; identical to the checked-in `parity-checklist.md`) |
|
||||
| Feature breadth (weighted, beyond the ribbon: dialog options, citation styles, proofing languages, chart types, UI languages) | **~80%** | estimated |
|
||||
| Feature depth (weighted by use, table below) | **~68%** | estimated |
|
||||
| **Ready for real work** (full target) | **~60%** (range 55–63%) | estimated: weighted sum over the dimension table ([By dimension](#by-dimension)) |
|
||||
| **Mainstream practitioner** | **~55%** | estimated, same method |
|
||||
| **Essentials user** | **~63%** | estimated, same method |
|
||||
| Remaining effort to beta | **~150–230 h** of Opus 5.5 agent wall-clock: the blocking beta list ([gaps.md](gaps.md) #1–#7), which lifts file formats, layout, stability and UI enough to reach ~75% | estimated |
|
||||
| Remaining effort to full parity with Word desktop | **~750–1,250 h** | estimated |
|
||||
| Commands | 431 engine commands (+ `ui.*` commands in the front end) | measured (source count) |
|
||||
| Tests | 852 `#[test]` functions + 10 `proptest!` blocks | measured (source count) |
|
||||
| Code | ~88,700 lines of Rust in 15 crates, 3 apps and xtask | measured (`wc -l`) |
|
||||
| Ribbon/menu catalog coverage | **510 / 522 (97.7%)** | **measured**: `cargo xtask parity`, as written to the checked-in [`parity-checklist.md`](parity-checklist.md) by #7969 (2026-11-28) |
|
||||
| Feature breadth (weighted, beyond the ribbon: dialog options, citation styles, proofing languages, chart types, UI languages) | **~85%** (was ~80%) | estimated: about 100 dialog names (was 16 modal dialogs), 28 interface languages (was 13), 10 built-in proofing languages (was 5) |
|
||||
| Feature depth (weighted by use, table below) | **~71%** (was ~68%) | estimated |
|
||||
| **Ready for real work** (full target) | **~63%** (range 58–66%; was ~60%) | estimated: weighted sum over the dimension table ([By dimension](#by-dimension)) |
|
||||
| **Mainstream practitioner** | **~56%** (was ~55%) | estimated, same method |
|
||||
| **Essentials user** | **~62%** (was ~63%) | estimated, same method |
|
||||
| Remaining effort to beta | **~175–275 h** of Opus 5.5 agent wall-clock (was ~150–230 h): finishing epic #7671 (~25–45 h) plus the blocking beta list ([gaps.md](gaps.md) #1–#7), which lifts file formats, layout, stability and UI enough to reach ~75% | estimated |
|
||||
| Remaining effort to full parity with Word desktop | **~775–1,300 h** (was ~750–1,250 h; #7671 added) | estimated |
|
||||
| Commands | 678 distinct engine command ids (+ `ui.*` commands in the front end) | measured (source count: unique ids in `CommandSpec::new("…"` under `crates/engine/src`) |
|
||||
| Tests | 5,826 `#[test]` functions + 9 `proptest!` lines | measured (source count: `grep` over `crates`, `apps`, `xtask`) |
|
||||
| Code | ~374,200 lines of Rust in 15 crates, 3 apps and xtask | measured (`wc -l` over every `.rs` file in `crates`, `apps`, `xtask`) |
|
||||
|
||||
**Stage: alpha.** All six core workflows pass the [alpha gate](roadmap.md#alpha-gate-core-workflows); see [`ROADMAP.md`](../ROADMAP.md) for why it isn't beta, and the distance.
|
||||
The percentage estimates in this table and below were re-measured 2026-11-28 against main `6fbf780789`, after the craft-ui port (#7101). Its regressions are tracked in epic #7671 (59 sub-issues, 14 closed). The re-measure used merged PRs since 2026-10-10, open bugs, the companion docs and #7671; nothing was compared against Word page by page. The hours were not re-priced area by area: they are the 2026-10-10 hours plus the #7671 work. The command, test and code counts were re-counted on 2026-11-28; the older numbers (431, 852, ~88,700) used the same kind of count and are out of date, though the earlier counting rules may have differed.
|
||||
|
||||
**Stage: alpha.** All six core workflows passed the [alpha gate](roadmap.md#alpha-gate-core-workflows) before the craft-ui port (not re-run since); see [`ROADMAP.md`](../ROADMAP.md) for why it isn't beta, and the distance.
|
||||
|
||||
## What we measured against
|
||||
|
||||
@@ -45,7 +47,7 @@ Labels → New Document with one label per recipient continues across sheets for
|
||||
and our knowledge of Word for Windows and Mac (Microsoft 365). Windows-only features (PDF Reflow
|
||||
open, Works/WordPerfect import) are counted, because a Word user on Windows expects them.
|
||||
- WordCraft as it is on origin/main today: source (catalog, command registry, readers/writers,
|
||||
layout), tests, the i18n catalogs, open issues (62 as of 2026-10-10) and open PRs (~45 as of 2026-10-10), git history.
|
||||
layout), tests, the i18n catalogs, open issues (2,275 as of 2026-11-28) and open PRs (1,535 as of 2026-11-28), git history.
|
||||
- **Not done this pass:** opening real-world .docx files in both apps and comparing pages. There is
|
||||
no real-world corpus in the repo (Word-produced files can't be committed), and the disk budget
|
||||
ruled out building. That comparison is the first gap in [`gaps.md`](gaps.md).
|
||||
@@ -56,33 +58,31 @@ Percent is depth and fidelity against Word, not presence. Weight is our estimate
|
||||
typical Word user's time spent in the area (sums to 100). Hours are Opus 5.5 agent wall-clock to
|
||||
full parity for the area.
|
||||
|
||||
| Area | Weight | Parity | Was (2026-10-06) | Hours | Evidence and what's missing |
|
||||
| Area | Weight | Parity | Was (2026-10-10) | Hours | Evidence and what's missing |
|
||||
|---|---|---|---|---|---|
|
||||
| Typing, selection, clipboard, undo, find/replace | 12 | 85% | 85% | 8–12 | Typing parity pinned by `tests/typing.rs` ([typing-parity.md](typing-parity.md)). Paste Special (#235), Advanced Find (#234) and Column Selection (#237) landed; Clipboard pane still missing (PR #264 open). |
|
||||
| Character and paragraph formatting | 11 | 82% | 85% | 8–12 | Nearly every property, Font/Paragraph dialogs, character border, Phonetic Guide (#288), Enclose Characters (#297). Kerning for fonts in the Font dialog. Missing: Asian Typography, ligature/stylistic-set options in the Font dialog's Advanced tab. |
|
||||
| Styles and themes | 8 | 74% | 75% | 8–12 | Gallery, pane, create/modify, style sets, themes. Style Inspector landed (#236). Missing: Manage Styles (#270 open), style separators, linked-style edge cases; Word ships 11 Quick Style sets plus dozens of themes, we ship our own smaller set. |
|
||||
| Lists | 6 | 78% | 75% | 5–8 | Bullets, numbering, multilevel, restart, `w:lvlOverride` levels (#134), Word's list AutoFormat and Enter/Backspace behaviour. Missing: Define New Multilevel List dialog depth, list styles, legal numbering edge cases. |
|
||||
| Tables | 8 | 76% | 72% | 10–16 | Merge/split, styles (cell text takes style formatting, #104), custom table styles saved in the .docx (#256), Word 2013 edge, floating tables, rows split across pages, sort, formula, cell gridlines (#243), Draw Table and Eraser (#303), tables nested 18 deep at most, so a .json save or AutoRecover snapshot reads back even with rich content in the deepest cell (#1596, #3618; the .docx reader and writer keep 24; Word has no limit). Cell Margins opens an editable dialog initialized from table defaults and preserves unchanged values (#1960). Missing: splitting or erasing around vertically merged cells, nested-table polish. Dragging column and row borders and the resize handle on the page (#217) and the column and row markers on the rulers (#700) landed, with Word's Ctrl, Alt, left-edge and selected-cells drags (#711), and so did selecting columns, rows and cells, the "+" insert buttons, the move handle and double-click AutoFit on the page, Select Column, and drags and Shift+arrows over cells selecting whole cells; right-clicking a cell offers the table's commands, following the selection as in Word (Delete Cells, Rows, Columns or Table, Merge and Split Cells, Distribute, AutoFit, Text Direction, Insert Caption…, Table Properties…); cell text direction landed (#245). |
|
||||
| Page layout and sections | 7 | 70% | 72% | 12–20 | Margins, size, columns, breaks, page borders, line numbers, vertical alignment, drop caps, hyphenation. Columns don't balance; RTL sections missing. Vertical sections (tbRl/btLr) landed (#491). Detail: [layout-parity.md](layout-parity.md). |
|
||||
| Headers, footers, page numbers, fields | 5 | 70% | 70% | 8–12 | First/even/odd, link to previous, TOC as an updatable field (#52), cross-references to real bookmarks (#227). Field coverage is a subset of Word's ~90 field codes; Field dialog missing. |
|
||||
| Footnotes and endnotes | 3 | 60% | 60% | 3–5 | Placed and editable, numbers from Word files (#103); long notes continue onto the next page under the continuation separator (#352). Footnote and Endnote dialog with options per section: below text, end of section, number format, start at, restart each section or page, custom mark, convert (#385). |
|
||||
| References (TOC, citations, bibliography, captions, index, TOA) | 5 | 65% | 60% | 12–20 | Working first versions, Zotero integration (#189), Zotero/Mendeley `ADDIN` fields round-trip. Caption, Index, Mark Entry, Custom TOC, Table of Figures and Create/Edit Source dialogs; updates honour the TOC (`\o \u \t \f \n \p \h`), table of figures (`\c \a \n \p`, any caption label, so a list of tables sits beside a list of figures; #3013), INDEX (`\c \e \h \r`), XE (`\b \i \t \r`) and SEQ/STYLEREF chapter switches (#402); Insert Caption… on the right-click menu of pictures, shapes, text boxes and charts (#1230). All 12 of Word's bibliography styles (APA, MLA, Chicago, IEEE, Harvard, ISO 690 author-date and numerical, Turabian, GB/T 7714, GOST name and title sort, SIST02; #383); bibliography sources saved in DOCX (#790). Manage Sources imports Word's bibliography file (`b:Sources`, `Sources.xml`, #2640). |
|
||||
| Review (proofing UI, comments, track changes, compare, protect) | 8 | 72% | 75% | 15–25 | Comment balloons, tracked insert/delete incl. paragraph marks (#244, #125), Compare / Combine with comparison settings (case, white space, formatting, tables, word or character level, #412), Restrict Editing pane with formatting and editing restrictions, exceptions for everyone and a password (#412). Formatting revisions (#41): kept in DOCX, recorded while tracking, accepted/rejected, "Formatted: …" balloons and change bars. Moves (#400): kept in DOCX, recorded on a tracked cut and paste, accepted/rejected at either end, green markup and "Moved from/to" balloons. Show revisions in balloons takes tracked deletions in the body out of the text into "Deleted: …" balloons (insertions stay inline, as in Word; deletions in headers, footers, notes and text boxes, and in print and PDF, stay inline). Missing: drag-and-drop moves, insert/delete balloons, Translate, Block Authors, modern comment threads/mentions. Lowered: these gaps are confirmed by source (no `rPrChange` anywhere). |
|
||||
| Proofing (spelling, grammar, thesaurus, languages) | 5 | 44% | (in Review) | 20–40 | English, Polish, Portuguese, Italian and Czech (system Hunspell, #1048), chosen per run from its language (`w:lang`): English word list (Moby plus our supplement of modern words such as "desktop", #520) and rule-based grammar; Polish against the installed Hunspell dictionary through a Hunspell-style affix engine, Polish grammar rules and TeX hyphenation patterns (2026-10-10); Portuguese (pt-BR) against the installed VERO Hunspell dictionary — the affix engine reads its `FLAG UTF-8` flags, continuation classes and forbidden spellings — with accent-first suggestions, conservative grammar rules and TeX patterns (2026-10-12); Italian (it-IT) against the installed Hunspell dictionary through the same affix engine, with accent-first suggestions and conservative grammar rules. Other languages are left unmarked. The custom dictionary persists across sessions (#40), and freestanding custom dictionary files (such as Microsoft Word's CUSTOM.DIC in UTF-16LE with BOM) can be selected in File › Options › Proofing (#5840). Word ships 120 proofing tools for ~50 languages plus Editor (style refinements, similarity). Issues #25, #40, #100. |
|
||||
| Mailings | 2 | 70% | 70% | 6–10 | Mail merge from CSV, fields, rules (IF, SKIPIF, NEXT, NEXTIF, evaluated alike in preview and merge), fields in headers/footers (one section per letter), preview, envelopes, labels. Select Recipients takes a typed list or CSV (#247); no Excel/Outlook/Contacts data sources, no email merge. |
|
||||
| Pictures, shapes, text boxes, WordArt | 6 | 60% | 60% | 20–30 | Insert, crop, recolour, styles, floating placement like Word (#136), wrap (square/top-bottom/behind/front), text boxes edit and overflow (#46), VML text boxes (#242), free rotation and flips with a rotation handle (#332), WordArt: text fill (solid, gradient, none), outline, shadow, glow and reflection with our own styles, and Transform warps along arch, circle, wave, slant, inflate/deflate, chevron and triangle (other presets kept and drawn flat), connectors (straight, elbow, curved, arrowheads) glued to shapes' connection sites and re-routed when those move (#416). Missing: tight/through contour wrap, rotated text-box text, group (#267 open), shape effects, WordArt 3-D/bevel and editing text in its bent form, connector routing around shapes, Drawing Canvas, Icons, online pictures, screenshot. |
|
||||
| Mailings | 2 | 70% | 70% | 6–10 | Mail merge from CSV, fields, rules (IF, SKIPIF, NEXT, NEXTIF, evaluated alike in preview and merge), fields in headers/footers (one section per letter), preview, envelopes, labels. Select Recipients takes a typed list, CSV (#247) or a sheet of an Excel (.xlsx/.xlsm) or OpenDocument (.ods) workbook, with Select Table to pick the sheet (#334); no Outlook/Contacts/Access data sources, no email merge. |
|
||||
| Pictures, shapes, text boxes, WordArt | 6 | 60% | 60% | 20–30 | Insert, crop, recolour, styles, floating placement like Word (#136), wrap (square/top-bottom/behind/front), text boxes edit and overflow (#46), VML text boxes (#242), free rotation and flips with a rotation handle (#332), text-box text direction (90°, 270°, stacked), Align Text and linked text boxes (#369), Icons: an original icon library drawn in code with a searchable picker, inserted as pictures and recoloured with Icon Color (#309), Drawing Canvas with Fit/Expand/Scale and DOCX `wpc:wpc` (#344; members edited by command, not yet dragged inside the canvas; the canvas rotates and flips as a whole). Missing: tight/through contour wrap, text in a freely rotated text box, group (#267 open), shape effects, WordArt, connectors, online pictures, screenshot. |
|
||||
| Equations | 1 | 75% | 20% (with Draw) | 4–8 | OMML read/write, OpenType MATH layout, in-place editor with an Equation tab (#191); typed `\int`, `\sum`… + Space wait for their limits (`_a^b`), any character that can't continue `\name` corrects it (`\int_0^1`), and an operator built without an operand takes the caret into it, as observed in Word for Windows on #4938 (#4917, `equation::tests::an_autocorrected_operator_waits_for_its_limits`). Missing: line breaking of long display equations, ink equations. |
|
||||
| Charts, SmartArt, Draw/ink, 3D models, icons | 4 | 3% | (20% with equations) | 70–110 | Icons landed (#309; an original library drawn in code). Draw: pens, pencil, highlighter, stroke eraser and Hide Ink (#307), ink saved as DrawingML freeforms; Lasso Select (move, recolour, delete), Add Pen gallery, Ink to Shape (line, arrow, rectangle, ellipse, triangle, polygon) and Ink Replay (#395); Ink to Math, pressure and Word's own InkML missing; charts: Insert › Chart makes column, bar (clustered and stacked), line, area, pie, doughnut and scatter charts with Chart Design (change type, Edit Data grid, title, legend, data labels) and saves them as real chart parts (#409); charts from Word are drawn (#292) and kept on save (#319) but stay read-only; SmartArt is drawn and kept (#292, #319); Insert › SmartArt (#497) creates and edits list, process, cycle, hierarchy, pyramid, radial, matrix and Venn graphics with our own layouts, a Text Pane and the SmartArt Design tab, saved as diagram parts with the drawing; SmartArt from other programs stays read-only. |
|
||||
| View (modes, zoom, panes, windows) | 3 | 72% | 70% | 6–10 | Print/web/draft/read/focus, dark page (#194), pages side by side when zoomed out (#251), navigation pane; Outline view with the Outlining tab: levels, promote/demote, moving with collapsed content, expand/collapse, Show Level, first line only, text formatting (#493). Switch Windows, Arrange All, View Side by Side and Synchronous Scrolling across the native windows (#322). Missing: Split, Master Document, Immersive Reader depth. |
|
||||
| Backstage, printing, options | 3 | 58% | 55% | 12–20 | New/Home pages (#254), save prompts (#151), web printing via the browser (#209). Desktop printing still goes through PDF; Options has a fraction of Word's panes. |
|
||||
| Right-to-left and complex scripts | 1 | 50% | 55% | 15–25 | UAX #9, Arabic shaping, RTL paragraphs (#207). No RTL sections/tables, kashida justification or mirrored UI; open bug reports (#215, #211, #199, #66, #63, #48, #19) need re-testing against #207. |
|
||||
| East Asian typography | 1 | 25% | not rated | 13–22 | IME input works (winit fixes pending, #155–#164). Vertical text in sections, text boxes and cells with upright ideographs (#491; no `vert` glyph alternates). Ruby/Phonetic Guide with DOCX round trip (#288); document grid (lines per page, characters per line, #391). Two lines in one and horizontal in vertical (`w:eastAsianLayout`) are kept on save but not laid out. No enclose characters, Asian line-break options. |
|
||||
| Accessibility | 1 | 50% | not rated | 10–18 | AccessKit enabled in eframe. Alt Text pane for pictures, shapes, text boxes, groups, charts and tables with Mark as decorative, all round-tripping in DOCX (#386). The Accessibility pane groups errors, warnings and tips with jump-to and one-click fixes; rules for alt text, heading order, header rows, blank table rows/columns, merged cells, low contrast (WCAG ratio), floating objects and blank paragraphs. Screen-reader access to the document canvas is still untested (#18); no reading-order tools. The document canvas describes its text, headings, lists, tables, links, pictures and caret to screen readers through AccessKit (#488); Windows Magnifier follows the caret, onto a new line too (#1119). |
|
||||
| Typing, selection, clipboard, undo, find/replace | 12 | 85% | 85% | 8–12 | Typing parity pinned by `tests/typing.rs` ([typing-parity.md](typing-parity.md)). Paste Special (#235), Advanced Find (#234) and Column Selection (#237) landed; Clipboard pane landed (#264). **2026-11-28:** Clipboard pane landed (#264, #323). Held at 85%: the port broke caret moves at 255-character runs (#7826) and PopClip copy and paste (#7712); pasting JPG pictures can freeze the UI (#7137). |
|
||||
| Character and paragraph formatting | 11 | 84% | 82% | 8–12 | Nearly every property, Font/Paragraph dialogs, character border, Phonetic Guide (#288), Enclose Characters (#297). Kerning for fonts in the Font dialog. Missing: stylistic-set options in the Font dialog's Advanced tab. **2026-11-28:** Up: OpenType ligatures from `w14:ligatures` (#2351) and the Asian Typography tab (#323) landed. |
|
||||
| Styles and themes | 8 | 77% | 74% | 8–12 | Gallery, pane, create/modify, style sets, themes. Style Inspector landed (#236). Missing: style separators, linked-style edge cases; Word ships 11 Quick Style sets plus dozens of themes, we ship our own smaller set. **2026-11-28:** Up: Manage Styles landed (#270, #323). Style separators still missing; the port changed the Styles gallery look (#7678, #7679). |
|
||||
| Lists | 6 | 78% | 78% | 5–8 | Bullets, numbering, multilevel, restart, `w:lvlOverride` levels (#134), Word's list AutoFormat and Enter/Backspace behaviour. Missing: Define New Multilevel List dialog depth, list styles, legal numbering edge cases. **2026-11-28:** No change: no landed work on the missing items found. |
|
||||
| Tables | 8 | 78% | 76% | 10–16 | Merge/split, styles (cell text takes style formatting, #104), custom table styles saved in the .docx (#256), Word 2013 edge, floating tables, rows split across pages, sort, formula, cell gridlines (#243), Draw Table and Eraser (#303), tables nested 18 deep at most, so a .json save or AutoRecover snapshot reads back even with rich content in the deepest cell (#1596, #3618; the .docx reader and writer keep 24; Word has no limit). Cell Margins opens an editable dialog initialized from table defaults and preserves unchanged values (#1960). Missing: splitting or erasing around vertically merged cells, nested-table polish. Dragging column and row borders and the resize handle on the page (#217) and the column and row markers on the rulers (#700) landed, with Word's Ctrl, Alt, left-edge and selected-cells drags (#711), and so did selecting columns, rows and cells, the "+" insert buttons, the move handle and double-click AutoFit on the page, Select Column, and drags and Shift+arrows over cells selecting whole cells; right-clicking a cell offers the table's commands, following the selection as in Word (Delete Cells, Rows, Columns or Table, Merge and Split Cells, Distribute, AutoFit, Text Direction, Insert Caption…, Table Properties…); cell text direction landed (#245). **2026-11-28:** Up: Split Cells on merged cells and Convert Text to Table dialogs (#2592, #2913), table paste into cells (#6742). Open: Convert Text to Table drops section breaks (#5548, critical). |
|
||||
| Page layout and sections | 7 | 74% | 70% | 12–20 | Margins, size, columns, breaks, page borders, line numbers, vertical alignment, drop caps, hyphenation. Vertical sections (tbRl/btLr) landed (#491). Detail: [layout-parity.md](layout-parity.md). **2026-11-28:** Up: newspaper columns balance (#353, #6821) and RTL sections landed (#362). |
|
||||
| Headers, footers, page numbers, fields | 5 | 74% | 70% | 8–12 | First/even/odd, link to previous, TOC as an updatable field (#52), cross-references to real bookmarks (#227). Field coverage is a subset of Word's ~90 field codes. **2026-11-28:** Up: field codes shown, edited, locked and stepped through (#349) and a Field dialog (#5062). |
|
||||
| Footnotes and endnotes | 3 | 60% | 60% | 3–5 | Placed and editable, numbers from Word files (#103); long notes continue onto the next page under the continuation separator (#352). Footnote and Endnote dialog with options per section: below text, end of section, number format, start at, restart each section or page, custom mark, convert (#385). **2026-11-28:** No change: small fixes only (#2647, #1663). |
|
||||
| References (TOC, citations, bibliography, captions, index, TOA) | 5 | 65% | 65% | 12–20 | Working first versions, Zotero integration (#189), Zotero/Mendeley `ADDIN` fields round-trip. Caption, Index, Mark Entry, Custom TOC, Table of Figures and Create/Edit Source dialogs; updates honour the TOC (`\o \u \t \f \n \p \h`), table of figures (`\c \a \n \p`, any caption label, so a list of tables sits beside a list of figures; #3013), INDEX (`\c \e \h \r`), XE (`\b \i \t \r`) and SEQ/STYLEREF chapter switches (#402); Insert Caption… on the right-click menu of pictures, shapes, text boxes and charts (#1230). All 12 of Word's bibliography styles (APA, MLA, Chicago, IEEE, Harvard, ISO 690 author-date and numerical, Turabian, GB/T 7714, GOST name and title sort, SIST02; #383); bibliography sources saved in DOCX (#790). Manage Sources imports Word's bibliography file (`b:Sources`, `Sources.xml`, #2640). **2026-11-28:** No change: inserting a citation mid-paragraph deletes the rest of it (#7045, critical, open). |
|
||||
| Review (proofing UI, comments, track changes, compare, protect) | 8 | 72% | 72% | 15–25 | Comment balloons, tracked insert/delete incl. paragraph marks (#244, #125), Compare / Combine with comparison settings (case, white space, formatting, tables, word or character level, #412), Restrict Editing pane with formatting and editing restrictions, exceptions for everyone and a password (#412). Formatting revisions (#41): kept in DOCX, recorded while tracking, accepted/rejected, "Formatted: …" balloons and change bars. Moves (#400): kept in DOCX, recorded on a tracked cut and paste, accepted/rejected at either end, green markup and "Moved from/to" balloons. Show revisions in balloons takes tracked deletions in the body out of the text into "Deleted: …" balloons (insertions stay inline, as in Word; deletions in headers, footers, notes and text boxes, and in print and PDF, stay inline). Missing: drag-and-drop moves, insert/delete balloons, Translate, Block Authors, modern comment threads/mentions. Lowered: these gaps are confirmed by source (no `rPrChange` anywhere). **2026-11-28:** No change: Compare still loses content in several cases (#6273, #5571, #3749, open). |
|
||||
| Proofing (spelling, grammar, thesaurus, languages) | 5 | 52% | 44% | 20–40 | English, Polish, Portuguese, Italian and Czech (system Hunspell, #1048), chosen per run from its language (`w:lang`): English word list (Moby plus our supplement of modern words such as "desktop", #520) and rule-based grammar; Polish against the installed Hunspell dictionary through a Hunspell-style affix engine, Polish grammar rules and TeX hyphenation patterns (2026-10-10); Portuguese (pt-BR) against the installed VERO Hunspell dictionary — the affix engine reads its `FLAG UTF-8` flags, continuation classes and forbidden spellings — with accent-first suggestions, conservative grammar rules and TeX patterns (2026-10-12); Italian (it-IT) against the installed Hunspell dictionary through the same affix engine, with accent-first suggestions and conservative grammar rules. Other languages are left unmarked. The custom dictionary persists across sessions (#40), and freestanding custom dictionary files (such as Microsoft Word's CUSTOM.DIC in UTF-16LE with BOM) can be selected in File › Options › Proofing (#5840). Word ships 120 proofing tools for ~50 languages plus Editor (style refinements, similarity). Issues #25, #40, #100. **2026-11-28:** Up: 10 built-in proofing languages (was 5; [gaps.md](gaps.md) #8) and Language packs in Options (#5208, #5515). Still far from Word's ~50. |
|
||||
| Mailings | 2 | 70% | 70% | 6–10 | Mail merge from CSV, fields, rules (IF, SKIPIF, NEXT, NEXTIF, evaluated alike in preview and merge), fields in headers/footers (one section per letter), preview, envelopes, labels. Select Recipients takes a typed list, CSV (#247) or a sheet of an Excel (.xlsx/.xlsm) or OpenDocument (.ods) workbook, with Select Table to pick the sheet (#334); no Outlook/Contacts/Access data sources, no email merge. **2026-11-28:** No change: no new data sources landed. |
|
||||
| Pictures, shapes, text boxes, WordArt | 6 | 64% | 60% | 20–30 | Insert, crop, recolour, styles, floating placement like Word (#136), wrap (square/top-bottom/behind/front), text boxes edit and overflow (#46), VML text boxes (#242), free rotation and flips with a rotation handle (#332), text-box text direction (90°, 270°, stacked), Align Text and linked text boxes (#369), Icons: an original icon library drawn in code with a searchable picker, inserted as pictures and recoloured with Icon Color (#309), Drawing Canvas with Fit/Expand/Scale and DOCX `wpc:wpc` (#344; members edited by command, not yet dragged inside the canvas; the canvas rotates and flips as a whole). Missing: text in a freely rotated text box, shape effects, WordArt, connectors, online pictures, screenshot. **2026-11-28:** Up: Group (#267, #323) and Tight/Through contour wrap (#354) landed; Format Shape pane gained Line and Layout sections (#5896). |
|
||||
| Equations | 1 | 78% | 75% | 4–8 | OMML read/write, OpenType MATH layout, in-place editor with an Equation tab (#191); typed `\int`, `\sum`… + Space wait for their limits (`_a^b`), any character that can't continue `\name` corrects it (`\int_0^1`), and an operator built without an operand takes the caret into it, as observed in Word for Windows on #4938 (#4917, `equation::tests::an_autocorrected_operator_waits_for_its_limits`). Missing: ink equations. **2026-11-28:** Up: long display equations wrap at operators (#326). The port broke the Equation tab galleries (#7975). |
|
||||
| Charts, SmartArt, Draw/ink, 3D models, icons | 4 | 30% | 3% | 70–110 | Icons landed (#309; an original library drawn in code). Draw: pens, pencil, highlighter, stroke eraser and Hide Ink (#307), ink saved as DrawingML freeforms; Lasso Select (move, recolour, delete), Add Pen gallery, Ink to Shape (line, arrow, rectangle, ellipse, triangle, polygon) and Ink Replay (#395); Ink to Math, pressure and Word's own InkML missing; charts: Insert › Chart makes column, bar (clustered and stacked), line, area, pie, doughnut and scatter charts with Chart Design (change type, Edit Data grid, title, legend, data labels) and saves them as real chart parts (#409); charts from Word are drawn (#292) and kept on save (#319) but stay read-only; SmartArt is drawn and kept (#292, #319); Insert › SmartArt (#497) creates and edits list, process, cycle, hierarchy, pyramid, radial, matrix and Venn graphics with our own layouts, a Text Pane and the SmartArt Design tab, saved as diagram parts with the drawing; SmartArt from other programs stays read-only. **2026-11-28:** Re-scored from 3%, which predates Insert › Chart (#409) and Insert › SmartArt (#497): WordCraft's own charts and SmartArt are editable, Word's are drawn and kept (#292, #319) but read-only. The port broke the Insert Diagram dialog and Diagram Design tab (#7973, #7974). |
|
||||
| View (modes, zoom, panes, windows) | 3 | 70% | 72% | 6–10 | Print/web/draft/read/focus, dark page (#194), pages side by side when zoomed out (#251), navigation pane; Outline view with the Outlining tab: levels, promote/demote, moving with collapsed content, expand/collapse, Show Level, first line only, text formatting (#493). Switch Windows, Arrange All, View Side by Side and Synchronous Scrolling across the native windows (#322). Missing: Split, Master Document, Immersive Reader depth. **2026-11-28:** Down: port regressions in the View tab and Read Mode (#7985, #7988, #8019, #8020); #7988 fixed by #8025. |
|
||||
| Backstage, printing, options | 3 | 64% | 58% | 12–20 | New/Home pages (#254), save prompts (#151), web printing via the browser (#209). Desktop printing still goes through PDF; Options has a fraction of Word's panes. **2026-11-28:** Up: native printing through craft-print (#783) with N-up, booklets and scale to paper (#641, #2108), and Word's Options panes (#492). Port regressions in File › Options and the File menu (#7987, #8018, #8022). |
|
||||
| Right-to-left and complex scripts | 1 | 58% | 50% | 15–25 | UAX #9, Arabic shaping, RTL paragraphs (#207). No kashida justification; open bug reports (#215, #211, #199, #66, #63, #48, #19) need re-testing against #207. **2026-11-28:** Up: RTL tables and sections (#362), letters join across formatting (#4093), Hebrew and Arabic copy from PDF as words (#1383), Arabic interface mirrored. Kashida still missing; #199 and #66 open; screen readers get wrong RTL positions since the port (#7823). |
|
||||
| East Asian typography | 1 | 35% | 25% | 13–22 | IME input works (winit fixes pending, #155–#164). Vertical text in sections, text boxes and cells with upright ideographs (#491; no `vert` glyph alternates). Ruby/Phonetic Guide with DOCX round trip (#288); document grid (lines per page, characters per line, #391). Two lines in one and horizontal in vertical (`w:eastAsianLayout`) are kept on save but not laid out. No enclose characters, Asian line-break options. **2026-11-28:** Up: Asian Typography tab (#323), automatic Asian/Latin spacing laid out (#2358), Enclose Characters (#297). |
|
||||
| Accessibility | 1 | 45% | 50% | 10–18 | AccessKit enabled in eframe. Alt Text pane for pictures, shapes, text boxes, groups, charts and tables with Mark as decorative, all round-tripping in DOCX (#386). The Accessibility pane groups errors, warnings and tips with jump-to and one-click fixes; rules for alt text, heading order, header rows, blank table rows/columns, merged cells, low contrast (WCAG ratio), floating objects and blank paragraphs. Screen-reader access to the document canvas is still untested (#18); no reading-order tools. The document canvas describes its text, headings, lists, tables, links, pictures and caret to screen readers through AccessKit (#488); Windows Magnifier follows the caret, onto a new line too (#1119). **2026-11-28:** Down: since the port, screen readers get wrong positions for right-to-left and vertical text (#7823, P0); a macOS accessibility client can freeze the UI (#6893). |
|
||||
| Agent control (CLI, MCP, control channel, macro record/playback) | 0 | beyond Word | 100%+ | — | Every action is a command id usable from CLI, MCP and a keyed control port. Word has VBA and Office.js instead (see Ecosystem). |
|
||||
|
||||
Weighted feature depth: **~68%** (Σ weight × parity / 100 over the table).
|
||||
Weighted feature depth: **~71%** (was ~68%; Σ weight × parity / 100 over the table): (12·85 + 11·84 + 8·77 + 6·78 + 8·78 + 7·74 + 5·74 + 3·60 + 5·65 + 8·72 + 5·52 + 2·70 + 6·64 + 1·78 + 4·30 + 3·70 + 3·64 + 1·58 + 1·35 + 1·45) / 100 = 71.4. The Mailings and Pictures rows were listed twice; the older copy of each was removed. Neither sum counted the copies.
|
||||
|
||||
## Readiness numbers: full, mainstream practitioner, essentials user
|
||||
|
||||
@@ -93,33 +93,38 @@ what still stops real work. The stage follows the full number and the core-workf
|
||||
|
||||
| Audience | Ready | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates |
|
||||
|---|---|---|---|
|
||||
| Full target (ready for real work) | **~60%** | **~650–1,100 h** (70–80% parallelizes) | Breadth: charts/SmartArt/Draw, localization and proofing languages, East Asian and RTL typography, `.doc` writing, PDF Reflow, ecosystem; plus everything below |
|
||||
| Mainstream practitioner | **~55%** | **~300–500 h** (~65% parallelizes) | DOCX real-world fidelity and preserving charts/SmartArt, pagination fidelity, formatting revisions, dialog depth, objects, stability |
|
||||
| Essentials user | **~63%** | **~90–140 h** (~50% parallelizes) | Install/launch stability, opening files people send (corpus subset, chart fallbacks), native printing, picture handling, English spelling depth |
|
||||
| Full target (ready for real work) | **~63%** (was ~60%) | **~675–1,150 h** (70–80% parallelizes) | Breadth: charts/SmartArt/Draw, localization and proofing languages, East Asian and RTL typography, `.doc` writing, PDF Reflow, ecosystem; plus everything below |
|
||||
| Mainstream practitioner | **~56%** (was ~55%) | **~325–550 h** (~65% parallelizes) | Finishing #7671 (multi-window data loss #7822 first), DOCX real-world fidelity and preserving charts/SmartArt, pagination fidelity, formatting revisions, dialog depth, objects, stability |
|
||||
| Essentials user | **~62%** (was ~63%) | **~105–165 h** (~50% parallelizes) | The #7671 regressions an essentials user meets (#7822, idle CPU #7674, dialog labels #7976), install/launch stability, opening files people send (corpus subset, chart fallbacks), native printing, picture handling, English spelling depth |
|
||||
|
||||
Hours are calibrated as in [Calibration](#calibration-of-hours-from-this-repos-history) and are
|
||||
subsets: essentials ⊂ mainstream ⊂ full. Mainstream to ~95%: its areas' depth (~180–280 h) plus
|
||||
the file-exchange, stability and interaction work behind the discounts (~135–225 h). Essentials to
|
||||
~95%: launch/install stability (15–25 h), opening received files (30–50 h), native printing (6–10
|
||||
h), pictures and tables (12–18 h), spelling depth (8–12 h), polish (10–20 h).
|
||||
2026-11-28: each audience's hours are the 2026-10-10 hours plus the #7671 work it meets (full and
|
||||
mainstream ~25–45 h, essentials ~15–25 h). The areas were not re-priced one by one, so work done
|
||||
since 2026-10-10 (native printing, column balancing) is not yet taken off.
|
||||
|
||||
### The discounts (evidence)
|
||||
|
||||
| Discount | Mainstream | Essentials | Evidence |
|
||||
|---|---|---|---|
|
||||
| Interaction fidelity | ×0.93 | — | Typing pinned to Word (`tests/typing.rs`), ribbon, keytips, mini-toolbar; but 16 modal dialogs against Word's ~100, 125 of ~250 shortcuts, picture/shape handling complaints (#82, #142), lines wrap differently without an Aptos-metric font |
|
||||
| Discoverability and UI clarity | — | ×0.95 | Word-style ribbon a Word user already knows, command search, keytips; some newer pane strings and tooltips terse or untranslated |
|
||||
| Stability on real machines | ×0.90 | ×0.90 (launch and install) | Never-crash standard, hostile-param fuzzing, panic guard; but open startup crash on Intel UHD (#170), freezes (#77, #59, #31), Windows writes fail without admin (#218), installer conflicts with other Crafting Apps (#64, #73, #106, #51); 5 days of field history |
|
||||
| Exchanging files with Word users | ×0.90 | ×0.92 (opening files people send) | Word opens our .docx; `.doc` import; but no real-world corpus test, charts/SmartArt/OLE dropped silently, pagination differs (Aptos, no column balancing or footnote continuation). Simple documents, which are most of what a casual user receives, come through well; double-click open on macOS is fixed on main but not yet released (#223, #279) |
|
||||
| Product | **×0.753** | **×0.787** | |
|
||||
| Interaction fidelity | ×0.93 | — | Typing pinned to Word (`tests/typing.rs`), ribbon, keytips, mini-toolbar; about 100 dialog names (`dialogs::route`, was 16 modal dialogs), 140 (macOS) / 158 (Linux, Windows) of Word's ~250 shortcuts ([gaps.md](gaps.md) #24), picture and shape complaints closed (#82, #142). Held at ×0.93, not raised, because of port regressions: caret moves stop at 255-character runs (#7826), Customize Keyboard can't assign a shortcut (#7971), dialog labels missing or clipped (#7976, #7982) |
|
||||
| Discoverability and UI clarity | — | ×0.93 (was ×0.95) | Word-style ribbon a Word user already knows, command search, keytips; but since the port the View tab lost group labels (#7985), command search lost locations and shortcuts (#7983), disabled buttons are unreadable (#7978) and disabled-reason tooltips are gone (#7824) |
|
||||
| Stability on real machines | ×0.87 (was ×0.90) | ×0.90 (launch and install) | Never-crash standard, hostile-param fuzzing, panic guard; old freezes and install conflicts closed (#77, #59, #31, #218, #64, #73, #106, #51). But the port added multi-window data loss (#7822, P0) and ~85% idle CPU (#7674); open: closing or crashing with a second document (#5809, #5563), Windows freezes (#6104, #5801), GPU-reset panic (#7187), startup failures (#170, #6031, #5363, #7096) and data-loss bugs (#7045, #7069, #5548). Launch and install held: old failures closed, new ones opened |
|
||||
| Exchanging files with Word users | ×0.92 (was ×0.90) | ×0.92 (opening files people send) | Word opens our .docx; `.doc` import; charts, SmartArt and OLE now kept on save (#319), encrypted files open (#55), double-click open on macOS released (#223). Still no real-world corpus test; DOCX drops modern charts with a text fallback (#7238); legacy `.doc` import loses table merges, padding and alignment (#7300–#7306), which holds essentials at ×0.92 |
|
||||
| Product | **×0.744** (0.93 × 0.87 × 0.92; was ×0.753) | **×0.770** (0.93 × 0.90 × 0.92; was ×0.787) | |
|
||||
|
||||
### Full target (ready for real work): ~60%
|
||||
### Full target (ready for real work): ~63%
|
||||
|
||||
The additive weighted sum over the [dimension table](#by-dimension): **0.30·68 + 0.20·60 + 0.15·55 +
|
||||
0.10·65 + 0.10·50 + 0.05·75 + 0.04·25 + 0.03·95 + 0.01·40 + 0.02·15 ≈ 60%** (range 55–63%). No
|
||||
The additive weighted sum over the [dimension table](#by-dimension): **0.30·71 + 0.20·65 + 0.15·60 +
|
||||
0.10·62 + 0.10·45 + 0.05·70 + 0.04·45 + 0.03·95 + 0.01·45 + 0.02·15 = 62.9 ≈ 63%** (range 58–66%).
|
||||
Was 0.30·68 + 0.20·60 + 0.15·55 + 0.10·65 + 0.10·50 + 0.05·75 + 0.04·27 + 0.03·95 + 0.01·40 +
|
||||
0.02·15 = 60.5 (the old formula wrote 25 for Localization; the table said 27). No
|
||||
multiplicative discounts: stability, file formats, layout and UI are weighted dimensions here.
|
||||
|
||||
### Mainstream practitioner: ~55%
|
||||
### Mainstream practitioner: ~56%
|
||||
|
||||
The typical professional Word user (office, legal, academic, writing) in their own language, weekly
|
||||
work only. Left out: equations, mail merge, Draw/ink, East Asian and right-to-left typography,
|
||||
@@ -129,24 +134,24 @@ dictation and pens.
|
||||
| Area | Weight | Depth |
|
||||
|---|---|---|
|
||||
| Typing, selection, clipboard, undo, find/replace | 17 | 85% |
|
||||
| Character and paragraph formatting | 16 | 82% |
|
||||
| Styles | 9 | 74% |
|
||||
| Tables | 9 | 76% |
|
||||
| Character and paragraph formatting | 16 | 84% (was 82%) |
|
||||
| Styles | 9 | 77% (was 74%) |
|
||||
| Tables | 9 | 78% (was 76%) |
|
||||
| Review (comments, track changes) | 9 | 72% |
|
||||
| Lists | 8 | 78% |
|
||||
| Page layout and sections | 6 | 70% |
|
||||
| Headers, footers, page numbers, fields | 5 | 70% |
|
||||
| Proofing in the user's language (English) | 5 | 55% |
|
||||
| Pictures, shapes, text boxes | 5 | 60% |
|
||||
| Page layout and sections | 6 | 74% (was 70%) |
|
||||
| Headers, footers, page numbers, fields | 5 | 74% (was 70%) |
|
||||
| Proofing in the user's language (English) | 5 | 60% (was 55%) |
|
||||
| Pictures, shapes, text boxes | 5 | 64% (was 60%) |
|
||||
| References (TOC, captions, citations) | 4 | 65% |
|
||||
| Footnotes | 2 | 60% |
|
||||
| Charts and SmartArt (pasted from Excel or received) | 2 | 3% |
|
||||
| Print and PDF | 2 | 65% |
|
||||
| View | 1 | 72% |
|
||||
| Charts and SmartArt (pasted from Excel or received) | 2 | 25% (was 3%) |
|
||||
| Print and PDF | 2 | 72% (was 65%) |
|
||||
| View | 1 | 70% (was 72%) |
|
||||
|
||||
Base ≈ **73%**; **73% × 0.753 ≈ 55%**.
|
||||
Base ≈ **75%** (75.3; was 73.1); **75.3% × 0.744 = 56.0 ≈ 56%**. English proofing: American, British and Canadian spelling each against its own word list ([gaps.md](gaps.md) #8). Received charts are drawn and kept (#292, #319) but read-only. Print and PDF: native printing (#783, #641).
|
||||
|
||||
### Essentials user: ~63%
|
||||
### Essentials user: ~62%
|
||||
|
||||
Someone who uses only the core of Word: create or open a document, type and format it, a list, a
|
||||
picture, a simple table, spelling, undo, save, PDF or print, default settings. Advanced options,
|
||||
@@ -157,18 +162,18 @@ mainstream.
|
||||
|---|---|---|
|
||||
| Typing, selection, copy/paste, undo | 20 | 85% |
|
||||
| Font, size, bold/italic/underline, colour, highlight | 15 | 88% |
|
||||
| New, open, save, AutoSave, templates | 12 | 80% |
|
||||
| New, open, save, AutoSave, templates | 12 | 78% (was 80%) |
|
||||
| Alignment, line spacing, indents | 8 | 85% |
|
||||
| Bullets and numbering | 8 | 85% |
|
||||
| Spelling (English) | 8 | 65% |
|
||||
| Insert, move and resize a picture | 7 | 65% |
|
||||
| Simple table | 6 | 78% |
|
||||
| Spelling (English) | 8 | 68% (was 65%) |
|
||||
| Insert, move and resize a picture | 7 | 68% (was 65%) |
|
||||
| Simple table | 6 | 80% (was 78%) |
|
||||
| Heading styles from the gallery | 5 | 78% |
|
||||
| Print and export PDF | 5 | 70% |
|
||||
| Print and export PDF | 5 | 78% (was 70%) |
|
||||
| Find and replace | 3 | 85% |
|
||||
| Page numbers and a simple header | 3 | 75% |
|
||||
|
||||
Base ≈ **80%**; **80% × 0.787 ≈ 63%**.
|
||||
Base ≈ **81%** (80.8; was 80.0); **80.8% × 0.770 = 62.2 ≈ 62%**. Open and save down for multi-window data loss (#7822) and recent documents that don't open on Linux (#7322); pictures up as #82 and #142 closed; print up for native printing (#783).
|
||||
|
||||
### User evidence (GitHub, 2026-10-10; no issue was filed by a storytold org member)
|
||||
|
||||
@@ -189,22 +194,22 @@ Base ≈ **80%**; **80% × 0.787 ≈ 63%**.
|
||||
Weights are our estimate of how much each dimension decides whether a professional can switch from
|
||||
Word. Their weighted sum is the **full ready for real work** number.
|
||||
|
||||
| Dimension | Weight | Parity | Hours to full | Doc | Evidence |
|
||||
|---|---|---|---|---|---|
|
||||
| Features (depth, table above) | 30% | 68% | 210–335 | this file | Weighted table above. Hours: the area table sums to 290–460 h; the Page layout, Footnotes, RTL and East Asian rows (~50–85 h) are counted under Layout and the Proofing row (25–45 h) under Localization, so they aren't counted twice |
|
||||
| File formats (DOCX fidelity first) | 20% | 60% | 185–300 | [file-format-parity.md](file-format-parity.md) | DOCX opens in Word and round-trips our own tests, but no real-world corpus test yet; charts, SmartArt, OLE and encrypted files are lost or refused (content controls kept since #381) |
|
||||
| Layout and pagination fidelity | 15% | 55% | 90–145 | [layout-parity.md](layout-parity.md) | Aptos has no metric-matched substitute so lines break differently from Word; no column balancing, footnote continuation or document grid; compatibility modes beyond 15 partial |
|
||||
| UI/UX fidelity | 10% | 65% | 65–100 | [ui-parity.md](ui-parity.md) | Ribbon, keytips, mini-toolbar, Backstage, 125 shortcuts; 16 modal dialogs against Word's ~100; no ribbon/keyboard customization |
|
||||
| Stability | 10% | 50% | 25–45 | [gaps.md](gaps.md) | Never-crash standard and hostile-param fuzzing in place, but open reports of a startup crash on Intel UHD (#170), freezes (#77, #59, #31) and Windows write failure without admin (#218); local desktop recovery with focused lifecycle tests, but no longer soak test; 5 days of field history |
|
||||
| Performance | 5% | 75% | 10–20 | [layout-parity.md](layout-parity.md) | 61 ms cold layout and 1.4 ms relayout on a 188-page document (measured 2026-10-06, not re-run); font picker freezes fixed in #233; typing no longer starts and stops render threads on every repaint (#3027); no large real-world documents measured |
|
||||
| Localization | 4% | 27% | 75–120 + native review | [localization-parity.md](localization-parity.md) | 13 UI languages (Word 30); 4 of the 12 key languages partly done; English and Polish proofing |
|
||||
| Platforms | 3% | 95% | 5–10 | [ROADMAP.md](../ROADMAP.md) | macOS (universal, signed), Windows x64/x86/arm64, Linux (AppImage/deb/rpm/Flatpak), FreeBSD, web. Beyond Word on Linux, BSD and the web; Word's iPad/iPhone/Android apps are out of scope |
|
||||
| Hardware | 1% | 40% | 20–40 | [hardware-parity.md](hardware-parity.md) | No native printing on desktop, no pen/ink, no dictation; GPU drawing and HiDPI fine. Ink hours are in the Features row (Draw tab) |
|
||||
| Ecosystem and plugins | 2% | 15% | 40–80 | [gaps.md](gaps.md) | Zotero built in, macros record/play commands, `.docm` macros preserved (#172). No VBA execution, no Office add-ins, no EndNote/Mendeley plugins, no cloud storage or co-authoring |
|
||||
| AI features | 0% | 40% | 15–30 | [gaps.md](gaps.md) | Beyond Word for external agents (MCP, CLI). No in-app writing assistant like Copilot yet (chat PR #178 open). Weight 0: Copilot is a paid add-on and not what decides a switch |
|
||||
| Dimension | Weight | Parity | Was (2026-10-10) | Hours to full | Doc | Evidence |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Features (depth, table above) | 30% | 71% | 68% | 200–325 (was written 210–335; corrected from the rows) | this file | Weighted table above. Up: Field dialog, column balancing, Group, contour wrap, native printing, 10 proofing languages, Insert › Chart and SmartArt re-scored (#349, #353, #267, #354, #783, #409, #497); down for port regressions in View, Accessibility and Equation galleries (#7985, #7823, #7975). Hours: the area table sums to 265–435 h; the Page layout, Footnotes, RTL and East Asian rows (43–72 h) are counted under Layout and the Proofing row (20–40 h) under Localization, so they aren't counted twice |
|
||||
| File formats (DOCX fidelity first) | 20% | 65% | 60% | 185–300 | [file-format-parity.md](file-format-parity.md) | Up: charts, SmartArt and OLE kept on save (#319), encrypted packages open and save (#55, #281), Word 2003 XML opens and saves (#548, #1081), content controls kept (#381), a structural `.docx` checker (#5875). Still no real-world corpus test (gap #1); open critical file bugs: modern charts dropped with a text fallback (#7238), Word 2010 number formats lost (#5318), Compare drops the comments part (#6273); legacy `.doc` table import losses (#7300–#7306) |
|
||||
| Layout and pagination fidelity | 15% | 60% | 55% | 90–145 | [layout-parity.md](layout-parity.md) | Up: all three missing items named here landed: column balancing (#353, #6821), footnote continuation (#352) and the document grid (#391); RTL sections (#362). Still: Aptos has no metric-matched substitute, so lines break differently from Word; no page-by-page comparison with Word; compatibility modes beyond 15 partial ([gaps.md](gaps.md) #4) |
|
||||
| UI/UX fidelity | 10% | 62% | 65% | 65–100 + #7671 | [ui-parity.md](ui-parity.md) | Before the port it rose: about 100 dialog names (was 16), 140/158 shortcuts (was 125), Customize Keyboard and Customize Ribbon/Quick Access (#368, #379). The port took more back: 45 of #7671's 59 sub-issues are open, among them Customize Keyboard can't assign a shortcut (#7971), dialog labels missing or text clipped (#7976, #7982), previews shrunk (#7977), unreadable disabled buttons (#7978) and the ribbon 12 px short (#7680); #8025 and #8031 fixed #7988 and #7970 |
|
||||
| Stability | 10% | 45% | 50% | 25–45 + #7671 P0s | [gaps.md](gaps.md) | Down: the port added multi-window data loss (#7822, P0). Open: closing or crashing with a second document (#5809, #5563), Windows freezes (#6104, #5801), a GPU-reset panic (#7187), startup failures (#170, #6031, #5363, #7096), data-loss bugs (#7045, #7069, #5548); 47 open issues marked critical. Old freezes and the no-admin write failure are closed (#77, #59, #31, #218). Seven weeks of field history now, not 5 days |
|
||||
| Performance | 5% | 70% | 75% | 10–20 | [layout-parity.md](layout-parity.md) | Down: since the port the app uses ~85% CPU while idle (#7674; #7719 merged, #7881, #7882, #7912, #7913 in review); starting a new document lagged 20+ s in v0.18.1 (#7688). 61 ms cold layout and 1.4 ms relayout on a 188-page document (measured 2026-10-06, not re-run: no bench for it); scrolling a 1,096-page one-table document ~2–5 ms a frame (#811); no large real-world documents measured |
|
||||
| Localization | 4% | 45% | 27% | 75–120 + native review | [localization-parity.md](localization-parity.md) | Up. Measured at the `craft-i18n.rev` pin (`e56d262`): 36 locales have a non-empty `wordcraft.tsv`, and 28 of them are in the app's language list (English makes 29; Word has 30; was 13). `cargo xtask i18n-report`'s check, run on this branch, finds 510–595 strings missing in 19 of them and 841–934 in nine (de, et, ja, pt-br, sr, sr-latn, uk, zh-hans, zh-hant). Set against each catalog's translated rows, that is ~80–84% and ~70–73% complete; that's an upper bound, as some rows may be stale. The report prints no English total. No catalog has had a native-speaker review. Proofing: 10 built-in languages against Word's ~50 ([gaps.md](gaps.md) #8). The 8 other catalogs (bn, fa, he, id, ka, lv, nb, sk) aren't offered yet |
|
||||
| Platforms | 3% | 95% | 95% | 5–10 | [ROADMAP.md](../ROADMAP.md) | No change: macOS (universal, signed), Windows x64/x86/arm64, Linux (AppImage/deb/rpm/Flatpak), FreeBSD, web. Launch failures on single setups (Raspberry Pi OS #7096, Windows without `Windows.Data.Pdf.dll` #6031) are counted under Stability. Word's iPad/iPhone/Android apps are out of scope |
|
||||
| Hardware | 1% | 45% | 40% | 20–40 | [hardware-parity.md](hardware-parity.md) | Up: native printing on desktop through craft-print with printer choice, copies, duplex, N-up, booklets and scale to paper (#783, #641, #2108); Linux Read Aloud through espeak-ng or Speech Dispatcher. No pen pressure, no dictation; GPU drawing and HiDPI fine. Ink hours are in the Features row (Draw tab) |
|
||||
| Ecosystem and plugins | 2% | 15% | 15% | 40–80 | [gaps.md](gaps.md) | No change: Zotero built in, macros record/play commands, `.docm` macros preserved (#172), Templates and Add-ins dialog with Organizer (#382). No VBA execution, no Office add-ins, no EndNote/Mendeley plugins, no cloud storage (WebDAV in progress, #4877) or co-authoring |
|
||||
| AI features | 0% | 40% | 40% | 15–30 | [gaps.md](gaps.md) | No change: beyond Word for external agents (MCP, CLI). No in-app writing assistant; the chat and assistant PRs closed unmerged (#178, #815). Weight 0: Copilot is a paid add-on and not what decides a switch |
|
||||
|
||||
**Ready for real work ≈ 0.30·68 + 0.20·60 + 0.15·55 + 0.10·65 + 0.10·50 + 0.05·75 + 0.04·25 +
|
||||
0.03·95 + 0.01·40 + 0.02·15 ≈ 60%.**
|
||||
**Ready for real work = 0.30·71 + 0.20·65 + 0.15·60 + 0.10·62 + 0.10·45 + 0.05·70 + 0.04·45 +
|
||||
0.03·95 + 0.01·45 + 0.02·15 = 62.9 ≈ 63%** (was 60.5 ≈ 60%).
|
||||
|
||||
## Methodology
|
||||
|
||||
@@ -223,6 +228,12 @@ Word. Their weighted sum is the **full ready for real work** number.
|
||||
priced DOCX corpus fidelity at 10 h. The new evidence is the Word bundle inventory (30 UI
|
||||
languages, 120 proofing tools, 12 bibliography styles), the 62 open issues as of 2026-10-10 (crashes, freezes,
|
||||
RTL reports) and the size of comparable work actually done (below).
|
||||
- **2026-11-28 re-measure** (main `6fbf780789`, after the craft-ui port): each area and dimension
|
||||
was re-scored from the 1,863 PRs merged since 2026-10-10, the open bugs (814 labelled `bug`, 47
|
||||
marked critical), the companion docs (each last reviewed 2026-10-10 to 2026-10-12, with small
|
||||
updates through November) and epic #7671. A number moved only where landed work or an open
|
||||
regression supports it. The interface catalogs were counted at the `craft-i18n.rev` pin, and the missing-translation
|
||||
report was run once (see the Localization row). The app was not run, and nothing was compared with Word page by page.
|
||||
|
||||
### Calibration of hours (from this repo's history)
|
||||
|
||||
@@ -325,3 +336,5 @@ can be used without committing Word output.
|
||||
| 2026-10-06 | major | First estimate in ROADMAP.md: ~62% real feature parity, 120–150 h to 100% |
|
||||
| 2026-10-29 | trivial | Tables row: Table Properties' row, column and cell settings apply to the selection, as in Word (#4857); no percentage change |
|
||||
| 2026-11-07 | trivial | Proofing: freestanding custom dictionary file support (plain UTF-8 and Word CUSTOM.DIC UTF-16LE with BOM) in File › Options › Proofing (#5840); no percentage change |
|
||||
| 2026-11-28 | minor | Refreshed against the 28 Nov parity run (#7969): catalog coverage 510 / 522 (97.7%); commands, tests and lines of code re-counted from source; open issue and PR counts updated. The percentage estimates are unchanged: they predate the craft-ui port (#7101), whose regressions are tracked in epic #7671, and are being re-measured. |
|
||||
| 2026-11-28 | minor | Re-measured against main `6fbf780789` after the craft-ui port (#7101, #7671). Full ~60% → ~63%, mainstream ~55% → ~56%, essentials ~63% → ~62%, feature depth ~68% → ~71%, breadth ~80% → ~85%. Dimensions: Features 68 → 71, File formats 60 → 65, Layout 55 → 60, UI/UX 65 → 62, Stability 50 → 45, Performance 75 → 70, Localization 27 → 45, Hardware 40 → 45; Platforms, Ecosystem and AI unchanged. Beta ~150–230 h → ~175–275 h, full parity ~750–1,250 h → ~775–1,300 h (#7671 work added; areas not re-priced). Duplicate Mailings and Pictures rows removed; superseded "missing" notes dropped; Features hours corrected to the rows, 200–325 h |
|
||||
|
||||
+2
-1
File diff suppressed because one or more lines are too long
@@ -33,11 +33,12 @@ OUTPUT="$DIST/wordcraft-$VERSION-macos-aarch64-nightly.zip"
|
||||
nightly_compile_gui
|
||||
|
||||
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
|
||||
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/WordCraft"
|
||||
chmod 755 "$APP/Contents/MacOS/WordCraft"
|
||||
cp "$ROOT/assets/app-icon/wordcraft-nightly.icns" "$APP/Contents/Resources/wordcraft-nightly.icns"
|
||||
nightly_copy_notices "$APP/Contents/Resources"
|
||||
# Launcher admits notices under Resources/docs, not beside the icon.
|
||||
nightly_copy_notices "$APP/Contents/Resources/docs"
|
||||
# The private mktemp cwd is the helper authority root: stage the template inside it.
|
||||
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
|
||||
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
|
||||
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
|
||||
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
|
||||
real signature, notarization or Mac run."""
|
||||
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
|
||||
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
@@ -27,6 +27,8 @@ COMMIT = "b" * 40
|
||||
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
|
||||
ASSET = f"wordcraft-{VERSION}-macos-aarch64-nightly.zip"
|
||||
APP = "WordCraft Nightly.app"
|
||||
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
|
||||
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
|
||||
TEAM = "ABCDE12345"
|
||||
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
|
||||
SECRETS = {
|
||||
@@ -183,6 +185,50 @@ class Fixture:
|
||||
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
|
||||
return self.input
|
||||
|
||||
def package(self, font_licences):
|
||||
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
|
||||
source = HERE.parents[1]
|
||||
checkout = self.root / "source"
|
||||
checkout.mkdir()
|
||||
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
|
||||
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
|
||||
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
|
||||
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
|
||||
"assets/app-icon/wordcraft-nightly.icns"):
|
||||
target = checkout / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source / relative, target)
|
||||
env = self.env(**dict.fromkeys(SECRETS))
|
||||
|
||||
def git(*args):
|
||||
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
|
||||
|
||||
git("init", "-q")
|
||||
git("add", "--", ".")
|
||||
git("-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-qm", "Packaging fixture")
|
||||
commit = git("rev-parse", "HEAD").strip()
|
||||
version = VERSION[:-12] + commit[:12]
|
||||
# Generated licence text exercises the copier without depending on a font checkout.
|
||||
fonts = self.root / "craft-fonts"
|
||||
for family, data in font_licences.items():
|
||||
licence = fonts / "fonts" / family / "OFL.txt"
|
||||
licence.parent.mkdir(parents=True)
|
||||
licence.write_bytes(data)
|
||||
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
|
||||
(self.bin / "cargo").write_text(
|
||||
'#!/bin/sh\nset -eu\n'
|
||||
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/wordcraft"\n'
|
||||
'mkdir -p "$(dirname "$gui")"\n'
|
||||
"printf \"#!/bin/sh\\necho 'WordCraft %s (nightly-v1)'\\n\" \"$WORDCRAFT_VERSION\" >\"$gui\"\n",
|
||||
)
|
||||
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
|
||||
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
|
||||
WORDCRAFT_BUILD_CHANNEL="nightly-v1", WORDCRAFT_VERSION=version,
|
||||
WORDCRAFT_BUILD_SHA=commit, WORDCRAFT_BUILD_DATE="2026-11-23")
|
||||
assert result.returncode == 0, result.stdout
|
||||
return self.dist / ASSET.replace(VERSION, version)
|
||||
|
||||
def env(self, **changes):
|
||||
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
|
||||
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
|
||||
@@ -410,6 +456,40 @@ class Verify(unittest.TestCase):
|
||||
|
||||
|
||||
class Build(unittest.TestCase):
|
||||
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
|
||||
f = Fixture(self)
|
||||
fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"}
|
||||
archive = f.package(fonts)
|
||||
source = HERE.parents[1]
|
||||
resources = f"{APP}/Contents/Resources"
|
||||
icon = "wordcraft-nightly.icns"
|
||||
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
|
||||
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
|
||||
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
|
||||
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
|
||||
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
|
||||
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
|
||||
contents = f"{APP}/Contents"
|
||||
gui = f"{contents}/MacOS/WordCraft"
|
||||
with zipfile.ZipFile(archive) as zipped:
|
||||
entries = zipped.infolist()
|
||||
names = {entry.filename for entry in entries}
|
||||
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
|
||||
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
|
||||
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
|
||||
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
|
||||
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
|
||||
for path, data in expected_files.items():
|
||||
with self.subTest(path=path):
|
||||
self.assertEqual(zipped.read(path), data)
|
||||
mode = zipped.getinfo(path).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode))
|
||||
self.assertFalse(mode & 0o111)
|
||||
mode = zipped.getinfo(gui).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
|
||||
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
|
||||
def test_compilation_refuses_signing_material_before_building(self):
|
||||
f = Fixture(self)
|
||||
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
|
||||
|
||||
@@ -38,6 +38,49 @@ def assert_nightly_serialization(source):
|
||||
raise ValueError("nightly serialization must use its stable group and no cancellation")
|
||||
|
||||
|
||||
def caller_entries(lines, indent):
|
||||
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
|
||||
entries = {}
|
||||
children = None
|
||||
for line in lines:
|
||||
if children is not None and line.startswith(" " * (indent + 1)):
|
||||
children.append(line)
|
||||
continue
|
||||
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
|
||||
if row is None or row[1] in entries:
|
||||
raise ValueError("malformed or duplicate caller mapping entry")
|
||||
children = []
|
||||
entries[row[1]] = row[2], children
|
||||
return entries
|
||||
|
||||
|
||||
def assert_caller_secrets(source, job_name, names):
|
||||
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
|
||||
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
|
||||
root = caller_entries(lines, 0)
|
||||
job_marker, job_lines = root.pop("jobs", (None, []))
|
||||
jobs = caller_entries(job_lines, 2)
|
||||
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
|
||||
raise ValueError("the caller must have one plain job block")
|
||||
job = caller_entries(jobs[job_name][1], 4)
|
||||
if "environment" in job or "environment" in root or "secrets" in root:
|
||||
raise ValueError("only the native callee may bind the environment")
|
||||
if names:
|
||||
if "secrets" not in job:
|
||||
raise ValueError("signer requires an explicit target-specific secret map")
|
||||
mode, secret_lines = job.pop("secrets")
|
||||
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
|
||||
if mode is not None or caller_entries(secret_lines, 6) != expected:
|
||||
raise ValueError("signer must forward exactly the reviewed same-name secret references")
|
||||
elif "secrets" in job:
|
||||
raise ValueError("unsigned caller must not pass secrets")
|
||||
for value, children in (*root.values(), *job.values()):
|
||||
outside_map = "\n".join([value or "", *children])
|
||||
# Scan all remaining text: quoted braces can appear before a secret reference.
|
||||
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
|
||||
raise ValueError("secret bindings belong only in the signer map")
|
||||
|
||||
|
||||
def literal_off(condition):
|
||||
expression = " ".join(condition.split())
|
||||
if expression.startswith("${{") and expression.endswith("}}"):
|
||||
@@ -87,6 +130,12 @@ def job_conditions(jobs):
|
||||
|
||||
|
||||
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
|
||||
# The pinned shared registry enables Windows, Linux and macOS for WordCraft.
|
||||
SIGNER_SECRETS = {
|
||||
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
|
||||
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
|
||||
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
|
||||
}
|
||||
# Each platform's one trust field in policy v3, and the public stable identity it must name.
|
||||
NIGHTLY_TRUST = {
|
||||
"windows-x86_64": ("publisher_subject",
|
||||
@@ -226,8 +275,49 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
with self.subTest(workflow=name):
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
|
||||
self.assertNotIn("secrets.", executable)
|
||||
|
||||
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
header = " secrets:\n"
|
||||
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
|
||||
self.assertIn(linux, signer)
|
||||
mutations = {
|
||||
"missing name": signer.replace(linux, ""),
|
||||
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
|
||||
"duplicate name": signer.replace(linux, linux + linux),
|
||||
"duplicate map": signer + header + linux,
|
||||
"quoted duplicate map": signer + ' "secrets": inherit\n',
|
||||
"inherit": signer.split(header)[0] + " secrets: inherit\n",
|
||||
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
|
||||
"yaml merge": signer + " <<: *other\n",
|
||||
"environment": signer + " environment: release\n",
|
||||
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
|
||||
}
|
||||
for change, source in mutations.items():
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(source, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_unsigned_caller_has_no_secrets(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
assert_caller_secrets(producer, "unsigned", set())
|
||||
for suffix in (" secrets: {}\n", " secrets: inherit\n",
|
||||
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
|
||||
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(producer + suffix, "unsigned", set())
|
||||
|
||||
def test_unsigned_caller_refuses_secret_after_format_brace(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
# This inert fixture is never dispatched; the brace is part of the format string.
|
||||
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
|
||||
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
|
||||
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
|
||||
assert_caller_secrets(source, "unsigned", set())
|
||||
|
||||
|
||||
class NightlyTrustAnchors(unittest.TestCase):
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user