ui-contract: a host's window-input policy reaches every OS window the runtime hosts

FrameInput::window_input(WindowInput::Dropped) drops a hosted window's own
events and OS files in the input filter, before injected input joins, so an
agent-driven session's floated panels take only injected input. eframe runs
raw_input_hook for the main window only; the root's input stays the host's.
The test kit's Windows takes the policy; trials cover the drop and a macOS
Control+Click in a hosted window.
This commit is contained in:
Dylan M. Taylor committed 2026-11-24 09:55:46 -05:00
1 parent 7762aab37b
commit badd2a8822
5 files changed
+150 -8

No files matched your search

@@ -3,6 +3,7 @@
//! A family crate hands the filter what it learned outside the window (a key equivalent the platform's menu
//! took) and the filter puts it into the viewport's input in the hook, ahead of the stages that read keys, so it
//! reaches the application as the key press the user made. No family crate touches `RawInput` or `egui::Event`.
//! The host's window-input policy (`FrameInput::window_input`) is applied here too, first.
use std::collections::HashMap;
@@ -12,6 +13,7 @@ use egui::{Context, Event, ViewportId};
use super::injected::{egui_modifiers, key_press, key_release};
use super::memory::Service;
use super::repaint;
use crate::runtime::frame::WindowInput;
use crate::runtime::windows::KeyEquivalent;
#[derive(Default)]
@@ -35,8 +37,10 @@ fn repeat_running_pass(ctx: &Context, viewport: ViewportId, reason: &'static str
}
}
/// The input hook's filter step: adds the queued key equivalents of `input.viewport_id` to `input.events`.
/// The input hook's filter step: drops a hosted window's input under [`WindowInput::Dropped`], then adds the queued
/// key equivalents of `input.viewport_id` to `input.events`.
pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) {
drop_window_input(ctx, input);
dismiss_input(ctx, input);
let queued = Service::<Pending>::run(ctx, |pending| pending.by_viewport.remove(&input.viewport_id));
let Some(queued) = queued else { return };
@@ -51,6 +55,18 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) {
}
}
/// The policy step: under [`WindowInput::Dropped`] a hosted window's input keeps none of the window system's events or
/// files. It runs before the injected step joins the input, so injected input still reaches the window. The root's
/// input is the host's own, in eframe's `raw_input_hook`, where the host may already have added its own events.
fn drop_window_input(ctx: &Context, input: &mut egui::RawInput) {
if input.viewport_id == ViewportId::ROOT || crate::runtime::frame::window_input(ctx) != WindowInput::Dropped {
return;
}
input.events.clear();
input.hovered_files.clear();
input.dropped_files.clear();
}
/// Puts the press of `chord` ahead of its key-up when that is already in the input, else last; `tap` adds the
/// release right after it.
fn insert_press(input: &mut egui::RawInput, chord: Chord, platform: craft_keymap::Platform, tap: bool) {
+29 -1
View File
@@ -32,12 +32,35 @@ pub struct FrameInput {
pub host: Option<Arc<Host>>,
/// The modifiers the app's own tablet or latched-key reader holds down beyond the window's input.
pub latched: Mods,
/// Whether the window system's input reaches the OS windows the runtime hosts.
pub window_input: WindowInput,
}
/// Whether the window system's input reaches the OS windows the runtime hosts beside the root (a panel floated into
/// its own window). eframe gives the host only the root's raw input (`App::raw_input_hook`), so the host applies its
/// policy to the root there and gives it here for the rest.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum WindowInput {
/// The window system's input reaches every hosted window.
#[default]
Live,
/// An agent-driven session: a hosted window's events, hovered files and dropped files are dropped before any
/// stage reads them, so only the runtime's injected input reaches it. Its window facts (size, focus, close
/// requests) stay.
Dropped,
}
impl FrameInput {
/// A frame with `root` and no host.
pub fn new(root: RootEnv) -> Self {
FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE }
FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE, window_input: WindowInput::Live }
}
/// Sets whether the window system's input reaches the hosted windows.
pub fn window_input(mut self, window_input: WindowInput) -> Self {
self.window_input = window_input;
self
}
/// Sets the command input.
@@ -416,6 +439,11 @@ pub(crate) fn root_input(ctx: &Context) -> (WheelSpeed, AltCodePages) {
pass_state::with::<FrameState, _>(ctx, |state| state.input.as_ref().map(|input| (input.root.wheel, input.root.alt_codes))).unwrap_or_default()
}
/// The frame's window-input policy; `Live` before the app sets any input.
pub(crate) fn window_input(ctx: &Context) -> WindowInput {
pass_state::with::<FrameState, _>(ctx, |state| state.input.as_ref().map(|input| input.window_input)).unwrap_or_default()
}
/// How far a press may move and still be a click, in points: the app's hit tolerances (`HitSizes::slop`). egui's own
/// click options stay the app's.
pub(crate) fn slop(ctx: &Context) -> f32 {
+89 -2
View File
@@ -3,7 +3,8 @@
//! 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, and `act`.
//! 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};
@@ -19,7 +20,7 @@ use craft_ui::testing::pointer::{moved, press, release, wheel};
use craft_ui::testing::windows::{FakeSystem, NoWindows};
use craft_ui::testing::{Fixture, trial};
use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen};
use craft_ui_test_kit::windows::{Out, Windows};
use craft_ui_test_kit::windows::{FilesOver, Out, Windows};
use craft_window::policy::{Decision, Desktop, DesktopKind, Frame, MacInset, Runtime, TitleBarPref};
use craft_window::restore::Store;
use egui::{Event, Pos2, Rect, Response, UserAttentionType, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
@@ -1310,3 +1311,89 @@ fn a_title_with_nul_reaches_the_window_without_it() {
assert_eq!(send("Notes.docx"), ["Notes.docx"], "a changed title is sent");
assert_eq!(send("\0Report\0\0 draft.docx\0"), ["Report draft.docx"], "a title changed back is sent again, every NUL dropped");
}
/// What the hosted child window's passes saw: its last pass's pointer, events and OS files, and the clicks since the
/// last reset.
#[derive(Clone, Copy, Debug, Default)]
struct ChildSeen {
pointer: bool,
events: usize,
files: usize,
primary: bool,
secondary: bool,
}
/// One frame of a root window that hosts the child window as an OS window with a 200-point click area at its origin:
/// `root` events go to the root, `events` and `dropped` files to the child. Returns whether the root knows the pointer.
fn hosted_frame(windows: &Windows, root: Vec<Event>, events: Vec<Event>, dropped: Vec<String>, seen: &Cell<ChildSeen>) -> bool {
let root_pointer = Cell::new(false);
windows.frame_with_files(root, events, FilesOver::Child, Vec::new(), dropped, |ui| {
root_pointer.set(ui.ctx().input(|input| input.pointer.latest_pos().is_some()));
ui.ctx().show_viewport_immediate(child(), ViewportBuilder::default(), |cui, _| {
let area = cui.allocate_rect(Rect::from_min_size(Pos2::ZERO, Vec2::splat(200.0)), egui::Sense::click());
let (pointer, events, files) = cui.ctx().input(|input| {
(input.pointer.latest_pos().is_some(), input.events.len(), input.raw.hovered_files.len() + input.raw.dropped_files.len())
});
let was = seen.get();
seen.set(ChildSeen {
pointer,
events,
files,
primary: was.primary || area.clicked(),
secondary: was.secondary || area.secondary_clicked(),
});
});
});
root_pointer.get()
}
/// A panel floated into its own OS window gets a macOS Control+Click as a secondary click, as the main window does:
/// the Control-click mapping runs on every hosted window's input, which eframe's `raw_input_hook` never sees.
#[trial]
fn a_control_click_in_a_hosted_window_is_a_secondary_click_on_macos() {
let shell = ShellInfo::default().os(Os::Mac).caps(Caps::native(Os::Mac));
let windows = Windows::with(InstallSpec::new(shell, Arc::new(FakeSystem::new())));
let seen = Cell::new(ChildSeen::default());
let at = Pos2::new(50.0, 50.0);
let control = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::CTRL };
hosted_frame(&windows, vec![], vec![], vec![], &seen);
hosted_frame(&windows, vec![], vec![moved(at)], vec![], &seen);
hosted_frame(&windows, vec![], vec![control(true)], vec![], &seen);
hosted_frame(&windows, vec![], vec![control(false)], vec![], &seen);
hosted_frame(&windows, vec![], vec![], vec![], &seen);
assert!(seen.get().secondary && !seen.get().primary, "the Control+Click is a secondary click there: {:?}", seen.get());
}
/// `WindowInput::Dropped` (an agent-driven session): a hosted window's own events and OS files reach none of its
/// passes, while the root's input stays the host's and injected input still reaches the hosted window. Under `Live`
/// the same input reaches it.
#[trial]
fn dropped_window_input_leaves_a_hosted_window_only_injected_input() {
use craft_ui::runtime::frame::WindowInput;
let at = Pos2::new(50.0, 50.0);
for policy in [WindowInput::Live, WindowInput::Dropped] {
let windows = Windows::new();
windows.window_input(policy);
let seen = Cell::new(ChildSeen::default());
hosted_frame(&windows, vec![], vec![], vec![], &seen);
let root_pointer = hosted_frame(&windows, vec![moved(at)], vec![moved(at)], vec!["clip.mov".to_owned()], &seen);
assert!(root_pointer, "{policy:?}: the root's input is the host's");
let after_move = seen.get();
hosted_frame(&windows, vec![], vec![press(at)], vec![], &seen);
hosted_frame(&windows, vec![], vec![release(at)], vec![], &seen);
hosted_frame(&windows, vec![], vec![], vec![], &seen);
let live = policy == WindowInput::Live;
assert_eq!(after_move.pointer, live, "{policy:?}: the window's pointer move {after_move:?}");
assert_eq!(after_move.events > 0, live, "{policy:?}: the window's events {after_move:?}");
assert_eq!(after_move.files > 0, live, "{policy:?}: the files dropped on the window {after_move:?}");
assert_eq!(seen.get().primary, live, "{policy:?}: the window's own click {:?}", seen.get());
seen.set(ChildSeen::default());
let host = WindowHost::of(&windows.ctx);
host.inject_click(child(), Pos2::new(60.0, 60.0), PointerButton::Primary, 1, Mods::NONE, false);
for _ in 0..8 {
hosted_frame(&windows, vec![], vec![], vec![], &seen);
}
assert!(seen.get().primary, "{policy:?}: the injected click reaches the window: {:?}", seen.get());
}
}
+14 -3
View File
@@ -5,7 +5,7 @@
use craft_host::target::ShellInfo;
use craft_ui::runtime::InstallSpec;
use craft_ui::runtime::env::RootEnv;
use craft_ui::runtime::frame::{FrameInput, set_input};
use craft_ui::runtime::frame::{FrameInput, WindowInput, set_input};
use craft_ui::testing::Frames;
use craft_ui::testing::access::{AccessTree, tree_of};
use craft_ui::testing::windows::FakeSystem;
@@ -281,6 +281,7 @@ pub struct Windows {
pub ctx: Context,
root_info: RefCell<ViewportInfo>,
root: RefCell<RootEnv>,
window_input: Cell<WindowInput>,
}
impl Default for Windows {
@@ -309,7 +310,12 @@ impl Windows {
COMMANDS.with(|kept| kept.borrow_mut().clear());
BUILDERS.with(|kept| kept.borrow_mut().clear());
NOW.with(|now| now.set(0.0));
Windows { ctx, root_info: RefCell::new(ViewportInfo::default()), root: RefCell::new(RootEnv::default()) }
Windows {
ctx,
root_info: RefCell::new(ViewportInfo::default()),
root: RefCell::new(RootEnv::default()),
window_input: Cell::new(WindowInput::Live),
}
}
/// The window facts child passes report from now on.
@@ -323,6 +329,11 @@ impl Windows {
with_facts(viewport, |info| info.clone())
}
/// The window-input policy every following frame's input gives, as a host's `FrameInput::window_input` does.
pub fn window_input(&self, policy: WindowInput) {
self.window_input.set(policy);
}
/// The window facts the root viewport reports from now on.
pub fn root_info(&self, info: ViewportInfo) {
*self.root_info.borrow_mut() = info;
@@ -360,7 +371,7 @@ impl Windows {
CHILD_FILES.with(|files| *files.borrow_mut() = child_files);
TREES.with(|kept| kept.borrow_mut().clear());
SHAPES.with(|kept| kept.borrow_mut().clear());
set_input(&self.ctx, FrameInput::new(self.root.borrow().clone()));
set_input(&self.ctx, FrameInput::new(self.root.borrow().clone()).window_input(self.window_input.get()));
let mut input = RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, ROOT_SIZE)),
events: root,
+1 -1
View File
@@ -141,7 +141,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. `
| When | eframe method | Call |
| --- | --- | --- |
| Once, when the app is created | with the `CreationContext` | `embed::install(ctx, InstallSpec, &UiFonts)`: the runtime, then the app's fonts. Returns the font `Stack`. |
| Each frame | `raw_input_hook` | `embed::before_input(ctx, \|output\| { ...; input })`: the closure receives the `FrameOutput` of the frame before (fired commands, announcements, chrome toggles) and returns the `FrameInput` for this frame (`RootEnv`, command states, the `Host`). |
| Each frame | `raw_input_hook` | `embed::before_input(ctx, \|output\| { ...; input })`: the closure receives the `FrameOutput` of the frame before (fired commands, announcements, chrome toggles) and returns the `FrameInput` for this frame (`RootEnv`, command states, the `Host`). eframe runs the hook for the main window only: an app that drops the window system's input there (an agent-driven session) sets `FrameInput::window_input(WindowInput::Dropped)` too, and the runtime drops it in every other OS window it hosts, before injected input joins. macOS Control+Click is the runtime's in every window; the app does not map it. |
| Each frame | `logic`, after the app's own logic | `embed::logic(ctx, \|\| decision)`: the root window's close path. The closure runs only when the root window was asked to close, and returns `CloseDecision::Close` or `Hold`. |
| Each pass | `ui`, before the app's UI | `embed::before_ui(ctx, frame)`: hands the runtime the root's native window (eframe's `Frame`, or any `raw_window_handle::HasWindowHandle`) on Windows, where the runtime answers the window's hit test (resize edges, the title bar's move area, snap layouts on the maximize button), and fits the root window to its monitor once. Native only; it needs no eframe feature of the facade. |
| Each pass | `ui`, where the app draws its own document canvas | Optional: `ui::runtime::focus::host_canvas(ctx, id, KeyUse::CANVAS)` declares it as the window's canvas (Tab row below). |