top-w2: net change of 6 commits

- top-w2: written by an agent
- top-w2: finished by an agent
- top-w2: review fixes (review-1)
- top-w2: the menu-letter step of the shortcut trial types its letter as text, which mnemonics read (top run round)
- top-w2: typed letters in a menu go to the container of the focused row's level, with a trial for a title-click menu (top run round)
- top-w2: a menu row's pick walks out from the menu it runs in, with a trial for Cut from the Help search field's edit menu (top run round)
This commit is contained in:
aiongg
2026-11-15 04:46:09 +00:00
parent de5d6b3199
commit 46bd564b75
22 changed files with 842 additions and 70 deletions
+21
View File
@@ -352,4 +352,25 @@ mod tests {
}
}
}
#[test]
fn turkish_and_azerbaijani_keep_the_dotted_and_dotless_i_pairs_apart() {
assert!(!Folder::new("en").turkic());
for locale in ["tr", "az", "tr-TR", "AZ_az"] {
let f = Folder::new(locale).keep_accents();
assert!(f.turkic(), "{locale}");
// Dotless: `I` is the capital of `ı`, not of `i`.
assert_eq!(f.key("I"), f.key("ı"), "{locale}");
assert_ne!(f.key("I"), f.key("i"), "{locale}");
assert!(f.contains("IRMAK", "ırmak"), "{locale}");
assert!(!f.contains("IRMAK", "irmak"), "{locale}");
// Dotted: `İ`, precomposed or as `I` and a combining dot, is the capital of `i`.
for dotted in ["İ", "I\u{307}"] {
assert_eq!(f.key(dotted), f.key("i"), "{locale} {dotted:?}");
assert_ne!(f.key(dotted), f.key("ı"), "{locale} {dotted:?}");
assert!(f.contains(&format!("{dotted}STANBUL"), "istanbul"), "{locale} {dotted:?}");
assert!(!f.contains(&format!("{dotted}STANBUL"), "ıstanbul"), "{locale} {dotted:?}");
}
}
}
}
-1
View File
@@ -436,7 +436,6 @@ impl Mods {
/// The held modifiers' names for a screen reader, in the platform's order: `Ctrl Option Shift Cmd` on macOS,
/// `Ctrl Alt Shift` elsewhere.
// P3(top-w2): tp.T16, `Mods::spoken` public for `ToggleButton::spoken` callers
pub fn spoken(self, platform: Platform) -> Vec<&'static str> {
let m = self.effective(platform);
let table: [(bool, &'static str); 4] = if platform.is_mac() {
+19 -5
View File
@@ -1030,6 +1030,9 @@ impl Names {
/// The catalog by normalized path and label, for the match steps.
struct Index {
tool: Vec<bool>,
/// Each command's default triggers, for choosing among same-named commands by the keys an
/// entry carries.
defaults: Vec<Vec<Trigger>>,
/// Whether each command has a default binding, for choosing among same-named commands.
has_default: Vec<bool>,
/// Whether each command has a menu path of its own (not an import-only one).
@@ -1047,6 +1050,7 @@ impl Index {
fn new(keymap: &Keymap) -> Index {
let mut ix = Index {
tool: Vec::new(),
defaults: Vec::new(),
has_default: Vec::new(),
has_menu: Vec::new(),
keys: HashMap::new(),
@@ -1056,6 +1060,7 @@ impl Index {
};
for (i, b) in keymap.catalog().iter().enumerate() {
ix.tool.push(matches!(b.kind, CommandKind::Tool { .. }));
ix.defaults.push(b.defaults.iter().map(|d| d.trigger).collect());
ix.has_default.push(!b.defaults.is_empty());
ix.has_menu.push(!b.paths.is_empty());
ix.keys.insert(b.command.key(), i);
@@ -1069,11 +1074,20 @@ impl Index {
}
/// The one command of `list` of the wanted kind. Among several, those with a default binding
/// win over those without, then those with a menu path over those without; the pick is
/// unique only when one is left. Aliases such as `history.undo` thus lose to the command
/// users know from the menu.
fn pick(&self, list: Option<&Vec<usize>>, tool: bool) -> Found {
/// that is one of `keys` win first: a source that gives two commands one label still carries
/// the key that tells them apart. Then those with a default binding win over those without,
/// then those with a menu path over those without; the pick is unique only when one is left.
/// Aliases such as `history.undo` thus lose to the command users know from the menu.
fn pick(&self, list: Option<&Vec<usize>>, tool: bool, keys: &[ForeignKey]) -> Found {
let mut fits: Vec<usize> = list.into_iter().flatten().copied().filter(|i| self.tool.get(*i) == Some(&tool)).collect();
let carried = |i: &usize| {
self.defaults
.get(*i)
.is_some_and(|d| d.iter().any(|t| keys.iter().any(|k| k.trigger.as_ref().is_ok_and(|kt| kt == t))))
};
if fits.len() > 1 && fits.iter().any(carried) {
fits.retain(carried);
}
for preferred in [&self.has_default, &self.has_menu] {
if fits.len() > 1 && fits.iter().any(|i| preferred[*i]) {
fits.retain(|i| preferred[*i]);
@@ -1111,7 +1125,7 @@ impl Index {
let toggle_steps = self.toggles.steps(menu.as_ref(), &toggle_segs, panel);
let mut many = false;
for (list, by_panel) in steps.into_iter().chain(toggle_steps) {
match self.pick(list, tool) {
match self.pick(list, tool, &entry.keys) {
Found::One(i, _) => return Found::One(i, by_panel),
Found::Many => many = true,
Found::None => {}
+84 -2
View File
@@ -1,8 +1,8 @@
//! Photoshop .kys sets.
use super::kys::{self, KysError, MAX_BYTES};
use crate::Trigger;
use crate::keymap::Binding;
use crate::keymap::{Binding, CommandDef, CommandKind, Keymap};
use crate::{CommandRef, ImportOptions, Platform, Scope, Scopes, Trigger, plan};
fn binding(text: &str) -> Binding {
Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
@@ -20,6 +20,23 @@ fn set(rows: &str, filename: &str) -> String {
format!("<photoshop-keyboard-shortcuts version=\"4\" filename=\"{filename}\">{rows}</photoshop-keyboard-shortcuts>")
}
fn command(id: &str, label: &str, defaults: &[&str]) -> CommandDef {
defaults.iter().fold(CommandDef::new(id, label, Scope::app()), |c, d| c.with_default(binding(d)))
}
fn tool(id: &str, label: &str, defaults: &[&str]) -> CommandDef {
command(id, label, defaults).with_kind(CommandKind::Tool { group: None })
}
fn keymap(catalog: Vec<CommandDef>) -> Keymap {
Keymap::new(catalog, Scopes::new(), Platform::Mac)
}
/// Every entry's id with its keys, in file order.
fn by_id(set: &crate::ForeignSet) -> Vec<(String, Vec<Trigger>)> {
set.entries.iter().map(|e| (e.id.clone().unwrap_or_default(), keys(e))).collect()
}
#[test]
// A Mac set's Control+Opt+Cmd+G and a Windows set's Ctrl+Alt+G read as the same chord with Cmd; the set name comes from the filename attribute.
fn reads_a_mac_and_a_windows_set() {
@@ -60,3 +77,68 @@ fn reads_a_mac_and_a_windows_set() {
let refused = std::thread::Builder::new().stack_size(512 * 1024).spawn(move || kys::read(&deep).err()).unwrap().join().unwrap();
assert!(matches!(refused, Some(KysError::NotASet(m)) if m.contains("nested")));
}
#[test]
// The `+` key spelled alone, or after a modifier as `Cmd++`, is a key and not a separator, both when written and when read.
fn a_bare_plus_key_is_written_and_read() {
let km = keymap(vec![command("view.zoomIn", "Zoom In", &["Cmd++"]), tool("tool.zoom", "Zoom Tool", &["+"])]);
let xml = kys::write("Mine", &km);
assert!(xml.contains("<shortcut>Cmd++</shortcut>"), "{xml}");
assert!(xml.contains(">+</tool>"), "{xml}");
let back = kys::read(&xml).unwrap();
assert_eq!(by_id(&back), [("view.zoomIn".to_string(), vec![trigger("Cmd++")]), ("tool.zoom".to_string(), vec![trigger("+")])]);
// A Windows set: its Ctrl row makes Ctrl the command key, and the `+` row stays the bare key.
let windows = kys::read(&set(
"<command name=\"Copy\"><shortcut>Ctrl+C</shortcut></command><command name=\"Zoom In\"><shortcut>+</shortcut></command>",
"",
))
.unwrap();
assert_eq!(keys(&windows.entries[0]), [trigger("Cmd+C")]);
assert_eq!(keys(&windows.entries[1]), [trigger("+")]);
}
#[test]
// A set the suite writes spells keys as Photoshop's Mac sets do and reads back into the same bindings, matched by id even where the labels differ.
fn a_written_set_reads_back_with_photoshops_key_spelling() {
let km = keymap(vec![
command("edit.copy", "Copy", &["Cmd+C", "F3"]),
command("filter.blur", "Gaussian Blur…", &["Cmd+Ctrl+Alt+Shift+G"]),
command("edit.unbound", "Unbound", &[]),
tool("tool.move", "Move Tool", &["V"]),
]);
let xml = kys::write(" My & Set ", &km);
assert!(xml.contains("KeyboardCustomization/My &amp; Set=My &amp; Set"), "{xml}");
assert!(
xml.contains(
"<command kind=\"static\" name=\"Gaussian Blur...\" craft-id=\"filter.blur\"><shortcut>Control+Opt+Shift+Cmd+G</shortcut></command>"
),
"{xml}"
);
assert!(xml.contains("<shortcut>Cmd+C</shortcut><shortcut>F3</shortcut>"), "{xml}");
assert!(!xml.contains("Unbound"), "a command without a key is left out: {xml}");
let back = kys::read(&xml).unwrap();
assert_eq!(back.name.as_deref(), Some("My & Set"));
assert_eq!(
by_id(&back),
[
("edit.copy".to_string(), vec![trigger("Cmd+C"), trigger("F3")]),
("filter.blur".to_string(), vec![trigger("Cmd+Ctrl+Alt+Shift+G")]),
("tool.move".to_string(), vec![trigger("V")]),
]
);
// Into a keymap whose labels say something else and that has no keys: the ids decide.
let mut fresh = keymap(vec![
command("edit.copy", "Duplicate To Clipboard", &[]),
command("filter.blur", "Soften", &[]),
command("edit.unbound", "Unbound", &[]),
tool("tool.move", "Arrow", &[]),
]);
plan(&back, &fresh, &ImportOptions::default()).apply(&mut fresh);
for id in ["edit.copy", "filter.blur", "edit.unbound", "tool.move"] {
let c = CommandRef::new(id);
assert_eq!(fresh.bindings(&c), km.bindings(&c), "{id}");
}
}
+20 -7
View File
@@ -15,7 +15,7 @@ pub fn marked(label: &str, folder: &Folder) -> (String, Option<char>) {
/// [`marked`] with the character index of the marked letter in the returned text.
pub fn marked_at(label: &str, folder: &Folder) -> (String, Option<(char, usize)>) {
let _ = folder; // P3(top-w2): tp.T9
let turkic = folder.turkic();
let mut text = String::with_capacity(label.len());
let mut mark = None;
let mut at = 0;
@@ -27,8 +27,11 @@ pub fn marked_at(label: &str, folder: &Folder) -> (String, Option<(char, usize)>
continue;
}
let Some(next) = chars.next() else { break };
if mark.is_none() && next != '&' && next.is_ascii_alphanumeric() {
mark = Some((next.to_ascii_uppercase(), at));
if mark.is_none()
&& next != '&'
&& let Some(key) = letter(next, turkic)
{
mark = Some((key, at));
}
text.push(next);
at += 1;
@@ -51,14 +54,14 @@ pub fn assign(labels: &[&str], folder: &Folder) -> Vec<Option<(char, usize)>> {
}
for ((text, _), slot) in parsed.iter().zip(&mut out) {
if slot.is_none() {
*slot = first_unused(text, &used);
*slot = first_unused(text, &used, folder.turkic());
used.extend(slot.map(|(letter, _)| letter));
}
}
out
}
fn first_unused(text: &str, used: &[char]) -> Option<(char, usize)> {
fn first_unused(text: &str, used: &[char], turkic: bool) -> Option<(char, usize)> {
let mut previous_alnum = false;
let mut starts = Vec::new();
for (at, c) in text.chars().enumerate() {
@@ -71,7 +74,17 @@ fn first_unused(text: &str, used: &[char]) -> Option<(char, usize)> {
starts
.into_iter()
.chain(all)
.filter(|(c, _)| c.is_ascii_alphanumeric())
.map(|(c, at)| (c.to_ascii_uppercase(), at))
.filter_map(|(c, at)| Some((letter(c, turkic)?, at)))
.find(|(c, _)| !used.contains(c))
}
/// The key that types `c`, as a mnemonic letter: its upper case, which must be an ASCII letter or digit. In Turkish
/// and Azerbaijani `I` is the capital of `ı`, so `ı` takes the I key, while `i` and `İ` have no key of their own.
fn letter(c: char, turkic: bool) -> Option<char> {
match c {
'ı' if turkic => Some('I'),
'i' if turkic => None,
c if c.is_ascii_alphanumeric() => Some(c.to_ascii_uppercase()),
_ => None,
}
}
+82 -1
View File
@@ -3,7 +3,7 @@
use std::collections::BTreeMap;
use craft_keymap::chord::foreign::{Flavor, ForeignError};
use craft_keymap::import::{FailedChange, UnmatchedReason};
use craft_keymap::import::{FailedChange, UnmatchedReason, kys};
use craft_keymap::{
Binding, CommandDef, CommandKind, CommandRef, ContextRule, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportReport, Keymap,
MAX_COMMANDS, Overrides, Platform, Scope, Scopes, plan, reserved,
@@ -202,3 +202,84 @@ fn a_failed_change_keeps_its_shortcut_when_a_later_change_frees_room() {
assert!(r.conflicts_cleared.is_empty(), "{:?}", r.conflicts_cleared);
assert_eq!(r.imported, 1);
}
/// A Mac keymap of `catalog` with no reserved chords, for sets read with [`kys::read`].
fn mac_keymap(catalog: Vec<CommandDef>) -> Keymap {
Keymap::new(catalog, Scopes::new(), Platform::Mac)
}
/// A `.kys` set of `rows`.
fn kys_set(rows: &str) -> ForeignSet {
kys::read(&format!("<photoshop-keyboard-shortcuts version=\"4\">{rows}</photoshop-keyboard-shortcuts>")).unwrap_or_else(|e| panic!("{e}"))
}
/// The command holds exactly the bindings `texts`, in any order.
fn has_all(km: &Keymap, id: &str, texts: &[&str]) {
let got = km.bindings(&CommandRef::new(id));
let want = bindings(texts);
assert!(got.len() == want.len() && want.iter().all(|w| got.contains(w)), "{id}: {got:?}, wanted {want:?}");
}
fn tool(id: &str, label: &str, keys: &[&str]) -> CommandDef {
command(id, label, &[], keys).with_kind(CommandKind::Tool { group: None })
}
#[test]
fn a_shared_label_goes_to_the_command_whose_default_key_the_row_carries() {
// Photoshop names a row by its label alone; both commands are `Levels…` and both have a
// default, so only the row's keys tell them apart.
let catalog = vec![command("image.levels", "Levels…", &[], &["Cmd+L"]), command("layer.newLevels", "Levels…", &[], &["Cmd+Alt+L"])];
let mut km = mac_keymap(catalog);
let set = kys_set(
"<command name=\"Levels...\"><shortcut>Cmd+L</shortcut><shortcut>F9</shortcut></command>\
<command name=\"Levels...\"><shortcut>Opt+Cmd+L</shortcut><shortcut>F10</shortcut></command>\
<command name=\"Levels...\"><shortcut>F11</shortcut></command>",
);
let r = plan(&set, &km, &ImportOptions::default()).apply(&mut km);
has_all(&km, "image.levels", &["Cmd+L", "F9"]);
has_all(&km, "layer.newLevels", &["Cmd+Alt+L", "F10"]);
let unmatched: Vec<(&str, &str, UnmatchedReason)> = r.unmatched.iter().map(|u| (u.item.as_str(), u.keys.as_str(), u.reason)).collect();
assert_eq!(unmatched, [("Levels...", "F11", UnmatchedReason::Ambiguous)], "a row carrying neither default stays ambiguous");
}
#[test]
fn a_row_with_a_default_and_a_function_key_keeps_both() {
let mut km = mac_keymap(vec![command("edit.copy", "Copy", &["Edit", "Copy"], &["Cmd+C"])]);
let set = kys_set("<command name=\"Copy\"><shortcut>F3</shortcut><shortcut>Cmd+C</shortcut></command>");
let r = plan(&set, &km, &ImportOptions::default()).apply(&mut km);
has_all(&km, "edit.copy", &["Cmd+C", "F3"]);
assert!(r.unmatched.is_empty() && r.unreadable.is_empty() && r.failed.is_empty(), "{r:?}");
}
#[test]
fn tool_keys_match_by_name_or_id_and_take_one_letter() {
let catalog = vec![
// A command with a tool's label: a tool row never binds it.
command("edit.move", "Move Tool", &["Edit", "Move Tool"], &[]),
tool("tool.move", "Move Tool", &["M"]),
tool("tool.pencil", "Pencil Tool", &[]),
tool("tool.brush", "Brush Tool", &[]),
tool("tool.lasso", "Lasso Tool", &["L"]),
];
let mut km = mac_keymap(catalog);
let set = kys_set(
"<command name=\"Copy\"><shortcut>Cmd+C</shortcut></command>\
<tool name=\"Move Tool\">V</tool>\
<tool name=\"pencil tool\">n</tool>\
<tool name=\"Renamed\" craft-id=\"tool.brush\">B</tool>\
<tool name=\"Imaginary Tool\">Q</tool>\
<tool name=\"Lasso Tool\">Shift+L</tool>",
);
let r = plan(&set, &km, &ImportOptions::default()).apply(&mut km);
// By name, ignoring case, and by id whatever the name says.
has(&km, "tool.move", &["V"]);
has(&km, "tool.pencil", &["N"]);
has(&km, "tool.brush", &["B"]);
has(&km, "edit.move", &[]);
// A tool key with a modifier is unreadable and the tool keeps its key.
has(&km, "tool.lasso", &["L"]);
let unreadable: Vec<&str> = r.unreadable.iter().map(|u| u.item.as_str()).collect();
assert_eq!(unreadable, ["Lasso Tool"]);
let unmatched: Vec<(&str, UnmatchedReason)> = r.unmatched.iter().map(|u| (u.item.as_str(), u.reason)).collect();
assert_eq!(unmatched, [("Copy", UnmatchedReason::NoMatch), ("Imaginary Tool", UnmatchedReason::NoMatch)]);
}
+36 -1
View File
@@ -1,5 +1,10 @@
//! A label with no typable letter takes its English label's letter as its mnemonic, shown after it: "文件(F)".
//! A label with no typable letter takes its English label's letter as its mnemonic, shown after it: "文件(F)"; in
//! Turkish the dotless ı takes the I key and the dotted i none.
use std::sync::Arc;
use craft_host::target::Os;
use craft_host::{AppInfo, Host};
use craft_menu::{CommandRef, Labeled, MenuBarUi, Row, from_items};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
@@ -21,3 +26,33 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() {
fixture.settle();
assert!(fixture.by_label("新建(N)").is_some(), "Alt+F opens the title's menu, whose row shows its own English letter");
}
/// A host whose interface language is Turkish, with an empty catalog.
fn turkish() -> Arc<Host> {
let (i18n, _) = craft_i18n::I18n::from_owned([("tr".to_owned(), String::new(), String::new())], &["tr"]);
let tr = i18n.from_code("tr").unwrap_or_else(|| panic!("tr is offered"));
Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).lang(tr).build())
}
/// The rows shown after Alt with `key` on a Linux bar titled `ix` and `ı` under a Turkish host: `One` is `ix`'s, `Two`
/// is `ı`'s.
fn opened_by(key: Key) -> (bool, bool) {
let bar = from_items(&["ix", "ı"], &[Row::new(&["ix"], CommandRef::new("menu.one"), "One"), Row::new(&["ı"], CommandRef::new("menu.two"), "Two")]);
let mut fixture = Fixture::new(move |ui| {
MenuBarUi::new(&bar).show(ui);
});
// A Mac bar has no letters; the host gives the Turkish folder.
fixture.os(Os::Linux).host(turkish());
fixture.settle();
assert!(fixture.by_label("ix").is_some() && fixture.by_label("ı").is_some(), "the titles show as written");
fixture.key(key, Modifiers::ALT);
fixture.settle();
(fixture.by_label("One").is_some(), fixture.by_label("Two").is_some())
}
#[trial]
fn turkic_labels_keep_dotted_and_dotless_i_apart() {
// ı's capital is I, so ı holds the I key; the dotted i has no key of its own, so ix takes X.
assert_eq!(opened_by(Key::I), (false, true), "Alt+I opens ı");
assert_eq!(opened_by(Key::X), (true, false), "Alt+X opens ix");
}
+7 -2
View File
@@ -277,9 +277,14 @@ pub(crate) fn layer_rect(ctx: &Context, id: Id) -> Option<Rect> {
ctx.memory(|memory| memory.area_rect(id))
}
/// The viewport's safe rect: the room overlays must stay inside.
/// The viewport's safe rect: the room overlays must stay inside, the part of the content rect the user can see on
/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect.
pub(crate) fn safe_rect(ctx: &Context) -> Rect {
ctx.content_rect()
let content = ctx.content_rect();
ctx.input(|input| {
let viewport = input.viewport();
craft_window::desktop::visible_part(content, viewport.monitor_size, viewport.inner_rect, craft_window::desktop::WindowState::of(viewport))
})
}
/// Hands egui the whole layer order of the running pass, bottom first. egui consumes it by the end of the pass.
+28 -15
View File
@@ -166,14 +166,13 @@ pub(crate) fn owner_at(ctx: &Context, target: Option<&StopRec>, scopes: &[Id], b
/// The shortcut events the key owner leaves to the app (9.3), and the presses the focused component holds
/// (`holds_press`). The owner is the focused component's class, or `Blocked` while a modal layer is stacked above the
/// focus; inside a layer its `Overlay.keys` class ranks with the component's. `Menu` and `Recorder` keep every key; a
/// text field keeps the text its presses typed. `consumed` is what routing did with each press and `taken_texts` whether
/// a component took each text of the pass.
/// focus; inside a layer its `Overlay.keys` class ranks with the component's. A `Recorder` keeps every key and a `Menu`
/// every key but a command chord (`keeps_key`); a text field keeps the text its presses typed. `consumed` is what
/// routing did with each press and `taken_texts` whether a component took each text of the pass.
fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consumed: &[Taken], taken_texts: &[bool]) -> (Shortcuts, Vec<bool>) {
let scopes = target.map(|rec| focus::scope_chain(ctx, rec)).unwrap_or_default();
let owner = owner_at(ctx, target, &scopes, None);
let own = target.map(|rec| rec.stop.keys.owner);
let silent = keeps_every_key(owner);
let dialog = owner == KeyOwner::Class(OwnerClass::Dialog);
// The focused component keeps its own keys inside a dialog: a text field its typing, a widget its activation.
let typing = owner != KeyOwner::Blocked && own == Some(OwnerClass::Text);
@@ -183,8 +182,14 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu
.zip(consumed)
.map(|(press, taken)| holds_press(owner, target, press, *taken == Taken::Yes, press.text.is_some_and(|at| taken_texts[at])))
.collect();
let keys =
if silent { Vec::new() } else { batch.shortcuts.iter().filter(|shortcut| !shortcut.press.is_some_and(|at| held[at])).copied().collect() };
// A shortcut without a press of its own (a release, or the clipboard event that stands for ⌘C) follows the owner by
// its modifiers, as its press would.
let keys = batch
.shortcuts
.iter()
.filter(|shortcut| !keeps_key(owner, shortcut.input.mods) && !shortcut.press.is_some_and(|at| held[at]))
.copied()
.collect();
(Shortcuts { keys, typing, dialog, layout: Layout::default() }, held)
}
@@ -192,12 +197,13 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu
/// egui's input, where the app reads its own keys, nor the app's shortcuts. A widget or popup holds the presses its
/// routing `taken`, the keys its filter keeps from the key stage, and the presses whose text it took (`typed`: the
/// type-ahead of a list). A text field holds the presses whose text it took, its typing; the egui text widget behind it
/// reads the text, not the press, and the editing keys, which stay in egui's input. A menu or a recorder holds every
/// press, except that a text field in a menu (a menu's search field) keeps the text field's rule.
/// reads the text, not the press, and the editing keys, which stay in egui's input. A recorder holds every press and a
/// menu every press but a command chord (`keeps_key`), except that a text field in a menu (a menu's search field) keeps
/// the text field's rule: the editing chords it lists reach it as edits before routing (`Strip::press`).
fn holds_press(owner: KeyOwner, target: Option<&StopRec>, press: &Press, taken: bool, typed: bool) -> bool {
let Some(keys) = target.map(|rec| &rec.stop.keys) else { return false };
let text = keys.owner == OwnerClass::Text;
if keeps_every_key(owner) && !text {
if keeps_key(owner, press.mods) && !text {
return true;
}
let open = owner != KeyOwner::Blocked;
@@ -211,14 +217,21 @@ fn holds_press(owner: KeyOwner, target: Option<&StopRec>, press: &Press, taken:
(widget && (taken || typed || kept)) || (open && text && typed)
}
/// `Menu` and `Recorder` keep every key (9.3): no press of theirs reaches egui's input or the app's shortcuts.
fn keeps_every_key(owner: KeyOwner) -> bool {
matches!(owner, KeyOwner::Class(OwnerClass::Menu | OwnerClass::Recorder))
/// Whether the key owner `owner` keeps a press with `mods` held from egui's input and the app's shortcuts (9.3). A
/// `Recorder` keeps every key. A `Menu` keeps every key but a command chord, one with Cmd or Ctrl held: its shortcut
/// runs, and running a command from a key closes the open popups (`overlay::close_popups`), so ⌘⌥P under an open menu
/// works as it does with the menu closed.
fn keeps_key(owner: KeyOwner, mods: Mods) -> bool {
match owner {
KeyOwner::Class(OwnerClass::Recorder) => true,
KeyOwner::Class(OwnerClass::Menu) => !(mods.cmd || mods.ctrl),
_ => false,
}
}
/// Where the focused stop `rec` sends the typed `text`, and as what: a digits stop takes its digits, and the rest goes
/// to the list `driven` drives, to a text or type-ahead stop, or to the menu around the stop. Empty when no component
/// takes the text. Reads state only, so a query can ask it.
/// to the list `driven` drives, to a text or type-ahead stop, or to the container of the menu level around the stop.
/// Empty when no component takes the text. Reads state only, so a query can ask it.
fn text_route(ctx: &Context, rec: &StopRec, driven: Option<Driven>, text: &str) -> Vec<(Id, Intent)> {
let mut route = Vec::new();
let rest;
@@ -239,7 +252,7 @@ fn text_route(ctx: &Context, rec: &StopRec, driven: Option<Driven>, text: &str)
} else if matches!(rec.stop.keys.owner, OwnerClass::Text) || (rec.stop.role.type_ahead && letters) {
Some(rec.stop.id)
} else if letters {
focus::menu_scope(ctx, rec)
focus::menu_level(ctx, rec)
} else {
None
};
+16 -5
View File
@@ -40,7 +40,8 @@ pub struct PointerFrame {
pub press: Option<PressStart>,
/// The button released in the pass.
pub release: Option<PointerButton>,
/// The modifiers held.
/// The modifiers held, with the ones the app latches for the user (a Modifier Keys panel) added: the app holds
/// them down for every press and drag. Key chords read the keyboard's own modifiers instead.
pub mods: Mods,
/// The pass's time in seconds.
pub time: f64,
@@ -88,7 +89,8 @@ pub struct PassPointer {
#[derive(Default)]
pub(crate) struct Memory {
last_press: Option<(Pos2, f64, u32, craft_keymap::Mods)>,
/// The latest primary press: where, when, its click count and the modifiers held with it.
last_press: Option<(Pos2, f64, u32, Mods)>,
press_targets: PressTargets,
/// A cancel a service requested for the running pass.
requested: Option<(u64, PressCancel)>,
@@ -116,9 +118,13 @@ pub(crate) struct Shapes {
/// The begin hook (H5): converts the pass's pointer input.
pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) {
let viewport = pass::current_viewport(ctx);
let pass_nr = pass::pass_nr(ctx, viewport);
let mut read = input::pointer_read(ctx);
// Every pass reads its own input and the frame's latches, so a second pass of a frame builds the same
// modifiers from its own (event-free) input and counts no press twice.
let mods = with_latched(read.mods, latched);
// A drag that started in another window reaches this one through the desktop pointer (8.4).
if read.pos.is_none() {
read.pos = drag::cross_window_pointer(ctx, viewport);
@@ -131,8 +137,8 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) {
let mut events = read.events.clone();
for event in &mut events {
if let PointerEvent::Pressed { button: PointerButton::Primary, pos, time, clicks, .. } = event {
*clicks = count_clicks(memory.last_press, *pos, *time, latched, hit.slop); // P3(top-w2): pn.C14
memory.last_press = Some((*pos, *time, *clicks, latched));
*clicks = count_clicks(memory.last_press, *pos, *time, mods, hit.slop);
memory.last_press = Some((*pos, *time, *clicks, mods));
}
}
if read.primary_pressed || other_pressed {
@@ -152,7 +158,7 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) {
buttons: read.buttons,
press,
release: read.release,
mods: read.mods,
mods,
time: read.time,
kind: read.kind,
sample: read.sample,
@@ -176,6 +182,11 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) {
PerViewport::<Shapes>::with(ctx, viewport, |shapes| shapes.last = std::mem::take(&mut shapes.this));
}
/// The modifiers `held` with the app's `latched` ones added, field by field: `Mods` has no operator for it.
fn with_latched(held: Mods, latched: Mods) -> Mods {
Mods { cmd: held.cmd || latched.cmd, ctrl: held.ctrl || latched.ctrl, alt: held.alt || latched.alt, shift: held.shift || latched.shift }
}
/// The running viewport's pass number.
pub(crate) fn pass_of(ctx: &Context) -> u64 {
pass::pass_nr(ctx, pass::current_viewport(ctx))
@@ -0,0 +1,158 @@
//! Latched modifiers (`FrameInput::latched`): the app holds them down for every press, and only for pointer work.
use craft_behavior::Sense;
use craft_keymap::{Chord, Key as ChordKey, Mods};
use craft_ui::contract::{Common, Component, Cx, Focus as _, Pointer as _, Props as _, Role, Show as _};
use craft_ui::runtime::focus::{FocusTarget, KeyUse, request};
use craft_ui::style::StyleCx;
use craft_ui::testing::input::key_press;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Frames, trial};
use craft_ui_test_kit::contract::PlainStyle;
use egui::{Id, Key, Modifiers, Pos2, Response, Ui};
use std::cell::{Cell, RefCell};
/// The probe claims K plain and with Shift: which one a press of K takes tells the modifiers key routing read.
const CLAIMS: &[Chord] = &[Chord::plain(ChordKey::K), Chord::new(Mods::SHIFT, ChordKey::K)];
/// What the probe saw.
#[derive(Default)]
struct Log {
/// The modifiers of each pass's activation.
activations: Vec<Mods>,
/// The claimed chords the probe took.
claimed: Vec<Chord>,
/// `pointer::frame(..).mods` of every pass.
pointer: Vec<Mods>,
}
/// A focusable button that logs its activations' modifiers and the claimed chords it takes.
#[derive(Component)]
struct LatchProbe<'a> {
#[common]
common: Common,
log: &'a RefCell<Log>,
}
impl Component for LatchProbe<'_> {
const ROLE: Role = Role::BUTTON;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: LatchProbeStyleKey) -> PlainStyle {
PlainStyle::min(egui::vec2(80.0, 30.0))
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS
}
fn keys(&self) -> KeyUse {
Self::KEYS.with_claims(CLAIMS)
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let activation = cx.activation().map(|activation| activation.mods);
let claimed: Vec<Chord> = CLAIMS.iter().copied().filter(|chord| cx.take_claimed(*chord)).collect();
let mut log = self.log.borrow_mut();
log.activations.extend(activation);
log.claimed.extend(claimed);
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
/// The probe's frame closure, the probe's id and rect once shown, and a switch that discards the next pass.
struct Rig {
log: RefCell<Log>,
shown: Cell<Option<(Id, egui::Rect)>>,
discard: Cell<bool>,
}
impl Rig {
fn new() -> Self {
Rig { log: RefCell::new(Log::default()), shown: Cell::new(None), discard: Cell::new(false) }
}
fn show(&self, ui: &mut Ui) {
let response = LatchProbe { common: Common::new(), log: &self.log }.id_salt("latch").show(ui);
self.shown.set(Some((response.id, response.rect)));
self.log.borrow_mut().pointer.push(craft_ui::runtime::pointer::frame(ui.ctx()).mods);
if self.discard.take() {
ui.ctx().request_discard("the trial reruns the pass");
}
}
fn at(&self) -> Pos2 {
self.shown.get().map_or(Pos2::ZERO, |(_, rect)| rect.center())
}
fn clear(&self) {
*self.log.borrow_mut() = Log::default();
}
}
/// A click on the probe whose release frame runs a second pass; returns that frame's pass count.
fn click_with_rerun(frames: &mut Frames, rig: &Rig) -> usize {
let at = rig.at();
frames.frame(vec![moved(at)], |ui| rig.show(ui));
frames.frame(vec![press(at)], |ui| rig.show(ui));
rig.discard.set(true);
let passes = frames.frame(vec![release(at)], |ui| rig.show(ui));
frames.idle(1, |ui| rig.show(ui));
passes
}
#[trial]
fn a_latched_modifier_reaches_every_press_until_released() {
let rig = Rig::new();
let mut frames = Frames::new();
frames.idle(3, |ui| rig.show(ui));
let id = rig.shown.get().map(|(id, _)| id).expect("the probe showed");
request(&frames.ctx, FocusTarget::Id(id));
frames.idle(2, |ui| rig.show(ui));
frames.latched(Mods::SHIFT);
rig.clear();
assert_eq!(click_with_rerun(&mut frames, &rig), 2, "the release frame runs a second pass");
{
let log = rig.log.borrow();
assert_eq!(log.activations, [Mods::SHIFT], "one click, one activation, Shift held by the latch, on the rerun pass too");
assert!(log.pointer.iter().all(|mods| mods.shift), "every pass's pointer frame holds the latch: {:?}", log.pointer);
}
// A typed key keeps the keyboard's own modifiers: K reaches the plain-K claim, not Shift+K.
rig.clear();
frames.frame(vec![key_press(Key::K, Modifiers::NONE)], |ui| rig.show(ui));
frames.idle(1, |ui| rig.show(ui));
assert_eq!(rig.log.borrow().claimed, [Chord::plain(ChordKey::K)], "no Shift chord fired from a latched Shift");
frames.latched(Mods::NONE);
rig.clear();
click_with_rerun(&mut frames, &rig);
let log = rig.log.borrow();
assert_eq!(log.activations, [Mods::NONE], "a released latch leaves the click plain");
assert!(log.pointer.iter().all(|mods| !mods.shift), "{:?}", log.pointer);
}
#[trial]
fn a_latch_change_adds_no_pass() {
let rig = Rig::new();
let mut frames = Frames::new();
frames.idle(3, |ui| rig.show(ui));
// The pointer rests on the probe, where a change of the held modifiers could matter to it.
let at = rig.at();
frames.frame(vec![moved(at)], |ui| rig.show(ui));
frames.idle(2, |ui| rig.show(ui));
let steady = frames.frame(Vec::new(), |ui| rig.show(ui));
frames.latched(Mods::SHIFT);
let latched = frames.frame(Vec::new(), |ui| rig.show(ui));
let held = frames.frame(Vec::new(), |ui| rig.show(ui));
frames.latched(Mods::NONE);
let released = frames.frame(Vec::new(), |ui| rig.show(ui));
assert_eq!(latched, steady, "latching runs no extra pass");
assert_eq!(held, steady);
assert_eq!(released, steady, "releasing runs no extra pass");
}
@@ -3,6 +3,7 @@ mod cursor;
mod elapsed;
mod env;
mod frame;
mod latch;
mod memory;
mod pen;
mod pointer;
@@ -1,10 +1,29 @@
//! `ModifierKeysPanel`: on-screen toggles for the modifier keys, for a touch screen without a keyboard.
use crate::contract::{Bind, Pattern};
use craft_keymap::Mods;
use crate::buttons::ToggleButton;
use crate::contract::{Bind, Pattern, Props as _, Show as _, ShowContainer as _};
use crate::layout_components::Row;
use crate::runtime::env::{Env, Label};
use craft_behavior::{EditEvent, Mixed};
use craft_keymap::{Mods, Platform};
use egui::{Response, Ui};
use std::sync::Arc;
#[cfg(feature = "testing")]
mod stories;
/// The panel's buttons in their fixed order, each with the one modifier it latches: Shift, the command key (⌘ on
/// macOS, Ctrl elsewhere) and Alt (⌥ on macOS).
const KEYS: [(&str, Mods); 3] = [("shift", Mods::SHIFT), ("command", Mods::CMD), ("alt", Mods::ALT)];
/// A panel of latching modifier-key toggles: a press on one holds that modifier for the next click or key.
///
/// - Three toggle buttons, Shift, the command key and Alt, over one binding of the latched modifiers.
/// - Each face is the modifier as chord text writes it on the OS (`⇧ ⌘ ⌥` on macOS, `Shift Ctrl Alt` elsewhere), and
/// its accessible name the modifier's spoken name (`Shift`, `Cmd`, `Option` on macOS).
/// - The app hands the binding's value to the runtime as the frame's latched modifiers (`FrameInput::latched`): every
/// press and drag then reads them as held. Key chords read the keyboard's own modifiers.
/// - The panel adds no words: its title is the dock panel's.
#[must_use = "show the panel with `show`"]
#[derive(Pattern)]
pub struct ModifierKeysPanel<'a> {
@@ -14,13 +33,55 @@ pub struct ModifierKeysPanel<'a> {
impl<'a> ModifierKeysPanel<'a> {
/// A panel over the latched modifiers in `latched`.
pub fn new(latched: Bind<'a, Mods>) -> Self {
let _ = latched;
todo!("tp.T16")
ModifierKeysPanel { latched }
}
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> Response {
let _ = (ui, &self.latched);
todo!("tp.T16")
let ModifierKeysPanel { mut latched } = self;
let os = Env::of(ui).view().shell().os;
Row::new()
.show(ui, |ui, row| {
let held = latched.reborrow().read(row).and_then(|held| held.same().copied()).unwrap_or_default();
// Off macOS a held Ctrl is the command key: the buttons show and edit the modifiers as the OS reads them.
let before = held.effective(os);
let mut now = before;
for (salt, key) in KEYS {
let mut on = holds(now, key);
ToggleButton::new(face(key, os), Bind::bound(&mut on)).spoken(Label::from(spoken(key, os))).id_salt(salt).show(ui);
now = set(now, key, on);
}
if now != before {
let toggled = KEYS.iter().find(|(_, key)| holds(now, *key) != holds(before, *key)).map_or(Mods::NONE, |(_, key)| *key);
let name: Arc<str> = Arc::from(spoken(toggled, os).as_str());
let _ = latched.reborrow().write(row, &EditEvent::set(Mixed::Same(held), now, name, None));
}
})
.output
}
}
/// The face of the button for the one-modifier `key`: its symbol on macOS, its name elsewhere.
fn face(key: Mods, os: Platform) -> String {
key.parts(os).concat()
}
/// The name a screen reader says for the one-modifier `key`.
fn spoken(key: Mods, os: Platform) -> String {
key.spoken(os).join(" ")
}
/// Whether `mods` holds the one modifier of `key`.
fn holds(mods: Mods, key: Mods) -> bool {
(key.shift && mods.shift) || (key.cmd && mods.cmd) || (key.alt && mods.alt)
}
/// `mods` with the one modifier of `key` held or released.
fn set(mods: Mods, key: Mods, on: bool) -> Mods {
Mods {
shift: if key.shift { on } else { mods.shift },
cmd: if key.cmd { on } else { mods.cmd },
alt: if key.alt { on } else { mods.alt },
ctrl: mods.ctrl,
}
}
@@ -0,0 +1,15 @@
//! Stories of `ModifierKeysPanel`.
use super::ModifierKeysPanel;
use crate::contract::Bind;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_keymap::Mods;
use egui::Ui;
#[story(ModifierKeysPanel<'static>, covers = [], drive = Drive::Never, title = "Shift latched")]
fn modifier_keys_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let latched = data.value("latched", Mods::SHIFT);
ModifierKeysPanel::new(Bind::bound(&mut *latched)).show(ui);
let readout = format!("{latched:?}");
StoryOutput::default().readout(readout)
}
+11 -4
View File
@@ -1,7 +1,9 @@
//! `ToggleButton`: a button that stays pressed while on.
use super::face::{self, FaceLook, FaceSpec};
use crate::contract::{Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, PaintUi, Pointer as _, Props, Role};
use crate::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, PaintUi, Pointer as _, Props, Role,
};
use crate::primitives::IconSpec;
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
@@ -65,7 +67,6 @@ pub struct ToggleButton<'a> {
#[prop(flag)]
escape_disarms: bool,
/// The name a screen reader hears when it differs from the face (a modifier key's symbol face).
// P3(top-w2): tp.T16 decision, the `spoken` prop
#[prop]
spoken: Option<Label>,
}
@@ -82,7 +83,7 @@ impl<'a> ToggleButton<'a> {
role: None,
icon_only: false,
escape_disarms: false,
spoken: None, // P3(top-w2): tp.T16
spoken: None,
}
.label(label)
}
@@ -98,7 +99,7 @@ impl<'a> ToggleButton<'a> {
role: None,
icon_only: false,
escape_disarms: false,
spoken: None, // P3(top-w2): tp.T16
spoken: None,
};
<ToggleButton as Props>::command(button, command)
}
@@ -172,6 +173,12 @@ impl Component for ToggleButton<'_> {
self.value.as_mut().map(Bind::reborrow)
}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
if let Some(spoken) = &self.spoken {
access.name(Name::Text(cx.env.resolve(spoken).as_str().to_owned()));
}
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
cx.join_roving();
if self.escape_disarms && cx.value().copied() == Some(true) && cx.take_claimed(ESCAPE[0]) {
+3 -2
View File
@@ -308,8 +308,9 @@ impl<'a> MenuBar<'a> {
fn texts(&self, env: &EnvView<'_>) -> Vec<(String, Option<(char, usize)>)> {
let labels: Vec<Label> = self.titles.iter().map(|title| env.resolve(&title.label)).collect();
let refs: Vec<&str> = labels.iter().map(Label::as_str).collect();
let marks = if env.shell().os.is_mac() { vec![None; refs.len()] } else { mnemonic::assign(&refs, &env.folder()) }; // P3(top-w2): tp.T11
refs.iter().zip(marks).map(|(label, mark)| (mnemonic::marked(label, &env.folder()).0, mark)).collect() // P3(top-w2): tp.T11
let folder = env.folder();
let marks = if env.shell().os.is_mac() { vec![None; refs.len()] } else { mnemonic::assign(&refs, &folder) };
refs.iter().zip(marks).map(|(label, mark)| (mnemonic::marked(label, &folder).0, mark)).collect()
}
fn face(text: &str, lit: bool, mnemonic: Option<usize>) -> TitleFace {
+10 -6
View File
@@ -370,7 +370,7 @@ impl Component for MenuItem<'_> {
}
let columns = self.columns(cx, &level);
let detail = self.detail_size(cx);
let text = mnemonic::marked(cx.resolved.label, &cx.env.folder()).0; // P3(top-w2): tp.T11
let text = mnemonic::marked(cx.resolved.label, &cx.env.folder()).0;
let run = TextRun::new(text.as_str()).role(self.label_look(cx.style).role);
let label = if text.is_empty() { Vec2::ZERO } else { cx.layout_at(&run, f32::INFINITY).size() };
let gap = cx.gap();
@@ -479,9 +479,13 @@ impl Component for MenuItem<'_> {
if takes_over && level.clear_submenu() {
frame::request_repaint(&ctx);
}
// The run closes the menus: focus leaves them first, so the command reaches the stop focus returns to.
if asked && !self.keep_open {
crate::runtime::focus::return_from_pick(&ctx, crate::runtime::focus::PickedIn::Menus);
// The run closes the menus out from the one this row runs in: focus leaves them first, so the command reaches
// the stop focus returns to.
if asked
&& !self.keep_open
&& let Some(menu) = crate::runtime::focus::running_menu(&ctx)
{
crate::runtime::focus::return_from_pick(&ctx, crate::runtime::focus::PickedIn::Menus(menu));
}
// Every activation of a menu row reaches its command as `FireSource::Menu`, whether it was typed, clicked or keyed.
// A typed letter also runs a row that has no command: the injected activation closes the menu.
@@ -513,7 +517,7 @@ impl Component for MenuItem<'_> {
let level = cx.env.get::<MenuLevel>();
let command = cx.command.as_deref();
let (mark_column, icon_column) = self.lead_columns(&cx.core.ctx, side, gap, command, &level);
let text = mnemonic::marked(cx.resolved.label, &cx.env.folder()).0; // P3(top-w2): tp.T11
let text = mnemonic::marked(cx.resolved.label, &cx.env.folder()).0;
let mark = self.mark(command, &level);
let draw = ui.draw();
let detail = self.detail.as_ref().map(|detail| cx.env.resolve(detail));
@@ -568,7 +572,7 @@ impl Component for MenuItem<'_> {
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let level = cx.env.get::<MenuLevel>();
access.name(Name::Text(mnemonic::marked(cx.resolved.label, &cx.env.folder()).0)); // P3(top-w2): tp.T11
access.name(Name::Text(mnemonic::marked(cx.resolved.label, &cx.env.folder()).0));
if self.heading {
access.role(Role::HEADING);
return;
+3 -3
View File
@@ -162,7 +162,7 @@ impl MenuLevel {
}
let letters = if let Some(folder) = state.lettered {
let labels: Vec<&str> = state.now.iter().map(|row| row.text.as_str()).collect();
mnemonic::assign(&labels, &folder) // P3(top-w2): tp.T11
mnemonic::assign(&labels, &folder)
} else {
vec![None; state.now.len()]
};
@@ -185,10 +185,10 @@ impl MenuLevel {
pub(super) fn mnemonic_of(&self, id: Id) -> Option<(char, usize)> {
self.with(|state| {
let folder = state.lettered?; // P3(top-w2): tp.T11
let folder = state.lettered?;
let at = state.now.iter().position(|row| row.id == id)?;
let labels: Vec<&str> = state.now.iter().map(|row| row.text.as_str()).collect();
mnemonic::assign(&labels, &folder)[at] // P3(top-w2): tp.T11
mnemonic::assign(&labels, &folder)[at]
})
}
+27
View File
@@ -66,3 +66,30 @@ fn help_search_ignores_accents_and_matches_the_english_label_and_the_path() {
assert!(!rig.open(absent), "{typed:?} leaves {absent:?} out");
}
}
/// A menu a title click opened takes the letter a row marks: the row runs and the run closes the menu.
#[trial]
fn a_letter_runs_the_row_it_marks_in_a_menu_a_title_click_opened() {
use std::cell::Cell;
use std::rc::Rc;
let saved = Rc::new(Cell::new(0));
let seen = saved.clone();
let mut fixture = Fixture::new(move |ui| {
let titles = vec![MenuTitle::new("&File", |ui| {
MenuItem::new("&New").show(ui);
if MenuItem::new("&Save").show(ui).ran {
seen.set(seen.get() + 1);
}
})];
MenuBar::new("Main menu", titles).show(ui);
});
fixture.settle();
let file = fixture.by_label("File").expect("the File title");
fixture.click(&file);
fixture.settle();
assert!(fixture.by_label("Save").is_some(), "File is open");
fixture.type_text("s");
fixture.settle();
assert_eq!(saved.get(), 1, "the letter runs the row it marks");
assert!(fixture.by_label("Save").is_none(), "and the run closes the menu");
}
@@ -118,6 +118,74 @@ fn a_shortcut_pressed_on_the_focused_bar_runs_once_where_focus_was_and_gives_foc
assert_eq!(fixture.focused_stop().map(|(id, _)| id), target.get(), "and the focus is back on that stop");
}
/// A command chord pressed while a menu is open closes the menu and runs where focus was, as with the menu closed
/// (#9065); the open menu's own keys, a plain letter among them, still drive it.
#[trial]
fn a_command_shortcut_closes_an_open_menu_and_runs() {
use craft_ui::contract::ShowContainer as _;
use craft_ui::runtime::commands::Commands as _;
let count = Rc::new(Cell::new(0));
let target = Rc::new(Cell::new(None));
let (seen, stop) = (count.clone(), target.clone());
let mut fixture = Fixture::new(move |ui| {
let titles = vec![MenuTitle::new("&Edit", |ui| {
MenuItem::command(EditCommands::Undo).show(ui);
MenuItem::new("&Zoom").show(ui);
})];
MenuBar::new("Main menu", titles).show(ui);
craft_ui::layout_components::Stack::new().command_scope(<BarKeysCommand as craft_ui::contract::CommandSet>::SCOPE).show(ui, |ui, cx| {
while cx.take_command::<BarKeysCommand>().is_some() {
seen.set(seen.get() + 1);
}
stop.set(Some(craft_ui::buttons::Button::new("Target").show(ui).id));
});
});
fixture.settle();
craft_ui::runtime::focus::request(fixture.ctx(), craft_ui::runtime::focus::FocusTarget::Id(target.get().expect("the button ran")));
fixture.settle();
let open_edit = |fixture: &mut Fixture| {
let edit = fixture.by_label("Edit").expect("the Edit title");
fixture.click(&edit);
fixture.settle();
assert!(fixture.by_label("Zoom").is_some(), "Edit is open");
};
open_edit(&mut fixture);
fixture.key(egui::Key::P, egui::Modifiers::COMMAND | egui::Modifiers::ALT);
fixture.settle();
assert_eq!(count.get(), 1, "the shortcut runs once with the menu open, in the scope focus came from");
assert!(fixture.by_label("Zoom").is_none(), "and closes the menu");
assert_eq!(fixture.focused_stop().map(|(id, _)| id), target.get(), "focus is back on the stop that held it");
open_edit(&mut fixture);
// A mnemonic reads the typed text, as the open menu's other letters do.
fixture.type_text("z");
fixture.settle();
assert!(fixture.by_label("Zoom").is_none(), "a plain letter still picks the row it marks, which closes the menu");
assert_eq!(count.get(), 1, "and runs no shortcut");
assert_eq!(fixture.focused_stop().map(|(id, _)| id), target.get());
}
/// ⌘Z and ⌘C are the Help search field's own editing chords: with the field focused they stay with it, Help stays open,
/// and no app command runs (#9314). The text-field rule of `holds_press` meets the command-chord rule of an open menu
/// here.
#[trial]
fn undo_and_copy_stay_with_the_help_search_field() {
let mut rig = rig();
rig.click("Help");
rig.fixture.type_text("und");
rig.fixture.settle();
let search = rig.fixture.focused_stop().map(|(id, _)| id);
assert!(search.is_some() && search != rig.field.get(), "Help opens with its search field focused");
for key in [egui::Key::Z, egui::Key::C] {
rig.fixture.key(key, egui::Modifiers::COMMAND);
rig.fixture.settle();
assert!(rig.fixture.by_label("About").is_some(), "⌘{key:?} keeps Help open");
assert_eq!(rig.fixture.focused_stop().map(|(id, _)| id), search, "⌘{key:?} keeps the focus in the search field");
}
assert_eq!(*rig.text.borrow(), "helloabc", "no app Undo ran in the field that held focus before Help opened");
}
/// A bar whose Help searches the target scope's Toggle, then the Target button inside that scope; returns the count
/// of Toggle runs and the button's id.
fn scoped_rig() -> ScopedRig {
@@ -183,3 +251,35 @@ fn the_help_search_takes_its_editing_keys() {
fixture.settle();
assert!(field_reads(&fixture, "txo"), "Left moves the caret before the last letter");
}
/// A field inside an open menu keeps its own edit menu: Cut picked from the Help search field's edit menu cuts the
/// search text, not the text of the field that held focus before Help opened, and closes only the edit menu.
#[trial]
fn cut_from_the_help_search_fields_edit_menu_cuts_the_search_text() {
use craft_ui::testing::pointer;
let mut rig = rig();
rig.click("Help");
rig.fixture.type_text("und");
rig.fixture.key(egui::Key::A, egui::Modifiers::COMMAND);
rig.fixture.settle();
let held = rig.fixture.focused_stop().map(|(id, _)| id);
// Well after the title click: egui counts presses of any button into one click run.
rig.fixture.advance(1.0);
let search = rig.fixture.by_label("Search menus").expect("the search field").center();
rig.fixture.frame(vec![pointer::secondary(search, true)]);
rig.fixture.frame(vec![pointer::secondary(search, false)]);
rig.fixture.settle();
let cut = rig.fixture.by_label("Cut").expect("the search field's edit menu");
assert!(!rig.fixture.tree().is_disabled_key(cut.node), "Cut follows the search field's selection");
let at = cut.center();
let mut copied = Vec::new();
let click = [vec![pointer::moved(at)], vec![pointer::press(at)], vec![pointer::release(at)]];
for events in click.into_iter().chain(std::iter::repeat_n(Vec::new(), 8)) {
rig.fixture.frame(events);
copied.extend_from_slice(rig.fixture.copied());
}
assert_eq!(copied, ["und"], "Cut takes the search text");
assert_eq!(*rig.text.borrow(), "helloabc", "and leaves the field under the menus alone");
assert!(rig.fixture.by_label("About").is_some(), "the pick closes only the edit menu: Help stays open");
assert_eq!(rig.fixture.focused_stop().map(|(id, _)| id), held, "focus is back in the search field");
}
+2 -1
View File
@@ -1,5 +1,6 @@
//! Which desktop and backend the window opens on, read from the environment and, on Wayland, the
//! compositor's registry; and, with the `ui` feature, whether a window fits its monitor (`fits`).
//! compositor's registry; and, with the `ui` feature, whether a window fits its monitor (`fits`)
//! and the part of it the user can see above the taskbar (`visible_part`).
#[cfg(feature = "ui")]
mod work_area;
+132 -9
View File
@@ -1,14 +1,19 @@
//! Whether a window fits its monitor.
//! Whether a window fits its monitor, and the part of a window the user can see and reach.
//!
//! egui doesn't expose the monitor's work area (the screen less the taskbar, Dock or panel), only
//! the monitor's size. [`TASKBAR`] is the room kept free at the monitor's bottom edge.
//! the monitor's size and the window's position on the desktop. [`TASKBAR`] is the room kept free
//! at the monitor's bottom edge. A window can be larger than its display, and menus sized by the
//! window's content rect then run under the taskbar: [`visible_part`] is the content rect cut to
//! the monitor less that room.
use egui::{Rect, Vec2, ViewportInfo};
use egui::{Rect, Vec2, ViewportInfo, pos2, vec2};
/// Room kept free at the monitor's bottom edge for a taskbar or Dock egui can't see (the Windows
/// taskbar is 40–48 pt tall; a bottom Dock about as much).
// pc: crates/ui-egui/src/work_area.rs:17 `TASKBAR`.
pub const TASKBAR: f32 = 48.0;
/// Below this, the guess about where the monitor is went wrong: use the whole window.
const MIN_VISIBLE: f32 = 160.0;
/// Whether a window of outer size `outer` fits `monitor`: `outer.x <= monitor.x + 0.5` and
/// `outer.y <= monitor.y - TASKBAR + 0.5`.
@@ -24,21 +29,139 @@ pub enum WindowState {
Normal,
/// Maximized.
Maximized,
/// Full screen.
/// Full screen, which covers the taskbar on purpose: all of it can be seen.
FullScreen,
}
impl WindowState {
/// The state `info` reports.
pub fn of(info: &ViewportInfo) -> Self {
let _ = info;
todo!("tp.T12")
if info.fullscreen == Some(true) {
Self::FullScreen
} else if info.maximized == Some(true) {
Self::Maximized
} else {
Self::Normal
}
}
}
/// The part of `content` that is visible on a monitor of size `monitor` for a window in `state` with inner rect
/// `inner`; the whole of `content` when the monitor or the position is unknown.
/// `inner` (the content's rect on the desktop), both in egui points; the whole of `content` when the monitor is
/// unknown or the input makes no sense.
// pc: crates/ui-egui/src/work_area.rs:24 `visible_part`.
pub fn visible_part(content: Rect, monitor: Option<Vec2>, inner: Option<Rect>, state: WindowState) -> Rect {
let _ = (content, monitor, inner, state);
todo!("tp.T12")
let Some(m) = monitor else { return content };
if state == WindowState::FullScreen || !m.x.is_finite() || !m.y.is_finite() || m.x < 1.0 || m.y < 1.0 {
return content;
}
// A maximized window is usually inside the work area already, but not always (#3737): on X11
// a window manager that doesn't reserve a panel's space (a panel without a strut) maximizes it
// to the whole monitor, and the panel then covers its bottom. Where the window is known, it is
// checked like any other; only a maximized window with no position (Wayland) is taken to fit.
if state == WindowState::Maximized && inner.is_none() {
return content;
}
// #3737: Wayland never tells a window where it is, so egui has no `inner_rect` there, only the
// monitor's size. A window bigger than the monitor less the taskbar still runs under it
// wherever it is: at best its content starts at the monitor's top, so at most that much of it
// can be seen.
let Some(inner) = inner else {
let room = vec2(m.x, m.y - TASKBAR);
return trusted(content, Rect::from_min_size(content.min, room));
};
if !inner.min.is_finite() || !inner.max.is_finite() {
return content;
}
// Only the monitor's size is known, not where it is on the desktop: assume monitors tile the
// desktop by their size (true for one monitor, and for side-by-side ones of the same size).
let c = inner.center();
let origin = pos2((c.x / m.x).floor() * m.x, (c.y / m.y).floor() * m.y);
let screen = Rect::from_min_size(origin, m);
let usable = Rect::from_min_max(screen.min, pos2(screen.max.x, screen.max.y - TASKBAR));
// Desktop → window coordinates.
let shift = content.min - inner.min;
trusted(content, usable.translate(shift))
}
/// `content` cut to `usable`, unless that leaves too little to be a sensible guess.
fn trusted(content: Rect, usable: Rect) -> Rect {
let visible = content.intersect(usable);
if !visible.is_positive() || visible.height() < MIN_VISIBLE.min(content.height()) || visible.width() < MIN_VISIBLE.min(content.width()) {
return content;
}
visible
}
#[cfg(test)]
mod tests {
use super::*;
use WindowState::{FullScreen, Maximized, Normal};
const MONITOR: Vec2 = vec2(1366.0, 768.0);
fn window(x: f32, y: f32, w: f32, h: f32) -> (Rect, Rect) {
(Rect::from_min_size(pos2(0.0, 0.0), vec2(w, h)), Rect::from_min_size(pos2(x, y), vec2(w, h)))
}
#[test]
fn a_window_taller_than_its_display_is_cut_at_the_taskbar() {
// 1440 × 900 at the desktop origin on 1366 × 768: right and bottom are off-screen.
let (content, inner) = window(0.0, 0.0, 1440.0, 900.0);
assert_eq!(visible_part(content, Some(MONITOR), Some(inner), Normal), Rect::from_min_max(pos2(0.0, 0.0), pos2(1366.0, 768.0 - TASKBAR)));
// Below a 31 pt title bar, a full-height window reaches under the taskbar.
let (content, inner) = window(0.0, 31.0, 1366.0, 737.0);
assert_eq!(visible_part(content, Some(MONITOR), Some(inner), Normal).bottom(), 768.0 - TASKBAR - 31.0);
// A small window clear of the taskbar is all visible.
let (content, inner) = window(100.0, 80.0, 800.0, 500.0);
assert_eq!(visible_part(content, Some(MONITOR), Some(inner), Normal), content);
// On a second monitor to the right, the same.
let (content, inner) = window(1366.0 + 100.0, 0.0, 1440.0, 900.0);
assert_eq!(visible_part(content, Some(MONITOR), Some(inner), Normal).bottom(), 768.0 - TASKBAR);
}
#[test]
fn maximized_unknown_or_nonsense_input_keeps_the_window() {
let (content, inner) = window(0.0, 0.0, 1440.0, 900.0);
assert_eq!(visible_part(content, Some(MONITOR), Some(inner), FullScreen), content, "full screen covers the taskbar on purpose");
assert_eq!(visible_part(content, None, Some(inner), Normal), content);
assert_eq!(visible_part(content, Some(vec2(f32::NAN, 768.0)), Some(inner), Normal), content);
assert_eq!(visible_part(content, Some(vec2(0.0, 0.0)), Some(inner), Normal), content);
assert_eq!(visible_part(content, Some(MONITOR), Some(Rect::from_min_size(pos2(f32::INFINITY, 0.0), vec2(10.0, 10.0))), Normal), content);
// A guess that would leave almost nothing visible is not trusted.
let (content, inner) = window(0.0, 600.0, 1000.0, 300.0);
assert_eq!(visible_part(content, Some(MONITOR), Some(inner), Normal), content);
}
#[test]
fn a_maximized_window_under_a_panel_is_still_cut_at_the_taskbar() {
// #3737, X11: the window manager maximized the window to the whole 1920 × 1080 monitor
// without reserving the bottom panel's space, so the panel covers it.
for scale in [1.0_f32, 1.5] {
let monitor = vec2(1920.0, 1080.0) / scale;
let content = Rect::from_min_size(pos2(0.0, 0.0), monitor);
let bottom = monitor.y - TASKBAR;
assert_eq!(visible_part(content, Some(monitor), Some(content), Maximized).bottom(), bottom, "at {scale}×");
// A window manager that reserves the panel: the maximized window already ends above it.
let fitted = Rect::from_min_size(pos2(0.0, 0.0), vec2(monitor.x, bottom));
assert_eq!(visible_part(fitted, Some(monitor), Some(fitted), Maximized), fitted, "at {scale}×");
// Full screen is meant to cover the panel.
assert_eq!(visible_part(content, Some(monitor), Some(content), FullScreen), content, "at {scale}×");
}
}
#[test]
fn an_unknown_window_position_still_keeps_clear_of_the_taskbar() {
// #3737, Wayland: only the monitor's size is known. A window taller than the monitor less
// the taskbar can be seen at most down to there, wherever it is.
let content = Rect::from_min_size(pos2(0.0, 0.0), vec2(1366.0, 740.0));
assert_eq!(visible_part(content, Some(MONITOR), None, Normal), Rect::from_min_max(pos2(0.0, 0.0), pos2(1366.0, 768.0 - TASKBAR)));
let big = Rect::from_min_size(pos2(0.0, 0.0), vec2(1440.0, 900.0));
assert_eq!(visible_part(big, Some(MONITOR), None, Normal), Rect::from_min_max(pos2(0.0, 0.0), pos2(1366.0, 768.0 - TASKBAR)));
// One that fits, or a maximized one, is all visible.
let small = Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 600.0));
assert_eq!(visible_part(small, Some(MONITOR), None, Normal), small);
assert_eq!(visible_part(content, Some(MONITOR), None, Maximized), content);
assert_eq!(visible_part(content, Some(MONITOR), None, FullScreen), content);
}
}