diff --git a/README.md b/README.md index 299f5e2c..35121fdd 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in directory): a message can ask for the state of the window manager, ask which monitor, workspace or container has the focus, give the focus to another window, move the focused window to another tile, change the layout, resize a -tile, retile every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +tile, float a window, retile every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, the command line, is how a person sends them. `komorebic start` runs the `komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma session: @@ -139,8 +139,9 @@ again. `change-layout`, `cycle-layout` and `flip-layout` tile the workspace in another layout, `layout-ratios` and `scrolling-layout-columns` tune it, `toggle-tiling` stops it moving windows and starts it again, `preselect-direction` reserves a tile for the next window, `resize-edge` and -`resize-axis` move the edges of the focused tile, and `promote` brings the -focused window to the largest tile. The scrolling layout +`resize-axis` move the edges of the focused tile, `promote` brings the +focused window to the largest tile, and `toggle-float` takes it out of the +layout. The scrolling layout is a strip of columns that runs past the edges of the monitor and scrolls to the window that has the focus. diff --git a/docs/cli/toggle-float.md b/docs/cli/toggle-float.md new file mode 100644 index 00000000..846dfd87 --- /dev/null +++ b/docs/cli/toggle-float.md @@ -0,0 +1,10 @@ +```text +Toggle floating mode for the focused window + +Usage: toggle-float + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index f656e2fb..a79c3dc1 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -85,7 +85,8 @@ the same thing at every level. - A **monitor** ([`Monitor`]) is one of the backend's monitors: its bounds, its work area, its padding, an optional work area offset, and its workspaces. It shows the focused one. -- A **workspace** ([`Workspace`]) has a layout, its padding, and its containers, in order. +- A **workspace** ([`Workspace`]) has a layout, its padding, its containers, in order, and its + floating windows, which are in no container and which the layout does not tile. - A **container** ([`Container`]) has its windows. A new window gets a container of its own. A container can be locked, which keeps it at its index while others are inserted, removed or swapped around it. @@ -294,6 +295,13 @@ focuses the container at index 0 ([`WindowManager::promote_focus_to_front`]), an `PromoteWindow` focuses the container in a direction and promotes it. On the grid layout they change nothing. +`ToggleFloat` takes the window the compositor has focused out of its container into the +workspace's floating windows, and back into a container of its own at the focused index +([`WindowManager::toggle_float`]). A floating window is in the index of managed windows like +any other, so its events find it, and [`Workspace::update`] leaves it where it is. Where a +floated window goes is [`WindowManagementBehaviour::toggle_float_placement`]: by default it +stays where it is. + `ResizeWindowEdge` and `ResizeWindowAxis` resize the focused container ([`WindowManager::resize_window`]). A resize is an adjustment of the container's tile, kept in [`Workspace::resize_dimensions`], one per container, which the layout applies when it calculates @@ -362,7 +370,7 @@ module's unit. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized window out, move the focus, move the focused container, change the layout, resize or - promote the focused container). + promote the focused container, float a window). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -563,7 +571,8 @@ A window is shown, and ends up on a tile: [`komorebi/tests/layout_options.rs`](../../komorebi/tests/layout_options.rs) and [`komorebi/tests/scrolling.rs`](../../komorebi/tests/scrolling.rs), the layout options and the scrolling layout; [`komorebi/tests/resize.rs`](../../komorebi/tests/resize.rs), resizing; - [`komorebi/tests/promote.rs`](../../komorebi/tests/promote.rs), promoting. + [`komorebi/tests/promote.rs`](../../komorebi/tests/promote.rs), promoting; + [`komorebi/tests/float.rs`](../../komorebi/tests/float.rs), floating. - [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, @@ -603,6 +612,8 @@ A window is shown, and ends up on a tile: [`Workspace::layout_options`]: ../../komorebi/src/workspace.rs [`Workspace::resize_dimensions`]: ../../komorebi/src/workspace.rs [`WindowManager::resize_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::toggle_float`]: ../../komorebi/src/window_manager.rs +[`WindowManagementBehaviour::toggle_float_placement`]: ../../komorebi/src/core/mod.rs [`WindowManager::promote_container_to_front`]: ../../komorebi/src/window_manager.rs [`WindowManager::promote_container_swap`]: ../../komorebi/src/window_manager.rs [`WindowManager::promote_focus_to_front`]: ../../komorebi/src/window_manager.rs diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index dbd17385..b45e243b 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -127,8 +127,8 @@ the run. printed, failing the test if it fails. `state()` is the daemon's state as `komorebic state` prints it, `managed(workspace)` the number of windows the daemon has on a workspace of the first monitor, `managed_all()` the number it - has on every workspace of every monitor, and `focused_title(workspace)` the - title of the window it has focused there. + has on every workspace of every monitor (floating windows too), and + `focused_title(workspace)` the title of the window it has focused there. - `daemon` reads the daemon's view of the desktop from that log, at the debug level the nodes set: `daemon.events(log)` lists the window events it handled, in order, `daemon.window_ids(log)` maps a window's title to the daemon's id diff --git a/docs/index.md b/docs/index.md index 6a2a93a4..77226bf8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -34,8 +34,9 @@ anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to sta daemon, ask it what it is doing and read its log. [Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window, [Moving windows](usage/moving-windows.md) how to move the focused window to another tile, -[Layouts](usage/layouts.md) how to change the arrangement of the tiles, and -[Resizing windows](usage/resizing-windows.md) how to change the size of one. +[Layouts](usage/layouts.md) how to change the arrangement of the tiles, +[Resizing windows](usage/resizing-windows.md) how to change the size of one, and +[Floating windows](usage/floating-windows.md) how to take a window out of the layout. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/floating-windows.md b/docs/usage/floating-windows.md new file mode 100644 index 00000000..83b44797 --- /dev/null +++ b/docs/usage/floating-windows.md @@ -0,0 +1,15 @@ +# Floating windows + +A floating window is one of a workspace's windows that is not in its layout: komorebi gives it no +tile and does not move it, and it stays where it is put by hand. + +[`komorebic toggle-float`](../cli/toggle-float.md) takes the window that has the focus out of the +layout, and the other windows of the workspace share the work area. The same command on a +floating window puts it back in the layout, at the place of the focused window. + +```sh +komorebic toggle-float +``` + +A floated window keeps its size and position by default. The floating windows of a workspace are +in the daemon's state as `floating_windows`, next to its containers. diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 4ff6ec9d..6917ca94 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -352,6 +352,7 @@ pub enum SocketMessage { PromoteSwap, PromoteFocus, PromoteWindow(OperationDirection), + ToggleFloat, // Current Workspace Commands ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 79d8ade2..a7397297 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -24,6 +24,8 @@ use crate::core::SocketMessage; use crate::core::SubscribeOptions; use crate::state::State; +use crate::window::AspectRatio; +use crate::window::PredefinedAspectRatio; use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; use lazy_static::lazy_static; @@ -88,6 +90,11 @@ lazy_static! { /// same name, without options, keeps the options it had. pub static ref SUBSCRIPTION_SOCKET_OPTIONS: Arc>> = Arc::new(Mutex::new(HashMap::new())); + /// The aspect ratio a window that is floated by `ToggleFloat` is given when the placement of + /// floated windows centers and resizes them + static ref FLOATING_WINDOW_TOGGLE_ASPECT_RATIO: Arc> = Arc::new(Mutex::new( + AspectRatio::Predefined(PredefinedAspectRatio::Widescreen) + )); } /// The padding, in pixels, between the edge of a monitor's work area and the tiles of its diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 9df4f6e8..ea47fb34 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -37,6 +37,9 @@ //! already, and **CancelPreselect** gives the reserved place up. //! - **MouseFollowsFocus** and **ToggleMouseFollowsFocus** set whether the pointer is moved to //! the window that is given the focus. +//! - **ToggleFloat** takes the focused window out of the layout into the floating windows of the +//! workspace, which komorebi does not move, or puts a floating window back +//! ([`WindowManager::toggle_float`]). //! - **ResizeWindowEdge** and **ResizeWindowAxis** resize the focused container by the //! [`WindowManager::resize_delta`] that **ResizeDelta** sets ([`WindowManager::resize_window`]), //! and **QuickSave**, **QuickLoad**, **Save** and **Load** write the resize adjustments of the @@ -144,6 +147,8 @@ impl WindowManager { /// [`WindowManager::move_container_in_cycle_direction`] give. /// - There is no focused workspace to change the layout or the tiling of, to preselect a /// place in, or to resize or promote a container of, or it cannot be tiled again. + /// - The focused window cannot be floated or put back, for one of the reasons + /// [`WindowManager::toggle_float`] gives. /// - The file of `QuickSave` or `Save` cannot be written, or the file of `QuickLoad` or /// `Load` cannot be read or is not a list of resize adjustments. /// - The window manager fails to retile, for one of the reasons @@ -205,6 +210,7 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::ToggleFloat => self.toggle_float(false)?, SocketMessage::ResizeWindowEdge(direction, sizing) => { self.resize_window(direction, sizing, self.resize_delta, true)?; } diff --git a/komorebi/src/ring.rs b/komorebi/src/ring.rs index cab51c2a..ae8b2f25 100644 --- a/komorebi/src/ring.rs +++ b/komorebi/src/ring.rs @@ -109,6 +109,37 @@ macro_rules! impl_ring_elements { } } } + }; // This allows passing a different name to be used for the functions. For instance, the + // `floating_windows` ring calls this as: + // ```rust + // impl_ring_elements!(Workspace, Window, "floating_window"); + // ``` + // Which allows using the `Window` element but name the functions as `floating_window` + ($name:ty, $element:ident, $el_name:literal) => { + pastey::paste! { + impl $name { + pub const fn [<$el_name:lower s>](&self) -> &std::collections::VecDeque<$element> { + self.[<$el_name:lower s>].elements() + } + + pub fn [<$el_name:lower s_mut>](&mut self) -> &mut std::collections::VecDeque<$element> { + self.[<$el_name:lower s>].elements_mut() + } + + #[allow(dead_code)] + pub fn [](&self) -> Option<&$element> { + self.[<$el_name:lower s>].focused() + } + + pub const fn [](&self) -> usize { + self.[<$el_name:lower s>].focused_idx() + } + + pub fn [](&mut self) -> Option<&mut $element> { + self.[<$el_name:lower s>].focused_mut() + } + } + } }; } diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 7795aad3..9d497d84 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -80,6 +80,7 @@ impl From<&WindowManager> for State { .iter() .map(|workspace| Workspace { containers: workspace.containers.clone(), + floating_windows: workspace.floating_windows.clone(), layout: workspace.layout.clone(), layout_options: workspace.layout_options, layout_flip: workspace.layout_flip, diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 76e42f74..e51cb942 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -6,6 +6,7 @@ //! focus, a close) is a command to the backend. Nothing is cached, so a window that changed its //! title, or closed, is seen as it is now. +use crate::FLOATING_WINDOW_TOGGLE_ASPECT_RATIO; use crate::backend::backend; use crate::core::Rect; use color_eyre::eyre; @@ -18,6 +19,8 @@ use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write; use std::path::PathBuf; +use strum::Display; +use strum::EnumString; /// A handle to a window on the desktop: just its id. /// @@ -191,13 +194,21 @@ impl Window { backend().unminimize(self.id) } - /// Moves the window to the middle of `work_area`, keeping its size + /// Moves the window to the middle of `work_area`, keeping its size, or with `resize` making it + /// half as high as the work area and as wide as the aspect ratio of floating windows says /// /// # Errors /// /// The backend does not know the window, or refuses to move it. - pub fn center(&mut self, work_area: &Rect) -> eyre::Result<()> { - let (target_width, target_height) = { + pub fn center(&mut self, work_area: &Rect, resize: bool) -> eyre::Result<()> { + let (target_width, target_height) = if resize { + let (aspect_ratio_width, aspect_ratio_height) = FLOATING_WINDOW_TOGGLE_ASPECT_RATIO + .lock() + .width_and_height(); + let target_height = work_area.bottom / 2; + let target_width = (target_height * aspect_ratio_width) / aspect_ratio_height; + (target_width, target_height) + } else { let current_rect = self.rect()?; (current_rect.right, current_rect.bottom) }; @@ -234,6 +245,51 @@ impl Window { } } +#[derive(Copy, Clone, Debug, Display, EnumString, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +/// Aspect ratio for temporarily floating windows +pub enum AspectRatio { + /// A predefined aspect ratio + #[cfg_attr(feature = "schemars", schemars(title = "Predefined"))] + Predefined(PredefinedAspectRatio), + /// A custom W:H aspect ratio + #[cfg_attr(feature = "schemars", schemars(title = "Custom"))] + Custom(i32, i32), +} + +impl Default for AspectRatio { + fn default() -> Self { + AspectRatio::Predefined(PredefinedAspectRatio::default()) + } +} + +#[derive(Copy, Clone, Debug, Default, Display, EnumString, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Predefined aspect ratio +pub enum PredefinedAspectRatio { + /// 21:9 + Ultrawide, + /// 16:9 + Widescreen, + /// 4:3 + #[default] + Standard, +} + +impl AspectRatio { + pub fn width_and_height(self) -> (i32, i32) { + match self { + AspectRatio::Predefined(predefined) => match predefined { + PredefinedAspectRatio::Ultrawide => (21, 9), + PredefinedAspectRatio::Widescreen => (16, 9), + PredefinedAspectRatio::Standard => (4, 3), + }, + AspectRatio::Custom(w, h) => (w, h), + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 7ef9be02..d511cc33 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -29,6 +29,7 @@ use crate::core::Layout; use crate::core::OperationDirection; use crate::core::Rect; use crate::core::Sizing; +use crate::core::WindowManagementBehaviour; use crate::desktop; use crate::monitor::Monitor; use crate::ring::Ring; @@ -58,6 +59,8 @@ pub struct WindowManager { pub command_listener: UnixListener, /// How many pixels `ResizeWindowEdge` and `ResizeWindowAxis` resize by pub resize_delta: i32, + /// How new and floated windows are placed: `ToggleFloat` reads its `toggle_float_placement` + pub window_management_behaviour: WindowManagementBehaviour, /// Whether the pointer is moved to the window that is given the focus, which is the default pub mouse_follows_focus: bool, pub work_area_offset: Option, @@ -111,6 +114,7 @@ impl WindowManager { monitors: Ring::default(), command_listener: listener, resize_delta: 50, + window_management_behaviour: WindowManagementBehaviour::default(), mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -406,6 +410,88 @@ impl WindowManager { std::process::exit(0) } + /// Takes the window that has the focus in the compositor out of the layout of the focused + /// workspace, or puts it back when it is one of its floating windows and `force_float` is not + /// set, and tiles the workspace again + /// + /// # Errors + /// + /// - The compositor reports no focused window. + /// - There is no focused workspace, or the window cannot be floated or put back, for one of + /// the reasons [`WindowManager::float_window`] and [`WindowManager::unfloat_window`] give. + /// - The workspace cannot be tiled again. + #[tracing::instrument(skip(self))] + pub fn toggle_float(&mut self, force_float: bool) -> eyre::Result<()> { + let window_id = backend() + .foreground_window() + .ok_or_eyre("no foreground window")?; + + let workspace = self.focused_workspace_mut()?; + + let mut is_floating_window = false; + + for window in workspace.floating_windows() { + if window.id == window_id { + is_floating_window = true; + } + } + + if is_floating_window && !force_float { + self.unfloat_window()?; + } else { + self.float_window()?; + } + + self.update_focused_workspace(is_floating_window, true) + } + + /// Takes the focused window out of its container into the floating windows of the focused + /// workspace ([`Workspace::new_floating_window`]), places it as + /// [`WindowManagementBehaviour::toggle_float_placement`] says, and gives it the focus + /// + /// # Errors + /// + /// There is no focused monitor, workspace, container or window, or the backend refuses to + /// move or focus the window. + #[tracing::instrument(skip(self))] + pub fn float_window(&mut self) -> eyre::Result<()> { + tracing::info!("floating window"); + + let mouse_follows_focus = self.mouse_follows_focus; + let work_area = self.focused_monitor_work_area()?; + + let toggle_float_placement = self.window_management_behaviour.toggle_float_placement; + + let workspace = self.focused_workspace_mut()?; + workspace.new_floating_window()?; + + let window = workspace + .floating_windows_mut() + .back_mut() + .ok_or_eyre("there is no floating window")?; + + if toggle_float_placement.should_center() { + window.center(&work_area, toggle_float_placement.should_resize())?; + } + window.focus(mouse_follows_focus)?; + + Ok(()) + } + + /// Puts the floating window that has the focus in the compositor back in the layout of the + /// focused workspace ([`Workspace::new_container_for_floating_window`]) + /// + /// # Errors + /// + /// There is no focused workspace, or the focused window is not one of its floating windows. + #[tracing::instrument(skip(self))] + pub fn unfloat_window(&mut self) -> eyre::Result<()> { + tracing::info!("unfloating window"); + + let workspace = self.focused_workspace_mut()?; + workspace.new_container_for_floating_window() + } + /// Resizes the focused container by `delta` pixels on its `direction` side, by giving it a /// resize adjustment that the layout applies, and tiles the workspace again if `update` is set /// @@ -854,6 +940,10 @@ impl WindowManager { known_window_ids.insert(window.id, (m_idx, w_idx)); } } + + for window in workspace.floating_windows() { + known_window_ids.insert(window.id, (m_idx, w_idx)); + } } } @@ -1120,4 +1210,112 @@ mod tests { assert_eq!(wm.minimized_windows.get(&631), Some(&Window::from(631))); Ok(()) } + + #[test] + fn test_float_window() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let mut container = Container::default(); + + // Add three windows to the container + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + + // Should have 3 windows in the container + assert_eq!(container.windows().len(), 3); + + // Add the container to the workspace + let workspace = m.focused_workspace_mut().unwrap(); + workspace.add_container_to_back(container); + + // Add monitor to the window manager + wm.monitors_mut().push_back(m); + } + + // Add focused window to floating window list + wm.float_window().ok(); + + { + let workspace = wm.focused_workspace().unwrap(); + let floating_windows = workspace.floating_windows(); + let container = workspace.focused_container().unwrap(); + + // Hwnd 0 should be added to floating_windows + assert_eq!(floating_windows[0].id, 0); + + // Should have a length of 1 + assert_eq!(floating_windows.len(), 1); + + // Should have 2 windows in the container + assert_eq!(container.windows().len(), 2); + + // Should be focused on window 1 + assert_eq!(container.focused_window().unwrap().id, 1); + } + + // Add focused window to floating window list + wm.float_window().ok(); + + { + let workspace = wm.focused_workspace().unwrap(); + let floating_windows = workspace.floating_windows(); + let container = workspace.focused_container().unwrap(); + + // Hwnd 1 should be added to floating_windows + assert_eq!(floating_windows[1].id, 1); + + // Should have a length of 2 + assert_eq!(floating_windows.len(), 2); + + // Should have 1 window in the container + assert_eq!(container.windows().len(), 1); + + // Should be focused on window 2 + assert_eq!(container.focused_window().unwrap().id, 2); + } + } + + #[test] + fn test_float_nonexistent_window() { + let (mut wm, _context) = setup_window_manager(); + + { + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add another workspace + let new_workspace_index = m.new_workspace_idx(); + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Add monitor to window manager + wm.monitors_mut().push_back(m); + } + + // Should return an error when trying to float a non-existent window + let result = wm.float_window(); + assert!( + result.is_err(), + "Expected an error when trying to float a non-existent window" + ); + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 31eecb0b..61f48c14 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -5,6 +5,7 @@ //! container on its tile with [`Window::set_position`]. The work area and the padding a workspace //! falls back to come from the monitor it is on ([`WorkspaceGlobals`]). +use crate::backend::backend; use crate::container::Container; use crate::core::Axis; use crate::core::CycleDirection; @@ -27,6 +28,7 @@ use std::num::NonZeroUsize; #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Workspace { pub containers: Ring, + pub floating_windows: Ring, pub layout: Layout, pub layout_options: Option, pub layout_flip: Option, @@ -44,6 +46,7 @@ pub struct Workspace { } impl_ring_elements!(Workspace, Container); +impl_ring_elements!(Workspace, Window, "floating_window"); impl Default for Workspace { fn default() -> Self { @@ -58,6 +61,7 @@ impl Default for Workspace { layout_options: None, globals: Default::default(), tile: true, + floating_windows: Default::default(), preselected_container_idx: None, promotion_swap_container_idx: None, } @@ -225,6 +229,7 @@ impl Workspace { pub fn prune_duplicate_windows(&mut self) -> eyre::Result<()> { let mut tracker = HashMap::new(); let mut to_prune_from_containers = vec![]; + let mut to_prune_from_floating = vec![]; for container in self.containers() { for window in container.windows() { @@ -244,6 +249,22 @@ impl Workspace { tracker.remove(&id); } + for window in self.floating_windows() { + let entry = tracker.entry(window.id).or_insert(0); + *entry += 1; + } + + for (window_id, count) in &tracker { + if *count > 1 { + to_prune_from_floating.push(*window_id); + } + } + + for id in to_prune_from_floating { + self.remove_window(id)?; + tracker.remove(&id); + } + Ok(()) } @@ -251,6 +272,7 @@ impl Workspace { #[tracing::instrument(skip(self))] pub fn reap_invalid_windows(&mut self) -> eyre::Result { let mut invalid_window_ids = vec![]; + let mut invalid_floating_window_ids = vec![]; for container in self.containers() { for window in container.windows() { @@ -260,13 +282,25 @@ impl Workspace { } } + for window in self.floating_windows() { + if !window.is_valid() { + invalid_floating_window_ids.push(window.id); + } + } + for window_id in &invalid_window_ids { let _ = self.remove_window(*window_id); } - tracing::debug!("reaping invalid windows {invalid_window_ids:?}"); + for window_id in &invalid_floating_window_ids { + self.remove_floating_window(*window_id); + } - Ok(invalid_window_ids.len()) + tracing::debug!( + "reaping invalid windows {invalid_window_ids:?} {invalid_floating_window_ids:?}" + ); + + Ok(invalid_window_ids.len() + invalid_floating_window_ids.len()) } pub fn remove_window(&mut self, window_id: u32) -> eyre::Result { @@ -315,7 +349,7 @@ impl Workspace { } pub fn is_empty(&self) -> bool { - self.containers().is_empty() + self.containers().is_empty() && self.floating_windows().is_empty() } pub fn contains_window(&self, window_id: u32) -> bool { @@ -325,6 +359,12 @@ impl Workspace { } } + for window in self.floating_windows() { + if window_id == window.id { + return true; + } + } + false } @@ -385,6 +425,97 @@ impl Workspace { fn focus_first_container(&mut self) { self.focus_container(0); } + + /// Takes the focused window out of its container, and out of the layout, into the floating + /// windows of the workspace; a container that is left with no window is removed + /// + /// # Errors + /// + /// The workspace has no containers, or the focused one has no window. + pub fn new_floating_window(&mut self) -> eyre::Result<()> { + let window = { + let focused_idx = self.focused_container_idx(); + + let container = self + .focused_container_mut() + .ok_or_eyre("there is no container")?; + + let window = container + .remove_focused_window() + .ok_or_eyre("there is no window")?; + + if container.windows().is_empty() { + self.remove_container_by_idx(focused_idx); + + if focused_idx == self.containers().len() { + self.focus_container(focused_idx.saturating_sub(1)); + } + } + + window + }; + + self.floating_windows_mut().push_back(window); + + Ok(()) + } + + /// Puts the floating window that has the focus in the compositor back in the layout, in a + /// container of its own at the index of the focused container + /// + /// # Errors + /// + /// The window the compositor has focused is not a floating window of the workspace. + pub fn new_container_for_floating_window(&mut self) -> eyre::Result<()> { + let focused_idx = self.focused_container_idx(); + let window = self + .remove_focused_floating_window() + .ok_or_eyre("there is no floating window")?; + + let mut container = Container::default(); + container.add_window(&window)?; + + self.insert_container_at_idx(focused_idx, container); + + Ok(()) + } + + pub fn remove_focused_floating_window(&mut self) -> Option { + let window_id = backend().foreground_window()?; + self.remove_floating_window(window_id) + } + + pub fn remove_floating_window(&mut self, window_id: u32) -> Option { + let mut idx = None; + for (i, window) in self.floating_windows().iter().enumerate() { + if window_id == window.id { + idx = Option::from(i); + } + } + + match idx { + None => None, + Some(idx) => { + if self.floating_windows().get(idx).is_some() { + self.focus_previous_floating_window(); + self.floating_windows_mut().remove(idx) + } else { + None + } + } + } + } + + pub fn focus_previous_floating_window(&mut self) { + let focused_idx = self.focused_floating_window_idx(); + self.focus_floating_window(focused_idx.saturating_sub(1)); + } + + pub fn focus_floating_window(&mut self, idx: usize) { + tracing::info!("focusing floating window"); + + self.floating_windows.focus(idx); + } } impl Workspace { @@ -509,7 +640,7 @@ impl Workspace { && resize_dimensions_is_empty; if percentage_override { - window.center(&work_area)?; + window.center(&work_area, false)?; } else if let Err(error) = window.set_position(layout) { tracing::warn!("failed to set window position: {error}") } @@ -887,6 +1018,45 @@ mod tests { assert_eq!(ws.containers()[2].focused_window().unwrap().id, 3); } + #[test] + fn test_locked_containers_toggle_float() { + let mut ws = Workspace::default(); + + // add 4 containers + for i in 0..4 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + if i == 1 { + container.locked = true; + } + ws.add_container_to_back(container); + } + assert_eq!(ws.containers().len(), 4); + + // set index 0 focused + ws.focus_container(0); + + // float index 0 + ws.new_floating_window().unwrap(); + + assert_eq!(ws.containers()[0].focused_window().unwrap().id, 2); + // index 1 should still be the same + assert_eq!(ws.containers()[1].focused_window().unwrap().id, 1); + assert_eq!(ws.containers()[2].focused_window().unwrap().id, 3); + + // unfloat - have to do this semi-manually becuase of calls to WindowsApi in + // new_container_for_floating_window which usually handles unfloating + let window = ws.floating_windows_mut().pop_back().unwrap(); + let mut container = Container::default(); + container.add_window(&window).unwrap(); + ws.insert_container_at_idx(ws.focused_container_idx(), container); + + // all indexes should be at their original position + for i in 0..4 { + assert_eq!(ws.containers()[i].focused_window().unwrap().id, i as u32); + } + } + #[test] fn test_contains_window() { // Create default workspace @@ -1350,6 +1520,40 @@ mod tests { assert_eq!(focused_container.focused_window_idx(), 1); } + #[test] + fn test_new_floating_window() { + let mut workspace = Workspace::default(); + + { + // Container with 3 windows + let mut container = Container::default(); + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + workspace.add_container_to_back(container); + } + + // Add window to floating_windows + workspace.new_floating_window().ok(); + + // Should have 1 floating window + assert_eq!(workspace.floating_windows().len(), 1); + + // Should have only 2 windows now + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 2); + + // Should contain hwnd 0 since this is the first window in the container + let floating_windows = workspace.floating_windows_mut(); + let mut contains = false; + for w in floating_windows { + if w.id == 0 { + contains = true; + } + } + assert!(contains); + } + #[test] fn test_layout_boundary_clamping() { use crate::core::Rect; diff --git a/komorebi/tests/float.rs b/komorebi/tests/float.rs new file mode 100644 index 00000000..1e13d738 --- /dev/null +++ b/komorebi/tests/float.rs @@ -0,0 +1,125 @@ +//! Floating a window with `toggle-float`, against an in-memory desktop: the messages go in +//! through [`WindowManager::process_command`], and what comes out is which windows the layout +//! tiles and where the backend is asked to put them. +//! +//! Window ids are in the 25_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel), +/// and a window for each of `ids`, opened in that order. The last one has the focus. +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmt-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + wm + }); + + (fake, wm) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn tiled(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().unwrap().id) + .collect() +} + +fn floating(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .floating_windows() + .iter() + .map(|window| window.id) + .collect() +} + +#[test] +fn toggle_float_takes_the_focused_window_out_of_the_layout_and_puts_it_back() { + let (fake, mut wm) = desktop_with(&[25_001, 25_002]); + let half = fake.rect_of(25_001).unwrap(); + + send(&fake, &mut wm, SocketMessage::ToggleFloat); + + assert_eq!(tiled(&wm), [25_001]); + assert_eq!(floating(&wm), [25_002]); + assert!( + fake.rect_of(25_001).unwrap().right > half.right, + "the window left in the layout has the work area" + ); + assert!(wm.focused_workspace().unwrap().contains_window(25_002)); + + send(&fake, &mut wm, SocketMessage::ToggleFloat); + + assert_eq!(tiled(&wm), [25_002, 25_001]); + assert!(floating(&wm).is_empty()); +} + +#[test] +fn a_floating_window_is_left_where_it_is_by_a_retile() { + let (fake, mut wm) = desktop_with(&[25_011, 25_012]); + send(&fake, &mut wm, SocketMessage::ToggleFloat); + let by_hand = Rect { + left: 300, + top: 200, + right: 640, + bottom: 480, + }; + fake.move_window_by_user(25_012, by_hand); + + send(&fake, &mut wm, SocketMessage::Retile); + + assert_eq!(fake.rect_of(25_012), Some(by_hand)); +} + +#[test] +fn toggle_float_without_a_focused_window_is_an_error() { + let (fake, mut wm) = desktop_with(&[25_021]); + fake.set_foreground(None); + + let result = with_backend(fake.clone(), || { + wm.process_command(SocketMessage::ToggleFloat, Vec::new()) + }); + + assert_eq!( + result.map_err(|error| error.to_string()), + Err(String::from("no foreground window")) + ); + assert_eq!(tiled(&wm), [25_021]); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index d6c65017..45d75e63 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -16,6 +16,7 @@ //! next window and give it up. //! - `promote`, `promote-swap`, `promote-focus` and `promote-window` bring a window to the largest //! tile, or the focus to it. +//! - `toggle-float` takes the focused window out of the layout, or puts it back. //! - `resize-edge` and `resize-axis` resize the focused window by the `resize-delta`, and //! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of //! the tiles of the focused workspace and load them back. @@ -304,6 +305,8 @@ enum SubCommand { Retile, /// Toggle window tiling on the focused workspace ToggleTiling, + /// Toggle floating mode for the focused window + ToggleFloat, /// Enable or disable mouse follows focus on all workspaces #[clap(arg_required_else_help = true)] MouseFollowsFocus(MouseFollowsFocus), @@ -453,6 +456,9 @@ fn main() -> eyre::Result<()> { SubCommand::FlipLayout(args) => { send_message(&SocketMessage::FlipLayout(args.axis))?; } + SubCommand::ToggleFloat => { + send_message(&SocketMessage::ToggleFloat)?; + } SubCommand::ResizeEdge(args) => { send_message(&SocketMessage::ResizeWindowEdge(args.edge, args.sizing))?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 1440500b..1b856f63 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -209,6 +209,7 @@ fn the_layout_subcommands_send_the_layout_axis_or_direction_they_are_given() { r#"{"type":"FlipLayout","content":"HorizontalAndVertical"}"#, ); sends(&["toggle-tiling"], r#"{"type":"ToggleTiling"}"#); + sends(&["toggle-float"], r#"{"type":"ToggleFloat"}"#); sends( &["preselect-direction", "up"], r#"{"type":"PreselectDirection","content":"Up"}"#, @@ -383,6 +384,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "state.md", "stop.md", "subscribe-socket.md", + "toggle-float.md", "toggle-mouse-follows-focus.md", "toggle-tiling.md", "unsubscribe-socket.md", diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index 17960b28..be3a9f55 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -289,13 +289,17 @@ class Kde: return sum(len(container["windows"]["elements"]) for container in containers) def managed_all(self) -> int: - """The number of windows the daemon has, in the containers of every workspace it has.""" - return sum( - len(container["windows"]["elements"]) - for monitor in self.state()["monitors"]["elements"] - for workspace in monitor["workspaces"]["elements"] - for container in workspace["containers"]["elements"] - ) + """The number of windows the daemon has, on every workspace of every monitor. + + That is the windows of the containers, and the floating windows. + """ + total = 0 + for monitor in self.state()["monitors"]["elements"]: + for workspace in monitor["workspaces"]["elements"]: + for container in workspace["containers"]["elements"]: + total += len(container["windows"]["elements"]) + total += len(workspace["floating_windows"]["elements"]) + return total def monitor_bridge(self, path: str) -> None: """Starts recording the bridge's traffic on the session bus to `path`, in the background. diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index cc684f7e..22195438 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -349,8 +349,13 @@ def container(*titles: str, focused: int = 0) -> dict[str, object]: } -def workspace(*containers: dict[str, object], focused: int = 0) -> dict[str, object]: - return {"containers": {"elements": list(containers), "focused": focused}} +def workspace( + *containers: dict[str, object], focused: int = 0, floating: tuple[str, ...] = () +) -> dict[str, object]: + return { + "containers": {"elements": list(containers), "focused": focused}, + "floating_windows": {"elements": [window(t) for t in floating], "focused": 0}, + } def a_state(*workspaces: dict[str, object]) -> str: @@ -381,10 +386,13 @@ def test_managed_counts_the_windows_of_every_container_of_the_workspace( assert kde.managed(1) == 1 -def test_managed_all_counts_the_windows_of_every_workspace_of_every_monitor( +def test_managed_all_counts_the_windows_and_the_floating_windows_of_every_workspace( machine: FakeMachine, ) -> None: - first = {"id": 1, "workspaces": {"elements": [workspace(container("a", "b"))], "focused": 0}} + first = { + "id": 1, + "workspaces": {"elements": [workspace(container("a", "b"), floating=("f",))], "focused": 0}, + } second = { "id": 2, "workspaces": {"elements": [workspace(container("c")), workspace()], "focused": 0}, @@ -394,7 +402,7 @@ def test_managed_all_counts_the_windows_of_every_workspace_of_every_monitor( output=json.dumps({"monitors": {"elements": [first, second], "focused": 0}}), ) - assert Kde(machine, "main").managed_all() == 3 + assert Kde(machine, "main").managed_all() == 4 def test_managed_is_zero_for_a_workspace_without_containers(machine: FakeMachine) -> None: diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 97e240fc..41332fbf 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -182,6 +182,8 @@ scrolling-layout-columns 2 change-layout bsp preselect-direction left cancel-preselect +toggle-float +toggle-float toggle-tiling toggle-tiling mouse-follows-focus enable