Compare commits

...
Author SHA1 Message Date
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-29 03:25:47 +00:00
60 changed files with 1384 additions and 874 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}");
}
+87
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),
@@ -1054,4 +1115,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);
}
+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");
}
+29 -8
View File
@@ -24,6 +24,9 @@ pub(crate) struct ChromeOpen {
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 +247,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 +277,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");
}
}
+10 -11
View File
@@ -163,11 +163,12 @@ 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;
}
// Build the history rows only when the popover is about to show; idle frames skip allocating/localizing them.
let labels = if open { undo_list_rows(app) } else { Vec::new() };
let mut mark = app.chrome.undo_mark;
let mut picked = None;
Popover::new(tl!("Undo History").to_string(), Bind::bound(&mut open)).opened_by(&out.response).show(ui, |ui, cx| {
@@ -213,19 +214,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"})))
+153 -15
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,14 +241,67 @@ 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,
}
}
@@ -482,8 +535,10 @@ pub(crate) fn highlight_button_appearance(name: &str) -> (&'static str, Option<C
/// removes highlighting (#2105).
fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> ColorPick {
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))
let in_effect = wordcraft_engine::cmd::format::cached_state(&app.session)
.get("highlight")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| "none".into());
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();
@@ -529,14 +584,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 +669,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 +703,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 +712,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 +846,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")));
}
}
+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;
}
+5 -3
View File
@@ -22,7 +22,9 @@ 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_only(prepare_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();
@@ -75,8 +77,8 @@ pub(crate) struct WordCountDialog {
}
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 }
}
}
+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,
+81
View File
@@ -1892,6 +1892,45 @@ 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");
}
/// #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 +2379,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 +2543,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,
+1 -1
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",
+4 -1
View File
@@ -129,6 +129,8 @@ struct Strings {
numeral_id: String,
proofing_language: String,
autosave_reason: String,
/// The Initials box's placeholder: the initials an empty box falls back to (#8018).
initials_hint: String,
}
impl Strings {
@@ -199,6 +201,7 @@ impl Strings {
numeral_id,
proofing_language,
autosave_reason: crate::AutoSaveBlock::Browser.reason().to_string(),
initials_hint: app.session.user_initials(),
}
}
}
@@ -357,7 +360,7 @@ impl PreferencesModel for OptionsModel<'_> {
Some(tl!("Personalize")),
vec![
RowSpec::new("general.userName", tl!("User name:"), RowKind::Text(&app.session.author)).enabled(!protected),
RowSpec::new("general.initials", tl!("Initials:"), RowKind::Text(&app.session.initials)),
RowSpec::new("general.initials", tl!("Initials:"), RowKind::Text(&app.session.initials)).placeholder(&s.initials_hint),
],
),
],
+33
View File
@@ -539,3 +539,36 @@ fn folder_settings_have_apply_and_clear() {
}
let _ = std::fs::remove_dir_all(&dir);
}
/// #8018: an empty Initials box paints the initials it falls back to.
#[test]
fn empty_initials_box_paints_the_default_initials() {
fn painted(shapes: &[egui::epaint::ClippedShape], out: &mut Vec<String>) {
fn walk(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|c| walk(c, out)),
_ => {}
}
}
shapes.iter().for_each(|c| walk(&c.shape, out));
}
let shown = || {
let mut a = app();
a.session.author = "Zora Quentin".into();
a.run("ui.backstage", json!({"value": true, "page": "options", "pane": "general"})).unwrap();
let mut h = crate::test_harness::builder().build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
options_frames(&mut h, 3);
let mut texts = Vec::new();
painted(&h.output().shapes, &mut texts);
texts
};
assert!(shown().iter().any(|t| t == "ZQ"), "empty box paints the default initials");
}
+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.
+6
View File
@@ -91,11 +91,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");
}
}
+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: _,
+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),