diff --git a/crates/i18n/src/fold.rs b/crates/i18n/src/fold.rs index 213a90969..a25397ce3 100644 --- a/crates/i18n/src/fold.rs +++ b/crates/i18n/src/fold.rs @@ -31,7 +31,6 @@ use crate::scripts::{Direction, direction}; pub struct Folder { turkic: bool, accents: bool, - #[allow(dead_code)] // P3(pdf-chrome-w1): CH-C3 rtl: bool, } @@ -58,6 +57,12 @@ impl Folder { self.turkic } + /// Whether the locale writes right to left, by its main script ([`direction`]); a locale with no script data is + /// left to right. + pub(crate) fn rtl(&self) -> bool { + self.rtl + } + /// `s` folded, with the map back to `s`. pub fn fold(&self, s: &str) -> Folded { let nfkd = DecomposingNormalizerBorrowed::new_nfkd(); diff --git a/crates/i18n/src/matcher.rs b/crates/i18n/src/matcher.rs index 7b15dccfd..7d670a6dc 100644 --- a/crates/i18n/src/matcher.rs +++ b/crates/i18n/src/matcher.rs @@ -27,7 +27,8 @@ pub enum Rank { pub struct Match { /// How well it matches. pub rank: Rank, - /// Every occurrence of the query, as byte ranges of the text, in order. + /// Every occurrence of the query, as byte ranges of the text, in order; for `AllWords`, the first occurrence of + /// each word, sorted by start. pub ranges: Vec>, } @@ -36,12 +37,22 @@ pub struct Match { pub struct Matcher { folder: Folder, query: Folded, + /// The folded words of a query of two or more words in a right-to-left locale, where a line typed or pasted + /// across directions often holds its words in another order; empty otherwise, so a left-to-right ranking is + /// the whole-run one. + words: Vec, } impl Matcher { /// A matcher for `query` with surrounding space ignored. An empty query matches every text. pub fn new(folder: &Folder, query: &str) -> Matcher { - Matcher { folder: *folder, query: folder.fold(query.trim()) } + let query = query.trim(); + let words: Vec = if folder.rtl() { + query.split_whitespace().map(|word| folder.fold(word)).filter(|word| !word.as_str().is_empty()).collect() + } else { + Vec::new() + }; + Matcher { folder: *folder, query: folder.fold(query), words: if words.len() > 1 { words } else { Vec::new() } } } /// Whether the query is empty. @@ -54,8 +65,11 @@ impl Matcher { if self.is_empty() { return Some(Match { rank: Rank::Whole, ranges: Vec::new() }); } - let ranges: Vec> = self.folder.fold(text).matches(&self.query).collect(); - let first = ranges.first()?; + let folded = self.folder.fold(text); + let ranges: Vec> = folded.matches(&self.query).collect(); + let Some(first) = ranges.first().cloned() else { + return self.all_words(&folded); + }; let rank = if first.start == 0 && first.end == text.len() { Rank::Whole } else if first.start == 0 { @@ -67,4 +81,15 @@ impl Matcher { }; Some(Match { rank, ranges }) } + + /// `AllWords` when every word of the query occurs in `folded`, with each word's first occurrence as source ranges. + fn all_words(&self, folded: &Folded) -> Option { + if self.words.is_empty() { + return None; + } + let mut ranges: Vec> = self.words.iter().map(|word| folded.matches(word).next()).collect::>()?; + ranges.sort_by_key(|range| range.start); + ranges.dedup(); + Some(Match { rank: Rank::AllWords, ranges }) + } } diff --git a/crates/i18n/src/region.rs b/crates/i18n/src/region.rs index d0fa03d5e..58320b109 100644 --- a/crates/i18n/src/region.rs +++ b/crates/i18n/src/region.rs @@ -388,3 +388,47 @@ fn read_system() -> Region { fn read_system() -> Region { Region::from_tag(&sys_locale::get_locale().unwrap_or_default()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))] + #[test] + fn each_locale_category_decides_its_own_part_and_lc_all_all_of_them() { + let env = |pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| (*v).to_owned()); + fn none() -> Option { + None + } + // `LC_ALL` decides every part, `C` included. + let all = from_posix(env(&[("LC_ALL", "de_DE.UTF-8"), ("LC_PAPER", "en_US"), ("LC_TIME", "en_US"), ("LANG", "en_US")]), none); + assert_eq!(all, Region::from_tag("de_DE.UTF-8")); + assert_eq!(from_posix(env(&[("LC_ALL", "C"), ("LANG", "de_DE")]), none), Region::from_tag("C")); + // An empty `LC_ALL` is unset: each category decides its own part. + let split = from_posix( + env(&[ + ("LC_ALL", ""), + ("LC_NUMERIC", "pl_PL"), + ("LC_TIME", "en_GB"), + ("LC_MEASUREMENT", "en_US"), + ("LC_PAPER", "en_US"), + ("LANG", "de_DE"), + ]), + none, + ); + assert_eq!( + (split.numbers.as_str(), split.time.as_str(), split.measurement, split.paper), + ("pl-PL", "en-GB", Measurement::Us, Paper::Letter) + ); + // `LANG` fills every category not set. + let lang = from_posix(env(&[("LC_PAPER", "en_US"), ("LANG", "de_DE")]), none); + assert_eq!( + (lang.numbers.as_str(), lang.time.as_str(), lang.measurement, lang.paper), + ("de-DE", "de-DE", Measurement::Metric, Paper::Letter) + ); + // `LANG` set to `C`, or unset, gives way to the platform's locale. + let platform = from_posix(env(&[("LANG", "C.UTF-8")]), || Some("en-CA".to_owned())); + assert_eq!((platform.numbers.as_str(), platform.measurement, platform.paper), ("en-CA", Measurement::Metric, Paper::Letter)); + assert_eq!(from_posix(env(&[]), none), Region::default()); + } +} diff --git a/crates/i18n/src/tests.rs b/crates/i18n/src/tests.rs index d4dc9df01..e3fdfeb7e 100644 --- a/crates/i18n/src/tests.rs +++ b/crates/i18n/src/tests.rs @@ -1,6 +1,7 @@ //! Tests for the i18n facade. use super::*; +use crate::matcher::{Matcher, Rank}; use unicode_bidi::{BidiClass, bidi_class}; impl I18n { @@ -135,3 +136,95 @@ fn lookup_parses_only_what_it_reaches() { assert_eq!(i.t(Lang::PSEUDO, "Undo"), "⟦Undo⟧"); assert_eq!(i.parsed(), ["pt", "pt-br"]); } + +#[test] +fn words_in_any_order_match_after_a_whole_run() { + // "Delete page" in Arabic and Hebrew, queried with its two words the other way round. + for (locale, text, reversed, missing) in [("ar", "حذف صفحة", "صفحة حذف", "صفحة نسخ"), ("he", "מחק עמוד", "עמוד מחק", "עמוד העתק")] { + let folder = Folder::new(locale); + let matcher = Matcher::new(&folder, reversed); + let found = matcher.score(text).map(|found| (found.rank, found.ranges)); + assert_eq!(found, Some((Rank::AllWords, vec![0..6, 7..15])), "{locale}: each word's first occurrence, in text order"); + let whole = matcher.score(reversed).map(|found| found.rank); + assert_eq!(whole, Some(Rank::Whole), "{locale}"); + assert!(Matcher::new(&folder, text).score(&format!("x {text}")).is_some_and(|run| run.rank < Rank::AllWords), "{locale}: a whole run ranks first"); + assert_eq!(Matcher::new(&folder, missing).score(text), None, "{locale}: every word must occur"); + assert_eq!(Matcher::new(&Folder::new("en"), reversed).score(text), None, "{locale}: a left-to-right folder keeps the whole run"); + } +} + +#[test] +fn lookups_fall_back_to_the_english_row_then_the_source_by_context_and_id() { + let i = all(E).0; + let fr = lang(&i, "fr"); + // The app's row comes before the shared one. + assert_eq!(i.t(fr, "Save"), "Sauvegarder"); + assert_eq!(i.tc(fr, "menu", "Open"), "Ouvrir le menu"); + assert_eq!(i.tc(fr, "no such context", "Open"), "Ouvrir", "a context with no row takes the plain row"); + assert_eq!(i.get(fr, "no such context", "Open"), None, "get takes no other row"); + assert_eq!(i.tid(fr, "file.save", "Save"), "Enregistrer le fichier"); + assert_eq!(i.tid(fr, "no.such.id", "Open"), "Ouvrir", "an id with no row takes the row of its English label"); + assert_eq!(i.tid(fr, "no.such.id", "No such label"), "No such label"); + assert_eq!(i.t(fr, "no such label"), "no such label"); + // A regional locale falls back to its language, and only then to the source. + let pt_br = lang(&i, "pt-br"); + assert_eq!(i.t(pt_br, "Save"), "Salvar"); + assert_eq!(i.t(pt_br, "Undo"), "Desfazer"); + assert_eq!(i.t(pt_br, "Open"), "Open"); + assert_eq!(i.t(Lang::EN, "Save"), "Save"); +} + +#[test] +fn catalog_problems_are_reported_and_escapes_kept() { + static C: &Embedded = &[( + "ja", + "# c\r\n\tLine\\nTab\\tPath\\\\\tOther\\nTab\\tPath\\\\\r\nweight\tLight\tThin\r\ntheme\tLight\tPale\r\nno tabs here\n\tonly\n\ta\tb\tc\textra\n\t\tempty source\n\tOpen…\tOpen\n\tok\tはい\n\tok\tまた\n\tBad\\q\tx\n", + "", + )]; + let (i, problems) = all(C); + assert!(problems.is_empty(), "rows are checked when the locale is first read: {problems:?}"); + let ja = lang(&i, "ja"); + assert_eq!(i.t(ja, "Line\nTab\tPath\\"), "Other\nTab\tPath\\"); + assert_eq!(i.tc(ja, "weight", "Light"), "Thin"); + assert_eq!(i.tc(ja, "theme", "Light"), "Pale"); + assert_eq!(i.t(ja, "ok"), "はい", "of a row defined twice, the first is kept"); + assert_eq!(i.t(ja, "Open…"), "Open…", "a row that drops the ellipsis is skipped"); + let found = i.check_all(); + let lines: Vec<&str> = found.iter().filter_map(|p| p.strip_prefix("ja/common: line ")).filter_map(|p| p.split(':').next()).collect(); + assert_eq!(lines, ["5", "6", "7", "8", "9", "11", "12"], "{found:?}"); +} + +#[test] +fn plural_forms_follow_cldr_for_every_offered_language() { + static C: &Embedded = &[ + ("fr", "@plural\t{n} file|{n} files\tun {n}|autre {n}\n", ""), + ("ru", "@plural\t{n} file|{n} files\tone {n}|few {n}|many {n}\n", ""), + ("ja", "@plural\t{n} file|{n} files\tother {n}\n", ""), + ("ar", "@plural\t{n} file|{n} files\tzero {n}|one {n}|two {n}|few {n}|many {n}|other {n}\n", ""), + ("pl", "@plural\t{n} file|{n} files\tone {n}|few {n}|many {n}\n", ""), + ("pt", "@plural\t{n} file|{n} files\tum {n}|outro {n}\n", ""), + ("pt-br", "@plural\t{n} file|{n} files\tum {n}|outro {n}\n", ""), + ("de", "@plural\t{n} file|{n} files\teins {n}|zwei {n}|drei {n}\n", ""), + ]; + let i = all(C).0; + let counted = |code: &str, n: u64| i.trn_plain(lang(&i, code), n, "{n} file", "{n} files"); + for (code, expected) in [ + ("fr", &[(0, "un 0"), (1, "un 1"), (2, "autre 2"), (1_000_000, "autre 1000000")][..]), + ("ru", &[(1, "one 1"), (2, "few 2"), (5, "many 5"), (11, "many 11"), (21, "one 21"), (22, "few 22"), (112, "many 112")]), + ("ja", &[(1, "other 1"), (2, "other 2")]), + ("ar", &[(0, "zero 0"), (1, "one 1"), (2, "two 2"), (3, "few 3"), (11, "many 11"), (100, "other 100"), (103, "few 103")]), + ("pl", &[(1, "one 1"), (2, "few 2"), (5, "many 5"), (12, "many 12"), (22, "few 22")]), + // CLDR's `pt` is Brazilian, where 0 is singular; Portugal's is not. + ("pt", &[(0, "outro 0"), (1, "um 1"), (2, "outro 2")]), + ("pt-br", &[(0, "um 0"), (1, "um 1"), (2, "outro 2")]), + // German has two forms: the three-form row is skipped and the English shows. + ("de", &[(1, "1 file"), (2, "2 files")]), + ] { + for &(n, want) in expected { + assert_eq!(counted(code, n), want, "{code}: {n}"); + } + } + let found = i.check_all(); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].starts_with("de/common: line 1: expected 2"), "{found:?}"); +} diff --git a/crates/ui-contract/src/contract/tooltip.rs b/crates/ui-contract/src/contract/tooltip.rs index c7f4f37a1..e90760b2f 100644 --- a/crates/ui-contract/src/contract/tooltip.rs +++ b/crates/ui-contract/src/contract/tooltip.rs @@ -71,29 +71,33 @@ fn spec_text(env: &crate::runtime::env::EnvView<'_>, spec: &TooltipSpec, enabled } /// The text the component's own tooltip shows, or `None` when it has none: its validity message when no container -/// shows it (`message`); else the tooltip's text, or its disabled text while disabled, with the bound command's -/// chord; else the full label when the paint cut it, or its own label when the component declares it paints no -/// label (`shows_label`). +/// shows it (`message`); else a base text with the bound command's chord, and the bound command's hint on a line +/// after it; else, with no base text, the hint alone with the chord. The base is the tooltip's text, or its disabled +/// text while disabled; else the full label when the paint cut it, or its own label when the component declares it +/// paints no label (`shows_label`). fn text_of(core: &super::CxCore<'_>, shows_label: bool, message: Option) -> Option { if message.is_some() { return message; } let base = match core.resolved.tooltip.map(|tooltip| tooltip.spec()) { - Some(spec) => spec_text(&core.env, spec, core.resolved.enabled), + Some(spec) => Some(spec_text(&core.env, spec, core.resolved.enabled)), None => { let paint = core.paint.borrow(); - match paint.elided.clone() { - Some(full) => full, - None if !shows_label && !core.resolved.label.is_empty() => core.resolved.label.to_owned(), - None => return None, - } + paint.elided.clone().or_else(|| (!shows_label && !core.resolved.label.is_empty()).then(|| core.resolved.label.to_owned())) } }; + let command = core.command.as_deref(); let platform = crate::runtime::windows::os_of(&core.ctx); - Some(match core.command.as_deref().and_then(|command| command.chord.as_ref()) { - Some(chord) => with_chord(&base, chord, platform), - None => base, - }) + let chorded = |text: &str| match command.and_then(|command| command.chord.as_ref()) { + Some(chord) => with_chord(text, chord, platform), + None => text.to_owned(), + }; + match (base, command.and_then(|command| command.hint.as_deref())) { + (Some(base), Some(hint)) => Some(format!("{}\n{hint}", chorded(&base))), + (Some(base), None) => Some(chorded(&base)), + (None, Some(hint)) => Some(chorded(hint)), + (None, None) => None, + } } /// A tooltip's text followed by the chord that does the same, as every tooltip shows a key: "Hide Layers (⌘,)". diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 5f5f40eee..65207fb9b 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -80,6 +80,8 @@ pub(crate) struct Board { queue: Vec, /// App-scope commands for the next `FrameOutput`. out: Vec, + /// App-scope commands a key pressed while only their own state disabled them, for the next `FrameOutput`. + declined: Vec, /// The commands instances took since the last `FrameOutput`, in order. delivered: Vec, instances: Vec, @@ -394,13 +396,15 @@ impl Board { Some(_) => reached, }; let live = app || instance.is_some_and(|id| self.is_live(ctx, id)); + let refused = !(modal && live && !matches!(declaring, Some(Declaration::Focused { inactive: true }))); let chord = self.keymap.as_ref().and_then(|cache| cache.keymap.shown_chord(command)); let resolved = ResolvedCommand { label: state.and_then(|s| s.title_ref().cloned()).unwrap_or_else(|| Arc::from(def.map_or(command.id.as_str(), |def| def.label.as_str()))), - catalog_label: Default::default(), // P3(pdf-chrome-w1): CH-C25 - icon: def.and_then(|def| def.icon.clone()), + catalog_label: def.map(|def| Arc::from(def.label.as_str())), + icon: state.and_then(|s| s.icon_ref().cloned()).or_else(|| def.and_then(|def| def.icon.clone())), chord, - enabled: flags.enabled && modal && live && !matches!(declaring, Some(Declaration::Focused { inactive: true })), + enabled: flags.enabled && !refused, + refused, checked: flags.checked, marked: state.is_some_and(CommandState::is_marked), hint: state.and_then(|s| s.hint_ref().cloned()), @@ -677,10 +681,8 @@ pub(crate) fn take_fired(ctx: &Context) -> Vec { /// The app-scope commands a key press fired while only the app's own command state disabled them, since the last /// call. -#[allow(dead_code)] // P3(pdf-chrome-w1): CH-C2 pub(crate) fn take_declined(ctx: &Context) -> Vec { - let _ = ctx; - todo!("CH-C2") + with(ctx, |board| std::mem::take(&mut board.declined)) } /// The commands instances took since the last call. @@ -814,6 +816,7 @@ fn resolve_in( } if gate.is_some_and(|gate| !gate.allows(command)) { resolved.enabled = false; + resolved.refused = true; } (resolved, key) } @@ -1249,6 +1252,21 @@ pub(crate) fn begin(ctx: &Context) { let (app, instance) = with(ctx, |board| board.target_of(ctx, &hit.command, &board.here)); let (resolved, _) = resolve_in(ctx, &hit.command, instance, Reach::Focus, None); if !resolved.enabled { + // The key stays taken. When the app's own state of an app-scope command is all that disables it, + // the app hears of the press so it can say why nothing ran; a refusal by the gate, the modal rule + // or a declaring instance's state is not the app's to explain. + if app && resolved.instance.is_none() && !resolved.refused { + let declined = Fired { + command: hit.command, + target: None, + source: FireSource::Key, + phase: FirePhase::Press, + cycle: hit.cycle.len() > 1, + alt_variant: hit.alt_variant, + time, + }; + with(ctx, |board| board.declined.push(declined)); + } continue; } // An app-scope command a modal layer's instance declares is delivered to that instance. diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index dd422ceb5..e3e665570 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -25,7 +25,8 @@ pub use board::keymap_builds; pub(crate) use board::publish as publish_for; pub(crate) use board::take as take_for_instance; pub(crate) use board::{ - begin, binds_scoped, edit_chords, end, install, note_focus, platform, register_instance, set_input, take_delivered, take_fired, window_shortcuts, + begin, binds_scoped, edit_chords, end, install, note_focus, platform, register_instance, set_input, take_declined, take_delivered, take_fired, + window_shortcuts, }; #[doc(hidden)] pub use board::{bound_around, take_around}; @@ -224,11 +225,10 @@ impl CommandState { } /// An icon for this frame in place of the command's own, by catalogue name or registered app set name. - #[allow(dead_code)] // P3(pdf-chrome-w1): CM-C31 #[must_use] - pub fn icon(self, icon: impl Into>) -> Self { - let _ = icon; - todo!("CM-C31") + pub fn icon(mut self, icon: impl Into>) -> Self { + self.icon = Some(icon.into()); + self } /// The accessible description and second tooltip line. @@ -255,7 +255,6 @@ impl CommandState { self.title.as_ref() } - #[allow(dead_code)] // P3(pdf-chrome-w1): CM-C31 pub(crate) fn icon_ref(&self) -> Option<&Cow<'static, str>> { self.icon.as_ref() } @@ -274,7 +273,7 @@ pub struct ResolvedCommand { /// The command's catalogue label (the registry's), whatever title the state sets; `None` for a command the /// registry does not define. pub catalog_label: Option>, - /// The icon name. + /// The icon name: the state's icon, else the command's own. pub icon: Option>, /// The chord surfaces show: the first single-press binding that runs the command ([`chord`]). pub chord: Option, @@ -289,6 +288,10 @@ pub struct ResolvedCommand { /// What the command is. pub kind: CommandKind, pub(crate) command: CommandRef, + /// Something besides the command's own state refuses it: the gate, the modal rule, the instance's liveness or a + /// focused component whose edit does nothing now. A key whose app-scope command its state alone disables is + /// declined (`FrameOutput::declined`); a refused one is not. + pub(crate) refused: bool, #[doc(hidden)] pub instance: Option, } diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 4b62a8444..15980e0a8 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -364,6 +364,7 @@ pub fn take_output(ctx: &Context) -> FrameOutput { let mut output = pass_state::with::(ctx, |state| std::mem::take(&mut state.output)); output.fired = commands::take_fired(ctx); output.delivered = commands::take_delivered(ctx); + output.declined = commands::take_declined(ctx); // The menu, palette and automation fires of the chrome and nav commands reach the app as ordinary fires with no // window: the focused window's shell takes a toggle, and its focus service a pane move, in the next pass. A key fire // already acted in the key stage. diff --git a/crates/ui-shell/tests/it/commands/board.rs b/crates/ui-shell/tests/it/commands/board.rs index daf673588..7650bf305 100644 --- a/crates/ui-shell/tests/it/commands/board.rs +++ b/crates/ui-shell/tests/it/commands/board.rs @@ -1,7 +1,7 @@ use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Tap}; use craft_ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft_ui::runtime::commands::{ - CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, fire, resolve, + CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FirePhase, FireSource, Fired, fire, resolve, }; use craft_ui::runtime::focus::{FocusTarget, request}; use craft_ui::runtime::frame::take_output; @@ -103,6 +103,43 @@ fn the_gate_may_resolve_commands() { assert_eq!(ids(&take_output(&frames.ctx).fired), ["trial.save"]); } +/// 11.3: a key whose app-scope command only the app's own state disables is declined, in order, once, though a discard +/// pass reruns its frame; one the gate also refuses is not, and none of them fires. +#[trial] +fn a_disabled_commands_key_is_declined_and_a_gated_one_is_not() { + let mut frames = Frames::new(); + frames.commands( + CommandInput::new() + .state(AppCommand::Play, CommandState::new().enabled(false)) + .state(AppCommand::Save, CommandState::new().enabled(false)) + .state(AppCommand::Jump, CommandState::new().enabled(false)) + .gate(CommandGate::new(|command: &CommandRef| *command != CommandRef::from(AppCommand::Jump))), + ); + let mut show = |ui: &mut Ui| { + Tap::new().id_salt("go").command(AppCommand::Go).show(ui); + }; + frames.idle(2, &mut show); + let keys = vec![ + key_press(Key::F8, Modifiers::NONE), + key_press(Key::J, Modifiers::COMMAND | Modifiers::ALT), + key_press(Key::K, Modifiers::COMMAND), + ]; + let mut first = true; + frames.frame(keys, |ui| { + show(ui); + if std::mem::take(&mut first) { + ui.ctx().request_discard("declined trial"); + } + }); + frames.idle(1, &mut show); + let output = take_output(&frames.ctx); + assert_eq!(ids(&output.declined), ["trial.play", "trial.save"], "the state-disabled keys, in order, and not the gated one"); + assert!(output.declined.iter().all(|declined| declined.source == FireSource::Key && declined.phase == FirePhase::Press)); + assert!(output.fired.is_empty(), "a declined key fires nothing"); + frames.idle(2, &mut show); + assert!(take_output(&frames.ctx).declined.is_empty(), "nothing is declined again in later frames"); +} + /// 11.3: a scoped entry waits for its instance and is dropped when the instance stops being live. #[trial] fn an_untaken_scoped_entry_is_dropped_with_its_instance() { diff --git a/crates/ui-widgets/tests/it/commands/mod.rs b/crates/ui-widgets/tests/it/commands/mod.rs index c3bed565b..36b0d9e24 100644 --- a/crates/ui-widgets/tests/it/commands/mod.rs +++ b/crates/ui-widgets/tests/it/commands/mod.rs @@ -1,3 +1,60 @@ //! The command board: registry, state, the gate, firing and scoped delivery. mod panel_scope; + +use craft_behavior::IconId; +use craft_ui::buttons::{Button, IconButton}; +use craft_ui::contract::tooltip::DELAY; +use craft_ui::contract::{CommandSet, Props as _, Show as _}; +use craft_ui::runtime::commands::CommandState; +use craft_ui::testing::pointer::moved; +use craft_ui::testing::{Fixture, trial}; +use egui::{Rect, Ui}; +use std::cell::Cell; +use std::rc::Rc; + +/// App-scope commands whose state carries a hint. +#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] +#[command(prefix = "hint")] +#[non_exhaustive] +pub enum HintCommand { + #[command(label = "Save", default = "Cmd+Shift+F9")] + Save, + #[command(label = "Open", default = "Cmd+Shift+F10")] + Open, +} + +/// The text the pointer's rest on what `show` shows (it returns its rect) adds after the tooltip delay, its runs +/// joined by line, with `command` given `state`. +fn tooltip_of(command: HintCommand, state: CommandState, show: impl Fn(&mut Ui) -> Rect + 'static) -> String { + let at = Rc::new(Cell::new(Rect::NOTHING)); + let seen = Rc::clone(&at); + let mut fixture = Fixture::new(move |ui| seen.set(show(ui))); + fixture.command_state(command, state); + fixture.settle(); + let before: Vec = fixture.texts().iter().map(|run| run.text.clone()).collect(); + fixture.frame(vec![moved(at.get().center())]); + fixture.advance(DELAY); + fixture.settle(); + let added: Vec = fixture.texts().iter().map(|run| run.text.clone()).filter(|text| !before.contains(text)).collect(); + added.join("\n") +} + +/// L-72: a bound command's hint is the tooltip's second line, under the label and its chord, enabled or not; with no +/// other tooltip text (the label shows whole), the hint is the tooltip, with the chord after it. +#[trial] +fn a_bound_commands_hint_is_the_tooltips_second_line() { + const NEEDS: &str = "Needs an open document"; + for enabled in [true, false] { + let text = tooltip_of(HintCommand::Save, CommandState::new().enabled(enabled).hint(NEEDS), |ui| { + IconButton::new(IconId::new("play")).label("Save").command(HintCommand::Save).show(ui).rect + }); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 2, "enabled {enabled}: {text:?}"); + assert!(lines[0].starts_with("Save (") && lines[0].ends_with(')'), "enabled {enabled}: the label and its chord first, {text:?}"); + assert_eq!(lines[1], NEEDS, "enabled {enabled}: the hint after the label"); + } + const OPENS: &str = "Opens a document from disk"; + let text = tooltip_of(HintCommand::Open, CommandState::new().hint(OPENS), |ui| Button::new("Open").command(HintCommand::Open).show(ui).rect); + assert!(text.starts_with(&format!("{OPENS} (")) && text.ends_with(')') && !text.contains('\n'), "the hint alone, with the chord: {text:?}"); +}