diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index b386352e..ac23ca20 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -28,6 +28,7 @@ use crate::splash::mdm_enrollment; use crate::state::State; use crate::window::AdhocWindow; use crate::window::RuleDebug; +use crate::window::Snapping; use crate::window::Window; use crate::window::should_act; use crate::window_manager::WindowManager; @@ -89,6 +90,13 @@ pub fn listen_for_events(wm: Arc>) { impl WindowManager { #[instrument(skip_all)] pub fn process_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> { + // the step is off the channel whatever is done about it, and the next that comes waits for + // this one to begin and no longer, which is not so if it is left to where it is handled: + // nothing is handled while paused, or on another space + if matches!(event, WindowManagerEvent::ResizeStep(_, _, _)) { + window_manager_event_listener::resize_step_taken(); + } + if matches!(event, WindowManagerEvent::ScreenLock(_, _)) { let application = self.application(event.process_id())?; if application.name().unwrap_or_default() == "loginwindow" { @@ -132,6 +140,14 @@ impl WindowManager { return Ok(()); } + // A step of a drag says only that the window has moved, and is handled before anything that + // is done for the other events: they ask the app of the window things, which is time that + // the windows next to the edge spend not following it, and a step is not in anybody's + // subscription for the same reason + if let WindowManagerEvent::ResizeStep(_, _, window_id) = event { + return self.live_resize_step(window_id); + } + let mut rule_debug = RuleDebug::default(); let mut should_manage = true; @@ -842,7 +858,17 @@ impl WindowManager { let pending_move_op = Arc::make_mut(&mut self.pending_move_op); *pending_move_op = None; - if let Some((origin_monitor_idx, origin_workspace_idx, wid)) = pending { + // The window of a drag by an edge that the windows next to it follow is where the + // layout has put its tile, and not where somebody has moved it to, so it is not a + // move that it ends + let following_drag = self + .live_resize + .as_ref() + .is_some_and(|live| live.window == window_id); + + if let Some((origin_monitor_idx, origin_workspace_idx, wid)) = pending + && !following_drag + { // If the window handles don't match then something went wrong and the pending move // is not related to this current move, if so abort this operation. if wid != window_id { @@ -1042,60 +1068,125 @@ impl WindowManager { } } WindowManagerEvent::ResizeStart(_, _, window_id) => { - animator::cancel(window_id); - - // AXWindowResized fires again and again through a drag; only the first frame is - // the one the drag started from - let already_recorded = matches!( - *self.pending_resize_op, - Some((wid, Some(_))) if wid == window_id - ); - - if !already_recorded { - let workspace = self.focused_workspace()?; - if let Some(container) = workspace.container_for_window(window_id) - && let Some(window) = container.windows().iter().find(|w| w.id == window_id) + // While an edge is dragged the windows next to it are laid out again and again, + // and they say that they were resized, which is not somebody dragging them. Most + // of that is dropped where it is heard, but what was heard before the drag was + // followed is dropped here, since taking it for a drag would lose the one that + // is going on. + if self.another_window_is_being_dragged(window_id) { + tracing::debug!( + "ignoring the start of a resize of window {window_id}: it is following a drag" + ); + } else { + // a drag that was followed, and whose end was never heard + if self + .live_resize + .as_ref() + .is_some_and(|live| live.window != window_id) { - let started_from = Rect::from(MacosApi::window_rect(&window.element)?); + self.live_resize_forget(); + } - let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); - *pending_resize_op = Option::from((window_id, Some(started_from))); + animator::cancel(window_id); + + // AXWindowResized fires again and again through a drag; only the first frame is + // the one the drag started from + let already_recorded = matches!( + *self.pending_resize_op, + Some((wid, Some(_))) if wid == window_id + ); + + if !already_recorded { + let workspace = self.focused_workspace()?; + if let Some(container) = workspace.container_for_window(window_id) + && let Some(window) = + container.windows().iter().find(|w| w.id == window_id) + { + let started_from = Rect::from(MacosApi::window_rect(&window.element)?); + + let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); + *pending_resize_op = Option::from((window_id, Some(started_from))); + + // the windows next to the edge follow it from here + self.live_resize_begin(window_id); + + // the edges at the left and at the top move the window as well, which + // is somebody resizing it, and not moving it + if self.live_resize.is_some() + && matches!( + *self.pending_move_op, + Some((_, _, wid)) if wid == window_id + ) + { + let pending_move_op = Arc::make_mut(&mut self.pending_move_op); + *pending_move_op = None; + } + } } } } WindowManagerEvent::ResizeEnd(_, _, window_id) => { + // The drag is over, and so is anything that followed it. The windows next to the + // edge are what the layout was when it began, for the end to be worked out from + // there, as it is when there were no steps. + let dragged = self.live_resize.as_ref().map(|live| live.window); + let stepped = self.live_resize_end(); + let pending = *self.pending_resize_op; // Always consume the pending resize op whenever this event is handled let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); *pending_resize_op = None; + // The end of a drag that was followed is the end of that drag, whichever window + // the event is about: the windows next to the edge say that they were resized as + // the button goes up, and it is the window that was dragged that is looked at. + let window_id = match (dragged, pending) { + (Some(dragged), Some((wid, _))) if wid == dragged => dragged, + _ => window_id, + }; + + // the windows next to the edge are where the last step put them, a few pixels from + // where the end of the drag does, which is not worth animating + let _snapping = stepped.then(Snapping::end); + + let mut redraw = stepped; + let mut mismatched = None; + if let Some((wid, Some(started_from))) = pending { - // If the window handles don't match then something went wrong and the pending resize - // is not related to this current resize, if so abort this operation. if wid != window_id { - eyre::bail!( - "window handles for resize operation don't match: {} != {}", - wid, - window_id - ); - } + mismatched = Some(wid); + } else { + let workspace = self.focused_workspace()?; + if workspace.tile + && let Some(container) = workspace.container_for_window(window_id) + && let Some(window) = + container.windows().iter().find(|w| w.id == window_id) + { + let ended_at = Rect::from(MacosApi::window_rect(&window.element)?); - let workspace = self.focused_workspace()?; - if workspace.tile - && let Some(container) = workspace.container_for_window(window_id) - && let Some(window) = container.windows().iter().find(|w| w.id == window_id) - { - let ended_at = Rect::from(MacosApi::window_rect(&window.element)?); - - tracing::info!("resizing with mouse"); - if self.resize_by_drag(window_id, started_from, ended_at)? { - self.update_focused_workspace(false, false)?; + tracing::info!("resizing with mouse"); + redraw |= self.resize_by_drag(window_id, started_from, ended_at)?; } } } + + if redraw { + self.update_focused_workspace(false, false)?; + } + + // If the window handles don't match then something went wrong and the pending resize + // is not related to this current resize, if so abort this operation. + if let Some(wid) = mismatched { + eyre::bail!( + "window handles for resize operation don't match: {} != {}", + wid, + window_id + ); + } } // handled before this match - WindowManagerEvent::SpaceChange(_, _) + WindowManagerEvent::ResizeStep(_, _, _) + | WindowManagerEvent::SpaceChange(_, _) | WindowManagerEvent::ScreenLock(_, _) | WindowManagerEvent::ScreenUnlock(_, _) => {} } diff --git a/komorebi/src/scrolling.rs b/komorebi/src/scrolling.rs index 0b03b11a..5f5b3719 100644 --- a/komorebi/src/scrolling.rs +++ b/komorebi/src/scrolling.rs @@ -22,6 +22,7 @@ use crate::core::Sizing; use crate::core::WindowHidingPosition; use crate::core_graphics::CoreGraphicsApi; use crate::is_visible_on_another_display; +use crate::window::is_stepping; use crate::workspace::Workspace; use crate::workspace::clamp_to_work_area; use color_eyre::eyre; @@ -179,9 +180,16 @@ impl Workspace { // what a column takes up around its window on either side let around_window = container_padding + border_offset + border_width; + // windows next to an edge that is dragged are laid out for every step of the drag, and + // what they have turned out to be is not asked: a window that has not settled is not what + // it will be, and a column is never made narrower again once it was made wider for it + let stepping = is_stepping(); + // windows that were not what they were told to be since the last layout, which is where // the animator says so - self.adopt_actual_sizes(around_window, adjusted_work_area.right); + if !stepping { + self.adopt_actual_sizes(around_window, adjusted_work_area.right); + } self.place_scrolling( work_area, @@ -195,7 +203,7 @@ impl Workspace { // window that refused is known by now, and everything after it is placed again with room // for it. Once is enough: the sizes that are read back this time round are picked up by // the next layout, and a layout is never made to chase them. - if self.adopt_actual_sizes(around_window, adjusted_work_area.right) { + if !stepping && self.adopt_actual_sizes(around_window, adjusted_work_area.right) { self.place_scrolling( work_area, adjusted_work_area, @@ -700,10 +708,9 @@ impl Workspace { sizing: Sizing, delta: i32, ) { - let Some(id) = self - .focused_container() - .map(|container| container.id.clone()) - else { + // the left edge of a column is moved by panning the strip, which is only done for the + // active column of the space, so the space has to agree about which one that is + let Some(id) = self.focused_scrolling_column() else { return; }; @@ -973,6 +980,48 @@ mod tests { ); } + /// Where the edges of the column at `idx` are, from the left and the right + fn edges_of(placements: &[ScrollingPlacement], idx: usize) -> (i32, i32) { + let rect = placements[idx].rect; + + (rect.left, rect.left + rect.right) + } + + #[test] + fn resizing_by_the_left_edge_moves_that_edge_and_keeps_the_right_one() { + let mut workspace = workspace(3, 3); + let before = workspace.layout_scrolling(&AREA, 0); + let (left, right) = edges_of(&before, 2); + + workspace.resize_scrolling_column(OperationDirection::Left, Sizing::Increase, 100); + let after = workspace.layout_scrolling(&AREA, 0); + + assert_eq!(edges_of(&after, 2), (left - 50, right)); + + // and moving it back puts it back + workspace.resize_scrolling_column(OperationDirection::Left, Sizing::Decrease, 100); + assert_eq!( + edges_of(&workspace.layout_scrolling(&AREA, 0), 2), + (left, right) + ); + } + + #[test] + fn resizing_a_column_that_has_focus_but_is_not_the_active_one_moves_its_left_edge_too() { + // dragging the edge of a window moves the focus of the workspace to its container, and the + // strip is only told about that when something asks it to lay out + let mut workspace = workspace(3, 5); + workspace.focus_container(0); + let before = workspace.layout_scrolling(&AREA, 0); + let (left, right) = edges_of(&before, 1); + + workspace.focus_container(1); + workspace.resize_scrolling_column(OperationDirection::Left, Sizing::Increase, 100); + let after = workspace.layout_scrolling(&AREA, 0); + + assert_eq!(edges_of(&after, 1), (left - 50, right)); + } + #[test] fn a_column_is_as_tall_as_the_work_area_so_resizing_its_height_does_nothing() { let mut workspace = workspace(3, 2); diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index 39050660..a16fdbc3 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -1218,6 +1218,7 @@ impl StaticConfig { minimized_windows: HashMap::new(), pending_move_op: Arc::new(None), pending_resize_op: Arc::new(None), + live_resize: None, already_moved_window_handles: Default::default(), known_window_ids: HashMap::new(), }; diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 2fddaca1..d1229cac 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -96,6 +96,8 @@ use std::path::Path; use std::path::PathBuf; use std::ptr::NonNull; use std::str::FromStr; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; use strum::Display; use strum::EnumString; use tracing::instrument; @@ -123,6 +125,131 @@ lazy_static::lazy_static! { /// How long, in seconds, to wait for a window to say how big it is after it was resized const ARRIVAL_TIMEOUT: f32 = 1.0; +/// The window that somebody is dragging by an edge while the windows next to it follow +/// +/// Nothing is dragged while the mouse button is up, so a button that went up without anything +/// saying so, which is what a tap that was turned off does, cannot leave the window of a drag that +/// is long over being treated as one that is going on. +#[derive(Debug, Default)] +struct Drag { + /// The id of the window, or nought for none, which is no id that a window has + window: AtomicU32, +} + +impl Drag { + fn begin(&self, window_id: u32) { + self.window.store(window_id, Ordering::SeqCst); + } + + fn end(&self) { + self.window.store(0, Ordering::SeqCst); + } + + /// The window that is being dragged, if there is one, given a way to find out whether the + /// button is down, which is only asked if there is a drag to ask about: this is for every + /// move and resize that any window says. + /// + /// With the button up there is nothing being dragged, and nothing is going to say so, so it is + /// forgotten here. + fn window(&self, mouse_is_down: impl FnOnce() -> bool) -> Option { + let window_id = self.window.load(Ordering::SeqCst); + + if window_id == 0 { + return None; + } + + if !mouse_is_down() { + let _ = self + .window + .compare_exchange(window_id, 0, Ordering::SeqCst, Ordering::SeqCst); + + return None; + } + + Some(window_id) + } +} + +static DRAG: Drag = Drag { + window: AtomicU32::new(0), +}; + +/// How windows are put where a layout says while the windows next to one that is dragged follow it +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Snap { + /// The way it always is + Off, + /// For a step of the drag of the window with this id + Step(u32), + /// For the end of a drag that was followed + End, +} + +lazy_static::lazy_static! { + static ref SNAP: parking_lot::Mutex = parking_lot::Mutex::new(Snap::Off); + + /// Where every window was last sent in the steps of the drag that is going on, so that a window + /// that would be sent where it is already is left alone + static ref SENT: parking_lot::Mutex> = + parking_lot::Mutex::new(HashMap::new()); +} + +fn snap() -> Snap { + *SNAP.lock() +} + +/// Lays out what is laid out while it is alive straight into place and not by animation, as the +/// windows next to one that is dragged follow it, and are not to be seen catching up. +pub struct Snapping; + +impl Snapping { + /// For a step of the drag of the window `dragged`, which is left to the person dragging it, and + /// which does not wait to be told what the windows turned out to be, nor send a window where it + /// was sent last. + pub fn step(dragged: u32) -> Self { + *SNAP.lock() = Snap::Step(dragged); + Self + } + + /// For the end of a drag that was followed: the windows are a few pixels from where the end of + /// the drag puts them, which is not worth animating, and every one of them is sent there. + pub fn end() -> Self { + *SNAP.lock() = Snap::End; + Self + } +} + +impl Drop for Snapping { + fn drop(&mut self) { + *SNAP.lock() = Snap::Off; + } +} + +/// Whether the windows are being laid out for a step of a drag, in which what a window turned out to +/// be is not asked, since a window that has not settled would say something that is not true. +pub fn is_stepping() -> bool { + matches!(snap(), Snap::Step(_)) +} + +/// Somebody has taken hold of the edge of a window, and the windows next to it follow it from +/// here until [`live_resize_ends`]. +pub fn live_resize_begins(window_id: u32) { + SENT.lock().clear(); + DRAG.begin(window_id); +} + +/// The drag is over. +pub fn live_resize_ends() { + DRAG.end(); + SENT.lock().clear(); +} + +/// The window that somebody is dragging by an edge while the windows next to it follow, which is +/// none unless the button is down. +pub fn dragged_window() -> Option { + DRAG.window(MacosApi::left_mouse_button_is_pressed) +} + const NOTIFICATIONS: &[&str] = &[ kAXWindowMiniaturizedNotification, kAXWindowDeminiaturizedNotification, @@ -153,6 +280,24 @@ unsafe extern "C-unwind" fn window_observer_callback( ) = notification && let Some(window_id) = window_id { + // While an edge is dragged the windows next to it are laid out again and again, and + // every one of them says so, with the mouse button down: it would be taken for somebody + // dragging that window. What is said by the window that is being dragged is a step, and + // nothing is asked of its app to say so, since the app is busy with the drag. + if let Some(dragged) = dragged_window() { + if window_id == dragged { + window_manager_event_listener::send_notification( + WindowManagerEvent::ResizeStep( + SystemNotification::Accessibility(moved_or_resized), + process_id, + window_id, + ), + ); + } + + return; + } + let mouse_is_down = MacosApi::left_mouse_button_is_pressed(); let verdict = @@ -562,6 +707,8 @@ impl Window { // goes straight to the other edge let motion = match parked_at { Some(_) => None, + // the windows next to an edge that is dragged follow it, and are not seen sliding + None if snap() != Snap::Off => None, None => animation::motion_for(AnimationPrefix::Movement), }; @@ -741,6 +888,15 @@ impl Window { } pub fn set_position(&self, rect: &Rect) -> Result<(), AccessibilityError> { + match snap() { + Snap::Step(dragged) => return self.set_position_for_step(dragged, rect), + Snap::End => { + PARKED_WINDOWS.lock().remove(&self.id); + return self.set_position_direct(rect); + } + Snap::Off => {} + } + match animation::motion_for(AnimationPrefix::Movement) { Some(motion) => { self.slide_in_from_edge(rect); @@ -761,7 +917,14 @@ impl Window { /// window that was not resized is not asked: that costs a round trip to the app, and what /// the window turned out to be is not going to be any different from last time. pub fn note_arrival(&self, target: &Rect, resized: bool) { - if !resized || animation::motion_for(AnimationPrefix::Movement).is_some() { + // for a step of a drag it is not asked, however the window got there: a round trip to every + // window that was resized, each of which can take as long as the timeout, is time that the + // windows next to the edge spend not following it, and a window that has not settled would + // say that it is wider than it will be + let animated = + snap() == Snap::Off && animation::motion_for(AnimationPrefix::Movement).is_some(); + + if !resized || animated || is_stepping() { return; } @@ -819,6 +982,34 @@ impl Window { } } + /// Put the window where a step of the drag of the window `dragged` says that it goes + /// + /// The window that is being dragged is where the person dragging it has it. Any other goes + /// straight there, without an animation to catch up with the next step, and not at all if it + /// is where it was sent last. + fn set_position_for_step(&self, dragged: u32, rect: &Rect) -> Result<(), AccessibilityError> { + if self.id == dragged { + tracing::debug!("window {} is left alone: it is being dragged", self.id); + + return Ok(()); + } + + if SENT.lock().insert(self.id, *rect) == Some(*rect) { + tracing::debug!( + "window {} is left alone: it is where it was sent last, {rect:?}", + self.id + ); + + return Ok(()); + } + + tracing::debug!("window {} is sent to {rect:?}", self.id); + + // nothing is going to slide it in, so nothing else is going to say that it is back + PARKED_WINDOWS.lock().remove(&self.id); + self.set_position_direct(rect) + } + fn set_position_direct(&self, rect: &Rect) -> Result<(), AccessibilityError> { self.set_point( CGPoint::new(rect.left as CGFloat, rect.top as CGFloat), @@ -1895,3 +2086,66 @@ pub fn should_act_individual( should_act } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nothing_is_dragged_before_a_drag_begins() { + let drag = Drag::default(); + + assert_eq!(drag.window(|| true), None); + assert_eq!(drag.window(|| false), None); + } + + #[test] + fn the_button_is_not_asked_about_when_there_is_no_drag() { + let drag = Drag::default(); + + assert_eq!( + drag.window(|| panic!("nothing was being dragged, so there is nothing to ask")), + None + ); + } + + #[test] + fn the_window_of_a_drag_is_dragged_for_as_long_as_the_button_is_down() { + let drag = Drag::default(); + drag.begin(42); + + assert_eq!(drag.window(|| true), Some(42)); + assert_eq!(drag.window(|| true), Some(42)); + } + + #[test] + fn nothing_is_dragged_once_the_drag_has_ended() { + let drag = Drag::default(); + drag.begin(42); + drag.end(); + + assert_eq!(drag.window(|| true), None); + } + + #[test] + fn a_button_that_went_up_without_the_end_being_seen_leaves_nothing_dragged() { + // the tap that sees the button go up can be turned off, and then nothing says so + let drag = Drag::default(); + drag.begin(42); + + assert_eq!(drag.window(|| false), None); + + // and it is not dragged again by the next time that the button is down + assert_eq!(drag.window(|| true), None); + } + + #[test] + fn a_drag_that_began_is_not_forgotten_by_one_that_ended_before() { + let drag = Drag::default(); + drag.begin(42); + drag.end(); + drag.begin(7); + + assert_eq!(drag.window(|| true), Some(7)); + } +} diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index a0fcd6ec..f8a54917 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1,3 +1,4 @@ +use crate::AccessibilityUiElement; use crate::CoreFoundationRunLoop; use crate::DATA_DIR; use crate::LibraryError; @@ -33,7 +34,11 @@ use crate::monitor::Monitor; use crate::ring::Ring; use crate::static_config::StaticConfig; use crate::window::AdhocWindow; +use crate::window::Snapping; use crate::window::Window; +use crate::window::dragged_window; +use crate::window::live_resize_begins; +use crate::window::live_resize_ends; use crate::window::should_act_individual; use crate::window_manager_event::ManualNotification; use crate::window_manager_event::SystemNotification; @@ -46,6 +51,7 @@ use color_eyre::eyre::OptionExt; use color_eyre::eyre::bail; use crossbeam_channel::Receiver; use hotwatch::Hotwatch; +use komorebi_layouts::scrolling::model::ScrollingSpace; use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFRunLoop; use parking_lot::Mutex; @@ -61,6 +67,43 @@ use std::os::unix::net::UnixStream; use std::path::PathBuf; use std::sync::Arc; +/// What the workspace was when somebody took hold of an edge of a window, and what has been done +/// with it since, so that the windows next to the edge can follow it as it is dragged +/// +/// Every step of the drag, and the end of it, is worked out from this and not from the step +/// before: a drag ends the same with its steps as without them, and one that is taken back to +/// where it began puts the windows next to it back. +#[derive(Debug)] +pub struct LiveResize { + /// The window that is being dragged + pub window: u32, + /// How many containers there were, since a window that opens or closes in the middle of a drag + /// changes what the layout is made of, and what is kept is no longer about it + pub containers: usize, + pub resize_dimensions: Vec>, + pub latest_layout: Vec, + pub scrolling: Option>, + /// Whether the windows next to the edge have been laid out for a step, which is to be put + /// right when the drag ends, whatever it comes to + pub stepped: bool, + /// The windows next to the dragged one and their apps, which are not waited for for as long as + /// they are by default while the drag is on + timeouts: Vec, +} + +/// How long, in seconds, the apps of the windows next to a dragged edge are waited for, which is +/// a good deal less than the time that it takes for an app that does not answer to be given up on: +/// a step is no use to anybody by then +const LIVE_RESIZE_TIMEOUT: f32 = 0.25; + +/// Say how long the apps in `elements` are waited for. Nought is what they are waited for by +/// default. +fn set_messaging_timeouts(elements: &[AccessibilityUiElement], seconds: f32) { + for element in elements { + let _ = AccessibilityApi::set_messaging_timeout(element, seconds); + } +} + #[derive(Debug)] pub struct WindowManager { pub monitors: Ring, @@ -83,6 +126,8 @@ pub struct WindowManager { pub minimized_windows: HashMap, pub pending_move_op: Arc>, pub pending_resize_op: Arc)>>, + /// The workspace as it was when an edge that the windows next to it follow was taken hold of + pub live_resize: Option, pub already_moved_window_handles: Arc>>, /// Maps each known window id to the (monitor, workspace) index pair managing it pub known_window_ids: HashMap, @@ -167,6 +212,7 @@ impl WindowManager { minimized_windows: HashMap::new(), pending_move_op: Arc::new(None), pending_resize_op: Arc::new(None), + live_resize: None, already_moved_window_handles: Default::default(), known_window_ids: Default::default(), }) @@ -1715,6 +1761,63 @@ impl WindowManager { /// its size to a grid of cells, or keeps to a minimum size, is never quite on its tile const DRAG_SNAP_TOLERANCE: i32 = 32; + /// How far an edge can have got between somebody taking hold of it and the start of the drag + /// being handled, which a fast drag makes a good many pixels + const DRAG_LAG_ALLOWANCE: i32 = 64; + + /// Where the edges of a drag began, given the first frame of the window that was seen once the + /// drag was going on, the frame that it is in now and the tile that it was put in. All three + /// are `[left, top, right, bottom]`. + /// + /// The first AXWindowResized is reported after the edge has already moved, and handlers run + /// one at a time, so the frame a drag is first seen in is not the one it began from, and can + /// even be the one it has ended in. + /// + /// * An edge that has moved since the drag was first seen was dragged, and began on its tile + /// if the frame that it was first seen in was no further from it than a fast drag gets + /// before it is handled. Any further and it is measured from where it was seen. + /// * An edge that has not moved was not dragged, and the offset of an app from its tile is not + /// part of the drag, nor is a window that cannot be as small as its tile. + /// * Where nothing has moved at all the drag was over before it was seen, and an edge that is + /// further from its tile than an app strays from its tile on its own was dragged. + fn drag_origin(started: [i32; 4], ended: [i32; 4], tile: Option<[i32; 4]>) -> [i32; 4] { + let Some(tile) = tile else { + return started; + }; + + let seen_moving = started != ended; + + let mut origin = started; + for i in 0..4 { + let began_on_tile = if seen_moving { + ended[i] != started[i] && (started[i] - tile[i]).abs() <= Self::DRAG_LAG_ALLOWANCE + } else { + (ended[i] - tile[i]).abs() > Self::DRAG_SNAP_TOLERANCE + }; + + if began_on_tile { + origin[i] = tile[i]; + } + } + + origin + } + + /// The edges that were moved from `origin` to `ended`, and by how much, which is negative + /// for an edge that went left or up. + fn edges_moved(origin: [i32; 4], ended: [i32; 4]) -> Vec<(OperationDirection, i32)> { + [ + OperationDirection::Left, + OperationDirection::Up, + OperationDirection::Right, + OperationDirection::Down, + ] + .into_iter() + .enumerate() + .filter_map(|(i, edge)| (ended[i] != origin[i]).then_some((edge, ended[i] - origin[i]))) + .collect() + } + /// Applies a mouse drag of the edge(s) of `window_id`'s tile, given the frame the window was /// first seen in once the drag was going on and the frame it ended in. Returns whether the /// workspace needs to be re-tiled, which also puts back a window dragged by an edge with no @@ -1734,41 +1837,31 @@ impl WindowManager { // A Rect is (left, top, width, height); work in edges instead let edges = |r: &Rect| [r.left, r.top, r.left + r.right, r.top + r.bottom]; - let started = edges(&started_from); let ended = edges(&ended_at); let tile = workspace.latest_layout.get(idx).map(edges); - // The first AXWindowResized is reported after the edge has already moved, and handlers - // run one at a time, so the frame a drag is first seen in is not the one it began from, - // and can even be the one it ended in. An edge that ended up further from its tile than - // an app strays from its tile on its own was dragged, and began on its tile. Any other - // edge was not moved, and the offset of the app from its tile is not part of the drag. - let moved: Vec<(OperationDirection, i32)> = [ - OperationDirection::Left, - OperationDirection::Up, - OperationDirection::Right, - OperationDirection::Down, - ] - .into_iter() - .enumerate() - .filter_map(|(i, edge)| { - let from = match tile { - Some(tile) if (ended[i] - tile[i]).abs() > Self::DRAG_SNAP_TOLERANCE => tile[i], - _ => started[i], - }; - - (ended[i] != from).then_some((edge, ended[i] - from)) - }) - .collect(); + let origin = Self::drag_origin(edges(&started_from), ended, tile); + let moved = Self::edges_moved(origin, ended); if moved.is_empty() { return Ok(false); } - // Resize the container of the dragged window, which is not necessarily the focused one + self.apply_mouse_resize(idx, &moved)?; + + Ok(true) + } + + /// Resize the container at `idx` by the edges that were dragged, which is not necessarily + /// the one that has focus. + fn apply_mouse_resize( + &mut self, + idx: usize, + moved: &[(OperationDirection, i32)], + ) -> eyre::Result<()> { self.focused_workspace_mut()?.focus_container(idx); - for (edge, by) in moved { + for &(edge, by) in moved { let outward = match edge { OperationDirection::Left | OperationDirection::Up => by < 0, OperationDirection::Right | OperationDirection::Down => by > 0, @@ -1784,7 +1877,212 @@ impl WindowManager { self.resize_window(edge, sizing, by.abs() * 2, false)?; } - Ok(true) + Ok(()) + } + + /// What a drag by an edge of `window_id` is followed from, if it is one that the windows next + /// to the edge follow: that is a window in a container of a workspace that is tiled, and + /// where nothing is maximised or in monocle. + fn live_resize_snapshot(&self, window_id: u32) -> Option { + let workspace = self.focused_workspace().ok()?; + + let follows = workspace.tile + && matches!(workspace.layer, WorkspaceLayer::Tiling) + && workspace.monocle_container.is_none() + && workspace.maximized_window.is_none() + && workspace.container_idx_for_window(window_id).is_some(); + + follows.then(|| LiveResize { + window: window_id, + containers: workspace.containers().len(), + resize_dimensions: workspace.resize_dimensions.clone(), + latest_layout: workspace.latest_layout.clone(), + scrolling: workspace.scrolling.clone(), + stepped: false, + timeouts: vec![], + }) + } + + /// Somebody has taken hold of an edge of `window_id`: keep what the workspace is, for the + /// windows next to the edge to follow it from here, if they are to. + pub fn live_resize_begin(&mut self, window_id: u32) { + // one that was never ended, by a window manager that did not hear that the button went up + self.live_resize_forget(); + + let Some(mut live) = self.live_resize_snapshot(window_id) else { + return; + }; + + if let Ok(workspace) = self.focused_workspace() { + let dragged_process = workspace + .container_for_window(window_id) + .and_then(|container| container.windows().iter().find(|w| w.id == window_id)) + .map(|window| window.application.process_id); + + for container in workspace.containers() { + for window in container.windows().iter().filter(|w| w.id != window_id) { + live.timeouts.push(window.element.clone()); + + // the app of the window that is dragged is asked where that window is for + // every step, and is not to be given up on any sooner for a neighbour that + // is one of its windows + if Some(window.application.process_id) != dragged_process { + live.timeouts.push(window.application.element().clone()); + } + } + } + } + + set_messaging_timeouts(&live.timeouts, LIVE_RESIZE_TIMEOUT); + + live_resize_begins(window_id); + self.live_resize = Some(live); + } + + /// Stop following a drag, wherever it got to, and give back what was kept. + pub(crate) fn live_resize_forget(&mut self) -> Option { + live_resize_ends(); + + let live = self.live_resize.take()?; + set_messaging_timeouts(&live.timeouts, 0.0); + + Some(live) + } + + /// Whether the windows next to an edge are following the drag of a window other than + /// `window_id`. + /// + /// A window that is moved or resized while somebody is dragging another one is a window that + /// the layout has moved, and not somebody dragging it. With the button up there is no drag, + /// whatever was kept. + pub fn another_window_is_being_dragged(&self, window_id: u32) -> bool { + self.live_resize + .as_ref() + .is_some_and(|live| live.window != window_id && dragged_window() == Some(live.window)) + } + + /// Work out what the workspace is for where the dragged window is now, from what it was when + /// the drag began, and say whether that is to be laid out. + /// + /// `now` is where the window is, which is not asked for here. + pub(crate) fn live_resize_apply(&mut self, now: Rect) -> eyre::Result { + let Some(mut live) = self.live_resize.take() else { + return Ok(false); + }; + + let Some((_, Some(started_from))) = + (*self.pending_resize_op).filter(|(window, _)| *window == live.window) + else { + self.live_resize = Some(live); + return Ok(false); + }; + + let workspace = self.focused_workspace()?; + + // a window that opens or closes in the middle of a drag changes what the layout is made + // of, and there is nothing in what was kept to follow it by: the end of the drag is + // worked out from what the workspace is by then + if workspace.containers().len() != live.containers + || workspace.container_idx_for_window(live.window).is_none() + { + tracing::debug!("not following the drag any more: the containers have changed"); + + // the drag is still going on, and what the layout moves is still not somebody dragging + // it, so that is left as it is until the button goes up + set_messaging_timeouts(&live.timeouts, 0.0); + + return Ok(false); + } + + // a window that was only moved changes no tile until it is let go, and one that has been + // taken back to where it began is a step like any other, which puts the windows back + let resized = now.right != started_from.right || now.bottom != started_from.bottom; + if !resized && !live.stepped { + self.live_resize = Some(live); + return Ok(false); + } + + let workspace = self.focused_workspace_mut()?; + workspace.resize_dimensions = live.resize_dimensions.clone(); + workspace.latest_layout = live.latest_layout.clone(); + workspace.scrolling = live.scrolling.clone(); + + let moved = self.resize_by_drag(live.window, started_from, now); + + // what was kept is kept whatever came of this + live.stepped |= moved.as_ref().is_ok_and(|moved| *moved); + let lay_out = live.stepped; + self.live_resize = Some(live); + + moved?; + + Ok(lay_out) + } + + /// Lay out the workspace for where the edge of the dragged window is now. + /// + /// This is for a step of the drag of `window_id`, which says only that the window has moved. + pub fn live_resize_step(&mut self, window_id: u32) -> eyre::Result<()> { + if self.is_paused + || !self + .live_resize + .as_ref() + .is_some_and(|live| live.window == window_id) + { + return Ok(()); + } + + // the button went up, and the end of the drag is on its way + if dragged_window() != Some(window_id) { + return Ok(()); + } + + let element = self + .focused_workspace()? + .container_for_window(window_id) + .and_then(|container| container.windows().iter().find(|w| w.id == window_id)) + .map(|window| window.element.clone()) + .ok_or_eyre("the dragged window is not in a container on the focused workspace")?; + + let now = Rect::from(MacosApi::window_rect(&element)?); + + if !self.live_resize_apply(now)? { + return Ok(()); + } + + let offset = self.work_area_offset; + let _snapping = Snapping::step(window_id); + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .update_focused_workspace(offset) + } + + /// The drag is over: put the workspace back to what it was when the drag began, for the end + /// of the drag to work out what it did from there, as it does when there were no steps. + /// + /// Says whether the windows next to the edge were laid out for any step of the drag, in + /// which case they are not where the layout for the end of the drag puts them, and are to be + /// laid out again whatever the drag comes to. + pub(crate) fn live_resize_end(&mut self) -> bool { + let Some(live) = self.live_resize_forget() else { + return false; + }; + + if !live.stepped { + return false; + } + + if let Ok(workspace) = self.focused_workspace_mut() + && workspace.containers().len() == live.containers + && workspace.container_idx_for_window(live.window).is_some() + { + workspace.resize_dimensions = live.resize_dimensions; + workspace.latest_layout = live.latest_layout; + workspace.scrolling = live.scrolling; + } + + true } #[tracing::instrument(skip(self))] @@ -5898,4 +6196,448 @@ mod tests { assert_eq!(after[2].left, tile.left - 211, "{tile:?} -> {:?}", after[2]); assert_tiling(&after); } + + // Following an edge that is dragged, with the windows next to it laid out for every step. + // Nothing here asks a window where it is, so the frame that a step finds the dragged window + // in is given. + + /// The edge of `window_id` has been taken hold of, and the first frame of it that was seen is + /// `started_from` + fn followed(wm: &mut WindowManager, window_id: u32, started_from: Rect) { + *Arc::make_mut(&mut wm.pending_resize_op) = Some((window_id, Some(started_from))); + wm.live_resize = Some(wm.live_resize_snapshot(window_id).unwrap()); + } + + /// A step of the drag, and the layout that comes of it recorded the way that updating the + /// workspace records it. Says whether the workspace was laid out. + fn step(wm: &mut WindowManager, now: Rect) -> bool { + let laid_out = wm.live_resize_apply(now).unwrap(); + + if laid_out { + let latest_layout = tiles(wm); + wm.focused_workspace_mut().unwrap().latest_layout = latest_layout; + } + + laid_out + } + + #[test] + fn test_the_steps_of_a_drag_and_its_end_come_to_what_the_drag_comes_to_without_them() { + let (mut stepped, _context) = tiled(DefaultLayout::UltrawideVerticalStack, &[1, 2, 3]); + let tile = tiles(&stepped)[2]; + let started_from = grown_left(tile, 22); + let ended_at = grown_left(tile, 107); + + let (mut at_once, _other) = tiled(DefaultLayout::UltrawideVerticalStack, &[1, 2, 3]); + at_once.resize_by_drag(3, started_from, ended_at).unwrap(); + + let before = tiles(&stepped); + followed(&mut stepped, 3, started_from); + for by in [40, 75, 107] { + assert!(step(&mut stepped, grown_left(tile, by)), "step to {by}"); + + // the neighbours follow, a step at a time + assert_ne!(tiles(&stepped), before, "step to {by}"); + } + + assert!(stepped.live_resize_end()); + stepped.resize_by_drag(3, started_from, ended_at).unwrap(); + + assert_eq!(tiles(&stepped), tiles(&at_once)); + assert_eq!( + stepped.focused_workspace().unwrap().latest_layout, + at_once.focused_workspace().unwrap().latest_layout + ); + assert!(stepped.live_resize.is_none()); + } + + #[test] + fn test_a_step_moves_the_neighbours_to_where_the_edge_is() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let before = tiles(&wm); + let tile = before[1]; + + followed(&mut wm, 2, tile); + assert!(step(&mut wm, grown_left(tile, 60))); + + let after = tiles(&wm); + assert_eq!(after[1].left, tile.left - 60); + assert_eq!(after[0].right, before[0].right - 60); + assert_tiling(&after); + + // the window that is dragged is the one with focus + assert_eq!(wm.focused_workspace().unwrap().focused_container_idx(), 1); + } + + #[test] + fn test_a_drag_that_is_taken_back_to_where_it_began_puts_the_neighbours_back() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let before = tiles(&wm); + let tile = before[1]; + + followed(&mut wm, 2, grown_left(tile, 22)); + assert!(step(&mut wm, grown_left(tile, 120))); + assert_ne!(tiles(&wm), before); + + // back to the frame that it was first seen in + assert!(step(&mut wm, grown_left(tile, 22))); + + assert_eq!(tiles(&wm), before); + assert!(no_resizes(&wm)); + } + + #[test] + fn test_two_steps_to_the_same_frame_do_not_add_up() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let tile = tiles(&wm)[1]; + + followed(&mut wm, 2, tile); + step(&mut wm, grown_left(tile, 60)); + let once = tiles(&wm); + + step(&mut wm, grown_left(tile, 60)); + step(&mut wm, grown_left(tile, 60)); + + assert_eq!(tiles(&wm), once); + } + + #[test] + fn test_a_drag_that_only_moved_the_window_lays_nothing_out() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let tile = tiles(&wm)[1]; + followed(&mut wm, 2, tile); + + // the same size, somewhere else: that is a window being moved by its title bar + let moved = Rect { + left: tile.left + 80, + top: tile.top + 40, + ..tile + }; + + assert!(!step(&mut wm, moved)); + assert!(no_resizes(&wm)); + + // and the end of it has nothing to put back + assert!(!wm.live_resize_end()); + } + + #[test] + fn test_the_end_of_a_drag_that_was_not_laid_out_for_has_nothing_to_put_back() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let tile = tiles(&wm)[1]; + followed(&mut wm, 2, tile); + + assert!(!wm.live_resize_end()); + assert!(wm.live_resize.is_none()); + } + + #[test] + fn test_the_end_of_a_drag_puts_the_workspace_back_for_the_drag_to_be_applied_to() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let before = tiles(&wm); + let tile = before[1]; + + followed(&mut wm, 2, tile); + assert!(step(&mut wm, grown_left(tile, 60))); + assert_ne!(tiles(&wm), before); + + assert!(wm.live_resize_end()); + + assert_eq!(tiles(&wm), before); + assert_eq!(wm.focused_workspace().unwrap().latest_layout, before); + assert!(no_resizes(&wm)); + } + + #[test] + fn test_a_container_that_opens_in_the_middle_of_a_drag_stops_it_being_followed() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let tile = tiles(&wm)[1]; + + followed(&mut wm, 2, tile); + assert!(step(&mut wm, grown_left(tile, 40))); + + wm.focused_workspace_mut() + .unwrap() + .new_container_for_window(&Window::from(4)) + .unwrap(); + let resizes = wm.focused_workspace().unwrap().resize_dimensions.clone(); + + assert!(!step(&mut wm, grown_left(tile, 80))); + assert!(wm.live_resize.is_none()); + + // what the workspace is now is left as it is, not put back to what it was before + assert_eq!(wm.focused_workspace().unwrap().resize_dimensions, resizes); + assert!(!wm.live_resize_end()); + } + + #[test] + fn test_a_container_that_closes_in_the_middle_of_a_drag_stops_it_being_followed() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let tile = tiles(&wm)[1]; + + followed(&mut wm, 2, tile); + wm.focused_workspace_mut() + .unwrap() + .remove_window(3) + .unwrap(); + + assert!(!step(&mut wm, grown_left(tile, 80))); + assert!(wm.live_resize.is_none()); + } + + #[test] + fn test_a_step_for_a_window_that_is_not_the_one_that_was_taken_hold_of_is_ignored() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let before = tiles(&wm); + let tile = before[1]; + + // the pending resize is of another window than the one that is followed + followed(&mut wm, 2, tile); + *Arc::make_mut(&mut wm.pending_resize_op) = Some((3, Some(before[2]))); + + assert!(!step(&mut wm, grown_left(tile, 60))); + assert_eq!(tiles(&wm), before); + + wm.live_resize_step(3).unwrap(); + assert_eq!(tiles(&wm), before); + } + + #[test] + fn test_a_drag_is_only_followed_in_a_workspace_that_is_tiled() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + assert!(wm.live_resize_snapshot(2).is_some()); + + // a window that is not in a container + assert!(wm.live_resize_snapshot(99).is_none()); + + wm.focused_workspace_mut().unwrap().tile = false; + assert!(wm.live_resize_snapshot(2).is_none()); + wm.focused_workspace_mut().unwrap().tile = true; + + wm.focused_workspace_mut().unwrap().layer = WorkspaceLayer::Floating; + assert!(wm.live_resize_snapshot(2).is_none()); + wm.focused_workspace_mut().unwrap().layer = WorkspaceLayer::Tiling; + + wm.focused_workspace_mut().unwrap().monocle_container = Some(Container::default()); + assert!(wm.live_resize_snapshot(2).is_none()); + wm.focused_workspace_mut().unwrap().monocle_container = None; + + wm.focused_workspace_mut().unwrap().maximized_window = Some(Window::from(2)); + assert!(wm.live_resize_snapshot(2).is_none()); + } + + #[test] + fn test_nothing_is_followed_where_there_is_nothing_that_was_kept() { + let (mut wm, _context) = tiled(DefaultLayout::BSP, &[1, 2, 3]); + let before = tiles(&wm); + + assert!(!wm.live_resize_apply(grown_left(before[1], 60)).unwrap()); + assert!(!wm.live_resize_end()); + wm.live_resize_step(2).unwrap(); + + assert_eq!(tiles(&wm), before); + } + + // A drag is measured from the tile that the window was put in, which is where the edge began + // when it was taken hold of, and not from where the window had got to when the start of the + // drag was first seen. + + #[test] + fn test_an_edge_dragged_before_the_start_was_handled_is_measured_from_the_tile() { + let tile = [27, 27, 623, 725]; + // read after the right edge had gone 7px + let started = [27, 27, 630, 725]; + let ended = [27, 27, 683, 725]; + + assert_eq!( + WindowManager::drag_origin(started, ended, Some(tile)), + [27, 27, 623, 725] + ); + } + + #[test] + fn test_a_drag_of_under_the_snap_tolerance_is_measured_from_the_tile_too() { + // dragged by 10, and seen after 3 of them: it used to be 7 that was asked for, since an + // edge that is not 32 from its tile is taken to be where it began + let tile = [27, 27, 623, 725]; + let started = [27, 27, 626, 725]; + let ended = [27, 27, 633, 725]; + + let origin = WindowManager::drag_origin(started, ended, Some(tile)); + + let moved = WindowManager::edges_moved(origin, ended); + assert!( + matches!(moved[..], [(OperationDirection::Right, 10)]), + "{moved:?}" + ); + } + + #[test] + fn test_an_edge_that_did_not_move_is_left_as_it_was_read() { + // a window that cannot be as narrow as its tile, dragged by the other edge + let tile = [27, 27, 623, 725]; + let started = [27, 27, 650, 725]; + let ended = [27, 27, 650, 760]; + + assert_eq!( + WindowManager::drag_origin(started, ended, Some(tile)), + [27, 27, 650, 725] + ); + } + + #[test] + fn test_an_edge_far_from_its_tile_is_left_as_it_was_read() { + let tile = [27, 27, 623, 725]; + let started = [27, 27, 800, 725]; + let ended = [27, 27, 830, 725]; + + assert_eq!( + WindowManager::drag_origin(started, ended, Some(tile)), + started + ); + } + + #[test] + fn test_there_is_nothing_to_go_by_without_a_tile() { + let started = [27, 27, 630, 725]; + let ended = [27, 27, 683, 725]; + + assert_eq!(WindowManager::drag_origin(started, ended, None), started); + } + + #[test] + fn test_a_drag_that_was_over_when_it_was_first_seen_is_measured_from_the_tile() { + let tile = [27, 27, 623, 725]; + let seen = [27, 27, 834, 725]; + + assert_eq!( + WindowManager::drag_origin(seen, seen, Some(tile)), + [27, 27, 623, 725] + ); + } + + #[test] + fn test_a_window_that_is_a_little_off_its_tile_has_not_been_dragged() { + // nothing moved, and the offset is what an app does on its own + let tile = [27, 27, 623, 725]; + let seen = [27, 27, 640, 725]; + + let origin = WindowManager::drag_origin(seen, seen, Some(tile)); + + assert_eq!(origin, seen); + assert!(WindowManager::edges_moved(origin, seen).is_empty()); + } + + // The same, for the Scrolling layout, whose tiles are not worked out from the resizes of the + // workspace but from the strip that it keeps. + + /// A monitor with a workspace in the Scrolling layout, with a container per window id, the + /// last of them focused, laid out as a window update would + fn scrolled(ids: &[u32]) -> (WindowManager, TestContext) { + let (mut wm, context) = setup_window_manager(); + + let m = monitor::new( + 0, + WORK_AREA, + WORK_AREA, + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + wm.monitors_mut().push_back(m); + + let workspace = wm.focused_workspace_mut().unwrap(); + workspace.layout = Layout::Default(DefaultLayout::Scrolling); + for id in ids { + workspace + .new_container_for_window(&Window::from(*id)) + .unwrap(); + } + + scroll_layout(&mut wm); + + (wm, context) + } + + /// Lay the strip out and record the tiles, as updating the workspace does + fn scroll_layout(wm: &mut WindowManager) -> Vec { + let workspace = wm.focused_workspace_mut().unwrap(); + let rects: Vec = workspace + .layout_scrolling(&WORK_AREA, 0) + .iter() + .map(|placement| placement.rect) + .collect(); + workspace.latest_layout = rects.clone(); + + rects + } + + fn scroll_step(wm: &mut WindowManager, now: Rect) -> Vec { + assert!(wm.live_resize_apply(now).unwrap()); + + scroll_layout(wm) + } + + fn grown_right(r: Rect, by: i32) -> Rect { + Rect { + right: r.right + by, + ..r + } + } + + #[test] + fn test_the_steps_of_a_drag_of_a_column_do_not_add_up_and_a_drag_back_restores_the_strip() { + let (mut wm, _context) = scrolled(&[1, 2, 3, 4, 5]); + let before = scroll_layout(&mut wm); + let tile = before[3]; + + followed(&mut wm, 4, tile); + + // a column is as much wider as the edge was dragged, and not by the sum of the steps + for by in [40, 100, 100] { + let rects = scroll_step(&mut wm, grown_right(tile, by)); + + assert_eq!(rects[3].right, tile.right + by, "dragged by {by}"); + } + + // and taken back + let rects = scroll_step(&mut wm, tile); + assert_eq!(rects, before); + + assert!(wm.live_resize_end()); + assert_eq!(scroll_layout(&mut wm), before); + } + + #[test] + fn test_the_left_edge_of_a_column_that_is_dragged_stays_where_it_is_dragged_to() { + let (mut wm, _context) = scrolled(&[1, 2, 3, 4, 5]); + + // the strip is at its start, with the first column the one that the strip says is active, + // and the second is the one that is dragged: dragging an edge only moves the focus of the + // workspace to it, and not that of the strip + wm.focused_workspace_mut().unwrap().focus_container(0); + let before = scroll_layout(&mut wm); + let tile = before[1]; + assert_eq!(tile.left, 640); + followed(&mut wm, 2, tile); + + let rects = scroll_step(&mut wm, grown_left(tile, 60)); + + // the edge goes as far as it was dragged, and the other is where it was + assert_eq!(rects[1].left, tile.left - 60); + assert_eq!(rects[1].left + rects[1].right, tile.left + tile.right); + assert_eq!(rects[1].right, tile.right + 60); + } + + #[test] + fn test_the_left_edge_of_the_last_column_that_is_dragged_stays_where_it_is_dragged_to() { + let (mut wm, _context) = scrolled(&[1, 2, 3, 4, 5]); + let before = scroll_layout(&mut wm); + let tile = before[3]; + followed(&mut wm, 4, tile); + + let rects = scroll_step(&mut wm, grown_left(tile, 60)); + + assert_eq!(rects[3].left, tile.left - 60); + assert_eq!(rects[3].left + rects[3].right, tile.left + tile.right); + } } diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index 89049b81..b1545139 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -42,6 +42,9 @@ pub enum WindowManagerEvent { MoveStart(SystemNotification, i32, u32), MoveEnd(SystemNotification, i32, u32), ResizeStart(SystemNotification, i32, u32), + /// The window that is being dragged by an edge has moved, which is not a report of + /// where it is, only that it has: the handler looks + ResizeStep(SystemNotification, i32, u32), ResizeEnd(SystemNotification, i32, u32), SpaceChange(SystemNotification, i32), ScreenLock(SystemNotification, i32), @@ -155,6 +158,7 @@ impl WindowManagerEvent { | WindowManagerEvent::MoveStart(_, process_id, _) | WindowManagerEvent::MoveEnd(_, process_id, _) | WindowManagerEvent::ResizeStart(_, process_id, _) + | WindowManagerEvent::ResizeStep(_, process_id, _) | WindowManagerEvent::ResizeEnd(_, process_id, _) | WindowManagerEvent::SpaceChange(_, process_id) | WindowManagerEvent::ScreenLock(_, process_id) @@ -173,6 +177,7 @@ impl WindowManagerEvent { | WindowManagerEvent::MoveStart(n, _, _) | WindowManagerEvent::MoveEnd(n, _, _) | WindowManagerEvent::ResizeStart(n, _, _) + | WindowManagerEvent::ResizeStep(n, _, _) | WindowManagerEvent::ResizeEnd(n, _, _) | WindowManagerEvent::Unmanage(n, _, _) | WindowManagerEvent::SpaceChange(n, _) @@ -200,6 +205,7 @@ impl WindowManagerEvent { | WindowManagerEvent::MoveStart(_, _, window_id) | WindowManagerEvent::MoveEnd(_, _, window_id) | WindowManagerEvent::ResizeStart(_, _, window_id) + | WindowManagerEvent::ResizeStep(_, _, window_id) | WindowManagerEvent::ResizeEnd(_, _, window_id) | WindowManagerEvent::Restore(_, _, window_id) => Some(*window_id), } diff --git a/komorebi/src/window_manager_event_listener.rs b/komorebi/src/window_manager_event_listener.rs index 555e3641..3e1a8f2f 100644 --- a/komorebi/src/window_manager_event_listener.rs +++ b/komorebi/src/window_manager_event_listener.rs @@ -2,10 +2,15 @@ use crate::window_manager_event::WindowManagerEvent; use crossbeam_channel::Receiver; use crossbeam_channel::Sender; use std::sync::OnceLock; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; static CHANNEL: OnceLock<(Sender, Receiver)> = OnceLock::new(); +/// Whether a step of a drag is waiting in the channel for the window manager to take it +static RESIZE_STEP_WAITING: AtomicBool = AtomicBool::new(false); + fn channel() -> &'static (Sender, Receiver) { CHANNEL.get_or_init(|| crossbeam_channel::bounded(20)) } @@ -18,8 +23,73 @@ pub fn event_rx() -> Receiver { channel().1.clone() } +/// Whether a step of a drag may be sent, which it may if none is waiting. Says that one is. +/// +/// A step is only a signal that the window has moved, and what is done about it is to look at where +/// the window is, which is the newest of what any number of them would have said. So one that waits +/// is enough, and the channel is not filled with the ones that come faster than they are handled. +fn claim_resize_step(waiting: &AtomicBool) -> bool { + !waiting.swap(true, Ordering::AcqRel) +} + +fn release_resize_step(waiting: &AtomicBool) { + waiting.store(false, Ordering::Release); +} + +/// Say that a step of a drag is being taken, so the next one that comes is let through. +/// +/// This is for the start of a step and not the end of it: one that comes while a step is being +/// taken waits for the next, and the last frame of a drag is never lost. +pub fn resize_step_taken() { + release_resize_step(&RESIZE_STEP_WAITING); +} + pub fn send_notification(notification: WindowManagerEvent) { + let is_step = matches!(notification, WindowManagerEvent::ResizeStep(_, _, _)); + + if is_step && !claim_resize_step(&RESIZE_STEP_WAITING) { + return; + } + if event_tx().try_send(notification).is_err() { + // there is nothing in the channel for a step that was not sent to wait for + if is_step { + resize_step_taken(); + } + tracing::warn!("channel is full; dropping notification") } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_step_is_let_through_when_none_is_waiting() { + let waiting = AtomicBool::new(false); + + assert!(claim_resize_step(&waiting)); + } + + #[test] + fn only_one_step_waits_however_many_come() { + let waiting = AtomicBool::new(false); + + assert!(claim_resize_step(&waiting)); + assert!(!claim_resize_step(&waiting)); + assert!(!claim_resize_step(&waiting)); + } + + #[test] + fn a_step_that_comes_while_one_is_being_taken_is_let_through_for_after() { + let waiting = AtomicBool::new(false); + assert!(claim_resize_step(&waiting)); + + // the handler says that it has begun, and what comes after is the next one + release_resize_step(&waiting); + + assert!(claim_resize_step(&waiting)); + assert!(!claim_resize_step(&waiting)); + } +}