From 948425f9ae930695d5622189c85eec6302949f51 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 12:50:28 -0700 Subject: [PATCH] refactor(windows): the workspace is komorebi-core's Workspace over WindowsPlatform BEHAVIOUR (Windows runtime): the type of every workspace in the daemon changes; by construction the code is the same. Marked because it was only type-checked. komorebi/src/workspace.rs no longer defines Workspace: `type Workspace = komorebi_core::Workspace`, with WorkspaceLayer, WorkspaceWindowLocation, CachedLayoutDefault and the threshold helpers re-exported from the crate. WindowsPlatform implements WorkspacePlatform (the window is Window, no extra state, default_padding reads DEFAULT_CONTAINER_PADDING and DEFAULT_WORKSPACE_PADDING as Default did, the foreground window, cursor, rule matching with the regex table and the three scrolling lookups forward to what the file called inline; after_floating_removed stays the default no-op, as Windows does not refocus). The functions that moved are gone from the file; every other method of the old impl (update, hide, restore, remove_window, apply_wallpaper, load_static_config, border_kinds_on_show, windows_on_show, the scrolling glue of scrolling.rs, ...) is a method of the extension traits WorkspaceExt and WorkspaceScrolling, unchanged in body, which each caller imports. static_config::workspace_config(&Workspace) replaces the From<&Workspace> impl for WorkspaceConfig (orphan rule). Workspace is built with state: Default::default() in state.rs. Windows e2e scenarios needed (all of them touch the workspace): tiled, stack and float state scenarios with komorebic state compared to e2e/lib/tests/fixtures/kfw-{tiled,stack,float}.json; commands, workspaces, stacking, scrolling, resize, borders and animation sweeps; workspace rules and initial_window_placement rules; focus and move across workspaces and monitors; the schema checks. Verified: Windows clippy --workspace --locked --all-targets -D warnings: PASS. Not run: Windows tests, e2e. --- komorebi/src/monitor.rs | 1 + komorebi/src/pan.rs | 1 + komorebi/src/process_command.rs | 6 +- komorebi/src/process_event.rs | 1 + komorebi/src/reaper.rs | 1 + komorebi/src/scrolling.rs | 320 ++++---- komorebi/src/state.rs | 1 + komorebi/src/static_config.rs | 11 +- komorebi/src/window_manager.rs | 10 +- komorebi/src/windows_api.rs | 1 + komorebi/src/workspace.rs | 1239 ++++--------------------------- 11 files changed, 371 insertions(+), 1221 deletions(-) diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 39c2fc30..6c70adb1 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -1,3 +1,4 @@ +use crate::workspace::WorkspaceExt; use std::collections::HashMap; use std::collections::VecDeque; use std::sync::atomic::Ordering; diff --git a/komorebi/src/pan.rs b/komorebi/src/pan.rs index d835cde5..51058777 100644 --- a/komorebi/src/pan.rs +++ b/komorebi/src/pan.rs @@ -11,6 +11,7 @@ use crate::core::PanGesture; use crate::core::Rect; use crate::live_resize; use crate::live_resize::Snapping; +use crate::scrolling::WorkspaceScrolling; use crate::window_manager::WindowManager; use crate::windows_backend::backend; use color_eyre::eyre; diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 309df3c9..555173ec 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -1,3 +1,5 @@ +use crate::scrolling::WorkspaceScrolling; +use crate::workspace::WorkspaceExt; use color_eyre::eyre; use color_eyre::eyre::OptionExt; use color_eyre::eyre::WrapErr; @@ -2002,7 +2004,9 @@ if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) pub fn add_session_float_rule(&mut self) -> eyre::Result<()> { let foreground_window = WindowsApi::foreground_window()?; let window = Window::from(foreground_window); - if let (Some(exe), Some(title), Some(class)) = (window.exe(), window.title(), window.class()) { + if let (Some(exe), Some(title), Some(class)) = + (window.exe(), window.title(), window.class()) + { let rule = MatchingRule::Composite(vec![ IdWithIdentifier { kind: ApplicationIdentifier::Exe, diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 0b1f9cbb..df59a5f5 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -1,3 +1,4 @@ +use crate::workspace::WorkspaceExt; use std::process::Command; use std::sync::Arc; diff --git a/komorebi/src/reaper.rs b/komorebi/src/reaper.rs index 92ad0695..00077fbc 100644 --- a/komorebi/src/reaper.rs +++ b/komorebi/src/reaper.rs @@ -10,6 +10,7 @@ use crate::WindowManagerEvent; use crate::border_manager; use crate::notify_subscribers; use crate::winevent::WinEvent; +use crate::workspace::WorkspaceExt; use crossbeam_channel::Receiver; use crossbeam_channel::Sender; diff --git a/komorebi/src/scrolling.rs b/komorebi/src/scrolling.rs index 51994f50..f46fea83 100644 --- a/komorebi/src/scrolling.rs +++ b/komorebi/src/scrolling.rs @@ -10,8 +10,6 @@ use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; use crate::animation::ANIMATION_MANAGER; use crate::animation::prefix::AnimationPrefix; use crate::container::Container; -use crate::core::DefaultLayout; -use crate::core::Layout; use crate::core::LayoutOptions; use crate::core::OperationDirection; use crate::core::Rect; @@ -20,6 +18,7 @@ use crate::core::Sizing; use crate::core::WindowHandlingBehaviour; use crate::windows_backend::backend; use crate::workspace::Workspace; +use crate::workspace::WorkspaceExt; use color_eyre::eyre; use komorebi_backend::WindowId; use komorebi_layouts::scrolling; @@ -168,7 +167,7 @@ pub(crate) fn animations_enabled() -> bool { .is_some_and(|enabled| *enabled) } -impl Workspace { +pub(crate) trait WorkspaceScrolling { /// Learn from what windows turned out to be when they were sent to where the layout put them, /// which is that some of them are wider than the layout said and will not be any narrower. /// @@ -178,7 +177,171 @@ impl Workspace { /// /// `around_window` is what a column takes up around its window on either side, and the strip /// is `viewport_width` wide. Returns whether any column changed. - pub(crate) fn adopt_actual_widths(&mut self, around_window: i32, viewport_width: i32) -> bool { + fn adopt_actual_widths(&mut self, around_window: i32, viewport_width: i32) -> bool; + + fn scrolling_ids(&self) -> Vec; + + /// Set how many columns the Scrolling layout shows at once, keeping every other layout option. + fn set_scrolling_columns(&mut self, columns: usize); + + /// Make the space match the containers, and the focus, as they are now. + fn sync_scrolling(&mut self, viewport: komorebi_scrolling::Viewport); + + /// Say what the column of the container at this index was given, as it is about to be taken + /// out of the workspace, for the workspace that it is put in to find. + fn note_scrolling_departure(&self, idx: usize); + + /// Make the space match the containers and the focus as they are now, for a space that is + /// there to be made to match. + /// + /// This is for a change that is about to be made to the containers, and that the space is + /// going to be told about directly. The space has to know what there is before it is told + /// what goes. + fn sync_scrolling_containers(&mut self); + + /// Give focus to what the strip says should have it after the container `removed` has gone, + /// and tell whether the strip had anything to say. + /// + /// Focus goes back to the column that the closed one was opened next to, if nothing has + /// moved focus since, and otherwise to the column that takes its place on the right. Focus that + /// is not on the closed column stays where it is. This is not what the other layouts do, which + /// always move focus to the left. + fn focus_after_scrolling_removal(&mut self, removed: &str) -> bool; + + /// Where every container goes in `work_area`, from left to right, with `container_padding` + /// taken off every side of each. + fn layout_scrolling( + &mut self, + work_area: &Rect, + container_padding: i32, + ) -> Vec; + + /// Where the container that a new window gets goes, if the strip has a say: after the last + /// tile of the column that has focus. + /// + /// A new window is a column of its own beside the focused one, and not a tile in the middle of + /// it, which is what the container after the focused one would be if the column has other + /// tiles below. + fn scrolling_insertion_idx(&self) -> Option; + + /// Where focus would go from the focused container in this direction, in the strip as it is + /// now, or `None` if it would not go anywhere. + /// + /// Left and right are the neighbouring columns, and focus goes to the tile that had it last + /// in the one it arrives at. Up and down are the tiles of the focused column, and stop at + /// the ends. + fn scrolling_idx_for_direction(&self, direction: OperationDirection) -> Option; + + /// Make the order of the containers the order of the tiles of the strip, and focus the tile + /// that the strip says has it. + /// + /// Most of what the strip does leaves the order alone. What moves a tile past another does + /// not, and the list of containers is what is true, so it is made to match. + fn apply_scrolling_order(&mut self); + + /// Make the space agree with which container has focus, and give back the id of that + /// container, for a command that is about the focused column. + /// + /// There is nothing to do until a layout has made the space, and in a layout that is not + /// Scrolling. + fn focused_scrolling_column(&mut self) -> Option; + + /// Move the focused column one place to the left or right, or the focused tile one place up + /// or down in its column, and tell whether anything moved. + /// + /// A column moves with all of its tiles. + fn move_scrolling(&mut self, direction: OperationDirection) -> bool; + + /// Take the neighbouring tile on one side into the focused column: the first tile of the + /// column on the right to the bottom of it, or the last tile of the column on the left to the + /// top of it. Up and down mean nothing here. + fn consume_scrolling(&mut self, direction: OperationDirection); + + /// Take the focused tile out of its column and put it in a column of its own on the right. + fn expel_scrolling(&mut self); + + /// Stack the windows of the focused column in one tile, or spread the stack in the focused tile + /// out into the tiles of a column, whichever it is, and tell whether there was anything to do. + /// + /// A column of several tiles becomes one tile that is a stack of all of their windows, in the + /// order that they were in, with the window that had focus still showing. A tile that is a stack + /// becomes a column of a tile for each of its windows, in the order of its tabs, with focus on + /// the window that had it. Either way the column keeps its width, but the heights that its tiles + /// were given are not remembered for when it is toggled back. + fn toggle_scrolling_column_stack(&mut self) -> eyre::Result; + + /// Put the windows of all of the containers with these ids in the first of them, in order. + fn stack_scrolling_column(&mut self, column: &[String]); + + /// Put each of the windows of the focused container in a container of its own, in the same + /// column, and tell whether it had more than one. + fn unstack_scrolling_column(&mut self) -> bool; + + /// Put every column back to the width that the `columns` option gives, which forgets every + /// width that was set by resizing, by a preset, or by taking the full width, and every window + /// back to an equal share of the height of its column. The narrowest that windows were found + /// to accept is forgotten as well. + /// + /// The focused column stays where it is on screen unless it has to scroll to stay in view. + fn reset_scrolling_sizes(&mut self); + + /// Make the focused column as wide as the screen, or give it back the width that it had. + fn toggle_scrolling_full_width(&mut self); + + /// Make the focused column as wide as it can be without scrolling anything else out of view, + /// which is to fill the room that the columns in view leave. Only the Scrolling layout has + /// columns to expand. + fn expand_scrolling_column(&mut self); + + /// Start moving the strip across the screen by hand, and give back the strip as it is, for + /// putting it back if the pan is given up. Only the Scrolling layout has a strip to move, and + /// not before a layout has made it. + fn begin_scrolling_pan(&mut self) -> Option>; + + /// Move the strip by `dx` pixels on the screen, to the right if it is positive. Nothing else + /// changes: not which container has focus, nor the width of any. + fn pan_scrolling(&mut self, dx: f64); + + /// Let go of the strip, going at `velocity` pixels a second on the screen, to the right if it + /// is positive, and let it come to rest, which is with a column against an edge of the screen. + /// Focus goes to the nearest column that is fully in view if the focused one is not, and + /// this tells whether it moved. + fn end_scrolling_pan(&mut self, velocity: f64) -> bool; + + /// Give up a pan: the strip is put back to what it was when it began. + fn cancel_scrolling_pan(&mut self, saved: ScrollingSpace); + + /// How far into the strip the left edge of the screen is, in pixels. A strip that is moved + /// by `dx` has this smaller by `dx`. + fn scrolling_view_offset(&self) -> Option; + + /// Where the strip puts the window that shows in each container, as how far its left edge + /// is from the left edge of the screen, and whether it is on the screen there and so + /// where it really is: windows that are not are parked at an edge. + fn scrolling_lefts(&self) -> Vec<(isize, i32, bool)>; + + /// How wide the screen is that the strip is moved across, in pixels. + fn scrolling_view_width(&self) -> Option; + + /// How far one step of a pan goes, if nothing says: a column of the width that a new one + /// is given. + fn scrolling_pan_step(&self) -> Option; + + /// Centre the focused column on the screen, this once. + fn center_scrolling_column(&mut self); + + /// Make the focused column wider or narrower with the horizontal edges, and the focused window + /// taller or shorter in its column with the vertical ones. + fn resize_scrolling_column( + &mut self, + direction: OperationDirection, + sizing: Sizing, + delta: i32, + ); +} + +impl WorkspaceScrolling for Workspace { + fn adopt_actual_widths(&mut self, around_window: i32, viewport_width: i32) -> bool { // a window that is still on its way, or whose move was only asked for, is not what it // is going to be, and taking its size for a minimum would make the column too wide for good if !window_sizes_are_settled() { @@ -241,11 +404,6 @@ impl Workspace { adopted } - /// Whether the workspace is laid out as a strip of columns. - pub(crate) fn is_scrolling(&self) -> bool { - matches!(self.layout, Layout::Default(DefaultLayout::Scrolling)) - } - fn scrolling_ids(&self) -> Vec { self.containers() .iter() @@ -253,8 +411,7 @@ impl Workspace { .collect() } - /// Set how many columns the Scrolling layout shows at once, keeping every other layout option. - pub fn set_scrolling_columns(&mut self, columns: usize) { + fn set_scrolling_columns(&mut self, columns: usize) { let mut options = self.layout_options.unwrap_or(LayoutOptions { scrolling: None, grid: None, @@ -275,7 +432,6 @@ impl Workspace { self.layout_options = Some(options); } - /// Make the space match the containers, and the focus, as they are now. fn sync_scrolling(&mut self, viewport: komorebi_scrolling::Viewport) { let options = scrolling_options(self.effective_layout_options()); let ids = self.scrolling_ids(); @@ -292,9 +448,7 @@ impl Workspace { ); } - /// Say what the column of the container at this index was given, as it is about to be taken - /// out of the workspace, for the workspace that it is put in to find. - pub(crate) fn note_scrolling_departure(&self, idx: usize) { + fn note_scrolling_departure(&self, idx: usize) { if let Some(space) = &self.scrolling && let Some(container) = self.containers().get(idx) && let Some(record) = space.column_record(&container.id) @@ -303,13 +457,7 @@ impl Workspace { } } - /// Make the space match the containers and the focus as they are now, for a space that is - /// there to be made to match. - /// - /// This is for a change that is about to be made to the containers, and that the space is - /// going to be told about directly. The space has to know what there is before it is told - /// what goes. - pub(crate) fn sync_scrolling_containers(&mut self) { + fn sync_scrolling_containers(&mut self) { let ids = self.scrolling_ids(); let focused = self .focused_container() @@ -321,14 +469,7 @@ impl Workspace { } } - /// Give focus to what the strip says should have it after the container `removed` has gone, - /// and tell whether the strip had anything to say. - /// - /// Focus goes back to the column that the closed one was opened next to, if nothing has - /// moved focus since, and otherwise to the column that takes its place on the right. Focus that - /// is not on the closed column stays where it is. This is not what the other layouts do, which - /// always move focus to the left. - pub(crate) fn focus_after_scrolling_removal(&mut self, removed: &str) -> bool { + fn focus_after_scrolling_removal(&mut self, removed: &str) -> bool { let Some(space) = self.scrolling.as_mut() else { return false; }; @@ -346,9 +487,7 @@ impl Workspace { true } - /// Where every container goes in `work_area`, from left to right, with `container_padding` - /// taken off every side of each. - pub(crate) fn layout_scrolling( + fn layout_scrolling( &mut self, work_area: &Rect, container_padding: i32, @@ -361,13 +500,7 @@ impl Workspace { .unwrap_or_default() } - /// Where the container that a new window gets goes, if the strip has a say: after the last - /// tile of the column that has focus. - /// - /// A new window is a column of its own beside the focused one, and not a tile in the middle of - /// it, which is what the container after the focused one would be if the column has other - /// tiles below. - pub(crate) fn scrolling_insertion_idx(&self) -> Option { + fn scrolling_insertion_idx(&self) -> Option { if !self.is_scrolling() { return None; } @@ -382,16 +515,7 @@ impl Workspace { .map(|idx| idx + 1) } - /// Where focus would go from the focused container in this direction, in the strip as it is - /// now, or `None` if it would not go anywhere. - /// - /// Left and right are the neighbouring columns, and focus goes to the tile that had it last - /// in the one it arrives at. Up and down are the tiles of the focused column, and stop at - /// the ends. - pub(crate) fn scrolling_idx_for_direction( - &self, - direction: OperationDirection, - ) -> Option { + fn scrolling_idx_for_direction(&self, direction: OperationDirection) -> Option { // the strip may not have heard about everything that happened since the last layout, so // this goes by a copy of it that has let mut probe = self.scrolling.clone()?; @@ -415,11 +539,6 @@ impl Workspace { } } - /// Make the order of the containers the order of the tiles of the strip, and focus the tile - /// that the strip says has it. - /// - /// Most of what the strip does leaves the order alone. What moves a tile past another does - /// not, and the list of containers is what is true, so it is made to match. fn apply_scrolling_order(&mut self) { let Some(space) = self.scrolling.as_ref() else { return; @@ -447,11 +566,6 @@ impl Workspace { self.resize_dimensions = vec![None; self.containers().len()]; } - /// Make the space agree with which container has focus, and give back the id of that - /// container, for a command that is about the focused column. - /// - /// There is nothing to do until a layout has made the space, and in a layout that is not - /// Scrolling. fn focused_scrolling_column(&mut self) -> Option { if !self.is_scrolling() || self.scrolling.is_none() { return None; @@ -463,11 +577,7 @@ impl Workspace { .map(|container| container.id.clone()) } - /// Move the focused column one place to the left or right, or the focused tile one place up - /// or down in its column, and tell whether anything moved. - /// - /// A column moves with all of its tiles. - pub(crate) fn move_scrolling(&mut self, direction: OperationDirection) -> bool { + fn move_scrolling(&mut self, direction: OperationDirection) -> bool { let Some(id) = self.focused_scrolling_column() else { return false; }; @@ -505,10 +615,7 @@ impl Workspace { moved } - /// Take the neighbouring tile on one side into the focused column: the first tile of the - /// column on the right to the bottom of it, or the last tile of the column on the left to the - /// top of it. Up and down mean nothing here. - pub(crate) fn consume_scrolling(&mut self, direction: OperationDirection) { + fn consume_scrolling(&mut self, direction: OperationDirection) { if self.focused_scrolling_column().is_none() { return; } @@ -528,8 +635,7 @@ impl Workspace { } } - /// Take the focused tile out of its column and put it in a column of its own on the right. - pub(crate) fn expel_scrolling(&mut self) { + fn expel_scrolling(&mut self) { if self.focused_scrolling_column().is_none() { return; } @@ -543,15 +649,7 @@ impl Workspace { } } - /// Stack the windows of the focused column in one tile, or spread the stack in the focused tile - /// out into the tiles of a column, whichever it is, and tell whether there was anything to do. - /// - /// A column of several tiles becomes one tile that is a stack of all of their windows, in the - /// order that they were in, with the window that had focus still showing. A tile that is a stack - /// becomes a column of a tile for each of its windows, in the order of its tabs, with focus on - /// the window that had it. Either way the column keeps its width, but the heights that its tiles - /// were given are not remembered for when it is toggled back. - pub(crate) fn toggle_scrolling_column_stack(&mut self) -> eyre::Result { + fn toggle_scrolling_column_stack(&mut self) -> eyre::Result { let Some(id) = self.focused_scrolling_column() else { return Ok(false); }; @@ -573,7 +671,6 @@ impl Workspace { Ok(self.unstack_scrolling_column()) } - /// Put the windows of all of the containers with these ids in the first of them, in order. fn stack_scrolling_column(&mut self, column: &[String]) { let focused_window = self .focused_container() @@ -613,8 +710,6 @@ impl Workspace { self.focus_container(idx); } - /// Put each of the windows of the focused container in a container of its own, in the same - /// column, and tell whether it had more than one. fn unstack_scrolling_column(&mut self) -> bool { let idx = self.focused_container_idx(); @@ -674,13 +769,7 @@ impl Workspace { true } - /// Put every column back to the width that the `columns` option gives, which forgets every - /// width that was set by resizing, by a preset, or by taking the full width, and every window - /// back to an equal share of the height of its column. The narrowest that windows were found - /// to accept is forgotten as well. - /// - /// The focused column stays where it is on screen unless it has to scroll to stay in view. - pub(crate) fn reset_scrolling_sizes(&mut self) { + fn reset_scrolling_sizes(&mut self) { if let Some(space) = self.scrolling.as_mut() { space.reset_widths(); space.reset_heights(); @@ -694,8 +783,7 @@ impl Workspace { } } - /// Make the focused column as wide as the screen, or give it back the width that it had. - pub(crate) fn toggle_scrolling_full_width(&mut self) { + fn toggle_scrolling_full_width(&mut self) { if let Some(id) = self.focused_scrolling_column() && let Some(space) = self.scrolling.as_mut() { @@ -703,10 +791,7 @@ impl Workspace { } } - /// Make the focused column as wide as it can be without scrolling anything else out of view, - /// which is to fill the room that the columns in view leave. Only the Scrolling layout has - /// columns to expand. - pub(crate) fn expand_scrolling_column(&mut self) { + fn expand_scrolling_column(&mut self) { if self.is_scrolling() && self.focused_scrolling_column().is_some() && let Some(space) = self.scrolling.as_mut() @@ -715,10 +800,7 @@ impl Workspace { } } - /// Start moving the strip across the screen by hand, and give back the strip as it is, for - /// putting it back if the pan is given up. Only the Scrolling layout has a strip to move, and - /// not before a layout has made it. - pub(crate) fn begin_scrolling_pan(&mut self) -> Option> { + fn begin_scrolling_pan(&mut self) -> Option> { if !self.is_scrolling() || self.scrolling.is_none() { return None; } @@ -732,19 +814,13 @@ impl Workspace { Some(saved) } - /// Move the strip by `dx` pixels on the screen, to the right if it is positive. Nothing else - /// changes: not which container has focus, nor the width of any. - pub(crate) fn pan_scrolling(&mut self, dx: f64) { + fn pan_scrolling(&mut self, dx: f64) { if let Some(space) = self.scrolling.as_mut() { space.pan_by(dx); } } - /// Let go of the strip, going at `velocity` pixels a second on the screen, to the right if it - /// is positive, and let it come to rest, which is with a column against an edge of the screen. - /// Focus goes to the nearest column that is fully in view if the focused one is not, and - /// this tells whether it moved. - pub(crate) fn end_scrolling_pan(&mut self, velocity: f64) -> bool { + fn end_scrolling_pan(&mut self, velocity: f64) -> bool { let Some(space) = self.scrolling.as_mut() else { return false; }; @@ -765,23 +841,17 @@ impl Workspace { } } - /// Give up a pan: the strip is put back to what it was when it began. - pub(crate) fn cancel_scrolling_pan(&mut self, saved: ScrollingSpace) { + fn cancel_scrolling_pan(&mut self, saved: ScrollingSpace) { if self.scrolling.is_some() { self.scrolling = Some(saved); } } - /// How far into the strip the left edge of the screen is, in pixels. A strip that is moved - /// by `dx` has this smaller by `dx`. - pub(crate) fn scrolling_view_offset(&self) -> Option { + fn scrolling_view_offset(&self) -> Option { self.scrolling.as_ref().map(ScrollingSpace::view_offset) } - /// Where the strip puts the window that shows in each container, as how far its left edge - /// is from the left edge of the screen, and whether it is on the screen there and so - /// where it really is: windows that are not are parked at an edge. - pub(crate) fn scrolling_lefts(&self) -> Vec<(isize, i32, bool)> { + fn scrolling_lefts(&self) -> Vec<(isize, i32, bool)> { let Some(space) = self.scrolling.as_ref() else { return vec![]; }; @@ -801,14 +871,11 @@ impl Workspace { .collect() } - /// How wide the screen is that the strip is moved across, in pixels. - pub(crate) fn scrolling_view_width(&self) -> Option { + fn scrolling_view_width(&self) -> Option { self.scrolling.as_ref().map(|space| space.viewport().width) } - /// How far one step of a pan goes, if nothing says: a column of the width that a new one - /// is given. - pub(crate) fn scrolling_pan_step(&self) -> Option { + fn scrolling_pan_step(&self) -> Option { let space = self.scrolling.as_ref()?; let viewport = f64::from(space.viewport().width); @@ -820,8 +887,7 @@ impl Workspace { Some(step.round() as i32) } - /// Centre the focused column on the screen, this once. - pub(crate) fn center_scrolling_column(&mut self) { + fn center_scrolling_column(&mut self) { if self.focused_scrolling_column().is_some() && let Some(space) = self.scrolling.as_mut() { @@ -829,9 +895,7 @@ impl Workspace { } } - /// Make the focused column wider or narrower with the horizontal edges, and the focused window - /// taller or shorter in its column with the vertical ones. - pub(crate) fn resize_scrolling_column( + fn resize_scrolling_column( &mut self, direction: OperationDirection, sizing: Sizing, @@ -853,7 +917,9 @@ impl Workspace { #[cfg(test)] mod tests { use super::*; + use crate::DefaultLayout; use crate::HIDDEN_HWNDS; + use crate::Layout; use crate::window::Window; const AREA: Rect = Rect { diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 931500e5..c6102625 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -287,6 +287,7 @@ impl From<&WindowManager> for State { .initial_window_placement_rules .clone(), scrolling: None, + state: Default::default(), }) .collect::>(); ws.focus(monitor.workspaces.focused_idx()); diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index a9f3beea..18506012 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -80,6 +80,7 @@ use crate::window_manager::WindowManager; use crate::window_manager_event::WindowManagerEvent; use crate::windows_api::WindowsApi; use crate::workspace::Workspace; +use crate::workspace::WorkspaceExt; use color_eyre::eyre; use crossbeam_channel::Receiver; use hotwatch::EventKind; @@ -109,8 +110,10 @@ pub use komorebi_config::static_config::ThemeOptions; pub use komorebi_config::static_config::Wallpaper; pub use komorebi_config::static_config::WorkspaceConfig; -impl From<&Workspace> for WorkspaceConfig { - fn from(value: &Workspace) -> Self { +/// The `komorebi.json` entry that describes a workspace (the shared `Workspace` is not local, so this is +/// a function and not a `From` impl) +pub fn workspace_config(value: &Workspace) -> WorkspaceConfig { + { let mut layout_rules = HashMap::new(); for (threshold, layout) in &value.layout_rules { match layout { @@ -155,7 +158,7 @@ impl From<&Workspace> for WorkspaceConfig { let tile = if value.tile { None } else { Some(false) }; - Self { + WorkspaceConfig { name: value .name .clone() @@ -219,7 +222,7 @@ impl From<&Monitor> for MonitorConfig { fn from(value: &Monitor) -> Self { let mut workspaces = vec![]; for w in value.workspaces() { - workspaces.push(WorkspaceConfig::from(w)); + workspaces.push(workspace_config(w)); } let default_container_padding = DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst); diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index f5e63666..c8b19863 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1,3 +1,5 @@ +use crate::scrolling::WorkspaceScrolling; +use crate::workspace::WorkspaceExt; use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; @@ -637,7 +639,9 @@ impl WindowManager { already_moved_window_handles.insert(window.hwnd); self.add_window_handle_to_move_based_on_workspace_rule( - &window.title().ok_or_eyre("the window has no title")?, + &window + .title() + .ok_or_eyre("the window has no title")?, window.hwnd, i, j, @@ -649,7 +653,9 @@ impl WindowManager { } } else { self.add_window_handle_to_move_based_on_workspace_rule( - &window.title().ok_or_eyre("the window has no title")?, + &window + .title() + .ok_or_eyre("the window has no title")?, window.hwnd, i, j, diff --git a/komorebi/src/windows_api.rs b/komorebi/src/windows_api.rs index 1bb39165..6c698b23 100644 --- a/komorebi/src/windows_api.rs +++ b/komorebi/src/windows_api.rs @@ -1,3 +1,4 @@ +use crate::workspace::WorkspaceExt; use color_eyre::eyre; use color_eyre::eyre::Error; use color_eyre::eyre::OptionExt; diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index cbaba58e..ab2778da 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -1,15 +1,95 @@ +use crate::scrolling::WorkspaceScrolling; use std::collections::HashMap; use std::ffi::OsStr; -use std::fmt::Display; -use std::fmt::Formatter; use std::io::Write; use std::num::NonZeroUsize; + +pub use komorebi_core::WorkspaceLayer; +pub use komorebi_core::WorkspaceWindowLocation; +pub(crate) use komorebi_core::resolve_threshold_match; +pub(crate) use komorebi_core::sorted_layout_options_rules; + +/// The workspace over the Windows [`Window`], which is `komorebi_core::Workspace` with this +/// platform's methods added by [`WorkspaceExt`] and the scrolling ones of [`WorkspaceScrolling`] +pub type Workspace = komorebi_core::Workspace; + +/// The Windows daemon as the platform of the shared workspace +#[derive(Debug, Clone, PartialEq)] +pub struct WindowsPlatform; + +impl komorebi_core::WorkspacePlatform for WindowsPlatform { + type Window = Window; + type State = (); + + fn default_padding() -> (Option, Option) { + ( + Option::from(DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst)), + Option::from(DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst)), + ) + } + + fn foreground_window_id() -> Option { + crate::window::foreground_window_id() + } + + fn cursor_position() -> Option<(i32, i32)> { + crate::window::cursor_position() + } + + fn should_act_window( + title: &str, + exe_name: &str, + class: &str, + path: &str, + rules: &[crate::core::config_generation::MatchingRule], + ) -> Option { + should_act_window( + title, + exe_name, + class, + path, + rules, + ®EX_IDENTIFIERS.lock(), + ) + } + + fn should_act_window_individual( + title: &str, + exe_name: &str, + class: &str, + path: &str, + rule: &crate::core::config_generation::IdWithIdentifier, + ) -> bool { + should_act_window_individual( + title, + exe_name, + class, + path, + rule, + ®EX_IDENTIFIERS.lock(), + ) + } + + fn scrolling_idx_for_direction( + workspace: &Workspace, + direction: OperationDirection, + ) -> Option { + workspace.scrolling_idx_for_direction(direction) + } + + fn scrolling_insertion_idx(workspace: &Workspace) -> Option { + workspace.scrolling_insertion_idx() + } + + fn note_scrolling_departure(workspace: &Workspace, idx: usize) { + workspace.note_scrolling_departure(idx); + } +} use std::sync::atomic::Ordering; use crate::DATA_DIR; use crate::DEFAULT_CONTAINER_PADDING; use crate::DEFAULT_WORKSPACE_PADDING; -use crate::FloatingLayerBehaviour; use crate::HIDDEN_HWNDS; use crate::INITIAL_CONFIGURATION_LOADED; use crate::KomorebiTheme; @@ -18,27 +98,18 @@ use crate::REGEX_IDENTIFIERS; use crate::REMOVE_TITLEBARS; use crate::SocketMessage; use crate::Wallpaper; -use crate::WindowContainerBehaviour; use crate::animation::engine::AnimationBatch; use crate::border_manager; use crate::container::Container; use crate::container::ContainerExt; -use crate::core::Axis; use crate::core::CustomLayout; -use crate::core::CycleDirection; use crate::core::DefaultLayout; -use crate::core::InitialWindowPlacementRules; use crate::core::Layout; use crate::core::LayoutDefaultEntry; use crate::core::LayoutOptions; use crate::core::OperationDirection; -use crate::core::PlacementMatchingRules; -use crate::core::PlacementTarget; -use crate::core::Rect; use crate::core::WindowKind; -use crate::core::WindowPlacement; use crate::lockable_sequence::LockableSequence; -use crate::ring::Ring; use crate::should_act; use crate::should_act_window; use crate::should_act_window_individual; @@ -48,185 +119,74 @@ use crate::static_config::WorkspaceConfig; use crate::window::PlatformWindowId; use crate::window::Window; use crate::window::WindowDetails; -use crate::window::cursor_position; -use crate::window::foreground_window_id; use crate::windows_api::WindowsApi; use crate::windows_backend::backend; use color_eyre::eyre; use color_eyre::eyre::OptionExt; use komorebi_backend::WindowId; +use komorebi_core::CachedLayoutDefault; use komorebi_core::ContainerWindow; pub use komorebi_core::WorkspaceGlobals; -use komorebi_scrolling::ScrollingSpace; use komorebi_themes::Base16ColourPalette; use komorebi_themes::KomorebiThemeCustom as Custom; -use serde::Deserialize; -use serde::Serialize; use uds_windows::UnixStream; -#[allow(clippy::struct_field_names)] -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -pub struct Workspace { - pub name: Option, - pub containers: Ring, - pub monocle_container: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub monocle_container_restore_idx: Option, - pub maximized_window: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub maximized_window_restore_idx: Option, - pub floating_windows: Ring, - pub layout: Layout, - pub layout_options: Option, - pub layout_rules: Vec<(usize, Layout)>, - /// Threshold-based layout options rules (container_count >= threshold -> use these options). - /// Sorted by threshold ascending at load time. - #[serde(default)] - pub layout_options_rules: Vec<(usize, LayoutOptions)>, - /// Cached per-layout defaults from the global `layout_defaults` config setting. - /// Pre-sorted at config load time; used as fallback when workspace has no overrides. - #[serde(skip)] - pub(crate) layout_defaults_cache: HashMap, - pub work_area_offset_rules: Vec<(usize, Rect)>, - pub layout_flip: Option, - pub workspace_padding: Option, - pub container_padding: Option, - pub latest_layout: Vec, - pub resize_dimensions: Vec>, - pub tile: bool, - pub work_area_offset: Option, - pub apply_window_based_work_area_offset: bool, - pub window_container_behaviour: Option, - pub window_container_behaviour_rules: Option>, - pub float_override: Option, - #[serde(skip)] - pub globals: WorkspaceGlobals, - pub layer: WorkspaceLayer, - pub floating_layer_behaviour: Option, - pub wallpaper: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_config: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub preselected_container_idx: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub promotion_swap_container_idx: Option, - /// Initial window placement rules that determine where new tiled windows are placed - #[serde(skip_serializing_if = "Option::is_none")] - pub initial_window_placement_rules: Option, - /// The strip of columns that the Scrolling layout lays containers out in - #[serde(skip)] - #[cfg_attr(feature = "schemars", schemars(skip))] - pub(crate) scrolling: Option>, +pub trait WorkspaceExt { + fn load_static_config( + &mut self, + config: &WorkspaceConfig, + layout_defaults: Option<&HashMap>, + ) -> eyre::Result<()>; + + /// Compute effective layout options using the complete-replacement cascade: + /// + /// If the workspace defines EITHER `layout_options` OR `layout_options_rules`, + /// it completely replaces the global `layout_defaults` for this layout. + /// Global defaults are only used when the workspace has NEITHER setting. + /// + /// Within the effective source (workspace or global): + /// 1. Try threshold match from rules (highest matching threshold wins) + /// 2. If a rule matches -> use it (full replacement of base) + /// 3. Else -> use the base `layout_options` + fn effective_layout_options(&self) -> Option; + + fn hide(&mut self, omit: Option); + + fn apply_wallpaper(&self, hmonitor: isize, monitor_wp: &Option) -> eyre::Result<()>; + + fn restore( + &mut self, + mouse_follows_focus: bool, + hmonitor: isize, + monitor_wp: &Option, + ) -> eyre::Result<()>; + + fn update(&mut self) -> eyre::Result<()>; + + fn hwnd_from_exe(&self, exe: &str) -> Option; + + fn promote_container(&mut self) -> eyre::Result<()>; + + fn remove_window(&mut self, window_id: isize) -> eyre::Result<()>; + + fn new_floating_window(&mut self) -> eyre::Result<()>; + + fn new_maximized_window(&mut self) -> eyre::Result<()>; + + fn reintegrate_maximized_window(&mut self) -> eyre::Result<()>; + + /// The windows that are on show, which are the ones to slide when the + /// workspace is switched + fn windows_on_show(&self) -> Vec; + + /// What kind of border each of the windows that are on show has + fn border_kinds_on_show(&self) -> Vec<(isize, WindowKind)>; + + fn visible_window_details(&self) -> Vec; } -#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -pub enum WorkspaceLayer { - #[default] - Tiling, - Floating, -} - -impl Display for WorkspaceLayer { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - match self { - WorkspaceLayer::Tiling => write!(f, "Tiling"), - WorkspaceLayer::Floating => write!(f, "Floating"), - } - } -} - -impl_ring_elements!(Workspace, Container); -impl_ring_elements!(Workspace, Window, "floating_window"); - -impl Default for Workspace { - fn default() -> Self { - Self { - name: None, - containers: Ring::default(), - monocle_container: None, - maximized_window: None, - maximized_window_restore_idx: None, - monocle_container_restore_idx: None, - floating_windows: Ring::default(), - layout: Layout::Default(DefaultLayout::BSP), - layout_options: None, - layout_rules: vec![], - layout_options_rules: vec![], - layout_defaults_cache: HashMap::new(), - work_area_offset_rules: vec![], - layout_flip: None, - workspace_padding: Option::from(DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst)), - container_padding: Option::from(DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst)), - latest_layout: vec![], - resize_dimensions: vec![], - tile: true, - work_area_offset: None, - apply_window_based_work_area_offset: true, - window_container_behaviour: None, - window_container_behaviour_rules: None, - float_override: None, - layer: Default::default(), - floating_layer_behaviour: Default::default(), - globals: Default::default(), - workspace_config: None, - wallpaper: None, - preselected_container_idx: None, - promotion_swap_container_idx: None, - initial_window_placement_rules: None, - scrolling: None, - } - } -} - -#[derive(Debug)] -pub enum WorkspaceWindowLocation { - Monocle(usize), // window_idx - Maximized, - Container(usize, usize), // container_idx, window_idx - Floating(usize), // idx in floating_windows -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -/// Cached per-layout default options (pre-sorted rules) derived from the global `layout_defaults`. -pub(crate) struct CachedLayoutDefault { - pub layout_options: Option, - /// Threshold-based rules, sorted by threshold ascending at load time - pub layout_options_rules: Vec<(usize, LayoutOptions)>, -} - -/// Convert an optional HashMap of threshold-based layout options rules into a Vec sorted by -/// threshold ascending. -fn sorted_layout_options_rules( - rules: Option<&HashMap>, -) -> Vec<(usize, LayoutOptions)> { - match rules { - Some(rules) => { - let mut sorted: Vec<(usize, LayoutOptions)> = - rules.iter().map(|(t, o)| (*t, *o)).collect(); - sorted.sort_by_key(|(t, _)| *t); - sorted - } - None => vec![], - } -} - -/// Find the highest matching threshold rule for the given container count. -/// Rules must be sorted by threshold ascending. -fn resolve_threshold_match( - rules: &[(usize, LayoutOptions)], - container_count: usize, -) -> Option { - rules - .iter() - .rev() - .find(|(threshold, _)| container_count >= *threshold) - .map(|(_, opts)| *opts) -} - -impl Workspace { - pub fn load_static_config( +impl WorkspaceExt for Workspace { + fn load_static_config( &mut self, config: &WorkspaceConfig, layout_defaults: Option<&HashMap>, @@ -356,17 +316,7 @@ impl Workspace { Ok(()) } - /// Compute effective layout options using the complete-replacement cascade: - /// - /// If the workspace defines EITHER `layout_options` OR `layout_options_rules`, - /// it completely replaces the global `layout_defaults` for this layout. - /// Global defaults are only used when the workspace has NEITHER setting. - /// - /// Within the effective source (workspace or global): - /// 1. Try threshold match from rules (highest matching threshold wins) - /// 2. If a rule matches -> use it (full replacement of base) - /// 3. Else -> use the base `layout_options` - pub(crate) fn effective_layout_options(&self) -> Option { + fn effective_layout_options(&self) -> Option { let container_count = self.containers().len(); let has_workspace_overrides = @@ -388,7 +338,7 @@ impl Workspace { resolve_threshold_match(effective_rules, container_count).or(effective_base) } - pub fn hide(&mut self, omit: Option) { + fn hide(&mut self, omit: Option) { for window in self.floating_windows_mut().iter_mut().rev() { let mut should_hide = omit.is_none(); @@ -417,11 +367,7 @@ impl Workspace { } } - pub fn apply_wallpaper( - &self, - hmonitor: isize, - monitor_wp: &Option, - ) -> eyre::Result<()> { + fn apply_wallpaper(&self, hmonitor: isize, monitor_wp: &Option) -> eyre::Result<()> { if let Some(wallpaper) = self.wallpaper.as_ref().or(monitor_wp.as_ref()) { if let Err(error) = WindowsApi::set_wallpaper(&wallpaper.path, hmonitor) { tracing::error!("failed to set wallpaper: {error}"); @@ -537,7 +483,7 @@ impl Workspace { Ok(()) } - pub fn restore( + fn restore( &mut self, mouse_follows_focus: bool, hmonitor: isize, @@ -594,7 +540,7 @@ impl Workspace { self.apply_wallpaper(hmonitor, monitor_wp) } - pub fn update(&mut self) -> eyre::Result<()> { + fn update(&mut self) -> eyre::Result<()> { if !INITIAL_CONFIGURATION_LOADED.load(Ordering::SeqCst) { return Ok(()); } @@ -875,62 +821,7 @@ impl Workspace { Ok(()) } - pub fn container_for_window(&self, window_id: PlatformWindowId) -> Option<&Container> { - self.containers() - .get(self.container_idx_for_window(window_id)?) - } - - /// If there is a container which holds the window with `window_id` it will focus that container. - /// This function will only emit a focus on the window if it isn't the focused window of that - /// container already. - pub fn focus_container_by_window(&mut self, window_id: PlatformWindowId) -> eyre::Result<()> { - let container_idx = self - .container_idx_for_window(window_id) - .ok_or_eyre("there is no container/window")?; - - let container = self - .containers_mut() - .get_mut(container_idx) - .ok_or_eyre("there is no container")?; - - let window_idx = container - .idx_for_window(window_id) - .ok_or_eyre("there is no window")?; - - let mut should_load = false; - - if container.focused_window_idx() != window_idx { - should_load = true - } - - container.focus_window(window_idx); - - if should_load { - container.load_focused_window(); - } - - self.focus_container(container_idx); - - Ok(()) - } - - pub fn container_idx_from_current_point(&self) -> Option { - let mut idx = None; - - let point = cursor_position()?; - - for (i, _container) in self.containers().iter().enumerate() { - if let Some(rect) = self.latest_layout.get(i) - && rect.contains_point(point) - { - idx = Option::from(i); - } - } - - idx - } - - pub fn hwnd_from_exe(&self, exe: &str) -> Option { + fn hwnd_from_exe(&self, exe: &str) -> Option { for container in self.containers() { if let Some(window_id) = container.hwnd_from_exe(exe) { return Option::from(window_id); @@ -961,115 +852,7 @@ impl Workspace { None } - pub fn location_from_exe(&self, exe: &str) -> Option { - for (container_idx, container) in self.containers().iter().enumerate() { - if let Some(window_idx) = container.idx_from_exe(exe) { - return Some(WorkspaceWindowLocation::Container( - container_idx, - window_idx, - )); - } - } - - if let Some(window) = self.maximized_window - && let Some(window_exe) = window.exe() - && exe == window_exe - { - return Some(WorkspaceWindowLocation::Maximized); - } - - if let Some(container) = &self.monocle_container - && let Some(window_idx) = container.idx_from_exe(exe) - { - return Some(WorkspaceWindowLocation::Monocle(window_idx)); - } - - for (window_idx, window) in self.floating_windows().iter().enumerate() { - if let Some(window_exe) = window.exe() - && exe == window_exe - { - return Some(WorkspaceWindowLocation::Floating(window_idx)); - } - } - - None - } - - pub fn contains_managed_window(&self, window_id: PlatformWindowId) -> bool { - for container in self.containers() { - if container.contains_window(window_id) { - return true; - } - } - - if let Some(window) = self.maximized_window - && window_id == window.id() - { - return true; - } - - if let Some(container) = &self.monocle_container - && container.contains_window(window_id) - { - return true; - } - - false - } - - pub fn is_focused_window_monocle_or_maximized(&self) -> eyre::Result { - let window_id = foreground_window_id().ok_or_eyre("no foreground window")?; - if let Some(window) = self.maximized_window - && window_id == window.id() - { - return Ok(true); - } - - if let Some(container) = &self.monocle_container - && container.contains_window(window_id) - { - return Ok(true); - } - - Ok(false) - } - - pub fn is_empty(&self) -> bool { - self.containers().is_empty() - && self.maximized_window.is_none() - && self.monocle_container.is_none() - && self.floating_windows().is_empty() - } - - pub fn contains_window(&self, window_id: PlatformWindowId) -> bool { - for container in self.containers() { - if container.contains_window(window_id) { - return true; - } - } - - if let Some(window) = self.maximized_window - && window_id == window.id() - { - return true; - } - - if let Some(container) = &self.monocle_container - && container.contains_window(window_id) - { - return true; - } - - for window in self.floating_windows() { - if window_id == window.id() { - return true; - } - } - - false - } - - pub fn promote_container(&mut self) -> eyre::Result<()> { + fn promote_container(&mut self) -> eyre::Result<()> { let focused_idx = self.focused_container_idx(); let container = self .containers_mut() @@ -1093,61 +876,7 @@ impl Workspace { Ok(()) } - pub fn add_container_to_back(&mut self, container: Container) { - self.containers_mut().push_back(container); - self.focus_last_container(); - } - - pub fn add_container_to_front(&mut self, container: Container) { - self.containers_mut().push_front(container); - self.focus_first_container(); - } - - // this fn respects locked container indexes - we should use it for pretty much everything - // except monocle and maximize toggles - pub fn insert_container_at_idx(&mut self, idx: usize, container: Container) -> usize { - let insertion_idx = self - .containers_mut() - .insert_respecting_locks(idx, container); - - if insertion_idx > self.resize_dimensions.len() { - self.resize_dimensions.push(None); - } else { - self.resize_dimensions.insert(insertion_idx, None); - } - - self.focus_container(insertion_idx); - - insertion_idx - } - - // this fn respects locked container indexes - we should use it for pretty much everything - // except monocle and maximize toggles - pub fn remove_container_by_idx(&mut self, idx: usize) -> Option { - // wherever it goes next, it goes as wide as it was - self.note_scrolling_departure(idx); - - let container = self.containers_mut().remove_respecting_locks(idx); - - if idx < self.resize_dimensions.len() { - self.resize_dimensions.remove(idx); - } - - container - } - - pub fn container_idx_for_window(&self, window_id: PlatformWindowId) -> Option { - let mut idx = None; - for (i, x) in self.containers().iter().enumerate() { - if x.contains_window(window_id) { - idx = Option::from(i); - } - } - - idx - } - - pub fn remove_window(&mut self, window_id: isize) -> eyre::Result<()> { + fn remove_window(&mut self, window_id: isize) -> eyre::Result<()> { border_manager::delete_border(window_id); if self.floating_windows().iter().any(|w| w.hwnd == window_id) { @@ -1222,270 +951,7 @@ impl Workspace { Ok(()) } - pub fn remove_focused_container(&mut self) -> Option { - let focused_idx = self.focused_container_idx(); - let container = self.remove_container_by_idx(focused_idx); - self.focus_previous_container(); - - container - } - - pub fn remove_container(&mut self, idx: usize) -> Option { - let container = self.remove_container_by_idx(idx); - self.focus_previous_container(); - - container - } - - pub fn preselect_container_idx(&mut self, insertion_idx: usize) { - self.preselected_container_idx = Some(insertion_idx); - self.insert_container_at_idx(insertion_idx, Container::preselect()); - } - - pub fn cancel_preselect(&mut self) { - if let Some(idx) = self.preselected_container_idx { - self.containers_mut().remove_respecting_locks(idx); - self.preselected_container_idx = None; - } - } - - pub fn new_idx_for_direction(&self, direction: OperationDirection) -> Option { - // in a strip, left and right are the neighbouring columns and up and down are the tiles of - // the column, which the strip is the one to say - if self.is_scrolling() && self.scrolling.is_some() { - return self.scrolling_idx_for_direction(direction); - } - - let len = NonZeroUsize::new(self.containers().len())?; - - direction.destination( - self.layout.as_boxed_direction().as_ref(), - self.layout_flip, - self.focused_container_idx(), - len, - self.layout_options, - ) - } - - pub fn new_idx_for_cycle_direction(&self, direction: CycleDirection) -> Option { - Option::from(direction.next_idx( - self.focused_container_idx(), - NonZeroUsize::new(self.containers().len())?, - )) - } - - // this is what we use for stacking - pub fn move_window_to_container(&mut self, target_container_idx: usize) -> eyre::Result<()> { - 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")?; - - // This is a little messy - let adjusted_target_container_index = if container.windows().is_empty() { - self.remove_container_by_idx(focused_idx); - - if focused_idx < target_container_idx { - target_container_idx.saturating_sub(1) - } else { - target_container_idx - } - } else { - container.load_focused_window(); - target_container_idx - }; - - let target_container = self - .containers_mut() - .get_mut(adjusted_target_container_index) - .ok_or_eyre("there is no container")?; - - target_container.add_window(window); - - self.focus_container(adjusted_target_container_index); - self.focused_container_mut() - .ok_or_eyre("there is no container")? - .load_focused_window(); - - Ok(()) - } - - pub fn new_container_for_focused_window(&mut self) -> eyre::Result<()> { - let focused_container_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_container_idx); - } else { - container.load_focused_window(); - } - - self.new_container_for_window(window); - - let mut container = Container::default(); - container.add_window(window); - Ok(()) - } - - 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 new_container_for_window(&mut self, window: Window) { - let next_idx = if let Some(idx) = self.preselected_container_idx { - let next = idx; - self.preselected_container_idx = None; - self.remove_container_by_idx(next); - next - } else if self.containers().is_empty() { - 0 - } else if let Some(idx) = self.scrolling_insertion_idx() { - idx - } else { - self.resolve_placement_index(&window) - }; - - let mut container = Container::default(); - container.add_window(window); - - self.insert_container_at_idx(next_idx, container); - } - - /// Resolves the container index at which a new window should be placed, - /// based on the `initial_window_placement_rules` configuration. - /// - /// Falls back to the default placement (currently `AfterFocused`, - /// i.e. `focused_container_idx() + 1`) when: - /// - No rules are configured - /// - A `Rules` map has no matching rule for the window - /// - A resolved index is out of bounds - fn resolve_placement_index(&self, window: &Window) -> usize { - let fallback_idx = self.focused_container_idx() + 1; - - let Some(rules) = &self.initial_window_placement_rules else { - return fallback_idx; - }; - - match rules { - InitialWindowPlacementRules::Target(target) => { - self.resolve_placement_target(target, fallback_idx) - } - InitialWindowPlacementRules::Rules(rules_map) => { - let (Some(title), Some(exe_name), Some(class), Some(path)) = - (window.title(), window.exe(), window.class(), window.path()) - else { - return fallback_idx; - }; - - let regex_identifiers = REGEX_IDENTIFIERS.lock().clone(); - - // BTreeMap iterates in key order - for (target, placement_rules) in rules_map { - let matched = match placement_rules { - PlacementMatchingRules::Single(id) => should_act_window_individual( - &title, - &exe_name, - &class, - &path, - id, - ®ex_identifiers, - ), - PlacementMatchingRules::Many(rules) => { - // OR logic: any matching rule triggers placement at this target. - // Each MatchingRule handles its own Simple/Composite (AND) logic - // internally via should_act. - should_act_window( - &title, - &exe_name, - &class, - &path, - rules, - ®ex_identifiers, - ) - .is_some() - } - }; - - if matched { - return self.resolve_placement_target(target, fallback_idx); - } - } - - // No matching rule found - fallback_idx - } - } - } - - /// Resolves a `WindowPlacement` variant to a concrete container index. - fn resolve_window_placement(&self, placement: &WindowPlacement, fallback_idx: usize) -> usize { - match placement { - WindowPlacement::AfterFocused => self.focused_container_idx() + 1, - WindowPlacement::BeforeFocused => self.focused_container_idx(), - WindowPlacement::Primary => { - let idx = self.layout.primary_index(); - if idx <= self.containers().len() { - idx - } else { - fallback_idx - } - } - WindowPlacement::Secondary => { - if let Some(idx) = self.layout.secondary_index(self.containers().len()) { - if idx <= self.containers().len() { - idx - } else { - fallback_idx - } - } else { - fallback_idx - } - } - WindowPlacement::Last => self.containers().len(), - } - } - - /// Resolves a `PlacementTarget` (either a named placement or a 1-based index) to a concrete container index. - fn resolve_placement_target(&self, target: &PlacementTarget, fallback_idx: usize) -> usize { - match target { - PlacementTarget::Placement(placement) => { - self.resolve_window_placement(placement, fallback_idx) - } - PlacementTarget::Index(idx) => { - // Config indices are 1-based; convert to 0-based - let zero_based = idx.saturating_sub(1); - if zero_based <= self.containers().len() { - zero_based - } else { - fallback_idx - } - } - } - } - - pub fn new_floating_window(&mut self) -> eyre::Result<()> { + fn new_floating_window(&mut self) -> eyre::Result<()> { let window = if let Some(maximized_window) = self.maximized_window { let window = maximized_window; self.maximized_window = None; @@ -1533,335 +999,7 @@ impl Workspace { Ok(()) } - fn enforce_resize_constraints(&mut self) { - match self.layout { - Layout::Default(DefaultLayout::BSP) => self.enforce_resize_constraints_for_bsp(), - Layout::Default(DefaultLayout::Columns) => self.enforce_resize_for_columns(), - Layout::Default(DefaultLayout::Rows) => self.enforce_resize_for_rows(), - Layout::Default(DefaultLayout::VerticalStack) => { - self.enforce_resize_for_vertical_stack(); - } - Layout::Default(DefaultLayout::RightMainVerticalStack) => { - self.enforce_resize_for_right_vertical_stack(); - } - Layout::Default(DefaultLayout::HorizontalStack) => { - self.enforce_resize_for_horizontal_stack(); - } - Layout::Default(DefaultLayout::UltrawideVerticalStack) => { - self.enforce_resize_for_ultrawide(); - } - _ => self.enforce_no_resize(), - } - } - - fn enforce_resize_constraints_for_bsp(&mut self) { - for (i, rect) in self.resize_dimensions.iter_mut().enumerate() { - if let Some(rect) = rect { - // Even containers can't be resized to the bottom - if i % 2 == 0 { - rect.bottom = 0; - // Odd containers can't be resized to the right - } else { - rect.right = 0; - } - } - } - - // The first container can never be resized to the left or the top - if let Some(Some(first)) = self.resize_dimensions.first_mut() { - first.top = 0; - first.left = 0; - } - - // The last container can never be resized to the bottom or the right - if let Some(Some(last)) = self.resize_dimensions.last_mut() { - last.bottom = 0; - last.right = 0; - } - } - - fn enforce_resize_for_columns(&mut self) { - let resize_dimensions = &mut self.resize_dimensions; - match resize_dimensions.len() { - 0 | 1 => self.enforce_no_resize(), - _ => { - let len = resize_dimensions.len(); - for (i, rect) in resize_dimensions.iter_mut().enumerate() { - if let Some(rect) = rect { - rect.top = 0; - rect.bottom = 0; - - if i == 0 { - rect.left = 0; - } - if i == len - 1 { - rect.right = 0; - } - } - } - } - } - } - - fn enforce_resize_for_rows(&mut self) { - let resize_dimensions = &mut self.resize_dimensions; - match resize_dimensions.len() { - 0 | 1 => self.enforce_no_resize(), - _ => { - let len = resize_dimensions.len(); - for (i, rect) in resize_dimensions.iter_mut().enumerate() { - if let Some(rect) = rect { - rect.left = 0; - rect.right = 0; - - if i == 0 { - rect.top = 0; - } - if i == len - 1 { - rect.bottom = 0; - } - } - } - } - } - } - - fn enforce_resize_for_vertical_stack(&mut self) { - let resize_dimensions = &mut self.resize_dimensions; - match resize_dimensions.len() { - // Single window can not be resized at all - 0 | 1 => self.enforce_no_resize(), - _ => { - // Zero is actually on the left - if let Some(left) = resize_dimensions[0].as_mut() { - left.top = 0; - left.bottom = 0; - left.left = 0; - } - - // Handle stack on the right - let stack_size = resize_dimensions[1..].len(); - for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { - if let Some(rect) = rect { - // No containers can resize to the right - rect.right = 0; - - // First container in stack cant resize up - if i == 0 { - rect.top = 0; - } else if i == stack_size - 1 { - // Last cant be resized to the bottom - rect.bottom = 0; - } - } - } - } - } - } - - fn enforce_resize_for_right_vertical_stack(&mut self) { - let resize_dimensions = &mut self.resize_dimensions; - match resize_dimensions.len() { - // Single window can not be resized at all - 0 | 1 => self.enforce_no_resize(), - _ => { - // Zero is actually on the right - if let Some(left) = resize_dimensions[1].as_mut() { - left.top = 0; - left.bottom = 0; - left.right = 0; - } - - // Handle stack on the right - let stack_size = resize_dimensions[1..].len(); - for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { - if let Some(rect) = rect { - // No containers can resize to the left - rect.left = 0; - - // First container in stack cant resize up - if i == 0 { - rect.top = 0; - } else if i == stack_size - 1 { - // Last cant be resized to the bottom - rect.bottom = 0; - } - } - } - } - } - } - - fn enforce_resize_for_horizontal_stack(&mut self) { - let resize_dimensions = &mut self.resize_dimensions; - match resize_dimensions.len() { - 0 | 1 => self.enforce_no_resize(), - _ => { - if let Some(left) = resize_dimensions[0].as_mut() { - left.top = 0; - left.left = 0; - left.right = 0; - } - - let stack_size = resize_dimensions[1..].len(); - for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { - if let Some(rect) = rect { - rect.bottom = 0; - - if i == 0 { - rect.left = 0; - } - if i == stack_size - 1 { - rect.right = 0; - } - } - } - } - } - } - - fn enforce_resize_for_ultrawide(&mut self) { - let resize_dimensions = &mut self.resize_dimensions; - match resize_dimensions.len() { - // Single window can not be resized at all - 0 | 1 => self.enforce_no_resize(), - // Two windows can only be resized in the middle - 2 => { - // Zero is actually on the right - if let Some(right) = resize_dimensions[0].as_mut() { - right.top = 0; - right.bottom = 0; - right.right = 0; - } - - // One is on the left - if let Some(left) = resize_dimensions[1].as_mut() { - left.top = 0; - left.bottom = 0; - left.left = 0; - } - } - // Three or more windows means 0 is in center, 1 is at the left, 2.. are a vertical - // stack on the right - _ => { - // Central can be resized left or right - if let Some(right) = resize_dimensions[0].as_mut() { - right.top = 0; - right.bottom = 0; - } - - // Left one can only be resized to the right - if let Some(left) = resize_dimensions[1].as_mut() { - left.top = 0; - left.bottom = 0; - left.left = 0; - } - - // Handle stack on the right - let stack_size = resize_dimensions[2..].len(); - for (i, rect) in resize_dimensions[2..].iter_mut().enumerate() { - if let Some(rect) = rect { - // No containers can resize to the right - rect.right = 0; - - // First container in stack cant resize up - if i == 0 { - rect.top = 0; - } else if i == stack_size - 1 { - // Last cant be resized to the bottom - rect.bottom = 0; - } - } - } - } - } - } - - fn enforce_no_resize(&mut self) { - for rect in self.resize_dimensions.iter_mut().flatten() { - rect.left = 0; - rect.right = 0; - rect.top = 0; - rect.bottom = 0; - } - } - - pub fn new_monocle_container(&mut self) -> eyre::Result<()> { - let focused_idx = self.focused_container_idx(); - - // we shouldn't use remove_container_by_idx here because it doesn't make sense for - // monocle and maximized toggles which take over the whole screen before being reinserted - // at the same index to respect locked container indexes - let container = self - .containers_mut() - .remove(focused_idx) - .ok_or_eyre("there is no container")?; - - // We don't remove any resize adjustments for a monocle, because when this container is - // inevitably reintegrated, it would be weird if it doesn't go back to the dimensions - // it had before - - self.monocle_container = Option::from(container); - self.monocle_container_restore_idx = Option::from(focused_idx); - self.focus_previous_container(); - - self.monocle_container - .as_mut() - .ok_or_eyre("there is no monocle container")? - .load_focused_window(); - - Ok(()) - } - - pub fn reintegrate_monocle_container(&mut self) -> eyre::Result<()> { - let restore_idx = self - .monocle_container_restore_idx - .ok_or_eyre("there is no monocle restore index")?; - - let container = self - .monocle_container - .as_ref() - .ok_or_eyre("there is no monocle container")?; - - let container = container.clone(); - if restore_idx >= self.containers().len() { - self.containers_mut() - .resize(restore_idx, Container::default()); - } - - // we shouldn't use insert_container_at_index here because it doesn't make sense for - // monocle and maximized toggles which take over the whole screen before being reinserted - // at the same index to respect locked container indexes - self.containers_mut().insert(restore_idx, container); - self.focus_container(restore_idx); - self.focused_container_mut() - .ok_or_eyre("there is no container")? - .load_focused_window(); - - self.monocle_container = None; - self.monocle_container_restore_idx = None; - - Ok(()) - } - - pub fn cycle_monocle_container(&mut self, direction: CycleDirection) -> eyre::Result<()> { - if self.containers().is_empty() { - return Ok(()); - } - - self.reintegrate_monocle_container()?; - - let new_idx = self - .new_idx_for_cycle_direction(direction) - .ok_or_eyre("there is no container to cycle monocle to")?; - - self.focus_container(new_idx); - self.new_monocle_container()?; - - Ok(()) - } - - pub fn new_maximized_window(&mut self) -> eyre::Result<()> { + fn new_maximized_window(&mut self) -> eyre::Result<()> { let focused_idx = self.focused_container_idx(); if matches!(self.layer, WorkspaceLayer::Floating) { @@ -1930,7 +1068,7 @@ impl Workspace { Ok(()) } - pub fn reintegrate_maximized_window(&mut self) -> eyre::Result<()> { + fn reintegrate_maximized_window(&mut self) -> eyre::Result<()> { let restore_idx = self .maximized_window_restore_idx .ok_or_eyre("there is no maximized restore index")?; @@ -1964,66 +1102,7 @@ impl Workspace { Ok(()) } - #[tracing::instrument(skip(self))] - pub fn focus_container(&mut self, idx: usize) { - tracing::info!("focusing container"); - - self.containers.focus(idx); - } - - pub fn swap_containers(&mut self, i: usize, j: usize) { - self.containers.elements_mut().swap_respecting_locks(i, j); - self.focus_container(j); - } - - pub fn remove_focused_floating_window(&mut self) -> Option { - let window_id = foreground_window_id()?; - self.remove_floating_window(window_id) - } - - pub fn remove_floating_window(&mut self, window_id: PlatformWindowId) -> 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.floating_windows_mut().remove(idx) - } else { - None - } - } - } - } - - pub fn visible_windows(&self) -> Vec> { - let mut vec = vec![]; - - vec.push(self.maximized_window.as_ref()); - - if let Some(monocle) = &self.monocle_container { - vec.push(monocle.focused_window()); - } - - for container in self.containers() { - vec.push(container.focused_window()); - } - - for window in self.floating_windows() { - vec.push(Some(window)); - } - - vec - } - - /// The windows that are on show, which are the ones to slide when the - /// workspace is switched - pub fn windows_on_show(&self) -> Vec { + fn windows_on_show(&self) -> Vec { if let Some(monocle) = &self.monocle_container { return monocle.focused_window().copied().into_iter().collect(); } @@ -2035,8 +1114,7 @@ impl Workspace { .collect() } - /// What kind of border each of the windows that are on show has - pub fn border_kinds_on_show(&self) -> Vec<(isize, WindowKind)> { + fn border_kinds_on_show(&self) -> Vec<(isize, WindowKind)> { if let Some(monocle) = &self.monocle_container { return monocle .focused_window() @@ -2075,7 +1153,7 @@ impl Workspace { kinds } - pub fn visible_window_details(&self) -> Vec { + fn visible_window_details(&self) -> Vec { let mut vec: Vec = vec![]; if let Some(maximized) = self.maximized_window { @@ -2102,19 +1180,6 @@ impl Workspace { vec } - - pub fn focus_previous_container(&mut self) { - let focused_idx = self.focused_container_idx(); - self.focus_container(focused_idx.saturating_sub(1)); - } - - fn focus_last_container(&mut self) { - self.focus_container(self.containers().len().saturating_sub(1)); - } - - fn focus_first_container(&mut self) { - self.focus_container(0); - } } #[cfg(test)]