diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 846b8aaec..b13108b7b 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -34,9 +34,10 @@ pub struct FrameInput { pub latched: Mods, /// The window in which the app's own egui code shows a modal this frame (a dialog the app draws itself, not a /// framework layer). It blocks the app's other windows as a framework app-modal layer open in it does: their - /// presses, keys, wheel and text go nowhere, a press there brings the modal's window forward, and they refuse to - /// close. A panel floated into a window of its own is one of them. `None` (the default) when the app shows no such - /// modal; set every frame from the app's own state. + /// presses, keys, wheel and text go nowhere, a press there brings the modal's window forward, they refuse to close, + /// and the modal's window takes the keyboard if one of them has it when the modal opens. A panel floated into a + /// window of its own is one of them. `None` (the default) when the app shows no such modal; set every frame from + /// the app's own state. pub app_modal: Option, /// Whether the window system's input reaches the OS windows the runtime hosts. pub window_input: WindowInput, diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index 9cc9b4376..4d3bb4b1c 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -5,7 +5,7 @@ use crate::runtime::cursor; use crate::runtime::egui::input::{self as raw_input, RawInput}; -use crate::runtime::egui::{injected, pass, viewports}; +use crate::runtime::egui::{injected, pass, repaint, viewports}; use crate::runtime::frame::PerViewport; use crate::runtime::ime; use crate::runtime::overlay; @@ -56,6 +56,11 @@ pub(crate) use viewport::{PopupOpen, ViewportOpen, close_popup, place_popup, sho /// Seconds between writes of a changed placement store. const FLUSH_SECONDS: f64 = 1.0; +/// Seconds after an app-modal layer opens until its window takes the keyboard from a window it blocks: an OS dialog +/// the app opens with the modal (a file dialog) takes the focus a little later, and a focus request sent before then +/// could bring the modal's window over it. +const MODAL_FOCUS_WAIT: f64 = 0.2; + /// Install-time inputs and the cross-window records of one context. #[derive(Default)] pub(crate) struct Shared { @@ -93,6 +98,8 @@ pub(crate) struct Shared { lowered: bool, /// Where the raise of the modal's window above the palettes it lowered stands. raise: Raise, + /// The pass time at which the modal's window takes the keyboard from a window it blocks, until then. + modal_focus: Option, /// Whether the root window showed an app-modal or popup layer in the last root pass: palette windows are hidden /// meanwhile, and one that opens meanwhile opens hidden. palettes_yield: bool, @@ -533,18 +540,23 @@ pub(crate) fn pressed_elsewhere(ctx: &Context, popup: ViewportId, appeared: bool if viewport == opener { return false; } - // A press in a popup window opened from the popup, at any depth, is inside its family. - let mut at = Some(viewport); - while let Some(window) = at { - if window == popup { - return false; - } - at = PerViewport::::with_existing(ctx, window, |record| record.opener).flatten(); - } - true + // A press in a popup window opened from the popup is inside its family. + !in_family(ctx, viewport, popup) }) } +/// Whether `viewport`'s window is `window` or a popup window opened from it, at any depth. +fn in_family(ctx: &Context, viewport: ViewportId, window: ViewportId) -> bool { + let mut at = Some(viewport); + while let Some(shown) = at { + if shown == window { + return true; + } + at = PerViewport::::with_existing(ctx, shown, |record| record.opener).flatten(); + } + false +} + /// Whether no window of the app has focus, as the last frame's windows reported. pub(crate) fn app_away(ctx: &Context) -> bool { shared(ctx, |shared| shared.app.away) @@ -674,6 +686,8 @@ fn flush_store(ctx: &Context) { /// window reports focus: the batch that took focus from one window gave it to no other. /// /// Once a palette has stood lowered under an app-modal layer, the modal's window is raised above it, once per modal. +/// A window that has the keyboard when a modal comes to block it drops the keys the modal needs, so the modal's window +/// takes the keyboard from it ([`focus_modal`]). fn follow_activity(ctx: &Context) { let windows = viewports::reported(ctx); let focused: Vec = windows @@ -683,13 +697,18 @@ fn follow_activity(ctx: &Context) { .collect(); let modal = overlay::app_modal_viewport(ctx); let minimized = viewports::current(ctx).minimized; + let now = pass::now(ctx); let (repaint, raise) = shared(ctx, |shared| { shared.stacking.retain(|viewport| windows.iter().any(|(open, _)| open == viewport) && !focused.contains(viewport)); shared.stacking.extend(&focused); let app = AppState { away: focused.is_empty(), modal, minimized }; let lowered = std::mem::take(&mut shared.lowered); + let modal_changed = app.modal != shared.app.modal; + if modal_changed { + shared.modal_focus = app.modal.map(|_| now + MODAL_FOCUS_WAIT); + } let (step, raise) = match shared.raise { - _ if app.modal != shared.app.modal => (Raise::Waiting, None), + _ if modal_changed => (Raise::Waiting, None), Raise::Waiting if lowered => (Raise::Due, None), Raise::Due => (Raise::Done, app.modal), step => (step, None), @@ -701,11 +720,36 @@ fn follow_activity(ctx: &Context) { if let Some(modal) = raise { act(ctx, modal, WindowAction::Raise); } + if let Some(modal) = modal { + focus_modal(ctx, modal, &windows); + } if repaint { ctx.request_repaint(); } } +/// Gives the window of `modal`, the app's top modal, the OS focus when one of `windows` that it blocks still has it +/// [`MODAL_FOCUS_WAIT`] after the modal opened; once per modal. With the focus elsewhere by then (in the modal's own +/// window, in an OS dialog, in another app) nothing is sent. +fn focus_modal(ctx: &Context, modal: ViewportId, windows: &[(ViewportId, viewports::Facts)]) { + let Some(due) = shared(ctx, |shared| shared.modal_focus) else { return }; + let blocked = |viewport: ViewportId| overlay::modal_viewport(ctx, viewport) == Some(modal) && !in_family(ctx, viewport, modal); + let wait = due - pass::now(ctx); + if wait > 0.0 { + if windows.iter().any(|(viewport, _)| blocked(*viewport)) { + repaint::request_after(ctx, ViewportId::ROOT, wait); + } + return; + } + shared(ctx, |shared| shared.modal_focus = None); + let focused = |viewport: ViewportId| { + PerViewport::::with_existing(ctx, viewport, |record| record.facts.is_some_and(|facts| facts.focus_reported)).unwrap_or(false) + }; + if !focused(modal) && windows.iter().any(|(viewport, _)| focused(*viewport) && blocked(*viewport)) { + act(ctx, modal, WindowAction::Focus); + } +} + /// Records whether the root window shows an app-modal or popup layer: palette windows hide meanwhile, so a click on a /// palette cannot bring it over the layer, and the palettes' mounts hide and show them as they do for the app's state /// ([`show_viewport`]), asked for by a repaint when it changes. Runs at the end of the root pass, where the diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 0a9b57e81..c423ae089 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -1,10 +1,10 @@ -//! `runtime::windows`: the input hook per viewport, window info per viewport, the press release after an OS -//! resize (H4), the raise of a modal's window, the mount of a full-window container (in a window of its own, or in a -//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, a -//! palette's level under a modal and its visibility while the main window is minimized, injected keys across a focus -//! loss, non-finite injected points, a repeated injected press, the window that has the keys, a wheel with no known -//! pointer, the placement of a minimized window, the root frame decided again, a held close, `act`, and a hosted -//! window's Control-click and window-input policy. +//! `runtime::windows`: the input hook per viewport, window info per viewport, the press release after an OS resize +//! (H4), the raise of a modal's window and the keyboard it takes from a window it blocks, the mount of a full-window +//! container (in a window of its own, or in a full-screen or Wayland-maximized main window), the size of a +//! content-sized window, the app id of child windows, a palette's level under a modal and its visibility while the main +//! window is minimized, injected keys across a focus loss, non-finite injected points, a repeated injected press, the +//! window that has the keys, a wheel with no known pointer, the placement of a minimized window, the root frame decided +//! again, a held close, `act`, and a hosted window's Control-click and window-input policy. use craft_behavior::{Cursor, CursorIcon, PointerButton, Sense}; use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind}; @@ -328,6 +328,120 @@ fn an_app_modal_in_one_window_blocks_the_cursor_and_the_close_of_the_others() { } } +/// Window facts with the focus as given, at a place the window system tells. +fn focus(on: bool) -> ViewportInfo { + ViewportInfo { focused: Some(on), inner_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::splat(300.0))), ..ViewportInfo::default() } +} + +fn on_x11() -> Windows { + Windows::with(InstallSpec::new(ShellInfo::default().backend(Backend::X11), Arc::new(FakeSystem::new()))) +} + +/// How many focus requests `out` sent to `viewport`. +fn focus_requests(out: &Out, viewport: ViewportId) -> usize { + out.commands.iter().filter(|(id, command)| *id == viewport && *command == ViewportCommand::Focus).count() +} + +/// Frames that last longer than a modal's window waits before it takes the keyboard. +const PAST_THE_WAIT: usize = 40; + +/// The app's own modal that opens while a window it blocks has the keyboard (a command typed in a floated panel opens +/// the save prompt in the main window) gets the keys it needs: its window takes the OS focus from the blocked one, +/// once, and the wait before it wakes an idle app. Nothing is sent when no blocked window has the focus by then (an OS +/// dialog that opened with the modal took it, or the modal's window has it) or the modal closed meanwhile. +#[trial] +fn an_app_modal_takes_the_keyboard_from_a_window_it_blocks() { + // The frames after the modal opens in which the main window, which shows it, got a focus request, with the main + // window and a child window focused as given and `before` run before each frame. + let requests = |root: bool, float: bool, before: &dyn Fn(&Windows, usize)| -> Vec { + let windows = on_x11(); + windows.root_info(focus(root)); + windows.child_info(focus(float)); + let frame = || windows.frame(vec![], vec![], |ui| ui.ctx().show_viewport_immediate(child(), ViewportBuilder::default(), |_, _| {})); + for _ in 0..4 { + frame(); + } + windows.app_modal(Some(ViewportId::ROOT)); + (0..PAST_THE_WAIT) + .flat_map(|at| { + before(&windows, at); + vec![at; focus_requests(&frame(), ViewportId::ROOT)] + }) + .collect() + }; + let none: [usize; 0] = []; + let sent = requests(false, true, &|_, _| {}); + let &[handed] = sent.as_slice() else { panic!("the main window takes the keyboard from the float once: {sent:?}") }; + assert!(handed > 1, "not before an OS dialog that opens with the modal could take it: frame {handed}"); + let closes = |windows: &Windows, at| { + if at == handed { + windows.app_modal(None); + } + }; + assert_eq!(requests(false, true, &closes), none, "the modal closed meanwhile"); + let os_dialog = |windows: &Windows, at| { + if at == 1 { + windows.child_info(focus(false)); + } + }; + assert_eq!(requests(false, true, &os_dialog), none, "an OS dialog took the focus"); + assert_eq!(requests(false, false, &|_, _| {}), none, "no window of the app has the focus"); + assert_eq!(requests(true, false, &|_, _| {}), none, "the modal's window has the focus"); + + let woken = Arc::new(Mutex::new(false)); + let settled = |windows: &Windows, at| { + if at == 2 { + let woken = woken.clone(); + windows.ctx.set_request_repaint_callback(move |info| *woken.lock().unwrap() |= !info.delay.is_zero()); + } + }; + requests(false, true, &settled); + assert!(*woken.lock().unwrap(), "an idle app wakes for the hand-over"); +} + +/// A framework modal in a window of its own takes the keyboard from the main window it blocks. +#[trial] +fn a_framework_modal_takes_the_keyboard_from_the_window_it_blocks() { + let windows = on_x11(); + windows.root_info(focus(true)); + windows.child_info(focus(false)); + let sent: usize = (0..PAST_THE_WAIT).map(|_| focus_requests(&modal_frame(&windows), child())).sum(); + assert_eq!(sent, 1, "once"); +} + +/// A popup window opened from the window that shows the app's modal keeps the keyboard. +#[trial] +fn a_popup_window_of_the_modals_window_keeps_the_keyboard() { + use craft_behavior::overlay::{Align, Side}; + use craft_ui::contract::overlay::{Anchor, Place}; + let windows = on_x11(); + windows.root_info(focus(false)); + windows.child_info(focus(true)); + let open = Cell::new(false); + let frame = || { + windows.frame(vec![], vec![], |ui| { + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |ui, _| { + if open.get() { + let anchor = Rect::from_min_size(Pos2::new(20.0, 20.0), Vec2::splat(10.0)); + let place = Place::anchored(Anchor::Rect(anchor), Side::Below, Align::Start); + let props = ContainerProps::new().mount(Mount::Layer(Overlay::menu().place(place))); + Modal { common: Common::new(), props }.id_salt("popup").show(ui, |_, _| {}); + } + }); + }) + }; + let palette = builder_titled(&frame(), "tool").0; + windows.app_modal(Some(palette)); + open.set(true); + frame(); + windows.child_info(focus(false)); + let outs: Vec = (0..PAST_THE_WAIT).map(|_| frame()).collect(); + let popup = outs.last().and_then(|out| out.builders.iter().map(|(id, _)| *id).find(|id| ![ViewportId::ROOT, palette].contains(id))); + let popup = popup.expect("the layer opened in the palette shows in a popup window"); + assert_eq!(windows.facts(popup).focused, Some(true), "the popup window has the keyboard"); + assert_eq!(outs.iter().map(|out| focus_requests(out, palette)).sum::(), 0, "the modal's window leaves it there"); +} + /// A window that a modal in another window blocks takes no wheel, as it takes no press or key: what is under the /// pointer there does not scroll. #[trial] diff --git a/docs/craft-framework.md b/docs/craft-framework.md index f6c9bdb46..e84081d62 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -166,7 +166,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | Quit | egui's quit shortcuts are cleared. ⌘Q (Ctrl+Q on Windows and Linux) is the default of the command `QuitCommand::Quit` (id `window.quit`), which the runtime runs from any source: it asks the root window to close through the close path below, so the app's close decision asks about unsaved work. It fires with a modal open; the close path then refuses under an app-modal layer. Its default is bound and yielded as F6 is; an app whose own shortcut table reads its quit key from egui unbinds it there. | | Close path | The runtime's window host owns the root window's close request. `embed::logic` asks the app through its closure, then hands the close to the platform quit where there is one (macOS). | | Wheel | `RootEnv::wheel_speed` scales each wheel delta once; a Ctrl or Cmd wheel keeps the device's distance. The install's `WheelModifiers` set egui's zoom and sideways modifiers. On Windows and Linux, a Ctrl+wheel in fractions of a notch (a point-unit one on Linux) is a touchpad pinch and arrives as `Event::Zoom`, at egui's Ctrl-scroll zoom speed: Windows hands a precision touchpad's pinch to apps only that way. Whole notches stay wheel events, except within 0.25 s of a pinch step. An app whose Ctrl+wheel does something else, or zooms at its own rate, sets `RootEnv::ctrl_wheel_pinch(false)` and reads the wheel events itself. | -| App modals | A modal the app draws with its own egui code blocks nothing outside egui by itself. While one shows, the app names its window each frame with `FrameInput::app_modal(Some(viewport))`: the app's other windows, panels floated into windows of their own among them, are then blocked as under a framework app-modal layer (their presses, keys, wheel and text are dropped, a press there brings the modal's window forward, and they refuse to close). | +| App modals | A modal the app draws with its own egui code blocks nothing outside egui by itself. While one shows, the app names its window each frame with `FrameInput::app_modal(Some(viewport))`: the app's other windows, panels floated into windows of their own among them, are then blocked as under a framework app-modal layer (their presses, keys, wheel and text are dropped, a press there brings the modal's window forward, they refuse to close, and the modal's window takes the keyboard if one of them has it when the modal opens). | | Input pacing | One press per pass: extra presses in one frame wait for the next passes. A press outside an open framework menu closes the menu and goes no further. After an OS resize of the window, the held pointer is released. | The window's keys are the ones the runtime routes to no component: an Escape or a plain Enter while nothing has the focus, neither a framework stop nor one of the app's own widgets or popups, and the arrows' nudge. The window's plain Enter also stays in egui's input. `with_window_intents` offers them to its closure while nothing has framework focus. The closure takes what it handles (`Intents::take(Intent::Cancel)`; `Intent` and the other types `Intents` reads are in `ui::runtime::keys`) and returns whether it took anything; the rest stays for later readers. A framework scope that ran earlier in the pass takes them first (an open dialog takes the Escape that closes it), so the app reads them last in its UI to see what no component took. App code that read `Key::Escape`, `Key::Tab`, F6 or F10 from egui while none of its own widgets had focus reads these intents and `FrameOutput::chrome_toggles` instead; its own focused widgets and popups keep reading Escape and the plain Enter from egui (Tab only where the widget keeps it or a popup is open), and no window intent comes of them. An Escape pressed in the OS window of a floated dock panel that nothing there takes, not even a reader of that window's intents, is the Cancel of the window the dock is in, in its next pass, so the app reads it where it reads its own; a popup or a modal open over the panel keeps it, and any other OS window (an app's own viewport, a dialog or document window) keeps its Escape to itself (`WindowSpec::hands_on_cancel`).