Compare commits

..
Author SHA1 Message Date
reubgrandClaude Sonnet 5.5 4767a33981 validate: grade a settings DOCTYPE by its measured cell whatever the content-type casing (#8004)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-28 21:31:12 +00:00
Martin BallandClaude Opus 5.5 4699c8d7c7 fix(dialogs): frame the lists of Customize Ribbon and Quick Access Toolbar (#8037)
Part of #7981. v0.19.1 drew a border around these lists; after the port an
empty or short list has no visible bounds. Uses SurfaceKind::Frame, which List
already takes through its surface prop.


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

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-28 21:12:00 +00:00
Dylan M. Taylor 7abfe7d86a ci: pin storytold/craft-common-actions to @main universally (#8065) 2026-11-28 16:07:48 -05:00
Martin BallandClaude Opus 5.5 08a4392b18 fix(layout): keep a negatively indented table inside the Read Mode column (#8020) (#8039)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-28 20:57:02 +00:00
Dylan M. Taylor d1bb1ff547 ci(nightly): enable all signed Linux package formats (deb, rpm, appimage, flatpak, oci, arch) (#8061) 2026-11-28 15:32:06 -05:00
Martin BallandClaude Opus 5.5 56512dbc1d UI port: dialog captions, previews and clipped text (#7671) (#8026)
* fix(dialogs): draw captions for bare fields and radio groups (part of #7976)

A text box, number box, drop-down or radio group names itself for assistive
technology but draws no caption, so dialogs showed bare controls. Add
host::labelled (caption beside) and host::captioned (caption above), both over
craft's Field, which names the control by the same label, and use them where a
dialog drew a bare control: Envelopes, Labels, Table Properties, Custom
Properties, Index, Merge To, Insert Merge Field, Find Recipient, Rule If/Skip
If, Paste Special, Page Numbers, Line Numbers, Sort, Table Formula, Drop Cap,
Define List, Define Bullet, Enclose, Recipient List and the Borders/Shading
colour rows. The shared number helpers (count/length/percent/named field) label
every dialog that uses them (Hyphenation, Page Setup size, Insert Table...).

Partial: the Bookmark Sort by group is left to the Bookmark fix. Cross-reference and
Language lists get a plain caption line (a Field would rename the list), and the
Borders/Shading colour rows get plain text beside them (a Field would drop the
spoken colour). A group inside a titled section uses radios_in_section, and a box
after a same-named radio uses count_box, so no caption is drawn twice.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(dialogs): draw previews at a sample size, not the icon side (part of #7977)

A Picture takes the icon side as its height unless given an extent, so the
Enclose, Define Bullet, Define List and Manage Styles previews shrank to
icons. Give them PictureSize::Sample(Large) (the style preview its device-pixel
size). Borders, Page Borders, Shading and Columns draw their previews inside
craft widgets (EdgePicker, the Columns dialog), so they need a craft-libs fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(dialogs): Custom Properties footer, Recipient List headers, Special Characters shortcuts (part of #7982)

- Custom Properties: with no properties the list's own empty text is measured
  shorter than it is drawn, so the dialog was a row short and its footer was
  drawn over the Value box and the hint. The empty text is now a plain line.
- Recipient List: the columns shared the dialog's width, so six field names
  were cut to "First N", "Addre"; each column now takes a fixed share of control
  heights and the grid scrolls.
- Special Characters: the Shortcut key column took a third of the list and cut
  "Ctrl+Shift+..."; it now takes a fixed width.
Insert Chart type names, Page Setup margins, File Home/New names, the zoom label
and the Paragraph preview are craft widgets and need their own fixes.

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-28 20:19:59 +00:00
Martin BallandClaude Opus 5.5 4deb338b44 UI port: Symbol tiles and Equation/SmartArt pictures follow the craft theme's colours (#7671) (#8046)
* fix(symbol): glyph tiles follow the theme's light or dark mode (#8021)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(theme): Equation and SmartArt pictures take the craft theme's text colours, not egui's visuals (Part of #7975)

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-28 20:18:24 +00:00
Martin BallandClaude Opus 5.5 0c6c377681 fix(backstage): File menu page rows a theme gap apart, as v0.19.1 (#8022) (#8047)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-28 20:18:18 +00:00
Martin BallandClaude Opus 5.5 17c163c425 Read Mode: 4 columns at 1440 px as before (#8019) (#8038)
* fix(read-mode): lay out 4 columns at 1440 px, not 2 (#8019)

craft's reading_size takes its column target from the body text's measure
(66 characters), which is wider than the 295 px v0.19.1 used. Keep the
gaps from the tokens and pin the target and least width to the old values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(read-mode): page arrows back at the bottom right, as v0.19.1 (#8019)

The page-turn row sat at the bottom left (craft's ReadingNav start). Lay it out from the far end, inset by the page view's side margin token; it mirrors to the bottom left in a right-to-left interface.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-28 20:18:12 +00:00
Martin BallandClaude Opus 5.5 6fbf780789 UI port: Cell Margins shows lengths in the interface unit; Organizer shows both style lists (#7671) (#8031)
* fix(dialogs): Cell Margins shows points in the interface unit, not as cm (#7970)

The fields held points but only labelled them with the unit, so 5.4 pt read 5.4 cm. They now declare points and a length unit, so the field converts as every other length field does. OK without an edit never wrote margins (the dialog compares against the stored values); the test pins that and the shown unit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(dialogs): Organizer shows both style lists with Copy, Delete and Rename between (#7980)

The lists sat in one row that the first list filled, which pushed the other file's list off the dialog. Three grid columns, as the old dialog had; Rename starts the list's own rename field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* test(dialogs): Cell Margins converts a typed length back to points (#7970)

Cover the typed path CodeRabbit asked about: 1 cm typed in the field reaches the table as about 28.35 pt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(dialogs): frame the Organizer's Document and Template lists

Part of #7980. v0.19.1 drew a border around both lists; after the port an
empty list has no visible bounds. Uses SurfaceKind::Frame, which List already
takes through its surface prop. Builds on the Organizer layout of #8031.

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-28 18:51:07 +00:00
Martin BallandClaude Opus 5.5 57fb4544f2 UI port: Read Mode table fit, Options slider, Apply/Clear and hints (#7671) (#8025)
* fix(layout): Read Mode fits a wide table to its column (#7988)

In the reading view a table with its own width is scaled to the column,
less its start offset (indent plus half border), mirrored tables too.

Not addressed here: Read Mode laying out 2 wider columns where v0.19.1
laid out 4, and the pager moving from bottom right to bottom left.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(options): Read Aloud slider, one Agents heading, hints, Apply/Clear on folders (#7987)

Part of #7987. Fixed: the Read Aloud speed is a slider again; the Agents
page no longer repeats its heading; the Display and Save hints sit under
the rows they explain (they were page footnotes), and the Privacy hint
is back; User templates and Dictionaries folder have v0.19.1's Apply and
Clear and the placeholder again (typing saves nothing until Apply or
Enter; Clear returns to the default).

Still open: the General > Initials placeholder (RowKind::Text has no
placeholder, needs craft-libs); the speed slider's accessible value text
does not carry the x unit. Reset Section at the bottom of Advanced is
not a defect: the page scrolls.

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-28 18:50:56 +00:00
Dylan M. Taylor eeeb31d85f ci(nightly): roll out signing pin, macOS docs layout, and profile reopen fix (#8045) 2026-11-28 11:56:37 -05:00
Martin BallandClaude Opus 5.5 5796c665b9 ci(sonar): ignore S8707 path traversal in crates/validate developer scripts (#7994)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 23:38:04 +00:00
FredApps e74e627a38 parity: headless column from the engine registry (RFC-0052) (#7969) 2026-11-28 00:01:17 +01:00
53 changed files with 1382 additions and 430 deletions
+3 -3
View File
@@ -4,10 +4,10 @@
"repository_id": 1408489772,
"producer_workflow_id": 429734489,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
+6 -6
View File
@@ -44,10 +44,10 @@ jobs:
- name: Install the system libraries the GUI links
run: sudo apt-get update && sudo apt-get install -y pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
@@ -128,10 +128,10 @@ jobs:
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
@@ -188,10 +188,10 @@ jobs:
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
+16 -2
View File
@@ -34,12 +34,26 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: main
app-name: wordcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment (which trusts release and
# nightly-signer) and export keys in its signing step.
+3 -2
View File
@@ -22,9 +22,9 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: main
app-name: wordcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
@@ -32,3 +32,4 @@ jobs:
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+1
View File
@@ -74,5 +74,6 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
- Contributor credits: `docs/contributors.md`.
+11
View File
@@ -889,6 +889,17 @@ fn parity_markdown(p: &Value) -> String {
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
}
let h = &p["headless"];
s += &format!(
"\n**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n",
h["yes"],
h["no"]["window"].as_u64().unwrap_or(0) + h["no"]["os"].as_u64().unwrap_or(0) + h["no"]["engine-gap"].as_u64().unwrap_or(0),
h["no"]["window"],
h["no"]["os"],
h["no"]["engine-gap"],
h["partial"],
h["unknown"]
);
s += "\n## Missing\n\n";
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
let m = t["missing"].as_array().cloned().unwrap_or_default();
+76 -1
View File
@@ -157,6 +157,9 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
if std::fs::metadata(&child).is_ok_and(|meta| !meta.is_dir()) {
return Err(format!("the nightly {label} must be a directory"));
}
Ok(child)
}
@@ -171,11 +174,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(windows)]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
let _ = (path, metadata);
Ok(())
}
/// The app's exclusive create probe: a file only this process can have made, created and removed.
pub fn probe_writable(dir: &Path) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
@@ -245,6 +293,8 @@ fn validate_for(
Ok(confirmed)
}
const PROFILE_FOLDERS: [&str; 5] = ["recovery", "logs", "fonts", "Templates", "FontStore"];
#[cfg(test)]
mod tests {
use super::*;
@@ -341,6 +391,31 @@ mod tests {
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
+137 -1
View File
@@ -532,6 +532,98 @@ Tools|Templates|Templates and Add-ins|tools.templates
Tools|Views|Full Screen View|view.fullScreenView
";
/// RFC-0052 hand marks for catalog features with no engine command: `id|headless|reach|why`.
///
/// `headless` is `no` or `partial`, `reach` is `window` (needs a desktop window, dialog or
/// pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could
/// be an engine command, isn't one yet). `yes` is never written here: a feature is `yes` only when
/// its id is in the engine registry that `wordcraft-cli` and the MCP server load, and a mark on such
/// an id is stale (`headless_errors`). A missing feature with no mark is `unknown`.
pub const HEADLESS: &str = "\
tools.dictate|no|os|speech recognition service
insert.onlinePicture|no|os|online image search service
insert.model3d|no|engine-gap|3-D model files could be inserted by a command
insert.screenshot|no|os|screen capture of other windows
addins.get|no|os|add-in store service
insert.video|no|os|online video service
insert.inkEquation|no|window|drawn with a pen or pointer
draw.inkToMath|no|os|handwriting recognition service
review.translate|no|os|online translation service
review.blockAuthors|no|os|co-authoring service
view.readLayout|no|window|Read Mode window layout
";
/// One feature's RFC-0052 `headless:` value and, for `no`/`partial`, its `reach:` and reason.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Headless {
pub value: &'static str,
pub reach: Option<&'static str>,
pub why: &'static str,
}
const REACHES: [&str; 3] = ["window", "os", "engine-gap"];
/// Parsed `HEADLESS`-format marks: (id, value, reach, why). A malformed line is an error.
pub fn headless_marks(src: &'static str) -> Result<Vec<(&'static str, Headless)>, String> {
let mut out = Vec::new();
for line in src.lines().filter(|l| !l.trim().is_empty()) {
let f: Vec<&'static str> = line.splitn(4, '|').collect();
let [id, value, reach, why] = f[..] else {
return Err(format!("headless mark `{line}`: want `id|headless|reach|why`"));
};
if !matches!(value, "no" | "partial") {
return Err(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
}
if !REACHES.contains(&reach) {
return Err(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap"));
}
if out.iter().any(|(m, _)| *m == id) {
return Err(format!("headless mark `{id}` is written twice"));
}
out.push((id, Headless { value, reach: Some(reach), why }));
}
Ok(out)
}
/// The `headless:` value of a catalog feature: `yes` when the engine registry has its id, else its
/// hand mark, else `unknown`.
pub fn headless_of(id: &str, live: bool, marks: &[(&'static str, Headless)]) -> Headless {
if live {
return Headless { value: "yes", reach: None, why: "" };
}
marks.iter().find(|(m, _)| *m == id).map(|(_, h)| *h).unwrap_or(Headless { value: "unknown", reach: None, why: "" })
}
/// Problems with the marks against the catalog and the registry's ids: unknown ids, and marks on
/// ids the engine registry has (they would hide a `yes`).
pub fn headless_errors(src: &'static str, catalog: &[(&str, &str, &str, &str)], live: impl Fn(&str) -> bool) -> Vec<String> {
let marks = match headless_marks(src) {
Ok(m) => m,
Err(e) => return vec![e],
};
let mut errs = Vec::new();
for (id, _) in &marks {
if !catalog.iter().any(|e| e.3 == *id) {
errs.push(format!("headless mark `{id}` is not a catalog id"));
} else if live(id) {
errs.push(format!("headless mark `{id}` is stale: the engine registry has it, so it is `yes`"));
}
}
errs
}
/// Headless counts in the RFC-0052 summary shape.
fn headless_summary(values: &[Headless]) -> Value {
let count = |v: &str| values.iter().filter(|h| h.value == v).count();
let no = |r: &str| values.iter().filter(|h| h.value == "no" && h.reach == Some(r)).count();
json!({
"yes": count("yes"),
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
"partial": count("partial"),
"unknown": count("unknown"),
})
}
/// Catalog entries: (tab, group, feature, id).
pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)> {
CATALOG
@@ -546,9 +638,13 @@ pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)
/// Parity summary: per tab and overall, with the missing features.
pub fn parity(reg: &Registry) -> Value {
let e = entries();
let marks = headless_marks(HEADLESS).unwrap_or_default();
let mut values = Vec::with_capacity(e.len());
let mut tabs: Vec<(&str, usize, usize, Vec<String>)> = Vec::new();
for (tab, group, label, id) in &e {
let have = reg.get(id).is_some();
let h = headless_of(id, have, &marks);
values.push(h);
let t = match tabs.iter_mut().find(|t| t.0 == *tab) {
Some(t) => t,
None => {
@@ -564,7 +660,8 @@ pub fn parity(reg: &Registry) -> Value {
if have {
t.1 += 1;
} else {
t.3.push(format!("{group} › {label} (`{id}`)"));
let reach = h.reach.map(|r| format!(", reach: {r} ({})", h.why)).unwrap_or_default();
t.3.push(format!("{group} › {label} (`{id}`): headless: {}{reach}", h.value));
}
}
let live = tabs.iter().map(|t| t.1).sum::<usize>();
@@ -573,6 +670,7 @@ pub fn parity(reg: &Registry) -> Value {
"live": live,
"total": total,
"percent": if total == 0 { 0.0 } else { (live as f64 * 1000.0 / total as f64).round() / 10.0 },
"headless": headless_summary(&values),
"tabs": tabs.iter().map(|t| json!({"tab": t.0, "live": t.1, "total": t.2, "missing": t.3})).collect::<Vec<_>>(),
})
}
@@ -597,6 +695,44 @@ mod tests {
assert!(pct >= 90.4, "parity {pct}%");
}
#[test]
fn headless_marks_are_current() {
let reg = crate::cmd::registry();
let errs = headless_errors(HEADLESS, &entries(), |id| reg.get(id).is_some());
assert!(errs.is_empty(), "{errs:?}");
}
#[test]
fn headless_yes_comes_only_from_the_registry() {
let marks = headless_marks("a.b|no|window|pointer\n").unwrap();
assert_eq!(headless_of("a.b", true, &marks).value, "yes", "a live id is yes whatever the mark says");
assert_eq!(headless_of("a.b", false, &marks).reach, Some("window"));
assert_eq!(headless_of("c.d", false, &marks).value, "unknown");
assert!(headless_marks("a.b|yes|window|x\n").is_err(), "a hand-written yes is refused");
assert!(headless_marks("a.b|no|desk|x\n").is_err(), "reach must be window, os or engine-gap");
assert!(headless_marks("a.b|no\n").is_err());
assert!(headless_marks("a.b|no|os|x\na.b|partial|os|y\n").is_err(), "one mark per id");
}
#[test]
fn headless_errors_flag_stale_and_unknown_marks() {
let cat = [("T", "G", "F", "a.b"), ("T", "G", "H", "c.d")];
let errs = headless_errors("a.b|no|os|x\nz.z|no|os|y\n", &cat, |id| id == "a.b");
assert!(errs.iter().any(|e| e.contains("`a.b` is stale")), "{errs:?}");
assert!(errs.iter().any(|e| e.contains("`z.z` is not a catalog id")), "{errs:?}");
assert!(headless_errors("bad\n", &cat, |_| false).len() == 1);
}
#[test]
fn parity_counts_every_feature_once_in_the_headless_summary() {
let p = parity(&crate::cmd::registry());
let h = &p["headless"];
let n = |v: &Value| v.as_u64().unwrap_or(0);
let no = n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]);
assert_eq!(n(&h["yes"]) + no + n(&h["partial"]) + n(&h["unknown"]), n(&p["total"]));
assert_eq!(n(&h["yes"]), n(&p["live"]), "every live feature is an engine command here");
}
#[test]
fn read_mode_view_menu_is_catalogued() {
let e = entries();
+22 -1
View File
@@ -10,7 +10,7 @@ use wordcraft_geom::Rect;
use crate::boxes::BoxContext;
use crate::para::{CellText, ClKind, ParaLayout};
use crate::{BoxInput, BoxLayout, Ctx, Placed, layout_box};
use crate::{BoxInput, BoxLayout, Ctx, Placed, ViewMode, layout_box};
/// Largest preferred table width, as a share of the text column, that a file can ask for.
const MAX_WIDTH_SHARE: f32 = 10.0;
@@ -431,6 +431,12 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
grid.iter_mut().for_each(|w| *w *= k);
total = avail;
}
// The reading view reflows to its column, so even a table with its own width fits it (#7988).
if ctx.opts.view == ViewMode::Read && total > avail && avail > 0.0 {
let k = avail / total;
grid.iter_mut().for_each(|w| *w *= k);
total = avail;
}
if !t.props.fixed {
// Measuring lays paragraphs out once more; it mustn't count their equations twice.
let eq_count = ctx.eq_count;
@@ -477,6 +483,14 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
} else {
indent - first_cell_left_margin_in(t, margins_def)
};
// The reading view fits the table into what the start offset leaves of the column, mirrored or not (#7988).
let room = (avail - start_offset.max(0.0)).max(1.0);
if ctx.opts.view == ViewMode::Read && acc > room && !matches!(t.props.align, Some(Align::Center | Align::Right)) {
let k = room / acc;
colx.iter_mut().for_each(|c| *c *= k);
acc = room;
total = room;
}
let x = match (t.props.align, rtl) {
(Some(Align::Center), _) => (avail - total) / 2.0,
// End alignment: the right margin, or the left one in a right-to-left table.
@@ -485,6 +499,13 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
(_, true) => avail - total - start_offset,
(_, false) => start_offset,
};
// The reading view has no margin to hang a negative indent into: keep the table inside the column (#8020).
// The clamp also pulls in an over-large positive indent. A table wider than the column keeps its start edge.
let x = if ctx.opts.view == crate::ViewMode::Read {
if total > avail { if rtl { avail - total } else { 0.0 } } else { x.clamp(0.0, avail - total) }
} else {
x
};
TableFrame { ncols, colx, acc, total, margins_def, tborders, rtl, x }
}
+58
View File
@@ -660,6 +660,31 @@ fn reading_layout_reflows_into_viewport_height_pages_without_changing_print_layo
assert!(invalid.pages.iter().all(|p| p.w.is_finite() && p.h.is_finite()));
}
#[test]
fn reading_layout_fits_a_wide_table_to_the_column() {
crate::test_fonts();
// #7988: a 468 pt table is wider than a reading column but must not run past its edge, however it is indented or mirrored.
let cases = [(0.0, false, None), (36.0, false, None), (36.0, true, None)];
let aligned = [None, Some(Align::Left), Some(Align::Center), Some(Align::Right)].map(|a| (36.0, false, a));
let aligned_rtl = [Some(Align::Left), Some(Align::Right)].map(|a| (36.0, true, a));
for (indent, rtl, align) in cases.into_iter().chain(aligned).chain(aligned_rtl) {
let mut d = Document::from_text("Before.");
let mut t = Table::new(2, 4, 468.0);
t.props.indent = Some(indent);
t.props.bidi_visual = rtl;
t.props.align = align;
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
let opts = LayoutOptions { view: ViewMode::Read, web_width: 360.0, read_height: 600.0, ..Default::default() };
let l = layout(&d, &mut LayoutCache::new(), &opts);
let p = &l.pages[0];
let cells: Vec<_> = p.items.iter().filter_map(|i| if let Placed::Cell { rect, .. } = i { Some(*rect) } else { None }).collect();
let (left, right) = cells.iter().fold((f32::MAX, 0.0f32), |(l, r), c| (l.min(c.x), r.max(c.x + c.w)));
assert!(right > left, "cells placed");
assert!(right <= p.body.x + p.body.w + 0.5, "indent {indent} rtl {rtl} {align:?}: right {right} vs column {}", p.body.x + p.body.w);
assert!(left >= p.body.x - 0.5, "indent {indent} rtl {rtl} {align:?}: left {left} vs column {}", p.body.x);
}
}
#[test]
fn hit_and_caret_agree() {
crate::test_fonts();
@@ -17799,3 +17824,36 @@ fn header_text_covers_the_whole_band_of_centred_and_right_lines() {
assert!(hit(x + left - 60.0), "{align:?}: beyond 40pt left of the band the picture is hit");
}
}
#[test]
fn reading_layout_keeps_a_negatively_indented_table_in_the_column() {
crate::test_fonts();
// #8020: a table indented left of the margin ran out of the column's start edge (right edge when mirrored).
for (rtl, width, indent, align) in [
(false, 300.0, -36.0, None),
(true, 300.0, -36.0, None),
(true, 400.0, -36.0, None),
(false, 400.0, -36.0, None),
(false, 300.0, -36.0, Some(Align::Center)),
] {
let mut d = Document::from_text("Before.");
let mut t = Table::new(2, 4, width);
t.props.indent = Some(indent);
t.props.bidi_visual = rtl;
t.props.align = align;
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
let opts = LayoutOptions { view: ViewMode::Read, web_width: 360.0, read_height: 600.0, ..Default::default() };
let l = layout(&d, &mut LayoutCache::new(), &opts);
let p = &l.pages[0];
let cells: Vec<_> = p.items.iter().filter_map(|i| if let Placed::Cell { rect, .. } = i { Some(*rect) } else { None }).collect();
let (left, right) = cells.iter().fold((f32::MAX, 0.0f32), |(l, r), c| (l.min(c.x), r.max(c.x + c.w)));
assert!(right > left, "cells placed");
// A table wider than the column keeps its start edge there; one that fits is inside at both edges.
if !rtl || width <= 300.0 {
assert!(left >= p.body.x - 0.5, "rtl {rtl} width {width}: left {left} vs column {}", p.body.x);
}
if rtl || width <= 300.0 {
assert!(right <= p.body.x + p.body.w + 0.5, "rtl {rtl} width {width}: right {right} vs column {}", p.body.x + p.body.w);
}
}
}
-11
View File
@@ -147,12 +147,6 @@ 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
@@ -189,11 +183,6 @@ 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);
}
+2 -1
View File
@@ -250,7 +250,8 @@ fn side_menu(ui: &mut Ui, band: f32, current: &str, has_document: bool, show_dis
.least_width(LeastWidth::SideMenu)
.surface(SurfaceKind::Brand)
.label(label("File"))
.gap(Gap::None)
// v0.19.1's row pitch (~42 pt against the 38 pt rows): the theme's tight gap between the page rows.
.gap(Gap::Tight)
.scroll(Scroll::vertical())
.header(move |ui, _| {
ui.add_space(band);
+4 -2
View File
@@ -748,7 +748,7 @@ fn about_stays_at_the_bottom_of_a_side_menu_that_fits() {
}
/// The side menu is production's rail: 200 pt wide (five rail columns, `LeastWidth::SideMenu`), its page rows about
/// 38 pt tall one after another. The footer's links are rows of the same place, so they read in the rail's white ink;
/// 38 pt tall a tight gap apart. The footer's links are rows of the same place, so they read in the rail's white ink;
/// production's were a little shorter (32 pt), which the side menu place has no row for.
#[test]
fn the_side_menu_rows_are_production_s_rail_rows() {
@@ -758,7 +758,9 @@ fn the_side_menu_rows_are_production_s_rail_rows() {
// The least width holds in the row beside the page: before, the row gave the menu only its widest name (~123 pt).
assert!((190.0..=260.0).contains(&info.width()), "the menu is production's 200 pt rail: {info:?}");
assert!((34.0..=44.0).contains(&info.height()), "a page row is a rail row: {info:?}");
assert!((recover.min.y - info.max.y).abs() < 1.0, "the rows follow each other without a gap: {info:?} {recover:?}");
// v0.19.1's pitch was ~42 pt for 38 pt rows: the rows are a little apart, not touching and not far apart.
let gap = recover.min.y - info.max.y;
assert!((1.0..=8.0).contains(&gap), "the rows have a small gap between them: {info:?} {recover:?}");
assert!(about.height() <= info.height() + 1.0, "the footer link is no taller than a page row: {info:?} {about:?}");
}
+10 -1
View File
@@ -716,8 +716,17 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
let mut state = std::mem::take(&mut app.canvas.reading);
let source = source::WordPages::new(app, layout, false, None);
let out = ReadingView::new(tl!("Document"), &source, &mut state, paper).zoom(zoom).show_at(ui, columns);
// The page-turn row sits at the bottom right, as in v0.19.1 (the far end, so the bottom left in a right-to-left UI),
// the page view's side margin in from the edge.
let margin = Env::of(ui).tokens.space.inset.page_side;
let footer = footer.shrink2(egui::vec2(margin, 0.0));
let far = if crate::i18n::current().rtl() {
egui::Layout::left_to_right(egui::Align::Center)
} else {
egui::Layout::right_to_left(egui::Align::Center)
};
let nav = ui
.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| {
.scope_builder(egui::UiBuilder::new().max_rect(footer).layout(far), |ui| {
ReadingNav::new(&mut state, layout.pages.len()).position(true).action(tl!("Edit Document")).show(ui)
})
.inner;
+14 -1
View File
@@ -56,7 +56,7 @@ impl Component for ReadingProbe {
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> egui::Vec2 {
let measure = ReadingMeasure::of(TypeRole::Body, |run| cx.layout(run));
self.measured = Some(ReadingMetrics::new(cx.style.column_gap, cx.style.nav_bar, measure));
self.measured = Some(metrics(cx.style.column_gap, cx.style.nav_bar, measure));
egui::Vec2::ZERO
}
@@ -69,6 +69,19 @@ impl Component for ReadingProbe {
}
}
/// Column widths Read Mode has always used (about one column per 295 screen points, none under 192), as v0.19.1 laid out 4
/// columns at 1440 screen points. craft's body-text measure (66 characters) gives 2 there, so only the gaps come from it.
const COLUMN_TARGET: f32 = 295.0;
const COLUMN_MIN: f32 = 192.0;
fn metrics(column_gap: f32, nav_bar: f32, measure: ReadingMeasure) -> ReadingMetrics {
let mut m = ReadingMetrics::new(column_gap, nav_bar, measure);
// lean: fixed px, not the text size; follow the body text again if Read Mode should scale with it.
m.column_target = COLUMN_TARGET;
m.column_min = COLUMN_MIN;
m
}
/// The reading metrics under the current theme, or `None` when the probe did not measure this pass.
pub(super) fn read(ui: &mut Ui) -> Option<ReadingMetrics> {
ReadingProbe { common: Common::new(), measured: None }.label("Reading metrics").show(ui).metrics
+42
View File
@@ -253,6 +253,48 @@ fn drawing_over_the_pages_follows_the_read_mode_page_color() {
assert_eq!(blank(&a), Rgb::WHITE, "the paper under the raster, not the page color");
}
/// #8019: at 1440 x 900 Read Mode lays out several narrow columns (v0.19.1: 4), not the two the body
/// text's measure gave after the port.
#[test]
fn read_mode_lays_out_several_columns_at_1440() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
a.run("view.readMode", json!({})).unwrap();
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,
);
h.run_steps(4);
let px = ReadingView::screen_scale(1.0) * h.state().session.view.read_width;
assert!(px > 0.0 && 4.0 * px < 1440.0, "columns {px} px wide: four do not fit");
}
/// #8019: the page-turn row (position and Edit Document) sits in the bottom-right quadrant, as in v0.19.1,
/// not at the bottom left where craft's row starts.
#[test]
fn read_mode_pager_is_at_the_bottom_right() {
use egui_kittest::kittest::Queryable;
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
a.run("view.readMode", json!({})).unwrap();
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,
);
h.run_steps(4);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
for label in ["Edit Document", "1 / 1"] {
let r = h.get_all_by_label(label).last().unwrap().rect();
assert!(r.center().x > screen.center().x && r.center().y > screen.center().y, "{label} at {r:?}: not bottom right");
}
}
/// #299: the caret's colour is worked out only when the caret is drawn: with text selected
/// there is no caret, so the page's draw list isn't built for it.
#[test]
+1 -19
View File
@@ -25,11 +25,7 @@ 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) };
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,
}
HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string())
})
.collect()
}
@@ -85,17 +81,3 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
}
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");
}
}
@@ -5,11 +5,10 @@
//! through `tools.customizeKeyboard`, so agents get the same result without the dialog.
use craft::keymap::{Binding, CommandDef, Keymap, Overrides};
use craft::menu::shortcuts::{Area, DialogState, Layout, Options, Outcome, ShortcutsDialog};
use craft::menu::shortcuts::{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;
@@ -50,61 +49,11 @@ 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()) }
@@ -298,53 +247,4 @@ 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"));
}
}
+11 -11
View File
@@ -6,10 +6,9 @@ use craft::ui::buttons::Button;
use craft::ui::choice::{Radio, RadioGroup};
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, clicked};
use craft::ui::dialog::DialogId;
use craft::ui::display::{Picture, Text};
use craft::ui::form::FieldGroup;
use craft::ui::display::{Picture, PictureSize, Text};
use craft::ui::layout_components::Row;
use craft::ui::list::ThumbAspect;
use craft::ui::list::{ThumbAspect, ThumbSize};
use craft::ui::patterns::form_dialogs::FormCx;
use craft::ui::primitives::{ContentPainterCx, TextureCache};
use craft::ui::runtime::env::Label;
@@ -20,7 +19,7 @@ use wordcraft_doc::props::Align;
use super::dialogs_insert::symbol::SymbolRequest;
use super::font::FontRequest;
use super::host::{Asks, ChildAnswer, WordForm, open_form};
use super::host::{Asks, ChildAnswer, WordForm, captioned, open_form};
use crate::WordApp;
/// The alignments the dialog offers: `para.defineBullet`'s `align` and their names.
@@ -183,6 +182,7 @@ impl DefineBulletForm {
}
},
)
.extent(PictureSize::Sample(ThumbSize::Large))
}
}
@@ -210,8 +210,8 @@ impl WordForm for DefineBulletForm {
});
let entries: Vec<Entry<String>> = ALIGNMENTS.iter().map(|(k, n)| Entry::new((*k).to_string(), Label::from(tl!(n)))).collect();
let current = if self.align.is_empty() { "left".to_string() } else { self.align.clone() };
FieldGroup::new(Label::from(tl!("Alignment:"))).show(ui, |ui, _| {
let group = RadioGroup::new(Label::from(tl!("Alignment:")), Bind::given(current.clone())).show(ui, |ui, _| {
let group = captioned(ui, Label::from(tl!("Alignment:")), |name, ui| {
RadioGroup::new(name, Bind::given(current.clone())).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
for e in &entries {
if let (Some(id), label) = (e.value(), e.label()) {
@@ -219,12 +219,12 @@ impl WordForm for DefineBulletForm {
}
}
});
});
if let Some(a) = group.output.value().cloned() {
self.align = a;
}
})
});
FieldGroup::new(Label::from(tl!("Preview"))).show(ui, |ui, _| {
if let Some(a) = group.and_then(|g| g.output.value().cloned()) {
self.align = a;
}
captioned(ui, Label::from(tl!("Preview")), |_, ui| {
self.preview().show(ui);
});
self.ch.chars().count() == 1
@@ -4,10 +4,11 @@ use craft::text::ui::columns::{ColumnsApply, TextColumns, TextColumnsDialog};
use craft::ui::choice::{Radio, RadioGroup};
use craft::ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, SideLabel};
use craft::ui::dialog::DialogId;
use craft::ui::form::{Field, FieldGroup};
use craft::ui::form::Field;
use craft::ui::layout_components::Stack;
use craft::ui::patterns::form_dialogs::FormCx;
use craft::ui::runtime::env::Label;
use craft::ui::sections::GroupBox;
use craft::ui::text::NumberField;
use egui::Ui;
use serde::{Deserialize, Serialize};
@@ -15,7 +16,7 @@ use serde_json::{Map, Value, json};
use super::{settled, word};
use crate::WordApp;
use crate::dialogs::host::{Asks, DialogHooks, Keyed, Settle, WordForm, open_with};
use crate::dialogs::host::{Asks, DialogHooks, Keyed, Settle, WordForm, captioned, open_with};
use crate::options::lengths;
use crate::widgets::font_box::{CatalogRef, font_picker};
@@ -104,14 +105,16 @@ impl WordForm for DropCapForm {
fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
let enabled = self.position != "none";
Stack::new().show(ui, |ui, _| {
RadioGroup::new(word("Position"), Bind::bound(&mut self.position)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
for (at, (v, l)) in [("none", "None"), ("dropped", "Dropped"), ("margin", "In margin")].into_iter().enumerate() {
cx.labelled(ui, at, word(l), SideLabel::new().layout(FieldLayout::After), Radio::new(v.to_string()));
}
});
captioned(ui, word("Position"), |name, ui| {
RadioGroup::new(name, Bind::bound(&mut self.position)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
for (at, (v, l)) in [("none", "None"), ("dropped", "Dropped"), ("margin", "In margin")].into_iter().enumerate() {
cx.labelled(ui, at, word(l), SideLabel::new().layout(FieldLayout::After), Radio::new(v.to_string()));
}
});
})
});
FieldGroup::new(word("Options")).show(ui, |ui, _| {
GroupBox::new(word("Options"), None).show(ui, |ui, _| {
if let Some(catalog) = self.catalog.get() {
Field::new(word("Font:")).show(ui, |ui, _| {
font_picker(word("Font:"), Bind::bound(&mut self.font), catalog, Bind::bound(&mut self.settings), &[], None)
@@ -3,6 +3,7 @@ use std::sync::Arc;
use craft::behavior::{ColumnWidth, Selection, SelectionChange, keyed};
use craft::font_manager::Catalog;
use craft::font_manager::picker::FontPickerSettings;
use craft::theme::Mode;
use craft::ui::contract::{Bind, CollectionEvent, ColumnKey, ColumnSpec, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft::ui::display::{Kbd, Text};
@@ -11,7 +12,7 @@ use craft::ui::layout_components::Stack;
use craft::ui::list::{ListRow, ThumbAspect, ThumbSize};
use craft::ui::patterns::form_dialogs::{FormCx, FormDialog};
use craft::ui::primitives::ContentPainterCx;
use craft::ui::runtime::env::Label;
use craft::ui::runtime::env::{Env, Label};
use craft::ui::table::Table;
use craft::ui::tabs::{Tab, TabKind, TabStrip};
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
@@ -546,7 +547,7 @@ fn special_table(ui: &mut Ui, form: &mut SymbolForm) -> bool {
let columns = vec![
ColumnSpec::new(glyph.clone(), Label::Empty, ColumnWidth::fill(0.5)),
ColumnSpec::new(name.clone(), word("Special Characters"), ColumnWidth::fill(2.0)),
ColumnSpec::new(keys.clone(), word("Shortcut key:"), ColumnWidth::fill(1.0)),
ColumnSpec::new(keys.clone(), word("Shortcut key:"), ColumnWidth::Controls(5.5)),
];
let positions: Vec<usize> = (0..SPECIAL.len()).collect();
let source = keyed(&positions, |at: &usize| *at);
@@ -614,7 +615,8 @@ fn symbol_page(ui: &mut Ui, form: &mut SymbolForm, catalog: Option<&Arc<Catalog>
{
form.jump_to(name);
}
let dark = ui.visuals().dark_mode;
// The theme's mode, not egui's `dark_mode`, which the craft theme does not drive (light tiles in the light theme, #8021).
let dark = Env::of(ui).view().mode() == Mode::Dark;
let activated = glyph_grid(ui, form, dark);
recent_row(ui, form, dark);
if let Some(c) = form.selected {
+31 -12
View File
@@ -15,7 +15,7 @@ use egui::Ui;
use serde_json::Value;
use crate::WordApp;
use crate::dialogs::host::{DialogHooks, open_form, open_form_with};
use crate::dialogs::host::{DialogHooks, labelled, open_form, open_form_with};
mod page;
pub(crate) mod print;
@@ -92,11 +92,23 @@ pub(crate) fn points() -> LengthUnits {
LengthUnits::new(UnitKind::Points, UnitKind::Points, 96.0)
}
/// A whole-number field over `value` within `range`; true when the user changed it.
/// A whole-number field over `value` within `range`, with its caption; true when the user changed it.
pub(crate) fn count_field(ui: &mut Ui, label: &str, value: &mut u32, range: RangeInclusive<u32>, enabled: bool) -> bool {
labelled(ui, label.to_string(), |name, ui| count_box(ui, name, value, range.clone(), enabled)).unwrap_or(false)
}
/// `count_field` with no caption, named `label` for assistive technology: for a box that follows a radio carrying the
/// same words ("Start at:").
pub(crate) fn count_box(
ui: &mut Ui,
label: impl Into<craft::ui::runtime::env::Label>,
value: &mut u32,
range: RangeInclusive<u32>,
enabled: bool,
) -> bool {
let was = f64::from(*value);
let mut shown = Some(was);
NumberField::new(label.to_string(), Bind::bound(&mut shown)).range(f64::from(*range.start())..=f64::from(*range.end())).enabled(enabled).show(ui);
NumberField::new(label, Bind::bound(&mut shown)).range(f64::from(*range.start())..=f64::from(*range.end())).enabled(enabled).show(ui);
match shown {
Some(n) if n != was => {
*value = (n.round().max(0.0) as u32).clamp(*range.start(), *range.end());
@@ -116,8 +128,10 @@ pub(crate) fn length_field(ui: &mut Ui, label: &str, value: &mut f32, lengths: L
let was = f64::from(*value);
// The form takes the field's edit events, not a write into a copy that lives one pass: an edit that commits as the
// dialog files its OK (Enter, or a click on OK) reaches the form in the pass that files it.
let out = NumberField::length(label.to_string(), Bind::given(Some(was)), lengths).range(range).enabled(enabled).show(ui);
match edited(&out.edit.events) {
let out = labelled(ui, label.to_string(), |name, ui| {
NumberField::length(name, Bind::given(Some(was)), lengths).range(range.clone()).enabled(enabled).show(ui)
});
match out.as_ref().and_then(|out| edited(&out.edit.events)) {
Some(n) if n != was => {
*value = n as f32;
true
@@ -129,8 +143,8 @@ pub(crate) fn length_field(ui: &mut Ui, label: &str, value: &mut f32, lengths: L
/// A percentage field over `value`; true when the user changed it.
pub(crate) fn percent_field(ui: &mut Ui, label: &str, value: &mut f32, range: RangeInclusive<f64>) -> bool {
let was = f64::from(*value);
let out = NumberField::new(label.to_string(), Bind::given(Some(was))).range(range).unit("%").show(ui);
match edited(&out.edit.events) {
let out = labelled(ui, label.to_string(), |name, ui| NumberField::new(name, Bind::given(Some(was))).range(range.clone()).unit("%").show(ui));
match out.as_ref().and_then(|out| edited(&out.edit.events)) {
Some(n) if n != was => {
*value = n as f32;
true
@@ -151,11 +165,16 @@ pub(crate) fn named_field<K: NumberName + 'static>(
enabled: bool,
) {
let presets = vec![Entry::new(NumberPick::Choice(name.0.id()), name.1.to_string()).checked(matches!(*value, NamedOr::Named(_)))];
let mut field = NumberField::named(label.to_string(), Bind::bound(value)).range(range).presets(&presets).enabled(enabled);
if let Some(lengths) = lengths {
field = field.lengths(lengths);
}
field.show(ui);
labelled(ui, label.to_string(), |name, ui| {
{
let field = NumberField::named(name, Bind::bound(&mut *value)).range(range.clone()).presets(&presets).enabled(enabled);
match lengths {
Some(lengths) => field.lengths(lengths),
None => field,
}
}
.show(ui)
});
}
/// The number a named field holds, 0 while it holds its name.
@@ -14,7 +14,7 @@ use serde_json::{Value, json};
use wordcraft_engine::cmd::objects::fit_size;
use super::{DialogId, WordApp, length_field, percent_field, points};
use crate::dialogs::host::{Asks, FormHost, WordForm};
use crate::dialogs::host::{Asks, FormHost, WordForm, captioned, labelled};
// ---------------------------------------------------------------------------------------------
// Size
@@ -300,14 +300,22 @@ impl WordForm for PageNumbersForm {
fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
let formats: Vec<Entry<String>> =
crate::dialogs_notes::FORMATS.iter().map(|(v, l)| Entry::new((*v).to_string(), tl!(l).to_string())).collect();
Select::new(tl!("Number format").to_string(), Bind::bound(&mut self.format), &formats).show(ui);
RadioGroup::new(tl!("Page numbering").to_string(), Bind::bound(&mut self.cont)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
cx.labelled(ui, 0, Label::from(tl!("Continue from previous section")), SideLabel::new().layout(FieldLayout::After), Radio::new(true));
cx.labelled(ui, 1, Label::from(tl!("Start at:")), SideLabel::new().layout(FieldLayout::After), Radio::new(false));
});
labelled(ui, tl!("Number format").to_string(), |name, ui| Select::new(name, Bind::bound(&mut self.format), &formats).show(ui));
captioned(ui, tl!("Page numbering").to_string(), |name, ui| {
RadioGroup::new(name, Bind::bound(&mut self.cont)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
cx.labelled(
ui,
0,
Label::from(tl!("Continue from previous section")),
SideLabel::new().layout(FieldLayout::After),
Radio::new(true),
);
cx.labelled(ui, 1, Label::from(tl!("Start at:")), SideLabel::new().layout(FieldLayout::After), Radio::new(false));
});
})
});
super::count_field(ui, tl!("Start at:"), &mut self.start, 0..=100_000, !self.cont);
super::count_box(ui, tl!("Start at:"), &mut self.start, 0..=100_000, !self.cont);
true
}
@@ -12,7 +12,7 @@ use wordcraft_engine::cmd::mailings::{ENVELOPE_SIZES, LABEL_PRODUCTS};
use wordcraft_geom::Region;
use crate::WordApp;
use crate::dialogs::host::{Asks, WordForm, open_form};
use crate::dialogs::host::{Asks, WordForm, labelled, open_form};
// ---------------------------------------------------------------------------------------------
// Envelopes
@@ -72,10 +72,12 @@ impl WordForm for EnvelopeForm {
fn body(&mut self, ui: &mut egui::Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
let sizes: Vec<Entry<usize>> =
ENVELOPE_SIZES.iter().enumerate().map(|(i, (n, w, h))| Entry::new(i, envelope_label(n, *w, *h, &self.region))).collect();
TextField::new(tl!("Delivery address:"), Bind::bound(&mut self.delivery)).lines(4).show(ui);
labelled(ui, tl!("Delivery address:"), |name, ui| TextField::new(name, Bind::bound(&mut self.delivery)).lines(4).show(ui));
Checkbox::new(Bind::bound(&mut self.omit_return)).label(tl!("Omit")).show(ui);
TextField::new(tl!("Return address:"), Bind::bound(&mut self.ret)).lines(3).enabled(!self.omit_return).show(ui);
Select::new(tl!("Envelope size:"), Bind::bound(&mut self.size), &sizes).show(ui);
labelled(ui, tl!("Return address:"), |name, ui| {
TextField::new(name, Bind::bound(&mut self.ret)).lines(3).enabled(!self.omit_return).show(ui)
});
labelled(ui, tl!("Envelope size:"), |name, ui| Select::new(name, Bind::bound(&mut self.size), &sizes).show(ui));
self.ready()
}
fn commands(&self) -> Vec<(String, Value)> {
@@ -202,9 +204,9 @@ impl WordForm for LabelsForm {
Checkbox::new(Bind::bound(&mut self.recipients)).label(tl!("One label per recipient")).show(ui);
}
let per_recipient = self.has_recipients && self.recipients && !self.single;
TextField::new(tl!("Address:"), Bind::bound(&mut self.text)).lines(4).enabled(!per_recipient).show(ui);
labelled(ui, tl!("Address:"), |name, ui| TextField::new(name, Bind::bound(&mut self.text)).lines(4).enabled(!per_recipient).show(ui));
let products: Vec<Entry<usize>> = (0..LABEL_PRODUCTS.len()).map(|i| Entry::new(i, product_label(i, &self.region))).collect();
Select::new(tl!("Label:"), Bind::bound(&mut self.product), &products).show(ui);
labelled(ui, tl!("Label:"), |name, ui| Select::new(name, Bind::bound(&mut self.product), &products).show(ui));
let (rows, cols) = LABEL_PRODUCTS.get(self.product).map_or((1, 1), |p| (p.rows, p.cols));
let mut single = self.single;
let (mut row, mut col) = (self.row, self.col);
@@ -216,21 +218,17 @@ impl WordForm for LabelsForm {
Radio::new(1u8).label(tl!("Single label")).show(ui);
});
single = mode == 1;
if let Some(Some(v)) = NumberField::new(tl!("Row:"), Bind::given(Some(row as f64)))
.range(1.0..=rows.max(1) as f64)
.enabled(single_on)
.show(ui)
.value()
.copied()
if let Some(Some(v)) = labelled(ui, tl!("Row:"), |name, ui| {
NumberField::new(name, Bind::given(Some(row as f64))).range(1.0..=rows.max(1) as f64).enabled(single_on).show(ui)
})
.and_then(|out| out.value().copied())
{
row = v as usize;
}
if let Some(Some(v)) = NumberField::new(tl!("Column:"), Bind::given(Some(col as f64)))
.range(1.0..=cols.max(1) as f64)
.enabled(single_on)
.show(ui)
.value()
.copied()
if let Some(Some(v)) = labelled(ui, tl!("Column:"), |name, ui| {
NumberField::new(name, Bind::given(Some(col as f64))).range(1.0..=cols.max(1) as f64).enabled(single_on).show(ui)
})
.and_then(|out| out.value().copied())
{
col = v as usize;
}
@@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::{WordApp, count_field, named_field, number_or_zero, points};
use crate::dialogs::host::{Asks, WordForm};
use crate::dialogs::host::{Asks, WordForm, labelled};
/// The field's one name: a width that shares the text width out.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -96,7 +96,7 @@ impl WordForm for FormulaForm {
});
let functions: Vec<Entry<String>> = FORMULA_FUNCTIONS.iter().map(|n| Entry::new((*n).to_string(), (*n).to_string())).collect();
let mut picked = String::new();
Select::new(tl!("Paste function:").to_string(), Bind::bound(&mut picked), &functions).show(ui);
labelled(ui, tl!("Paste function:").to_string(), |name, ui| Select::new(name, Bind::bound(&mut picked), &functions).show(ui));
if !picked.is_empty() {
self.paste(&picked);
}
@@ -18,7 +18,7 @@ use serde_json::{Value, json};
use wordcraft_doc::section::LineNumberRestart;
use super::{WordApp, count_field, length_field, named_field, number_or_zero, points};
use crate::dialogs::host::{Asks, Filed, WordForm};
use crate::dialogs::host::{Asks, Filed, WordForm, captioned};
/// The field's one name: no limit on consecutive hyphens.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -105,12 +105,14 @@ impl WordForm for LineNumbersForm {
length_field(ui, tl!("From text:"), &mut self.distance, lengths, 0.0..=22.0 * 72.0, on && !self.auto_distance);
count_field(ui, tl!("Count by:"), &mut self.count_by, 1..=100, on);
let opts = [("restartPage", tl!("Restart Each Page")), ("restartSection", tl!("Restart Each Section")), ("continuous", tl!("Continuous"))];
RadioGroup::new(tl!("Numbering:").to_string(), Bind::bound(&mut self.restart)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
for (at, (v, l)) in opts.iter().enumerate() {
cx.labelled(ui, at, Label::from(*l), SideLabel::new().layout(FieldLayout::After), Radio::new((*v).to_string()));
}
});
captioned(ui, tl!("Numbering:").to_string(), |name, ui| {
RadioGroup::new(name, Bind::bound(&mut self.restart)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
for (at, (v, l)) in opts.iter().enumerate() {
cx.labelled(ui, at, Label::from(*l), SideLabel::new().layout(FieldLayout::After), Radio::new((*v).to_string()));
}
});
})
});
true
}
@@ -444,6 +446,8 @@ impl WordForm for LanguageForm {
let which: Vec<usize> = (0..list.len()).collect();
let source = keyed(which.as_slice(), |i: &usize| *i);
let selection = at.map_or_else(|| Selection::new(Vec::new(), None, None), Selection::single);
// A plain caption, not a `Field`: the list keeps its own accessible name (#7976).
Text::new(Label::from(heading.to_string())).show(ui);
let shown = List::<usize>::new(Label::from(heading.to_string()))
.select(SelectMode::Single)
.selection(Bind::given(selection))
+11 -15
View File
@@ -22,7 +22,7 @@ use serde_json::{Value, json};
use wordcraft_doc::section::NumFormat;
use wordcraft_engine::cmd::lists::{LEVELS, caret_list, level_json, levels_of};
use super::dialogs_para::{color_row, pick, radios, srgba, word};
use super::dialogs_para::{color_row, pick, radios, radios_in_section, srgba, word};
use super::host::{Asks, ChildAnswer, WordForm, open_form};
use crate::WordApp;
use crate::colors::{AutoFace, ColorFieldEmpty, Palette};
@@ -282,7 +282,7 @@ impl ListForm {
Stack::new().show(ui, |ui, _| {
Text::new(word(tl!("Preview"))).show(ui);
Picture::painter(word(tl!("Preview")), ThumbAspect::new(5, 3), preview(rows.clone(), level))
.extent(PictureSize::Thumb(ThumbSize::Large))
.extent(PictureSize::Sample(ThumbSize::Large))
.show(ui);
});
});
@@ -599,7 +599,7 @@ fn choose(ui: &mut Ui, salt: &'static str, label: Label, options: &[(&str, &str)
/// A radio group over `options` setting `value`.
fn choose_radio(ui: &mut Ui, label: Label, options: &[(&str, &str)], value: &mut String) {
let current = index_of(options, value).unwrap_or(0);
if let Some((v, _)) = radios(ui, label, &labels(options), current).and_then(|at| options.get(at)) {
if let Some((v, _)) = radios_in_section(ui, label, &labels(options), current).and_then(|at| options.get(at)) {
*value = v.to_string();
}
}
@@ -829,6 +829,12 @@ mod tests {
assert_eq!(h.state_mut().run("list.define", json!({})).unwrap(), json!({"pending": "defineList"}));
h.run_steps(2);
// The sheet fills the Preview image's rect, which is larger than the 80 × 48 icon-side thumbnail it once
// shrank to (#7977).
let preview = egui_kittest::kittest::Queryable::get_by_role_and_label(&h, egui::accesskit::Role::Image, "Preview").rect();
assert!(preview.width() > 80.0 && preview.height() > 48.0, "{theme}: the preview is {preview:?}");
let is_sheet = |r: egui::Rect| (r.width() - preview.width()).abs() <= 2.0 && (r.height() - preview.height()).abs() <= 2.0;
let mut shapes = Vec::new();
collect_shapes(&h.output().shapes, &mut shapes);
@@ -836,11 +842,7 @@ mod tests {
let white_rects: Vec<_> = shapes
.iter()
.filter_map(|s| match s {
egui::Shape::Rect(r)
if r.fill == egui::Color32::WHITE && (r.rect.width() - 80.0).abs() <= 5.0 && (r.rect.height() - 48.0).abs() <= 5.0 =>
{
Some(r)
}
egui::Shape::Rect(r) if r.fill == egui::Color32::WHITE && is_sheet(r.rect) => Some(r),
_ => None,
})
.collect();
@@ -850,13 +852,7 @@ mod tests {
let stroke_rects: Vec<_> = shapes
.iter()
.filter_map(|s| match s {
egui::Shape::Rect(r)
if r.stroke.color == egui::Color32::from_gray(160)
&& (r.rect.width() - 80.0).abs() <= 5.0
&& (r.rect.height() - 48.0).abs() <= 5.0 =>
{
Some(r)
}
egui::Shape::Rect(r) if r.stroke.color == egui::Color32::from_gray(160) && is_sheet(r.rect) => Some(r),
_ => None,
})
.collect();
+32 -5
View File
@@ -14,6 +14,7 @@ use craft::theme::Srgba;
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
use craft::ui::contract::{Bind, CollectionEvent, Entry, FieldLayout, Props as _, Show as _, ShowCollection as _, ShowContainer as _, SideLabel};
use craft::ui::dialog::DialogId;
use craft::ui::display::Text;
use craft::ui::form::Field;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::patterns::form_dialogs::FormCx;
@@ -25,7 +26,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use wordcraft_doc::props::{Border, BorderStyle, Borders, Rgb, TabAlign, TabLeader, TabStop};
use super::host::{Asks, ChildAnswer, DialogHooks, Keyed, Settle, WordForm, open_form, open_with};
use super::host::{Asks, ChildAnswer, DialogHooks, Keyed, Settle, WordForm, captioned, open_form, open_with};
use crate::WordApp;
use crate::colors::{AutoFace, ColorFieldEmpty, Palette, color_field};
use crate::options::unit_kind;
@@ -60,6 +61,23 @@ pub(super) fn color_row(
}
}
/// `color_row` with `label` drawn beside it as plain text. Not a `Field`: its label scope would rename the split button
/// "Color:" and drop the colour it speaks ("Color: Automatic").
fn captioned_color_row(
ui: &mut Ui,
key: &'static str,
label: Label,
value: &mut String,
empty: &ColorFieldEmpty,
palette: &Palette,
asks: &mut Vec<Asks>,
) {
Row::new().show(ui, |ui, _| {
Text::new(label.clone()).show(ui);
color_row(ui, key, &label, value, empty, palette, asks);
});
}
/// A drop-down over `labels` under `label`, showing entry `current` (empty while it is `None`). The index of the entry
/// picked in this pass.
pub(super) fn pick(ui: &mut Ui, salt: &'static str, label: Label, labels: &[Label], current: Option<usize>, enabled: bool) -> Option<usize> {
@@ -72,9 +90,18 @@ pub(super) fn pick(ui: &mut Ui, salt: &'static str, label: Label, labels: &[Labe
.flatten()
}
/// A radio group over `labels` under `label`, entry `current` chosen. The index chosen in this pass, when it is
/// another one.
/// A radio group over `labels` under a caption `label`, entry `current` chosen. The index chosen in this pass, when it
/// is another one.
pub(super) fn radios(ui: &mut Ui, label: Label, labels: &[Label], current: usize) -> Option<usize> {
captioned(ui, label.clone(), |_, ui| radio_set(ui, label.clone(), labels, current)).flatten()
}
/// `radios` with no caption: for a group inside a section that already carries its title.
pub(super) fn radios_in_section(ui: &mut Ui, label: Label, labels: &[Label], current: usize) -> Option<usize> {
radio_set(ui, label, labels, current)
}
fn radio_set(ui: &mut Ui, label: Label, labels: &[Label], current: usize) -> Option<usize> {
let mut at = current;
RadioGroup::new(label, Bind::bound(&mut at)).show(ui, |ui, cx| {
for (i, text) in labels.iter().enumerate() {
@@ -481,7 +508,7 @@ fn lines(ui: &mut Ui, key: &'static str, l: &mut LineForm, area: SampleArea, fil
l.style = *style;
}
let automatic = ColorFieldEmpty::Automatic { label: word(tl!("Automatic")), value: "", face: AutoFace::One(srgba(Rgb(0, 0, 0))) };
color_row(ui, key, &word(tl!("Color:")), &mut l.color, &automatic, palette, asks);
captioned_color_row(ui, key, word(tl!("Color:")), &mut l.color, &automatic, palette, asks);
let names: Vec<Label> = WIDTHS.iter().map(|w| word(crate::i18n::fmt(tl!("{n} pt"), &[("n", &w.to_string())]))).collect();
let current = WIDTHS.iter().position(|w| *w == l.width);
if let Some(width) = pick(ui, "width", word(tl!("Width:")), &names, current, true).and_then(|at| WIDTHS.get(at)) {
@@ -540,7 +567,7 @@ impl WordForm for BordersForm {
Self::apply_to(ui, &mut self.whole_doc, word(tl!("This section")), word(tl!("Whole document")));
}
_ => {
color_row(ui, "fill", &word(tl!("Fill")), &mut self.fill, &ColorFieldEmpty::NoColor, &palette, asks);
captioned_color_row(ui, "fill", word(tl!("Fill")), &mut self.fill, &ColorFieldEmpty::NoColor, &palette, asks);
// The same sample as the Borders tab shows, without the lines and not editable.
let mut none = BorderEdges::default();
let area = if self.fill_to_text { SampleArea::Text } else { SampleArea::Paragraph };
@@ -1,6 +1,7 @@
use craft::behavior::{Mixed, Selection, keyed};
use craft::ui::contract::{Bind, Entry, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::dialog::DialogId;
use craft::ui::display::Text;
use craft::ui::form::Field;
use craft::ui::list::{List, ListRow};
use craft::ui::patterns::form_dialogs::FormCx;
@@ -156,6 +157,7 @@ impl WordForm for CrossRefForm {
let source = keyed(&which, |i: &usize| *i);
let mut selection = self.selected.map_or_else(|| Selection::new(Vec::new(), None, None), Selection::single);
let targets = &self.targets;
Text::new(Label::from(tl!("For which item:").to_string())).show(ui);
let _ = List::new(Label::from(tl!("For which item:").to_string()))
.max_rows(8)
.select(SelectMode::Single)
@@ -20,7 +20,7 @@ use wordcraft_engine::cmd::references::FieldCode;
use super::sample::{LEADERS, leader_char, sample_card};
use crate::WordApp;
use crate::dialogs::host::{Asks, Filed, WordForm, open_form};
use crate::dialogs::host::{Asks, Filed, WordForm, captioned, labelled, open_form};
/// The tab leaders as drop-down entries (value, translated label).
pub(super) fn leaders() -> Vec<Entry<String>> {
@@ -104,18 +104,21 @@ impl WordForm for IndexForm {
fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, asks: &mut Vec<Asks>) -> bool {
sample_card(tl!("Preview"), self.sample_lines(), self.right_align, leader_char(&self.leader)).show(ui);
let kind = RadioGroup::new(Label::from(tl!("Type:").to_string()), Bind::given(self.kind.clone())).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Radio::new("indented".to_string()).label(Label::from(tl!("Indented").to_string())).show(ui);
Radio::new("runIn".to_string()).label(Label::from(tl!("Run-in").to_string())).show(ui);
});
let kind = captioned(ui, Label::from(tl!("Type:").to_string()), |name, ui| {
RadioGroup::new(name, Bind::given(self.kind.clone())).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Radio::new("indented".to_string()).label(Label::from(tl!("Indented").to_string())).show(ui);
Radio::new("runIn".to_string()).label(Label::from(tl!("Run-in").to_string())).show(ui);
});
})
});
if let Some(kind) = kind.output.value().cloned() {
if let Some(kind) = kind.and_then(|kind| kind.output.value().cloned()) {
self.kind = kind;
}
let columns =
NumberField::new(Label::from(tl!("Columns:").to_string()), Bind::given(Some(f64::from(self.columns)))).range(1.0..=4.0).show(ui);
if let Some(Some(n)) = columns.edit.value().cloned() {
let columns = labelled(ui, Label::from(tl!("Columns:").to_string()), |name, ui| {
NumberField::new(name, Bind::given(Some(f64::from(self.columns)))).range(1.0..=4.0).show(ui)
});
if let Some(Some(n)) = columns.and_then(|out| out.edit.value().cloned()) {
self.columns = n.round().clamp(1.0, 4.0) as u32;
}
Checkbox::new(Bind::bound(&mut self.right_align)).label(Label::from(tl!("Page numbers at the right margin").to_string())).show(ui);
+11 -10
View File
@@ -20,11 +20,12 @@ 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::{Grid, Row, Stack};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{List, ListRow, ToggleCell, ToggleState};
use craft::ui::notices::Notice;
use craft::ui::runtime::env::Label;
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::style::SurfaceKind;
use craft::ui::tabs::{Tab, TabKind, TabStrip};
use craft::ui::text::TextField;
use egui::{Context, Ui};
@@ -51,8 +52,6 @@ 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");
@@ -145,10 +144,10 @@ impl RibbonDialog {
fn body(&mut self, ui: &mut Ui) {
self.page_tabs(ui);
search(ui, &mut self.filter);
Grid::new(&PANES).fill_width().show(ui, |ui, _| {
Stack::new().fill_width().show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Text::new(word("Choose a command")).show(ui);
Row::new().fill_width().show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
if let Some(category) = pick(ui, "rb_categories", "Categories:", &self.categories, &self.category) {
self.category = category;
self.filter.clear();
@@ -221,9 +220,9 @@ impl RibbonDialog {
self.file("remove", Value::Object(address(&sel)));
}
});
Stack::new().fill_width().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Text::new(word("Ribbon tabs")).show(ui);
Row::new().fill_width().show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
self.tree(ui);
Stack::new().show(ui, |ui, _| {
for (text, by) in [("Up", -1), ("Down", 1)] {
@@ -262,6 +261,7 @@ impl RibbonDialog {
let rows = &self.tree;
let out = List::new(word("Ribbon tabs"))
.id(self.tree_id(ui))
.surface(SurfaceKind::Frame)
.tree(true)
.select(SelectMode::Single)
.columns(columns)
@@ -311,9 +311,9 @@ impl RibbonDialog {
self.file("qatRemove", json!(self.qat_selected));
}
});
Stack::new().fill_width().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Text::new(word("Quick Access Toolbar")).show(ui);
Row::new().fill_width().show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
if let Some(id) = pick(ui, "rb_qat", "Quick Access Toolbar", &self.qat, &self.qat_selected) {
self.qat_selected = id;
}
@@ -405,6 +405,7 @@ fn pick(ui: &mut Ui, salt: &'static str, label: &str, rows: &[(String, String)],
let mut selection = at.map_or_else(Selection::default, Selection::single);
List::new(word(label))
.id(ui.scope_id().with(salt))
.surface(SurfaceKind::Frame)
.select(SelectMode::Single)
// The list scrolls its own rows, as main's fixed-height boxes did, so the dialog's body does not scroll it too.
.max_rows(12)
+73 -41
View File
@@ -3,18 +3,21 @@
//! `styles.copyFrom`, `styles.delete`, `styles.rename`), so agents get the same result without
//! the dialogs.
use craft::behavior::{EditEvent, Selection, SelectionChange, item_source::keyed};
use craft::behavior::{ColumnWidth, EditEvent, Selection, SelectionChange, item_source::keyed};
use craft::host::PickRequest;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename};
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft::ui::display::Text;
use craft::ui::form::Field;
use craft::ui::layout_components::Row;
use craft::ui::layout::CellAlign;
use craft::ui::layout_components::{Grid, Stack};
use craft::ui::list::{List, ListRow};
use craft::ui::notices::Notice;
use craft::ui::patterns::form_dialogs::{FormCx, PathRow};
use craft::ui::runtime::env::{Env, Label};
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::style::SurfaceKind;
use egui::{Context, Ui};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -24,6 +27,15 @@ use super::styles::{action, label};
use crate::WordApp;
const ORGANIZER_KEY: &str = "organizer";
/// The Organizer's columns: each takes what it holds, and a list holds at least `LIST_WIDTH` (a fill column takes no more
/// than its content in a dialog that sizes to its content, so an empty list was a few pixels wide).
const COLUMNS: [ColumnWidth; 3] = [ColumnWidth::Content; 3];
/// The least width of a list, in points.
const LIST_WIDTH: f32 = 200.0;
/// The rows each list shows before it scrolls.
const LIST_ROWS: u16 = 12;
/// The other file's list has its name above it, so it shows one row fewer to end level with the first.
const OTHER_ROWS: u16 = LIST_ROWS - 1;
/// The Templates and Add-ins dialog's fields.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
@@ -236,50 +248,69 @@ impl OrganizerDialog {
fn body(&mut self, ui: &mut Ui) {
let reason = browse_reason(ui);
Row::new().show(ui, |ui, _| {
let mut selection = Selection::single(self.left.clone());
let mine = &self.mine;
let source = keyed(mine, |st| text_of(st, "id"));
let out = List::new(label(tl!("Document")))
.select(SelectMode::Single)
.selection(Bind::bound(&mut selection))
.rename(true)
.can_rename(|key: &String| {
mine.iter().find(|x| text_of(x, "id") == *key).is_some_and(|x| !x.get("builtIn").and_then(Value::as_bool).unwrap_or(true))
})
.id_salt("mine")
.show_items(ui, &source, &mut |_, icx| {
let Some(st) = mine.get(icx.at) else { return ListRow::spacer() };
ListRow::new(label(text_of(st, "name"))).lead_text(label(glyph(&text_of(st, "type"))), label(""))
});
for event in out.events {
match event {
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => {
if let Some(key) = keys.last() {
self.left = key.clone();
let mine_id = ui.scope_id().with("organizer_mine");
// Three columns as the old dialog had: this document's styles, Copy / Delete / Rename, the other file's styles.
Grid::new(&COLUMNS).cells(CellAlign::Top).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
ui.set_min_width(LIST_WIDTH);
let mut selection = Selection::single(self.left.clone());
let mine = &self.mine;
let source = keyed(mine, |st| text_of(st, "id"));
let out = List::new(label(tl!("Document")))
.surface(SurfaceKind::Frame)
.select(SelectMode::Single)
.selection(Bind::bound(&mut selection))
.rename(true)
.can_rename(|key: &String| {
mine.iter().find(|x| text_of(x, "id") == *key).is_some_and(|x| !x.get("builtIn").and_then(Value::as_bool).unwrap_or(true))
})
.id(mine_id)
.min_rows(LIST_ROWS)
.max_rows(LIST_ROWS)
.show_items(ui, &source, &mut |_, icx| {
let Some(st) = mine.get(icx.at) else { return ListRow::spacer() };
ListRow::new(label(text_of(st, "name"))).lead_text(label(glyph(&text_of(st, "type"))), label(""))
});
for event in out.events {
match event {
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => {
if let Some(key) = keys.last() {
self.left = key.clone();
}
}
CollectionEvent::Rename(EditEvent::Commit { after, .. }) => {
self.requests.push(Request::Rename { style: after.key, name: after.name });
}
_ => {}
}
CollectionEvent::Rename(EditEvent::Commit { after, .. }) => {
self.requests.push(Request::Rename { style: after.key, name: after.name });
}
_ => {}
}
}
if action(ui, "copy", label(tl!("Copy")), !self.right.is_empty(), None) {
self.requests.push(Request::Copy);
}
if action(ui, "delete", label(tl!("Delete")), !self.left_builtin(), None) {
self.requests.push(Request::Delete(self.left.clone()));
}
let name = std::path::Path::new(&self.file).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "—".into());
Field::new(label(name)).show(ui, |ui, _| {
});
Stack::new().show(ui, |ui, _| {
if action(ui, "copy", label(tl!("Copy")), !self.right.is_empty(), None) {
self.requests.push(Request::Copy);
}
if action(ui, "delete", label(tl!("Delete")), !self.left_builtin(), None) {
self.requests.push(Request::Delete(self.left.clone()));
}
// The list's own rename field takes the name in place.
if action(ui, "rename", label(tl!("Rename…")), !self.left_builtin(), None) {
request_rename(ui.ctx(), mine_id, &self.left);
}
});
Stack::new().show(ui, |ui, _| {
ui.set_min_width(LIST_WIDTH);
let name = std::path::Path::new(&self.file).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "—".into());
Text::new(label(name)).show(ui);
let mut selection = Selection::single(self.right.clone());
let other = &self.other;
let source = keyed(other, |(n, _)| n.clone());
let out = List::new(label(tl!("Template")))
.surface(SurfaceKind::Frame)
.select(SelectMode::Single)
.selection(Bind::bound(&mut selection))
.id_salt("other")
.min_rows(OTHER_ROWS)
.max_rows(OTHER_ROWS)
.show_items(ui, &source, &mut |_, icx| {
let Some((n, ty)) = other.get(icx.at) else { return ListRow::spacer() };
ListRow::new(label(n)).lead_text(label(glyph(ty)), label(""))
@@ -291,12 +322,13 @@ impl OrganizerDialog {
self.right = key.clone();
}
}
let picked = template_row(label(tl!("Template")), Bind::bound(&mut self.file), reason.clone()).show(ui).picked;
if let Some(path) = picked {
self.requests.push(Request::Load(path));
}
});
});
// The other file's path and Browse stand under both lists, at the dialog's full width.
let picked = template_row(label(tl!("Template")), Bind::bound(&mut self.file), reason.clone()).show(ui).picked;
if let Some(path) = picked {
self.requests.push(Request::Load(path));
}
if !self.message.is_empty() {
Notice::new(craft::theme::variant::Tone::Bad, label(&self.message)).show(ui);
}
+17 -14
View File
@@ -4,10 +4,10 @@
use craft::ui::choice::{Radio, RadioGroup};
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::DialogId;
use craft::ui::display::Picture;
use craft::ui::display::{Picture, PictureSize};
use craft::ui::form::{Field, FieldGroup};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::ThumbAspect;
use craft::ui::list::{ThumbAspect, ThumbSize};
use craft::ui::patterns::form_dialogs::FormCx;
use craft::ui::primitives::{ContentPainterCx, HAlign, PaintShape, StrokeColor, StrokeWidth, TextRun};
use craft::ui::runtime::env::Label;
@@ -17,7 +17,7 @@ use egui::{CornerRadius, Rect, Ui, pos2, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::host::{Asks, WordForm, open_form};
use super::host::{Asks, WordForm, captioned, open_form};
use crate::WordApp;
const PREVIEW_W: f32 = 110.0;
@@ -81,24 +81,27 @@ impl EncloseForm {
d.text(line, &TextRun::new(text.as_str()).role(role).align(HAlign::Center));
});
})
.extent(PictureSize::Sample(ThumbSize::Large))
}
}
/// A radio group over `value` whose options are `(id, label)`.
fn radios(ui: &mut Ui, name: &'static str, value: &mut String, options: &[(&'static str, &'static str)], enabled: bool, horizontal: bool) {
let group = RadioGroup::new(Label::from(name), Bind::given(value.clone())).enabled(enabled).show(ui, |ui, _| {
let items = |ui: &mut Ui| {
for (id, label) in options {
Radio::new((*id).to_string()).label(Label::from(tl!(*label))).enabled(enabled).show(ui);
let group = captioned(ui, Label::from(name), |name, ui| {
RadioGroup::new(name, Bind::given(value.clone())).enabled(enabled).show(ui, |ui, _| {
let items = |ui: &mut Ui| {
for (id, label) in options {
Radio::new((*id).to_string()).label(Label::from(tl!(*label))).enabled(enabled).show(ui);
}
};
if horizontal {
Row::new().show(ui, |ui, _| items(ui));
} else {
Stack::new().show(ui, |ui, _| items(ui));
}
};
if horizontal {
Row::new().show(ui, |ui, _| items(ui));
} else {
Stack::new().show(ui, |ui, _| items(ui));
}
})
});
if let Some(v) = group.output.value().cloned() {
if let Some(v) = group.and_then(|g| g.output.value().cloned()) {
*value = v;
}
}
+36 -28
View File
@@ -19,7 +19,7 @@ use craft::ui::sections::Section;
use craft::ui::style::TypeRole;
use craft::ui::text::{NumberField, TextField};
use super::host::{Asks, WordForm, open_form};
use super::host::{Asks, WordForm, captioned, labelled, open_form};
/// Opens the form dialog `name` when it is one of this file's: Table Properties (only with a table selection) or Custom
/// Properties.
@@ -49,14 +49,16 @@ fn flag(ui: &mut Ui, id: &'static str, label: String, value: &mut bool, enabled:
/// A radio group choosing one of `options` (key, label) into `value`.
fn choose(ui: &mut Ui, id: &'static str, label: String, value: &mut String, options: &[(&str, String)]) {
let chosen = RadioGroup::new(Label::from(label), Bind::given(value.clone())).id_salt(id).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
for (key, text) in options {
Radio::new((*key).to_string()).label(Label::from(text.clone())).show(ui);
}
});
let chosen = captioned(ui, Label::from(label), |name, ui| {
RadioGroup::new(name, Bind::given(value.clone())).id_salt(id).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
for (key, text) in options {
Radio::new((*key).to_string()).label(Label::from(text.clone())).show(ui);
}
});
})
});
if let Some(next) = chosen.output.value().cloned() {
if let Some(next) = chosen.and_then(|c| c.output.value().cloned()) {
*value = next;
}
}
@@ -240,14 +242,21 @@ impl WordForm for CustomPropertiesForm {
let rows: Vec<String> = self.props.iter().map(|p| format!("{} = {}", p.name, p.value)).collect();
let positions: Vec<usize> = (0..rows.len()).collect();
let mut selection = if self.selected < rows.len() { Selection::single(self.selected) } else { Selection::default() };
List::new(Label::from(tl!("Properties").to_string()))
.id_salt("props")
.max_rows(6)
.select(SelectMode::Single)
.allow_empty(true)
.empty(Label::from(tl!("This document has no custom properties.").to_string()))
.selection(Bind::bound(&mut selection))
.show_items(ui, &keyed(&positions, |at| *at), &mut |at, _| ListRow::new(rows.get(*at).cloned().unwrap_or_default()));
if rows.is_empty() {
// lean: craft's `List` measures its `.empty()` text shorter than it draws it, so the dialog is a row short and
// its footer is drawn over the last row (#7982). Show the text ourselves; drop this once craft-libs fixes
// `List`. The same latent overlap may hit the other `.empty()` users: bookmarks.rs:112/268, macros.rs:71,
// dialogs_refs/cross_ref.rs:165, dialogs_refs/sources.rs:311 and dialogs_review.rs:423.
Text::new(Label::from(tl!("This document has no custom properties.").to_string())).shade(Shade::Muted).show(ui);
} else {
List::new(Label::from(tl!("Properties").to_string()))
.id_salt("props")
.max_rows(6)
.select(SelectMode::Single)
.allow_empty(true)
.selection(Bind::bound(&mut selection))
.show_items(ui, &keyed(&positions, |at| *at), &mut |at, _| ListRow::new(rows.get(*at).cloned().unwrap_or_default()));
}
if let Some(at) = selection.items.first().copied()
&& at != self.selected
{
@@ -265,15 +274,16 @@ impl WordForm for CustomPropertiesForm {
self.delete();
}
});
let typed = TextField::new(Label::from(tl!("Name:").to_string()), Bind::given(self.name.clone()))
.id_salt("name")
.limit(wordcraft_engine::cmd::file::MAX_CUSTOM_NAME)
.show(ui);
if let Some(text) = typed.value().cloned() {
let typed = labelled(ui, Label::from(tl!("Name:").to_string()), |name, ui| {
TextField::new(name, Bind::given(self.name.clone())).id_salt("name").limit(wordcraft_engine::cmd::file::MAX_CUSTOM_NAME).show(ui)
});
if let Some(text) = typed.and_then(|out| out.value().cloned()) {
self.name = text;
}
let typed = TextField::new(Label::from(tl!("Value:").to_string()), Bind::given(self.value.clone())).id_salt("value").show(ui);
if let Some(text) = typed.value().cloned() {
let typed = labelled(ui, Label::from(tl!("Value:").to_string()), |name, ui| {
TextField::new(name, Bind::given(self.value.clone())).id_salt("value").show(ui)
});
if let Some(text) = typed.and_then(|out| out.value().cloned()) {
self.value = text;
}
if !self.message.is_empty() {
@@ -444,11 +454,9 @@ fn mixed_check(ui: &mut Ui, id: &'static str, label: String, key: &str, value: &
/// A length field over points, shown in the interface unit of `units`, within `lo..=hi` points.
fn length(ui: &mut Ui, id: &'static str, label: String, value: &mut f32, (lo, hi): (f32, f32), units: LengthUnits, enabled: bool) {
let mut points = Some(f64::from(*value));
NumberField::length(Label::from(label), Bind::bound(&mut points), units)
.id_salt(id)
.range(f64::from(lo)..=f64::from(hi))
.enabled(enabled)
.show(ui);
labelled(ui, Label::from(label), |name, ui| {
NumberField::length(name, Bind::bound(&mut points), units).id_salt(id).range(f64::from(lo)..=f64::from(hi)).enabled(enabled).show(ui)
});
if let Some(next) = points {
*value = next as f32;
}
+19 -1
View File
@@ -7,8 +7,9 @@
//! answer is inferred from side effects.
use craft::color_ui::ui::{ColorPickerDialog, ColorPickerTab};
use craft::ui::contract::Bind;
use craft::ui::contract::{Bind, FieldLayout, ShowContainer as _};
use craft::ui::dialog::{ChildDialog, DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft::ui::form::Field;
use craft::ui::patterns::form_dialogs::{AboutTab, FormButtons, FormCx, FormDialog, HostedAbout};
use craft::ui::runtime::env::Label;
use craft::ui::sections::FooterButton;
@@ -417,6 +418,23 @@ impl<F: WordForm> StackDialog for FormHost<F> {
}
}
/// `show` (given `label` to name its control, and the field's `Ui`) with `label` drawn beside the control. A text box,
/// number box or drop-down names itself but draws no caption, so every bare one in a dialog goes through here
/// (#7976). `None` when the field is not shown this pass.
pub(crate) fn labelled<R>(ui: &mut Ui, label: impl Into<Label>, show: impl FnMut(Label, &mut Ui) -> R) -> Option<R> {
field(ui, FieldLayout::Beside, label.into(), show)
}
/// `labelled`, with the caption above the control: for a radio group or a preview, which has no box for a side label
/// to sit against (#7976).
pub(crate) fn captioned<R>(ui: &mut Ui, label: impl Into<Label>, show: impl FnMut(Label, &mut Ui) -> R) -> Option<R> {
field(ui, FieldLayout::Above, label.into(), show)
}
fn field<R>(ui: &mut Ui, layout: FieldLayout, label: Label, mut show: impl FnMut(Label, &mut Ui) -> R) -> Option<R> {
Field::new(label.clone()).layout(layout).show(ui, |ui, _| show(label.clone(), ui)).inner
}
/// Opens `form` as a dialog, over `parent` when there is one.
pub(crate) fn open_form<F: WordForm>(app: &mut WordApp, parent: Option<DialogId>, form: F) -> DialogId {
let id = open_node(app, parent, FormHost::new(form, parent));
+10 -5
View File
@@ -22,7 +22,7 @@ use serde::Serialize;
use serde_json::{Value, json};
use wordcraft_engine::cmd::mailings::{FilterOp, FilterRule, SortKey};
use super::host::{DialogHooks, Settle, open_with};
use super::host::{DialogHooks, Settle, labelled, open_with};
use crate::WordApp;
/// The address parts Match Fields lists, with their keys in `mailings.matchFields`' `address`.
@@ -376,7 +376,7 @@ fn recipient_body(ui: &mut egui::Ui, d: &mut RecipientDraft, editing: &mut bool,
filter.only_merged = false;
}
Checkbox::new(Bind::bound(&mut filter.only_merged)).label(tl!("Show only records that will be merged")).enabled(order.is_some()).show(ui);
TextField::search(tl!("Find in list"), Bind::bound(&mut filter.find)).show(ui);
labelled(ui, tl!("Find in list:"), |name, ui| TextField::search(name, Bind::bound(&mut filter.find)).show(ui));
// The rows the grid shows, by real index: edits and removes go to the right record.
let fresh = visible_recipients(rows, order.as_deref(), &filter.find, filter.only_merged);
// A press that ends a cell's edit (one on the row's Remove part) completes its click on release, a pass later: the
@@ -394,7 +394,7 @@ fn recipient_body(ui: &mut egui::Ui, d: &mut RecipientDraft, editing: &mut bool,
let columns = fields
.iter()
.enumerate()
.map(|(j, f)| ColumnSpec::new(ColumnKey::index(j as u32), f.clone(), ColumnWidth::fill(1.0)).removable(tl!("Remove field"), can_remove))
.map(|(j, f)| ColumnSpec::new(ColumnKey::index(j as u32), f.clone(), ColumnWidth::Controls(6.0)).removable(tl!("Remove field"), can_remove))
.collect();
// The dialog body scrolls, and a collection owns its own scroll: the grid shows this many records and scrolls
// the rest itself.
@@ -530,11 +530,16 @@ fn filter_section(ui: &mut egui::Ui, fields: &[String], filter: &mut RecipientFi
let directions = [Entry::new(false, tl!("Ascending")), Entry::new(true, tl!("Descending"))];
for (i, (field, desc)) in filter.sort.iter_mut().enumerate() {
let label = tl!(if i == 0 { "Sort by" } else { "Then by" });
if let Some(f) = Select::new(label, Bind::given(field.clone()), &keys).id_salt(("sort", i)).show(ui).value().cloned() {
if let Some(f) = labelled(ui, label, |name, ui| Select::new(name, Bind::given(field.clone()), &keys).id_salt(("sort", i)).show(ui))
.and_then(|out| out.value().cloned())
{
*field = f;
}
let has_field = !field.is_empty();
if let Some(d) = Select::new(tl!("Order"), Bind::given(*desc), &directions).id_salt(("dir", i)).enabled(has_field).show(ui).value().copied() {
if let Some(d) =
labelled(ui, tl!("Order"), |name, ui| Select::new(name, Bind::given(*desc), &directions).id_salt(("dir", i)).enabled(has_field).show(ui))
.and_then(|out| out.value().copied())
{
*desc = d;
}
}
+16 -12
View File
@@ -15,7 +15,7 @@ use craft::ui::text::{NumberField, TextField};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::host::{Asks, DialogHooks, FormHost, Settle, WordForm, open_form, open_form_with, open_with};
use super::host::{Asks, DialogHooks, FormHost, Settle, WordForm, captioned, labelled, open_form, open_form_with, open_with};
use super::mailings::ADDRESS_PARTS;
use crate::WordApp;
@@ -115,7 +115,7 @@ impl WordForm for InsertMergeFieldForm {
} else if let (Some(name), _) = pick_name(ui, tl!("Fields:"), &self.fields, &self.field) {
self.field = name;
}
TextField::new(tl!("Field:"), Bind::bound(&mut self.field)).show(ui);
labelled(ui, tl!("Field:"), |name, ui| TextField::new(name, Bind::bound(&mut self.field)).show(ui));
!self.field.trim().is_empty()
}
fn commands(&self) -> Vec<(String, Value)> {
@@ -209,7 +209,7 @@ impl WordForm for FindRecipientForm {
Some(tl!("Find").into())
}
fn body(&mut self, ui: &mut egui::Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
TextField::new(tl!("Find:"), Bind::bound(&mut self.text)).show(ui);
labelled(ui, tl!("Find:"), |name, ui| TextField::new(name, Bind::bound(&mut self.text)).show(ui));
!self.text.trim().is_empty()
}
fn commands(&self) -> Vec<(String, Value)> {
@@ -261,10 +261,12 @@ impl WordForm for MergeRecordsForm {
}
fn body(&mut self, ui: &mut egui::Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
let mut choice = self.choice;
RadioGroup::new(tl!("Records"), Bind::bound(&mut choice)).show(ui, |ui, _| {
Radio::new(0u8).label(tl!("All")).show(ui);
Radio::new(1u8).label(tl!("Current record")).show(ui);
Radio::new(2u8).label(tl!("From:")).show(ui);
captioned(ui, tl!("Records"), |name, ui| {
RadioGroup::new(name, Bind::bound(&mut choice)).show(ui, |ui, _| {
Radio::new(0u8).label(tl!("All")).show(ui);
Radio::new(1u8).label(tl!("Current record")).show(ui);
Radio::new(2u8).label(tl!("From:")).show(ui);
})
});
self.choice = choice;
// Typing a number picks the range.
@@ -344,17 +346,19 @@ impl WordForm for MergeRuleForm {
}))
.show(ui);
if self.fields.is_empty() {
TextField::new(tl!("Field:"), Bind::bound(&mut self.field)).show(ui);
labelled(ui, tl!("Field:"), |name, ui| TextField::new(name, Bind::bound(&mut self.field)).show(ui));
} else {
let entries: Vec<Entry<String>> = self.fields.iter().map(|f| Entry::new(f.clone(), Label::from(f.clone()))).collect();
if let Some(f) = Select::new(tl!("Field:"), Bind::given(self.field.clone()), &entries).show(ui).value().cloned() {
if let Some(f) = labelled(ui, tl!("Field:"), |name, ui| Select::new(name, Bind::given(self.field.clone()), &entries).show(ui))
.and_then(|out| out.value().cloned())
{
self.field = f;
}
}
TextField::new(tl!("Equals:"), Bind::bound(&mut self.value)).show(ui);
labelled(ui, tl!("Equals:"), |name, ui| TextField::new(name, Bind::bound(&mut self.value)).show(ui));
if !skip {
TextField::new(tl!("Then insert:"), Bind::bound(&mut self.then)).show(ui);
TextField::new(tl!("Otherwise insert:"), Bind::bound(&mut self.els)).show(ui);
labelled(ui, tl!("Then insert:"), |name, ui| TextField::new(name, Bind::bound(&mut self.then)).show(ui));
labelled(ui, tl!("Otherwise insert:"), |name, ui| TextField::new(name, Bind::bound(&mut self.els)).show(ui));
}
self.params().is_some()
}
+10 -8
View File
@@ -8,7 +8,7 @@ use craft::ui::patterns::form_dialogs::FormCx;
use craft::ui::runtime::env::Label;
use serde::{Deserialize, Serialize};
use super::host::{Asks, WordForm, open_form};
use super::host::{Asks, WordForm, captioned, open_form};
use super::{Value, WordApp};
use egui::Ui;
use serde_json::json;
@@ -69,13 +69,15 @@ impl WordForm for PasteSpecialForm {
return true;
}
let formats = self.formats.clone();
RadioGroup::new(Label::from(tl!("Paste as:")), Bind::bound(&mut self.choice)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
for (at, f) in formats.iter().enumerate() {
let label = wordcraft_engine::cmd::paste::FORMATS.iter().find(|(id, _)| id == f).map(|(_, l)| *l).unwrap_or(f.as_str());
cx.labelled(ui, at, Label::from(tl!(label).to_owned()), SideLabel::new().layout(FieldLayout::After), Radio::new(at));
}
});
captioned(ui, Label::from(tl!("Paste as:")), |name, ui| {
RadioGroup::new(name, Bind::bound(&mut self.choice)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
for (at, f) in formats.iter().enumerate() {
let label = wordcraft_engine::cmd::paste::FORMATS.iter().find(|(id, _)| id == f).map(|(_, l)| *l).unwrap_or(f.as_str());
cx.labelled(ui, at, Label::from(tl!(label).to_owned()), SideLabel::new().layout(FieldLayout::After), Radio::new(at));
}
});
})
});
if let Some(f) = formats.get(self.choice) {
Text::new(Label::from(tl!("Result"))).show(ui);
+2 -2
View File
@@ -191,11 +191,11 @@ const MARGIN_SIDES: [(&str, &str); 4] = [("top", "Top"), ("left", "Left"), ("bot
fn open_cell_margins(app: &mut WordApp, ctx: &Context, parent: Option<DialogId>) -> Option<DialogId> {
let margins = cell_margins_pt(app)?;
let fields = DialogFields::from_pairs(MARGIN_SIDES.iter().zip(margins).map(|((key, _), v)| (*key, v)));
let kind = crate::options::unit_kind(app.session.units());
let units = crate::options::lengths(app.session.units());
let dialog = HostedParamDialog::new(ctx, "tableCellMargins", fields, move |fields| {
let params: Vec<Param> = MARGIN_SIDES
.iter()
.map(|(key, label)| Param::number(*key, tl!(label).to_string(), 0.0, 1.0, 2).bounds(Some(0.0), Some(144.0)).unit(kind))
.map(|(key, label)| Param::number(*key, tl!(label).to_string(), 0.0, units.shown.step(), 2).bounds(Some(0.0), Some(144.0)).length(units))
.collect();
ParamDialog::command("tableCellMargins", tl!("Cell Margins").to_string(), params).values(Bind::bound(fields)).alt_resets(false)
});
+2 -2
View File
@@ -8,7 +8,7 @@ use craft::ui::contract::{
Bind, CollectionEvent, ColumnSpec, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec, clicked,
};
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft::ui::display::{Picture, Shade, Text};
use craft::ui::display::{Picture, PictureSize, Shade, Text};
use craft::ui::form::Field;
use craft::ui::list::{List, ListRow};
use craft::ui::pickers::Select;
@@ -183,7 +183,7 @@ impl ManageStylesDialog {
if let Some((key, image)) = &self.preview {
let image = image.clone();
let make = move || image.clone();
Picture::new(label(tl!("Preview")), self.made, &make).revision(key.styles).show(ui);
Picture::new(label(tl!("Preview")), self.made, &make).revision(key.styles).extent(PictureSize::DevicePixels).show(ui);
}
Text::new(label(describe(&cur))).shade(Shade::Muted).show(ui);
let style = self.selected.clone();
+209
View File
@@ -2283,3 +2283,212 @@ fn modal_dialog_with_open_popup_does_not_shake_on_inside_click_but_shakes_on_out
let key2 = chrome::nudge_id(&h.ctx, id2);
assert!(h.ctx.data(|d| d.get_temp::<f64>(key2)).is_none(), "reopened dialog starts still");
}
/// #7976: a text box, number box, drop-down or radio group has an accessible name but draws no caption of its own;
/// the dialog must draw one beside or above it, or the field reads as a bare box.
#[test]
fn bare_fields_and_groups_draw_their_captions() {
use egui::accesskit::Role;
for (dialog, captions) in
[("envelopes", &["Delivery address", "Return address", "Envelope size"][..]), ("dropCap", &["Position", "Lines to drop"][..])]
{
let mut h = app_harness(app_with("Lanterns"));
h.state_mut().run("ui.dialog", json!({"name": dialog})).unwrap();
h.run_steps(6);
for caption in captions {
let drawn = h.query_all(egui_kittest::kittest::By::new().role(Role::Label).label_contains(caption)).count();
assert!(drawn > 0, "{dialog} draws no caption \"{caption}\"");
}
}
}
/// #7976: a caption is drawn once. A group inside a titled section, or a box after a radio that says the same
/// words, must not repeat them as a second caption.
#[test]
fn captions_are_not_drawn_twice() {
use egui::accesskit::Role;
for (dialog, caption) in
[("trackChangesOptions", "Balloons"), ("trackChangesOptions", "Comments"), ("pageNumbers", "Start at"), ("tableSort", "My list has")]
{
let mut app = app_with("Lanterns");
if dialog == "tableSort" {
app.run("insert.table", json!({"rows": 3, "cols": 3})).unwrap();
}
let mut h = app_harness(app);
h.state_mut().run("ui.dialog", json!({"name": dialog})).unwrap();
h.run_steps(6);
let drawn = h.query_all(egui_kittest::kittest::By::new().role(Role::Label).label_contains(caption)).count();
assert!(drawn <= 1, "{dialog} draws \"{caption}\" {drawn} times");
}
}
/// #7977: a preview picture is drawn at a sample size, not at the icon side it takes by default.
#[test]
fn dialog_previews_are_drawn_larger_than_a_control() {
use egui::accesskit::Role;
for dialog in ["enclose", "defineBullet"] {
let mut h = app_harness(app_with("Lanterns"));
h.state_mut().run("ui.dialog", json!({"name": dialog})).unwrap();
h.run_steps(6);
let preview = h.get_by_role_and_label(Role::Image, "Preview").rect();
let button = h.get_by_role_and_label(Role::Button, "Cancel").rect();
assert!(
preview.height() > 2.0 * button.height(),
"{dialog}: 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() {
use egui::accesskit::Role;
let mut h = app_harness(app_with("Lanterns"));
h.state_mut().run("ui.dialog", json!({"name": "customProperties"})).unwrap();
h.run_steps(6);
let hint = h.get_by_label_contains("Text properties only").rect();
let cancel = h.get_by_role_and_label(Role::Button, "Cancel").rect();
let value = h.get_by_role_and_label(Role::TextInput, "Value:").rect();
assert!(!hint.intersects(cancel) && !value.intersects(cancel), "the hint {hint:?} or Value {value:?} overlaps Cancel {cancel:?}");
}
/// #7970: Cell Margins shows the table's points in the interface unit (0.19 cm, not 5.4 cm), and OK without
/// an edit leaves the table's margins as they were.
#[test]
fn cell_margins_dialog_shows_points_in_the_interface_unit_and_ok_changes_nothing() {
let mut app = app_with("");
let _ = app.run("insert.table", json!({"rows": 1, "cols": 1}));
app.session.prefs.units = Some(wordcraft_geom::Unit::Centimeters);
let mut h = app_harness(app);
h.run_steps(2);
let (tp, _, _) = h.state().session.sel.focus.path.cell().unwrap();
let margins =
|h: &egui_kittest::Harness<'_, WordApp>| h.state().session.doc.table(h.state().session.sel.focus.story, &tp).unwrap().props.cell_margins;
let before = margins(&h);
let _ = h.state_mut().run("ui.dialog", json!({"name": "tableCellMargins"}));
h.run_steps(3);
let left = h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Left").value().unwrap_or_default();
let shown: f64 = left.trim_end_matches(|c: char| !c.is_ascii_digit()).replace(',', ".").parse().unwrap_or(f64::NAN);
assert!(shown < 1.0, "5.4 pt is about 0.19 cm, not the point count: {left:?}");
let id = id_of(h.state(), "tableCellMargins");
let ctx = h.ctx.clone();
let _ = h.state_mut().dialog_host.confirm_by_id(&ctx, id);
h.run_steps(4);
assert_eq!(margins(&h), before, "OK without an edit writes no margins");
}
/// #7970: a width typed into Cell Margins in the interface unit reaches the table in points (1 cm is about 28 pt).
#[test]
fn cell_margins_dialog_converts_a_typed_length_back_to_points() {
let mut app = app_with("");
let _ = app.run("insert.table", json!({"rows": 1, "cols": 1}));
app.session.prefs.units = Some(wordcraft_geom::Unit::Centimeters);
let mut h = app_harness(app);
h.run_steps(2);
let (tp, _, _) = h.state().session.sel.focus.path.cell().unwrap();
let _ = h.state_mut().run("ui.dialog", json!({"name": "tableCellMargins"}));
h.run_steps(3);
h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Left").click();
h.run_steps(3);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Paste("1".into()));
h.run_steps(3);
h.key_press(egui::Key::Tab);
h.run_steps(3);
let id = id_of(h.state(), "tableCellMargins");
let ctx = h.ctx.clone();
let _ = h.state_mut().dialog_host.confirm_by_id(&ctx, id);
h.run_steps(4);
let left = h.state().session.doc.table(h.state().session.sel.focus.story, &tp).unwrap().props.cell_margins.map(|m| m[1]);
assert!(left.is_some_and(|l| (l - 28.35).abs() < 0.5), "1 cm is about 28.35 pt: {left:?}");
}
/// #7980: the Organizer shows this document's styles and the other file's side by side, with Copy, Delete and
/// Rename between them, all inside the dialog.
#[test]
fn organizer_shows_both_lists_and_its_buttons() {
use egui::accesskit::Role;
let mut h = app_harness(app_with(""));
h.run_steps(2);
let _ = h.state_mut().run("ui.dialog", json!({"name": "organizer"}));
h.run_steps(4);
let rect = |h: &egui_kittest::Harness<'_, WordApp>, role, name: &str| h.get_by_role_and_label(role, name).rect();
let mine = rect(&h, Role::List, "Document");
let other = rect(&h, Role::List, "Template");
assert!(mine.is_positive() && other.is_positive() && mine.right() <= other.left(), "the lists stand side by side: {mine:?} {other:?}");
// Each list is wider than the button column between them, empty (no other file) or not.
let rename = rect(&h, Role::Button, "Rename…");
assert!(mine.width() > rename.width() && other.width() > rename.width(), "the lists are wider than the buttons: {mine:?} {other:?} {rename:?}");
// The ribbon has its own Copy: the one that counts stands between the lists.
for name in ["Copy", "Delete", "Rename…"] {
let between = h
.query_all(egui_kittest::kittest::By::new().role(Role::Button).label(name))
.any(|b| b.rect().left() >= mine.right() - 1.0 && b.rect().right() <= other.left() + 1.0);
assert!(between, "{name} stands between the lists {mine:?} {other:?}");
}
}
/// Part of #7980: the Organizer's two lists have a visible frame, as before the port; without it an empty list is a
/// blank patch.
#[test]
fn the_organizer_lists_are_framed() {
use egui::accesskit::Role;
fn rects<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::epaint::RectShape>) {
match shape {
egui::Shape::Vec(inner) => inner.iter().for_each(|s| rects(s, out)),
egui::Shape::Rect(r) => out.push(r),
_ => {}
}
}
let mut h = app_harness(app_with(""));
h.run_steps(2);
let _ = h.state_mut().run("ui.dialog", json!({"name": "organizer"}));
h.run_steps(4);
let mut seen = Vec::new();
h.output().shapes.iter().for_each(|c| rects(&c.shape, &mut seen));
for label in ["Document", "Template"] {
let list = h.get_by_role_and_label(Role::List, label).rect();
assert!(
seen.iter().any(|r| r.stroke.width > 0.0
&& r.stroke.color.a() > 0
&& r.rect.contains_rect(list.shrink(2.0))
&& list.expand(2.0).contains_rect(r.rect)),
"the list {label:?} {list:?} has a border"
);
}
}
/// Part of #7981 and #7980: the lists of Customize Ribbon and its Quick Access Toolbar page have a visible
/// frame, as before the port; without it an empty list is a blank patch.
#[test]
fn the_ribbon_customizer_lists_are_framed() {
use egui::accesskit::Role;
fn rects<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::epaint::RectShape>) {
match shape {
egui::Shape::Vec(inner) => inner.iter().for_each(|s| rects(s, out)),
egui::Shape::Rect(r) => out.push(r),
_ => {}
}
}
fn assert_framed(h: &egui_kittest::Harness<'_, WordApp>, label: &str) {
let list = h.get_by_role_and_label(Role::List, label).rect();
let mut seen = Vec::new();
h.output().shapes.iter().for_each(|c| rects(&c.shape, &mut seen));
assert!(
seen.iter().any(|r| r.stroke.width > 0.0
&& r.stroke.color.a() > 0
&& r.rect.contains_rect(list.shrink(2.0))
&& list.expand(2.0).contains_rect(r.rect)),
"the list {label:?} {list:?} has a border"
);
}
let mut h = app_harness(app_with(""));
open_named(&mut h, "customizeRibbon", json!({}));
assert_framed(&h, "Categories:");
assert_framed(&h, "Commands:");
assert_framed(&h, "Ribbon tabs");
h.get_by_role_and_label(Role::Tab, "Quick Access Toolbar").click();
h.run_steps(3);
assert_framed(&h, "Quick Access Toolbar");
}
+17 -1
View File
@@ -44,7 +44,8 @@ pub(crate) fn button_picture(id: &str) -> &'static str {
/// The ink math pictures are rendered in: the theme's text colour.
fn ink(ui: &Ui) -> Color32 {
ui.visuals().text_color()
// The craft theme's token, not egui's visuals, which the craft theme does not drive (grey ink in the light theme, #7975).
craft::ui::style::rgba_color(craft::ui::runtime::env::Env::of(ui).tokens.color.text.normal)
}
/// The keys `0..n` as a collection source.
@@ -386,6 +387,21 @@ mod placeholder_tests {
output.textures_delta.clear();
}
/// The pictures' ink is the craft theme's text colour, so it reads against the window in the light theme (egui's
/// own visuals are not driven by the craft theme and gave grey ink there, #7975).
#[test]
fn the_equation_ink_contrasts_with_the_theme_surface() {
let ctx = crate::test_harness::context();
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
let env = craft::ui::runtime::env::Env::of(ui);
let luma = |c: egui::Color32| 0.299 * f32::from(c.r()) + 0.587 * f32::from(c.g()) + 0.114 * f32::from(c.b());
let ink = super::ink(ui);
let surface = craft::ui::style::rgba_color(env.tokens.color.surface.background);
assert!((luma(ink) - luma(surface)).abs() > 100.0, "ink {ink:?} against {surface:?}");
});
output.textures_delta.clear();
}
#[test]
fn a_missing_math_glyph_falls_back_to_its_linear_name() {
// Without craft-fonts the interface fonts may have no `┬`: the Equation button's picture
+76 -26
View File
@@ -9,6 +9,7 @@ use craft::behavior::{EditEvent, MotionMode, keyed};
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Entry, Props as _, Show, ShowCollection, ShowContainer};
use craft::ui::display::{Elide, Shade, Text};
use craft::ui::form::{SliderField, SliderFieldLayout};
use craft::ui::layout_components::Row;
use craft::ui::list::{List, ListRow};
use craft::ui::patterns::preferences::{GroupSpec, PageSpec, PrefValue, PreferencesModel, PreferencesPage, RowKind, RowSpec};
@@ -302,7 +303,6 @@ impl PreferencesModel for OptionsModel<'_> {
use crate::StatusCount;
use crate::scroll::ScrollSpeed;
use crate::theme::{Animations, Appearance};
use wordcraft_engine::speech::{MAX_RATE, MIN_RATE};
let app = &*self.app;
let s = &self.strings;
let prefs = &app.session.prefs;
@@ -375,7 +375,8 @@ impl PreferencesModel for OptionsModel<'_> {
b("display.spaces", tl!("Spaces"), marks.spaces),
b("display.paragraphs", tl!("Paragraph marks"), marks.paragraphs),
b("display.hidden", tl!("Hidden text"), marks.hidden),
b("display.allMarks", tl!("Show all formatting marks"), app.session.view.marks),
b("display.allMarks", tl!("Show all formatting marks"), app.session.view.marks)
.help(tl!("These marks show even when Show/Hide ¶ is off.")),
],
),
GroupSpec::new(
@@ -404,8 +405,7 @@ impl PreferencesModel for OptionsModel<'_> {
],
),
],
)
.footnote(tl!("These marks show even when Show/Hide ¶ is off."));
);
let proofing = page_of(
"proofing",
@@ -445,7 +445,11 @@ impl PreferencesModel for OptionsModel<'_> {
GroupSpec::new(Some(tl!("Save documents")), {
// The browser can't write to the user's files, so AutoSave can't be turned on there (#176).
let row = b("save.autosave", tl!("AutoSave documents you have saved in WordCraft"), app.autosave && !browser).enabled(!browser);
vec![if browser { row.help(&s.autosave_reason) } else { row }]
vec![row.help(if browser {
&s.autosave_reason
} else {
tl!("AutoSave writes your changes to the file a moment after you stop typing.")
})]
}),
// The open document's `file.privacyOptions` (#1062): saved with it, honoured when it is saved.
GroupSpec::new(
@@ -460,12 +464,12 @@ impl PreferencesModel for OptionsModel<'_> {
"save.removeDateTime",
tl!("Leave out the date and time of comments and tracked changes when saving"),
settings.remove_date_time,
),
)
.help(tl!("The document you are editing keeps the names and dates; only the saved file leaves them out.")),
],
),
],
)
.footnote(tl!("AutoSave writes your changes to the file a moment after you stop typing."));
);
let language = page_of(
"language",
@@ -486,11 +490,7 @@ impl PreferencesModel for OptionsModel<'_> {
GroupSpec::new(
Some(tl!("Dictionaries")),
vec![
RowSpec::new(
"language.dictionariesFolder",
tl!("Dictionaries folder:"),
RowKind::Text(prefs.dictionaries_folder.as_deref().unwrap_or("")),
)
RowSpec::new("language.dictionariesFolder", tl!("Dictionaries folder:"), RowKind::Custom)
.help(tl!("Hunspell .aff and .dic files here (pl_PL, pt_BR, it_IT, hr_HR, tr_TR) are used before the system's.\nAn installed Language pack is used after this folder.")),
custom("language.dictionaryFiles", tl!("Dictionary files")),
],
@@ -523,12 +523,7 @@ impl PreferencesModel for OptionsModel<'_> {
GroupSpec::new(
Some(tl!("Read Aloud")),
vec![
RowSpec::new(
"accessibility.readAloudSpeed",
tl!("Speed"),
RowKind::float(app.session.read_aloud.rate() as f64, (MIN_RATE as f64)..=(MAX_RATE as f64), 2),
)
.step(0.05),
RowSpec::new("accessibility.readAloudSpeed", tl!("Speed"), RowKind::Custom),
b("accessibility.skipCitations", tl!("Skip citations & bibliography"), app.session.read_aloud.skip_citations),
],
),
@@ -586,12 +581,8 @@ impl PreferencesModel for OptionsModel<'_> {
groups.push(GroupSpec::new(
Some(tl!("File locations")),
vec![
RowSpec::new(
"advanced.templatesFolder",
tl!("User templates:"),
RowKind::Text(prefs.user_templates_folder.as_deref().unwrap_or("")),
)
.help(tl!("File › New lists the .dotx and .dotm templates here under Personal; Save as Word Template starts here.")),
RowSpec::new("advanced.templatesFolder", tl!("User templates:"), RowKind::Custom)
.help(tl!("File › New lists the .dotx and .dotm templates here under Personal; Save as Word Template starts here.")),
],
));
}
@@ -710,6 +701,15 @@ impl PreferencesModel for OptionsModel<'_> {
"general.defaultApp" => default_app_row(self.app, ui),
"proofing.autoCorrect" => self.command_button(ui, tl!("AutoCorrect Options"), "tools.autocorrect"),
"proofing.customDictionaryFile" => self.custom_dictionary_file(ui),
"language.dictionariesFolder" => {
let saved = self.app.session.prefs.dictionaries_folder.clone().unwrap_or_default();
self.folder_row(ui, key, tl!("Dictionaries folder:"), saved, tl!("Not set: the system's usual places").to_string())
}
"advanced.templatesFolder" => {
let saved = self.app.session.prefs.user_templates_folder.clone().unwrap_or_default();
let default = self.app.services.templates_dir.as_ref().map(|d| d.to_string_lossy().into_owned());
self.folder_row(ui, key, tl!("User templates:"), saved, default.unwrap_or_else(|| tl!("Not set").to_string()))
}
"proofing.customDictionary" => self.custom_dictionary(ui),
"language.proofingLanguage" => {
Text::new(self.strings.proofing_language.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
@@ -724,6 +724,7 @@ impl PreferencesModel for OptionsModel<'_> {
dictionary_files(ui);
false
}
"accessibility.readAloudSpeed" => self.read_aloud_speed(ui),
"advanced.customizeKeyboard" => self.command_button(ui, tl!("Customize…"), "tools.customizeKeyboard"),
"advanced.customizeRibbon" => self.command_button(ui, tl!("Customize…"), "tools.customizeRibbon"),
_ => false,
@@ -732,7 +733,6 @@ impl PreferencesModel for OptionsModel<'_> {
fn custom_page(&mut self, ui: &mut Ui, page: &str) -> bool {
if page == "agents" {
Text::new(tl!("Agents")).role(TypeRole::Heading).show(ui);
Text::new(tl!("Every command is available to scripts and AI agents: run `wordcraft-cli mcp` for an MCP server, or start the app with `--control <port>` for the JSON control channel."))
.show(ui);
}
@@ -769,6 +769,56 @@ impl OptionsModel<'_> {
clicked
}
/// The Read Aloud speed: a slider with its number, as the player's.
fn read_aloud_speed(&mut self, ui: &mut Ui) -> bool {
use wordcraft_engine::speech::{MAX_RATE, MIN_RATE};
let rate = f64::from(self.app.session.read_aloud.rate());
let out = SliderField::new(tl!("Speed"), Bind::given(rate), f64::from(MIN_RATE)..=f64::from(MAX_RATE))
.step(0.05)
.layout(SliderFieldLayout::Inline)
.short(true)
.unit(tl!("×"))
.show(ui);
// Committed, not live, so a drag doesn't restart the sentence on every frame.
let committed = out.edit.events.committed().copied();
if let Some(v) = committed {
self.set("accessibility.readAloudSpeed", PrefValue::Float(v));
}
committed.is_some()
}
/// A folder setting (v0.19.1's): the saved path or a placeholder, Apply (or Enter) saves the typed path,
/// Clear returns to the default. The draft follows the saved path whenever that changes.
fn folder_row(&mut self, ui: &mut Ui, key: &str, label: &'static str, saved: String, placeholder: String) -> bool {
#[derive(Clone, Default)]
struct Draft {
text: String,
seen: Option<String>,
}
let mut changed = false;
Row::new().id_salt(key).show(ui, |ui, cx| {
let draft = &mut cx.keep::<Draft>();
if draft.seen.as_deref() != Some(saved.as_str()) {
draft.text = saved.clone();
draft.seen = Some(saved.clone());
}
let out = TextField::new(label, Bind::bound(&mut draft.text)).limit(None).placeholder(placeholder.clone()).submits().show(ui);
let typed = draft.text.trim().to_string();
let differs = typed != saved;
let apply = Button::new(tl!("Apply")).enabled(differs).show(ui).clicked() || (out.submitted && differs);
let clear = Button::new(tl!("Clear")).enabled(!saved.is_empty()).show(ui).clicked();
if apply {
self.set(key, PrefValue::Text(typed));
changed = true;
} else if clear {
self.set(key, PrefValue::Text(String::new()));
draft.text.clear();
changed = true;
}
});
changed
}
fn custom_dictionary_file(&mut self, ui: &mut Ui) -> bool {
let saved = self.app.session.prefs.custom_dictionary.clone().unwrap_or_default();
let out = TextField::new(tl!("Dictionary file:"), Bind::given(saved)).limit(None).show(ui);
+85
View File
@@ -454,3 +454,88 @@ fn escape_does_not_commit_the_custom_dictionary_path() {
assert_eq!(dictionary_field_text(&h), "", "the field shows the saved (empty) path");
let _ = std::fs::remove_dir_all(&dir);
}
/// #7987: the Read Aloud speed is a slider, not only a number box.
#[test]
fn read_aloud_speed_is_a_slider() {
use egui_kittest::kittest::Queryable;
let h = options_harness(app(), system_reducing_motion(false));
let _ = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Speed");
}
/// #7987: the Agents page names itself once.
#[test]
fn agents_page_has_one_heading() {
use egui_kittest::kittest::Queryable;
let mut a = app();
a.run("ui.backstage", json!({"value": true, "page": "options", "pane": "agents"})).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);
use egui_kittest::kittest::NodeT;
// The nav entry is a list item; every other node that carries the name is a title.
let titles = h.query_all_by_label("Agents").filter(|n| n.accesskit_node().role() != egui::accesskit::Role::ListItem).count();
assert_eq!(titles, 2, "the page's group and its title, no second heading");
}
/// #7987: a hint sits under the setting it explains, not in a page footnote at the bottom.
#[test]
fn display_and_save_hints_sit_under_their_rows() {
let mut a = app();
let (display, save, privacy) = with_model(&mut a, true, |m| {
let pages = m.pages();
let help_of = |page: &str, key: &str| {
let p = pages.iter().find(|p| p.id == page).expect("page");
let r = p.groups.iter().flat_map(|g| g.rows.iter()).find(|r| r.key == key).expect("row");
(p.footnote.is_none(), r.help.is_some())
};
(help_of("display", "display.allMarks"), help_of("save", "save.autosave"), help_of("save", "save.removeDateTime"))
});
assert_eq!(display, (true, true));
assert_eq!(save, (true, true));
assert_eq!(privacy, (true, true), "the Privacy hint under its row");
}
/// #7987: a folder setting has Apply and Clear. Typing alone saves nothing, Apply saves the typed path, and Clear
/// returns to the default.
#[test]
fn folder_settings_have_apply_and_clear() {
use egui_kittest::kittest::Queryable;
let dir = std::env::temp_dir().join(format!("wc-ui-folder-row-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.to_string_lossy().into_owned();
for (pane, label, saved) in [
("advanced", "User templates:", (|a: &WordApp| a.session.prefs.user_templates_folder.clone()) as fn(&WordApp) -> Option<String>),
("language", "Dictionaries folder:", |a: &WordApp| a.session.prefs.dictionaries_folder.clone()),
] {
let mut a = app();
a.run("ui.backstage", json!({"value": true, "page": "options", "pane": pane})).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);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, label).focus();
options_frames(&mut h, 2);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, label).type_text(&path);
options_frames(&mut h, 3);
assert_eq!(saved(h.state()), None, "{label} typing alone saved");
h.get_by_label("Apply").click();
options_frames(&mut h, 3);
assert_eq!(saved(h.state()).as_deref(), Some(path.as_str()), "{label} Apply");
h.get_by_label("Clear").click();
options_frames(&mut h, 3);
assert_eq!(saved(h.state()), None, "{label} Clear");
}
let _ = std::fs::remove_dir_all(&dir);
}
+1 -1
View File
@@ -61,7 +61,7 @@ pub(super) fn smart_art_design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let on = layouts.iter().position(|l| *l == g.layout);
let colors = g.colors;
let theme = &theme;
let line = ui.visuals().weak_text_color();
let line = craft::ui::style::rgba_color(craft::ui::runtime::env::Env::of(ui).tokens.color.text.muted);
let picked = pick_tile(ui, tl!("Layouts"), 4, CaptionPlace::None, on, layouts.len(), |at| match layouts.get(at).copied() {
Some(layout) => Tile::new(tl!(layout.label()).to_string())
.thumb(ThumbAspect::new(46, 31), move |cx, r| crate::dialogs_smart_art::preview(cx, r, layout, colors, theme, line)),
-3
View File
@@ -476,9 +476,6 @@ impl Tokens {
on_close: Color32::WHITE,
}
}
pub fn get(ctx: &egui::Context) -> Tokens {
if ctx.global_style().visuals.dark_mode { Tokens::dark() } else { Tokens::light() }
}
}
/// Add `faces` after every other font of the interface families.
+4 -1
View File
@@ -922,10 +922,13 @@ fn check_doctypes(pkg: &Package, acc: &mut Acc) {
/// The adverse non-relationships roles in the isolated, closure, and forms probe series.
fn is_measured_adverse_doctype(form: scan::DoctypeForm, content_type: Option<&str>) -> bool {
// Windows Word refuses a settings part with a DOCTYPE however its content type is cased (#7736 K3/K4).
if content_type.is_some_and(|ct| ct.eq_ignore_ascii_case(package::SETTINGS_CONTENT_TYPE)) {
return true;
}
match content_type {
Some(
package::STYLES_CONTENT_TYPE
| package::SETTINGS_CONTENT_TYPE
| package::FONT_TABLE_CONTENT_TYPE
| package::THEME_CONTENT_TYPE
| package::NUMBERING_CONTENT_TYPE
+23
View File
@@ -503,6 +503,29 @@ fn xml_doctype_internal_entity_in_diagram_definitions_warns() {
}
}
#[test]
fn xml_doctype_in_settings_grades_the_same_whatever_the_content_type_casing() {
// #7736 K3/K4: Windows Word refuses both packages; the grade must not depend on the Override's casing.
let exact = "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml";
let varied = "application/vnd.openxmlformats-officedocument.Wordprocessingml.Settings+XML";
let grade = |content_type: &str| {
let mut doc = Doc::minimal();
doc.set_doc_rels(
r#"<Relationship Id="rSet" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/>"#,
);
doc.add_with_override(
"word/settings.xml",
content_type,
r#"<!DOCTYPE w:settings [<!ENTITY greeting "hello">]><w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"/>"#,
);
let report = validate(&doc);
let finding = assert_finding(&report, "XML-DOCTYPE", Some("word/settings.xml"));
(finding.severity, finding.evidence)
};
assert_eq!(grade(exact), (Severity::Error, Evidence::Observed));
assert_eq!(grade(varied), grade(exact));
}
#[test]
fn xml_doctype_attlist_in_diagram_layout_warns() {
let mut doc = Doc::minimal();
+14 -12
View File
@@ -32,35 +32,37 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-
| Editing | 41 | 41 |
| Tools | 7 | 7 |
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 510 yes, 12 no (window 3, os 8, engine-gap 1), 0 partial, 0 unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.
## Missing
### Home
- Voice › Dictate (`tools.dictate`)
- Voice › Dictate (`tools.dictate`): headless: no, reach: os (speech recognition service)
### Insert
- Illustrations › Online Pictures (`insert.onlinePicture`)
- Illustrations › 3D Models (`insert.model3d`)
- Illustrations › Screenshot (`insert.screenshot`)
- Add-ins › Get Add-ins (`addins.get`)
- Media › Online Video (`insert.video`)
- Symbols › Ink Equation (`insert.inkEquation`)
- Illustrations › Online Pictures (`insert.onlinePicture`): headless: no, reach: os (online image search service)
- Illustrations › 3D Models (`insert.model3d`): headless: no, reach: engine-gap (3-D model files could be inserted by a command)
- Illustrations › Screenshot (`insert.screenshot`): headless: no, reach: os (screen capture of other windows)
- Add-ins › Get Add-ins (`addins.get`): headless: no, reach: os (add-in store service)
- Media › Online Video (`insert.video`): headless: no, reach: os (online video service)
- Symbols › Ink Equation (`insert.inkEquation`): headless: no, reach: window (drawn with a pen or pointer)
### Draw
- Convert › Ink to Math (`draw.inkToMath`)
- Convert › Ink to Math (`draw.inkToMath`): headless: no, reach: os (handwriting recognition service)
### Review
- Language › Translate (`review.translate`)
- Protect › Block Authors (`review.blockAuthors`)
- Language › Translate (`review.translate`): headless: no, reach: os (online translation service)
- Protect › Block Authors (`review.blockAuthors`): headless: no, reach: os (co-authoring service)
### Read Mode
- View › Layout (`view.readLayout`)
- View › Layout (`view.readLayout`): headless: no, reach: window (Read Mode window layout)
### Equation
- Tools › Ink Equation (`insert.inkEquation`)
- Tools › Ink Equation (`insert.inkEquation`): headless: no, reach: window (drawn with a pen or pointer)
+3 -2
View File
@@ -33,11 +33,12 @@ OUTPUT="$DIST/wordcraft-$VERSION-macos-aarch64-nightly.zip"
nightly_compile_gui
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/WordCraft"
chmod 755 "$APP/Contents/MacOS/WordCraft"
cp "$ROOT/assets/app-icon/wordcraft-nightly.icns" "$APP/Contents/Resources/wordcraft-nightly.icns"
nightly_copy_notices "$APP/Contents/Resources"
# Launcher admits notices under Resources/docs, not beside the icon.
nightly_copy_notices "$APP/Contents/Resources/docs"
# The private mktemp cwd is the helper authority root: stage the template inside it.
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
+82 -2
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
real signature, notarization or Mac run."""
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
import base64
import importlib.util
import json
@@ -27,6 +27,8 @@ COMMIT = "b" * 40
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
ASSET = f"wordcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "WordCraft Nightly.app"
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
SECRETS = {
@@ -183,6 +185,50 @@ class Fixture:
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
return self.input
def package(self, font_licences):
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
source = HERE.parents[1]
checkout = self.root / "source"
checkout.mkdir()
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
"assets/app-icon/wordcraft-nightly.icns"):
target = checkout / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source / relative, target)
env = self.env(**dict.fromkeys(SECRETS))
def git(*args):
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
git("init", "-q")
git("add", "--", ".")
git("-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-qm", "Packaging fixture")
commit = git("rev-parse", "HEAD").strip()
version = VERSION[:-12] + commit[:12]
# Generated licence text exercises the copier without depending on a font checkout.
fonts = self.root / "craft-fonts"
for family, data in font_licences.items():
licence = fonts / "fonts" / family / "OFL.txt"
licence.parent.mkdir(parents=True)
licence.write_bytes(data)
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
(self.bin / "cargo").write_text(
'#!/bin/sh\nset -eu\n'
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/wordcraft"\n'
'mkdir -p "$(dirname "$gui")"\n'
"printf \"#!/bin/sh\\necho 'WordCraft %s (nightly-v1)'\\n\" \"$WORDCRAFT_VERSION\" >\"$gui\"\n",
)
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
WORDCRAFT_BUILD_CHANNEL="nightly-v1", WORDCRAFT_VERSION=version,
WORDCRAFT_BUILD_SHA=commit, WORDCRAFT_BUILD_DATE="2026-11-23")
assert result.returncode == 0, result.stdout
return self.dist / ASSET.replace(VERSION, version)
def env(self, **changes):
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
@@ -410,6 +456,40 @@ class Verify(unittest.TestCase):
class Build(unittest.TestCase):
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
f = Fixture(self)
fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"}
archive = f.package(fonts)
source = HERE.parents[1]
resources = f"{APP}/Contents/Resources"
icon = "wordcraft-nightly.icns"
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
contents = f"{APP}/Contents"
gui = f"{contents}/MacOS/WordCraft"
with zipfile.ZipFile(archive) as zipped:
entries = zipped.infolist()
names = {entry.filename for entry in entries}
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
for path, data in expected_files.items():
with self.subTest(path=path):
self.assertEqual(zipped.read(path), data)
mode = zipped.getinfo(path).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode))
self.assertFalse(mode & 0o111)
mode = zipped.getinfo(gui).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
self.assertEqual(result.returncode, 0, result.stdout)
def test_compilation_refuses_signing_material_before_building(self):
f = Fixture(self)
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
+96 -6
View File
@@ -38,6 +38,49 @@ def assert_nightly_serialization(source):
raise ValueError("nightly serialization must use its stable group and no cancellation")
def caller_entries(lines, indent):
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
entries = {}
children = None
for line in lines:
if children is not None and line.startswith(" " * (indent + 1)):
children.append(line)
continue
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
if row is None or row[1] in entries:
raise ValueError("malformed or duplicate caller mapping entry")
children = []
entries[row[1]] = row[2], children
return entries
def assert_caller_secrets(source, job_name, names):
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
root = caller_entries(lines, 0)
job_marker, job_lines = root.pop("jobs", (None, []))
jobs = caller_entries(job_lines, 2)
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
raise ValueError("the caller must have one plain job block")
job = caller_entries(jobs[job_name][1], 4)
if "environment" in job or "environment" in root or "secrets" in root:
raise ValueError("only the native callee may bind the environment")
if names:
if "secrets" not in job:
raise ValueError("signer requires an explicit target-specific secret map")
mode, secret_lines = job.pop("secrets")
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
if mode is not None or caller_entries(secret_lines, 6) != expected:
raise ValueError("signer must forward exactly the reviewed same-name secret references")
elif "secrets" in job:
raise ValueError("unsigned caller must not pass secrets")
for value, children in (*root.values(), *job.values()):
outside_map = "\n".join([value or "", *children])
# Scan all remaining text: quoted braces can appear before a secret reference.
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
raise ValueError("secret bindings belong only in the signer map")
def literal_off(condition):
expression = " ".join(condition.split())
if expression.startswith("${{") and expression.endswith("}}"):
@@ -87,6 +130,12 @@ def job_conditions(jobs):
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# The pinned shared registry enables Windows, Linux and macOS for WordCraft.
SIGNER_SECRETS = {
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
}
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
"windows-x86_64": ("publisher_subject",
@@ -140,7 +189,7 @@ def reviewed_manual_actors(caller_source, policy):
def caller_pin(name):
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0]
return re.findall(r"(?m)^ tooling-revision: (\S+)$", (ROOT / ".github/workflows" / name).read_text())[0]
class TrustedSourcePreparation(unittest.TestCase):
@@ -226,8 +275,49 @@ class TrustedSourcePreparation(unittest.TestCase):
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
header = " secrets:\n"
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
self.assertIn(linux, signer)
mutations = {
"missing name": signer.replace(linux, ""),
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
"duplicate name": signer.replace(linux, linux + linux),
"duplicate map": signer + header + linux,
"quoted duplicate map": signer + ' "secrets": inherit\n',
"inherit": signer.split(header)[0] + " secrets: inherit\n",
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
"yaml merge": signer + " <<: *other\n",
"environment": signer + " environment: release\n",
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
}
for change, source in mutations.items():
with self.subTest(change=change), self.assertRaises(ValueError):
assert_caller_secrets(source, "release", SIGNER_SECRETS)
def test_unsigned_caller_has_no_secrets(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
assert_caller_secrets(producer, "unsigned", set())
for suffix in (" secrets: {}\n", " secrets: inherit\n",
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
assert_caller_secrets(producer + suffix, "unsigned", set())
def test_unsigned_caller_refuses_secret_after_format_brace(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
# This inert fixture is never dispatched; the brace is part of the format string.
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
assert_caller_secrets(source, "unsigned", set())
class NightlyTrustAnchors(unittest.TestCase):
@@ -264,7 +354,7 @@ class NightlyTrustAnchors(unittest.TestCase):
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
pins.update(uses)
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main")
class NightlyEnabledCallers(unittest.TestCase):
@@ -647,7 +737,7 @@ def trust_closure_problems(workflows):
if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"):
if name == "nightly-sign.yml":
signer_calls += 1
if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref):
if name != "nightly-sign.yml" or ref != "main":
problems.append(name + " calls nightly-release.yml@" + ref)
if workflow.lower() in ("release.yml", "release.yaml"):
stable_callers.add(name)
@@ -694,7 +784,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
"environment in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {environment: release}\n"},
"uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"},
"another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])},
"a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")},
"a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"},
"a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")},
}
+7 -1
View File
@@ -11,7 +11,7 @@ sonar.python.coverage.reportPaths=python-coverage.xml
# S4790 (weak hash): SHA-1 is a start-key and "SHA1/1K" checksum algorithm that ODF package
# encryption (ODF 1.3 Part 2 §4.16) names, and older office suites wrote it. It is needed to open
# those files, not chosen for new security: WordCraft writes a SHA-256 start key and checksum.
sonar.issue.ignore.multicriteria=odt_sha1
sonar.issue.ignore.multicriteria=odt_sha1,validate_py_paths
sonar.issue.ignore.multicriteria.odt_sha1.ruleKey=rust:S4790
sonar.issue.ignore.multicriteria.odt_sha1.resourceKey=crates/formats/src/odt/crypt.rs
@@ -22,3 +22,9 @@ sonar.issue.ignore.multicriteria.odt_sha1.resourceKey=crates/formats/src/odt/cry
# os_window, control-key). process_identity.rs is Windows-only (the taskbar AUMID) and cannot run
# on the Linux runner either.
sonar.coverage.exclusions=packaging/**,apps/wordcraft/src/main.rs,apps/wordcraft-cli/src/main.rs,apps/wordcraft/src/process_identity.rs
# S8707 (path traversal): the crates/validate *.py scripts are developer tools run by hand to
# regenerate checked-in files; reading and writing the paths given on their command line is
# their purpose, and nothing passes them untrusted input.
sonar.issue.ignore.multicriteria.validate_py_paths.ruleKey=pythonsecurity:S8707
sonar.issue.ignore.multicriteria.validate_py_paths.resourceKey=crates/validate/**/*.py