Merge pull request #5132 from squalorso/formatting-shortcuts-say-what-they-did

Screen readers: formatting shortcuts say what they did, as Word does
This commit is contained in:
FredApps
2026-11-21 00:00:57 +07:00
committed by GitHub
9 changed files with 388 additions and 5 deletions
+4 -1
View File
File diff suppressed because one or more lines are too long
+364
View File
@@ -0,0 +1,364 @@
//! Screen readers: what a formatting shortcut did, said as Word says it ("Bold On", "Center Off",
//! "Font 14pt"). Word raises these itself; here they go through a polite live region, which
//! screen readers read when it appears.
use egui::accesskit::{Live, Role};
use serde_json::Value;
use wordcraft_doc::Align;
use crate::WordApp;
/// How long an announcement stays in the tree: a screen reader reads its name after the
/// live-region event, so it must still be there then.
const SHOWN_MS: f64 = 3000.0;
/// An announcement for screen readers. Each one gets its own node, numbered: a live region is
/// read when it appears or its text changes, so the same text twice needs a new node.
#[derive(Clone, Debug)]
pub(crate) struct Announcement {
text: String,
serial: u64,
at: f64,
}
/// Announces what the shortcut for command `id` did, once it has run; nothing for a command Word
/// doesn't announce.
pub(crate) fn after_shortcut(app: &mut WordApp, id: &str, ctx: &egui::Context) {
let Some(text) = describe(app, id) else { return };
let serial = app.announcement.as_ref().map_or(0, |a| a.serial.wrapping_add(1));
app.announcement = Some(Announcement { text, serial, at: ctx.input(|i| i.time) * 1000.0 });
}
/// The words for what command `id` did: the command's name and whether its formatting is now on,
/// or the font size the selection now has.
fn describe(app: &WordApp, id: &str) -> Option<String> {
let on_off = |name: &str, on: bool| format!("{name} {}", if on { tl!("On") } else { tl!("Off") });
let state = || wordcraft_engine::cmd::format::state(&app.session);
let character = match id {
"format.bold" => Some(("bold", tl!("Bold"))),
"format.italic" => Some(("italic", tl!("Italic"))),
"format.underline" => Some(("underline", tl!("Underline"))),
"format.subscript" => Some(("subscript", tl!("Subscript"))),
"format.superscript" => Some(("superscript", tl!("Superscript"))),
_ => None,
};
if let Some((key, name)) = character {
return Some(on_off(name, state().get(key).and_then(Value::as_bool).unwrap_or(false)));
}
let alignment = match id {
"para.alignLeft" => Some((Align::Left, tl!("Align Left"))),
"para.alignCenter" => Some((Align::Center, tl!("Center"))),
"para.alignRight" => Some((Align::Right, tl!("Align Right"))),
"para.justify" => Some((Align::Justify, tl!("Justify"))),
_ => None,
};
if let Some((want, name)) = alignment {
// As the ribbon's buttons show it: Center twice centres, then goes back to the left. Read
// in a paragraph the command formatted: a selection ending at the next paragraph's start
// leaves that one out (#418).
let s = &app.session;
let formatted = wordcraft_engine::cmd::selected_paths(s);
let path = if formatted.contains(&s.sel.focus.path) { Some(s.sel.focus.path.clone()) } else { formatted.last().cloned() };
let at = path.map(|path| wordcraft_doc::Pos { path, off: 0, ..s.sel.focus.clone() });
let align = at.and_then(|at| s.doc.para_at(&at)).map(|p| s.doc.styles.resolve_para(&p.props)).map(|r| r.align.visual(r.bidi));
return Some(on_off(name, align == Some(want)));
}
if matches!(id, "format.growFont" | "format.shrinkFont" | "format.growFont1" | "format.shrinkFont1") {
// A selection of mixed sizes has no one size to say.
let size = state().get("size").and_then(Value::as_f64)?;
let unit = wordcraft_geom::Unit::Points;
let number = unit.number(size as f32, app.session.region().decimal());
return Some(format!("{} {number}{}", tl!("Font"), crate::options::unit_suffix(unit)));
}
None
}
/// Puts the latest announcement in the tree, as a polite live region, while it is fresh.
pub(crate) fn expose(app: &WordApp, ctx: &egui::Context) {
let Some(a) = &app.announcement else { return };
let age = ctx.input(|i| i.time) * 1000.0 - a.at;
if !(0.0..SHOWN_MS).contains(&age) {
return;
}
ctx.accesskit_node_builder(egui::Id::unique(("announcement", a.serial)), |node| {
// A label's text is its value: that is the name screen readers read (UI Automation's
// live-region event goes only to a node with a name).
node.set_role(Role::Label);
node.set_live(Live::Polite);
node.set_value(a.text.clone());
});
// A frame when it's due to go, so it leaves the tree even while nothing else happens.
ctx.request_repaint_after(std::time::Duration::from_secs_f64((SHOWN_MS - age) / 1000.0));
}
#[cfg(test)]
mod tests {
use egui::accesskit::{Live, Role};
use egui::{Key, Modifiers};
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::WordApp;
/// An announcement belongs to the window whose shortcut made it, as its status message does:
/// another window drawn within its three seconds doesn't put it in its own tree.
#[test]
fn an_announcement_stays_with_its_window() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.announcement = Some(super::Announcement { text: "Bold On".into(), serial: 0, at: 0.0 });
let mut other = crate::window_ui::WindowUi::new(app.session.document_id());
app.swap_window(&mut other);
assert!(app.announcement.is_none(), "the other window has nothing to say");
app.swap_window(&mut other);
assert_eq!(app.announcement.as_ref().map(|a| a.text.as_str()), Some("Bold On"), "it is back with its window");
}
fn harness(text: &str) -> egui_kittest::Harness<'static, WordApp> {
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text(text)), crate::Services::default());
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);
},
app,
);
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
crate::test_harness::frames(&mut h, 6);
assert!(h.state().canvas.focused(&ctx), "the page has the keyboard");
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 8) };
crate::test_harness::frames(&mut h, 2);
h
}
/// The live region's text and node (its id, written out), if one is in the tree. The text is
/// the label's value, which is its name to screen readers.
fn heard(h: &egui_kittest::Harness<'_, WordApp>) -> Option<(String, String)> {
let node = h.query_by(|n| n.role() == Role::Label && n.data().live() == Some(Live::Polite))?;
let n = node.accesskit_node();
assert!(n.label_comes_from_value(), "a label, named by its value");
Some((n.value().unwrap_or_default(), format!("{:?}", n.id())))
}
fn press(h: &mut egui_kittest::Harness<'_, WordApp>, m: Modifiers, key: Key) -> Option<(String, String)> {
h.key_press_modifiers(m, key);
crate::test_harness::frames(h, 2);
heard(h)
}
/// Ctrl+B, Ctrl+I, Ctrl+U and the alignment keys say what they did, as Word does ("Bold On",
/// then "Bold Off"), each time in a new live region, so the same words twice are heard twice.
#[test]
fn formatting_shortcuts_say_what_they_did() {
let mut h = harness("Lanterns glow");
assert_eq!(heard(&h), None, "nothing to say before a shortcut");
let (text, first) = press(&mut h, Modifiers::COMMAND, Key::B).expect("Ctrl+B is announced");
assert_eq!(text, "Bold On");
let (text, second) = press(&mut h, Modifiers::COMMAND, Key::B).expect("again");
assert_eq!(text, "Bold Off");
assert_ne!(first, second, "each announcement is a new live region");
for (key, said) in [
(Key::I, "Italic On"),
(Key::U, "Underline On"),
(Key::E, "Center On"),
(Key::E, "Center Off"),
(Key::R, "Align Right On"),
(Key::J, "Justify On"),
(Key::L, "Align Left On"),
] {
assert_eq!(press(&mut h, Modifiers::COMMAND, key).map(|(t, _)| t).as_deref(), Some(said), "{key:?}");
}
let (_, before) = heard(&h).expect("the last one");
let (text, again) = press(&mut h, Modifiers::COMMAND, Key::L).expect("Ctrl+L twice");
assert_eq!(text, "Align Left On", "left alignment stays");
assert_ne!(before, again, "the same words twice are a new live region, so they are heard again");
let grown = press(&mut h, Modifiers::COMMAND | Modifiers::SHIFT, Key::Period).map(|(t, _)| t).expect("Ctrl+Shift+. is announced");
assert!(grown.starts_with("Font ") && grown.ends_with(" pt"), "{grown}");
}
/// Only shortcuts are announced: a ribbon button says its own state, and a command that isn't
/// formatting says nothing. An announcement leaves the tree after three seconds.
#[test]
fn only_formatting_shortcuts_are_announced_for_a_while() {
let mut h = harness("Lanterns glow");
h.state_mut().run("format.bold", json!({})).unwrap();
crate::test_harness::frames(&mut h, 2);
assert_eq!(heard(&h), None, "a command run another way isn't announced");
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::Z), None, "Undo isn't announced");
assert!(press(&mut h, Modifiers::COMMAND, Key::I).is_some());
if let Some(a) = &mut h.state_mut().announcement {
a.at -= super::SHOWN_MS;
}
crate::test_harness::frames(&mut h, 2);
assert_eq!(heard(&h), None, "gone after three seconds");
}
/// A selection ending at the next paragraph's start (Shift+Down from a paragraph's start)
/// formats only the paragraph it covers, as in Word: that is the one the announcement says.
#[test]
fn alignment_is_said_for_the_paragraph_the_shortcut_formatted() {
let mut h = harness("Lanterns glow\nRivers run");
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(1, 0) };
crate::test_harness::frames(&mut h, 2);
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::E).map(|(t, _)| t).as_deref(), Some("Center On"));
let align =
|h: &egui_kittest::Harness<'_, WordApp>, i| h.state().session.doc.para_at(&wordcraft_doc::Pos::body(i, 0)).and_then(|p| p.props.align);
assert_eq!((align(&h, 0), align(&h, 1)), (Some(wordcraft_doc::Align::Center), None), "only the first paragraph is centred");
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::E).map(|(t, _)| t).as_deref(), Some("Center Off"));
}
/// The shortcut runs after the announcement's place in the frame, so the announcement goes in
/// the next frame's tree: a key asks egui for that frame itself.
#[test]
fn the_announcement_is_in_the_frame_after_the_key() {
let mut h = harness("Lanterns glow");
// The key down alone, in one frame (`key_press_modifiers` gives each event a frame).
h.input_mut().events.push(egui::Event::Key { key: Key::B, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
crate::test_harness::frame(&mut h);
assert_eq!(heard(&h), None, "the key's own frame built its tree before the shortcut ran");
assert!(h.ctx.has_requested_repaint(), "the key asked for another frame");
crate::test_harness::frame(&mut h);
assert_eq!(heard(&h).map(|(t, _)| t).as_deref(), Some("Bold On"));
}
/// Each formatting shortcut says its own words, read from the formatting after it ran: the
/// format's name and On or Off for Ctrl+B, I, U, = (Subscript) and Shift+= (Superscript), the
/// alignment's name for Ctrl+E, R, J and L, and the size the selection now has for
/// Ctrl+Shift+. and , (Grow and Shrink Font) and Ctrl+] and [ (by 1 pt). A selection of mixed
/// sizes has no one size to say, so nothing is said.
#[test]
fn every_formatting_shortcut_says_its_own_words() {
let mut h = harness("Lanterns glow");
h.state_mut().run("format.size", json!({"size": 12})).unwrap();
crate::test_harness::frames(&mut h, 2);
let (cmd, shift) = (Modifiers::COMMAND, Modifiers::COMMAND | Modifiers::SHIFT);
for (m, key, said) in [
(cmd, Key::B, "Bold On"),
(cmd, Key::B, "Bold Off"),
(cmd, Key::I, "Italic On"),
(cmd, Key::I, "Italic Off"),
(cmd, Key::U, "Underline On"),
(cmd, Key::U, "Underline Off"),
(cmd, Key::Equals, "Subscript On"),
(cmd, Key::Equals, "Subscript Off"),
(shift, Key::Equals, "Superscript On"),
(shift, Key::Equals, "Superscript Off"),
(cmd, Key::E, "Center On"),
(cmd, Key::R, "Align Right On"),
(cmd, Key::J, "Justify On"),
(cmd, Key::L, "Align Left On"),
(shift, Key::Period, "Font 14 pt"),
(shift, Key::Comma, "Font 12 pt"),
(cmd, Key::CloseBracket, "Font 13 pt"),
(cmd, Key::OpenBracket, "Font 12 pt"),
] {
assert_eq!(press(&mut h, m, key).map(|(t, _)| t).as_deref(), Some(said), "{m:?} {key:?}");
}
let mut h = harness("Lanterns glow");
let sizes = [(0, 8, 12.0), (8, 13, 16.0)];
for (from, to, size) in sizes {
h.state_mut().session.sel =
wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, from), focus: wordcraft_doc::Pos::body(0, to) };
h.state_mut().run("format.size", json!({"size": size})).unwrap();
}
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 13) };
crate::test_harness::frames(&mut h, 2);
assert_eq!(press(&mut h, shift, Key::Period), None, "mixed sizes: nothing to say");
assert!(h.state().announcement.is_none(), "and nothing waits to be said");
}
/// The words are looked up in the interface catalogs, so each language says its own.
#[test]
fn the_words_go_through_the_interface_catalogs() {
let mut h = harness("Lanterns glow");
// These delimiters mark translations in the synthetic locale and are absent from some test fonts.
h.ctx.add_glyph_rasterizer(egui::GlyphRasterizer::new("wordcraft::announce::pseudo_markers", |request| {
matches!(request.cluster, "⟦" | "⟧").then(|| egui::RasterizedGlyph {
bitmap: egui::GlyphBitmap {
image: egui::ColorImage::new([1, 1], vec![egui::Color32::WHITE]),
offset_px: egui::Vec2::ZERO,
is_color: false,
},
advance_px: request.font_size_px.max(1.0),
})
}));
h.state_mut().ui.language = "pseudo".into();
let said = press(&mut h, Modifiers::COMMAND, Key::B).map(|(t, _)| t).unwrap_or_default();
crate::i18n::apply_language(crate::i18n::Lang::EN);
assert!(
said.split_whitespace().all(|word| word.starts_with('⟦') && word.ends_with('⟧')) && said.contains('⟦'),
"every word is marked: {said:?}"
);
}
/// Ten presses in a burst, one per frame or all in one frame (a held key, or keys typed
/// faster than frames), leave one announcement at a time, the latest, in one live region:
/// each replaces the last (`WordApp::announcement` holds one), so nothing queues up.
#[test]
fn a_burst_of_ten_presses_leaves_one_announcement_the_latest() {
let live =
|h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by(|n| n.role() == Role::Label && n.data().live() == Some(Live::Polite)).count();
let mut h = harness("Lanterns glow");
let mut nodes = std::collections::HashSet::new();
for i in 0..10 {
let (text, node) = press(&mut h, Modifiers::COMMAND, Key::B).expect("each press is announced");
assert_eq!(text, if i % 2 == 0 { "Bold On" } else { "Bold Off" }, "press {i}");
assert_eq!(live(&h), 1, "press {i}: one live region in the tree");
nodes.insert(node);
}
assert_eq!(nodes.len(), 10, "each press a new node, so each is heard");
let mut h = harness("Lanterns glow");
let key = |pressed| egui::Event::Key { key: Key::B, physical_key: None, pressed, repeat: false, modifiers: Modifiers::COMMAND };
for _ in 0..10 {
h.input_mut().events.extend([key(true), key(false)]);
}
crate::test_harness::frames(&mut h, 2);
let bold = wordcraft_engine::cmd::format::state(&h.state().session).get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(false), "ten Ctrl+B in one frame: bold on and off five times");
assert_eq!(live(&h), 1, "one live region in the tree");
assert_eq!(heard(&h).map(|(t, _)| t).as_deref(), Some("Bold Off"), "the latest is said");
}
/// The words go through the interface's catalogs (`tl!`), as the ribbon's labels do: a
/// translated interface says them in its language. Checked with a fixture language and, when
/// the craft-i18n catalogs are embedded (`CRAFT_I18N_DIR`), Turkish and Simplified Chinese.
#[test]
fn the_announcements_are_in_the_interface_language() {
let said = |app: &mut WordApp, id: &str| {
app.run(id, json!({})).unwrap();
super::describe(app, id)
};
let app = || {
let mut app =
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns glow")), crate::Services::default());
app.session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 8) };
app.run("format.size", json!({"size": 12})).unwrap();
app
};
let mut a = app();
crate::i18n::apply_language(crate::i18n::fixture_lang(
"x-fixture",
"\tBold\tBold-FX\n\tOn\tOn-FX\n\tOff\tOff-FX\n\tCenter\tCenter-FX\n\tFont\tFont-FX\n\tpt\tpt-FX\n",
));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some("Bold-FX On-FX"));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some("Bold-FX Off-FX"));
assert_eq!(said(&mut a, "para.alignCenter").as_deref(), Some("Center-FX On-FX"));
assert_eq!(said(&mut a, "format.growFont").as_deref(), Some("Font-FX 14 pt-FX"));
// The catalogs' own words: craft-i18n's `common.tsv` and `wordcraft.tsv` rows.
if crate::i18n::catalogs_embedded() {
for (code, bold, center, font) in
[("tr", "Kalın Açık", "Ortala Açık", "Yazı Tipi 14 pt"), ("zh-hans", "加粗 开", "居中 开", "字体 14 磅")]
{
let mut a = app();
crate::i18n::apply_language(crate::i18n::Lang::from_code(code).expect("an interface language"));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some(bold), "{code}");
assert_eq!(said(&mut a, "para.alignCenter").as_deref(), Some(center), "{code}");
assert_eq!(said(&mut a, "format.growFont").as_deref(), Some(font), "{code}");
}
}
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
}
+2
View File
@@ -53,6 +53,7 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
@@ -137,6 +138,7 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
+4 -1
View File
@@ -123,7 +123,7 @@ impl WordApp {
for (id, label) in GATED_UI_COMMANDS {
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
}
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
// plain keys type, and every modified chord is offered to the keymap first.
match AppCatalog::new(defs, generation) {
Ok(catalog) => {
@@ -204,6 +204,9 @@ impl WordApp {
self.edits = host;
}
let result = if fired.source == FireSource::Automation { self.execute(id, params) } else { self.run(id, params) };
if from_key && result.is_ok() {
crate::announce::after_shortcut(self, id, ctx);
}
if let Err(error) = result {
log::debug!("command {id}: {error}");
}
+1
View File
@@ -75,6 +75,7 @@ impl WordApp {
/// handed in as values and read back after, so no body reads a stale copy. Returns the
/// shell's regions; a window another command swapped in mid-draw returns none.
pub(super) fn paint_window(&mut self, ui: &mut egui::Ui) -> ShellRegions {
crate::announce::expose(self, ui.ctx());
let window = self.windows.shown();
let stale = |app: &WordApp| app.windows.shown() != window;
let mode = self.screen_mode();
+3
View File
@@ -101,6 +101,7 @@ pub use dialogs::dialogs_ribbon;
pub use dialogs::dialogs_smart_art;
pub use file_dialogs::open_filters;
mod announce;
mod app;
mod services;
mod state;
@@ -416,6 +417,8 @@ pub struct WordApp {
pub spelling_review: Option<proofing_pane::SpellingForm>,
/// The status bar's message, until its `until` passes.
pub(crate) status: Option<Status>,
/// The latest formatting shortcut announcement for the active window.
pub(crate) announcement: Option<announce::Announcement>,
pub previews: previews::Previews,
/// Media key of the picture a pending Change Picture replaces (#147).
pub change_picture_target: Option<String>,
+5
View File
@@ -22,6 +22,8 @@ pub(crate) struct WindowUi {
pub(crate) restrict: crate::restrict_pane::RestrictPane,
pub(crate) spelling_review: Option<crate::proofing_pane::SpellingForm>,
pub(crate) status: Option<Status>,
/// Announcement belonging to this document window.
pub(crate) announcement: Option<crate::announce::Announcement>,
pub(crate) previews: previews::Previews,
pub(crate) change_picture_target: Option<String>,
pub(crate) recipient_list_pending: bool,
@@ -74,6 +76,7 @@ impl WindowUi {
restrict: Default::default(),
spelling_review: None,
status: None,
announcement: None,
previews: Default::default(),
change_picture_target: None,
recipient_list_pending: false,
@@ -184,6 +187,7 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
@@ -281,6 +285,7 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
+2 -1
View File
File diff suppressed because one or more lines are too long
+3 -2
View File
File diff suppressed because one or more lines are too long