Compare commits

..
Author SHA1 Message Date
Martin BallandClaude Opus 5.5 4daed0b5ad Undo History: the list keeps its rows while the popover fades out (#8141) (#8154)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:33:42 +00:00
Martin BallandClaude Opus 5.5 d22500664d View tab: Views and Zoom keep their labels at 1440 pt (#7985) (#8156)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:28:24 +00:00
Martin BallandClaude Opus 5.5 effb736735 File rail: the Back arrow reads in the rail's ink (#7707) (#8155)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:28:17 +00:00
Martin BallandClaude Opus 5.5 d7aac19341 docs: refresh roadmap and parity summary against the 28 Nov parity run (#8059)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:38:44 +00:00
Martin BallandClaude Opus 5.5 055a9065f5 docs(7822): the root window is never shown (amend ADR 0001) (#8110)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:38:37 +00:00
Hagai Baram 5265924f29 Word Count: keep automation changes to includeTextBoxes while open (#8139) (#8150) 2026-11-30 09:17:26 +00:00
Lucas Batista Vargas 0f241aef67 Mini toolbar: restore live preview and current-choice mark for Automatic and No Color (#7956) (#7957) 2026-11-30 08:19:15 +00:00
MaheshDesu 6478152244 UI: the Caption preview is its own label, not a field prefix (#8042) (#8043) 2026-11-30 08:09:02 +00:00
Dylan M. Taylor aaaeff2b94 ci(nightly): enable automated daily schedule and Stage 2 signer dispatch (#8054) 2026-11-29 16:16:22 -05:00
Dylan M. Taylor e1f261501c ci(sonarcloud): give each main commit its own concurrency group (#8144) 2026-11-29 16:05:30 -05:00
Lucas Batista Vargas 837999196a Picture and Shape: restore unit hints on size fields (#7952) (#7953) 2026-11-29 20:42:14 +00:00
Lucas Batista Vargas 13f5e9702c Manage Styles: open on the caret's current style (#7950) (#7951) 2026-11-29 20:42:09 +00:00
codeiou 0eace8de49 Search: the title bar keeps its command index between passes (#7674) (#7881) 2026-11-29 20:42:04 +00:00
codeiou 63863ec62d Caret: a window in the background shows no caret and stops repainting for it (#7674) (#7882) 2026-11-29 20:41:59 +00:00
codeiou b4f0a3abad Track Changes Options: the By author swatch shows the author colours side by side again (#7671) (#8011) 2026-11-29 20:41:54 +00:00
MaheshDesu ff98927ea6 UI: the Format Painter icon keeps its full outline (#7683) (#8044) 2026-11-29 20:41:48 +00:00
Lucas Batista Vargas fff580d8f0 perf(engine,ui-egui): skip char scans in word count, memoize format::state, and cache ribbon pickers (#7903) (#7913) 2026-11-29 20:41:43 +00:00
Lucas Batista Vargas 4b3e5d52df perf(ui-egui): defer closed Undo history rows and QAT menu assembly until opened (#7902) (#7912) 2026-11-29 20:38:45 +00:00
Dylan M. Taylor 53bbaa8978 test(nightly): retain exact launcher query and profile coverage (#8136) 2026-11-29 15:22:43 -05:00
Lucas Batista Vargas 813f069712 Styles pane: do not apply a style on right-click (#7958) (#7959) 2026-11-29 20:17:36 +00:00
Lucas Batista Vargas 43c38dfb56 Word Count: preserve the "Count words in text boxes and notes" preference on open (#7941) (#7942) 2026-11-29 19:55:25 +00:00
Dylan M. Taylor 6d6ab5f4dc feat: wire craft-nightly for self-isolated nightly launches (#8126) 2026-11-29 13:48:48 -05:00
Martin BallandClaude Opus 5.5 54f6709a97 UI port: Colors dialog shows no colour, not black, for an unknown Current (#7984) (#8048)
* fix(colors): Colors dialog shows no colour, not black, for an unknown Current; Current reads more targets (#7984)

Needs craft-libs ColorPickerDialog::no_current and the Colors: heading
(craft-libs branch fix/7984-colors-compare-none); waits for the pin to move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(colors): table shading Current skips cells a ragged table lacks (#7984)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(colors): Current reads the run shading the command changes (#7984)

para.shading shades the selected text, not its paragraph, when the selection is text within one
paragraph. Current now reads the selected runs' shading (new "shading" key in format.state, None
when mixed or unset) under the engine's own shades_text rule, now pub. shape.effects Current reads
shapes only, as the command applies glow to shapes only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:41:41 +00:00
Martin BallandClaude Opus 5.5 c6d71b829a fix(formats): an ODT list item's later paragraphs stay in the item (repin regression) (#8089)
craft-libs 9c27cebc14 reads an ODT list item's further paragraphs as unnumbered
paragraphs marked ParaProps.list_item. WordCraft's ParaProps had no such field,
so the bridge dropped it and HTML/Markdown export restarted numbering after the
item. Add the field, same type and serde name as craft-wordmodel's.


Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:43:20 +00:00
Martin BallandClaude Opus 5.5 af26131063 fix(dialogs): Borders and Shading draws its preview at sample size (#7977) (#8088)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:42:47 +00:00
Dylan M. Taylor 9b13180006 fix(nightly): enable Linux package_formats (including Flatpak) in signing policy (#8091) 2026-11-28 22:42:19 -05:00
Martin BallandClaude Opus 5.5 2ca5bf5dfa fix(options): Initials shows its default-initials placeholder again (#8018) (#8081)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:41:59 +00:00
Martin BallandClaude Opus 5.5 1f6cf16029 fix(docx): a text box in a hyperlinked nested group survives an edit (repin regression) (#8087)
craft-libs 6a46b44449 keeps a hyperlinked nested group as a nested
InlineObject::Group. WordCraft looks one level deep, so prune_text_boxes
dropped the nested box's story on the first edit. The bridge now lifts nested
members into the parent group, offsets composed, as the reader does for
unlinked groups.


Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:39:45 +00:00
Martin BallandClaude Opus 5.5 18bbf00090 UI port: Customize Keyboard categories, Customize Ribbon layout, command search locations (#7671) (#8024)
* fix(keyboard): Customize Keyboard lists the ribbon tabs as Categories, in a dialog of set size (#7971)

Catalog commands carry their English ribbon location as a menu path; Categories are
the ribbon tabs (from ribbon::TABS), Contextual Tabs, Other and All Commands.

Partial: the Commands list still gets no room until the craft-libs fix (a7d6dcfcbb on
fix/7971-keyboard-categories-height) is synced to main and WordCraft repins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(ribbon): Customize Ribbon and Quick Access panes share the width (#7981)

Tab names are no longer truncated and Up/Down no longer overlap the list.

Partial: the lists are still unframed (craft-libs List has no frame option).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(search): command search shows each command's ribbon location (#7983)

Partial: the shortcut per row and the popup width are not done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:25:47 +00:00
67 changed files with 1907 additions and 1086 deletions
+12 -2
View File
@@ -83,7 +83,9 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -95,7 +97,15 @@
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
+2 -2
View File
@@ -11,9 +11,9 @@ permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
# Automatic Stage 2 signer dispatch for completed scheduled nightly producer runs.
if: >-
false && github.repository == 'storytold/wordcraft' &&
github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
+3 -2
View File
@@ -1,8 +1,9 @@
name: WordCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
# Automated daily unsigned nightly build at 07:00 UTC plus supervised manual runs.
on:
schedule:
- cron: '0 7 * * *'
workflow_dispatch:
permissions:
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+1
View File
@@ -258,6 +258,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/pageNumber.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/pageWidth.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/painter.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/painter-fill.svg` | WordCraft contributors | original: the Format Painter's yellow bar, split out as the fill drawn under `painter.svg` | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/paraSpacing.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/pastCitation.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/paste.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
Generated
+9
View File
@@ -1818,6 +1818,14 @@ dependencies = [
"encoding_rs",
]
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
dependencies = [
"winsafe",
]
[[package]]
name = "craft-odf"
version = "0.1.0"
@@ -9098,6 +9106,7 @@ name = "wordcraft"
version = "0.18.1"
dependencies = [
"craft",
"craft-nightly",
"craft-proof",
"eframe",
"egui",
+1
View File
@@ -52,6 +52,7 @@ craft = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
+1
View File
@@ -43,6 +43,7 @@ craft = { workspace = true, features = [
"platform-appearance",
"platform-clipboard-system",
] }
craft-nightly = { workspace = true }
[dev-dependencies]
# Temporary settings folders for the `prefs` tests.
+19 -25
View File
@@ -1,23 +1,11 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(wordcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open WordCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable WordCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -37,7 +25,10 @@ pub fn version_query(args: &[OsString]) -> bool {
#[cfg(test)]
mod tests {
use super::*;
use super::{BuildFlavor, needs_native_error, version, version_query};
use craft_nightly::{Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
use std::ffi::OsString;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -47,19 +38,22 @@ mod tests {
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
let spec = crate::profile_root::spec();
let expected_root = canonical_profile_root(spec.app_id).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("letter.docx")], &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(launch.passthrough_args, vec![OsString::from("letter.docx")]);
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
fn stable_build_refuses_nightly_launch_flags() {
let spec = crate::profile_root::spec();
let args = craft_nightly::launch_arguments(std::path::Path::new(crate::launch_profile::launcher_root()), &[]);
let err = parse_startup(BuildFlavor::Stable, &spec, args, &StartupOptions::new()).unwrap_err();
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
+105 -164
View File
@@ -1,174 +1,132 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, preferences, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
//! Nightly-v1 bootstrap backed by `craft-nightly`. Selected before logging, preferences, fonts or
//! saved state. Stable launches retain their original arguments and directory policy.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
use std::ffi::{OsStr, OsString};
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub use craft_nightly::Profile;
/// Returns the active launch profile for this process, defaulting to [`Profile::Stable`] before
/// `craft_nightly::prepare_launch` installs one.
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
static STABLE: Profile = Profile::Stable;
craft_nightly::current().unwrap_or(&STABLE)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
fn is_nightly_flag_token(arg: &OsStr) -> bool {
arg.to_str().is_some_and(|s| {
s == craft_nightly::LAUNCH_PROFILE_FLAG
|| s == craft_nightly::PROFILE_ROOT_FLAG
|| s.starts_with("--launch-profile=")
|| s.starts_with("--profile-root=")
})
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
/// Returns `true` when `args` starts with nightly launch protocol flags followed by `--`.
/// `craft_nightly::parse_startup` consumes that `--`; preserving it lets `main.rs`'s
/// `split_at_delimiter` treat every argument after `--` as a document path.
pub fn had_launcher_separator(args: &[OsString]) -> bool {
if !args.first().is_some_and(|arg| is_nightly_flag_token(arg)) {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
let mut idx = 0;
while let Some(arg) = args.get(idx) {
if arg == "--" {
return true;
}
if arg == craft_nightly::LAUNCH_PROFILE_FLAG || arg == craft_nightly::PROFILE_ROOT_FLAG {
idx += 2;
} else if arg.to_str().is_some_and(|s| s.starts_with("--launch-profile=") || s.starts_with("--profile-root=")) {
idx += 1;
} else {
break;
}
}
false
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old settings-folder resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
/// Re-attaches the `--` separator when `craft_nightly` stripped one from an explicit launcher
/// header, leaving direct-launch arguments untouched.
pub fn passthrough_args(args: Vec<OsString>, had_separator: bool) -> Vec<OsString> {
if had_separator { std::iter::once(OsString::from("--")).chain(args).collect() } else { args }
}
/// The root the Launcher hands a nightly on this platform, in that platform's own spelling: `C:\NightlyData\profiles\wordcraft`
/// on Windows, `/nightly-data/profiles/wordcraft` elsewhere. A test that fixtures the hand-off uses this rather than a
/// literal, because a root literal in the other platform's spelling is not absolute here and `parse` refuses it (#7849).
/// literal, because a root literal in the other platform's spelling is not absolute here and validation refuses it (#7849).
#[cfg(test)]
pub(crate) fn launcher_root() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
crate::profile_root::validate(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref(), crate::profile_root::probe_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use super::{had_launcher_separator, launcher_root, passthrough_args};
use craft_nightly::{
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup, validate_and_prepare_root,
};
use std::ffi::OsString;
use std::path::PathBuf;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
super::launcher_root()
launcher_root()
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
let spec = crate::profile_root::spec();
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
let had_sep = had_launcher_separator(&argv);
assert!(!had_sep);
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "letter with spaces.docx"]));
fn direct_nightly_launch_resolves_canonical_root_and_preserves_user_arguments() {
let spec = crate::profile_root::spec();
let expected_root = canonical_profile_root(spec.app_id).unwrap();
let argv = args(&["--sample", "letter.docx"]);
let had_sep = had_launcher_separator(&argv);
assert!(!had_sep);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let spec = crate::profile_root::spec();
let mut argv = nightly();
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
let had_sep = had_launcher_separator(&argv);
assert!(had_sep);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), args(&["--", "--profile-root", "letter with spaces.docx"]));
}
#[test]
fn missing_duplicate_and_unknown_profile_arguments_are_refused() {
let spec = crate::profile_root::spec();
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
] {
assert!(parse(argv).is_err());
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).is_err());
}
}
@@ -177,53 +135,36 @@ mod tests {
/// instead of run against a directory this platform never meant.
#[test]
fn a_root_absolute_only_in_the_other_platforms_spelling_is_refused() {
let spec = crate::profile_root::spec();
let foreign = if cfg!(windows) { "/nightly-data/profiles/wordcraft" } else { r"C:\NightlyData\profiles\wordcraft" };
let argv = args(&["--launch-profile", VERSION, "--profile-root", foreign, "--"]);
assert!(parse(argv).is_err(), "the other platform's root spelling must not stand in: {foreign}");
let err = validate_and_prepare_root(std::path::Path::new(foreign), &spec).unwrap_err();
assert!(matches!(err, ProfileError::RelativeProfileRoot(_)), "the other platform's root spelling must not stand in: {foreign}");
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
fn launcher_and_plain_version_queries_are_recognized() {
let spec = crate::profile_root::spec();
let pair = &["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT];
for flag in ["--version", "-V"] {
let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(plain.is_version_query());
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
let direct = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert!(direct.is_version_query());
argv.push("letter with spaces.docx".into());
let with_document = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert!(!with_document.is_version_query());
assert_eq!(with_document.passthrough_args, args(&[flag, "letter with spaces.docx"]));
let mut with_sep = args(form);
with_sep.push("--".into());
with_sep.push(flag.into());
let separated = parse_startup(BuildFlavor::NightlyV1, &spec, with_sep, &StartupOptions::new()).unwrap();
assert!(separated.is_version_query());
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+31 -17
View File
@@ -415,34 +415,40 @@ fn report_launch_profile_error(error: &str) {
/// Select the immutable launch profile before any startup service or side effect.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before logging, crash handling, the update helper,
// The launch profile is decided before logging, crash handling, the update helper,
// fonts, preferences or the settings folder.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
// Plain `--version` / `-V` on nightly: answered before root resolution, validation,
// process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| launch_profile::prepare(launch, launch_profile::validate_root))
let had_separator = launch_profile::had_launcher_separator(&argv);
let early = craft_nightly::prepare_launch(build_flavor::COMPILED, &profile_root::spec(), argv, &craft_nightly::StartupOptions::new())
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher `--launch-profile nightly-v1 --profile-root <dir> [--] --version` / `-V`:
// `craft_nightly::prepare_launch` skips root validation and profile installation for
// version queries, so answer and exit before any startup side effect.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error.to_string());
std::process::exit(2);
}
let identity = if early.profile.is_nightly() {
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
} else {
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
};
if let Err(error) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
if let Err(error) = wordcraft_ui_egui::os_window::select_identity(identity) {
report_launch_profile_error(&error);
std::process::exit(2);
}
@@ -454,7 +460,7 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
@@ -1199,14 +1205,22 @@ mod command_line_tests {
use super::{documents_to_open, split_at_delimiter};
/// The argv the Launcher starts a nightly with, as `prepare_launch` hands it on. The root is the one this
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows `parse` rightly refuses it.
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows validation rightly refuses it.
fn launcher_argv(tail: &[&str]) -> Vec<String> {
let mut argv: Vec<std::ffi::OsString> = ["--launch-profile", "nightly-v1", "--profile-root", super::launch_profile::launcher_root(), "--"]
.iter()
.map(std::ffi::OsString::from)
.collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
super::launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
let had_separator = super::launch_profile::had_launcher_separator(&argv);
let launch = craft_nightly::parse_startup(
crate::build_flavor::BuildFlavor::NightlyV1,
&crate::profile_root::spec(),
argv,
&craft_nightly::StartupOptions::new(),
)
.unwrap();
super::launch_profile::passthrough_args(launch.passthrough_args, had_separator).iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
+160 -553
View File
@@ -1,4 +1,5 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//! App-owned nightly profile specification for `craft-nightly`; no stable fallback, migration or
//! process environment changes.
//!
//! WordCraft keeps all of its user state in one settings folder (`wordcraft_control_key::settings_dir`):
//! `config.toml`, `window.json`, `logs/`, `recovery/`, `fonts/`, `Templates/`,
@@ -8,603 +9,209 @@
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
use std::ffi::OsString;
use std::path::PathBuf;
use std::path::{Component, Path, PathBuf};
use craft_nightly::AppProfileSpec;
/// The app id of the nightly Flatpak this build ships in (`packaging/linux/flatpak-bundle.sh`).
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.wordcraft.nightly";
pub const APP_ID: &str = "wordcraft";
pub const DISPLAY_NAME: &str = "WordCraft";
pub const STABLE_PACKAGE_ID: &str = "ai.storyteller.wordcraft";
pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.wordcraft.nightly";
pub const STABLE_DIR_NAMES: &[&str] = &["wordcraft", "WordCraft", "craft-fonts", "Craft Fonts"];
pub const FORBIDDEN_ENV_VARS: &[&str] = &["WORDCRAFT_PROFILE_DIR"];
pub const FOLDER_ONLY_ENTRIES: &[&str] = &["recovery", "logs", "fonts", "Templates", "FontStore"];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
/// Returns WordCraft's `craft-nightly` isolation specification, including OS-specific installation
/// and sandbox roots that must never overlap a nightly profile.
pub fn spec() -> AppProfileSpec {
spec_with(|key| std::env::var_os(key))
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
fn spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: DISPLAY_NAME,
stable_dir_names: STABLE_DIR_NAMES,
stable_package_id: STABLE_PACKAGE_ID,
nightly_package_id: NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: FORBIDDEN_ENV_VARS,
portable_markers: &[],
folder_only_entries: FOLDER_ONLY_ENTRIES,
extra_forbidden_roots: extra_forbidden_roots_with(env),
}
}
#[cfg(any(unix, target_os = "windows"))]
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
if path.is_absolute() { Some(path) } else { None }
}
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
// Per-user and per-machine MSI install locations.
if let Some(local) =
non_empty_abs(&env, "LOCALAPPDATA").or_else(|| non_empty_abs(&env, "USERPROFILE").map(|p| p.join("AppData").join("Local")))
{
roots.push(local.join("Programs").join("ArtCraft").join("WordCraft"));
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(&env, key) {
roots.push(base.join("ArtCraft").join("WordCraft"));
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
#[cfg(all(unix, not(target_os = "macos")))]
{
// Native packages' locations and the stable Flatpak's per-app data folder.
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
if let Some(home) = non_empty_abs(&env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.wordcraft"));
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("WordCraft")))
.collect::<Result<Vec<_>, _>>()?;
// The suite's shared font store and the MSI's default per-user and per-machine folders.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Craft Fonts"));
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("WordCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("WordCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("wordcraft")))
.collect::<Result<Vec<_>, _>>()?;
// The shared font store (fonts and Language packs) and the native packages' locations.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("craft-fonts"));
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.wordcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
#[cfg(target_os = "macos")]
{
roots.push(PathBuf::from("/Applications/WordCraft.app"));
if let Some(home) = non_empty_abs(&env, "HOME") {
let library = home.join("Library");
vec![
library.join("Application Support/WordCraft"),
library.join("Caches/WordCraft"),
library.join("Caches/ai.storyteller.wordcraft"),
library.join("Preferences/WordCraft"),
library.join("Preferences/ai.storyteller.wordcraft.plist"),
library.join("Saved Application State/ai.storyteller.wordcraft.savedState"),
library.join("Application Support/Craft Fonts"),
home.join("Applications/WordCraft.app"),
PathBuf::from("/Applications/WordCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
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)
}
/// Every existing entry directly in the profile (`config.toml`, `logs`, `recovery`, `fonts`,
/// `Templates`, `window.json` and so on) must resolve inside it, so a link there cannot point
/// Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
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")?;
roots.push(library.join("Preferences/ai.storyteller.wordcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.wordcraft.savedState"));
roots.push(home.join("Applications/WordCraft.app"));
}
}
Ok(())
#[cfg(not(any(unix, target_os = "windows")))]
let _ = env;
roots
}
/// 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);
let probe = dir.join(format!(".nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or creating the profile of the person running them.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
// The developer switch that points a run at any folder: Nightly's folder comes from the Launcher.
if env("WORDCRAFT_PROFILE_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with WORDCRAFT_PROFILE_DIR".into());
}
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting a Flatpak
// runtime could point another profile at the stable app's token files; the nightly Flatpak
// itself (`packaging/linux/flatpak-bundle.sh`) is the one sandbox this build ships in.
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
&& id != NIGHTLY_FLATPAK_ID
{
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect its own subfolders elsewhere.
entries_stay_inside(&chosen)?;
// Recovery can read, adopt and sweep entries; a link there must never leave the profile.
private_subdirectory(&chosen, "recovery", "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, "recovery", "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
const PROFILE_FOLDERS: [&str; 5] = ["recovery", "logs", "fonts", "Templates", "FontStore"];
#[cfg(test)]
mod tests {
use super::*;
use super::{
APP_ID, DISPLAY_NAME, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, STABLE_DIR_NAMES, STABLE_PACKAGE_ID,
extra_forbidden_roots_with, spec_with,
};
use craft_nightly::{ProfileError, validate_and_prepare_root};
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
struct TempRoot(PathBuf);
impl Fixture {
fn new() -> Self {
impl TempRoot {
fn new(label: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("wordcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let candidate = std::env::temp_dir().join(format!(
"wordcraft-profile-spec-{label}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/wordcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
Self(root)
}
}
impl Drop for Fixture {
impl Drop for TempRoot {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn linux_fences_the_settings_folders_font_store_and_packages_but_allows_the_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let fonts = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()).join("craft-fonts");
std::fs::create_dir_all(fonts.join("language-packs")).unwrap();
for candidate in [fonts.clone(), fonts.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
for package in ["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"] {
assert!(fixture.check(Platform::Linux, &PathBuf::from(package)).is_err());
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
fn spec_preserves_wordcraft_isolation_contract() {
let spec = spec_with(|_| None);
assert_eq!(spec.app_id, APP_ID);
assert_eq!(spec.display_name, DISPLAY_NAME);
assert_eq!(spec.stable_dir_names, STABLE_DIR_NAMES);
assert_eq!(spec.stable_package_id, STABLE_PACKAGE_ID);
assert_eq!(spec.nightly_package_id, NIGHTLY_PACKAGE_ID);
assert_eq!(spec.profile_root_env, None);
assert_eq!(spec.forbidden_env_vars, FORBIDDEN_ENV_VARS);
assert!(spec.portable_markers.is_empty());
assert_eq!(spec.folder_only_entries, FOLDER_ONLY_ENTRIES);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn linux_extra_forbidden_roots_cover_native_packages_and_stable_flatpak() {
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/home/tester"))]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from("/usr/bin/wordcraft")));
assert!(roots.contains(&PathBuf::from("/usr/local/bin/wordcraft")));
assert!(roots.contains(&PathBuf::from("/opt/wordcraft")));
assert!(roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.wordcraft")));
}
#[cfg(target_os = "macos")]
#[test]
fn macos_extra_forbidden_roots_cover_bundles_plist_and_saved_state() {
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/Users/tester"))]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from("/Applications/WordCraft.app")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Applications/WordCraft.app")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Preferences/ai.storyteller.wordcraft.plist")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Saved Application State/ai.storyteller.wordcraft.savedState")));
}
#[cfg(target_os = "windows")]
#[test]
fn windows_extra_forbidden_roots_cover_per_user_and_machine_installs() {
let env = BTreeMap::from([
(String::from("LOCALAPPDATA"), OsString::from(r"C:\Users\tester\AppData\Local")),
(String::from("ProgramFiles"), OsString::from(r"C:\Program Files")),
(String::from("ProgramFiles(x86)"), OsString::from(r"C:\Program Files (x86)")),
]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from(r"C:\Users\tester\AppData\Local\Programs\ArtCraft\WordCraft")));
assert!(roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\WordCraft")));
assert!(roots.contains(&PathBuf::from(r"C:\Program Files (x86)\ArtCraft\WordCraft")));
}
#[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();
}
fn nightly_profile_reopens_and_enforces_folder_only_entries_and_extra_fences() {
let temp = TempRoot::new("reopen");
let fenced = temp.0.join("fenced-stable");
let mut spec = spec_with(|_| None);
spec.extra_forbidden_roots.push(fenced.clone());
let overlap = validate_and_prepare_root(&fenced.join("nightly"), &spec).unwrap_err();
assert!(matches!(overlap, ProfileError::ForbiddenRootOverlap { .. }));
assert!(!fenced.exists());
let private = temp.0.join("nightly-private");
assert_eq!(validate_and_prepare_root(&private, &spec).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();
}
}
#[test]
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
let flatpak = fixture.home().join(".var/app/ai.storyteller.wordcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
for name in FOLDER_ONLY_ENTRIES {
std::fs::create_dir(private.join(name)).unwrap();
}
assert!(!flatpak.exists());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
// Inside the Nightly Flatpak, XDG_DATA_HOME is this app's own persistent data folder, so
// the launcher's profile lands there rather than on the discarded sandbox home.
let nightly = fixture.home().join(".var/app/ai.storyteller.wordcraft.nightly/data/wordcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
}
#[test]
fn mac_fences_the_app_library_subtrees_the_shared_font_store_and_the_whole_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/WordCraft Nightly.app/Contents/MacOS/WordCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/WordCraft",
"Caches/WordCraft",
"Caches/ai.storyteller.wordcraft",
"Preferences/WordCraft",
"Saved Application State/ai.storyteller.wordcraft.savedState",
"Application Support/Craft Fonts",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen");
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_font_store_and_install_fences_remain_active() {
let fixture = Fixture::new();
let mut fixture = fixture;
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("WordCraft");
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
for name in FOLDER_ONLY_ENTRIES {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
let err = validate_and_prepare_root(&private, &spec).unwrap_err();
assert!(matches!(err, ProfileError::ExpectedDirectoryEntry(_)), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
let fonts = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Craft Fonts");
assert!(fixture.check(Platform::Windows, &fonts.join("nightly")).unwrap_err().contains("overlap"));
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("wordcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not WordCraft's install");
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/wordcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("recovery"), platform));
assert!(overlaps(&root.join("recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("wordcraft-other"), platform));
}
}
#[cfg(unix)]
#[test]
fn recovery_and_entry_aliases_cannot_leave_the_profile_and_stable_bytes_stay_untouched() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft/recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join("recovery")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "recovery must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
for name in ["logs", "fonts", "config.toml"] {
let private = fixture.root.join(format!("nightly-entry-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "{name} must not lead outside the profile");
}
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_recovery_alias_inside_the_profile_keeps_it_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join("recovery")).unwrap(), recovery);
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/wordcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("WORDCRAFT_PROFILE_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("WORDCRAFT_PROFILE_DIR"));
fixture.env.remove("WORDCRAFT_PROFILE_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.wordcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
// The nightly Flatpak is the one sandbox this build ships in, so its own id is accepted.
let flatpak_profile = fixture.home().join("nightly/flatpak-profile");
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
assert_eq!(fixture.check(Platform::Linux, &flatpak_profile).unwrap(), flatpak_profile);
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
let fixture = Fixture::new();
let file = fixture.home().join("not-a-directory");
std::fs::write(&file, b"do not replace me").unwrap();
assert!(fixture.check(Platform::Linux, &file).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
let candidate = fixture.home().join("nightly");
let calls = std::cell::Cell::new(0);
let result = validate_for(
Platform::Linux,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
calls.set(calls.get() + 1);
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
},
);
assert!(result.unwrap_err().contains("not writable"));
assert_eq!(calls.get(), 1);
assert!(!fixture.home().join(".config/wordcraft").exists());
}
#[cfg(unix)]
#[test]
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
use std::os::unix::fs::symlink;
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
let alias = fixture.home().join("alias");
symlink(&stable, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
let missing = fixture.home().join("missing-target");
let dangling = fixture.home().join("dangling");
symlink(&missing, &dangling).unwrap();
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
assert!(!missing.exists());
assert!(!stable.join("nightly").exists());
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
}
}
+5
View File
@@ -506,6 +506,11 @@ pub struct ParaProps {
/// file (not laid out yet); Word sizes a line by it, so dropping it changes Word's pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub text_alignment: Option<TextAlignment>,
/// A list item's paragraph after its first (or a list header's), with no number of its own,
/// at this list level (0..=8): formats with list items (ODT, HTML, Markdown) keep it in the
/// item. Set only directly, never by a style.
#[serde(skip_serializing_if = "Option::is_none")]
pub list_item: Option<u8>,
}
impl ParaProps {
+22 -5
View File
@@ -100,18 +100,35 @@ fn object_value_from_shared(
float: convert(float)?,
ch_w,
ch_h,
children: children.into_iter().map(|c| group_child_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
children: group_children_from_shared(children, graphics)?,
canvas: canvas.map(convert).transpose()?,
}),
other => convert(other),
}
}
fn group_child_value_from_shared(
source: craft_wordmodel::para::GroupChild,
/// A group's members. The shared reader keeps a hyperlinked nested group whole; WordCraft's
/// text box, layout and edit code looks one level deep, so lift its members into this group
/// (their offsets composed, scaled from the nested group's child space), as the reader does for
/// an unlinked one. The nested group's own link is dropped.
// lean: nested groups are flattened until WordCraft supports them (follow-up issue).
fn group_children_from_shared(
children: Vec<craft_wordmodel::para::GroupChild>,
graphics: &mut GraphicCache,
) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj, graphics)? })
) -> Result<Vec<wordcraft_doc::para::GroupChild>, DocxError> {
let mut out = Vec::with_capacity(children.len());
for c in children {
let (x, y) = (c.x, c.y);
match object_value_from_shared(c.obj, graphics)? {
wordcraft_doc::para::InlineObject::Group { w, h, ch_w, ch_h, children, .. } => {
let (kx, ky) = (if ch_w > 0.0 { w / ch_w } else { 1.0 }, if ch_h > 0.0 { h / ch_h } else { 1.0 });
// `children` is already flat: the recursion converted the nested group first.
out.extend(children.into_iter().map(|m| wordcraft_doc::para::GroupChild { x: x + m.x * kx, y: y + m.y * ky, obj: m.obj }));
}
obj => out.push(wordcraft_doc::para::GroupChild { x, y, obj }),
}
}
Ok(out)
}
fn table_value_from_shared(source: craft_wordmodel::table::Table, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Table, DocxError> {
+1
View File
@@ -229,6 +229,7 @@ fn every_para_prop_round_trips() {
fmt_change: None,
snap_to_grid: Some(false),
text_alignment: Some(TextAlignment::Top),
list_item: None, // not a DOCX property
};
let variants = [
ParaProps { line_spacing: Some(LineSpacing::AtLeast(14.0)), indent_first: Some(24.0), align: Some(Align::Center), ..Default::default() },
+20
View File
@@ -265,3 +265,23 @@ fn story_shared_by_many_shapes_is_written_once() {
// fallback. The other shapes do not repeat it.
assert_eq!(xml.matches(text.as_str()).count(), 2);
}
#[test]
fn text_box_in_a_linked_nested_group_survives_pruning() {
// The shared reader keeps a hyperlinked nested group whole; the box inside must still be
// reachable (`text_boxes` looks one level deep), or the first edit's prune deletes its story.
let inner = r#"<wpg:grpSp><wpg:cNvPr id="3" name="Inner"><a:hlinkClick r:id="rId9"/></wpg:cNvPr><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="635000" y="0"/><a:ext cx="635000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="635000" cy="635000"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:cNvPr id="4" name="Box"/><wps:cNvSpPr txBox="1"/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="rect"/></wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>Inside</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></wpg:grpSp>"#;
let doc = format!(
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><w:body><w:p><w:r><w:drawing><wp:inline><wp:extent cx="1270000" cy="635000"/><wp:docPr id="1" name="Outer"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="1270000" cy="635000"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:wgp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p></w:body></w:document>"#
);
let rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc_rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/" TargetMode="External"/></Relationships>"#;
let bytes = zip(&[("_rels/.rels", rels), ("word/document.xml", doc.as_bytes()), ("word/_rels/document.xml.rels", doc_rels)]);
let mut d = wordcraft_docx::read(&bytes).unwrap();
assert_eq!(boxes(&d).len(), 1);
// What every mutating command does after it runs.
d.prune_text_boxes();
assert_eq!(boxes(&d).len(), 1, "the nested box lost its story");
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
assert!(xml.contains("Inside"), "{xml}");
}
+95
View File
@@ -1,5 +1,7 @@
//! Character formatting (Home › Font).
use std::sync::{Arc, PoisonError};
use serde_json::{Value, json};
use wordcraft_doc::eq::{EncloseShape, EncloseStyle, Enclosure};
use wordcraft_doc::props::{Border, CharProps, Highlight, Rgb, TextColor, Underline, VertAlign};
@@ -8,8 +10,44 @@ use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use super::sel_result;
use super::tools::{is_turkic, lower_char, upper_char};
use crate::doc_state::{ColumnBlock, Selection};
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
#[derive(Clone, PartialEq)]
struct StateKey {
document_id: u64,
rev: u64,
sel: Selection,
pending: Option<CharProps>,
pending_at: Option<Pos>,
column: Option<ColumnBlock>,
font_gen: u64,
}
/// Cached result of [`cached_state`] and the session inputs it depends on.
pub(crate) struct StateCache {
key: StateKey,
value: Arc<Value>,
}
impl StateCache {
pub(crate) fn rev(&self) -> u64 {
self.key.rev
}
}
fn state_key(s: &Session) -> StateKey {
StateKey {
document_id: s.document_id(),
rev: s.rev(),
sel: s.sel.clone(),
pending: s.pending.clone(),
pending_at: s.pending_at.clone(),
column: s.column.clone(),
font_gen: wordcraft_fonts::FontDb::global().generation(),
}
}
/// Word's font size list.
pub const SIZES: [f32; 17] = [8.0, 9.0, 10.0, 10.5, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 36.0, 48.0, 72.0];
@@ -879,8 +917,30 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
apply(s, &|c| c.overlay(&props))
}
/// What the ribbon shows: the formatting at the selection (mixed values are null), cached per
/// document revision, selection, pending caret state, column selection, and font generation.
pub fn cached_state(s: &Session) -> Arc<Value> {
let key = state_key(s);
{
let cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(cached) = cache.as_ref()
&& cached.key == key
{
return Arc::clone(&cached.value);
}
}
let value = Arc::new(compute_state(s));
let mut cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
*cache = Some(StateCache { key, value: Arc::clone(&value) });
value
}
/// What the ribbon shows: the formatting at the selection (mixed values are null).
pub fn state(s: &Session) -> Value {
(*cached_state(s)).clone()
}
fn compute_state(s: &Session) -> Value {
let all = resolved(s);
let first = all.first().cloned();
let same = |f: &dyn Fn(&ResolvedChar) -> Value| -> Value {
@@ -906,6 +966,7 @@ pub fn state(s: &Session) -> Value {
"italic": all.iter().all(shown_italic),
"underline": all.iter().all(|r| r.underline != Underline::None),
"underlineColor": same(&|r| json!(r.underline_color.map_or_else(|| "auto".to_string(), |c| c.hex()))),
"shading": same(&|r| json!(r.shading.map(|c| c.hex()))),
"strike": all.iter().all(|r| r.strike),
"border": all.iter().all(|r| r.border.is_some()),
"subscript": all.iter().all(|r| r.vert_align == VertAlign::Subscript),
@@ -927,6 +988,14 @@ pub fn state(s: &Session) -> Value {
})
}
/// The selection's uniform highlight colour (`Some(None)` when uniformly unhighlighted), or `None`
/// when the selection is mixed or empty.
pub fn uniform_highlight(s: &Session) -> Option<Option<Rgb>> {
let all = resolved(s);
let first = all.first()?.highlight;
all.iter().all(|r| r.highlight == first).then_some(first)
}
/// What Enclose Characters works on: the selected text (one full-width or up to two half-width
/// characters), or enclosed characters already there (selected, or beside the caret).
#[derive(Clone, Debug, PartialEq)]
@@ -1054,4 +1123,30 @@ mod tests {
assert_eq!(convert("one 3.14 apples and two 2.5 pears.", "sentence", true), "One 3.14 apples and two 2.5 pears.");
assert_eq!(convert("pi is 3.14. next sentence.", "sentence", true), "Pi is 3.14. Next sentence.");
}
#[test]
fn cached_state_hits_until_selection_format_or_pending_changes() {
use serde_json::json;
use std::sync::Arc;
let mut s = crate::Session::new(wordcraft_doc::Document::new());
let a = super::cached_state(&s);
let b = super::cached_state(&s);
assert!(Arc::ptr_eq(&a, &b), "unchanged session should reuse cached format state Arc");
s.run("text.insert", &json!({"text": "hello world"})).unwrap();
let c = super::cached_state(&s);
assert!(!Arc::ptr_eq(&b, &c), "text edit bumps rev and invalidates cache");
s.run("format.bold", &json!({})).unwrap();
let d = super::cached_state(&s);
assert!(!Arc::ptr_eq(&c, &d), "pending bold changes caret formatting");
assert_eq!(d["bold"], json!(true));
assert!(Arc::ptr_eq(&d, &super::cached_state(&s)));
s.run("select.text", &json!({"text": "hello"})).unwrap();
let e = super::cached_state(&s);
assert!(!Arc::ptr_eq(&d, &e), "selection change updates format state");
assert_eq!(e["bold"], json!(false));
}
}
+1 -1
View File
@@ -304,7 +304,7 @@ pub fn specs() -> Vec<CommandSpec> {
/// start, so all of a paragraph's text is still text, except in the last paragraph of its story,
/// cell or box, where it stands for the paragraph with its mark. A selected picture, shape or text
/// box is its object character, not text (a field's object character is).
fn shades_text(s: &Session) -> bool {
pub fn shades_text(s: &Session) -> bool {
let (a, b) = s.sel.ordered();
if a == b || a.story != b.story || a.path != b.path {
return false;
+2
View File
@@ -149,6 +149,8 @@ pub struct Session {
/// ([`Session::why_disabled`]): computed once per document, revision and author instead of
/// for every button on every frame.
protect_facts: std::sync::Mutex<Option<((u64, u64, String), crate::cmd::protect::Facts)>>,
/// Cached result of [`crate::cmd::format::cached_state`] and the state key it was made for.
pub(crate) format_state: std::sync::Mutex<Option<crate::cmd::format::StateCache>>,
/// How many times the document's body was replaced under the same [`Self::document_id`]
/// (`document.setText`, version restore, compare, Undo/Redo). It is the body's IME
/// replacement epoch: a composition must not survive the swap, even when the new body has
+1
View File
@@ -285,6 +285,7 @@ impl Session {
last_highlight: _,
// Keyed by document id and revision, so one cache serves every document.
protect_facts: _,
format_state: _,
// The input method talks to the window, whichever document it shows; the IME
// context is keyed by `document_id`.
ime_state_revision: _,
+1
View File
@@ -131,6 +131,7 @@ impl Session {
untitled,
made_rev,
protect_facts: std::sync::Mutex::new(None),
format_state: std::sync::Mutex::new(None),
ime_body_epoch,
ime_state_revision: None,
ime_state_seen: None,
+5
View File
@@ -113,6 +113,7 @@ impl Session {
autocap: _,
rev: _,
protect_facts: _,
format_state: _,
cache: _,
layout: _,
// The word being typed, like `column`: valid only while `sel` is where typing left it.
@@ -296,6 +297,10 @@ impl Session {
if facts.as_ref().is_some_and(|((_, r, _), _)| *r != rev) {
*facts = None;
}
let format_state = self.format_state.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner);
if format_state.as_ref().is_some_and(|c| c.rev() != rev) {
*format_state = None;
}
}
/// [`crate::cmd::protect::Facts`] for the document as it is now, cached per revision.
+13
View File
@@ -1258,3 +1258,16 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
assert_eq!(p2.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
}
}
#[test]
fn odt_list_item_later_paragraphs_stay_in_the_item() {
// "One" has two paragraphs. The second must stay inside item 1, so HTML's "Two" is item 2.
let fodt = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text"><office:automatic-styles><text:list-style style:name="L1"><text:list-level-style-number text:level="1" style:num-format="1"/></text:list-style></office:automatic-styles><office:body><office:text><text:list text:style-name="L1"><text:list-item><text:p>One</text:p><text:p>Still one</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document>"#;
let doc = crate::odt::import_flat(fodt.as_bytes()).unwrap();
let html = crate::html::export(&doc);
assert_eq!(html.matches("<ol").count(), 1, "one list, not restarted: {html}");
let (one, still, two) = (html.find("One").unwrap(), html.find("Still one").unwrap(), html.find("Two").unwrap());
assert!(one < still && still < two, "{html}");
assert!(html[one..still].matches("</li>").count() == 0, "later paragraph left item 1: {html}");
}
+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<rect x="4" y="3" width="12" height="5" rx="1" fill="#F2C811"/>
</svg>

After

Width:  |  Height:  |  Size: 157 B

-1
View File
@@ -1,5 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<rect x="4" y="3" width="12" height="5" rx="1" fill="#F2C811" class="fixed"/>
<rect x="4" y="3" width="12" height="5" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M16 5.5 L17.5 5.5 L17.5 10 L10 10 L10 12" fill="none" stroke="currentColor" stroke-width="1.25"/>
<rect x="8.8" y="12" width="2.4" height="6" rx="1" fill="currentColor"/>

Before

Width:  |  Height:  |  Size: 460 B

After

Width:  |  Height:  |  Size: 380 B

+1
View File
@@ -107,6 +107,7 @@ impl WordApp {
command_states: Default::default(),
command_states_cache: None,
keytip_cache: None,
search_cache: None,
fonts_frames: 0,
clipboard_published: false,
printing: Default::default(),
+11
View File
@@ -147,6 +147,12 @@ const LINKED_EDIT: [craft::ui::runtime::commands::EditCommands; 5] = {
[Cut, Copy, Paste, Undo, Redo]
};
/// The English parts of a registry `location` (`Home › Font`, split as `i18n::location` does); `None` for no place.
pub(crate) fn location_path(location: &str) -> Option<Vec<&str>> {
let path: Vec<&str> = location.split(" › ").filter(|part| !part.is_empty()).collect();
(!path.is_empty()).then_some(path)
}
impl WordApp {
/// The app's commands as the keymap knows them: every engine command with its default
/// chords, then the interface commands. The interface commands come last because a tie in the
@@ -183,6 +189,11 @@ impl WordApp {
// warned about), so their chords go in as the set's replaced defaults (the `LINKED_EDIT` fold below).
for spec in registry.all().iter().filter(|spec| seen.insert(spec.id) && !LINKED_EDIT.iter().any(|c| c.id() == spec.id)) {
let mut def = CommandDef::new(CommandRef::new(spec.id), tl!(spec.label), Scope::app());
// Its ribbon place is its menu path, in English: Customize Keyboard files it under the tab by name,
// and the framework translates each segment where it shows it.
if let Some(path) = location_path(spec.location) {
def = def.with_path(path.into_iter().map(str::to_owned).collect());
}
for binding in default_bindings(spec.shortcut) {
def = def.with_default(binding);
}
+10 -1
View File
@@ -255,7 +255,16 @@ fn side_menu(ui: &mut Ui, band: f32, current: &str, has_document: bool, show_dis
.scroll(Scroll::vertical())
.header(move |ui, _| {
ui.add_space(band);
let _ = IconButton::command(IconSpec::svg(IconId::new("chevronLeft")), BackstagePageCommand::Back).show(ui);
// The side menu place, so the arrow reads in the rail's white ink, not a panel button's dark ink (#7707).
with_env(
ui,
|overrides| {
overrides.values.set(ControlPlace::SideMenu);
},
|ui| {
let _ = IconButton::command(IconSpec::svg(IconId::new("chevronLeft")), BackstagePageCommand::Back).show(ui);
},
);
})
// The community link above About, both at the reading start, as production's bottom links: rows of the side
// menu place too, so they read in the rail's white ink over the brand colour, not a panel button's dark ink.
+5 -2
View File
@@ -146,6 +146,9 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
let ctx = ui.ctx().clone();
let focused = app.canvas.focused(&ctx);
crate::dialogs_smart_art::end_typing_run(app, focused);
// The page keeps the keyboard focus while another window is active, but the caret shows and blinks only in the
// active window: a window in the background asks for no frames to blink it (#7674).
let active = focused && ctx.input(|input| input.focused);
let doc = app.session.layout();
let Some(pl) = place(app, &doc, body.pages) else { return };
@@ -184,7 +187,7 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
};
let ink = |app: &mut WordApp| caret_color_at(app, &doc, pl.page, pl.probe.0, pl.probe.1, zoom_key, dim_body);
let shown = pl.collapsed && focused;
let shown = pl.collapsed && active;
let mut bars: Vec<(Bar, Color32)> = Vec::new();
let mut composition = None;
if focused && !pl.in_equation && !app.canvas.ime_preedit.is_empty() {
@@ -211,7 +214,7 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
ctx.request_repaint();
} else if shown && blink_fading(since_ms / 1000.0, app.canvas.glide.secs()) {
ctx.request_repaint_after(std::time::Duration::from_millis(16));
} else if focused {
} else if active {
ctx.request_repaint_after(std::time::Duration::from_millis(530 - (since_ms as u64 % 530)));
}
}
+60
View File
@@ -2484,3 +2484,63 @@ fn hostile_numbers_are_ignored() {
assert!(h.state().canvas.view.zoom.is_finite() && h.state().canvas.view.zoom > 0.0);
assert!(h.state().canvas.view.offset.0.is_finite() && h.state().canvas.view.offset.1.is_finite());
}
/// A window in the background shows no caret and asks for no frames to blink one (#7674). The page keeps the keyboard
/// focus, so the caret blinks again once the window is active again.
#[test]
fn the_caret_blinks_only_while_the_window_is_active() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("text.insert", json!({"text": "Some text"})).unwrap();
// No glide or fade: the caret's frames are the blink's alone.
a.ui.animations = crate::theme::Animations::Off;
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
for _ in 0..6 {
h.app_frame();
}
assert!(h.state().canvas.focused(&ctx), "the page has the keyboard focus");
let blink = std::time::Duration::from_millis(530);
let next_frame =
|h: &H| h.output().viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |viewport| viewport.repaint_delay);
assert!(next_frame(&h) <= blink, "an active window asks for a frame within a blink");
// The caret is a stroke from its top to its bottom where the layout puts it. The blink runs on the wall clock:
// restarted, it is in its on half for the next 530 ms, so a caret the window draws at all is in the frame after.
let (top, bottom) = {
let app = h.state_mut();
let focus = app.session.sel.focus.clone();
let c = app.session.layout().caret(&focus).expect("the caret has a place");
let mut at = |y| crate::canvas::page_to_screen(app, c.page, c.x, y).expect("the caret's page is on screen");
(at(c.top), at(c.top + c.height))
};
let caret_drawn = |h: &mut H| {
h.state_mut().canvas.glide.restart(craft::platform::clock::monotonic_ms());
h.app_frame();
h.output().shapes.iter().any(|clipped| match &clipped.shape {
egui::Shape::Path(path) => path.points.len() == 2 && path.points[0].distance(top) < 1.5 && path.points[1].distance(bottom) < 1.5,
_ => false,
})
};
assert!(caret_drawn(&mut h), "an active window draws the caret");
h.input_mut().focused = false;
h.event(egui::Event::WindowFocused(false));
for _ in 0..3 {
h.app_frame();
}
assert!(h.state().canvas.focused(&ctx), "the page keeps the keyboard focus");
assert!(next_frame(&h) > blink, "a window in the background asks for no frame to blink the caret");
assert!(!caret_drawn(&mut h), "a window in the background draws no caret");
h.input_mut().focused = true;
h.event(egui::Event::WindowFocused(true));
h.app_frame();
assert!(next_frame(&h) <= blink, "active again, the caret blinks again");
}
+32 -8
View File
@@ -18,12 +18,18 @@ pub(crate) struct ChromeOpen {
pub(crate) undo: bool,
/// The actions marked in the open Undo drop-down; back to none whenever the drop-down is closed.
pub(crate) undo_mark: craft::ui::list::UndoMark,
/// The rows and mark the Undo drop-down had when it closed, drawn through its exit fade: a pick has already
/// undone those steps, so the live history would empty the list as it fades (#8141).
pub(crate) undo_closing: Option<(Vec<String>, craft::ui::list::UndoMark)>,
/// The command search.
pub(crate) search: bool,
/// How the title bar's controls at the end fit the room the leading controls leave them.
pub(crate) title_fit: Fit,
/// How the status bar's controls fit the room the page leaves them.
pub(crate) status_fit: Fit,
/// Cached word count `(document_id, count_key, words)` for [`StatusCount::Words`] so typing
/// avoids full-document text extraction and character scans.
pub(crate) status_words: Option<(u64, u64, usize)>,
}
/// The steps a bar's group of controls takes in a narrow window, from the fullest to the most compact.
@@ -244,6 +250,28 @@ impl WordApp {
wordcraft_engine::cmd::font::warns(font, &shown).then_some(shown)
}
/// The count in `unit` for the status bar, computing only word count when `unit` is
/// [`StatusCount::Words`] and the full [`StatusCounts`] has not already been cached.
pub fn cached_status_count(&mut self, unit: StatusCount) -> usize {
let key = self.session.rev().wrapping_mul(2) | u64::from(self.session.prefs.count_notes);
if self.status_counts.0 == key {
return self.status_counts.1.in_unit(unit);
}
if unit == StatusCount::Words {
let doc_id = self.session.document_id();
if let Some((cached_doc, cached_key, words)) = self.chrome.status_words
&& cached_doc == doc_id
&& cached_key == key
{
return words;
}
let words = self.session.word_count();
self.chrome.status_words = Some((doc_id, key, words));
return words;
}
self.cached_status_counts().in_unit(unit)
}
/// The document's counts, recomputed only when the document (or the count option) changes:
/// words as the status bar and the Word Count dialog count them, and characters with and
/// without spaces as the dialog does (#2797).
@@ -252,14 +280,10 @@ impl WordApp {
let key = self.session.rev().wrapping_mul(2) | u64::from(self.session.prefs.count_notes);
if self.status_counts.0 != key {
let text = self.session.counted_text();
self.status_counts = (
key,
StatusCounts {
words: self.session.word_count(),
chars: wordcraft_doc::count_chars(&text),
chars_no_spaces: wordcraft_doc::count_chars_no_spaces(&text),
},
);
let words = self.session.word_count();
self.chrome.status_words = Some((self.session.document_id(), key, words));
self.status_counts =
(key, StatusCounts { words, chars: wordcraft_doc::count_chars(&text), chars_no_spaces: wordcraft_doc::count_chars_no_spaces(&text) });
}
self.status_counts.1
}
+56 -9
View File
@@ -1,18 +1,45 @@
//! Command search: a `CommandPalette` in its in-place face, over the registry's commands.
use std::sync::Arc;
use craft::behavior::IconId;
use craft::keymap::CommandRef;
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Bind, Props as _, Show as _, TooltipSpec};
use craft::ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms};
use craft::ui::patterns::panels::{CommandPalette, PaletteFace};
use craft::ui::runtime::env::{Env, Label, WordTemplate};
use craft::ui::runtime::env::{Env, EnvView, Label, WordTemplate};
use craft::ui::runtime::inspect;
use egui::Ui;
use serde_json::json;
use crate::WordApp;
/// The search's entries and their index, kept between passes. Building the index folds every command's labels, so it
/// is built again only when the commands or the interface language change, not in every pass the field shows.
pub(crate) struct SearchCache {
registry: Arc<wordcraft_engine::Registry>,
lang: &'static str,
entries: Vec<HelpEntry>,
pub(crate) index: Arc<SearchIndex>,
}
impl SearchCache {
/// `kept` while it was built from `app`'s registry in the current language, else the entries and index built
/// again, their labels resolved and folded as `view` reads them.
fn for_pass(kept: Option<SearchCache>, app: &WordApp, view: &EnvView<'_>) -> SearchCache {
let lang = crate::i18n::current().code();
match kept {
Some(cache) if cache.lang == lang && Arc::ptr_eq(&cache.registry, &app.session.registry) => cache,
_ => {
let entries = help_entries(app);
let index = Arc::new(SearchIndex::new(view, &entries, &Synonyms::of(&view.words::<SearchWords>())));
SearchCache { registry: Arc::clone(&app.session.registry), lang, entries, index }
}
}
}
}
/// One help entry for each registry command Search offers: its label, with the English label so a search in
/// English finds it in any language. Paper Color opens the selector in Options instead of running with no
/// value, since Search is an interactive entry point.
@@ -25,7 +52,11 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
.map(|c| {
let command =
if c.id == "view.paperColor" { CommandRef::with_params("file.options", json!({"pane": "general"})) } else { CommandRef::new(c.id) };
HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string())
let entry = HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string());
match crate::app::command_board::location_path(c.location) {
Some(path) => entry.with_path(path.into_iter().map(|part| tl!(part).to_string())),
None => entry,
}
})
.collect()
}
@@ -49,13 +80,14 @@ pub(crate) fn is_open(app: &WordApp) -> bool {
/// rect it took. `compact` (a narrow window, #5886) shows the magnifier alone, and the search opens as a box over
/// the window, since the bar has no room for the field.
pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect {
// Built in every pass the field runs: the palette opens inside its own `show`, so the entries are there before
// it knows. The list lives for the pass only.
let entries = help_entries(app);
// There in every pass the field runs: the palette opens inside its own `show`, so the entries are there before
// it knows. They and their index are kept between passes ([`SearchCache`]).
let kept = app.search_cache.take();
let suggested: Vec<CommandRef> = crate::dialogs::SEARCH_SUGGESTIONS.iter().map(|id| CommandRef::new(*id)).collect();
let mut open = app.chrome.search;
let name = tl!("Search commands and help").to_string();
let ((rect, out), _) = inspect::record(ui, crate::keytips::search_region(), |ui| {
let commands: &WordApp = app;
let ((rect, out, cache), _) = inspect::record(ui, crate::keytips::search_region(), |ui| {
let mut rect = None;
if compact {
let button = IconButton::new(IconId::new("wordcraft.search")).label(name.clone()).tooltip(TooltipSpec::new(name.clone())).show(ui);
@@ -66,18 +98,33 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
}
let env = Env::of(ui);
let view = env.view();
let index = SearchIndex::new(&view, &entries, &Synonyms::of(&view.words::<SearchWords>()));
let out = CommandPalette::new(name.clone(), &entries, &index, Bind::bound(&mut open))
let cache = SearchCache::for_pass(kept, commands, &view);
let out = CommandPalette::new(name.clone(), &cache.entries, &cache.index, Bind::bound(&mut open))
.face(if compact { PaletteFace::Dialog } else { PaletteFace::InPlace })
.placeholder(Label::from(name.clone()))
.suggested((Label::from(tl!("Suggested").to_string()), suggested))
.fallback(WordTemplate::new(tl!("Find “{text}” in the document")))
.show(ui);
(rect.unwrap_or(out.response.rect), out)
(rect.unwrap_or(out.response.rect), out, cache)
});
app.search_cache = Some(cache);
app.chrome.search = open;
if let Some(text) = out.fallback {
crate::dialogs::find_in_navigation_pane(app, ui.ctx(), &text);
}
rect
}
#[cfg(test)]
mod tests {
use crate::{Services, WordApp};
/// #7983: a search result names the ribbon place of its command.
#[test]
fn search_entries_show_the_ribbon_location() {
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
let entries = super::help_entries(&app);
let bold = entries.iter().find(|e| e.command().id == "format.bold").expect("format.bold is searchable");
assert!(!bold.path().is_empty(), "the entry has a path");
}
}
+3 -3
View File
@@ -121,13 +121,13 @@ fn readouts(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
/// without spaces, whichever was chosen (#2797). A click opens Word Count; a right click the choice.
fn count(app: &mut WordApp, ui: &mut Ui) {
let unit = app.ui.status_count;
let counts = app.cached_status_counts();
let total = app.cached_status_count(unit);
// A selected picture/shape/text box isn't a text selection: show the total.
let text = if app.session.sel.is_collapsed() || crate::objects::selected(app).is_some() {
status_count_text(unit, counts.in_unit(unit), None)
status_count_text(unit, total, None)
} else {
let selected = crate::count_in_unit(&app.session.selected_text(), unit);
status_count_text(unit, counts.in_unit(unit), Some(selected))
status_count_text(unit, total, Some(selected))
};
let out = item(ui, text, None);
if out.clicked() {
+66
View File
@@ -249,6 +249,37 @@ fn the_status_bar_totals_are_the_word_count_dialogs_numbers() {
assert_eq!(line(StatusCount::CharactersNoSpaces), "6 of 21 characters (no spaces)");
}
#[test]
fn cached_status_count_words_matches_full_counts_across_edits() {
let mut a = new_app();
a.run("text.insert", json!({"text": "one two"})).unwrap();
assert_eq!(a.cached_status_count(StatusCount::Words), 2);
a.run("text.insert", json!({"text": " three four"})).unwrap();
assert_eq!(a.cached_status_count(StatusCount::Words), 4);
assert_eq!(a.cached_status_count(StatusCount::Words), a.cached_status_counts().words);
assert_eq!(a.cached_status_count(StatusCount::Characters), a.cached_status_counts().chars);
}
#[test]
fn previews_style_gallery_reuses_arc_until_styles_change() {
let mut a = new_app();
let rev = a.session.rev();
let first = a.previews.style_gallery(&a.session.doc, rev);
let second = a.previews.style_gallery(&a.session.doc, rev);
assert!(std::sync::Arc::ptr_eq(&first, &second), "same rev should reuse cached style gallery Arc");
assert!(!first.is_empty());
a.run("text.insert", json!({"text": "changed"})).unwrap();
let typed = a.previews.style_gallery(&a.session.doc, a.session.rev());
assert!(std::sync::Arc::ptr_eq(&second, &typed), "text edit with identical style sheet reuses gallery Arc");
a.run("styles.create", json!({"name": "Stage7TestStyle", "fromSelection": false})).unwrap();
let updated = a.previews.style_gallery(&a.session.doc, a.session.rev());
assert!(!std::sync::Arc::ptr_eq(&typed, &updated), "changing styles refreshes style gallery");
assert!(updated.iter().any(|(_, name)| name == "Stage7TestStyle"));
}
/// The status bar's actions, through its menus by name: the count row sets the unit and is kept between
/// runs, Overtype switches back to inserting.
#[test]
@@ -1126,3 +1157,38 @@ fn status_bar_view_mode_toggles_and_zoom_slider_proportions() {
});
assert!(has_14pt_knob, "Zoom slider should paint a {glyph_md} pt thumb (ControlSize::Md) matching 14 pt IconButton icons inside {slider:?}");
}
/// The title bar's command search keeps its entries and their index between passes: building the index folds every
/// command's labels, and an idle window repaints for its caret (#7674). New commands, or another interface language,
/// build it again.
#[test]
fn the_title_bar_search_keeps_its_index_until_the_commands_or_the_language_change() {
struct ResetLang;
impl Drop for ResetLang {
fn drop(&mut self) {
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
}
let _reset = ResetLang;
let index = |h: &egui_kittest::Harness<'static, WordApp>| {
h.state().search_cache.as_ref().map(|cache| std::sync::Arc::clone(&cache.index)).expect("the title bar's search has its index")
};
let mut h = harness(new_app());
let built = index(&h);
crate::test_harness::frames(&mut h, 4);
assert!(std::sync::Arc::ptr_eq(&built, &index(&h)), "idle passes keep the index");
let same_commands = wordcraft_engine::Registry::new(h.state().session.registry.all().to_vec());
h.state_mut().session.registry = std::sync::Arc::new(same_commands);
crate::test_harness::frames(&mut h, 1);
let rebuilt = index(&h);
assert!(!std::sync::Arc::ptr_eq(&built, &rebuilt), "a new command registry builds it again");
if crate::i18n::catalogs_embedded() {
h.state_mut().run("ui.language", json!({"value": "de"})).unwrap();
crate::test_harness::frames(&mut h, 2);
assert_eq!(crate::i18n::current().code(), "de");
assert!(!std::sync::Arc::ptr_eq(&rebuilt, &index(&h)), "another interface language builds it again");
}
}
+21 -12
View File
@@ -163,14 +163,19 @@ const UNDO_ROWS_SHOWN: u16 = 8;
fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
// The small filled triangle of the old toolbar.
let out = IconButton::new(IconSpec::glyph(&crate::ribbon::common::MENU_ARROW)).label(tl!("Undo History").to_string()).enabled(enabled).show(ui);
let labels = undo_list_rows(app);
let mut open = app.chrome.undo;
if out.response.clicked() {
open = !open;
}
let mut mark = app.chrome.undo_mark;
let was_open = app.chrome.undo;
// Through the exit fade the list draws what it had when it closed.
let closing = if open { None } else { app.chrome.undo_closing.take() };
let mut mark = closing.as_ref().map_or(app.chrome.undo_mark, |(_, m)| *m);
let mut picked = None;
let mut drawn = None;
Popover::new(tl!("Undo History").to_string(), Bind::bound(&mut open)).opened_by(&out.response).show(ui, |ui, cx| {
// Built inside the body, which runs only while the popover shows or fades.
let labels = closing.as_ref().map_or_else(|| undo_list_rows(app), |(l, _)| l.clone());
let rows = UndoRows::new(&labels);
// A collection owns its scroll: the popover's body scrolls, so the list caps its rows and scrolls the rest.
let events = UndoList::new(tl!("Undo History").to_string())
@@ -178,6 +183,7 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
.selection(Bind::bound(&mut mark))
.show_items(ui, &rows, &mut |key, _| rows.row(*key))
.events;
drawn = Some(labels.clone());
if let Some(count) = undo_count(&events) {
picked = Some(count);
cx.request_close();
@@ -198,6 +204,11 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
});
app.chrome.undo = open;
app.chrome.undo_mark = if open { mark } else { UndoMark::default() };
app.chrome.undo_closing = match (open, was_open) {
(true, _) => None,
(false, true) => drawn.map(|l| (l, mark)),
(false, false) => closing,
};
if let Some(count) = picked {
let _ = app.run("edit.undoTo", json!({"count": count}));
// Picking a row closes the Undo History popover on its foreground layer; return keyboard
@@ -213,19 +224,17 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
fn qat_menu(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
let out =
IconButton::new(IconId::new("wordcraft.more")).label(tl!("Customize Quick Access Toolbar").to_string()).glyphs(GlyphRole::Tool).show(ui);
let shown: Vec<(&'static str, String, bool)> = QAT_MENU
.iter()
.filter_map(|id| {
let label = app.session.registry.get(id).map(|s| tl!(s.label).to_string())?;
Some((*id, label, app.session.ribbon.qat().contains(id)))
})
.collect();
// No `open` binding: with one the framework leaves the opening to the app, without it the opener opens the menu.
Menu::new(tl!("Customize Quick Access Toolbar").to_string()).opened_by(&out.response, Trigger::Click).show(ui, |ui, _| {
MenuItem::heading(tl!("Customize Quick Access Toolbar").to_string()).show(ui);
for (id, label, on) in &shown {
let key = if *on { "qatRemove" } else { "qatAdd" };
MenuItem::command(CommandRef::with_params("tools.customizeRibbon", json!({ key: *id }))).label(label.clone()).check(*on).show(ui);
for &id in &QAT_MENU {
let Some(spec) = app.session.registry.get(id) else { continue };
let on = app.session.ribbon.qat().contains(&id);
let key = if on { "qatRemove" } else { "qatAdd" };
MenuItem::command(CommandRef::with_params("tools.customizeRibbon", json!({ key: id })))
.label(tl!(spec.label).to_string())
.check(on)
.show(ui);
}
Divider::horizontal().show(ui);
MenuItem::command(CommandRef::with_params("ui.dialog", json!({"name": "customizeQuickAccess"})))
+207 -36
View File
@@ -17,10 +17,10 @@ use craft::ui::choice::{CellMarks, SwatchTable};
use craft::ui::contract::{BodyCx, Hover, NoValue, Props as _, Show as _, clicked};
use craft::ui::dialog::{DialogId, DialogResult};
use craft::ui::menu::{MenuItem, MenuItemOutput};
use craft::ui::primitives::{IconMark, IconSpec};
use craft::ui::primitives::{Glyph, IconMark, IconSpec, StrokeWidth};
use craft::ui::runtime::env::Label;
use craft::ui::style::DataColor;
use egui::{Color32, Ui};
use craft::ui::style::{DataColor, UiTokens};
use egui::{Color32, Painter, Rect, Stroke, StrokeKind, Ui, vec2};
use serde_json::{Value, json};
use wordcraft_doc::Rgb;
@@ -241,18 +241,76 @@ pub fn apply(app: &mut WordApp, target: &Target, hex: &str) {
}
}
/// The colour a target has now (the dialog's Current swatch).
/// The colour every item has, `None` for no items, no colour, or items that differ.
fn agree(mut colors: impl Iterator<Item = Option<Rgb>>) -> Option<Rgb> {
let first = colors.next()??;
colors.all(|c| c == Some(first)).then_some(first)
}
/// The shading the given cells share; cells a ragged table lacks are skipped, not read as unshaded.
fn cell_shading(table: &wordcraft_doc::Table, cells: impl IntoIterator<Item = (usize, usize)>) -> Option<Rgb> {
agree(cells.into_iter().filter_map(|(r, c)| table.rows.get(r)?.cells.get(c).map(|cell| cell.props.shading)))
}
/// The colour a target has now (the dialog's Current swatch), read from what its command changes:
/// `para.shading` reads the selected text's shading when the selection is text within one paragraph,
/// else the paragraphs'; `shape.effects` reads shapes only. `None` when it has none, is Automatic,
/// differs across the selection, or cannot be read (a picture's icon colour is not stored).
fn current_of(app: &mut WordApp, target: &Target) -> Option<Rgb> {
use wordcraft_doc::InlineObject;
let Target::Run { cmd, .. } = target else { return None };
let s = &app.session;
let shapes = |o: &InlineObject| matches!(o, InlineObject::Shape { .. }) || o.is_canvas();
let objects = || wordcraft_engine::cmd::objects::target_objects(s, shapes).into_iter().map(|(_, o)| o);
match cmd.as_str() {
"format.color" => {
let st = wordcraft_engine::cmd::format::state(&app.session);
st.get("color").and_then(Value::as_str).and_then(parse)
"format.color" | "format.underlineColor" => {
let st = wordcraft_engine::cmd::format::cached_state(s);
let key = if cmd == "format.color" { "color" } else { "underlineColor" };
st.get(key).and_then(Value::as_str).and_then(parse)
}
// The command shades the selected text, not its paragraph, when the selection is text within one.
"para.shading" if wordcraft_engine::cmd::para::shades_text(s) => {
wordcraft_engine::cmd::format::cached_state(s).get("shading").and_then(Value::as_str).and_then(parse)
}
"para.shading" => agree(
wordcraft_engine::cmd::selected_paths(s)
.iter()
.map(|path| s.doc.para(s.sel.focus.story, path).and_then(|p| s.doc.styles.resolve_para(&p.props).shading)),
),
"table.shading" => {
let (tp, _, _) = s.sel.focus.path.cell()?;
let table = s.doc.table(s.sel.focus.story, &tp)?;
cell_shading(table, wordcraft_engine::cmd::table::selected_cells(s))
}
"design.pageColor" => s.doc.settings.page_color,
"shape.fill" => agree(objects().map(|o| {
let fill = match &o {
InlineObject::Shape { fill, .. } => fill.as_ref(),
o => o.canvas_style().and_then(|c| c.fill.as_ref()),
};
match fill {
Some(wordcraft_doc::fill::Fill::Solid { color, .. }) => Some(*color),
_ => None,
}
})),
"shape.outline" => agree(objects().map(|o| match &o {
InlineObject::Shape { stroke, .. } => *stroke,
o => o.canvas_style().and_then(|c| c.stroke),
})),
// Glow is applied to shapes only, so a canvas in the selection is not read.
"shape.effects" => agree(objects().filter(|o| matches!(o, InlineObject::Shape { .. })).map(|o| match &o {
InlineObject::Shape { effects, .. } => effects.glow.as_ref().map(|g| g.color),
_ => None,
})),
_ => None,
}
}
/// Whether the selection's font colour is uniformly Automatic.
fn current_is_auto(app: &WordApp) -> bool {
wordcraft_engine::cmd::format::state(&app.session).get("color").and_then(Value::as_str) == Some("auto")
}
/// The colour a split button's main part applies: what its target remembers, else what is in effect.
fn remembered(app: &mut WordApp, target: &Target) -> Option<Rgb> {
match target {
@@ -287,9 +345,9 @@ pub struct ColorPick {
pub response: egui::Response,
/// The colour picked in this pass.
pub picked: Option<Rgb>,
/// What the pointer over a swatch did to the live preview: it shows while the pointer is over a
/// swatch and ends when it leaves.
pub preview: craft::behavior::Preview<Rgb>,
/// What the pointer over a swatch or menu choice did to the live preview: `Some(c)` for a
/// palette colour, `None` for Automatic / No Color, and `Ended` when the pointer leaves.
pub preview: craft::behavior::Preview<Option<Rgb>>,
/// The main part's stay of a split button; `Hover::default()` for a body without one.
pub hover: Hover,
}
@@ -318,9 +376,9 @@ fn swatch_table(
(picked, preview, out.response)
}
/// Two previews of one pass: a start wins over an end, as the pointer moving from one table to
/// Two previews of one pass: a start wins over an end, as the pointer moving from one control to
/// the next ends one and starts the other.
fn merge_preview(a: craft::behavior::Preview<Rgb>, b: craft::behavior::Preview<Rgb>) -> craft::behavior::Preview<Rgb> {
fn merge_preview<T>(a: craft::behavior::Preview<T>, b: craft::behavior::Preview<T>) -> craft::behavior::Preview<T> {
use craft::behavior::Preview;
match (a, b) {
(Preview::Shows(c), _) | (_, Preview::Shows(c)) => Preview::Shows(c),
@@ -329,6 +387,26 @@ fn merge_preview(a: craft::behavior::Preview<Rgb>, b: craft::behavior::Preview<R
}
}
/// Tracks hover preview transitions for a single `MenuItem` inside a colour drop-down so hovering
/// it previews `None` and leaving or closing the drop-down ends the preview.
fn item_preview(ctx: &egui::Context, key: egui::Id, hovered: bool, open: bool) -> craft::behavior::Preview<Option<Rgb>> {
use craft::behavior::Preview;
let was = ctx.data(|d| d.get_temp::<bool>(key)).unwrap_or(false);
if !open {
if was {
ctx.data_mut(|d| d.remove::<bool>(key));
return Preview::Ended;
}
return Preview::Unchanged;
}
if hovered != was {
ctx.data_mut(|d| d.insert_temp(key, hovered));
if hovered { Preview::Shows(None) } else { Preview::Ended }
} else {
Preview::Unchanged
}
}
/// The theme and recent swatches of `palette`; the colour in effect carries the selection mark.
fn swatches(ui: &mut Ui, palette: &Palette, current: Option<Rgb>) -> (Option<Rgb>, craft::behavior::Preview<Rgb>) {
let (mut picked, mut preview, _) = swatch_table(ui, "Theme Colors", &palette.theme, THEME_PER_ROW, current);
@@ -360,7 +438,7 @@ pub fn palette(ui: &mut Ui, app: &mut WordApp, target: Target) -> ColorPick {
if more.ran {
open_for(app, &target, current, ColorPickerTab::Standard);
}
ColorPick { response: more.response, picked, preview, hover: Hover::default() }
ColorPick { response: more.response, picked, preview: preview.map(Some), hover: Hover::default() }
}
/// A command colour drop-down's body: [`palette`]; the caller closes the drop-down.
@@ -390,30 +468,33 @@ enum Above {
}
/// A split button whose main part runs `main` and whose arrow opens `body`.
/// `body` returns its `ColorPick` and whether its `Automatic` / `No Color` item is hovered.
fn split_with(
ui: &mut Ui,
app: &mut WordApp,
label: Label,
icon: IconSpec<'static>,
main: CommandRef,
mut body: impl FnMut(&mut Ui, &mut WordApp, &mut BodyCx<'_>) -> ColorPick,
mut body: impl FnMut(&mut Ui, &mut WordApp, &mut BodyCx<'_>) -> (ColorPick, bool),
) -> ColorPick {
let mut inner: Option<(Option<Rgb>, craft::behavior::Preview<Rgb>)> = None;
let mut inner: Option<(Option<Rgb>, craft::behavior::Preview<Option<Rgb>>, bool)> = None;
// The arrow is its own button, named "<label> options" so it is told from the main part (#3172).
let arrow_name = crate::i18n::fmt(tl!("{name} options"), &[("name", label.as_str())]);
let out = SplitButton::<NoValue>::command(
main,
SplitMenu::Body(Box::new(|ui: &mut Ui, cx: &mut BodyCx<'_>| {
let pick = body(ui, app, cx);
inner = Some((pick.picked, pick.preview));
let (pick, empty_hovered) = body(ui, app, cx);
inner = Some((pick.picked, pick.preview, empty_hovered));
})),
)
.label(label)
.arrow_label(arrow_name)
.icon(icon)
.show(ui);
let (picked, preview) = inner.unwrap_or((None, craft::behavior::Preview::Unchanged));
ColorPick { response: out.response, picked, preview, hover: out.hover }
let open = inner.is_some();
let (picked, swatch_preview, empty_hovered) = inner.unwrap_or((None, craft::behavior::Preview::Unchanged, false));
let empty_preview = item_preview(ui.ctx(), out.response.id.with("empty_hover"), empty_hovered, open);
ColorPick { response: out.response, picked, preview: merge_preview(swatch_preview, empty_preview), hover: out.hover }
}
/// The split button of a colour `target`: the icon of its command with a bar of the remembered
@@ -433,24 +514,29 @@ fn color_split(ui: &mut Ui, app: &mut WordApp, label: Label, target: Target, abo
_ => CommandRef::new(cmd.clone()),
};
split_with(ui, app, label, icon, main, |ui, app, cx| {
let mut empty_hovered = false;
match above {
Above::Nothing => {}
Above::Automatic => {
let auto = CommandRef::with_params("format.color", json!({"color": "auto"}));
if MenuItem::new(tl!("Automatic").to_string()).command(auto).show(ui).ran {
let item = MenuItem::new(tl!("Automatic").to_string()).command(auto).check(current_is_auto(app)).show(ui);
if item.ran {
cx.request_close();
}
empty_hovered = item.response.hovered() && !item.ran;
}
Above::NoColor => {
let none = CommandRef::with_params(cmd.clone(), json!({"color": null}));
if MenuItem::new(tl!("No Color").to_string()).command(none).show(ui).ran {
let item = MenuItem::new(tl!("No Color").to_string()).command(none).show(ui);
if item.ran {
cx.request_close();
}
empty_hovered = item.response.hovered() && !item.ran;
}
}
let pick = menu(ui, app, target.clone());
close_after(&pick, cx);
pick
(pick, empty_hovered)
})
}
@@ -480,17 +566,15 @@ pub(crate) fn highlight_button_appearance(name: &str) -> (&'static str, Option<C
/// The highlight drop-down: the highlight colours five to a row, then No Color. A pick, No Color
/// too, becomes the split button's colour, as in Word: after No Color a click on the button
/// removes highlighting (#2105).
fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> ColorPick {
fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> (ColorPick, bool) {
use wordcraft_doc::props::Highlight;
let in_effect = Some(wordcraft_engine::cmd::format::state(&app.session))
.and_then(|st| st.get("highlight").and_then(Value::as_str).map(str::to_string))
.unwrap_or_else(|| "none".into());
let in_effect = wordcraft_engine::cmd::format::uniform_highlight(&app.session);
let shown: Vec<(&Highlight, Rgb)> = Highlight::ALL.iter().skip(1).filter_map(|h| h.rgb().map(|c| (h, c))).collect();
let swatches: Vec<(Label, Srgba)> = shown.iter().map(|(h, c)| (Label::from(tl!(h.name()).to_string()), srgba(*c))).collect();
let out = SwatchTable::new("Highlight Colors".to_string(), &swatches)
.per_row(5)
.tips(true)
.marks(|i: &usize| CellMarks::default().edge(shown.get(*i).is_some_and(|(h, _)| h.ooxml() == in_effect)))
.marks(|i: &usize| CellMarks::default().edge(shown.get(*i).is_some_and(|(_, c)| in_effect == Some(Some(*c)))))
.show_all(ui);
let mut picked = None;
if let Some((h, c)) = out.selected.and_then(|i| shown.get(i)) {
@@ -500,16 +584,20 @@ fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> ColorP
cx.request_close();
}
let preview = match out.preview {
craft::behavior::Preview::Shows(i) => shown.get(i).map_or(craft::behavior::Preview::Unchanged, |(_, c)| craft::behavior::Preview::Shows(*c)),
craft::behavior::Preview::Shows(i) => {
shown.get(i).map_or(craft::behavior::Preview::Unchanged, |(_, c)| craft::behavior::Preview::Shows(Some(*c)))
}
craft::behavior::Preview::Ended => craft::behavior::Preview::Ended,
_ => craft::behavior::Preview::Unchanged,
};
let none = CommandRef::with_params("format.highlight", json!({"color": "none"}));
if MenuItem::new(tl!("No Color").to_string()).command(none).show(ui).ran {
let no_color = MenuItem::new(tl!("No Color").to_string()).command(none).check(in_effect == Some(None)).show(ui);
if no_color.ran {
app.canvas.last_highlight = "none".into();
cx.request_close();
}
ColorPick { response: out.response, picked, preview, hover: Hover::default() }
let empty_hovered = no_color.response.hovered() && !no_color.ran;
(ColorPick { response: out.response, picked, preview, hover: Hover::default() }, empty_hovered)
}
/// Text Highlight Color: the highlight grid under the arrow; the main part applies the remembered
@@ -529,14 +617,15 @@ pub fn highlight_split(ui: &mut Ui, app: &mut WordApp, label: impl Into<Label>)
// More Colors…
/// The Colors dialog: Standard honeycomb and greys, Custom compact picker. `current` is the colour
/// the target has now; `key` comes back in the result.
/// the target has now, `None` when it has none: Current then shows no colour (as in v0.19.1) and
/// Restore does nothing, while New starts on black. `key` comes back in the result.
pub fn more_colors(current: Option<Rgb>, key: String, tab: ColorPickerTab) -> ColorPickerDialog {
let (cells, greys) = standard_cells();
ColorPickerDialog::new(key, tl!("Colors").to_string(), current.map_or(Srgba::rgb(0.0, 0.0, 0.0), srgba))
let dialog = ColorPickerDialog::new(key, tl!("Colors").to_string(), current.map_or(Srgba::rgb(0.0, 0.0, 0.0), srgba))
.layout(ColorPickerDialogLayout::Tabbed)
.standard(cells, greys)
.compare(current.is_some())
.tab(tab)
.tab(tab);
if current.is_some() { dialog } else { dialog.no_current() }
}
/// Opens the Colors dialog for `target`, remembering where its answer goes.
@@ -613,6 +702,23 @@ pub enum AutoFace {
Several(Vec<Srgba>),
}
/// The swatch of a choice of several colours (By author): the colours side by side in equal shares, framed as a one-colour
/// swatch is.
#[derive(craft::ui::contract::MemoProps)]
struct SwatchShares(Vec<Srgba>);
impl Glyph for SwatchShares {
fn paint(&self, painter: &Painter, tokens: &UiTokens, rect: Rect, color: Color32, _mirrored: bool) {
let width = rect.width() / self.0.len().max(1) as f32;
for (at, share) in self.0.iter().enumerate() {
let part = Rect::from_min_size(rect.min + vec2(width * at as f32, 0.0), vec2(width, rect.height()));
painter.rect_filled(part, 0.0, color32(rgb_of(*share)));
}
let stroke = Stroke::new(StrokeWidth::Thin.points(tokens, painter.pixels_per_point()), color);
painter.rect_stroke(rect, 0.0, stroke, StrokeKind::Inside);
}
}
/// What a colour field did in a pass.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ColorFieldResponse {
@@ -630,7 +736,7 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
let (shown, text) = match (current, empty) {
(Some(c), _) => (Some(srgba(c)), Label::from(c.hex())),
(None, ColorFieldEmpty::NoColor) => (None, Label::from(tl!("No Color").to_string())),
// PLAN: framework gap: `IconSpec` has no multi-share swatch face, so `AutoFace::Several` shows its first colour until `IconSource` can paint `SwatchFace` shares (ribbon-w2).
// Two or more `AutoFace::Several` colours paint as `SwatchShares` (below); a single one paints as itself.
(None, ColorFieldEmpty::Automatic { label, face, .. }) => (
match face {
AutoFace::One(c) => Some(*c),
@@ -639,7 +745,14 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
label.clone(),
),
};
let icon = shown.map_or_else(IconSpec::empty_swatch, IconSpec::swatch);
let shares = match (current, empty) {
(None, ColorFieldEmpty::Automatic { face: AutoFace::Several(colors), .. }) if colors.len() > 1 => Some(SwatchShares(colors.clone())),
_ => None,
};
let icon = match &shares {
Some(shares) => IconSpec::glyph(shares),
None => shown.map_or_else(IconSpec::empty_swatch, IconSpec::swatch),
};
let spoken_value = current.map_or_else(|| text.as_str().to_string(), |c| format!("#{}", c.hex()));
let spoken = format!("{} {spoken_value}", label.as_str());
let field = SplitButton::<NoValue>::body(text, |ui: &mut Ui, cx: &mut BodyCx<'_>| {
@@ -766,4 +879,62 @@ mod tests {
assert_eq!(app.ui.recent_colors.first().map(String::as_str), Some("7A3EC8"));
assert!(app.more_colors.is_empty(), "no entry outlives its dialog");
}
/// The Current swatch reads what the selection has, and says "no colour" where there is none or it
/// differs (#7984).
#[test]
fn current_reads_the_selection_and_is_none_when_unset_or_mixed() {
let c = |hex: u8| Rgb(hex, hex, hex);
assert_eq!(agree([Some(c(1)), Some(c(1))].into_iter()), Some(c(1)), "all alike");
assert_eq!(agree([Some(c(1)), Some(c(2))].into_iter()), None, "mixed");
assert_eq!(agree([Some(c(1)), None].into_iter()), None, "one has none");
assert_eq!(agree(std::iter::empty()), None, "nothing selected");
// Set on the caret's paragraph directly: the commands lay the page out, which costs ~0.7 s.
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
let shading = Target::cmd("para.shading");
assert_eq!(current_of(&mut app, &shading), None, "no shading yet");
assert_eq!(current_of(&mut app, &Target::cmd("table.shading")), None, "no table, no colour");
assert_eq!(current_of(&mut app, &Target::cmd("shape.fill")), None, "no shape selected");
let at = app.session.sel.focus.clone();
app.session.doc.para_mut(at.story, &at.path).unwrap().props.shading = Some(c(0xAA));
assert_eq!(current_of(&mut app, &shading), Some(c(0xAA)), "a collapsed caret reads its paragraph");
}
/// Text selected inside a paragraph is what Shading changes, so Current must not report the
/// paragraph's shading for it (#7984).
#[test]
fn partial_selection_reads_the_text_shading_not_the_paragraph() {
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("hello world")), crate::Services::default());
let at = app.session.sel.focus.clone();
app.session.doc.para_mut(at.story, &at.path).unwrap().props.shading = Some(Rgb(0xAA, 0xAA, 0xAA));
let mut end = at.clone();
end.off = 5;
app.session.sel = wordcraft_engine::Selection { anchor: at, focus: end };
let shading = Target::cmd("para.shading");
assert_eq!(current_of(&mut app, &shading), None, "the text has no shading, whatever its paragraph has");
let _ = app.session.run("format.shading", &json!({"color": "112233"}));
assert_eq!(current_of(&mut app, &shading), Some(Rgb(0x11, 0x22, 0x33)), "the selected run's shading");
}
/// A ragged table's missing cells do not blank Current when the real cells agree (#7984).
#[test]
fn table_shading_skips_missing_cells() {
let mut t = wordcraft_doc::Table::new(2, 2, 100.0);
t.rows[1].cells.pop();
for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
cell.props.shading = Some(Rgb(1, 2, 3));
}
let all = [(0, 0), (0, 1), (1, 0), (1, 1)];
assert_eq!(cell_shading(&t, all), Some(Rgb(1, 2, 3)), "the missing (1,1) is skipped");
t.rows[0].cells[1].props.shading = None;
assert_eq!(cell_shading(&t, all), None, "a real unshaded cell still blanks it");
}
/// A target with no colour opens with no Current colour, not black (#7984).
#[test]
fn no_current_colour_is_not_black() {
assert!(more_colors(None, "k".into(), ColorPickerTab::Standard).has_no_current());
assert!(!more_colors(Some(Rgb(0, 0, 0)), "k".into(), ColorPickerTab::Standard).has_no_current(), "a real black stays a current colour");
}
}
@@ -5,10 +5,11 @@
//! through `tools.customizeKeyboard`, so agents get the same result without the dialog.
use craft::keymap::{Binding, CommandDef, Keymap, Overrides};
use craft::menu::shortcuts::{DialogState, Layout, Options, Outcome, ShortcutsDialog};
use craft::menu::shortcuts::{Area, DialogState, Layout, Options, Outcome, ShortcutsDialog};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use egui::{Context, Ui};
use serde_json::{Value, json};
use wordcraft_engine::ribbon::{CONTEXTUAL_TABS, TABS};
use super::host::{DialogHooks, Settle, open_with};
use crate::WordApp;
@@ -49,11 +50,61 @@ fn assignable(binding: &Binding) -> bool {
chord.mods.cmd || chord.mods.ctrl || chord.mods.alt || chord.is_function_key()
}
/// The ribbon tab a command lives on, in English (the first part of its path).
fn tab(def: &CommandDef) -> &str {
def.paths.first().and_then(|path| path.first()).map_or("", String::as_str)
}
/// Tabs that come up with the selection or a view, besides the engine's contextual ones; they share one Categories entry.
const EXTRA_CONTEXT_TABS: [&str; 3] = ["Header & Footer", "Outlining", "Reading"];
fn in_tab<const N: usize>(def: &CommandDef) -> bool {
tab(def) == TABS[N]
}
fn in_context_tab(def: &CommandDef) -> bool {
CONTEXTUAL_TABS.contains(&tab(def)) || EXTRA_CONTEXT_TABS.contains(&tab(def))
}
fn in_no_tab(def: &CommandDef) -> bool {
!TABS.contains(&tab(def)) && !in_context_tab(def)
}
/// One filter per entry of `TABS` (the array's length makes the compiler check it).
const TAB_FILTERS: [fn(&CommandDef) -> bool; TABS.len()] = [
in_tab::<0>,
in_tab::<1>,
in_tab::<2>,
in_tab::<3>,
in_tab::<4>,
in_tab::<5>,
in_tab::<6>,
in_tab::<7>,
in_tab::<8>,
in_tab::<9>,
in_tab::<10>,
in_tab::<11>,
in_tab::<12>,
];
/// Categories as Word lists them: the ribbon tabs (not the framework's menu and panel ids), the contextual tabs, the
/// rest, then All Commands.
fn areas() -> Vec<Area> {
let mut areas: Vec<Area> = TABS.iter().copied().zip(TAB_FILTERS).map(|(name, rows)| Area::new(name, tl!(name), rows)).collect();
areas.push(Area::new("Contextual Tabs", tl!("Contextual Tabs"), in_context_tab));
areas.push(Area::new("Other", tl!("Other"), in_no_tab));
areas.push(Area::new("All Commands", tl!("All Commands"), |_| true));
areas
}
/// The framework dialog's options: the command-list layout, sorted by label, with the assign rule above.
fn options() -> Options {
Options::default().with(|o| {
o.layout = Layout::CommandLists;
o.sort_by_label = true;
o.own_areas = true;
o.size = Some(egui::vec2(720.0, 700.0));
o.areas = areas();
o.title = Some(tl!("Customize Keyboard").to_string());
o.accept = Some(Box::new(|_: &CommandDef, binding: &Binding| {
if assignable(binding) { Ok(()) } else { Err(tl!("Use a key combination with Ctrl, Alt or a function key.").to_string()) }
@@ -247,4 +298,53 @@ mod tests {
let unbound_labels = keys_list_labels(&h);
assert!(unbound_labels.iter().any(|t| t == "None"), "empty keys list says None: {unbound_labels:?}");
}
/// #7971: Categories are the ribbon tabs a command is on, not menu or panel ids; a command with no tab is under Other,
/// and every command is under All Commands.
#[test]
fn categories_are_ribbon_tabs() {
use craft::keymap::{CommandDef, Scope};
let on = |path: &[&str]| {
let mut def = CommandDef::new(CommandRef::new("x"), "X", Scope::app());
if !path.is_empty() {
def = def.with_path(path.iter().map(|part| part.to_string()).collect());
}
def
};
let areas = super::areas();
let listing = |def: &CommandDef| areas.iter().filter(|a| (a.rows)(def)).map(|a| a.id).collect::<Vec<_>>();
assert_eq!(listing(&on(&["Home", "Font"])), ["Home", "All Commands"]);
assert_eq!(listing(&on(&["Help", "Support"])), ["Help", "All Commands"], "every ribbon tab has its entry");
assert_eq!(listing(&on(&["Table Design", "Styles"])), ["Contextual Tabs", "All Commands"]);
assert_eq!(listing(&on(&[])), ["Other", "All Commands"]);
assert_eq!(areas.last().map(|a| a.id), Some("All Commands"), "All Commands comes last");
}
/// #7971: under another language, and for the SmartArt tab that shows as "Diagram Design", commands still land
/// under their tab (the catalog keeps English paths; only the display is translated).
#[test]
fn commands_stay_under_their_tab_in_another_language() {
let ctx = egui::Context::default();
crate::i18n::fixture_host(&ctx, "x-fixture", "\tHome\tHome-FX\n\tFont\tFont-FX\n\tDiagram Design\tDiagram-FX\n");
let mut a = app();
let catalog = a.catalog().expect("catalog");
let areas = super::areas();
let under = |id: &str, area: &str| {
let def = catalog.defs().iter().find(|def| def.command == CommandRef::new(id)).unwrap_or_else(|| panic!("{id} in catalog"));
areas.iter().any(|a| a.id == area && (a.rows)(def))
};
assert!(under("format.bold", "Home"), "Bold is under Home in a translated interface");
assert!(!under("format.bold", "Other"));
let smart = a.session.registry.all().iter().find(|spec| spec.location.starts_with("SmartArt Design")).expect("a SmartArt command");
assert!(under(smart.id, "Contextual Tabs") && !under(smart.id, "Other"), "{} is under the contextual tabs", smart.id);
}
/// #7971: the board's catalog files each engine command under its ribbon tab.
#[test]
fn catalog_paths_follow_the_ribbon_location() {
let mut a = app();
let catalog = a.catalog().expect("catalog");
let bold = catalog.defs().iter().find(|def| def.command == CommandRef::new("format.bold")).expect("format.bold");
assert_eq!(bold.paths.first().and_then(|p| p.first()).map(String::as_str), Some("Home"));
}
}
@@ -869,4 +869,39 @@ mod tests {
assert!(!black_text_samples.is_empty(), "{theme}: preview text samples must override text color with black");
}
}
/// The By author colour choice's swatch shows the first three author colours side by side, as it did before the
/// port, not the first author's colour alone.
#[test]
fn track_changes_options_by_author_swatch_shows_three_author_colours() {
use egui_kittest::kittest::Queryable as _;
fn fills_in(shape: &egui::Shape, area: egui::Rect, out: &mut Vec<egui::Color32>) {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| fills_in(shape, area, out)),
egui::Shape::Rect(rect) if area.contains_rect(rect.rect) => out.push(rect.fill),
_ => {}
}
}
let mut h = harness(app());
h.state_mut().run("review.trackingOptions", json!({})).unwrap();
h.run_steps(3);
// The Insertions row's colour field, at By author.
// The first node named "Color: By author" is the field's body, or its arrow once the row's `Field` names the body
// "Color:" (#7525); the field is every part of either name in that row.
let first = h.query_all_by_label("Color: By author").next().expect("a By author colour field").rect();
let field = h
.query_all_by_label("Color: By author")
.chain(h.query_all_by_label("Color:"))
.map(|node| node.rect())
.filter(|rect| (rect.center().y - first.center().y).abs() < 1.0)
.fold(first, |all, rect| all.union(rect));
let mut fills = Vec::new();
for clipped in &h.output().shapes {
fills_in(&clipped.shape, field, &mut fills);
}
for k in 0..3 {
let c = wordcraft_layout::display::revision_color(k);
assert!(fills.contains(&egui::Color32::from_rgb(c.0, c.1, c.2)), "author {k}'s colour is in the swatch: {fills:?}");
}
}
}
+3 -3
View File
@@ -6,7 +6,7 @@ use std::borrow::Cow;
use craft::behavior::{Mixed, SelectionChange, keyed};
use craft::color_ui::ui::ColorPickerTab;
use craft::pages::ui::table::{BorderEdges, EdgeKey, EdgeLook, EdgePicker, SampleArea};
use craft::pages::ui::table::{BorderEdges, EdgeKey, EdgeLook, EdgePicker, EdgeSize, SampleArea};
use craft::text::ui::DocUnit;
use craft::text::ui::ruler::{TabAlign as UiAlign, TabLeader as UiLeader, TabStop as UiStop};
use craft::text::ui::tabs_dialog::{MAX_STOPS, TabStopsDialog, TabStopsResult};
@@ -518,7 +518,7 @@ fn lines(ui: &mut Ui, key: &'static str, l: &mut LineForm, area: SampleArea, fil
Stack::new().show(ui, |ui, _| {
let mut edges = l.edges(between);
let sample = EdgeLook::sample(area, fill.map(srgba));
let picker = EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut edges)).look(sample);
let picker = EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut edges)).look(sample).preview(EdgeSize::Sample);
let picker = if between { picker.paragraph() } else { picker };
picker.show(ui);
l.take_edges(edges, between);
@@ -572,7 +572,7 @@ impl WordForm for BordersForm {
let mut none = BorderEdges::default();
let area = if self.fill_to_text { SampleArea::Text } else { SampleArea::Paragraph };
let sample = EdgeLook::sample(area, Rgb::parse(&self.fill).map(srgba));
EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut none)).look(sample).enabled(false).show(ui);
EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut none)).look(sample).preview(EdgeSize::Sample).enabled(false).show(ui);
Self::apply_to(ui, &mut self.fill_to_text, word(tl!("Paragraph")), word(tl!("Text")));
}
}
@@ -116,12 +116,15 @@ impl WordForm for CaptionForm {
let caption = Label::from(tl!("Caption:").to_string());
if let Some(text) = Field::new(caption.clone())
.show(ui, |ui, _| {
TextField::new(caption.clone(), Bind::given(self.text.clone()))
.prefix(Label::from(self.preview()))
.placeholder(Label::from(tl!("Caption text").to_string()))
.show(ui)
.value()
.cloned()
ui.horizontal(|ui| {
Text::new(Label::from(self.preview())).show(ui);
TextField::new(caption.clone(), Bind::given(self.text.clone()))
.placeholder(Label::from(tl!("Caption text").to_string()))
.show(ui)
.value()
.cloned()
})
.inner
})
.inner
.flatten()
@@ -105,6 +105,29 @@ fn caption_dialog_remembers_the_last_label() {
assert_eq!(CaptionForm::read(a).label, "Figure");
}
/// #8042: the caption's preview is a separate label, not a prefix inside the field; an empty
/// field shows only its placeholder.
#[test]
fn caption_preview_is_a_separate_label() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let mut a = app("A chart");
a.run("select.text", json!({"text": "A chart"})).unwrap();
a.run("references.caption", json!({})).unwrap();
let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
let field = h.get_by_role_and_label(Role::TextInput, "Caption:");
assert_eq!(field.value().as_deref(), Some(""), "the caption field starts empty");
assert!(h.query_by_role_and_label(Role::Label, "Figure 1").is_some(), "the preview is its own label");
}
/// #916: Cross-reference from the ribbon opens a dialog listing the targets of each type
/// (equation captions too) and inserts a `REF` field to the one picked.
#[test]
+10 -8
View File
@@ -20,7 +20,7 @@ use craft::ui::contract::{
};
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, PromptChoice, StackDialog, StandardPrompt, dialog_id};
use craft::ui::display::Text;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::layout_components::{Grid, Row, Stack};
use craft::ui::list::{List, ListRow, ToggleCell, ToggleState};
use craft::ui::notices::Notice;
use craft::ui::runtime::env::Label;
@@ -52,6 +52,8 @@ pub struct TreeItem {
pub command: Option<String>,
}
/// The body's panes: the command pickers, the Add and Remove buttons, then the ribbon or toolbar list.
const PANES: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)];
/// The column of show boxes in the ribbon tree.
const SHOWN: ColumnKey = ColumnKey::new("shown");
@@ -144,10 +146,10 @@ impl RibbonDialog {
fn body(&mut self, ui: &mut Ui) {
self.page_tabs(ui);
search(ui, &mut self.filter);
Row::new().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Grid::new(&PANES).fill_width().show(ui, |ui, _| {
Stack::new().fill_width().show(ui, |ui, _| {
Text::new(word("Choose a command")).show(ui);
Row::new().show(ui, |ui, _| {
Row::new().fill_width().show(ui, |ui, _| {
if let Some(category) = pick(ui, "rb_categories", "Categories:", &self.categories, &self.category) {
self.category = category;
self.filter.clear();
@@ -220,9 +222,9 @@ impl RibbonDialog {
self.file("remove", Value::Object(address(&sel)));
}
});
Stack::new().show(ui, |ui, _| {
Stack::new().fill_width().show(ui, |ui, _| {
Text::new(word("Ribbon tabs")).show(ui);
Row::new().show(ui, |ui, _| {
Row::new().fill_width().show(ui, |ui, _| {
self.tree(ui);
Stack::new().show(ui, |ui, _| {
for (text, by) in [("Up", -1), ("Down", 1)] {
@@ -311,9 +313,9 @@ impl RibbonDialog {
self.file("qatRemove", json!(self.qat_selected));
}
});
Stack::new().show(ui, |ui, _| {
Stack::new().fill_width().show(ui, |ui, _| {
Text::new(word("Quick Access Toolbar")).show(ui);
Row::new().show(ui, |ui, _| {
Row::new().fill_width().show(ui, |ui, _| {
if let Some(id) = pick(ui, "rb_qat", "Quick Access Toolbar", &self.qat, &self.qat_selected) {
self.qat_selected = id;
}
+44 -10
View File
@@ -22,7 +22,12 @@ use crate::WordApp;
/// Opens `wordCount` or `zoom`; any other name opens nothing.
pub(crate) fn open(app: &mut WordApp, name: &str, _params: &Value, parent: Option<DialogId>) -> Option<DialogId> {
match name {
"wordCount" => Some(open_with(app, parent, WordCountDialog::new(), DialogHooks::prepare_only(prepare_word_count))),
"wordCount" => Some(open_with(
app,
parent,
WordCountDialog::new(app.session.prefs.count_notes),
DialogHooks { prepare: Some(prepare_word_count), settle: settle_word_count },
)),
"zoom" => {
// The view keeps the zoom as a fraction (1.0 = 100%); the dialog shows and answers percent, as `view.zoom` takes it.
let percent = (f64::from(app.session.view.zoom) * 100.0).round();
@@ -32,15 +37,40 @@ pub(crate) fn open(app: &mut WordApp, name: &str, _params: &Value, parent: Optio
}
}
/// Reads the six counts from the session before each pass; the dialog never keeps them beyond the pass.
/// Reads the six counts and current `includeTextBoxes` preference from the session before each pass;
/// does not send `includeTextBoxes` so automation changes stay in effect while the dialog is open.
fn prepare_word_count(app: &mut WordApp, id: DialogId) {
let include = app.dialog_host.get_by_id::<WordCountDialog>(id).is_none_or(|d| d.include_text_boxes);
let stats = app.run("review.wordCount", json!({"includeTextBoxes": include})).ok();
let stats = app.session.run("review.wordCount", &json!({})).ok();
if let Some(d) = app.dialog_host.get_mut_by_id::<WordCountDialog>(id) {
if let Some(on) = stats.as_ref().and_then(|s| s["includeTextBoxes"].as_bool()) {
d.include_text_boxes = on;
}
d.stats = stats;
}
}
/// Applies user toggles of "Count words in text boxes and notes" via `review.wordCount` and
/// refreshes the displayed counts immediately.
fn settle_word_count(app: &mut WordApp, ctx: &Context, id: DialogId) -> Settle {
if let Some(res) = app.dialog_host.take_by_id::<WordCountDialog>(id) {
if let DialogResult::Ok(Some(on)) = res {
let _ = app.run("review.wordCount", json!({"includeTextBoxes": on}));
}
return Settle::Done;
}
if let Some(on) = app.dialog_host.get_mut_by_id::<WordCountDialog>(id).and_then(|d| d.toggled.take()) {
let stats = app.run("review.wordCount", json!({"includeTextBoxes": on})).ok();
if let Some(d) = app.dialog_host.get_mut_by_id::<WordCountDialog>(id) {
if let Some(val) = stats.as_ref().and_then(|s| s["includeTextBoxes"].as_bool()) {
d.include_text_boxes = val;
}
d.stats = stats;
}
ctx.request_repaint();
}
Settle::Keep
}
/// Runs `view.zoom` with the percent or the fit name the dialog answered with.
fn settle_zoom(app: &mut WordApp, _: &Context, id: DialogId) -> Settle {
match app.dialog_host.take_by_id::<ZoomDialog>(id) {
@@ -68,20 +98,22 @@ const COUNT_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content; 2];
/// The Word Count dialog.
pub(crate) struct WordCountDialog {
/// The counts of the last `prepare`.
/// The counts of the last `prepare` or `settle`.
stats: Option<Value>,
/// Whether text boxes and notes count.
include_text_boxes: bool,
/// User toggle waiting to be sent to `review.wordCount`.
toggled: Option<bool>,
}
impl WordCountDialog {
fn new() -> Self {
Self { stats: None, include_text_boxes: true }
fn new(include_text_boxes: bool) -> Self {
Self { stats: None, include_text_boxes, toggled: None }
}
}
impl StackDialog for WordCountDialog {
type Result = ();
type Result = Option<bool>;
fn id(&self) -> DialogId {
dialog_id("wordCount")
@@ -91,9 +123,10 @@ impl StackDialog for WordCountDialog {
Some("wordCount")
}
fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option<DialogResult<()>> {
fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option<DialogResult<Option<bool>>> {
let stats = self.stats.clone().unwrap_or(Value::Null);
let include = &mut self.include_text_boxes;
let pending_toggle = &mut self.toggled;
let shown = Dialog::new(tl!("Word Count").to_string())
// The old dialog's pair: Close as the default button, and Cancel; both only close it.
.buttons([
@@ -116,9 +149,10 @@ impl StackDialog for WordCountDialog {
.show(ui);
if let Some(on) = toggled.value().cloned() {
*include = on;
*pending_toggle = Some(on);
}
});
shown.output.closed.map(|_| DialogResult::Ok(()))
shown.output.closed.map(|_| DialogResult::Ok(self.toggled.take()))
}
}
+10 -1
View File
@@ -16,6 +16,9 @@ use crate::WordApp;
/// The Search Commands dialog; its answer is the query of the fallback row, when that was picked.
pub(super) struct SearchCommandsDialog {
entries: Vec<HelpEntry>,
/// The entries' index and the interface language it was built in: built when the dialog first shows, and again
/// only in another language, since building it folds every entry's labels.
index: Option<(&'static str, SearchIndex)>,
open: bool,
suggested: Vec<CommandRef>,
fallback: WordTemplate,
@@ -27,6 +30,7 @@ impl SearchCommandsDialog {
fn new(entries: Vec<HelpEntry>) -> Self {
Self {
entries,
index: None,
open: true,
suggested: SEARCH_SUGGESTIONS.iter().map(|id| CommandRef::new(*id)).collect(),
fallback: WordTemplate::new(tl!("Find “{text}” in the document")),
@@ -48,11 +52,16 @@ impl StackDialog for SearchCommandsDialog {
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<Option<String>>> {
let env = Env::of(ui);
let view = env.view();
let index = SearchIndex::new(&view, &self.entries, &Synonyms::of(&view.words::<SearchWords>()));
let lang = crate::i18n::current().code();
let index = match self.index.take() {
Some((built, index)) if built == lang => index,
_ => SearchIndex::new(&view, &self.entries, &Synonyms::of(&view.words::<SearchWords>())),
};
let out = CommandPalette::new(tl!("Search Commands"), &self.entries, &index, Bind::bound(&mut self.open))
.suggested((Label::from(tl!("Suggested")), self.suggested.clone()))
.fallback(self.fallback.clone())
.show(ui);
self.index = Some((lang, index));
if let Some(text) = out.fallback {
return Some(DialogResult::Ok(Some(text)));
}
+6 -2
View File
@@ -94,15 +94,19 @@ fn flag(v: &Value, k: &str, default: bool) -> bool {
v.get(k).and_then(Value::as_bool).unwrap_or(default)
}
/// Opens Manage Styles with `params["style"]` selected (the first style when none); `None` for another name.
/// Opens Manage Styles with `params["style"]` (or the caret's current style when omitted, falling back to the first style) selected; `None` for another name.
pub(crate) fn open(app: &mut WordApp, name: &str, params: &Value, parent: Option<DialogId>) -> Option<DialogId> {
if name != KEY {
return None;
}
let selected =
params.get("style").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(|| {
wordcraft_engine::cmd::format::state(&app.session).get("style").and_then(Value::as_str).unwrap_or_default().to_string()
});
let dialog = ManageStylesDialog {
id: dialog_id(KEY),
alphabetical: false,
selected: params.get("style").and_then(Value::as_str).unwrap_or_default().to_string(),
selected,
styles: Vec::new(),
preview: None,
made: 0,
+117
View File
@@ -1892,6 +1892,81 @@ fn word_count_shows_label_and_count_on_a_line_over_close_and_cancel() {
assert!(!is_open(h.state(), "wordCount"), "Cancel closes Word Count");
}
/// Reopening Word Count preserves the "Count words in text boxes and notes" setting.
#[test]
fn word_count_keeps_include_text_boxes_setting_across_reopens() {
use egui::accesskit::{Role, Toggled};
let mut app = app_with("one two three ");
let _ = app.run("insert.textBox", json!({"text": "four five six seven"}));
let mut h = app_harness(app);
h.run_steps(2);
let box_label = "Count words in text boxes and notes";
let box_toggled = |h: &egui_kittest::Harness<'_, WordApp>| h.get_by_role_and_label(Role::CheckBox, box_label).accesskit_node().toggled();
let word_count_is = |h: &egui_kittest::Harness<'_, WordApp>, expected: &str| {
let words_rect = h.get_by_label("Words").rect();
h.query_all_by_label(expected).any(|n| (n.rect().center().y - words_rect.center().y).abs() < 1.0)
};
super::open(h.state_mut(), "wordCount", &json!({})).expect("word count opens");
h.run_steps(3);
assert_eq!(box_toggled(&h), Some(Toggled::True));
assert!(word_count_is(&h, "7"), "counts text boxes on first open");
h.get_by_role_and_label(Role::CheckBox, box_label).click();
h.run_steps(3);
assert_eq!(box_toggled(&h), Some(Toggled::False));
assert!(!h.state().session.prefs.count_notes);
assert!(word_count_is(&h, "3"), "excludes text boxes after unticking");
h.get_by_role_and_label(Role::Button, "Cancel").click();
h.run_steps(3);
assert!(!is_open(h.state(), "wordCount"));
assert!(!h.state().session.prefs.count_notes);
super::open(h.state_mut(), "wordCount", &json!({})).expect("word count reopens");
h.run_steps(3);
assert!(!h.state().session.prefs.count_notes, "reopening must not turn count_notes back on");
assert_eq!(box_toggled(&h), Some(Toggled::False), "checkbox stays unticked across reopens");
assert!(word_count_is(&h, "3"), "reopened count still excludes text boxes");
}
/// #8139: while Word Count is open, automation changes to `includeTextBoxes` stay in effect
/// and update the dialog instead of being overwritten by the dialog's own checkbox copy.
#[test]
fn word_count_dialog_follows_automation_and_user_toggles() {
use egui::accesskit::{Role, Toggled};
let mut app = app_with("one two three ");
let _ = app.run("insert.textBox", json!({"text": "four five six seven"}));
let mut h = app_harness(app);
h.run_steps(2);
let box_label = "Count words in text boxes and notes";
let box_toggled = |h: &egui_kittest::Harness<'_, WordApp>| h.get_by_role_and_label(Role::CheckBox, box_label).accesskit_node().toggled();
let word_count_is = |h: &egui_kittest::Harness<'_, WordApp>, expected: &str| {
let words_rect = h.get_by_label("Words").rect();
h.query_all_by_label(expected).any(|n| (n.rect().center().y - words_rect.center().y).abs() < 1.0)
};
super::open(h.state_mut(), "wordCount", &json!({})).expect("word count opens");
h.run_steps(3);
assert!(h.state().session.prefs.count_notes);
assert_eq!(box_toggled(&h), Some(Toggled::True));
assert!(word_count_is(&h, "7"));
h.state_mut().run("review.wordCount", json!({"includeTextBoxes": false})).unwrap();
h.run_steps(3);
assert!(!h.state().session.prefs.count_notes, "open dialog must not overwrite automation change");
assert_eq!(box_toggled(&h), Some(Toggled::False), "checkbox clears to reflect automation change");
assert!(word_count_is(&h, "3"), "count updates to exclude text boxes");
h.get_by_role_and_label(Role::CheckBox, box_label).click();
h.run_steps(3);
assert!(h.state().session.prefs.count_notes, "user toggle updates preference");
assert_eq!(box_toggled(&h), Some(Toggled::True));
assert!(word_count_is(&h, "7"), "count updates to include text boxes");
}
/// #1885: the close control is at the title bar's right end; a click in the close box
/// closes the dialog; one just under the title bar leaves it open; a drag that starts on the box
/// doesn't move the dialog.
@@ -2340,6 +2415,18 @@ fn dialog_previews_are_drawn_larger_than_a_control() {
);
}
}
/// #7977: Borders and Shading draws its edge preview at sample size, not as a thumbnail.
#[test]
fn borders_preview_is_larger_than_a_thumbnail() {
use egui::accesskit::Role;
let mut h = app_harness(app_with("Lanterns"));
h.state_mut().run("ui.dialog", json!({"name": "borders"})).unwrap();
h.run_steps(6);
let preview = h.get_by_role_and_label(Role::Group, "Preview").rect();
let button = h.get_by_role_and_label(Role::Button, "Cancel").rect();
assert!(preview.height() > 2.0 * button.height(), "the preview is {}pt high beside a {}pt button", preview.height(), button.height());
}
/// #7982: Custom Properties' hint wraps inside the dialog instead of running under the Cancel button.
#[test]
fn custom_properties_hint_does_not_run_under_the_buttons() {
@@ -2492,3 +2579,33 @@ fn the_ribbon_customizer_lists_are_framed() {
h.run_steps(3);
assert_framed(&h, "Quick Access Toolbar");
}
// ---------------------------------------------------------------- Manage Styles
/// Manage Styles opens on the paragraph style at the caret when no explicit `style` parameter is given,
/// and honors an explicit `params["style"]` when provided.
#[test]
fn manage_styles_opens_on_caret_style() {
let mut app = app_with("Title line\nBody line");
app.run("para.style", json!({"style": "Heading2"})).unwrap();
let list = wordcraft_engine::cmd::para::manage_list(&app.session, false);
let first_id = list.as_array().and_then(|a| a.first()).and_then(|v| v.get("id")).and_then(Json::as_str).unwrap_or_default();
assert_ne!(first_id, "Heading2", "Heading2 must not be the first style so the test checks caret selection");
let mut h = app_harness(app);
h.run_steps(2);
let _ = h.state_mut().run("styles.manage", json!({}));
h.run_steps(3);
assert!(is_open(h.state(), "manageStyles"), "styles.manage opens Manage Styles");
assert_eq!(fields_of(h.state(), "manageStyles")["selected"], "Heading2", "Manage Styles starts on the caret's style");
assert!(!h.get_by_label("New Style…").accesskit_node().is_disabled());
assert!(
h.query_all(egui_kittest::kittest::By::new()).any(|n| n.accesskit_node().label().is_some_and(|l| l.contains("Based on: Normal"))),
"the dialog body renders the selected Heading 2 style's description"
);
let manage_id = id_of(h.state(), "manageStyles");
cancel(&mut h, manage_id);
open_named(&mut h, "manageStyles", json!({"style": "Heading1"}));
assert_eq!(fields_of(h.state(), "manageStyles")["selected"], "Heading1", "explicit style param still overrides caret style");
}
+1
View File
@@ -82,6 +82,7 @@ impl WordApp {
self.info_editing = None;
// Caches keyed by the revision alone: another document's revision can be the same number.
self.status_counts = crate::window_ui::NOT_COUNTED;
self.chrome.status_words = None;
self.previews.document_changed();
// The Start screen's placeholder (#1129) goes once a document is open beside it.
if let Some(placeholder) = self.no_document
+7 -2
View File
@@ -347,8 +347,13 @@ static WORDCRAFT_ICONS_TABLE: &[(&str, &[u8])] = &[
];
/// The app icon set. Every document is drawn with the pen width 1.25 of the 20-unit view box,
/// which the framework scales to its own stroke.
pub static WORDCRAFT_ICONS: AppIcons = AppIcons::new("wordcraft", Some(1.25), WORDCRAFT_ICONS_TABLE);
/// which the framework scales to its own stroke. The Format Painter's yellow bar is a fill drawn
/// under the icon, so its outline keeps its full stroke instead of the fixed layer covering it.
pub static WORDCRAFT_ICONS: AppIcons = AppIcons::new("wordcraft", Some(1.25), WORDCRAFT_ICONS_TABLE).with_fills(&[(
"painter",
include_bytes!("../icons/painter-fill.svg"),
[0xF2, 0xC8, 0x11, 0xFF],
)]);
/// Registers the app icon set beside the framework's catalog; runs before the first pass.
pub fn register() {
+2
View File
@@ -407,6 +407,8 @@ pub struct WordApp {
pub(crate) command_states_cache: Option<app::command_board::CommandStatesCache>,
/// Cached keytip control lists and reserved shortcut letters per registry and active ribbon tab.
pub(crate) keytip_cache: Option<keytips::KeytipCache>,
/// The command search's entries and index, per registry and interface language ([`chrome::search::SearchCache`]).
pub(crate) search_cache: Option<chrome::search::SearchCache>,
/// Frames drawn so far, counted to 2: the control channel's queued requests wait until the
/// fonts are warm.
pub(crate) fonts_frames: u8,
+12 -5
View File
@@ -155,7 +155,7 @@ pub fn context_menu_visible(app: &WordApp) -> bool {
/// command while the pointer rests on it; the context menu's copy of the bar (which calls this
/// from `canvas/context_menu.rs`) previews nothing.
pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
let st: Value = wordcraft_engine::cmd::format::state(&app.session);
let st = wordcraft_engine::cmd::format::cached_state(&app.session);
let flag = |k: &str| match st.get(k) {
Some(Value::Bool(b)) => *b,
Some(Value::String(s)) => !s.is_empty() && s != "none",
@@ -232,11 +232,12 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
let _ = Divider::vertical().show(ui);
let hl = crate::colors::highlight_split(ui, app, tl!("Text Highlight Color").to_string());
follow_list(app, preview, &hl.preview, |c| {
wordcraft_doc::props::Highlight::ALL
follow_list(app, preview, &hl.preview, |c| match c {
Some(c) => wordcraft_doc::props::Highlight::ALL
.iter()
.find(|h| h.rgb().as_ref() == Some(c))
.map(|h| ("format.highlight".to_string(), json!({"color": h.ooxml()})))
.map(|h| ("format.highlight".to_string(), json!({"color": h.ooxml()}))),
None => Some(("format.highlight".to_string(), json!({"color": "none"}))),
});
// PLAN: assumed ColorPick::hover (ribbon-w11, S-L413)
let color = app.canvas.last_highlight.clone();
@@ -250,7 +251,13 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
tl!("Font Color").to_string(),
Target::cmd("format.color").remember(Remember::FontColor),
);
follow_list(app, preview, &fc.preview, |c| Some(("format.color".to_string(), json!({"color": c.hex()}))));
follow_list(app, preview, &fc.preview, |c| {
let color = match c {
Some(c) => c.hex(),
None => "auto".to_string(),
};
Some(("format.color".to_string(), json!({"color": color})))
});
// PLAN: assumed ColorPick::hover (ribbon-w11, S-L413)
let color = app.canvas.last_font_color.clone();
preview_on_hover(app, fc.hover, fc.response.enabled(), "format.color", json!({"color": color}), preview);
+131
View File
@@ -848,3 +848,134 @@ fn the_anchor_spans_every_run_on_the_topmost_line() {
let l = visible_anchor(rects, clip, false).unwrap();
assert!(l.min.x == line1[0].min.x && l.max.x < a.max.x, "LTR anchor is the top run only: {l:?}");
}
/// Automatic in Font Color and No Color in Text Highlight Color mark the current choice when active.
#[test]
fn automatic_and_no_color_mark_the_current_choice() {
use egui::accesskit::Toggled;
let mut h = bar_over("brown fox");
let arrow = split_arrow(&h, "Font Color");
click_at(&mut h, arrow.center());
let auto = h.get_by_label("Automatic");
assert_eq!(auto.accesskit_node().role(), Role::MenuItemCheckBox);
assert_eq!(auto.accesskit_node().toggled(), Some(Toggled::True), "Automatic is checked by default");
h.key_press(egui::Key::Escape);
steps(&mut h);
h.state_mut().run("format.color", json!({"color": "FF0000"})).unwrap();
steps(&mut h);
let arrow = split_arrow(&h, "Font Color");
click_at(&mut h, arrow.center());
assert_eq!(h.get_by_label("Automatic").accesskit_node().toggled(), Some(Toggled::False), "Automatic is unchecked after a colour pick");
h.key_press(egui::Key::Escape);
steps(&mut h);
let arrow = split_arrow(&h, "Text Highlight Color");
click_at(&mut h, arrow.center());
let no_color = h.get_by_label("No Color");
assert_eq!(no_color.accesskit_node().role(), Role::MenuItemCheckBox);
assert_eq!(no_color.accesskit_node().toggled(), Some(Toggled::True), "No Color is checked when no highlight is applied");
h.key_press(egui::Key::Escape);
steps(&mut h);
h.state_mut().run("format.highlight", json!({"color": "yellow"})).unwrap();
steps(&mut h);
let arrow = split_arrow(&h, "Text Highlight Color");
click_at(&mut h, arrow.center());
assert_eq!(h.get_by_label("No Color").accesskit_node().toggled(), Some(Toggled::False), "No Color is unchecked after highlighting");
h.key_press(egui::Key::Escape);
steps(&mut h);
// Mixed selection (partly highlighted): No Color must stay unchecked, not collapse null to "none".
h.state_mut().run("select.text", json!({"text": "fox"})).unwrap();
h.state_mut().run("format.highlight", json!({"color": "none"})).unwrap();
h.state_mut().run("select.text", json!({"text": "brown fox"})).unwrap();
steps(&mut h);
let arrow = split_arrow(&h, "Text Highlight Color");
click_at(&mut h, arrow.center());
assert_eq!(
h.get_by_label("No Color").accesskit_node().toggled(),
Some(Toggled::False),
"No Color is unchecked when only part of the selection is highlighted"
);
h.key_press(egui::Key::Escape);
steps(&mut h);
// Mixed selection (two different highlight colours): No Color must stay unchecked.
h.state_mut().run("select.text", json!({"text": "fox"})).unwrap();
h.state_mut().run("format.highlight", json!({"color": "cyan"})).unwrap();
h.state_mut().run("select.text", json!({"text": "brown fox"})).unwrap();
steps(&mut h);
let arrow = split_arrow(&h, "Text Highlight Color");
click_at(&mut h, arrow.center());
assert_eq!(
h.get_by_label("No Color").accesskit_node().toggled(),
Some(Toggled::False),
"No Color is unchecked when selection has two highlight colours"
);
}
/// Hovering Automatic in Font Color or No Color in Text Highlight Color on the mini toolbar
/// previews removing the formatting and clears the preview when the pointer leaves or closes.
#[test]
fn automatic_and_no_color_preview_on_hover() {
for (button, item_label, swatch_query, setup_cmd, setup_color, preview_cmd, preview_color, swatch_color) in [
("Font Color", "Automatic", "#", "format.color", "FF0000", "format.color", "auto", None),
("Text Highlight Color", "No Color", "Yellow", "format.highlight", "yellow", "format.highlight", "none", Some("yellow")),
] {
let mut h = bar_over("brown fox");
h.state_mut().run(setup_cmd, json!({"color": setup_color})).unwrap();
steps(&mut h);
let (doc, sel, rev) = (h.state().session.doc.clone(), h.state().session.sel.clone(), h.state().session.rev());
let arrow = split_arrow(&h, button);
click_at(&mut h, arrow.center());
let target = h.get_by_label(item_label).rect().center();
hover_at(&mut h, target);
assert_eq!(
h.state().canvas.command_previewed,
Some((preview_cmd.to_string(), json!({"color": preview_color}))),
"{button} {item_label} hover previews {preview_cmd}({preview_color})"
);
assert_ne!(crate::canvas::page_doc(h.state()), &doc, "{button} {item_label}: page shows the live preview");
assert_eq!((&h.state().session.doc, &h.state().session.sel, h.state().session.rev()), (&doc, &sel, rev));
// Moving directly from Automatic / No Color to a swatch updates the preview cleanly.
let swatch = h.query_all_by_label_contains(swatch_query).next().expect("swatch present");
let expected_swatch = swatch_color
.map(str::to_string)
.unwrap_or_else(|| swatch.accesskit_node().label().unwrap_or_default().trim_start_matches('#').to_string());
let swatch_pos = swatch.rect().center();
hover_at(&mut h, swatch_pos);
assert_eq!(
h.state().canvas.command_previewed,
Some((preview_cmd.to_string(), json!({"color": expected_swatch}))),
"{button} moving to swatch switches preview"
);
// Moving back to Automatic / No Color restores its preview.
hover_at(&mut h, target);
assert_eq!(
h.state().canvas.command_previewed,
Some((preview_cmd.to_string(), json!({"color": preview_color}))),
"{button} moving back to {item_label} restores preview"
);
hover_at(&mut h, pos2(5.0, 5.0));
assert_eq!(h.state().canvas.command_previewed, None, "{button} {item_label}: moving off clears the preview");
// Closing the menu via Escape while hovering Automatic / No Color also clears the preview.
hover_at(&mut h, target);
assert_eq!(
h.state().canvas.command_previewed,
Some((preview_cmd.to_string(), json!({"color": preview_color}))),
"{button} {item_label}: hover active before Escape"
);
h.key_press(egui::Key::Escape);
steps(&mut h);
assert_eq!(h.state().canvas.command_previewed, None, "{button} {item_label}: Escape clears the preview");
}
}
+13 -6
View File
@@ -2,7 +2,7 @@ use std::borrow::Cow;
use craft::behavior::{IconId, Selection, SelectionChange, keyed};
use craft::ui::buttons::{Button, IconButton, ToggleButton};
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props, SelectMode, Show, ShowCollection, ShowContainer, clicked};
use craft::ui::contract::{Bind, CollectionEvent, Entry, LeadSource, Props, SelectMode, Show, ShowCollection, ShowContainer, clicked};
use craft::ui::display::Text;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{List, ListRow};
@@ -69,7 +69,7 @@ fn row_menu(
pub(super) fn styles(app: &mut WordApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
let st = wordcraft_engine::cmd::format::state(&app.session);
let st = wordcraft_engine::cmd::format::cached_state(&app.session);
let cur = st.get("style").and_then(Value::as_str).unwrap_or("Normal").to_string();
let current_name = app
.session
@@ -122,19 +122,26 @@ pub(super) fn styles(app: &mut WordApp, ui: &mut Ui) {
// The marker tells a character style from a paragraph style.
ListRow::new(name.clone()).trailing(if *is_char { "a" } else { "" })
});
let secondary_pointer = ui.input(|i| i.pointer.secondary_pressed() || i.pointer.secondary_down() || i.pointer.secondary_released());
let mut asked = None;
let mut picked_style = None;
for event in &out.events {
match event {
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => {
if let Some((id, ..)) = keys.first().and_then(|k| list.get(*k)) {
let _ = app.run("para.style", json!({"style": id}));
app.canvas.focus_page(&ctx);
CollectionEvent::Selection { change: SelectionChange::Set(keys), by, .. } => {
if !(secondary_pointer && matches!(by, LeadSource::Pointer)) {
picked_style = keys.first().copied();
}
}
CollectionEvent::ContextMenu(request) => asked = Some(request.key),
_ => {}
}
}
if asked.is_none()
&& let Some((id, ..)) = picked_style.and_then(|k| list.get(k))
{
let _ = app.run("para.style", json!({"style": id}));
app.canvas.focus_page(&ctx);
}
let menu_id = app.window_id("styles_row_menu");
let entries = |row: usize| {
let builtin = list.get(row).is_some_and(|s| s.3);
+57
View File
@@ -298,3 +298,60 @@ fn headings_show_their_list_numbers() {
let texts: Vec<String> = nav_headings(&doc).into_iter().map(|(_, _, t)| t).collect();
assert_eq!(texts, ["1. Intro", "1.1. Scope", "1.3. Terms", "2. Method", "Appendix"]);
}
/// Right-clicking a style in the Styles pane opens its context menu without applying the style,
/// while a primary click applies it.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn right_clicking_a_style_in_styles_pane_opens_its_menu_without_applying_it() {
use egui_kittest::kittest::Queryable;
let app = crate::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default());
let mut fonts = false;
let mut h = crate::test_harness::builder().with_size(egui::vec2(400.0, 1200.0)).build_ui_state(
|ui, app: &mut crate::WordApp| {
if !fonts {
crate::app::fonts::install_ui_fonts(ui.ctx(), crate::i18n::Lang::EN);
fonts = true;
return;
}
super::styles(app, ui);
},
app,
);
h.run_steps(4);
let undo_before = h.state().session.undo_depth();
let style_at_caret = |app: &crate::WordApp| {
wordcraft_engine::cmd::format::state(&app.session).get("style").and_then(serde_json::Value::as_str).unwrap_or_default().to_string()
};
assert_eq!(style_at_caret(h.state()), "Normal");
let over_list = h.get_by_label("Manage Styles…").rect().center() + egui::vec2(0.0, 120.0);
h.event(egui::Event::PointerMoved(over_list));
h.run_steps(1);
for _ in 0..40 {
if h.query_by_label("Heading 1").is_some() {
break;
}
h.event(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -120.0),
phase: egui::TouchPhase::Move,
modifiers: Default::default(),
source: egui::MouseWheelSource::Unknown,
});
h.run_steps(2);
}
h.get_by_label("Heading 1").click_secondary();
h.run_steps(3);
assert!(h.query_by_label("Modify…").is_some(), "right-clicking a style opens its context menu");
assert_eq!(style_at_caret(h.state()), "Normal", "right-clicking must not apply the style");
assert_eq!(h.state().session.undo_depth(), undo_before, "right-clicking leaves no undo step");
h.key_press(egui::Key::Escape);
h.run_steps(3);
h.get_by_label("Heading 1").click();
h.run_steps(3);
assert_eq!(style_at_caret(h.state()), "Heading1", "primary click applies the style");
}
+18
View File
@@ -33,6 +33,7 @@ pub struct Previews {
/// The Chinese, Japanese and Korean fonts of the font list (the Asian text font box).
east_asian: Option<Vec<String>>,
styles_hash: (u64, u64),
style_gallery: Option<(u64, &'static str, Arc<Vec<(String, String)>>)>,
}
impl Previews {
@@ -111,6 +112,7 @@ impl Previews {
/// Another document is shown: its revisions count apart from the last one's.
pub(crate) fn document_changed(&mut self) {
self.styles_hash = (u64::MAX, 0);
self.style_gallery = None;
}
/// Hash of the style sheet (recomputed only when the document revision changes).
@@ -123,6 +125,22 @@ impl Previews {
}
self.styles_hash.1
}
/// Localized `(id, name)` entries for the Home › Styles gallery, cached by style-sheet key
/// and interface language.
pub(crate) fn style_gallery(&mut self, doc: &Document, rev: u64) -> Arc<Vec<(String, String)>> {
let key = self.styles_key(doc, rev);
let lang = crate::i18n::current().code();
if let Some((cached_key, cached_lang, entries)) = &self.style_gallery
&& *cached_key == key
&& *cached_lang == lang
{
return Arc::clone(entries);
}
let entries = Arc::new(doc.styles.gallery().iter().map(|s| (s.id.clone(), crate::i18n::style_name(s))).collect());
self.style_gallery = Some((key, lang, Arc::clone(&entries)));
entries
}
}
/// The store key of a picture named by `value`: what makes two pictures one.
+18
View File
@@ -56,6 +56,18 @@ pub(crate) fn icon_only<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R {
)
}
/// Shows `add` with its inline buttons keeping their labels in a compact group (#7985): the ribbon then gains nothing by
/// compacting the group, so a wider group (Window) gives way first, as in v0.19.1.
pub(crate) fn labelled<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R {
craft::ui::runtime::env::with_env(
ui,
|overrides| {
overrides.values.set(craft::ui::buttons::GroupLevel::Full);
},
add,
)
}
/// Custom groups (Customize Ribbon, #379): up to three commands as stacked buttons, more as inline
/// buttons in columns of three. Each shows the command's own icon and label.
pub(super) fn custom_groups(row: &mut RibbonRow<'_>, app: &mut WordApp, groups: &[wordcraft_engine::ribbon::CustomGroup]) {
@@ -91,11 +103,17 @@ pub(super) fn custom_groups(row: &mut RibbonRow<'_>, app: &mut WordApp, groups:
/// resizes the one side only.
pub(super) fn size_field(ui: &mut Ui, app: &mut WordApp, label: &str, key: &str, pt: f32, lock_aspect: bool, range: RangeInclusive<f32>) {
let lengths = crate::options::lengths(app.session.units());
let hint = if lock_aspect {
tl!("Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions.")
} else {
tl!("Type a size in any unit, such as 3 cm or 300 px.")
};
let mut events = None;
// The label shows beside the field, as the old ribbon drew `H: 252 pt`; the Field makes it the control's one accessible name.
Field::new(tl!(label).to_string()).id_salt(("size_field_label", key)).sizing(Sizing::Content).show(ui, |ui, _| {
let field = NumberField::length(tl!(label).to_string(), Bind::given(Some(f64::from(pt))), lengths)
.range(f64::from(*range.start())..=f64::from(*range.end()))
.tooltip(TooltipSpec::new(hint.to_string()))
.id_salt(("size_field", key));
events = Some(field.show(ui).edit.events);
});
+1 -1
View File
@@ -147,7 +147,7 @@ pub(crate) fn styles(ui: &mut Ui, app: &mut WordApp, current: Option<&str>) {
let ppp = ui.ctx().pixels_per_point();
let revision = style_revision(app, mode);
let dark_page = app.session.view.dark_mode;
let entries: Vec<(String, String)> = app.session.doc.styles.gallery().iter().map(|s| (s.id.clone(), crate::i18n::style_name(s))).collect();
let entries = app.previews.style_gallery(&app.session.doc, app.session.rev());
let current = current.unwrap_or("Normal").to_string();
let out = {
let doc = &app.session.doc;
+20 -6
View File
@@ -139,10 +139,27 @@ fn text_effects_menu(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
}
}
fn format_font_size(s: f64) -> String {
if s.fract() == 0.0 { format!("{s:.0}") } else { format!("{s}") }
}
fn font_size_entries() -> &'static [Entry<String>] {
static ENTRIES: std::sync::OnceLock<Vec<Entry<String>>> = std::sync::OnceLock::new();
ENTRIES.get_or_init(|| {
wordcraft_engine::cmd::format::SIZES
.iter()
.map(|s| {
let label = format_font_size(f64::from(*s));
Entry::new(label.clone(), label)
})
.collect()
})
}
pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
// Read directly, not as a command: every command consumes the engine's pending undo joins, and
// the ribbon draws between an input method's deletion and the commit that replaces it.
let st = wordcraft_engine::cmd::format::state(&app.session);
let st = wordcraft_engine::cmd::format::cached_state(&app.session);
let flag = |k: &str| st.get(k).and_then(Value::as_bool).unwrap_or(false);
row.group(ribbon_group("clipboard", "Clipboard", "paste", Some("edit.clipboardPane")), |ui| {
// The face opens the menu and runs no command, so its tooltip adds Paste's key itself, as this
@@ -185,11 +202,8 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
if let Some(f) = out.picked {
let _ = app.run("format.font", json!({"name": f}));
}
let fmt = |s: f64| if s.fract() == 0.0 { format!("{s:.0}") } else { format!("{s}") };
let mut size = st.get("size").and_then(Value::as_f64).map(fmt).unwrap_or_default();
let sizes: Vec<Entry<String>> =
wordcraft_engine::cmd::format::SIZES.iter().map(|s| Entry::new(fmt(f64::from(*s)), fmt(f64::from(*s)))).collect();
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), &sizes)
let mut size = st.get("size").and_then(Value::as_f64).map(format_font_size).unwrap_or_default();
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), font_size_entries())
.tooltip(tl!("Font Size").to_string())
.show(ui);
if let Some(v) = out.edit.events.committed()
+1 -1
View File
@@ -383,7 +383,7 @@ pub(crate) fn caret_unreadable_dictionary(app: &WordApp) -> Option<(std::path::P
/// with every language and Set As Default, and Language Preferences… opens Options › Language
/// (#860: the short list alone left no way to pick French).
pub(crate) fn language_menu(ui: &mut Ui, app: &mut WordApp) {
let st = wordcraft_engine::cmd::format::state(&app.session);
let st = wordcraft_engine::cmd::format::cached_state(&app.session);
// The selection's own language; else (nothing set on the text) the one it gets from its
// style or the document default, as the status bar shows.
let current = match st.get("lang") {
+26
View File
@@ -1389,3 +1389,29 @@ fn symbol_tip_names_known_characters_and_falls_back_to_the_code_point() {
assert!(unnamed.contains("2602") && unnamed.contains("Miscellaneous Symbols"), "unnamed character: {unnamed}");
assert_eq!(symbol_tip("", ""), "");
}
#[test]
fn picture_and_shape_size_fields_show_unit_hints() {
use egui::accesskit::Role;
let cases = [
(false, "Shape Format", "Type a size in any unit, such as 3 cm or 300 px."),
(true, "Picture Format", "Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions."),
];
for (picture, tab, expected) in cases {
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
if picture {
a.run("insert.picture", json!({"data": png_data()})).unwrap();
} else {
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
}
let mut h = tab_harness(a, tab);
for side in ["W:", "H:"] {
let desc = h.get_by_role_and_label(Role::SpinButton, side).accesskit_node().description().unwrap_or_default();
assert_eq!(desc, expected, "{tab} {side} description");
}
h.get_by_role_and_label(Role::SpinButton, "W:").hover();
crate::test_harness::frames(&mut h, 40);
assert!(h.query_by_label_contains(expected).is_some(), "{tab} W: hover tooltip shows unit hint");
}
}
+57 -53
View File
@@ -8,7 +8,7 @@ use craft::ui::layout_components::{Row, Stack};
use craft::ui::menu::MenuItem;
use craft::ui::pickers::Select;
use super::common::menu_button;
use super::common::{labelled, menu_button};
use super::{Ui, WordApp, json};
/// The View tab's Views, Immersive, Page Movement, Show, Zoom, Dark Mode, Window, Macros and Templates
@@ -17,30 +17,32 @@ pub(super) fn view(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let v = app.session.view.clone();
let v_source = app.session.md_source.is_some();
row.group(RibbonGroup::new("view.views", tl!("Views").to_string(), IconId::new("printLayout").into()), |ui| {
Button::command(CommandRef::new("view.readMode"))
.label(tl!("Read\nMode").to_string())
.icon(IconId::new("readMode"))
.arrangement(Arrangement::Stacked)
.show(ui);
Button::command(CommandRef::new("view.printLayout"))
.label(tl!("Print\nLayout").to_string())
.icon(IconId::new("printLayout"))
.arrangement(Arrangement::Stacked)
.show(ui);
Button::command(CommandRef::new("view.webLayout"))
.label(tl!("Web\nLayout").to_string())
.icon(IconId::new("webLayout"))
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Button::command(CommandRef::new("view.outline")).label(tl!("Outline").to_string()).icon(IconId::new("outline")).show(ui);
Button::command(CommandRef::new("view.draft")).label(tl!("Draft").to_string()).icon(IconId::new("draft")).show(ui);
ToggleButton::command(CommandRef::new("view.markdownSource"))
.label(tl!("Markdown").to_string())
.tooltip(tl!("Markdown Source").to_string())
.icon(IconId::new("markdownSource"))
.selected(v_source)
labelled(ui, |ui| {
Button::command(CommandRef::new("view.readMode"))
.label(tl!("Read\nMode").to_string())
.icon(IconId::new("readMode"))
.arrangement(Arrangement::Stacked)
.show(ui);
Button::command(CommandRef::new("view.printLayout"))
.label(tl!("Print\nLayout").to_string())
.icon(IconId::new("printLayout"))
.arrangement(Arrangement::Stacked)
.show(ui);
Button::command(CommandRef::new("view.webLayout"))
.label(tl!("Web\nLayout").to_string())
.icon(IconId::new("webLayout"))
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Button::command(CommandRef::new("view.outline")).label(tl!("Outline").to_string()).icon(IconId::new("outline")).show(ui);
Button::command(CommandRef::new("view.draft")).label(tl!("Draft").to_string()).icon(IconId::new("draft")).show(ui);
ToggleButton::command(CommandRef::new("view.markdownSource"))
.label(tl!("Markdown").to_string())
.tooltip(tl!("Markdown Source").to_string())
.icon(IconId::new("markdownSource"))
.selected(v_source)
.show(ui);
});
});
});
row.group(RibbonGroup::new("view.immersive", tl!("Immersive").to_string(), IconId::new("immersive").into()), |ui| {
@@ -79,37 +81,39 @@ pub(super) fn view(row: &mut RibbonRow<'_>, app: &mut WordApp) {
});
});
row.group(RibbonGroup::new("view.zoom", tl!("Zoom").to_string(), IconId::new("zoom").into()), |ui| {
Button::command(CommandRef::with_params("ui.dialog", json!({"name": "zoom"})))
.label(tl!("Zoom").to_string())
.icon(IconId::new("zoom"))
.arrangement(Arrangement::Stacked)
.show(ui);
Button::command(CommandRef::new("view.zoom100"))
.label(tl!("100%").to_string())
.icon(crate::icons::spec("zoom100"))
.arrangement(Arrangement::Stacked)
.show(ui);
// Step the zoom up and down by 10% (issue #67), from whatever the page shows now.
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Button::command(CommandRef::new("view.zoomIn")).label(tl!("Zoom In").to_string()).icon(IconId::new("zoomIn")).show(ui);
Button::command(CommandRef::new("view.zoomOut")).label(tl!("Zoom Out").to_string()).icon(IconId::new("zoomOut")).show(ui);
});
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
ToggleButton::command(CommandRef::new("view.onePage"))
.label(tl!("One Page").to_string())
.icon(IconId::new("onePage"))
.selected(v.fit == "onePage")
labelled(ui, |ui| {
Button::command(CommandRef::with_params("ui.dialog", json!({"name": "zoom"})))
.label(tl!("Zoom").to_string())
.icon(IconId::new("zoom"))
.arrangement(Arrangement::Stacked)
.show(ui);
ToggleButton::command(CommandRef::new("view.multiplePages"))
.label(tl!("Multiple Pages").to_string())
.icon(IconId::new("multiplePages"))
.selected(v.multi_page)
.show(ui);
ToggleButton::command(CommandRef::new("view.pageWidth"))
.label(tl!("Page Width").to_string())
.icon(IconId::new("pageWidth"))
.selected(v.fit == "pageWidth")
Button::command(CommandRef::new("view.zoom100"))
.label(tl!("100%").to_string())
.icon(crate::icons::spec("zoom100"))
.arrangement(Arrangement::Stacked)
.show(ui);
// Step the zoom up and down by 10% (issue #67), from whatever the page shows now.
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Button::command(CommandRef::new("view.zoomIn")).label(tl!("Zoom In").to_string()).icon(IconId::new("zoomIn")).show(ui);
Button::command(CommandRef::new("view.zoomOut")).label(tl!("Zoom Out").to_string()).icon(IconId::new("zoomOut")).show(ui);
});
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
ToggleButton::command(CommandRef::new("view.onePage"))
.label(tl!("One Page").to_string())
.icon(IconId::new("onePage"))
.selected(v.fit == "onePage")
.show(ui);
ToggleButton::command(CommandRef::new("view.multiplePages"))
.label(tl!("Multiple Pages").to_string())
.icon(IconId::new("multiplePages"))
.selected(v.multi_page)
.show(ui);
ToggleButton::command(CommandRef::new("view.pageWidth"))
.label(tl!("Page Width").to_string())
.icon(IconId::new("pageWidth"))
.selected(v.fit == "pageWidth")
.show(ui);
});
});
});
row.group(RibbonGroup::new("view.darkMode", tl!("Dark Mode").to_string(), IconId::new("darkMode").into()), |ui| {
+14 -3
View File
@@ -1,6 +1,6 @@
//! The font box: Word's plain font picker over the app's catalog and its one recent-fonts list.
use std::sync::Arc;
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use craft::font_manager::Catalog;
use craft::font_manager::picker::{FontPicker, FontPickerKind, FontPickerOutput, FontPickerSettings, MissingAdvice};
@@ -41,10 +41,21 @@ impl CatalogRef {
/// The action rows after the font families, in the order `FontPickerOutput::action` indexes them:
/// Add Font…, and in the browser Load System Installed Fonts….
fn actions() -> Vec<Label> {
fn actions() -> Arc<Vec<Label>> {
static CACHE: OnceLock<Mutex<Option<(&'static str, Arc<Vec<Label>>)>>> = OnceLock::new();
let lang = crate::i18n::current().code();
let cell = CACHE.get_or_init(|| Mutex::new(None));
let mut guard = cell.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((cached_lang, rows)) = guard.as_ref()
&& *cached_lang == lang
{
return Arc::clone(rows);
}
let add = Label::from(tl!("Add Font…").to_string());
let load = cfg!(target_arch = "wasm32").then(|| Label::from(tl!("Load System Installed Fonts…").to_string()));
std::iter::once(add).chain(load).collect()
let rows = Arc::new(std::iter::once(add).chain(load).collect());
*guard = Some((lang, Arc::clone(&rows)));
rows
}
/// The command an action row runs.
+1
View File
@@ -150,6 +150,7 @@ impl WordApp {
command_states: _,
command_states_cache: _,
keytip_cache: _,
search_cache: _,
fonts_frames: _,
printing: _,
print_feedback_seen: _,
+12 -4
View File
@@ -1,14 +1,22 @@
# The root window hides instead of taking over another document
# The root window is never shown
The first window an app opens is the framework's root window, and the app ends when it closes. WordCraft
used to keep it open when the user closed it with other document windows open: it switched to another
window's document and that window disappeared, so the window the user closed stayed and a different one
vanished (#7752). We decided instead that the root window hides (storytold/craft-libs#584) and adopts
nothing, so the window the user closes is always the one that goes, and the app ends only when the last
document window closes or the user quits.
vanished (#7752). We decided instead that the window the user closes is always the one that goes, and
nothing adopts another document. The app ends only when the last document window closes or the user quits.
On native hosts (macOS, Windows, Linux, BSD) the root window is created hidden and never painted. Every
document window, the first one included, is a child window, so closing a document window closes exactly that
window. The web host is out of scope: it has one window, the page's canvas, which is the root viewport and
draws the document itself, so there it stays as it is. The mechanism comes
from the prototype in storytold/craft-libs#584; the framework docs (`docs/craft-framework.md` in
craft-libs) will carry it.
## Considered options
- **Root takes over another document** (the old behaviour): no framework change, but it is the reported bug,
and the moved window loses its position and size.
- **Root shows no document and stays visible**: leaves an empty window the user did not ask for.
- **Root hides when it is closed** (storytold/craft-libs#4218): cannot work on Wayland, where winit's
`set_visible` is a no-op, so the root never hides and its close button goes dead.
+18 -10
View File
@@ -1,34 +1,39 @@
# Implementation plan: closing document windows
For [the specification](../specs/multi-window-close.md) (#7822, part of #7671). Steps run in order; each is
For [the specification](../specs/multi-window-close.md) (#7822, part of #7671). Four steps run in order; each is
its own PR.
## 1. craft-libs prerequisites (base `next`)
## 1. storytold/egui patches
- **Hidden root window** (storytold/craft-libs#584, [ADR 0001](../adr/0001-hidden-root-window.md)): the root
OS window can close or hide while document windows stay open, and adopts nothing.
- eframe never paints a viewport built with `visible == Some(false)` (wgpu); it still runs that viewport's ui.
- egui-winit skips the XDG activation token for a hidden root.
## 2. craft-libs PR (storytold/craft-libs#584, [ADR 0001](../adr/0001-hidden-root-window.md))
- The root is created hidden and every document window is a child; `adopt` is removed. Documented in
`docs/craft-framework.md`.
- **Test kit with any number of windows** (C5-8): `craft_ui_test_kit::windows::Windows` keeps focus and close
events per child, so three-window tests can target one child.
- Not in scope: the cursor on non-root windows (C5-5, `cursor::image_target`) gets its own issue.
## 2. Repin craft-libs in WordCraft
## 3. Repin craft-libs in WordCraft
Brings storytold/craft-libs#3290 (one modal stack across windows) and the two changes above. Stage 3 of
#7671 does this repin.
Brings storytold/craft-libs#3290 (one modal stack across windows) and the changes above. Stage 3 of #7671
does this repin.
## 3. WordCraft PR (Fixes #7822)
## 4. WordCraft PR (Fixes #7822)
Code is in `crates/ui-egui/src/` unless noted.
| Spec rule | Change |
|---|---|
| 1 | Drop the root taking over another document (`settle_windows` in `windows.rs`); closing the root window closes it through step 1's hidden root. Rewrite `closing_a_window_asks_first_and_the_root_adopts_another`. |
| 1 | Drop the root taking over another document (`settle_windows` in `windows.rs`); the first document window is a child like the rest, so no root window is left to close. Rewrite `closing_a_window_asks_first_and_the_root_adopts_another`. |
| 2 | `other_window_on_document` filters windows by document (C5-6). |
| 3, 9 | `app::Closing` records the window that owns the prompt. Pumping, cancelling and closing the prompt use that window's dialog host, not the active one. |
| 4, 9 | `run` and `close_decision` check `closing` first: a close while one is running raises the prompt and returns, never calls `begin_closing` again. |
| 9 | Clearing `closing.prompt` in `sync_document` and `apply_close_answer` either continues the close or ends it, so no `Hold` is left with no prompt. `apply_close_answer` matches the guard's document, not the active one. |
| 5 | Cancelling Save As during a close cancels the close or quit (`continue_after_save`). |
| 7 | On one-document-at-a-time hosts, the root close acts on the active entry, not `root_key()`; the fallback layer keeps its close button (C5-1..3). |
| 7 | On one-document-at-a-time hosts, a close acts on the active entry, not `root_key()` (on the web that is the root window's close; on a full-screen or Wayland-maximized document window, that window's); the fallback layer keeps its close button (C5-1..3). |
| 8 | `file.close` takes `save`; `close_refused` names both options. `ui.closeWindow` takes `window` and defaults to `active_viewport()` (`control/handler.rs`). Update `docs/control-protocol.md` and `docs/mcp.md`. |
| — | `queue_for_window` repaints the target window (C5-7). |
@@ -36,3 +41,6 @@ Tests: the table in the specification, in `windows/tests.rs` and `documents.rs`.
Checks: `cargo fmt --all --check`, `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings`,
`cargo test -p wordcraft-ui-egui`, `cargo xtask layers`, `cargo xtask wasm`.
Real-window checks before step 4 merges: KDE Wayland; Windows; GNOME (requested on craft-libs#584); macOS
through CI plus a confirmation request in the PR. The release waits for this on all platforms.
+29 -22
View File
@@ -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)
@@ -42,8 +42,13 @@ every day, checked end to end on the main platform (macOS desktop), including sa
| References for reports and papers: TOC, footnotes, citations and bibliography, captions | yes | Updatable TOC field (#52), notes, APA/MLA/Chicago/IEEE, Zotero (#189); long footnotes don't continue (gap #4) | 0 |
| Share or print: export PDF, print | partial (not blocking) | PDF export solid (krilla); desktop printing goes through a PDF, no native print dialog (gap #6) | 0 (beta work: 6–10) |
**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**.
**Result: passed before the port.** At that check every core workflow completed on macOS and the work saved and
reopened; the partial rows were 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
@@ -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
View File
@@ -1,6 +1,6 @@
# WordCraft parity with Microsoft Word
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** trivial (Proofing: freestanding custom dictionary file support, #5840; previously trivial: Equations: `\int` + Space leaves ∫ waiting for its limits, `_a^b` then Space builds them, and the operand typed next goes inside, observed in Word for Windows on #4938, #4917; no percentage change; previously trivial: Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Tables row: tables nest 18 deep at most, so a .json save reads back, #3618); previously trivial (Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
> **Last reviewed:** 2026-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 plus English (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. Languages with neither a built-in nor an installed dictionary 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, online pictures, screenshot (WordArt effects and glued connectors landed in #416). **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 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 |
+28 -14
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Local regression checks for WordCraft's supervised manual nightly workflows and v3 policy."""
"""Local regression checks for WordCraft's automated and manual nightly workflows and v3 policy."""
import copy
import json
from pathlib import Path
@@ -147,6 +147,8 @@ NIGHTLY_TRUST = {
# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot.
# Update by PR, in the caller and the policy, when the team changes.
RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"]
AUTOMATIC_SIGNER_ACTORS = ["github-actions[bot]"]
NIGHTLY_SCHEDULE_CRON = "0 7 * * *"
def producer_platforms(source):
@@ -222,7 +224,9 @@ class TrustedSourcePreparation(unittest.TestCase):
producer_platforms(source.replace(" " + current + "\n", ""))
def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self):
for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")):
for name, workflow in (("nightly.yml", "nightly.yml"),
("nightly-dispatch.yml", "nightly-dispatch.yml"),
("nightly-sign.yml", "nightly-sign.yml")):
source = (ROOT / ".github/workflows" / workflow).read_text()
expected = NightlyEnabledCallers.GUARDS[name]
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
@@ -240,15 +244,21 @@ class TrustedSourcePreparation(unittest.TestCase):
self.assertTrue(literal_off("${{ false }}"))
self.assertTrue(literal_off("false && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')"))
def test_no_nightly_schedule_is_registered(self):
for name, event in (("nightly.yml", "workflow_dispatch"),
("nightly-sign.yml", "workflow_dispatch")):
def test_nightly_triggers_and_schedule_match_review(self):
expected_triggers = {
"nightly.yml": [" schedule:", " workflow_dispatch:"],
"nightly-sign.yml": [" workflow_dispatch:"],
}
for name, expected in expected_triggers.items():
source = (ROOT / ".github/workflows" / name).read_text()
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
triggers = [line for line in events.splitlines() if line.startswith(" ")
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
with self.subTest(workflow=name):
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
self.assertEqual(triggers, expected, "schedule/activation needs explicit review")
if name == "nightly.yml":
crons = re.findall(r"(?m)^ - cron: '([^']+)'$", events)
self.assertEqual(crons, [NIGHTLY_SCHEDULE_CRON], "nightly cron must match reviewed cadence")
def test_signer_serialization_contract_is_enforced(self):
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
@@ -358,12 +368,13 @@ class NightlyTrustAnchors(unittest.TestCase):
class NightlyEnabledCallers(unittest.TestCase):
"""Producer and signer run only in their exact context, for the reviewed manual actor."""
"""Producer, dispatch and signer run only in their exact context, for the reviewed actors."""
GUARDS = {
"nightly.yml": "github.repository == 'storytold/wordcraft' && github.ref == 'refs/heads/main' && "
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
"github.event_name == 'workflow_dispatch')",
"nightly-dispatch.yml": "github.repository == 'storytold/wordcraft' && github.event_name == 'workflow_run'",
"nightly-sign.yml": "github.repository == 'storytold/wordcraft' && github.event_name == 'workflow_dispatch' && "
"github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'",
}
@@ -382,7 +393,8 @@ class NightlyEnabledCallers(unittest.TestCase):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
policy = json.loads(INSTALLED_POLICY.read_text())
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
self.assertEqual(policy["automatic_signer_actors"], AUTOMATIC_SIGNER_ACTORS,
"automatic signer actor must be exactly the reviewed Actions bot")
def test_an_actor_outside_the_release_managers_is_refused(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
@@ -812,19 +824,21 @@ def dispatch_triggers(source):
class NightlyDispatchTransport(unittest.TestCase):
"""The scheduled transport stays literally off and can only reach the signer branch."""
"""The scheduled transport runs only for completed scheduled producer runs and can only reach the signer branch."""
def setUp(self):
self.source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text()
def test_every_dispatch_job_is_literal_off(self):
def test_dispatch_job_keeps_exact_context_guard(self):
jobs = self.source.split("\njobs:\n", 1)[1]
headers = re.findall(r"(?m)^ (?![\s#])[^\n]+", jobs)
conditions = job_conditions(jobs)
self.assertTrue(headers)
self.assertEqual(len(conditions), len(headers), "every job needs a literal-off condition")
for _, expression in conditions:
self.assertTrue(literal_off(expression), "nightly activation requires reviewed test update")
self.assertEqual(headers, [" dispatch:"])
self.assertEqual(len(conditions), 1)
indicator, expression = conditions[0]
self.assertEqual(indicator, ">-")
self.assertFalse(literal_off(expression), "scheduled dispatch transport must be enabled")
self.assertEqual(" ".join(expression.split()), NightlyEnabledCallers.GUARDS["nightly-dispatch.yml"])
def test_only_a_completed_scheduled_producer_is_transported(self):
self.assertEqual(re.findall(r"(?m)^ workflows: (.+)$", self.source),