From c19abe86631d25fefc28d9b4a8d0e90fd2b1002f Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 11 Nov 2026 18:48:02 +0000 Subject: [PATCH] Dock a native window by dragging its title row A floating dock group in its own OS window now moves through a window move gesture the app runs, which reports Begin, Update, Commit and Cancel like a layer's move, so the dock marks the target under the pointer and docks the whole window on release. - macOS (Caps::OS_MOVES_TRACKED): the OS moves the window (StartMove), and the app follows the system pointer, button and Cmd through SystemWindows, the running platform's WindowSystem in craft-window. The hand-off ends when the system reports the button up. - X11 and Windows: the app moves the window with SetOuterPosition so the pressed point stays under the pointer; Escape puts it back. - A drag started by a container shown in its own OS window follows that window's pointer, not its parent's. - The runtime's end hook sets NSWindow.movable for every window; a window whose move the app runs is never moved by AppKit from its band. --- crates/host/src/target.rs | 6 +- crates/ui-contract/Cargo.toml | 4 + crates/ui-contract/src/contract/body/hooks.rs | 2 +- .../ui-contract/src/contract/body/window.rs | 128 ++++++++++++++-- crates/ui-contract/src/runtime/drag.rs | 9 +- .../ui-contract/src/runtime/egui/viewports.rs | 12 +- crates/ui-contract/src/runtime/pointer.rs | 11 ++ crates/ui-contract/src/runtime/windows.rs | 92 +++++++++--- .../ui-contract/src/runtime/windows/host.rs | 13 +- .../ui-contract/src/runtime/windows/native.rs | 14 +- crates/ui-contract/src/testing/windows.rs | 2 +- crates/ui-patterns/tests/it/docking/native.rs | 141 +++++++++++++++++- crates/ui-shell/Cargo.toml | 2 +- crates/ui-shell/src/shell/app.rs | 11 +- crates/ui-shell/src/shell/title_bar.rs | 28 +--- crates/window/Cargo.toml | 8 +- crates/window/src/mac.rs | 11 +- crates/window/src/system.rs | 101 ++++++++++++- docs/ui-docking.md | 2 +- 19 files changed, 497 insertions(+), 100 deletions(-) diff --git a/crates/host/src/target.rs b/crates/host/src/target.rs index 82dd82774..732319cf2 100644 --- a/crates/host/src/target.rs +++ b/crates/host/src/target.rs @@ -152,6 +152,9 @@ bitflags::bitflags! { const NATIVE_MENU_BAR = 1 << 6; /// The OS resizes undecorated windows from their edges. const OS_RESIZES_UNDECORATED = 1 << 7; + /// The OS moves a window for a drag the app hands it, and the app keeps reading the system pointer and the + /// mouse button meanwhile; elsewhere the app moves the window itself. + const OS_MOVES_TRACKED = 1 << 8; } } @@ -160,7 +163,8 @@ impl Caps { pub const fn native(os: Os) -> Caps { let base = Caps::VIEWPORTS.union(Caps::WINDOW_COMMANDS).union(Caps::FILE_SYSTEM).union(Caps::THREADS).union(Caps::SYSTEM_CURSOR); match os { - Os::Mac => base.union(Caps::NATIVE_MENU_BAR).union(Caps::SCREEN_CAPTURE), + // AppKit moves a window smoothly; a window the app moves by its position jitters there. + Os::Mac => base.union(Caps::NATIVE_MENU_BAR).union(Caps::SCREEN_CAPTURE).union(Caps::OS_MOVES_TRACKED), Os::Windows => base.union(Caps::OS_RESIZES_UNDECORATED).union(Caps::SCREEN_CAPTURE), Os::Linux => base, } diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index 21115e476..350946538 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -70,6 +70,10 @@ fontique = { version = "0.11.1", default-features = false, features = ["system", egui_kittest = { version = "0.37", features = ["wgpu"], optional = true } image = { version = "0.25", default-features = false, features = ["png"], optional = true } +# The window host's end hook sets `NSWindow.movable` through craft-window's AppKit code. +[target.'cfg(target_os = "macos")'.dependencies] +craft-window = { workspace = true, features = ["ui", "appkit"] } + # build.rs reads icons/icons.toml and deflates the suite's default fonts (Inter, egui's faces) for `fonts::deflated_default_definitions`. [build-dependencies] toml = { version = "1.1", default-features = false, features = ["std", "parse", "serde"] } diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index eaeb230cd..247f9d525 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -595,7 +595,7 @@ impl ShapeHooks for BodyHooks<'_> { && let Some(viewport) = os_window(props, cx.core.memory.ctx(), cx.core.id) { self.window_os(viewport, cx); - self.window_movable(cx); + self.window_movable(viewport, cx); } self.pane_drag(props, cx); if layer && !(matches!(props.mount, Mount::Viewport { .. }) && viewports::available(cx.core.memory.ctx())) { diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 230428b3a..c179d74b7 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -12,7 +12,7 @@ use crate::runtime::memory::sub; use crate::runtime::windows::{self, ResizeEdge, WindowAction, WindowHit}; use crate::runtime::{keys, pointer}; use crate::style::ComponentStyle as _; -use craft_behavior::{CursorIcon, GesturePhase, HitLevel, HitPriority, PartKey, PressPhase}; +use craft_behavior::{CursorIcon, GesturePhase, HitLevel, HitPriority, PartKey, PointerEvent, PressPhase}; use craft_host::target::{Caps, WindowChrome, WindowState}; use craft_keymap::{Chord, Key, Mods}; use egui::{Context, Id, Pos2, Rect, Vec2, ViewportId}; @@ -83,12 +83,27 @@ enum WindowModeKind { } /// A container's window gesture, the keyboard mode or a pointer drag, with the placement Escape restores and the -/// rect the layer had when the gesture began. Kept in session memory. +/// rect the layer had when the gesture began, or the move of its OS window that the app runs. Kept in session memory. #[derive(Clone, Default, PartialEq)] pub(super) struct WindowMode { kind: Option, restore: Placement, began: Option, + moving: Option, +} + +/// A move of a viewport mount's OS window that the app runs ([`windows::keeps_app_drag`]), from its Begin to its Commit +/// or Cancel. Rects are the window's outer rect in desktop points. +#[derive(Clone, Copy, PartialEq)] +struct WindowMove { + /// The pressed point in the window's inner coordinates, which stays under the pointer. + grab: Vec2, + /// Where the window was when the move began; a cancel puts it back there. + start: Rect, + /// Where the move put the window last. + at: Rect, + /// The OS moves the window and the app follows the system pointer ([`Caps::OS_MOVES_TRACKED`]). + tracked: bool, } /// The outer rect of a viewport mount's OS window as the container last learnt it: the window's placement, which the @@ -206,7 +221,7 @@ impl BodyHooks<'_> { if mode.kind == Some(kind) { mode = WindowMode::default(); } else { - mode = WindowMode { kind: Some(kind), restore: current.clone(), began: Some(current.rect_over(rect)) }; + mode = WindowMode { kind: Some(kind), restore: current.clone(), began: Some(current.rect_over(rect)), moving: None }; self.reports.push(step(current.rect_over(rect), GesturePhase::Begin)); } } @@ -315,16 +330,21 @@ impl BodyHooks<'_> { } } - /// A press on the move band or a grip of a container in an OS window starts the OS move or resize. Where the - /// platform answers the hit test (`answered_by_platform`), the parts stand for its sink only. - pub(super) fn window_os(&self, viewport: ViewportId, cx: &Cx<'_, C>) { + /// A press on the move band or a grip of a container in an OS window starts the OS move or resize; the band of a + /// window whose move the app runs starts that move instead ([`Self::window_move`]). Where the platform answers the + /// hit test (`answered_by_platform`), the parts stand for its sink only. + pub(super) fn window_os(&mut self, viewport: ViewportId, cx: &mut Cx<'_, C>) { if answered_by_platform(&cx.core.ctx, viewport) { return; } + let app_moves = windows::app_moves(&cx.core.ctx, viewport); + if app_moves { + self.window_move(viewport, cx); + } // The parts stand only by `WindowParts`, and the results of a part not registered this pass are gone. let started = |key: (PartKey, Option)| cx.core.results.get(&key).is_some_and(|result| matches!(result.press.phase, PressPhase::DragStart { .. })); - if started((MOVE_BAND, None)) { + if !app_moves && started((MOVE_BAND, None)) { windows::act(&cx.core.ctx, viewport, WindowAction::StartMove); } for (index, (dx, dy, _)) in GRIPS.into_iter().enumerate() { @@ -334,9 +354,84 @@ impl BodyHooks<'_> { } } + /// The move of an OS window whose app runs it ([`windows::keeps_app_drag`]): a drag of the move band keeps the + /// pressed point under the pointer, and each step is reported through `placement_changed` as a layer's move is, + /// from Begin to Commit or Cancel. Where the platform tracks the OS's moves ([`Caps::OS_MOVES_TRACKED`]) the OS + /// moves the window, and the window is where the system pointer is less the pressed point; the move ends with the + /// release the window host adds once the system tells the button is up. Elsewhere the app moves the window to + /// this pass's pointer, relative to where the window reports itself, and Escape puts it back. The drag's desktop + /// pointer is the pressed point of the window where the move put it. + fn window_move(&mut self, viewport: ViewportId, cx: &mut Cx<'_, C>) { + let ctx = cx.core.ctx.clone(); + let Some(phase) = cx.core.results.get(&(MOVE_BAND, None)).map(|result| result.press.phase) else { return }; + let host = windows::WindowHost::of(&ctx); + let Some(facts) = host.facts(viewport) else { return }; + let outer = facts.outer.unwrap_or(facts.inner); + // Where the inner area lies in the outer rect. + let inset = facts.inner.min - outer.min; + let change = |rect: Rect, phase: GesturePhase| PlacementChange { rect, phase, pointer: None, kind: PlacementKind::Move }; + let pointer_of = |moving: &WindowMove| moving.at.min + inset + moving.grab; + let Some(mut moving) = self.mode.moving else { + if let PressPhase::DragStart { start, pos, .. } = phase { + let tracked = windows::shell_of(&ctx, viewport).caps.contains(Caps::OS_MOVES_TRACKED); + // The OS keeps the window where it is under the pointer now; the app puts the pressed point under it. + let grab = (if tracked { pos } else { start.origin }).to_vec2(); + let mut moving = WindowMove { grab, start: outer, at: outer, tracked }; + self.reports.push(change(outer, GesturePhase::Begin)); + if tracked { + windows::act(&ctx, viewport, WindowAction::StartMove); + } else { + moving.at = outer.translate(pos - start.origin); + windows::act(&ctx, viewport, WindowAction::SetOuterPosition(moving.at.min)); + } + windows::note_moved_pointer(&ctx, viewport, Some(pointer_of(&moving))); + self.reports.push(change(moving.at, GesturePhase::Update)); + self.mode.moving = Some(moving); + } + return; + }; + let ended = match phase { + PressPhase::Cancel { .. } => Some(GesturePhase::Cancel), + PressPhase::Drag { .. } | PressPhase::Held { .. } | PressPhase::DragStart { .. } => None, + // A release, or a press that ended in a pass the container did not run. + _ => Some(GesturePhase::Commit), + }; + if let Some(ended) = ended { + if ended == GesturePhase::Cancel && !moving.tracked { + windows::act(&ctx, viewport, WindowAction::SetOuterPosition(moving.start.min)); + moving.at = moving.start; + } + self.reports.push(change(moving.at, ended)); + windows::note_moved_pointer(&ctx, viewport, None); + self.mode.moving = None; + return; + } + let to = if moving.tracked { + // AppKit sends no pointer events while it moves the window: the next pass reads the system pointer again. + crate::runtime::egui::repaint::request(&ctx); + host.desktop_pointer().map(|pointer| pointer - moving.grab - inset) + } else { + // A pointer move of this pass is relative to where the window was when the system sent it, which is where + // the window reports itself now; a position from an earlier pass was measured against an older place. + let moved = + pointer::pass_pointer(&ctx).events.iter().rev().find_map(|event| if let PointerEvent::Moved(at) = event { Some(*at) } else { None }); + moved.map(|at| facts.inner.min + (at.to_vec2() - moving.grab) - inset) + }; + if let Some(to) = to.filter(|to| *to != moving.at.min) { + moving.at = Rect::from_min_size(to, moving.at.size()); + if !moving.tracked { + windows::act(&ctx, viewport, WindowAction::SetOuterPosition(to)); + } + windows::note_moved_pointer(&ctx, viewport, Some(pointer_of(&moving))); + self.reports.push(change(moving.at, GesturePhase::Update)); + self.mode.moving = Some(moving); + } + } + /// A viewport mount in an OS window reports the window's moves and resizes from its facts, through the /// `placement_changed` a layer reports its own through: one `Commit` per change, as the platform tells no gesture - /// phase. The first facts are the window's placement, not a change. + /// phase. The first facts are the window's placement, not a change; the steps of a move the app runs are that + /// move's own ([`Self::window_move`]). pub(super) fn window_placed(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) { if !matches!(props.mount, Mount::Viewport { .. }) { return; @@ -345,7 +440,11 @@ impl BodyHooks<'_> { let Some(facts) = windows::WindowHost::of(&cx.core.ctx).facts(viewport) else { return }; let now = facts.outer.unwrap_or(facts.inner); let placed = &mut cx.core.memory.shown::(sub(sub(cx.core.id, "body"), "window_placed")).0; - let Some(before) = placed.replace(now).filter(|before| *before != now) else { return }; + let before = placed.replace(now); + if self.mode.moving.is_some() { + return; + } + let Some(before) = before.filter(|before| *before != now) else { return }; let kind = resized_edge(before, now).map_or(PlacementKind::Move, PlacementKind::Size); self.reports.push(PlacementChange { rect: now, phase: GesturePhase::Commit, pointer: None, kind }); } @@ -418,11 +517,16 @@ impl BodyHooks<'_> { /// Tells the platform whether the OS may move the container's OS window from where the pointer is (21.2 /// `WindowDrag`; macOS `NSWindow.movable`): only where a press would go to the move band under the press-target /// rule (8.3), so a press on a control over the band never drags the window. Bands of one window combine: any band - /// that would take the press allows the move. A pass with no band writes nothing; `AppShell` writes `false` for a - /// pass with no title bar. - pub(super) fn window_movable(&self, cx: &Cx<'_, C>) { + /// that would take the press allows the move. A window whose move the app runs ([`Self::window_move`]) is never + /// moved by the OS from its band; only the move's own hand-off moves it. A pass with no band writes nothing; + /// `AppShell` writes `false` for a pass with no title bar. + pub(super) fn window_movable(&self, viewport: ViewportId, cx: &Cx<'_, C>) { let Some(band) = cx.core.results.get(&(MOVE_BAND, None)) else { return }; let ctx = &cx.core.ctx; + if windows::app_moves(ctx, viewport) { + viewports::write_movable(ctx, false); + return; + } let takes_press = band.hovered && pointer::pass_pointer(ctx).hover.is_some_and(|at| { let (click, drag) = input::hit_targets(ctx); diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index 1febf49f1..8d7a7bd74 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -204,12 +204,15 @@ fn board(ctx: &Context, f: impl FnOnce(&mut Board) -> R) -> R { pass_state::with::(ctx, f) } -/// Starts a session for `source` with `payload`. A running session stays: one per context. +/// Starts a session for `source` with `payload`. A running session stays: one per context. A container shown in an OS +/// window of its own runs in its parent's pass, but the press that starts its drag is its window's: the session follows +/// that window's pointer. #[doc(hidden)] pub fn start(ctx: &Context, source: Id, payload: Arc, also: Option>, preview: DragPreview) { + let viewport = WindowHost::of(ctx).viewport_of(source).unwrap_or_else(|| pass::current_viewport(ctx)); board(ctx, |board| { if board.session.is_none() { - let buttons = pointer::frame(ctx).buttons; + let buttons = pointer::buttons_of(ctx, viewport); let button = [PointerButton::Primary, PointerButton::Secondary, PointerButton::Middle, PointerButton::Extra1, PointerButton::Extra2] .into_iter() .find(|button| buttons.contains(Buttons::of(*button))) @@ -217,7 +220,7 @@ pub fn start(ctx: &Context, source: Id, payload: Arc, als board.session = Some(Session { source, moving: Moving { layer: overlay::entry(ctx, source).map(|entry| entry.layer), viewport: Some(viewports::viewport_id(source)) }, - viewport: pass::current_viewport(ctx), + viewport, button, payload, also, diff --git a/crates/ui-contract/src/runtime/egui/viewports.rs b/crates/ui-contract/src/runtime/egui/viewports.rs index 8ae824d33..03f39bb04 100644 --- a/crates/ui-contract/src/runtime/egui/viewports.rs +++ b/crates/ui-contract/src/runtime/egui/viewports.rs @@ -203,9 +203,13 @@ fn movable_id(viewport: ViewportId) -> egui::Id { super::memory::unique(("craft_ui.title_bar.movable", viewport)) } -/// Sets the `movable` flag of the key window when it has a full-size content view and visible window buttons; -/// `applied` holds the value last set. Does nothing off macOS. +/// Whether the OS may move the running viewport's window from where the pointer is in this pass: what the move bands +/// of the pass wrote (the body step writes it for every move band of an OS window, `true` only where a press would go +/// to the band), else what the app wrote with [`write_movable`], else true. #[doc(hidden)] -pub fn set_native_movable(movable: bool, applied: &mut Option) { - craft_window::mac::set_movable(movable, applied); +pub fn movable(ctx: &Context) -> bool { + match movable_record(ctx) { + Some((pass, movable)) if pass == pass_number(ctx) => movable, + _ => true, + } } diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 89aad80e0..528d83d93 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -188,6 +188,17 @@ pub fn with_pass_pointer(ctx: &Context, f: impl FnOnce(&PassPointer) -> R) -> PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| f(record)) } +/// The buttons held in the latest pass of `viewport`, which may be a child window whose pass ran inside this one. +pub(crate) fn buttons_of(ctx: &Context, viewport: ViewportId) -> Buttons { + PerViewport::>>::with_pass( + ctx, + viewport, + pass::pass_nr(ctx, viewport), + |_, _| {}, + |record| record.frame.as_ref().map_or(Buttons::empty(), |frame| frame.buttons), + ) +} + /// Reads the running pass's pointer frame, `None` before the begin hook, and its hover position in place. pub(crate) fn with_frame(ctx: &Context, f: impl FnOnce(Option<&PointerFrame>, Option) -> R) -> R { with_pass_pointer(ctx, |pointer| f(pointer.frame.as_ref(), pointer.hover)) diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index ea8b52b1e..e6c23715a 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -10,7 +10,7 @@ use crate::runtime::frame::PerViewport; use crate::runtime::overlay; use crate::runtime::pass_state; use craft_behavior::{Cursor, CursorIcon, CursorPriority}; -use craft_host::target::{Caps, EdgeInsets, ShellInfo, WindowChrome, WindowKind}; +use craft_host::target::{Caps, EdgeInsets, Os, ShellInfo, WindowChrome, WindowKind}; use craft_window::native::NativeWindow; use craft_window::policy::{Captions, Decision, Frame, LayoutWatch}; use craft_window::restore::Store; @@ -32,7 +32,7 @@ pub use hit::{CaptionRegions, HitSink, ResizeEdge, WindowHit}; pub(crate) use hit::{hit_sink_installed, note_exclusive}; use hit::{publish_regions, replay_caption_events}; pub use host::{KeyEquivalent, WindowFacts, WindowHost}; -pub(crate) use host::{clear_source_pointer, note_source_pointer}; +pub(crate) use host::{clear_source_pointer, note_moved_pointer, note_source_pointer}; #[doc(hidden)] pub use native::keeps_app_drag; #[cfg(windows)] @@ -65,6 +65,12 @@ 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, + 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. + tracked_move: Option, /// The pointer of the viewport a drag started in, in desktop points, for platforms that tell no system pointer. source_pointer: Option, /// Containers whose viewport the OS asked to close in this root frame. @@ -118,9 +124,14 @@ pub(crate) struct Record { searched: Option, /// The opacity the window was last set to; 1 is opaque. opacity: Option, - /// The window's component runs its own drag from the move band (a dock window's title row), so a press on the - /// band must reach it and the operating system's move loop is not started from the hit test. + /// The app runs the window's move from its move band (a dock window's title row, whose move docks the window), so a + /// press on the band must reach it and the operating system's move loop is not started from the hit test. app_drag: bool, + /// While the app moves the window: the desktop pointer, at the pressed point of the window where the move last put + /// it. The window's reported place lags the move. + moved_pointer: Option, + /// The `movable` flag last set on the OS window. + movable_applied: Option, } /// Passes between searches for an OS window that was not found. @@ -155,9 +166,8 @@ pub(crate) fn take_sent(ctx: &Context) -> Vec<(ViewportId, WindowAction)> { shared(ctx, |shared| std::mem::take(&mut shared.sent)) } -/// Whether `viewport`'s component declared its own drag from the move band. -#[cfg(feature = "testing")] -pub(crate) fn keeps_app_drag_of(ctx: &Context, viewport: ViewportId) -> bool { +/// Whether the app runs the move of `viewport`'s window ([`keeps_app_drag`]). +pub(crate) fn app_moves(ctx: &Context, viewport: ViewportId) -> bool { PerViewport::::with(ctx, viewport, |record| record.app_drag) } @@ -181,22 +191,32 @@ pub(crate) fn install(ctx: &Context, shell: ShellInfo, system: Arc bool { let viewport = input.viewport_id; replay_caption_events(ctx, viewport, input); @@ -206,10 +226,18 @@ 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, .. })); - PerViewport::::with(ctx, viewport, |record| { + let (held, command, tracked) = shared(ctx, |shared| (shared.system_primary, shared.system_command, shared.tracked_move)); + if tracked.is_some() + && let Some(command) = command + { + let mac = base.os == Os::Mac; + let modifiers = egui::Modifiers { command, mac_cmd: command && mac, ctrl: command && !mac, ..egui::Modifiers::NONE }; + input.events.push(egui::Event::ModifiersChanged(modifiers)); + } + let (released, handed_off) = PerViewport::::with(ctx, viewport, |record| { let resized = matches!((record.last_inner_size, size), (Some(before), Some(now)) if 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); + let handed_off = record.handoff.is_some_and(|handoff| handoff.released.is_none() && handoff.pass < pass) && held != Some(true); if handed_off { record.handoff = record.handoff.map(|handoff| HandOff { released: Some(pass), ..handoff }); } @@ -218,8 +246,12 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool { raw_input::push_primary_release(input, record.last_pos.unwrap_or(Pos2::ZERO)); } raw_input::follow_primary(&input.events, &mut record.primary_down, &mut record.last_pos); - release - }) + (release, handed_off) + }); + if handed_off && tracked == Some(viewport) { + shared(ctx, |shared| shared.tracked_move = None); + } + released } /// The begin hook (H5), where the viewport is current: refreshes its window info, and raises the modal's window @@ -270,10 +302,11 @@ fn reshow_cursor(ctx: &Context, viewport: ViewportId) { } } -/// The end hook: keeps the root window's placement, writes a changed placement store once a second, and drops the -/// close requests the viewport mounts did not take in this frame. +/// The end hook: sets the window's `movable` flag, keeps the root window's placement, writes a changed placement store +/// once a second, and drops the close requests the viewport mounts did not take in this frame. pub(crate) fn end(ctx: &Context) { publish_regions(ctx, pass::current_viewport(ctx)); + sync_movable(ctx); if pass::current_viewport(ctx) != ViewportId::ROOT { return; } @@ -318,6 +351,23 @@ pub fn logic(ctx: &Context) { } } +/// Sets the `movable` flag of the running viewport's OS window from this pass's [`viewports::movable`]: the one place +/// AppKit's flag is set, after the window's UI has run. A window is told apart by its viewport: the key window is the one +/// whose viewport has focus, so an unfocused viewport is left as it is. AppKit is only called when the flag changes. +/// Only a macOS window with a full-size content view has a flag to set; elsewhere this does nothing. +fn sync_movable(ctx: &Context) { + if !viewports::current(ctx).focus_reported { + return; + } + let movable = viewports::movable(ctx); + let viewport = pass::current_viewport(ctx); + PerViewport::::with(ctx, viewport, |record| { + if record.movable_applied != Some(movable) { + craft_window::mac::set_movable(movable, &mut record.movable_applied); + } + }); +} + fn flush_store(ctx: &Context) { let now = pass::now(ctx); let store = shared(ctx, |shared| { diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 79d8901f5..9888e347c 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -296,14 +296,21 @@ pub(super) fn scale_of(ctx: &Context, facts: &viewports::Facts) -> Option { } /// Records the pointer of the viewport a drag runs in, `local` in that viewport's coordinates, as a desktop -/// position: the fallback where the platform tells no system pointer. `None` keeps the last position. +/// position: the fallback where the platform tells no system pointer. While the app moves that viewport's window the +/// move's own pointer counts ([`note_moved_pointer`]). `None` keeps the last position. pub(crate) fn note_source_pointer(ctx: &Context, viewport: ViewportId, local: Option) { - let inner = PerViewport::::with(ctx, viewport, |record| record.facts.and_then(|facts| facts.inner)); - if let Some(desktop) = local.zip(inner).map(|(local, inner)| inner.min + local.to_vec2()) { + let (inner, moved) = PerViewport::::with(ctx, viewport, |record| (record.facts.and_then(|facts| facts.inner), record.moved_pointer)); + if let Some(desktop) = moved.or_else(|| local.zip(inner).map(|(local, inner)| inner.min + local.to_vec2())) { shared(ctx, |shared| shared.source_pointer = Some(desktop)); } } +/// Records the desktop pointer of a move the app runs of `viewport`'s window: the pressed point of the window where the +/// move last put it. `None` once the move ends. +pub(crate) fn note_moved_pointer(ctx: &Context, viewport: ViewportId, desktop: Option) { + PerViewport::::with(ctx, viewport, |record| record.moved_pointer = desktop); +} + /// Forgets the drag's pointer once the session ends. pub(crate) fn clear_source_pointer(ctx: &Context) { shared(ctx, |shared| shared.source_pointer = None); diff --git a/crates/ui-contract/src/runtime/windows/native.rs b/crates/ui-contract/src/runtime/windows/native.rs index 3b62f02c4..fcdaa2cfb 100644 --- a/crates/ui-contract/src/runtime/windows/native.rs +++ b/crates/ui-contract/src/runtime/windows/native.rs @@ -107,6 +107,9 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { WindowAction::StartMove => { viewports::command(ctx, viewport, egui::ViewportCommand::StartDrag); hand_off(ctx, viewport); + if base.caps.contains(Caps::OS_MOVES_TRACKED) { + shared(ctx, |shared| shared.tracked_move = Some(viewport)); + } } WindowAction::StartResize(edge) => { viewports::command(ctx, viewport, egui::ViewportCommand::BeginResize(viewports::resize_direction(edge))); @@ -169,9 +172,10 @@ fn native_of(ctx: &Context, viewport: ViewportId) -> Option { found } -/// Records that the component of `viewport`'s window runs its own drag from the window's move band, as the floating -/// dock group does to dock its window: the Windows hit test then leaves the band to the app, whose press starts that -/// drag and the OS move together. Runs in each pass of the component. +/// Records that the app runs the move of `viewport`'s window from its move band, as the floating dock group does to +/// dock its window, on every platform: the band's press starts the window's move gesture (Begin, Update, Commit or +/// Cancel through `placement_changed`, as a layer's move reports), not the OS's move, and the Windows hit test leaves +/// the band to the app. Runs in each pass of the component. #[doc(hidden)] pub fn keeps_app_drag(ctx: &Context, viewport: ViewportId) { PerViewport::::with(ctx, viewport, |record| record.app_drag = true); @@ -206,8 +210,8 @@ pub fn route_root(ctx: &Context, handle: impl FnOnce() -> Option) } } -/// The OS took the press that started a move or resize of `viewport`'s window: [`input_hook`] ends it on the next -/// input. +/// The OS took the press that started a move or resize of `viewport`'s window: [`input_hook`] ends it once the system +/// tells the button is up, or on the next input where it does not tell. fn hand_off(ctx: &Context, viewport: ViewportId) { let pass = pass::pass_nr(ctx, viewport); PerViewport::::with(ctx, viewport, |record| record.handoff = Some(HandOff { pass, released: None })); diff --git a/crates/ui-contract/src/testing/windows.rs b/crates/ui-contract/src/testing/windows.rs index 914bd64ab..13febed19 100644 --- a/crates/ui-contract/src/testing/windows.rs +++ b/crates/ui-contract/src/testing/windows.rs @@ -20,7 +20,7 @@ pub fn applied_actions(ctx: &egui::Context) -> Vec<(egui::ViewportId, crate::run /// Whether the window of `viewport` has a component that runs its own drag from the window's move band. pub fn keeps_app_drag(ctx: &egui::Context, viewport: egui::ViewportId) -> bool { - crate::runtime::windows::keeps_app_drag_of(ctx, viewport) + crate::runtime::windows::app_moves(ctx, viewport) } /// Starts the drag of the window container `source` (what the title row of a dock window does), with the pointer diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 15b63fbc3..108025c6c 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -1,16 +1,20 @@ -//! Native dock windows: when a float gets an OS window, what the dock records when the OS moves it, and the OS close. +//! Native dock windows: when a float gets an OS window, what the dock records when the OS moves it, the OS close, and +//! docking the whole window by dragging its title row. -use craft_behavior::dock::{Action, Floating, Layout, Permissions, Workspace}; +use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, Workspace}; use craft_behavior::placement::Placement; use craft_host::target::{Backend, Caps, Os, ShellInfo}; use craft_ui::contract::{Bind, BodyCx}; use craft_ui::docking::{DockConfig, DockPanels, PanelSpec}; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::InstallSpec; +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; use craft_ui_test_kit::windows::Windows; -use egui::{Pos2, Rect, Ui, Vec2, ViewportEvent, ViewportId, ViewportInfo}; +use egui::{Event, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; use std::sync::Arc; /// The root window and the palette overlap; the palette is the larger. @@ -158,6 +162,137 @@ fn the_os_close_of_a_native_float_closes_it_when_its_panels_may_close() { assert!(!closed(Permissions::ALL.closable(false)), "a window with a panel that may not close stays"); } +/// The main window, one docked group filling it, and a native palette window away from it. +const MAIN_AT: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(900.0, 700.0) }; +const FLOAT_AT: Rect = Rect { min: Pos2::new(1000.0, 150.0), max: Pos2::new(1400.0, 450.0) }; +/// A point of the palette's title row, clear of the lights and the actions, in the palette's coordinates. +const ROW_AT: Pos2 = Pos2::new(150.0, 10.0); +/// A desktop point over the middle of the main window's group. +const OVER_GROUP: Pos2 = Pos2::new(550.0, 400.0); + +/// A dock of one docked group and one native palette. +struct NativeDock { + windows: Windows, + workspace: Workspace, +} + +impl NativeDock { + fn on(os: Os, system: Arc) -> Self { + let shell = ShellInfo::default().os(os).caps(Caps::native(os)); + let windows = Windows::with(InstallSpec::new(shell, system)); + windows.root_info(info(true, MAIN_AT)); + windows.child_info(info(true, FLOAT_AT)); + let palette = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); + let mut dock = NativeDock { windows, workspace: Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])) }; + for _ in 0..3 { + dock.frame(vec![]); + } + dock + } + + /// One frame with `child` events for the palette's window: the dock's actions and the palette's window commands. + fn frame(&mut self, child: Vec) -> (Vec>, Vec) { + let mut actions = Vec::new(); + let workspace = &mut self.workspace; + let out = self.windows.frame(vec![], child, |ui| { + actions.extend( + DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui).actions, + ); + }); + let commands = out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect(); + (actions, commands) + } +} + +fn docks_window(actions: &[Action]) -> bool { + actions.iter().any(|action| matches!(action, Action::MoveWindow { .. })) +} + +fn outer_positions(commands: &[ViewportCommand]) -> Vec { + commands.iter().filter_map(|command| if let ViewportCommand::OuterPosition(at) = command { Some(*at) } else { None }).collect() +} + +/// Where the app moves windows itself (X11): a drag of the palette's title row moves the window so the pressed point +/// stays under the pointer, marks the main window's group under it, and the release docks the whole window there. +/// Escape puts the window back and docks nothing. +#[trial] +fn dragging_a_native_palette_by_its_title_row_docks_it_where_the_app_moves_windows() { + // From the title row to the main window's group, in three moves the window follows. + let step = (OVER_GROUP - (FLOAT_AT.min + ROW_AT.to_vec2())) / 3.0; + let drag_over_group = |dock: &mut NativeDock| { + let mut to = Vec::new(); + for events in [vec![moved(ROW_AT)], vec![press(ROW_AT)]] { + dock.frame(events); + } + for _ in 0..3 { + to.extend(outer_positions(&dock.frame(vec![moved(ROW_AT + step)]).1)); + } + for _ in 0..2 { + dock.frame(vec![]); + } + to + }; + + let mut dock = NativeDock::on(Os::Linux, Arc::new(FakeSystem::new())); + let to = drag_over_group(&mut dock); + assert_eq!(to.len(), 3, "the window follows each move: {to:?}"); + assert_eq!(to.last().map(|at| *at + ROW_AT.to_vec2()), Some(OVER_GROUP), "the pressed point stays under the pointer"); + assert!(drag::mark(&dock.windows.ctx).is_some(), "the group under the pointer shows the drop mark"); + let mut docked = false; + for events in [vec![release(ROW_AT)], vec![], vec![]] { + docked |= docks_window(&dock.frame(events).0); + } + assert!(docked, "the release docks the whole window"); + + let mut dock = NativeDock::on(Os::Linux, Arc::new(FakeSystem::new())); + drag_over_group(&mut dock); + let (actions, commands) = dock.frame(vec![key_press(Key::Escape, Modifiers::NONE)]); + assert_eq!(outer_positions(&commands).last(), Some(&FLOAT_AT.min), "Escape puts the window back"); + let mut docked = docks_window(&actions); + for events in [vec![release(ROW_AT)], vec![], vec![]] { + docked |= docks_window(&dock.frame(events).0); + } + assert!(!docked, "a cancelled move docks nothing"); +} + +/// Where the OS moves windows and the app reads the system pointer and button meanwhile (macOS): the title row's drag +/// hands the move to the OS, the system pointer over the main window's group marks it (Cmd keeps the drop floating), +/// and the window docks when the system tells the button is up, not on the first pass after the hand-off. +#[trial] +fn dragging_a_native_palette_by_its_title_row_docks_it_where_the_os_moves_windows() { + let system = Arc::new(FakeSystem::new()); + 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)); + for events in [vec![moved(ROW_AT)], vec![press(ROW_AT)]] { + dock.frame(events); + } + let (_, commands) = dock.frame(vec![moved(ROW_AT + Vec2::new(12.0, 0.0))]); + assert!(commands.contains(&ViewportCommand::StartDrag), "the OS moves the window: {commands:?}"); + system.set_pointer(Some([OVER_GROUP.x, OVER_GROUP.y])); + let mut docked = false; + for _ in 0..3 { + docked |= docks_window(&dock.frame(vec![]).0); + } + assert!(drag::mark(&dock.windows.ctx).is_some(), "the group under the system pointer shows the drop mark"); + system.set_command_held(Some(true)); + for _ in 0..2 { + docked |= docks_window(&dock.frame(vec![]).0); + } + assert!(drag::mark(&dock.windows.ctx).is_none(), "Cmd keeps the drop floating"); + system.set_command_held(Some(false)); + for _ in 0..2 { + docked |= docks_window(&dock.frame(vec![]).0); + } + assert!(!docked, "nothing docks while the system holds the button"); + system.set_primary_held(Some(false)); + for _ in 0..3 { + docked |= docks_window(&dock.frame(vec![]).0); + } + assert!(docked, "the button's release docks the whole window"); +} + /// A palette float made in the app window. fn float() -> Floating { Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0))) diff --git a/crates/ui-shell/Cargo.toml b/crates/ui-shell/Cargo.toml index 7451cad8d..95a46ae80 100644 --- a/crates/ui-shell/Cargo.toml +++ b/crates/ui-shell/Cargo.toml @@ -36,7 +36,7 @@ resvg = { version = "0.45.1", default-features = false } # `std::time::Instant` on native; the browser clock on wasm, where `Instant::now` panics. web-time = "1.1" -# `shell::title_bar::sync_movable` sets `NSWindow.movable` through craft-window's AppKit code, without its egui layer. +# `AppSpec::new` installs `craft_window::system::SystemWindows`, which reads AppKit without craft-window's egui layer. [target.'cfg(target_os = "macos")'.dependencies] craft-window = { workspace = true, features = ["appkit"] } diff --git a/crates/ui-shell/src/shell/app.rs b/crates/ui-shell/src/shell/app.rs index 11decdd80..23edd485e 100644 --- a/crates/ui-shell/src/shell/app.rs +++ b/crates/ui-shell/src/shell/app.rs @@ -11,7 +11,7 @@ use craft_host::target::{Backend, Os, ShellInfo, WindowState}; use craft_window::desktop::fits; use craft_window::policy::Decision; use craft_window::restore::Store; -use craft_window::system::{NoWindows, WindowSystem}; +use craft_window::system::{SystemWindows, WindowSystem}; use egui::{Context, Ui, ViewportId}; use std::sync::{Arc, Mutex}; use web_time::Instant; @@ -29,7 +29,7 @@ pub struct AppSpec { pub defaults: Defaults, /// Where window placement is kept. pub placement: Arc>, - /// The OS services the window host reads: the system pointer and its warp. + /// The OS services the window host reads: the system pointer, button and modifier state, and the pointer's warp. pub window_system: Arc, /// Who draws the root window's frame (`craft_window::policy::decide_for`). Unset: the OS draws it. pub frame: Option, @@ -45,7 +45,7 @@ impl AppSpec { shell_info: ShellInfo::default().backend(Backend::from_env()), defaults, placement: Arc::new(Mutex::new(Store::in_memory())), - window_system: Arc::new(NoWindows), + window_system: Arc::new(SystemWindows), frame: None, } } @@ -119,8 +119,6 @@ pub trait ShellApp { /// frame. `logic` carries the close path, which must run while the window is hidden. struct Driver { app: A, - /// The `movable` flag last set on the native window. - movable: Option, /// Whether the first fit of the root window to its monitor has run. fitted: bool, } @@ -174,7 +172,6 @@ impl eframe::App for Driver { self.fitted = fit_first(ui.ctx()); } self.app.ui(ui); - super::title_bar::sync_movable(ui.ctx(), &mut self.movable); } } @@ -219,7 +216,7 @@ fn create( crate::install(&cc.egui_ctx, install).map_err(|error| format!("the runtime could not be installed: {error}"))?; // The suite's interface face; an app that installs its own fonts in `make` replaces it. crate::fonts::UiFonts::new(&crate::fonts::I18nScripts).install(&cc.egui_ctx); - Ok(Box::new(Driver { app: make(&cc.egui_ctx), movable: None, fitted: false })) + Ok(Box::new(Driver { app: make(&cc.egui_ctx), fitted: false })) } } diff --git a/crates/ui-shell/src/shell/title_bar.rs b/crates/ui-shell/src/shell/title_bar.rs index b6fe2cfc4..0863c7b57 100644 --- a/crates/ui-shell/src/shell/title_bar.rs +++ b/crates/ui-shell/src/shell/title_bar.rs @@ -6,12 +6,10 @@ use egui::Context; /// Whether the OS may move the running viewport's window from where the pointer is in this pass: what the move bands /// of the pass wrote (the body step writes it for every move band of an OS window, `true` only where a press would go -/// to the band), else what the app wrote with [`set_window_movable`], else true. +/// to the band), else what the app wrote with [`set_window_movable`], else true. The runtime sets macOS's +/// `NSWindow.movable` from it at the end of each window's pass. pub fn window_movable(ctx: &Context) -> bool { - match viewports::movable_record(ctx) { - Some((pass, movable)) if pass == viewports::pass_number(ctx) => movable, - _ => true, - } + viewports::movable(ctx) } /// Records that the OS may move the running viewport's window in this pass (`true`) or not. `AppShell` writes `false` @@ -22,26 +20,6 @@ pub fn set_window_movable(ctx: &Context, movable: bool) { viewports::write_movable(ctx, movable); } -/// Sets the `movable` flag of the context's window from this pass's [`window_movable`]: the one place AppKit's flag is -/// set. Call it once per frame per window, after that window's UI has run; `applied` holds the value last set for the window, so AppKit is only -/// called when it changes. -/// -/// A window is told apart by its viewport: the key window is the one whose viewport has focus, so an unfocused -/// viewport is left as it is. Only a window with a full-size content view and visible window buttons is touched, -/// because floating panels in their own windows keep their own `movable`, which AppKit also needs to resize them. -/// Only a macOS window has a flag to set; elsewhere the call does nothing. Apple builds do not run on the dev box, -/// so the macOS side compiles by inspection until the Mac builds it. -pub fn sync_movable(ctx: &Context, applied: &mut Option) { - if !viewports::current(ctx).focus_reported { - return; - } - let movable = window_movable(ctx); - if *applied == Some(movable) { - return; - } - viewports::set_native_movable(movable, applied); -} - // The bar, its title and its two ends. mod bar; mod measure; diff --git a/crates/window/Cargo.toml b/crates/window/Cargo.toml index 18cedc53d..19b3f8ff4 100644 --- a/crates/window/Cargo.toml +++ b/crates/window/Cargo.toml @@ -10,7 +10,8 @@ repository.workspace = true [features] # `policy::apply` and `desktop::fits`: the frame decision on an `egui::ViewportBuilder`, and whether a window fits its monitor. ui = ["dep:egui"] -# `mac::set_movable`: AppKit's `movable` flag, without egui. `native_menu`: the application menu bar +# `mac::set_movable`: AppKit's `movable` flag, without egui. `system::SystemWindows`: AppKit's pointer, button and Cmd. +# `native_menu`: the application menu bar # on macOS (other platforms build the same API as no-ops). appkit = ["dep:objc2", "dep:objc2-app-kit", "dep:objc2-foundation", "dep:muda"] @@ -27,12 +28,13 @@ serde_json = { workspace = true } [target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies] wayland-client = "0.31" -# `mac::set_movable` (`NSWindow.movable`), `mac::measure` (button frames, OS version), +# `mac::set_movable` (`NSWindow.movable`), `mac::measure` (button frames, OS version), `system::SystemWindows` +# (`NSEvent` pointer, buttons and modifiers, `NSScreen` for the primary screen), # `native_menu` (muda menus, AppKit titles). [target.'cfg(target_os = "macos")'.dependencies] muda = { version = "0.21.2", default-features = false, optional = true } objc2 = { version = "0.6.4", default-features = false, features = ["std"], optional = true } -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSButton", "NSControl", "NSEvent", "NSMenu", "NSMenuItem", "NSResponder", "NSView", "NSWindow"], optional = true } +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSButton", "NSControl", "NSEvent", "NSMenu", "NSMenuItem", "NSResponder", "NSScreen", "NSView", "NSWindow"], optional = true } objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSBundle", "NSEnumerator", "NSGeometry", "NSLocale", "NSProcessInfo", "NSString"], optional = true } # `caps_lock`: the toggle bit of the Caps Lock key, through winsafe's safe wrapper (the workspace forbids `unsafe`). diff --git a/crates/window/src/mac.rs b/crates/window/src/mac.rs index 56a6b5205..82ade46c6 100644 --- a/crates/window/src/mac.rs +++ b/crates/window/src/mac.rs @@ -153,20 +153,19 @@ pub fn measure() -> Option { None } -/// Sets the `movable` flag of the key window when it has a full-size content view and visible window buttons; -/// floating panels in their own windows keep their own flag, which AppKit also needs to resize them. `applied` -/// holds the value last set. Does nothing off macOS. +/// Sets the `movable` flag of the key window when it has a full-size content view, whose transparent title strip +/// AppKit would otherwise move the window from: the app's own title bar or a tool window's title row says where it +/// may. `applied` holds the value last set. Does nothing off macOS. pub fn set_movable(movable: bool, applied: &mut Option) { #[cfg(all(feature = "appkit", target_os = "macos"))] { use objc2::MainThreadMarker; - use objc2_app_kit::{NSApplication, NSWindowButton, NSWindowStyleMask}; + use objc2_app_kit::{NSApplication, NSWindowStyleMask}; // eframe runs the app on the main thread; anywhere else AppKit is out of reach. let Some(mtm) = MainThreadMarker::new() else { return }; let Some(window) = NSApplication::sharedApplication(mtm).keyWindow() else { return }; - let buttons = window.standardWindowButton(NSWindowButton::CloseButton).is_some_and(|close| !close.isHidden()); - if window.styleMask().contains(NSWindowStyleMask::FullSizeContentView) && buttons { + if window.styleMask().contains(NSWindowStyleMask::FullSizeContentView) { window.setMovable(movable); *applied = Some(movable); } diff --git a/crates/window/src/system.rs b/crates/window/src/system.rs index 2ae7cc498..850ad418a 100644 --- a/crates/window/src/system.rs +++ b/crates/window/src/system.rs @@ -1,5 +1,6 @@ -//! `WindowSystem`: the OS calls the window host makes outside egui (desktop pointer, pointer warp, monitors). -//! egui-free. `FakeSystem` is the scripted implementation for tests. +//! `WindowSystem`: the OS calls the window host makes outside egui (desktop pointer, mouse button and modifier state, +//! pointer warp, monitors). egui-free. `SystemWindows` is the running platform's, `FakeSystem` the scripted +//! implementation for tests. use craft_behavior::Monitor; use std::sync::Mutex; @@ -9,6 +10,14 @@ 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; + + /// Whether the platform's command modifier (Cmd on macOS, Ctrl elsewhere) 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 key events. + fn command_held(&self) -> Option; + /// Moves the system pointer to `to` in desktop points. Returns whether the platform moved it. fn warp_pointer(&self, to: [f32; 2]) -> bool; @@ -25,6 +34,14 @@ impl WindowSystem for NoWindows { None } + fn primary_held(&self) -> Option { + None + } + + fn command_held(&self) -> Option { + None + } + fn warp_pointer(&self, _: [f32; 2]) -> bool { false } @@ -34,7 +51,65 @@ impl WindowSystem for NoWindows { } } -/// A scripted system: the pointer and monitors are set by the test, warps are recorded. +/// The running platform's services. AppKit tells the pointer, the primary button and Cmd on macOS (with the +/// `appkit` feature); elsewhere none is told. It warps no pointer and lists no monitors. +#[derive(Clone, Copy, Debug, Default)] +pub struct SystemWindows; + +impl WindowSystem for SystemWindows { + /// AppKit measures from the bottom-left of the primary screen (the one with the menu bar, first in + /// `NSScreen::screens`), y up; winit flips window positions against that screen's height, whichever screen a + /// window is on, so the pointer is flipped the same way. + fn desktop_pointer(&self) -> Option<[f32; 2]> { + #[cfg(all(feature = "appkit", target_os = "macos"))] + { + use objc2_app_kit::{NSEvent, NSScreen}; + // eframe runs the app on the main thread; anywhere else AppKit is out of reach. + let mtm = objc2::MainThreadMarker::new()?; + let primary = NSScreen::screens(mtm).firstObject()?; + let at = NSEvent::mouseLocation(); + Some([at.x as f32, (primary.frame().size.height - at.y) as f32]) + } + #[cfg(not(all(feature = "appkit", target_os = "macos")))] + { + None + } + } + + fn primary_held(&self) -> Option { + #[cfg(all(feature = "appkit", target_os = "macos"))] + { + Some(objc2_app_kit::NSEvent::pressedMouseButtons() & 1 != 0) + } + #[cfg(not(all(feature = "appkit", target_os = "macos")))] + { + None + } + } + + fn command_held(&self) -> Option { + #[cfg(all(feature = "appkit", target_os = "macos"))] + { + use objc2_app_kit::{NSEvent, NSEventModifierFlags}; + Some(NSEvent::modifierFlags_class().contains(NSEventModifierFlags::Command)) + } + #[cfg(not(all(feature = "appkit", target_os = "macos")))] + { + None + } + } + + fn warp_pointer(&self, _: [f32; 2]) -> bool { + false + } + + fn monitors(&self) -> Vec { + Vec::new() + } +} + +/// A scripted system: the pointer, the button and modifier state and the monitors are set by the test, warps are +/// recorded. #[derive(Debug, Default)] pub struct FakeSystem { state: Mutex, @@ -43,6 +118,8 @@ pub struct FakeSystem { #[derive(Debug, Default)] struct FakeState { pointer: Option<[f32; 2]>, + primary: Option, + command: Option, monitors: Vec, warps: Vec<[f32; 2]>, } @@ -58,6 +135,16 @@ 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 whether the command modifier is down; `None` where the platform does not tell. + pub fn set_command_held(&self, held: Option) { + self.with(|state| state.command = held); + } + /// Sets the monitors. pub fn set_monitors(&self, monitors: Vec) { self.with(|state| state.monitors = monitors); @@ -80,6 +167,14 @@ impl WindowSystem for FakeSystem { self.with(|state| state.pointer) } + fn primary_held(&self) -> Option { + self.with(|state| state.primary) + } + + fn command_held(&self) -> Option { + self.with(|state| state.command) + } + fn warp_pointer(&self, to: [f32; 2]) -> bool { self.with(|state| { state.warps.push(to); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index ca5895c58..798899cc4 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -111,7 +111,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords ## Floating and native windows -A floating window is a `Floating` in the layout: its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). +A floating window is a `Floating` in the layout: its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. Dragging a native window by its title row moves the whole window and docks it where it is released over a group of the main window, as a floating window inside the main window does: the window host runs that move (`runtime::windows::keeps_app_drag`). On macOS the OS moves the window and the app follows the system pointer and button (`Caps::OS_MOVES_TRACKED`); elsewhere the app moves it, and Escape puts it back. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). ## SplitArea on its own