diff --git a/docs/docs/configuration/drag-and-drop.md b/docs/docs/configuration/drag-and-drop.md index ecdf6f75b..aee3bc96e 100644 --- a/docs/docs/configuration/drag-and-drop.md +++ b/docs/docs/configuration/drag-and-drop.md @@ -266,3 +266,15 @@ COMPOSITOR.dnd.event.onStart((drag) => { Remember to give the cursor back with `overrideKind(null)` when the drag ends. + + +## Dragging a window with the data + +A browser or toolkit can tear a tab off into a new window and dock it back by +dragging the window itself along with the data +([xdg-toplevel-drag-v1](https://wayland.app/protocols/xdg-toplevel-drag-v1)). +ShojiWM moves that window with the pointer as an interactive move, so your +config gets `onWindowMove` events with `source: "toplevel-drag"` and its usual +snapping and workspace rules apply. The window is never the drop target: the +drop lands on what is under it. When the drag ends, the window stays where +the move left it. diff --git a/docs/i18n/ja/docusaurus-plugin-content-docs/current/configuration/drag-and-drop.md b/docs/i18n/ja/docusaurus-plugin-content-docs/current/configuration/drag-and-drop.md index b627aafa4..8bcf60b90 100644 --- a/docs/i18n/ja/docusaurus-plugin-content-docs/current/configuration/drag-and-drop.md +++ b/docs/i18n/ja/docusaurus-plugin-content-docs/current/configuration/drag-and-drop.md @@ -257,3 +257,15 @@ COMPOSITOR.dnd.event.onStart((drag) => { ``` ドラッグが終わったら、`overrideKind(null)` でカーソルを戻すのを忘れないでください。 + + +## データと一緒にウィンドウをドラッグする + +ブラウザーやツールキットは、データと一緒にウィンドウそのものをドラッグして、タブを +新しいウィンドウに切り離したり、元のウィンドウに戻したりできます +([xdg-toplevel-drag-v1](https://wayland.app/protocols/xdg-toplevel-drag-v1))。 +ShojiWM はそのウィンドウを対話的な移動としてポインターと一緒に動かします。設定には +`source: "toplevel-drag"` の `onWindowMove` イベントが届き、いつものスナップや +ワークスペースのルールがそのまま働きます。そのウィンドウ自身はドロップ先になりません。 +ドロップはその下にあるものに届きます。ドラッグが終わると、ウィンドウは移動が終わった +位置に残ります。 diff --git a/packages/shoji_wm/src/events.ts b/packages/shoji_wm/src/events.ts index d6732e7b7..bca2cdbd7 100644 --- a/packages/shoji_wm/src/events.ts +++ b/packages/shoji_wm/src/events.ts @@ -138,7 +138,12 @@ export interface WindowMoveRect { height: number; } -export type WindowMoveSource = "ssd" | "modifier" | "client-csd" | "xwayland"; +export type WindowMoveSource = + | "ssd" + | "modifier" + | "client-csd" + | "xwayland" + | "toplevel-drag"; export type WindowMovePhase = "start" | "update" | "end" | "cancel"; export interface WindowMoveEvent { diff --git a/src/shojiwm_lib/src/dnd.rs b/src/shojiwm_lib/src/dnd.rs index 490896984..e4b012666 100644 --- a/src/shojiwm_lib/src/dnd.rs +++ b/src/shojiwm_lib/src/dnd.rs @@ -14,6 +14,9 @@ //! of the negotiated action, the target window or the icon, end). A config //! that does not listen gets the built-in view: the icon at the pointer, //! gone when the drag ends. +//! +//! A drag can also carry a window (xdg-toplevel-drag-v1, see +//! `crate::toplevel_drag`). use std::{ any::Any, @@ -32,7 +35,7 @@ use smithay::{ dnd::{DnDGrab, DndAction, GrabType, Source, SourceMetadata}, pointer::Focus, }, - reexports::wayland_server::protocol::wl_surface::WlSurface, + reexports::wayland_server::protocol::{wl_data_source::WlDataSource, wl_surface::WlSurface}, utils::{IsAlive, Logical, Point, Rectangle, Serial}, }; use tracing::{debug, warn}; @@ -40,6 +43,7 @@ use tracing::{debug, warn}; use crate::{ ssd::{DecorationNode, DecorationTree, StandaloneDecoration, window_model::WindowIconSnapshot}, state::ShojiWM, + toplevel_drag::ToplevelDragGrab, }; /// How long a view may stay after its drag ended without the config @@ -639,6 +643,11 @@ impl ShojiWM { }; let metadata = source.metadata(); + // A `wl_data_device` drag hands over its `wl_data_source`, which may + // carry a toplevel (xdg-toplevel-drag-v1). + let data_source = (&source as &dyn Any) + .downcast_ref::() + .cloned(); let source_window = start_data .focus .as_ref() @@ -660,7 +669,10 @@ impl ShojiWM { self.end_drag(previous, DragEndKind::Cancelled, false, position); } let grab = DnDGrab::new_pointer(&self.display_handle, start_data, tracked, seat); - pointer.set_grab(self, grab, serial, Focus::Keep); + pointer.set_grab(self, ToplevelDragGrab { inner: grab }, serial, Focus::Keep); + if let Some(data_source) = data_source { + self.begin_toplevel_drag(&data_source); + } let now = Instant::now(); let drag = ActiveDrag { @@ -717,6 +729,7 @@ impl ShojiWM { accepted: bool, position: Point, ) { + self.mark_toplevel_drag_ended(); let Some(drag_id) = self.dnd.active.as_ref().map(|active| active.id) else { return; }; @@ -742,6 +755,7 @@ impl ShojiWM { return; } self.sync_drag_state(); + self.end_toplevel_drag(); let Some(active) = self.dnd.end(Instant::now()) else { return; }; diff --git a/src/shojiwm_lib/src/grabs/move_grab.rs b/src/shojiwm_lib/src/grabs/move_grab.rs index 08d2774cd..b365d0e1e 100644 --- a/src/shojiwm_lib/src/grabs/move_grab.rs +++ b/src/shojiwm_lib/src/grabs/move_grab.rs @@ -25,44 +25,62 @@ use smithay::{ utils::{Logical, Point}, }; -pub struct MoveSurfaceGrab { - pub start_data: PointerGrabStartData, +/// A window that follows the pointer: the part of a move that does not +/// depend on what drives it, a [`MoveSurfaceGrab`] or a toplevel drag +/// (`crate::toplevel_drag`). +#[derive(Debug)] +pub struct WindowMove { pub window: Window, - pub initial_window_location: Point, - pub initial_event_rect: smithay::utils::Rectangle, - pub source: WindowMoveSourceSnapshot, - pub runtime_managed: bool, - pub last_pointer: Point, + start_pointer: Point, + initial_window_location: Point, + initial_event_rect: smithay::utils::Rectangle, + source: WindowMoveSourceSnapshot, + runtime_managed: bool, + last_pointer: Point, } -impl MoveSurfaceGrab { - pub fn start( - start_data: PointerGrabStartData, +impl WindowMove { + /// A move of `window`, which sits at `initial_window_location` (and + /// `initial_event_rect` for the config) while the pointer is at + /// `start_pointer`. + pub fn new( window: Window, + start_pointer: Point, initial_window_location: Point, initial_event_rect: smithay::utils::Rectangle, source: WindowMoveSourceSnapshot, ) -> Self { - let last_pointer = start_data.location; Self { - start_data, window, + start_pointer, initial_window_location, initial_event_rect, source, runtime_managed: false, - last_pointer, + last_pointer: start_pointer, } } + pub fn last_pointer(&self) -> Point { + self.last_pointer + } + + /// Tell the config the move starts. The config answers at once, so this + /// must not run inside a pointer grab: what it asks for in reply takes the + /// pointer's lock. pub fn notify_start(&mut self, data: &mut ShojiWM) { - data.cursor_override = Some(CursorIcon::Grabbing); - data.schedule_redraw(); - self.runtime_managed = self.invoke_runtime_event( - data, - WindowMovePhaseSnapshot::Start, - self.start_data.location, - ); + self.runtime_managed = + self.invoke_runtime_event(data, WindowMovePhaseSnapshot::Start, self.start_pointer); + } + + /// Tell the config the move ended, once the caller has returned (see + /// `queue_grab_end_dispatch`). + pub fn finish(&self, data: &mut ShojiWM) { + if self.runtime_managed { + let window_id = data.snapshot_window(&self.window).id; + let event = self.runtime_event(data, WindowMovePhaseSnapshot::End, self.last_pointer); + data.queue_grab_end_dispatch(PendingGrabMotion::WindowMove { window_id, event }); + } } fn invoke_runtime_event( @@ -83,7 +101,7 @@ impl MoveSurfaceGrab { phase: WindowMovePhaseSnapshot, current_pointer: Point, ) -> WindowMoveEventSnapshot { - let start_pointer = self.start_data.location; + let start_pointer = self.start_pointer; let delta = current_pointer - start_pointer; let current_rect = move_rect_for_delta(self.initial_event_rect, delta); let output_name = data @@ -114,28 +132,20 @@ impl MoveSurfaceGrab { timestamp: std::time::Duration::from(data.clock.now()).as_millis() as u64, } } -} -impl PointerGrab for MoveSurfaceGrab { - fn motion( - &mut self, - data: &mut ShojiWM, - handle: &mut PointerInnerHandle<'_, ShojiWM>, - _focus: Option<(WlSurface, Point)>, - event: &MotionEvent, - ) { - // While the grab is active, no client has pointer focus - handle.motion(data, None, event); - self.last_pointer = event.location; + /// The pointer moved to `location`: move the window with it. Safe inside + /// a pointer grab, since the config hears about it later. + pub fn motion(&mut self, data: &mut ShojiWM, location: Point) { + self.last_pointer = location; if self.runtime_managed { let window_id = data.snapshot_window(&self.window).id; - let event = self.runtime_event(data, WindowMovePhaseSnapshot::Update, event.location); + let event = self.runtime_event(data, WindowMovePhaseSnapshot::Update, location); data.queue_grab_motion_dispatch(PendingGrabMotion::WindowMove { window_id, event }); return; } - let delta = event.location - self.start_data.location; + let delta = location - self.start_pointer; let new_location = self.initial_window_location.to_f64() + delta; // Unlike the runtime-managed path above, this fallback places the // window directly in the `Space`, whose element locations are whole @@ -221,6 +231,53 @@ impl PointerGrab for MoveSurfaceGrab { data.schedule_redraw(); } } +} + +pub struct MoveSurfaceGrab { + pub start_data: PointerGrabStartData, + pub window_move: WindowMove, +} + +impl MoveSurfaceGrab { + pub fn start( + start_data: PointerGrabStartData, + window: Window, + initial_window_location: Point, + initial_event_rect: smithay::utils::Rectangle, + source: WindowMoveSourceSnapshot, + ) -> Self { + let window_move = WindowMove::new( + window, + start_data.location, + initial_window_location, + initial_event_rect, + source, + ); + Self { + start_data, + window_move, + } + } + + pub fn notify_start(&mut self, data: &mut ShojiWM) { + data.cursor_override = Some(CursorIcon::Grabbing); + data.schedule_redraw(); + self.window_move.notify_start(data); + } +} + +impl PointerGrab for MoveSurfaceGrab { + fn motion( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + _focus: Option<(WlSurface, Point)>, + event: &MotionEvent, + ) { + // While the grab is active, no client has pointer focus + handle.motion(data, None, event); + self.window_move.motion(data, event.location); + } fn relative_motion( &mut self, @@ -247,13 +304,8 @@ impl PointerGrab for MoveSurfaceGrab { if !handle.current_pressed().contains(&BTN_LEFT) { // No more buttons are pressed, release the grab. handle.unset_grab(self, data, event.serial, event.time, true); - if self.runtime_managed { - let window_id = data.snapshot_window(&self.window).id; - let event = - self.runtime_event(data, WindowMovePhaseSnapshot::End, self.last_pointer); - data.queue_grab_end_dispatch(PendingGrabMotion::WindowMove { window_id, event }); - } - data.update_decoration_cursor_icon(self.last_pointer); + self.window_move.finish(data); + data.update_decoration_cursor_icon(self.window_move.last_pointer()); } } @@ -348,7 +400,7 @@ impl PointerGrab for MoveSurfaceGrab { fn unset(&mut self, data: &mut ShojiWM) { data.pointer_dispatch.discard_grab_motion(); - data.update_decoration_cursor_icon(self.last_pointer); + data.update_decoration_cursor_icon(self.window_move.last_pointer()); } } diff --git a/src/shojiwm_lib/src/handlers/compositor.rs b/src/shojiwm_lib/src/handlers/compositor.rs index 5fcd8b8ee..3a45c393c 100644 --- a/src/shojiwm_lib/src/handlers/compositor.rs +++ b/src/shojiwm_lib/src/handlers/compositor.rs @@ -836,6 +836,7 @@ impl CompositorHandler for ShojiWM { xdg_shell::handle_commit(self, surface); layer_shell::handle_commit(self, surface, layer_commit_damage); resize_grab::handle_commit(&mut self.space, surface); + self.toplevel_drag_commit(surface); if !self.idle_inhibited_surfaces.is_empty() { self.refresh_idle_inhibit_state(); diff --git a/src/shojiwm_lib/src/handlers/mod.rs b/src/shojiwm_lib/src/handlers/mod.rs index 4943c2c38..2c45a845e 100644 --- a/src/shojiwm_lib/src/handlers/mod.rs +++ b/src/shojiwm_lib/src/handlers/mod.rs @@ -1134,6 +1134,7 @@ crate::delegate_hyprland_toplevel_export!(ShojiWM); crate::delegate_tearing_control!(ShojiWM); crate::delegate_output_power!(ShojiWM); crate::delegate_gamma_control!(ShojiWM); +crate::delegate_toplevel_drag!(ShojiWM); crate::delegate_virtual_pointer!(ShojiWM); crate::delegate_virtual_keyboard!(ShojiWM); diff --git a/src/shojiwm_lib/src/handlers/xdg_shell.rs b/src/shojiwm_lib/src/handlers/xdg_shell.rs index 77e9b6b72..bf715253d 100644 --- a/src/shojiwm_lib/src/handlers/xdg_shell.rs +++ b/src/shojiwm_lib/src/handlers/xdg_shell.rs @@ -195,6 +195,7 @@ impl XdgShellHandler for ShojiWM { fn toplevel_destroyed(&mut self, surface: ToplevelSurface) { let wl_surface = surface.wl_surface(); + self.toplevel_drag_toplevel_destroyed(surface.xdg_toplevel()); let Some(window) = self .space .elements() diff --git a/src/shojiwm_lib/src/lib.rs b/src/shojiwm_lib/src/lib.rs index 879604076..ea45bf66d 100644 --- a/src/shojiwm_lib/src/lib.rs +++ b/src/shojiwm_lib/src/lib.rs @@ -67,6 +67,7 @@ pub mod runtime_process; pub mod runtime_workspace; pub mod ssd; pub mod state; +pub mod toplevel_drag; pub mod virtual_input; pub mod virtual_keyboard; pub mod window_decoration; diff --git a/src/shojiwm_lib/src/protocols/mod.rs b/src/shojiwm_lib/src/protocols/mod.rs index b12ba1441..3d2a76cb2 100644 --- a/src/shojiwm_lib/src/protocols/mod.rs +++ b/src/shojiwm_lib/src/protocols/mod.rs @@ -6,5 +6,6 @@ pub mod output_power; pub mod plasma_shell; pub mod screencopy; pub mod tearing_control; +pub mod toplevel_drag; pub mod virtual_keyboard; pub mod virtual_pointer; diff --git a/src/shojiwm_lib/src/protocols/toplevel_drag.rs b/src/shojiwm_lib/src/protocols/toplevel_drag.rs new file mode 100644 index 000000000..8e52f6680 --- /dev/null +++ b/src/shojiwm_lib/src/protocols/toplevel_drag.rs @@ -0,0 +1,416 @@ +//! `xdg_toplevel_drag_manager_v1` (staging xdg-toplevel-drag-v1.xml). +//! +//! A client moves a window with a drag and drop: it makes an +//! `xdg_toplevel_drag_v1` for the `wl_data_source` of the drag and attaches a +//! toplevel to it, before or during the drag. The compositor then moves that +//! toplevel with the pointer until the drag ends. Browsers and toolkits use it +//! to tear a tab off into a new window and to dock it back. +//! +//! This module keeps the protocol objects and the state of each drag object +//! ([`DragMachine`]); `crate::toplevel_drag` moves the window. + +use std::sync::Mutex; + +use smithay::reexports::wayland_server::{ + Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource, backend::ClientId, + protocol::wl_data_source::WlDataSource, +}; +use smithay::utils::{Logical, Point}; +use wayland_protocols::xdg::{ + shell::server::xdg_toplevel::XdgToplevel, + toplevel_drag::v1::server::{ + xdg_toplevel_drag_manager_v1::{self, XdgToplevelDragManagerV1}, + xdg_toplevel_drag_v1::{self, XdgToplevelDragV1}, + }, +}; + +const VERSION: u32 = 1; + +pub trait ToplevelDragHandler { + fn toplevel_drag_manager_state(&mut self) -> &mut ToplevelDragManagerState; + /// `drag` got a toplevel (`attach`). + fn toplevel_drag_attached(&mut self, drag: &XdgToplevelDragV1); + /// `drag` is gone (`destroy`, or its client went away). + fn toplevel_drag_destroyed(&mut self, drag: &XdgToplevelDragV1); +} + +/// Where a drag object is in the life of its drag and drop. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum DragPhase { + /// `wl_data_device.start_drag` has not run for the source yet. + #[default] + Waiting, + Dragging, + /// Dropped or cancelled. The object only waits for its `destroy`. + Ended, +} + +/// The toplevel moved with the drag, and where the pointer sits in it +/// (relative to its window geometry). +#[derive(Debug, Clone, PartialEq)] +pub struct Attachment { + pub toplevel: T, + pub offset: Point, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DragError { + /// `attach` while a toplevel that still has its role is attached. + ToplevelAttached, + /// `destroy` before the drag ended. + OngoingDrag, +} + +/// The state of one `xdg_toplevel_drag_v1`, generic over the toplevel so +/// it can be tested without a client. +#[derive(Debug)] +pub struct DragMachine { + phase: DragPhase, + attached: Option>, +} + +impl Default for DragMachine { + fn default() -> Self { + Self { + phase: DragPhase::default(), + attached: None, + } + } +} + +impl DragMachine { + pub fn phase(&self) -> DragPhase { + self.phase + } + + pub fn attached(&self) -> Option<&Attachment> { + self.attached.as_ref() + } + + /// `attach`. `has_role` tells whether a toplevel is still alive as an + /// `xdg_toplevel`. Returns whether the toplevel is now attached: after + /// the drag ended, an attach has no effect. + pub fn attach( + &mut self, + toplevel: T, + offset: Point, + has_role: impl Fn(&T) -> bool, + ) -> Result { + if self + .attached + .as_ref() + .is_some_and(|attached| has_role(&attached.toplevel)) + { + return Err(DragError::ToplevelAttached); + } + if self.phase == DragPhase::Ended { + self.attached = None; + return Ok(false); + } + self.attached = Some(Attachment { toplevel, offset }); + Ok(true) + } + + /// The source's drag started. Returns false when it already had. + pub fn start(&mut self) -> bool { + if self.phase != DragPhase::Waiting { + return false; + } + self.phase = DragPhase::Dragging; + true + } + + /// The drag was dropped or cancelled. Returns the toplevel that was + /// attached: it stays where it is. + pub fn end(&mut self) -> Option> { + self.phase = DragPhase::Ended; + self.attached.take() + } + + /// `toplevel` was unmapped or destroyed: the protocol detaches it. + /// Returns whether it was attached. + pub fn detach(&mut self, toplevel: &T) -> bool { + if self + .attached + .as_ref() + .is_some_and(|attached| attached.toplevel == *toplevel) + { + self.attached = None; + return true; + } + false + } + + /// `destroy`: allowed before the drag starts and after it ends. + pub fn check_destroy(&self) -> Result<(), DragError> { + match self.phase { + DragPhase::Dragging => Err(DragError::OngoingDrag), + DragPhase::Waiting | DragPhase::Ended => Ok(()), + } + } +} + +/// The user data of an `xdg_toplevel_drag_v1`. +#[derive(Debug)] +pub struct ToplevelDragData { + pub source: WlDataSource, + machine: Mutex>, +} + +impl ToplevelDragData { + pub fn with(&self, f: impl FnOnce(&mut DragMachine) -> R) -> R { + f(&mut self.machine.lock().unwrap()) + } +} + +/// The data of `drag`; every drag object has it. +pub fn toplevel_drag_data(drag: &XdgToplevelDragV1) -> &ToplevelDragData { + drag.data::() + .expect("xdg_toplevel_drag_v1 without its data") +} + +#[derive(Debug, Default)] +pub struct ToplevelDragManagerState { + drags: Vec, +} + +impl ToplevelDragManagerState { + pub fn new(display: &DisplayHandle) -> Self + where + D: GlobalDispatch, + D: Dispatch, + D: Dispatch, + D: 'static, + { + display.create_global::(VERSION, ()); + Self::default() + } + + /// The drag object made for `source`. + pub fn drag_for_source(&self, source: &WlDataSource) -> Option { + self.drags + .iter() + .find(|drag| toplevel_drag_data(drag).source == *source) + .cloned() + } +} + +impl GlobalDispatch for ToplevelDragManagerState +where + D: GlobalDispatch, + D: Dispatch, + D: Dispatch, + D: ToplevelDragHandler, + D: 'static, +{ + fn bind( + _state: &mut D, + _dh: &DisplayHandle, + _client: &Client, + manager: New, + _data: &(), + data_init: &mut DataInit<'_, D>, + ) { + data_init.init(manager, ()); + } +} + +impl Dispatch for ToplevelDragManagerState +where + D: Dispatch, + D: Dispatch, + D: ToplevelDragHandler, + D: 'static, +{ + fn request( + state: &mut D, + _client: &Client, + manager: &XdgToplevelDragManagerV1, + request: xdg_toplevel_drag_manager_v1::Request, + _data: &(), + _dh: &DisplayHandle, + data_init: &mut DataInit<'_, D>, + ) { + match request { + xdg_toplevel_drag_manager_v1::Request::GetXdgToplevelDrag { id, data_source } => { + let taken = state + .toplevel_drag_manager_state() + .drag_for_source(&data_source) + .is_some(); + let drag = data_init.init( + id, + ToplevelDragData { + source: data_source, + machine: Mutex::new(DragMachine::default()), + }, + ); + if taken { + manager.post_error( + xdg_toplevel_drag_manager_v1::Error::InvalidSource, + "the data source already has an xdg_toplevel_drag_v1", + ); + return; + } + state.toplevel_drag_manager_state().drags.push(drag); + } + xdg_toplevel_drag_manager_v1::Request::Destroy => {} + _ => {} + } + } +} + +impl Dispatch for ToplevelDragManagerState +where + D: Dispatch, + D: ToplevelDragHandler, + D: 'static, +{ + fn request( + state: &mut D, + _client: &Client, + drag: &XdgToplevelDragV1, + request: xdg_toplevel_drag_v1::Request, + data: &ToplevelDragData, + _dh: &DisplayHandle, + _data_init: &mut DataInit<'_, D>, + ) { + match request { + xdg_toplevel_drag_v1::Request::Attach { + toplevel, + x_offset, + y_offset, + } => { + let attached = data.with(|machine| { + machine.attach(toplevel, (x_offset, y_offset).into(), |toplevel| { + toplevel.is_alive() + }) + }); + match attached { + Ok(true) => state.toplevel_drag_attached(drag), + Ok(false) => {} + Err(_) => drag.post_error( + xdg_toplevel_drag_v1::Error::ToplevelAttached, + "a toplevel is already attached", + ), + } + } + xdg_toplevel_drag_v1::Request::Destroy => { + if data.with(|machine| machine.check_destroy()).is_err() { + drag.post_error( + xdg_toplevel_drag_v1::Error::OngoingDrag, + "destroyed before the drag ended", + ); + } + } + _ => {} + } + } + + fn destroyed( + state: &mut D, + _client: ClientId, + drag: &XdgToplevelDragV1, + _data: &ToplevelDragData, + ) { + state + .toplevel_drag_manager_state() + .drags + .retain(|existing| existing != drag); + state.toplevel_drag_destroyed(drag); + } +} + +/// Delegate the `xdg_toplevel_drag_manager_v1` global to +/// [`ToplevelDragManagerState`]. +#[macro_export] +macro_rules! delegate_toplevel_drag { + ($ty: ty) => { + smithay::reexports::wayland_server::delegate_global_dispatch!($ty: [ + wayland_protocols::xdg::toplevel_drag::v1::server::xdg_toplevel_drag_manager_v1::XdgToplevelDragManagerV1: () + ] => $crate::protocols::toplevel_drag::ToplevelDragManagerState); + + smithay::reexports::wayland_server::delegate_dispatch!($ty: [ + wayland_protocols::xdg::toplevel_drag::v1::server::xdg_toplevel_drag_manager_v1::XdgToplevelDragManagerV1: () + ] => $crate::protocols::toplevel_drag::ToplevelDragManagerState); + + smithay::reexports::wayland_server::delegate_dispatch!($ty: [ + wayland_protocols::xdg::toplevel_drag::v1::server::xdg_toplevel_drag_v1::XdgToplevelDragV1: $crate::protocols::toplevel_drag::ToplevelDragData + ] => $crate::protocols::toplevel_drag::ToplevelDragManagerState); + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A toplevel, by id. + #[derive(Debug, Clone, PartialEq)] + struct Toplevel(u32); + + fn alive(_: &Toplevel) -> bool { + true + } + + fn dead(_: &Toplevel) -> bool { + false + } + + #[test] + fn a_toplevel_attached_before_the_drag_moves_with_it_until_the_drop() { + let mut machine = DragMachine::default(); + assert_eq!(machine.attach(Toplevel(1), (10, 5).into(), alive), Ok(true)); + assert!(machine.check_destroy().is_ok(), "no drag yet"); + assert!(machine.start()); + assert_eq!(machine.phase(), DragPhase::Dragging); + assert_eq!(machine.attached().unwrap().offset, (10, 5).into()); + assert_eq!(machine.check_destroy(), Err(DragError::OngoingDrag)); + + let left = machine.end().unwrap(); + assert_eq!(left.toplevel, Toplevel(1)); + assert!(machine.attached().is_none()); + assert!(machine.check_destroy().is_ok()); + } + + #[test] + fn a_new_toplevel_can_be_attached_during_the_drag() { + let mut machine = DragMachine::default(); + assert!(machine.start()); + assert!(!machine.start(), "a source starts one drag"); + assert_eq!(machine.attach(Toplevel(2), (0, 0).into(), alive), Ok(true)); + assert_eq!(machine.attached().unwrap().toplevel, Toplevel(2)); + } + + #[test] + fn attaching_over_a_live_toplevel_is_an_error() { + let mut machine = DragMachine::default(); + machine.attach(Toplevel(1), (0, 0).into(), alive).unwrap(); + assert_eq!( + machine.attach(Toplevel(2), (0, 0).into(), alive), + Err(DragError::ToplevelAttached) + ); + // Once the first toplevel lost its role, another may take its place. + assert_eq!(machine.attach(Toplevel(2), (3, 4).into(), dead), Ok(true)); + assert_eq!(machine.attached().unwrap().toplevel, Toplevel(2)); + } + + #[test] + fn an_unmapped_toplevel_is_detached_and_can_attach_again() { + let mut machine = DragMachine::default(); + machine.start(); + machine.attach(Toplevel(1), (0, 0).into(), alive).unwrap(); + assert!(!machine.detach(&Toplevel(9)), "only the attached one"); + assert!(machine.detach(&Toplevel(1))); + assert!(machine.attached().is_none()); + assert_eq!(machine.attach(Toplevel(1), (0, 0).into(), alive), Ok(true)); + } + + #[test] + fn an_attach_after_the_drag_ended_does_nothing() { + let mut machine = DragMachine::default(); + machine.start(); + assert!(machine.end().is_none()); + assert_eq!(machine.attach(Toplevel(1), (0, 0).into(), alive), Ok(false)); + assert!(machine.attached().is_none()); + assert!(!machine.start(), "an ended drag does not start again"); + } +} diff --git a/src/shojiwm_lib/src/ssd/window_model.rs b/src/shojiwm_lib/src/ssd/window_model.rs index c306c01f4..8d02f6dc5 100644 --- a/src/shojiwm_lib/src/ssd/window_model.rs +++ b/src/shojiwm_lib/src/ssd/window_model.rs @@ -345,6 +345,8 @@ pub enum WindowMoveSourceSnapshot { Modifier, ClientCsd, Xwayland, + /// A window attached to a drag and drop (xdg-toplevel-drag-v1). + ToplevelDrag, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] diff --git a/src/shojiwm_lib/src/state.rs b/src/shojiwm_lib/src/state.rs index 27afdaa1c..ca0c86a27 100644 --- a/src/shojiwm_lib/src/state.rs +++ b/src/shojiwm_lib/src/state.rs @@ -294,6 +294,7 @@ pub struct ShojiWM { pub tearing_control_state: crate::protocols::tearing_control::TearingControlManagerState, pub output_power_manager_state: crate::protocols::output_power::OutputPowerManagerState, pub gamma_control_manager_state: crate::protocols::gamma_control::GammaControlManagerState, + pub toplevel_drag_manager_state: crate::protocols::toplevel_drag::ToplevelDragManagerState, /// Gamma ramps a wlr-gamma-control client set, by output name. pub gamma_ramps: HashMap>, /// Outputs whose panel is switched off (DPMS), by name; see [`crate::output_power`]. @@ -555,6 +556,8 @@ pub struct ShojiWM { pub runtime_dnd_enabled: bool, /// The drag in progress and the drag views the config shows. pub dnd: crate::dnd::DndState, + /// The drag in progress carries a window (xdg-toplevel-drag-v1). + pub(crate) toplevel_drag: Option, pub runtime_gesture_swipe: Option, /// The config's input grab (`COMPOSITOR.input.grab`), if one is held. pub runtime_input_grab: Option, @@ -1716,6 +1719,8 @@ impl ShojiWM { crate::protocols::virtual_pointer::VirtualPointerManagerState::new::(&dh); let gamma_control_manager_state = crate::protocols::gamma_control::GammaControlManagerState::new::(&dh); + let toplevel_drag_manager_state = + crate::protocols::toplevel_drag::ToplevelDragManagerState::new::(&dh); let color_management_state = crate::protocols::color_management::ColorManagementState::new::(&dh); let foreign_toplevel_list_state = @@ -1891,6 +1896,7 @@ impl ShojiWM { tearing_control_state, output_power_manager_state, gamma_control_manager_state, + toplevel_drag_manager_state, gamma_ramps: HashMap::new(), powered_off_outputs: HashMap::new(), headless_outputs: Vec::new(), @@ -2040,6 +2046,7 @@ impl ShojiWM { runtime_gesture_pinch_fingers: 0, runtime_dnd_enabled: false, dnd: Default::default(), + toplevel_drag: None, runtime_gesture_swipe: None, runtime_input_grab: None, pending_input_grab_key_event: None, @@ -4869,7 +4876,7 @@ impl ShojiWM { &self, pos: Point, ) -> Option<(WlSurface, Point)> { - for window in self.windows_top_to_bottom() { + for window in self.hit_test_windows_top_to_bottom() { let Some(location) = self.space.element_location(window) else { continue; }; @@ -4958,7 +4965,7 @@ impl ShojiWM { &self, pos: Point, ) -> Option<(WlSurface, Point)> { - for window in self.windows_top_to_bottom() { + for window in self.hit_test_windows_top_to_bottom() { let Some(location) = self.space.element_location(window) else { continue; }; @@ -5083,7 +5090,8 @@ impl ShojiWM { logical_pos: LogicalPoint, ) -> Option<(&Window, &WindowDecorationState)> { let pos = Point::::from((f64::from(logical_pos.x), f64::from(logical_pos.y))); - self.windows_top_to_bottom().into_iter().find_map(|window| { + let windows = self.hit_test_windows_top_to_bottom(); + windows.into_iter().find_map(|window| { let decoration = self.window_decorations.get(window)?; if !self.decoration_allows_input_at(decoration, pos) { return None; @@ -5169,7 +5177,8 @@ impl ShojiWM { pub fn raw_window_under(&self, logical_pos: LogicalPoint) -> Option<(&Window, LogicalRect)> { let pos = Point::::from((f64::from(logical_pos.x), f64::from(logical_pos.y))); - self.windows_top_to_bottom().into_iter().find_map(|window| { + let windows = self.hit_test_windows_top_to_bottom(); + windows.into_iter().find_map(|window| { if let Some(decoration) = self.window_decorations.get(window) && !self.decoration_allows_input_at(decoration, pos) { @@ -5210,6 +5219,16 @@ impl ShojiWM { self.sorted_windows_top_to_bottom(self.space.elements()) } + /// The windows the pointer can land on, top first: all but the one a + /// toplevel drag carries, which must not become its own drop target. + pub fn hit_test_windows_top_to_bottom(&self) -> Vec<&Window> { + let mut windows = self.windows_top_to_bottom(); + if let Some(dragged) = self.dragged_toplevel_surface() { + windows.retain(|window| !Self::is_window_root_surface(window, &dragged)); + } + windows + } + pub fn windows_for_output_top_to_bottom<'a>(&'a self, output: &'a Output) -> Vec<&'a Window> { self.sorted_windows_top_to_bottom( self.space diff --git a/src/shojiwm_lib/src/toplevel_drag.rs b/src/shojiwm_lib/src/toplevel_drag.rs new file mode 100644 index 000000000..885ad4753 --- /dev/null +++ b/src/shojiwm_lib/src/toplevel_drag.rs @@ -0,0 +1,450 @@ +//! Windows moved by a drag and drop (xdg-toplevel-drag-v1). +//! +//! A drag whose `wl_data_source` has an `xdg_toplevel_drag_v1` carries the +//! toplevel attached to it: the window follows the pointer, with the client's +//! offset between the pointer and the window geometry's top-left corner. The +//! move goes through [`WindowMove`], as an interactive move does, so a config +//! sees `onWindowMove` with the source `toplevel-drag` and keeps its +//! snapping, tiling and workspace rules. When the drag ends, the window stays +//! where the move left it. +//! +//! The carried window is left out of hit testing +//! (`hit_test_windows_top_to_bottom`), so it never becomes its own drop +//! target: the drop lands on what is under it. +//! +//! A torn-off tab attaches its new window before the window has a buffer. +//! Until then the window is placed directly, so its first frame shows at +//! the pointer; the move, and the config's events, start on the commit that +//! maps it. A window that unmaps is detached, as the protocol says. +//! +//! smithay's `DnDGrab` knows nothing of this. [`ToplevelDragGrab`] wraps it +//! and moves the window on each pointer motion before the grab sees it. + +use smithay::{ + backend::renderer::utils::with_renderer_surface_state, + desktop::Window, + input::pointer::{ + AxisFrame, ButtonEvent, GestureHoldBeginEvent, GestureHoldEndEvent, GesturePinchBeginEvent, + GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent, + GestureSwipeEndEvent, GestureSwipeUpdateEvent, GrabStartData as PointerGrabStartData, + MotionEvent, PointerGrab, PointerInnerHandle, RelativeMotionEvent, + }, + reexports::wayland_server::protocol::{wl_data_source::WlDataSource, wl_surface::WlSurface}, + utils::{Logical, Point, Rectangle}, +}; +use wayland_protocols::xdg::{ + shell::server::xdg_toplevel::XdgToplevel, + toplevel_drag::v1::server::xdg_toplevel_drag_v1::XdgToplevelDragV1, +}; + +use crate::{ + grabs::move_grab::WindowMove, + protocols::toplevel_drag::{ToplevelDragHandler, ToplevelDragManagerState, toplevel_drag_data}, + ssd::WindowMoveSourceSnapshot, + state::ShojiWM, +}; + +/// The drag object of the drag in progress, and the move of its window. +#[derive(Debug)] +pub(crate) struct ActiveToplevelDrag { + drag: XdgToplevelDragV1, + /// Set once the attached window is mapped. + window_move: Option, +} + +fn window_has_buffer(window: &Window) -> bool { + window.toplevel().is_some_and(|toplevel| { + with_renderer_surface_state(toplevel.wl_surface(), |state| state.buffer().is_some()) + .unwrap_or(false) + }) +} + +/// Where the window geometry's top-left corner goes for the pointer at +/// `pointer`. +fn window_location_for_pointer( + pointer: Point, + offset: Point, +) -> Point { + (pointer - offset.to_f64()).to_i32_round() +} + +impl ShojiWM { + /// `start_drag` with `source`: when the source has a drag object, the + /// drag carries its toplevel. Not from inside a pointer grab. + pub(crate) fn begin_toplevel_drag(&mut self, source: &WlDataSource) { + self.end_toplevel_drag(); + let Some(drag) = self.toplevel_drag_manager_state.drag_for_source(source) else { + return; + }; + if !toplevel_drag_data(&drag).with(|machine| machine.start()) { + return; + } + self.toplevel_drag = Some(ActiveToplevelDrag { + drag, + window_move: None, + }); + self.place_attached_toplevel(); + } + + /// The drag was dropped or cancelled: the toplevel is no longer + /// attached. Safe inside the grab; the move itself ends in + /// [`Self::end_toplevel_drag`]. + pub(crate) fn mark_toplevel_drag_ended(&mut self) { + if let Some(active) = self.toplevel_drag.as_ref() { + toplevel_drag_data(&active.drag).with(|machine| machine.end()); + } + } + + /// The drag is over: the window stays where it is. + pub(crate) fn end_toplevel_drag(&mut self) { + self.stop_toplevel_drag_move(); + if let Some(active) = self.toplevel_drag.take() { + toplevel_drag_data(&active.drag).with(|machine| machine.end()); + } + } + + /// The root surface of the window the drag carries. + pub(crate) fn dragged_toplevel_surface(&self) -> Option { + let active = self.toplevel_drag.as_ref()?; + let toplevel = toplevel_drag_data(&active.drag) + .with(|machine| machine.attached().map(|attached| attached.toplevel.clone()))?; + let surface = self.xdg_shell_state.get_toplevel(&toplevel)?; + Some(surface.wl_surface().clone()) + } + + /// The attached window and the pointer's offset in it. + fn attached_window(&self) -> Option<(Window, Point)> { + let active = self.toplevel_drag.as_ref()?; + let offset = toplevel_drag_data(&active.drag) + .with(|machine| machine.attached().map(|attached| attached.offset))?; + let surface = self.dragged_toplevel_surface()?; + let window = self + .space + .elements() + .find(|window| { + window + .toplevel() + .is_some_and(|toplevel| toplevel.wl_surface() == &surface) + }) + .cloned()?; + Some((window, offset)) + } + + /// Put the attached window under the pointer, and start its move once + /// it is mapped. Not from inside a pointer grab: the move's start asks + /// the config at once. + fn place_attached_toplevel(&mut self) { + let Some(pointer) = self.seat.get_pointer() else { + return; + }; + let location = pointer.current_location(); + let Some((window, offset)) = self.attached_window() else { + self.stop_toplevel_drag_move(); + return; + }; + let moving = self + .toplevel_drag + .as_ref() + .and_then(|active| active.window_move.as_ref()) + .map(|window_move| window_move.window == window); + match moving { + Some(true) => { + self.move_attached_toplevel(location); + return; + } + // Another window took the attachment. + Some(false) => self.stop_toplevel_drag_move(), + None => {} + } + + let target = window_location_for_pointer(location, offset); + if !window_has_buffer(&window) { + self.space.map_element(window, target, false); + self.schedule_redraw(); + return; + } + let current = self.space.element_location(&window).unwrap_or(target); + let rect = self + .managed_resize_initial_rect(&window, Rectangle::new(current, window.geometry().size)); + // The config's rect may include decorations: shift it with the window. + let rect = Rectangle::new(rect.loc + (target - current), rect.size); + let mut window_move = WindowMove::new( + window, + location, + target, + rect, + WindowMoveSourceSnapshot::ToplevelDrag, + ); + window_move.notify_start(self); + window_move.motion(self, location); + if let Some(active) = self.toplevel_drag.as_mut() { + active.window_move = Some(window_move); + } else { + window_move.finish(self); + } + } + + /// Move the window of the started move to follow `location`. + fn move_attached_toplevel(&mut self, location: Point) { + let Some(mut window_move) = self + .toplevel_drag + .as_mut() + .and_then(|active| active.window_move.take()) + else { + return; + }; + window_move.motion(self, location); + match self.toplevel_drag.as_mut() { + Some(active) => active.window_move = Some(window_move), + None => window_move.finish(self), + } + } + + /// The pointer moved during the drag (from [`ToplevelDragGrab`], with + /// the pointer's lock held). + fn toplevel_drag_motion(&mut self, location: Point) { + let Some(active) = self.toplevel_drag.as_ref() else { + return; + }; + if active.window_move.is_some() { + self.move_attached_toplevel(location); + return; + } + let Some((window, offset)) = self.attached_window() else { + return; + }; + if window_has_buffer(&window) { + // Mapped, but the move has not started: it starts outside the + // grab. + self.loop_handle + .insert_idle(|state| state.place_attached_toplevel()); + return; + } + self.space + .map_element(window, window_location_for_pointer(location, offset), false); + self.schedule_redraw(); + } + + /// A surface committed: the attached window may have mapped or + /// unmapped. + pub(crate) fn toplevel_drag_commit(&mut self, surface: &WlSurface) { + let Some(active) = self.toplevel_drag.as_ref() else { + return; + }; + let moving = active.window_move.is_some(); + let Some((window, _)) = self.attached_window() else { + return; + }; + if !window + .toplevel() + .is_some_and(|toplevel| toplevel.wl_surface() == surface) + { + return; + } + match (window_has_buffer(&window), moving) { + (true, false) => self.place_attached_toplevel(), + (false, true) => { + // An unmapped toplevel is detached; the client attaches it + // again after it maps, if it wants. + if let Some(active) = self.toplevel_drag.as_ref() + && let Some(toplevel) = window.toplevel() + { + toplevel_drag_data(&active.drag) + .with(|machine| machine.detach(toplevel.xdg_toplevel())); + } + self.stop_toplevel_drag_move(); + } + _ => {} + } + } + + /// A toplevel is destroyed: if the drag carries it, it is detached. + pub(crate) fn toplevel_drag_toplevel_destroyed(&mut self, toplevel: &XdgToplevel) { + let Some(active) = self.toplevel_drag.as_ref() else { + return; + }; + if toplevel_drag_data(&active.drag).with(|machine| machine.detach(toplevel)) { + self.stop_toplevel_drag_move(); + } + } + + fn stop_toplevel_drag_move(&mut self) { + let Some(window_move) = self + .toplevel_drag + .as_mut() + .and_then(|active| active.window_move.take()) + else { + return; + }; + self.pointer_dispatch.discard_grab_motion(); + window_move.finish(self); + } +} + +impl ToplevelDragHandler for ShojiWM { + fn toplevel_drag_manager_state(&mut self) -> &mut ToplevelDragManagerState { + &mut self.toplevel_drag_manager_state + } + + fn toplevel_drag_attached(&mut self, drag: &XdgToplevelDragV1) { + if self + .toplevel_drag + .as_ref() + .is_some_and(|active| active.drag == *drag) + { + self.place_attached_toplevel(); + } + } + + fn toplevel_drag_destroyed(&mut self, drag: &XdgToplevelDragV1) { + if self + .toplevel_drag + .as_ref() + .is_some_and(|active| active.drag == *drag) + { + self.end_toplevel_drag(); + } + } +} + +/// A pointer grab that moves the attached window on each motion, then +/// hands every event to `inner` (smithay's `DnDGrab`). +pub(crate) struct ToplevelDragGrab { + pub inner: G, +} + +impl> PointerGrab for ToplevelDragGrab { + fn motion( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + focus: Option<(WlSurface, Point)>, + event: &MotionEvent, + ) { + data.toplevel_drag_motion(event.location); + self.inner.motion(data, handle, focus, event); + } + + fn relative_motion( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + focus: Option<(WlSurface, Point)>, + event: &RelativeMotionEvent, + ) { + self.inner.relative_motion(data, handle, focus, event); + } + + fn button( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + event: &ButtonEvent, + ) { + self.inner.button(data, handle, event); + } + + fn axis( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + details: AxisFrame, + ) { + self.inner.axis(data, handle, details); + } + + fn frame(&mut self, data: &mut ShojiWM, handle: &mut PointerInnerHandle<'_, ShojiWM>) { + self.inner.frame(data, handle); + } + + fn gesture_swipe_begin( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + event: &GestureSwipeBeginEvent, + ) { + self.inner.gesture_swipe_begin(data, handle, event); + } + + fn gesture_swipe_update( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + event: &GestureSwipeUpdateEvent, + ) { + self.inner.gesture_swipe_update(data, handle, event); + } + + fn gesture_swipe_end( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + event: &GestureSwipeEndEvent, + ) { + self.inner.gesture_swipe_end(data, handle, event); + } + + fn gesture_pinch_begin( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + event: &GesturePinchBeginEvent, + ) { + self.inner.gesture_pinch_begin(data, handle, event); + } + + fn gesture_pinch_update( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + event: &GesturePinchUpdateEvent, + ) { + self.inner.gesture_pinch_update(data, handle, event); + } + + fn gesture_pinch_end( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + event: &GesturePinchEndEvent, + ) { + self.inner.gesture_pinch_end(data, handle, event); + } + + fn gesture_hold_begin( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + event: &GestureHoldBeginEvent, + ) { + self.inner.gesture_hold_begin(data, handle, event); + } + + fn gesture_hold_end( + &mut self, + data: &mut ShojiWM, + handle: &mut PointerInnerHandle<'_, ShojiWM>, + event: &GestureHoldEndEvent, + ) { + self.inner.gesture_hold_end(data, handle, event); + } + + fn start_data(&self) -> &PointerGrabStartData { + self.inner.start_data() + } + + fn unset(&mut self, data: &mut ShojiWM) { + self.inner.unset(data); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_window_keeps_the_offset_the_client_gave_under_the_pointer() { + let location = window_location_for_pointer(Point::from((300.4, 200.6)), (40, 10).into()); + assert_eq!(location, Point::from((260, 191))); + } +} diff --git a/src/shojiwm_rs/tests/toplevel_drag.rs b/src/shojiwm_rs/tests/toplevel_drag.rs new file mode 100644 index 000000000..722c62861 --- /dev/null +++ b/src/shojiwm_rs/tests/toplevel_drag.rs @@ -0,0 +1,305 @@ +//! xdg-toplevel-drag-v1: a window attached to a data drag follows the +//! pointer with the client's offset, stays where the drop leaves it, and is +//! never the drop target itself. + +mod common; + +use std::cell::RefCell; + +use smithay::{ + backend::input::ButtonState, + input::pointer::{ButtonEvent, MotionEvent}, + reexports::wayland_server::Resource, + utils::{Logical, Point, SERIAL_COUNTER}, +}; +use wayland_client::{ + Connection, Dispatch, Proxy, QueueHandle, event_created_child, + protocol::{ + wl_compositor, wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, + wl_pointer, wl_seat, wl_surface, + }, +}; +use wayland_protocols::xdg::{ + shell::client::{xdg_toplevel, xdg_wm_base}, + toplevel_drag::v1::client::{xdg_toplevel_drag_manager_v1, xdg_toplevel_drag_v1}, +}; + +const BTN_LEFT: u32 = 0x110; + +thread_local! { + static EVENTS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +#[derive(Debug, Clone, PartialEq)] +enum Seen { + Button(u32), + DragEnter(u32), + Drop, +} + +fn seen() -> Vec { + EVENTS.with(|events| events.borrow().clone()) +} + +fn setup() {} + +/// The client's side of a drag: the seat's pointer and data device. +struct Drag { + devices: wl_data_device_manager::WlDataDeviceManager, + device: wl_data_device::WlDataDevice, + manager: xdg_toplevel_drag_manager_v1::XdgToplevelDragManagerV1, +} + +impl Drag { + fn new(session: &mut common::Session) -> Self { + let qh = session.queue.handle(); + let seat: wl_seat::WlSeat = session.bind("wl_seat", 1); + seat.get_pointer(&qh, ()); + let devices: wl_data_device_manager::WlDataDeviceManager = + session.bind("wl_data_device_manager", 1); + let device = devices.get_data_device(&seat, &qh, ()); + let manager = session.bind("xdg_toplevel_drag_manager_v1", 1); + Self { + devices, + device, + manager, + } + } + + /// Press on `origin` and start a drag of a new source; returns the + /// source's toplevel drag object. + fn start( + &self, + session: &mut common::Session, + origin: &wl_surface::WlSurface, + attach_first: Option<(&xdg_toplevel::XdgToplevel, i32, i32)>, + ) -> xdg_toplevel_drag_v1::XdgToplevelDragV1 { + button(session, ButtonState::Pressed); + let Some(Seen::Button(serial)) = seen().last().cloned() else { + panic!("no button press reached the client: {:?}", seen()); + }; + let qh = session.queue.handle(); + let source = self.devices.create_data_source(&qh, ()); + source.offer("text/plain".into()); + let drag = self.manager.get_xdg_toplevel_drag(&source, &qh, ()); + if let Some((toplevel, x, y)) = attach_first { + drag.attach(toplevel, x, y); + } + self.device.start_drag(Some(&source), origin, None, serial); + session.roundtrip(); + drag + } +} + +/// A toplevel with `app_id`; with a `width`x`height` buffer, or none yet. +fn toplevel( + session: &mut common::Session, + app_id: &str, + buffer: Option<(i32, i32)>, +) -> (wl_surface::WlSurface, xdg_toplevel::XdgToplevel) { + let qh = session.queue.handle(); + let compositor: wl_compositor::WlCompositor = session.bind("wl_compositor", 1); + let shell: xdg_wm_base::XdgWmBase = session.bind("xdg_wm_base", 1); + let surface = compositor.create_surface(&qh, ()); + let xdg = shell.get_xdg_surface(&surface, &qh, ()); + let toplevel = xdg.get_toplevel(&qh, ()); + toplevel.set_app_id(app_id.into()); + surface.commit(); + session.roundtrip(); + if let Some((width, height)) = buffer { + session.attach_buffer(&surface, width, height); + } + (surface, toplevel) +} + +fn window_of( + session: &common::Session, + surface: &wl_surface::WlSurface, +) -> smithay::desktop::Window { + let id = Proxy::id(surface).protocol_id(); + session + .state + .space + .elements() + .find(|window| { + window + .toplevel() + .is_some_and(|toplevel| toplevel.wl_surface().id().protocol_id() == id) + }) + .cloned() + .expect("the toplevel is in the space") +} + +fn location(session: &common::Session, surface: &wl_surface::WlSurface) -> Point { + let window = window_of(session, surface); + session.state.space.element_location(&window).unwrap() +} + +fn place(session: &mut common::Session, surface: &wl_surface::WlSurface, x: i32, y: i32) { + let window = window_of(session, surface); + session.state.space.map_element(window, (x, y), false); +} + +fn move_pointer(session: &mut common::Session, x: f64, y: f64) { + let state = &mut session.state; + let pointer = state.seat.get_pointer().unwrap(); + let location = (x, y).into(); + state.pointer_contents = state.pointer_contents_at(location); + let under = state.pointer_contents.surface.clone(); + pointer.motion( + state, + under, + &MotionEvent { + location, + serial: SERIAL_COUNTER.next_serial(), + time: 0, + }, + ); + pointer.frame(state); + session.roundtrip(); +} + +fn button(session: &mut common::Session, state: ButtonState) { + let pointer = session.state.seat.get_pointer().unwrap(); + pointer.button( + &mut session.state, + &ButtonEvent { + serial: SERIAL_COUNTER.next_serial(), + time: 0, + button: BTN_LEFT, + state, + }, + ); + pointer.frame(&mut session.state); + session.roundtrip(); +} + +#[test] +fn an_attached_window_follows_the_pointer_and_is_not_the_drop_target() { + let mut session = common::Session::new(setup); + let (below, _) = toplevel(&mut session, "below", Some((300, 300))); + let (dragged, dragged_toplevel) = toplevel(&mut session, "dragged", Some((200, 150))); + place(&mut session, &below, 500, 300); + place(&mut session, &dragged, 50, 50); + let drag = Drag::new(&mut session); + + move_pointer(&mut session, 100.0, 100.0); + let object = drag.start(&mut session, &dragged, Some((&dragged_toplevel, 30, 20))); + assert_eq!( + location(&session, &dragged), + Point::from((70, 80)), + "the window jumps to keep the offset under the pointer" + ); + + move_pointer(&mut session, 600.0, 400.0); + assert_eq!(location(&session, &dragged), Point::from((570, 380))); + // The dragged window covers the pointer, yet the window below is the + // target. + let below_id = Proxy::id(&below).protocol_id(); + assert_eq!(seen().last(), Some(&Seen::DragEnter(below_id))); + + button(&mut session, ButtonState::Released); + assert_eq!(seen().last(), Some(&Seen::Drop)); + move_pointer(&mut session, 10.0, 10.0); + assert_eq!( + location(&session, &dragged), + Point::from((570, 380)), + "the window stays where the drop left it" + ); + // Destroying the object after the drop is allowed: no protocol error + // (a roundtrip would fail on one). + object.destroy(); + session.roundtrip(); +} + +#[test] +fn a_torn_off_window_is_placed_before_its_first_buffer() { + let mut session = common::Session::new(setup); + let (below, _) = toplevel(&mut session, "below", Some((300, 300))); + place(&mut session, &below, 500, 300); + let drag = Drag::new(&mut session); + + move_pointer(&mut session, 600.0, 400.0); + let object = drag.start(&mut session, &below, None); + + // The tab leaves the window: a new toplevel, attached before it maps. + let (torn, torn_toplevel) = toplevel(&mut session, "torn", None); + object.attach(&torn_toplevel, 10, 10); + session.roundtrip(); + assert_eq!(location(&session, &torn), Point::from((590, 390))); + + move_pointer(&mut session, 200.0, 200.0); + assert_eq!(location(&session, &torn), Point::from((190, 190))); + session.attach_buffer(&torn, 100, 100); + assert_eq!(location(&session, &torn), Point::from((190, 190))); + + move_pointer(&mut session, 550.0, 350.0); + assert_eq!(location(&session, &torn), Point::from((540, 340))); + let below_id = Proxy::id(&below).protocol_id(); + assert_eq!(seen().last(), Some(&Seen::DragEnter(below_id))); + + button(&mut session, ButtonState::Released); + assert_eq!(seen().last(), Some(&Seen::Drop)); + object.destroy(); + session.roundtrip(); +} + +impl Dispatch for common::Client { + fn event( + _: &mut Self, + _: &wl_pointer::WlPointer, + event: wl_pointer::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + if let wl_pointer::Event::Button { + serial, + state: wayland_client::WEnum::Value(wl_pointer::ButtonState::Pressed), + .. + } = event + { + EVENTS.with(|events| events.borrow_mut().push(Seen::Button(serial))); + } + } +} + +impl Dispatch for common::Client { + fn event( + _: &mut Self, + _: &wl_data_device::WlDataDevice, + event: wl_data_device::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + let seen = match event { + wl_data_device::Event::Enter { surface, .. } => { + Seen::DragEnter(surface.id().protocol_id()) + } + wl_data_device::Event::Drop => Seen::Drop, + _ => return, + }; + EVENTS.with(|events| events.borrow_mut().push(seen)); + } + + event_created_child!(common::Client, wl_data_device::WlDataDevice, [ + wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()), + ]); +} + +macro_rules! ignore_events { + ($($proxy:ty),*) => {$( + impl Dispatch<$proxy, ()> for common::Client { + fn event(_: &mut Self, _: &$proxy, _: <$proxy as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle) {} + } + )*}; +} + +ignore_events!( + wl_data_device_manager::WlDataDeviceManager, + wl_data_offer::WlDataOffer, + wl_data_source::WlDataSource, + xdg_toplevel_drag_manager_v1::XdgToplevelDragManagerV1, + xdg_toplevel_drag_v1::XdgToplevelDragV1 +);