diff --git a/crates/ui-contract/src/runtime/egui/injected.rs b/crates/ui-contract/src/runtime/egui/injected.rs index 78cfb8a03..f852748e2 100644 --- a/crates/ui-contract/src/runtime/egui/injected.rs +++ b/crates/ui-contract/src/runtime/egui/injected.rs @@ -92,9 +92,9 @@ pub(crate) fn text_frames(text: &str) -> Vec { vec![vec![text_event(text)]] } -/// A wheel turn of `delta` points with `modifiers`, as a mouse wheel reports it. -pub(crate) fn wheel(delta: Vec2, modifiers: Modifiers) -> Event { - Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta, phase: egui::TouchPhase::Move, modifiers, source: egui::MouseWheelSource::Wheel } +/// A wheel turn of `delta` in `unit` with `modifiers`, as a mouse wheel reports it. +pub(crate) fn wheel(unit: egui::MouseWheelUnit, delta: Vec2, modifiers: Modifiers) -> Event { + Event::MouseWheel { unit, delta, phase: egui::TouchPhase::Move, modifiers, source: egui::MouseWheelSource::Wheel } } /// What injected input holds down in a viewport: the modifiers, buttons and keys, where the pointer is, and the keys @@ -472,17 +472,23 @@ pub(crate) fn inject_key(ctx: &Context, viewport: ViewportId, key: Key, mods: Mo }); } -/// Queues a move to `at`, then a wheel turn of `delta` points, with `mods` held; the modifiers stay held after it. A +/// Queues a move to `at`, then a wheel turn of `delta` in `unit`, with `mods` held; the modifiers stay held after it. A /// non-finite `at` or `delta` queues nothing. -pub(crate) fn inject_wheel(ctx: &Context, viewport: ViewportId, at: Pos2, delta: Vec2, mods: Mods) { +pub(crate) fn inject_wheel(ctx: &Context, viewport: ViewportId, at: Pos2, delta: Vec2, unit: egui::MouseWheelUnit, mods: Mods) { let Some(at) = finite(at).filter(|_| delta.is_finite()) else { return }; let mods = platform_modifiers(ctx, mods); queue(ctx, viewport, |request| { request.move_to(at, mods, None); - request.step(mods, [wheel(delta, mods)]); + request.step(mods, [wheel(unit, delta, mods)]); }); } +/// Whether injected input holds `button` down in `viewport`, from the step that pressed it to the one that releases it +/// (between steps no event carries the hold). +pub(crate) fn held_button(ctx: &Context, viewport: ViewportId, button: egui::PointerButton) -> bool { + Service::::run(ctx, |injected| injected.held.get(&viewport).is_some_and(|held| held.buttons.contains(&button))) +} + /// Queues the release of what `released` names, at `at` (a move there first) or where the pointer is. Releasing /// everything lets the modifiers go too. Nothing held queues nothing. A non-finite `at` releases where the pointer is. pub(crate) fn inject_release(ctx: &Context, viewport: ViewportId, at: Option, released: Released) { diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index 82b9b96fc..eccfa7e52 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -5,7 +5,8 @@ use crate::runtime::cursor; use crate::runtime::egui::input::{self as raw_input, RawInput}; -use crate::runtime::egui::{pass, viewports}; +use crate::runtime::egui::{injected, pass, viewports}; +use crate::runtime::ime; use crate::runtime::frame::PerViewport; use crate::runtime::overlay; use crate::runtime::pass_state; @@ -15,7 +16,7 @@ use craft_window::desktop::Desktop; use craft_window::native::NativeWindow; use craft_window::policy::{Captions, Decision, Frame, LayoutWatch}; use craft_window::restore::Store; -use craft_window::system::WindowSystem; +use craft_window::system::{HeldButtons, WindowSystem}; use egui::{Context, Id, Pos2, Rect, Vec2, ViewportId}; use std::sync::{Arc, Mutex}; @@ -68,8 +69,8 @@ pub(crate) struct Shared { store: Option>>, /// The system pointer read in `set_input`. system_pointer: Option, - /// The primary button and the command modifier as the system told them in `set_input`; `None` where it does not. - system_primary: Option, + /// The mouse buttons and the command modifier as the system told them in `set_input`; `None` where it does not. + system_buttons: Option, system_command: Option, /// The window the OS moves for a drag it was handed where the platform tracks such moves /// ([`Caps::OS_MOVES_TRACKED`]), until the move ends. @@ -88,6 +89,9 @@ pub(crate) struct Shared { root_focused: bool, /// Whether no window of the app had focus when the last frame's windows had all reported. away: bool, + /// 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, /// The app's windows from the one focused longest ago to the one focused last: the stacking order of /// overlapping windows. stacking: Vec, @@ -107,8 +111,8 @@ pub(crate) struct Record { captions: Option, /// The level the window was opened with or last set to; a palette's egui level follows the app's activity. level: Option, - /// H4: whether the primary button is down as the viewport's events left the input hook. - primary_down: bool, + /// The buttons that are down as the viewport's events left the input hook. + buttons_down: Vec, /// Whether the user can resize the window; unknown for a window not opened by `show_viewport`. resizable: Option, /// Whether the window was opened hidden and its first pass has not run yet. @@ -218,15 +222,32 @@ pub(crate) fn set_input(ctx: &Context) { let system = shared(ctx, |shared| shared.system.clone()); let zoom = ctx.zoom_factor(); let pointer = system.as_ref().and_then(|system| system.desktop_pointer()).map(|[x, y]| Pos2::new(x, y) / zoom); - let (primary, command) = system.map_or((None, None), |system| (system.primary_held(), system.command_held())); + let buttons = system.as_ref().and_then(|system| system.buttons_held()); + let command = system.as_ref().and_then(|system| system.command_held()); for (viewport, facts) in viewports::reported(ctx) { refresh(ctx, viewport, facts); } shared(ctx, |shared| { shared.system_pointer = pointer; - shared.system_primary = primary; + shared.system_buttons = buttons; shared.system_command = command; }); + if ime::take_discard(ctx) + && let Some(system) = &system + { + system.discard_marked_text(); + } +} + +/// The system's bit of an egui pointer button. +fn held_of(button: egui::PointerButton) -> HeldButtons { + match button { + egui::PointerButton::Primary => HeldButtons::PRIMARY, + egui::PointerButton::Secondary => HeldButtons::SECONDARY, + egui::PointerButton::Middle => HeldButtons::MIDDLE, + egui::PointerButton::Extra1 => HeldButtons::EXTRA1, + egui::PointerButton::Extra2 => HeldButtons::EXTRA2, + } } /// The least change of an inner size, in points, that counts as a resize: far under one physical pixel at any scale @@ -247,8 +268,11 @@ fn size_changed(before: egui::Vec2, now: egui::Vec2) -> bool { /// ([`Caps::OS_RESIZES_UNDECORATED`]), a size change of a window the OS may resize under a held primary press (the /// size of a window that is not resizable is the app's own). While the OS runs a tracked move /// ([`Caps::OS_MOVES_TRACKED`]) it sends no key events, so every window's modifiers are the system's command modifier -/// alone. Reads only the raw input, the system's button and modifier state and the viewport's record. Returns whether -/// it added an event. +/// alone. A button the system reports up that egui still holds, in a frame with no button event and with no injected +/// step holding it, is released once, at the pointer's last position in the frame: the window never received its +/// release, and a release at the press position would be a click. Where the system tells nothing, nothing is +/// released. Reads only the raw input, the system's button and modifier state, the injected holds and the viewport's +/// record. Returns whether it added an event. pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool { let viewport = input.viewport_id; replay_caption_events(ctx, viewport, input); @@ -258,7 +282,9 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool { let pass = pass::pass_nr(ctx, viewport); let os_released = input.events.iter().any(|event| matches!(event, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, .. })); - let (held, command, tracked) = shared(ctx, |shared| (shared.system_primary, shared.system_command, shared.tracked_move)); + let no_button_event = !input.events.iter().any(|event| matches!(event, egui::Event::PointerButton { .. })); + let (buttons, command, tracked) = shared(ctx, |shared| (shared.system_buttons, shared.system_command, shared.tracked_move)); + let primary_held = buttons.is_some_and(|held| held.contains(HeldButtons::PRIMARY)); if tracked.is_some() && let Some(command) = command { @@ -266,20 +292,44 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool { let modifiers = egui::Modifiers { command, mac_cmd: command && mac, ctrl: command && !mac, ..egui::Modifiers::NONE }; input.events.push(egui::Event::ModifiersChanged(modifiers)); } + let lost: Vec = match buttons { + Some(held) if no_button_event => { + let down = PerViewport::::with(ctx, viewport, |record| record.buttons_down.clone()); + down.into_iter().filter(|button| !held.contains(held_of(*button)) && !injected::held_button(ctx, viewport, *button)).collect() + } + _ => Vec::new(), + }; let (released, handed_off) = PerViewport::::with(ctx, viewport, |record| { let resized = record.resizable != Some(false) && matches!((record.last_inner_size, size), (Some(before), Some(now)) if size_changed(before, now)); record.last_inner_size = size.or(record.last_inner_size); - let handed_off = record.handoff.is_some_and(|handoff| handoff.released.is_none() && handoff.pass < pass) && held != Some(true); + let handed_off = record.handoff.is_some_and(|handoff| handoff.released.is_none() && handoff.pass < pass) && !primary_held; if handed_off { record.handoff = record.handoff.map(|handoff| HandOff { released: Some(pass), ..handoff }); } - let release = record.primary_down && ((undecorated && resized) || (handed_off && !os_released)); - if release { - raw_input::push_primary_release(input, record.last_pos.unwrap_or(Pos2::ZERO)); + let primary = egui::PointerButton::Primary; + // A lost primary release already ends the press. + let release = record.buttons_down.contains(&primary) && !lost.contains(&primary) && ((undecorated && resized) || (handed_off && !os_released)); + if !lost.is_empty() { + let at = input + .events + .iter() + .rev() + .find_map(|event| match event { + egui::Event::PointerMoved(pos) => Some(*pos), + _ => None, + }) + .or(record.last_pos) + .unwrap_or(Pos2::ZERO); + for button in &lost { + raw_input::push_release(input, *button, at); + } } - raw_input::follow_primary(&input.events, &mut record.primary_down, &mut record.last_pos); - (release, handed_off) + if release { + raw_input::push_release(input, primary, record.last_pos.unwrap_or(Pos2::ZERO)); + } + raw_input::follow_buttons(&input.events, &mut record.buttons_down, &mut record.last_pos); + (release || !lost.is_empty(), handed_off) }); if handed_off && tracked == Some(viewport) { shared(ctx, |shared| shared.tracked_move = None); @@ -378,6 +428,7 @@ pub(crate) fn end(ctx: &Context) { } shared(ctx, |shared| shared.close_requests.clear()); follow_activity(ctx); + follow_overlays(ctx); follow_layout(ctx, viewports::current(ctx).focused); // The root window's placement is the app's `main` entry. if shared(ctx, |shared| shared.store.is_some()) { @@ -479,6 +530,22 @@ fn follow_activity(ctx: &Context) { } } +/// Hides the palette windows while the root window shows an app-modal or popup layer, so a click on a palette cannot +/// bring it over the layer, and shows them in the frame the layer closes. Runs at the end of the root pass, where the +/// layers of the running viewport are the root's. Focus moving between the app's windows does not touch it. +fn follow_overlays(ctx: &Context) { + let hidden = overlay::any_open(ctx, overlay::OpenFilter::Keys); + if shared(ctx, |shared| std::mem::replace(&mut shared.palettes_yield, hidden) == hidden) { + return; + } + for (viewport, _) in viewports::reported(ctx) { + if PerViewport::::with(ctx, viewport, |record| matches!(record.level, Some(WindowLevel::Palette))) { + ctx.send_viewport_cmd_to(viewport, egui::ViewportCommand::Visible(!hidden)); + } + } + ctx.request_repaint(); +} + /// On the root window's focus gain, re-reads the desktop's caption layout and gives the root frame the change. fn follow_layout(ctx: &Context, focused: bool) { shared(ctx, |shared| { diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 6e58e6ce5..3d78774e2 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -405,22 +405,6 @@ fn a_content_sized_window_takes_its_content_size_once_it_reported_its_place() { ); } -/// The OS windows the runtime opens carry the app id the app installed, as its main window does: docks and Wayland -/// compositors find the app's icon and rules by it. -#[trial] -fn a_viewport_opened_through_a_mount_carries_the_installed_app_id() { - let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(FakeSystem::new())).app_id("org.example.Craft")); - let out = windows.frame(vec![], vec![], |ui| { - Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {}); - }); - assert_eq!(builder_titled(&out, "tool").1.app_id.as_deref(), Some("org.example.Craft"), "the child window carries the app id"); - - let windows = Windows::new(); - let out = windows.frame(vec![], vec![], |ui| { - Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {}); - }); - assert_eq!(builder_titled(&out, "tool").1.app_id, None, "without an app id the window carries none"); -} /// fx.F20: a key and a modifier injected as held are let go when the window loses focus, as the platform lets its /// own go. Otherwise the next injected input, written against the stale state, would not announce its own Shift. @@ -481,7 +465,6 @@ fn non_finite_injected_points_queue_nothing_and_a_release_there_lets_go() { let nan = Pos2::new(f32::NAN, 10.0); host.inject_click(ViewportId::ROOT, nan, PointerButton::Primary, 1, Mods::NONE, false); host.inject_move(ViewportId::ROOT, Pos2::new(f32::INFINITY, 0.0), Mods::NONE, 0.0); - // P3(shell-w1): sh.K4 host.inject_wheel(ViewportId::ROOT, Pos2::new(20.0, 20.0), Vec2::new(0.0, f32::NAN), egui::MouseWheelUnit::Point, Mods::NONE); host.inject_pointer(ViewportId::ROOT, InjectedPointer::down(PointerButton::Primary, nan, Mods::NONE, None)); frames(6); @@ -614,3 +597,119 @@ fn a_floating_panel_opened_from_a_full_window_container_takes_input() { fixture.click(&probe).idle(2); assert_eq!(seen.borrow().activations, 1, "the click reaches the panel above the full-window container"); } + +/// A button the platform reports up while egui holds it (the window never got the release) is let go once, at the +/// pointer's last position so no click results. Nothing is released while the platform reports the button down, while +/// injected input holds it, or while the platform tells nothing. +#[trial] +fn a_button_the_platform_reports_up_is_released_once() { + use craft_ui::runtime::windows::InjectedPointer; + use craft_ui::testing::windows::HeldButtons; + + let system = Arc::new(FakeSystem::new()); + let windows = Windows::with(InstallSpec::new(ShellInfo::default(), system.clone())); + let host = WindowHost::of(&windows.ctx); + let secondary = egui::PointerButton::Secondary; + let down = Cell::new(false); + let clicked = Cell::new(false); + let releases = RefCell::new(Vec::new()); + let frame = |events: Vec| { + windows.frame(events, vec![], |ui| { + ui.ctx().input(|input| { + down.set(input.pointer.button_down(secondary)); + clicked.set(clicked.get() || input.pointer.button_clicked(secondary)); + releases.borrow_mut().extend(input.raw.events.iter().filter_map(|event| match event { + Event::PointerButton { pos, pressed: false, .. } => Some(*pos), + _ => None, + })); + }); + }); + }; + let at = Pos2::new(20.0, 20.0); + frame(vec![]); + frame(vec![moved(at)]); + system.set_buttons_held(Some(HeldButtons::SECONDARY)); + frame(vec![Event::PointerButton { pos: at, button: secondary, pressed: true, modifiers: egui::Modifiers::NONE }]); + assert!(down.get(), "the press is down"); + + frame(vec![moved(Pos2::new(60.0, 20.0))]); + assert!(down.get() && releases.borrow().is_empty(), "the system reports the button down: nothing is released"); + system.set_buttons_held(None); + frame(vec![moved(Pos2::new(80.0, 20.0))]); + assert!(down.get() && releases.borrow().is_empty(), "the platform tells nothing: nothing is released"); + + system.set_buttons_held(Some(HeldButtons::NONE)); + let away = Pos2::new(120.0, 20.0); + frame(vec![moved(away)]); + frame(vec![moved(Pos2::new(140.0, 20.0))]); + assert!(!down.get(), "the system reports the button up: egui lets it go"); + assert_eq!(*releases.borrow(), [away], "one release, at the pointer's position in the frame"); + assert!(!clicked.get(), "a release away from the press is no click"); + + host.inject_pointer(ViewportId::ROOT, InjectedPointer::down(PointerButton::Secondary, at, Mods::NONE, None)); + for _ in 0..4 { + frame(vec![]); + } + assert!(down.get(), "the injected press is held"); + for _ in 0..3 { + frame(vec![moved(Pos2::new(160.0, 20.0))]); + } + assert!(down.get(), "an injected hold between steps is no lost button"); +} + +/// A palette window hides while the root window shows an app-modal layer, returns in the frames after it closes, and +/// one that opens meanwhile opens hidden. +#[trial] +fn a_palette_hides_while_the_root_shows_a_modal_or_popup_and_returns_when_it_closes() { + let windows = Windows::new(); + let frame = |modal: bool, second: bool| { + windows.frame(vec![], vec![], |ui| { + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {}); + if second { + Palette::new("second", Some(WindowSpec::tool())).show(ui, |_, _| {}); + } + if modal { + let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal())); + Modal { common: Common::new(), props }.id_salt("modal").show(ui, |_, _| {}); + } + }) + }; + let visibility = |out: &Out| { + out.commands.iter().rev().find_map(|(id, command)| match command { + ViewportCommand::Visible(visible) if *id != ViewportId::ROOT => Some(*visible), + _ => None, + }) + }; + for _ in 0..4 { + frame(false, false); + } + assert_eq!((0..2).find_map(|_| visibility(&frame(false, false))), None, "no layer: the palette stays as it is"); + let hidden = (0..3).filter_map(|_| visibility(&frame(true, false))).last(); + assert_eq!(hidden, Some(false), "the palette hides under the modal"); + let out = frame(true, true); + assert_eq!(builder_titled(&out, "second").1.visible, Some(false), "a palette opened meanwhile opens hidden"); + let back = (0..3).filter_map(|_| visibility(&frame(false, false))).last(); + assert_eq!(back, Some(true), "the palette returns once the modal closed"); +} + +/// A key automation holds is in `keys::held` while it is held and not after its release. +#[trial] +fn a_key_held_by_automation_reads_as_held() { + let windows = Windows::new(); + let host = WindowHost::of(&windows.ctx); + let seen = RefCell::new(Vec::new()); + let frame = || { + windows.frame(vec![], vec![], |ui| *seen.borrow_mut() = craft_ui::runtime::keys::held(ui.ctx())); + }; + frame(); + host.inject_hold(ViewportId::ROOT, Key::A); + for _ in 0..3 { + frame(); + } + assert_eq!(*seen.borrow(), [egui::Key::A], "the held key reads as down"); + host.inject_let_go(ViewportId::ROOT, Key::A); + for _ in 0..3 { + frame(); + } + assert!(seen.borrow().is_empty(), "the released key reads as up"); +} diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 5e25fb2f1..0e565ec61 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -14,7 +14,8 @@ use craft_ui::runtime::drag; use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::trial; -use craft_ui::testing::windows::FakeSystem; +// PLAN: `HeldButtons` needs a re-export beside `FakeSystem` in crates/ui-contract/src/testing/windows.rs (not this set's file). +use craft_ui::testing::windows::{FakeSystem, HeldButtons}; use craft_ui_test_kit::windows::Windows; use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; use std::sync::Arc; @@ -404,17 +405,17 @@ fn dragging_a_native_palette_by_its_title_row_docks_it_where_the_os_moves_window let mut dock = NativeDock::on(Os::Mac, system.clone()); let pressed_at = FLOAT_AT.min + ROW_AT.to_vec2(); system.set_pointer(Some([pressed_at.x, pressed_at.y])); - system.set_primary_held(Some(true)); + system.set_buttons_held(Some(HeldButtons::PRIMARY)); dock.frame(vec![moved(ROW_AT)]); let (_, commands) = dock.frame(vec![press(ROW_AT)]); assert!(commands.contains(&ViewportCommand::StartDrag), "the press hands the move to the OS: {commands:?}"); - system.set_primary_held(Some(false)); + system.set_buttons_held(Some(HeldButtons::NONE)); let mut clicked = false; for _ in 0..3 { clicked |= docks_window(&dock.frame(vec![]).0); } assert!(!clicked && drag::mark(&dock.windows.ctx).is_none(), "a click on the row docks nothing"); - system.set_primary_held(Some(true)); + system.set_buttons_held(Some(HeldButtons::PRIMARY)); dock.frame(vec![press(ROW_AT)]); dock.frame(vec![]); system.set_pointer(Some([OVER_GROUP.x, OVER_GROUP.y])); @@ -433,7 +434,7 @@ fn dragging_a_native_palette_by_its_title_row_docks_it_where_the_os_moves_window docked |= docks_window(&dock.frame(vec![]).0); } assert!(!docked, "nothing docks while the system holds the button"); - system.set_primary_held(Some(false)); + system.set_buttons_held(Some(HeldButtons::NONE)); for _ in 0..3 { docked |= docks_window(&dock.frame(vec![]).0); } @@ -454,7 +455,7 @@ fn a_palette_drag_resolves_the_main_windows_drops_at_the_system_pointer_not_wher dock.frame_with(vec![moved(STALE)], vec![]); let pressed_at = FLOAT_AT.min + ROW_AT.to_vec2(); system.set_pointer(Some([pressed_at.x, pressed_at.y])); - system.set_primary_held(Some(true)); + system.set_buttons_held(Some(HeldButtons::PRIMARY)); dock.frame(vec![moved(ROW_AT)]); dock.frame(vec![press(ROW_AT)]); dock.frame(vec![]); @@ -470,7 +471,7 @@ fn a_palette_drag_resolves_the_main_windows_drops_at_the_system_pointer_not_wher matches!(mark, Some(DropMark::Region { area, .. }) if area == group), "the middle of the group under the system pointer is marked, the whole group: {mark:?}" ); - system.set_primary_held(Some(false)); + system.set_buttons_held(Some(HeldButtons::NONE)); for _ in 0..3 { docked |= docks_window(&dock.frame(vec![]).0); } diff --git a/crates/window/src/system.rs b/crates/window/src/system.rs index d9724bb1f..9756db0fa 100644 --- a/crates/window/src/system.rs +++ b/crates/window/src/system.rs @@ -7,7 +7,7 @@ use std::sync::Mutex; /// The mouse buttons the OS reports down, with no egui types. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct HeldButtons(#[allow(dead_code)] u8); // P3(shell-w1): sh.K5 +pub struct HeldButtons(u8); impl HeldButtons { /// No button. @@ -25,14 +25,12 @@ impl HeldButtons { /// Whether every button of `b` is down. pub fn contains(self, b: HeldButtons) -> bool { - let _ = b; - todo!("sh.K5") + self.0 & b.0 == b.0 } /// Adds the buttons of `b`. pub fn insert(&mut self, b: HeldButtons) { - let _ = b; - todo!("sh.K5") + self.0 |= b.0; } } @@ -41,11 +39,8 @@ pub trait WindowSystem: Send + Sync { /// The system pointer in desktop points, or `None` where the platform does not tell (Wayland, the web). fn desktop_pointer(&self) -> Option<[f32; 2]>; - /// Whether the primary mouse button is down now, or `None` where the platform does not tell. Read while the OS - /// moves a window for a drag and sends the app no pointer events. - fn primary_held(&self) -> Option; - - /// Every mouse button down now, or `None` where the platform does not tell. + /// Every mouse button down now, or `None` where the platform does not tell. Read while the OS moves a window for a + /// drag and sends the app no pointer events, and to find a release the window never received. fn buttons_held(&self) -> Option; /// Asks the input method to drop its marked text. Returns whether it did. @@ -79,9 +74,6 @@ impl WindowSystem for NoWindows { false } - fn primary_held(&self) -> Option { - None - } fn command_held(&self) -> Option { None @@ -121,18 +113,11 @@ impl WindowSystem for SystemWindows { } } + /// AppKit's `pressedMouseButtons` has one bit per button in the order of [`HeldButtons`]'s constants. fn buttons_held(&self) -> Option { - todo!("sh.K6") - } - - fn discard_marked_text(&self) -> bool { - todo!("ty.X3") - } - - fn primary_held(&self) -> Option { #[cfg(all(feature = "appkit", target_os = "macos"))] { - Some(objc2_app_kit::NSEvent::pressedMouseButtons() & 1 != 0) + Some(HeldButtons((objc2_app_kit::NSEvent::pressedMouseButtons() & 0x1f) as u8)) } #[cfg(not(all(feature = "appkit", target_os = "macos")))] { @@ -140,6 +125,27 @@ impl WindowSystem for SystemWindows { } } + /// Not while the key window has a sheet attached: a file dialog's name field would lose its composition. + fn discard_marked_text(&self) -> bool { + #[cfg(all(feature = "appkit", target_os = "macos"))] + { + use objc2_app_kit::{NSApplication, NSTextInputContext}; + let discarded = || -> Option<()> { + let mtm = objc2::MainThreadMarker::new()?; + if NSApplication::sharedApplication(mtm).keyWindow().is_some_and(|window| window.attachedSheet().is_some()) { + return None; + } + NSTextInputContext::currentInputContext(mtm)?.discardMarkedText(); + Some(()) + }; + discarded().is_some() + } + #[cfg(not(all(feature = "appkit", target_os = "macos")))] + { + false + } + } + fn command_held(&self) -> Option { #[cfg(all(feature = "appkit", target_os = "macos"))] { @@ -171,7 +177,8 @@ pub struct FakeSystem { #[derive(Debug, Default)] struct FakeState { pointer: Option<[f32; 2]>, - primary: Option, + buttons: Option, + discards: usize, command: Option, monitors: Vec, warps: Vec<[f32; 2]>, @@ -188,20 +195,14 @@ impl FakeSystem { self.with(|state| state.pointer = pointer); } - /// Sets whether the primary button is down; `None` where the platform does not tell. - pub fn set_primary_held(&self, held: Option) { - self.with(|state| state.primary = held); - } - /// Sets the buttons the test system reports down; `None` where the platform does not tell. pub fn set_buttons_held(&self, held: Option) { - let _ = held; - todo!("sh.K7") + self.with(|state| state.buttons = held); } /// The count of asked discards of marked text. pub fn discards(&self) -> usize { - todo!("ty.X4") + self.with(|state| state.discards) } /// Sets whether the command modifier is down; `None` where the platform does not tell. @@ -232,15 +233,12 @@ impl WindowSystem for FakeSystem { } fn buttons_held(&self) -> Option { - todo!("sh.K6") + self.with(|state| state.buttons) } fn discard_marked_text(&self) -> bool { - todo!("ty.X3") - } - - fn primary_held(&self) -> Option { - self.with(|state| state.primary) + self.with(|state| state.discards += 1); + true } fn command_held(&self) -> Option {