From 8f37b9aea6b54c84dbe97454cc252dad6d0999fb Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:00:18 -0700 Subject: [PATCH 01/33] fix(windows): take the rule-list locks in one documented order window_is_eligible (window.rs) took regex, ignore, manage, floating, then layered, no-titlebar and slow; apply_globals (static_config.rs) took ignore, regex, manage and the rest in yet another order: a rule check and a config load could wait for each other for ever (the KDE tree hit this, see ef1d3ef0 there). One order is now documented at the statics in lib.rs: floating, session floating, transparency, ignore, manage, layered, tray, object-name-change (two), slow, no-titlebar, workspace rules, regex (a leaf: every rule check takes its list and then the regexes). window_is_eligible takes the lists it reads up front in that order and, once it has matched them all, drops every guard BEFORE the slow-application sleep (before this, the sleep ran with the regex, ignore, manage, floating, layered and no-titlebar guards held, so a config load or rule command waited out the compensation time); apply_globals is reordered. Every other site that nests two of these (state.rs, process_command.rs session float rules, process_event.rs, window_manager_event.rs, transparency_manager.rs, window_manager.rs, workspace.rs) already followed the order. BEHAVIOUR: lock acquisition order and hold time only; no rule semantics change. Gate needed: Windows e2e commands and config_reload. Verified: not yet re-run after the guard-drop change. --- komorebi/src/lib.rs | 17 ++++++++++++ komorebi/src/static_config.rs | 9 +++--- komorebi/src/window.rs | 52 +++++++++++++++++++++-------------- 3 files changed, 53 insertions(+), 25 deletions(-) diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 9b4d0865..ba20ddfe 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -86,6 +86,23 @@ use which::which; use winreg::RegKey; use winreg::enums::HKEY_CURRENT_USER; +// LOCK ORDER of the rule lists. A thread that holds one of these and takes another must take them +// in this order (a thread that takes two in another order can wait for one that holds what it +// needs, and both wait for ever): +// +// FLOATING_APPLICATIONS, SESSION_FLOATING_APPLICATIONS, TRANSPARENCY_BLACKLIST, +// IGNORE_IDENTIFIERS, MANAGE_IDENTIFIERS, LAYERED_WHITELIST, TRAY_AND_MULTI_WINDOW_IDENTIFIERS, +// OBJECT_NAME_CHANGE_ON_LAUNCH, OBJECT_NAME_CHANGE_TITLE_IGNORE_LIST, +// SLOW_APPLICATION_IDENTIFIERS, NO_TITLEBAR, WORKSPACE_MATCHING_RULES, REGEX_IDENTIFIERS +// +// REGEX_IDENTIFIERS is last: every rule check holds the list it matches against and then the +// compiled regexes. PERMAIGNORE_CLASSES and WSL2_UI_PROCESSES are leaves (nothing is taken while +// they are held). Places that nest the others: window.rs (window_is_eligible), static_config.rs +// (apply_globals), +// state.rs (the State snapshot), process_command.rs (session float rules), process_event.rs, +// window_manager_event.rs, transparency_manager.rs, window_manager.rs. The same rule applies to +// any new place: lock in this order, or lock one at a time. + lazy_static! { static ref HIDDEN_HWNDS: Arc>> = Arc::new(Mutex::new(vec![])); static ref LAYERED_WHITELIST: Arc>> = Arc::new(Mutex::new(vec![ diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index c84b98e9..a9f3beea 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -559,17 +559,18 @@ impl ApplyGlobals for StaticConfig { transparency_manager::TRANSPARENCY_ALPHA.store(transparency_alpha, Ordering::SeqCst); } + // the order documented at the statics in lib.rs + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + let mut transparency_blacklist = TRANSPARENCY_BLACKLIST.lock(); let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); - let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); let mut manage_identifiers = MANAGE_IDENTIFIERS.lock(); + let mut layered_identifiers = LAYERED_WHITELIST.lock(); let mut tray_and_multi_window_identifiers = TRAY_AND_MULTI_WINDOW_IDENTIFIERS.lock(); let mut object_name_change_identifiers = OBJECT_NAME_CHANGE_ON_LAUNCH.lock(); let mut object_name_change_title_ignore_list = OBJECT_NAME_CHANGE_TITLE_IGNORE_LIST.lock(); - let mut layered_identifiers = LAYERED_WHITELIST.lock(); - let mut transparency_blacklist = TRANSPARENCY_BLACKLIST.lock(); let mut slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); - let mut floating_applications = FLOATING_APPLICATIONS.lock(); let mut no_titlebar_applications = NO_TITLEBAR.lock(); + let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); if let Some(rules) = &mut self.ignore_rules { populate_rules(rules, &mut ignore_identifiers, &mut regex_identifiers)?; diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 321b599c..e864086e 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -886,9 +886,16 @@ fn window_is_eligible( } } + // Every place that holds two of the rule lists takes them in the order documented at the + // statics in lib.rs, so all the lists this check reads are taken up front, in that order. + let floating_identifiers = FLOATING_APPLICATIONS.lock(); + let ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + let manage_identifiers = MANAGE_IDENTIFIERS.lock(); + let layered_whitelist = LAYERED_WHITELIST.lock(); + let slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); + let titlebars_removed = NO_TITLEBAR.lock(); let regex_identifiers = REGEX_IDENTIFIERS.lock(); - let ignore_identifiers = IGNORE_IDENTIFIERS.lock(); let should_ignore = if let Some(rule) = should_act( title, exe_name, @@ -903,7 +910,6 @@ fn window_is_eligible( false }; - let manage_identifiers = MANAGE_IDENTIFIERS.lock(); let managed_override = if let Some(rule) = should_act( title, exe_name, @@ -918,7 +924,6 @@ fn window_is_eligible( false }; - let floating_identifiers = FLOATING_APPLICATIONS.lock(); if let Some(rule) = should_act( title, exe_name, @@ -934,7 +939,6 @@ fn window_is_eligible( return false; } - let layered_whitelist = LAYERED_WHITELIST.lock(); let mut allow_layered = if let Some(rule) = should_act( title, exe_name, @@ -972,7 +976,6 @@ fn window_is_eligible( allow }; - let titlebars_removed = NO_TITLEBAR.lock(); let allow_titlebar_removed = if let Some(rule) = should_act( title, exe_name, @@ -987,23 +990,30 @@ fn window_is_eligible( false }; - { - let slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); - let should_sleep = should_act( - title, - exe_name, - class, - path, - &slow_application_identifiers, - ®ex_identifiers, - ) - .is_some(); + let should_sleep = should_act( + title, + exe_name, + class, + path, + &slow_application_identifiers, + ®ex_identifiers, + ) + .is_some(); - if should_sleep { - std::thread::sleep(Duration::from_millis( - SLOW_APPLICATION_COMPENSATION_TIME.load(Ordering::SeqCst), - )); - } + // Nothing below reads a rule list: release them all before sleeping, so a config load or a + // rule command is never kept waiting for the slow-application compensation time. + drop(floating_identifiers); + drop(ignore_identifiers); + drop(manage_identifiers); + drop(layered_whitelist); + drop(slow_application_identifiers); + drop(titlebars_removed); + drop(regex_identifiers); + + if should_sleep { + std::thread::sleep(Duration::from_millis( + SLOW_APPLICATION_COMPENSATION_TIME.load(Ordering::SeqCst), + )); } if (allow_wsl2_gui || allow_titlebar_removed || style.contains(WindowStyle::CAPTION) && ex_style.contains(ExtendedWindowStyle::WINDOWEDGE)) From 69073153d964a57194455539c357606899b741cc Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 09:54:46 -0700 Subject: [PATCH 02/33] refactor(windows): give Window the shared operation names Window already had focus, raise, hide, restore, minimize and close under the names of the shared Backend trait (docs/dev/seam.md section 2). Add the four that were missing as thin delegates: set_rect (set_position with top = false), alive (is_window), window_rect (WindowsApi::window_rect) and unminimize (WindowsApi::restore_window). No call site changes; the unused-by-the-daemon WindowsBackend now calls the new names. Not a behaviour change. Verified: Windows clippy -D warnings via tools/fast-check PASS. --- komorebi/src/window.rs | 25 +++++++++++++++++++++++++ komorebi/src/windows_backend.rs | 8 ++++---- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index e864086e..576067a0 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -725,6 +725,31 @@ impl Window { WindowsApi::is_window(self.hwnd) } + // The operation names of the shared `komorebi_backend::Backend` (docs/dev/seam.md, section 2). + // `set_rect`, `alive`, `window_rect` and `unminimize` only delegate; `focus`, `raise`, `hide`, + // `restore`, `minimize` and `close` above already carry the shared name. + + /// Set frame: `set_position` without raising the window to the front. + pub fn set_rect(self, rect: &Rect) -> eyre::Result<()> { + self.set_position(rect, false) + } + + /// Alive check: Windows still has the window (`IsWindow`). + pub fn alive(self) -> bool { + self.is_window() + } + + /// Frame query: the visible bounds (without the shadow), see `WindowsApi::window_rect`. + pub fn window_rect(self) -> eyre::Result { + WindowsApi::window_rect(self.hwnd) + } + + /// Windows has no unminimize of its own: `SW_SHOWNOACTIVATE`, as `restore` ends in for the + /// `Hide` and `Minimize` hiding behaviours, without the `HIDDEN_HWNDS` and border bookkeeping. + pub fn unminimize(self) { + WindowsApi::restore_window(self.hwnd); + } + pub fn remove_title_bar(self) -> eyre::Result<()> { let mut style = self.style()?; style.remove(WindowStyle::CAPTION); diff --git a/komorebi/src/windows_backend.rs b/komorebi/src/windows_backend.rs index 7df5c753..b8d4b3b0 100644 --- a/komorebi/src/windows_backend.rs +++ b/komorebi/src/windows_backend.rs @@ -54,7 +54,7 @@ fn platform(report: eyre::Report) -> Error { impl WindowsBackend { fn info(window: Window) -> Option { let hwnd = window.hwnd; - if !WindowsApi::is_window(hwnd) { + if !window.alive() { return None; } @@ -63,7 +63,7 @@ impl WindowsBackend { pid: i32::try_from(window.process_id()).unwrap_or_default(), // Windows reports the visible bounds (without the shadow); an error leaves the // default, which a caller cannot tell from a window at the origin: see seam.md 9 - rect: WindowsApi::window_rect(hwnd).unwrap_or_default(), + rect: window.window_rect().unwrap_or_default(), minimized: window.is_miminized(), alive: true, title: window.title().ok(), @@ -136,7 +136,7 @@ impl Backend for WindowsBackend { // contract does not have: it is false here and a caller raises with `raise`. // `Window::set_position` also keeps its animation, slide-in and live-resize guards // and skips the write when the frame is already right: see seam.md 9. - window.set_position(rect, false).map_err(|e| failed(id, e)) + window.set_rect(rect).map_err(|e| failed(id, e)) } fn focus(&self, id: WindowId, mouse_follows_focus: bool) -> Result<()> { @@ -172,7 +172,7 @@ impl Backend for WindowsBackend { // for the `Hide` and `Minimize` hiding behaviours, and without the HIDDEN_HWNDS and // border bookkeeping of `Window::restore` live(id)?; - WindowsApi::restore_window(id.to_hwnd()); + Window::from(id.to_hwnd()).unminimize(); Ok(()) } From 0a2562b9cf044013b76fa3db69b6e09621c09b0d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:14:39 -0700 Subject: [PATCH 03/33] feat(backend): frame(id) is a cheap live frame query with the reason for a failure Windows call sites read the frame about 60 times and rely on the Win32 error (or unwrap_or_default). The shared window_rect is built on window(id), which also asks title, class, exe and path and gives None for every failure. Add the provided method Backend::frame(id) -> Result: WindowGone for an unknown window, Platform for a failed read. The default goes through window() (a table lookup on KDE through Shared and on the fake, so the cached/requested-rect semantics of seam.md section 2 row 2 are kept); WindowsBackend overrides it with Window::window_rect (one DWM call) and MacosBackend with MacosApi::window_rect (the two Accessibility reads, no metadata). The contract tests check frame agrees with window().rect and is WindowGone for an unknown id; FakeBackend gets a test. A provided method, so no adapter had to change to compile. Not a behaviour change (nothing calls it yet). Verified: tools/fast-check (native crate tests pass, Windows clippy -D warnings, KDE check + lib tests, macOS fake-CC type-check) PASS; macOS cannot be run here. --- crates/komorebi-backend/src/backend.rs | 16 ++++++++++++++++ crates/komorebi-backend/src/contract.rs | 6 ++++++ crates/komorebi-backend/src/fake.rs | 11 +++++++++++ komorebi-for-mac/komorebi/src/macos_backend.rs | 9 +++++++++ komorebi/src/windows_backend.rs | 9 +++++++++ 5 files changed, 51 insertions(+) diff --git a/crates/komorebi-backend/src/backend.rs b/crates/komorebi-backend/src/backend.rs index 83e7ce74..a9df374a 100644 --- a/crates/komorebi-backend/src/backend.rs +++ b/crates/komorebi-backend/src/backend.rs @@ -325,6 +325,22 @@ pub trait Backend: Send + Sync + 'static { self.window(id).map(|w| w.rect) } + /// Returns the window's frame, or why there is none: [`Error::WindowGone`] when the backend + /// does not know the window, [`Error::Platform`] when the platform could not say. A **cheap + /// live frame query**: unlike [`Backend::window`] it never asks for the title, class, + /// executable or path, and unlike [`Backend::window_rect`] it keeps the reason for a failure. + /// + /// The frame is the same value as the `rect` of [`Backend::window`]: Windows the visible + /// bounds (`DWMWA_EXTENDED_FRAME_BOUNDS`, fallback `GetWindowRect`), macOS the Accessibility + /// position and size (two round trips), KDE the daemon's table (the requested rect until an + /// event corrects it, see "Reads after writes"). + /// + /// The default goes through [`Backend::window`], which is a table lookup on KDE and the fake; + /// Windows and macOS override it. + fn frame(&self, id: WindowId) -> Result { + self.window(id).map(|w| w.rect).ok_or(Error::WindowGone(id)) + } + /// Returns the id of the monitor whose bounds contain the point. A point outside every /// monitor gives `None` on KDE and macOS, and the **nearest** monitor on Windows /// (`MONITOR_DEFAULTTONEAREST`), so callers must not use `None` to detect "off screen". diff --git a/crates/komorebi-backend/src/contract.rs b/crates/komorebi-backend/src/contract.rs index 5c9b3441..d7bb47b0 100644 --- a/crates/komorebi-backend/src/contract.rs +++ b/crates/komorebi-backend/src/contract.rs @@ -208,6 +208,7 @@ fn window_agrees_with_windows() { assert!(info.alive); assert!(h.backend().is_window(id)); assert_eq!(h.backend().window_rect(id), Some(info.rect)); + assert_eq!(h.backend().frame(id).ok(), Some(info.rect)); assert!(h.backend().windows().iter().any(|w| w.id == id)); } @@ -219,6 +220,11 @@ fn an_unknown_window_is_not_a_window() { assert!(h.backend().window(unknown).is_none()); assert!(!h.backend().is_window(unknown)); assert!(h.backend().window_rect(unknown).is_none()); + assert!( + h.backend() + .frame(unknown) + .is_err_and(|e| e.is_window_gone()) + ); } fn commands_on_an_unknown_window() { diff --git a/crates/komorebi-backend/src/fake.rs b/crates/komorebi-backend/src/fake.rs index 9d9821b6..67c9a829 100644 --- a/crates/komorebi-backend/src/fake.rs +++ b/crates/komorebi-backend/src/fake.rs @@ -1056,6 +1056,17 @@ mod tests { Ok(()) } + #[test] + fn frame_is_the_requested_rect_and_an_unknown_window_is_gone() -> Result<()> { + let fake = fake_with(&[1]); + + fake.set_rect(ONE, &tile(10, 500))?; + + assert_eq!(fake.frame(ONE)?, tile(10, 500)); + assert!(fake.frame(WindowId(99)).is_err_and(|e| e.is_window_gone())); + Ok(()) + } + #[test] fn a_window_keeps_to_its_minimum_size() -> Result<()> { let fake = fake_with(&[1]); diff --git a/komorebi-for-mac/komorebi/src/macos_backend.rs b/komorebi-for-mac/komorebi/src/macos_backend.rs index 2a3bca30..6e9fc14d 100644 --- a/komorebi-for-mac/komorebi/src/macos_backend.rs +++ b/komorebi-for-mac/komorebi/src/macos_backend.rs @@ -187,6 +187,15 @@ impl Backend for MacosBackend { Ok(monitors) } + fn frame(&self, id: WindowId) -> Result { + // the Accessibility position and size only, without the title, executable and path + // lookups of `window` + let window = self.lookup(id)?; + MacosApi::window_rect(&window.element) + .map(Rect::from) + .map_err(|e| Self::failed(id, &window, e)) + } + fn cursor_pos(&self) -> Option<(i32, i32)> { let point = MacosApi::cursor_pos(); #[allow(clippy::cast_possible_truncation)] diff --git a/komorebi/src/windows_backend.rs b/komorebi/src/windows_backend.rs index b8d4b3b0..43ab5b82 100644 --- a/komorebi/src/windows_backend.rs +++ b/komorebi/src/windows_backend.rs @@ -126,6 +126,15 @@ impl Backend for WindowsBackend { Ok(monitors) } + fn frame(&self, id: WindowId) -> Result { + // one `DwmGetWindowAttribute` (fallback `GetWindowRect`), no title, class or exe lookups, + // and no `IsWindow` first: the Win32 error is the answer, as for every `window_rect` + // caller; `failed` says whether the window died + Window::from(id.to_hwnd()) + .window_rect() + .map_err(|e| failed(id, e)) + } + fn cursor_pos(&self) -> Option<(i32, i32)> { WindowsApi::cursor_pos().ok().map(|p| (p.x, p.y)) } From 07f931d6cb1ae34c4fca50390d9d6eb71656e4ce Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:01:11 -0700 Subject: [PATCH 04/33] feat(windows): backend() accessor for the daemon A static WindowsBackend behind backend() -> &'static dyn Backend, the way KDE spells it. Nothing calls it yet; the next revisions switch call sites one cluster at a time (docs/dev/backend-switch.md). Not a behaviour change. Verified: Windows clippy -D warnings via tools/fast-check PASS. --- komorebi/src/windows_backend.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/komorebi/src/windows_backend.rs b/komorebi/src/windows_backend.rs index 43ab5b82..640fca5d 100644 --- a/komorebi/src/windows_backend.rs +++ b/komorebi/src/windows_backend.rs @@ -241,3 +241,12 @@ impl Backend for WindowsBackend { ))) } } + +static BACKEND: WindowsBackend = WindowsBackend; + +/// The backend the daemon calls, like `backend()` on KDE. Stateless, so one static serves every +/// thread. Call sites are being switched to it one cluster at a time: see +/// `docs/dev/backend-switch.md` for which are. +pub fn backend() -> &'static dyn Backend { + &BACKEND +} From 078bdc1666dcfb518796d6ea0e249163c1867af6 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:01:11 -0700 Subject: [PATCH 05/33] refactor(windows): focus goes through backend() Switch the 40 Window::focus(mouse_follows)? call sites in process_event, process_command, workspace, window_manager, focus_manager and the stackbar click to backend().focus(WindowId::from_hwnd(..), mouse_follows). WindowsBackend::focus runs Window::focus, so the deferral while a window slides in, the already-foreground shortcut and the cursor centring are unchanged. animation/transition.rs:534 stays on Window::focus (it is the code Window::focus defers to). docs/dev/backend-switch.md records what is switched. BEHAVIOUR: a dead window now fails early with Error::WindowGone (before: the Win32 error from raise_and_focus_window) and a failed focus of a window that died meanwhile reports WindowGone; every caller uses ? or ignores the result. e2e gate needed: commands, focus, focus_follows_mouse, stacking, workspaces, lifecycle. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- docs/dev/backend-switch.md | 17 ++++++++ komorebi/src/focus_manager.rs | 5 ++- komorebi/src/process_command.rs | 19 +++++---- komorebi/src/process_event.rs | 16 ++++++-- komorebi/src/stackbar_manager/stackbar.rs | 6 ++- komorebi/src/window_manager.rs | 50 ++++++++++++++--------- komorebi/src/workspace.rs | 28 +++++++++---- 7 files changed, 100 insertions(+), 41 deletions(-) create mode 100644 docs/dev/backend-switch.md diff --git a/docs/dev/backend-switch.md b/docs/dev/backend-switch.md new file mode 100644 index 00000000..1bf88630 --- /dev/null +++ b/docs/dev/backend-switch.md @@ -0,0 +1,17 @@ +# Windows: which call sites go through `backend()` + +Step 8 of the unified-binaries plan. `komorebi::windows_backend::backend()` returns the shared +`komorebi_backend::Backend` (a stateless `WindowsBackend` over `WindowsApi` and `Window`). The daemon +switches one cluster at a time; each switch is its own revision marked BEHAVIOUR. + +What every switch changes, for the Windows daemon: `WindowsBackend` first asks `IsWindow` and fails +with `Error::WindowGone` for a dead window, and a failure of a window that died meanwhile is reported +as `WindowGone` (the message text changes: it was the Win32 error). Call sites use `?` or ignore the +result, none inspects the error. + +| Cluster | Operation | Status | Sites | Left on `Window`/`WindowsApi`, and why | e2e needed | +|---|---|---|---|---|---| +| focus | `focus(id, mouse_follows)` | switched | process_event (4), process_command (3), workspace (7), window_manager (24), focus_manager, stackbar | `animation/transition.rs:534` calls `Window::focus` from inside the slide-in code that `Window::focus` itself defers to (it would recurse through the backend for no gain) | commands, focus, focus_follows_mouse, stacking, workspaces, lifecycle | +| frame / position | `set_rect`, `window_rect` | not switched | | `Window::set_position` has the `top` flag, animation/slide-in/live-resize guards that the backend `set_rect` (always `top = false`) cannot carry | | +| hide / show | `hide`, `restore`, `minimize`, `unminimize`, `raise`, `close` | not switched | | | | +| queries | `window`, `foreground_window`, `cursor_pos`, `monitors`, `monitor_from_point` | not switched | | | | diff --git a/komorebi/src/focus_manager.rs b/komorebi/src/focus_manager.rs index e6055ff8..d6e3bf98 100644 --- a/komorebi/src/focus_manager.rs +++ b/komorebi/src/focus_manager.rs @@ -7,8 +7,9 @@ use std::ops::Deref; use std::sync::Arc; use std::sync::OnceLock; -use crate::Window; use crate::WindowManager; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; pub struct Notification(isize); @@ -65,7 +66,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result for notification in receiver { let mouse_follows_focus = wm.lock().mouse_follows_focus; - let _ = Window::from(*notification).focus(mouse_follows_focus); + let _ = backend().focus(WindowId::from_hwnd(*notification), mouse_follows_focus); } Ok(()) diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 7362499b..a3fd6d66 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -93,9 +93,11 @@ use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; use crate::windows_api::WindowsApi; +use crate::windows_backend::backend; use crate::winevent_listener; use crate::workspace::WorkspaceLayer; use crate::workspace::WorkspaceWindowLocation; +use komorebi_backend::WindowId; use stackbar_manager::STACKBAR_FOCUSED_TEXT_COLOUR; use stackbar_manager::STACKBAR_LABEL; use stackbar_manager::STACKBAR_MODE; @@ -283,7 +285,10 @@ impl WindowManager { if let Some(window) = &mut self.focused_workspace_mut()?.maximized_window { - window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(window.hwnd), + self.mouse_follows_focus, + )?; } } WorkspaceWindowLocation::Container(container_idx, window_idx) => { @@ -300,7 +305,10 @@ impl WindowManager { .floating_windows_mut() .get_mut(window_idx) { - window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(window.hwnd), + self.mouse_follows_focus, + )?; } } } @@ -1366,7 +1374,7 @@ impl WindowManager { } }; if let Some(window) = to_focus { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; } } SocketMessage::Stop => { @@ -2283,10 +2291,7 @@ if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) } } -pub fn read_commands_uds( - wm: &Arc>, - stream: UnixStream, -) -> eyre::Result<()> { +pub fn read_commands_uds(wm: &Arc>, stream: UnixStream) -> eyre::Result<()> { komorebi_transport::read_commands::(wm, stream, &WindowsConnectionPolicy) } diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 86813656..bb011c40 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -8,6 +8,8 @@ use parking_lot::Mutex; use crate::core::Rect; use crate::core::WindowContainerBehaviour; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; use crate::CURRENT_VIRTUAL_DESKTOP; use crate::DefaultLayout; @@ -301,7 +303,7 @@ impl WindowManager { match event { WindowManagerEvent::Raise(window) => { - window.focus(false)?; + backend().focus(WindowId::from_hwnd(window.hwnd), false)?; self.has_pending_raise_op = false; } WindowManagerEvent::Destroy(_, window) | WindowManagerEvent::Unmanage(window) => { @@ -435,7 +437,7 @@ impl WindowManager { if let Some(monocle) = &workspace.monocle_container { if let Some(window) = monocle.focused_window() { - window.focus(false)?; + backend().focus(WindowId::from_hwnd(window.hwnd), false)?; } } else { workspace.focus_container_by_window(window.hwnd)?; @@ -621,7 +623,10 @@ impl WindowManager { // first send the `FocusChange` event and only the `Show` event after // and we will be focusing the desktop on the `FocusChange` event since // it is still empty. - window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(window.hwnd), + self.mouse_follows_focus, + )?; } } @@ -812,7 +817,10 @@ impl WindowManager { self.update_focused_workspace(false, false)?; // Make sure to give focus to the moved window again - window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(window.hwnd), + self.mouse_follows_focus, + )?; } } else if window_management_behaviour.float_override { workspace.floating_windows_mut().push_back(window); diff --git a/komorebi/src/stackbar_manager/stackbar.rs b/komorebi/src/stackbar_manager/stackbar.rs index 68543ff2..71c208a4 100644 --- a/komorebi/src/stackbar_manager/stackbar.rs +++ b/komorebi/src/stackbar_manager/stackbar.rs @@ -18,7 +18,9 @@ use crate::stackbar_manager::STACKBAR_TAB_WIDTH; use crate::stackbar_manager::STACKBAR_UNFOCUSED_TEXT_COLOUR; use crate::stackbar_manager::STACKBARS_CONTAINERS; use crate::windows_api; +use crate::windows_backend::backend; use crossbeam_utils::atomic::AtomicConsume; +use komorebi_backend::WindowId; use std::os::windows::ffi::OsStrExt; use std::sync::atomic::Ordering; use std::sync::mpsc; @@ -370,7 +372,9 @@ impl Stackbar { // Restore the window corresponding to the tab we have clicked window.restore_with_border(false); - if let Err(err) = window.focus(false) { + if let Err(err) = + backend().focus(WindowId::from_hwnd(window.hwnd), false) + { tracing::error!( "stackbar WMLBUTTONDOWN focus error: hwnd {} ({})", *window, diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index a4e6502c..15d02218 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -48,6 +48,8 @@ use crate::core::Sizing; use crate::core::WindowContainerBehaviour; use crate::core::WindowManagementBehaviour; use crate::core::config_generation::MatchingRule; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; use crate::CrossBoundaryBehaviour; use crate::DATA_DIR; @@ -1129,17 +1131,17 @@ impl WindowManager { if follow_focus { if let Some(window) = self.focused_workspace()?.maximized_window { if trigger_focus { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else if let Some(container) = &self.focused_workspace()?.monocle_container { if let Some(window) = container.focused_window() && trigger_focus { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else if let Ok(window) = self.focused_window_mut() { if trigger_focus { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else { let desktop_window = Window::from(WindowsApi::desktop_window()?); @@ -1179,7 +1181,7 @@ impl WindowManager { && let Ok(window) = self.focused_window_mut() && trigger_focus { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } } @@ -1995,7 +1997,7 @@ impl WindowManager { if let Some(idx) = target_idx { focused_workspace.floating_windows.focus(idx); if let Some(window) = focused_workspace.floating_windows().get(idx) { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; } return Ok(()); } @@ -2055,11 +2057,11 @@ impl WindowManager { if let Ok(focused_workspace) = self.focused_workspace_mut() { if let Some(window) = focused_workspace.maximized_window { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; cross_monitor_monocle_or_max = true; } else if let Some(monocle) = &focused_workspace.monocle_container { if let Some(window) = monocle.focused_window() { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; cross_monitor_monocle_or_max = true; } } else if focused_workspace.layer == WorkspaceLayer::Tiling { @@ -2111,12 +2113,15 @@ impl WindowManager { } } else if ws.layer == WorkspaceLayer::Floating && !ws.floating_windows().is_empty() { if let Some(window) = ws.focused_floating_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else { ws.layer = WorkspaceLayer::Tiling; if let Ok(focused_window) = self.focused_window() { - focused_window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(focused_window.hwnd), + self.mouse_follows_focus, + )?; } } } @@ -2258,11 +2263,12 @@ impl WindowManager { if let Ok(focused_workspace) = self.focused_workspace_mut() { if let Some(window) = focused_workspace.maximized_window { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; cross_monitor_monocle_or_max = true; } else if let Some(monocle) = &focused_workspace.monocle_container { if let Some(window) = monocle.focused_window() { - window.focus(mouse_follows_focus)?; + backend() + .focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; cross_monitor_monocle_or_max = true; } } else if focused_workspace.layer == WorkspaceLayer::Tiling { @@ -2320,12 +2326,15 @@ impl WindowManager { } } else if ws.layer == WorkspaceLayer::Floating && !ws.floating_windows().is_empty() { if let Some(window) = ws.focused_floating_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else { ws.layer = WorkspaceLayer::Tiling; if let Ok(focused_window) = self.focused_window() { - focused_window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(focused_window.hwnd), + self.mouse_follows_focus, + )?; } } } @@ -2634,7 +2643,7 @@ impl WindowManager { if let Some(idx) = target_idx && let Some(window) = focused_workspace.floating_windows().get(idx) { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; } Ok(()) @@ -2674,7 +2683,8 @@ impl WindowManager { } else if monocle_next { self.toggle_monocle()?; } else { - self.focused_window_mut()?.focus(self.mouse_follows_focus)?; + let hwnd = self.focused_window_mut()?.hwnd; + backend().focus(WindowId::from_hwnd(hwnd), self.mouse_follows_focus)?; } Ok(()) @@ -2734,7 +2744,7 @@ impl WindowManager { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } self.update_focused_workspace(self.mouse_follows_focus, true) @@ -2771,7 +2781,7 @@ impl WindowManager { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } self.update_focused_workspace(self.mouse_follows_focus, true) @@ -2804,7 +2814,7 @@ impl WindowManager { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } self.update_focused_workspace(self.mouse_follows_focus, true) @@ -2948,7 +2958,7 @@ impl WindowManager { if changed_focus && let Some(container) = workspace.focused_container_mut() { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } @@ -3110,7 +3120,7 @@ impl WindowManager { if toggle_float_placement.should_center() { window.center(&work_area, toggle_float_placement.should_resize())?; } - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; Ok(()) } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 9b2bd4c7..48e43ddf 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -46,8 +46,10 @@ use crate::static_config::WorkspaceConfig; use crate::window::Window; use crate::window::WindowDetails; 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_scrolling::ScrollingSpace; use komorebi_themes::Base16ColourPalette; use komorebi_themes::KomorebiThemeCustom as Custom; @@ -553,7 +555,7 @@ impl Workspace { && let Some(window) = container.focused_window() { container.restore(); - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; return self.apply_wallpaper(hmonitor, monitor_wp); } @@ -583,18 +585,30 @@ impl Workspace { // when switching to a workspace if let Some(window) = to_focus { if self.maximized_window.is_none() && matches!(self.layer, WorkspaceLayer::Tiling) { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; } else if let Some(maximized_window) = self.maximized_window { maximized_window.restore(); - maximized_window.focus(mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(maximized_window.hwnd), + mouse_follows_focus, + )?; } else if let Some(floating_window) = self.focused_floating_window() { - floating_window.focus(mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(floating_window.hwnd), + mouse_follows_focus, + )?; } } else if let Some(maximized_window) = self.maximized_window { maximized_window.restore(); - maximized_window.focus(mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(maximized_window.hwnd), + mouse_follows_focus, + )?; } else if let Some(floating_window) = self.focused_floating_window() { - floating_window.focus(mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(floating_window.hwnd), + mouse_follows_focus, + )?; } self.apply_wallpaper(hmonitor, monitor_wp) @@ -1219,7 +1233,7 @@ impl Workspace { } else { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(false)?; + backend().focus(WindowId::from_hwnd(window.hwnd), false)?; } } From 3a86e8fb6ab31343c17f88084bac1ebece1d12ef Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:11:01 -0700 Subject: [PATCH 06/33] refactor(windows): frame writes with top = false go through backend() The two Window::set_position(rect, false) call sites (the workspace layout update in workspace.rs and the stackbar tab click) now call backend().set_rect(..), which is Window::set_rect = set_position(rect, false): the animation, slide-in and live-resize guards are the same. Not switched: the top = true callers (window.rs move_to_area/center, workspace.rs maximize area), since the shared set_rect has no top flag, and all window_rect reads: the shared window_rect is built on window(id), which asks title, class, exe and path of every window, returns None instead of the Win32 error and defaults on failure; the 60 call sites rely on Err or unwrap_or_default, so they stay on WindowsApi::window_rect until the trait or the adapter has a cheap frame query. BEHAVIOUR: a dead window fails early with Error::WindowGone, and one extra IsWindow call per write. e2e gate needed: commands, resize, layouts, stacking, scrolling, workspaces. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/stackbar_manager/stackbar.rs | 6 ++++-- komorebi/src/workspace.rs | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/komorebi/src/stackbar_manager/stackbar.rs b/komorebi/src/stackbar_manager/stackbar.rs index 71c208a4..4d5ecb48 100644 --- a/komorebi/src/stackbar_manager/stackbar.rs +++ b/komorebi/src/stackbar_manager/stackbar.rs @@ -360,8 +360,10 @@ impl Stackbar { // on top of other tiles before eventually ending up in the correct // tile if index != focused_window_idx - && let Err(err) = - window.set_position(&focused_window_rect, false) + && let Err(err) = backend().set_rect( + WindowId::from_hwnd(window.hwnd), + &focused_window_rect, + ) { tracing::error!( "stackbar WM_LBUTTONDOWN repositioning error: hwnd {} ({})", diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 48e43ddf..dd242c4d 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -850,7 +850,7 @@ impl Workspace { window.restore(); } - window.set_position(layout, false)?; + backend().set_rect(WindowId::from_hwnd(window.hwnd), layout)?; } } } From fad90dbd3eda707603aba7dfe75edc5b6f30a187 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:11:28 -0700 Subject: [PATCH 07/33] refactor(windows): plain hide and restore go through backend() The 23 window.hide() and window.restore() calls (container, workspace, monitor, process_command, process_event, window_manager) become let _ = backend().hide(..) / restore(..): WindowsBackend runs Window::hide and Window::restore, so hiding behaviour (cloak, hide, minimize), border and HIDDEN_HWNDS bookkeeping are the same. Not switched: hide_with_border and restore_with_border (the shared trait has no border flag), the animation transition and ghost dispatcher calls (they run inside the slide-in machinery), minimize, close, raise and maximize (to follow). BEHAVIOUR: a window that is already gone is skipped (IsWindow first), so it is no longer added to HIDDEN_HWNDS or shown; the result is ignored as before. e2e gate needed: commands, workspaces, stacking, lifecycle_hidden, minimize/monitor scenarios. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/container.rs | 8 +++++--- komorebi/src/monitor.rs | 4 +++- komorebi/src/process_command.rs | 6 +++--- komorebi/src/process_event.rs | 6 +++--- komorebi/src/window_manager.rs | 10 +++++----- komorebi/src/workspace.rs | 14 +++++++------- 6 files changed, 26 insertions(+), 22 deletions(-) diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs index 2e56eef1..ebb9707a 100644 --- a/komorebi/src/container.rs +++ b/komorebi/src/container.rs @@ -5,6 +5,8 @@ use serde::Serialize; use crate::Lockable; use crate::ring::Ring; use crate::window::Window; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] @@ -63,14 +65,14 @@ impl Container { } if should_hide { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } } pub fn restore(&self) { if let Some(window) = self.focused_window() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } } @@ -151,7 +153,7 @@ impl Container { for (i, window) in self.windows().iter().enumerate() { if i != focused_window_idx { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } } diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 945c70ae..ee4d2c53 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -12,6 +12,8 @@ use crate::border_manager::BORDER_ENABLED; use crate::border_manager::BORDER_OFFSET; use crate::border_manager::BORDER_WIDTH; use crate::core::Rect; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; use crate::DEFAULT_CONTAINER_PADDING; use crate::DEFAULT_WORKSPACE_PADDING; @@ -438,7 +440,7 @@ impl Monitor { } for window in target_workspace.floating_windows_mut() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } target_workspace.reintegrate_monocle_container()?; diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index a3fd6d66..e81d69c3 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -1308,7 +1308,7 @@ impl WindowManager { if i == focused_idx { to_focus = Some(*window); } else { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); window.raise()?; } } @@ -1316,7 +1316,7 @@ impl WindowManager { if let Some(focused_window) = &to_focus { // The focused window should be the last one raised to make sure it is // on top - focused_window.restore(); + let _ = backend().restore(WindowId::from_hwnd(focused_window.hwnd)); focused_window.raise()?; } @@ -1341,7 +1341,7 @@ impl WindowManager { window.raise()?; } for window in workspace.floating_windows() { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } else { let focused_container_idx = workspace.focused_container_idx(); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index bb011c40..6c00c302 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -511,7 +511,7 @@ impl WindowManager { "ignoring show event for window already associated with another workspace" ); - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); proceed = false; } @@ -643,7 +643,7 @@ impl WindowManager { if !(monocle_window_event || workspace.layer != WorkspaceLayer::Tiling) && monocle_container.is_some() { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } } @@ -1063,7 +1063,7 @@ impl WindowManager { container.restore(); } for window in workspace.floating_windows_mut() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } workspace.reintegrate_monocle_container()?; } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 15d02218..85bc4fea 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -702,7 +702,7 @@ impl WindowManager { // Hide the window we are about to remove if it is on the currently focused workspace if op.is_origin(focused_monitor_idx, focused_workspace_idx) { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); should_update_focused_workspace = true; } @@ -1510,7 +1510,7 @@ impl WindowManager { } if !ignore_restore { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } } } @@ -1758,7 +1758,7 @@ impl WindowManager { } for window in target_workspace.floating_windows_mut() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } target_workspace.reintegrate_monocle_container()?; @@ -3160,7 +3160,7 @@ impl WindowManager { } for window in workspace.floating_windows_mut() { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } Ok(()) @@ -3177,7 +3177,7 @@ impl WindowManager { } for window in workspace.floating_windows_mut() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } workspace.reintegrate_monocle_container() diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index dd242c4d..ec69d747 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -408,7 +408,7 @@ impl Workspace { } if should_hide { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } @@ -417,7 +417,7 @@ impl Workspace { } if let Some(window) = self.maximized_window { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } if let Some(container) = &self.monocle_container { @@ -577,7 +577,7 @@ impl Workspace { } for window in self.floating_windows() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } // Do this here to make sure that an error doesn't stop the restoration of other windows @@ -587,7 +587,7 @@ impl Workspace { if self.maximized_window.is_none() && matches!(self.layer, WorkspaceLayer::Tiling) { backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; } else if let Some(maximized_window) = self.maximized_window { - maximized_window.restore(); + let _ = backend().restore(WindowId::from_hwnd(maximized_window.hwnd)); backend().focus( WindowId::from_hwnd(maximized_window.hwnd), mouse_follows_focus, @@ -599,7 +599,7 @@ impl Workspace { )?; } } else if let Some(maximized_window) = self.maximized_window { - maximized_window.restore(); + let _ = backend().restore(WindowId::from_hwnd(maximized_window.hwnd)); backend().focus( WindowId::from_hwnd(maximized_window.hwnd), mouse_follows_focus, @@ -840,14 +840,14 @@ impl Workspace { } if hidden.get(i).copied().unwrap_or_default() { // it is seen on another monitor wherever it rests here - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } else { if crate::scrolling::should_restore_when_placed( window.hwnd, container.focused_window().map(|w| w.hwnd), &HIDDEN_HWNDS.lock(), ) { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } backend().set_rect(WindowId::from_hwnd(window.hwnd), layout)?; From f5a299aa9ef035e7f38b18d2e83d219dbfef426c Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:11:57 -0700 Subject: [PATCH 08/33] refactor(windows): minimize, close and raise go through backend() process_command (close and minimize of the foreground window, four raise calls) and monitor_reconciliator (four minimize calls) now call backend().close/minimize/raise. WindowsBackend runs Window::close, minimize and raise unchanged (minimize still leaves komorebi-bar alone). docs/dev/backend-switch.md now holds the full table of what is switched and what is left, including why the queries (window_rect, foreground_window, cursor_pos, monitors) were NOT switched: each would drop an error that callers use or report, or fabricate a default. BEHAVIOUR: a dead window is skipped by an IsWindow check first; minimize results are ignored as before. e2e gate needed: commands, monitor reconciliation (monitor_reconciliator), lifecycle. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- docs/dev/backend-switch.md | 24 +++++++++++++---------- komorebi/src/monitor_reconciliator/mod.rs | 14 +++++++++---- komorebi/src/process_command.rs | 12 ++++++------ 3 files changed, 30 insertions(+), 20 deletions(-) diff --git a/docs/dev/backend-switch.md b/docs/dev/backend-switch.md index 1bf88630..b60b26d2 100644 --- a/docs/dev/backend-switch.md +++ b/docs/dev/backend-switch.md @@ -2,16 +2,20 @@ Step 8 of the unified-binaries plan. `komorebi::windows_backend::backend()` returns the shared `komorebi_backend::Backend` (a stateless `WindowsBackend` over `WindowsApi` and `Window`). The daemon -switches one cluster at a time; each switch is its own revision marked BEHAVIOUR. +is switched one cluster at a time; each switch is its own revision marked BEHAVIOUR. -What every switch changes, for the Windows daemon: `WindowsBackend` first asks `IsWindow` and fails -with `Error::WindowGone` for a dead window, and a failure of a window that died meanwhile is reported -as `WindowGone` (the message text changes: it was the Win32 error). Call sites use `?` or ignore the -result, none inspects the error. +What every switched call changes in the Windows daemon: `WindowsBackend` first asks `IsWindow` and +fails with `Error::WindowGone` for a dead window, and a failure of a window that died meanwhile is +reported as `WindowGone` (the error text changes from the Win32 one). Call sites use `?` or ignore the +result; none inspects the error. The operations return `Result` where `Window::hide`, `restore` and +`minimize` returned `()`: those sites ignore it (`let _ =`), as the old code could not fail. -| Cluster | Operation | Status | Sites | Left on `Window`/`WindowsApi`, and why | e2e needed | +| Cluster | Operation | Status | Sites | Left on `Window` / `WindowsApi`, and why | e2e needed | |---|---|---|---|---|---| -| focus | `focus(id, mouse_follows)` | switched | process_event (4), process_command (3), workspace (7), window_manager (24), focus_manager, stackbar | `animation/transition.rs:534` calls `Window::focus` from inside the slide-in code that `Window::focus` itself defers to (it would recurse through the backend for no gain) | commands, focus, focus_follows_mouse, stacking, workspaces, lifecycle | -| frame / position | `set_rect`, `window_rect` | not switched | | `Window::set_position` has the `top` flag, animation/slide-in/live-resize guards that the backend `set_rect` (always `top = false`) cannot carry | | -| hide / show | `hide`, `restore`, `minimize`, `unminimize`, `raise`, `close` | not switched | | | | -| queries | `window`, `foreground_window`, `cursor_pos`, `monitors`, `monitor_from_point` | not switched | | | | +| focus | `focus(id, mouse_follows)` | switched | process_event 4, process_command 3, workspace 7, window_manager 24, focus_manager 1, stackbar 1 | `animation/transition.rs:534` calls `Window::focus` from inside the slide-in code that `Window::focus` itself defers to | commands, focus, focus_follows_mouse, stacking, workspaces, lifecycle | +| frame | `set_rect(id, rect)` | switched for `top = false` | workspace.rs (layout update), stackbar tab click | `set_position(.., true)` callers (window.rs `move_to_area`/`center`, workspace maximize area): the shared `set_rect` has no `top` flag | commands, resize, layouts, stacking, scrolling, workspaces | +| frame | `window_rect(id)` | NOT switched | 0 of about 60 | the shared `window_rect` is built on `window(id)`, which asks title, class, exe and path of the window, gives `None` for a failure and the call sites rely on `Err` or `unwrap_or_default`. Needs a cheap frame query on the trait (a `frame(id) -> Result`) or an override of the provided method with an error | | +| hide / show | `hide`, `restore` | switched for the plain forms | container, workspace, monitor, process_command, process_event, window_manager (23) | `hide_with_border` and `restore_with_border` (no border flag in the trait); `animation/transition.rs` and `ghost_dispatcher.rs` (inside the slide-in machinery); the `Container`/`Workspace` methods stay, they call these | commands, workspaces, stacking, lifecycle_hidden | +| hide / show | `minimize`, `close`, `raise` | switched | process_command (close 1, minimize 1, raise 4), monitor_reconciliator (minimize 4) | | commands, monitor reconciliation, lifecycle | +| hide / show | `unminimize`, `maximize` | not switched | | `unminimize` has no daemon caller (the daemon uses `restore`); `maximize`/`unmaximize` need the `Capability::Maximize` check and keep their own bookkeeping in workspace.rs | | +| queries | `foreground_window`, `cursor_pos`, `monitors`, `monitor_from_point`, `window` | NOT switched | 0 | `WindowsApi::foreground_window` is `Result` (null handle is an `Err` with a message the callers pass on), the trait gives `Option`; `cursor_pos` is `Result` vs `Option<(i32, i32)>`; `monitors` rebuilds `MonitorInfo` (drops the `Monitor` fields the daemon needs); `monitor_from_point` is never `None` on Windows. Each switch would drop an error the caller reports or fabricate a default | | diff --git a/komorebi/src/monitor_reconciliator/mod.rs b/komorebi/src/monitor_reconciliator/mod.rs index bb00eacb..582b0b98 100644 --- a/komorebi/src/monitor_reconciliator/mod.rs +++ b/komorebi/src/monitor_reconciliator/mod.rs @@ -15,9 +15,11 @@ use crate::monitor::Monitor; use crate::monitor_reconciliator::hidden::Hidden; use crate::notify_subscribers; use crate::state::State; +use crate::windows_backend::backend; use crossbeam_channel::Receiver; use crossbeam_channel::Sender; use crossbeam_utils::atomic::AtomicConsume; +use komorebi_backend::WindowId; use parking_lot::Mutex; use serde::Deserialize; use serde::Serialize; @@ -593,7 +595,8 @@ where // Minimize the focused window since Windows might try // to move it to another monitor if it was focused. if window.is_focused() { - window.minimize(); + let _ = backend() + .minimize(WindowId::from_hwnd(window.hwnd)); } } } @@ -604,7 +607,8 @@ where // Minimize the focused window since Windows might try // to move it to another monitor if it was focused. if maximized.is_focused() { - maximized.minimize(); + let _ = + backend().minimize(WindowId::from_hwnd(maximized.hwnd)); } } @@ -616,7 +620,8 @@ where // Minimize the focused window since Windows might try // to move it to another monitor if it was focused. if window.is_focused() { - window.minimize(); + let _ = backend() + .minimize(WindowId::from_hwnd(window.hwnd)); } } } @@ -626,7 +631,8 @@ where // Minimize the focused window since Windows might try // to move it to another monitor if it was focused. if window.is_focused() { - window.minimize(); + let _ = + backend().minimize(WindowId::from_hwnd(window.hwnd)); } } } diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index e81d69c3..b123aadb 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -406,10 +406,10 @@ impl WindowManager { WindowsApi::left_click(); } SocketMessage::Close => { - Window::from(WindowsApi::foreground_window()?).close()?; + backend().close(WindowId::from_hwnd(WindowsApi::foreground_window()?))?; } SocketMessage::Minimize => { - Window::from(WindowsApi::foreground_window()?).minimize(); + let _ = backend().minimize(WindowId::from_hwnd(WindowsApi::foreground_window()?)); } SocketMessage::LockMonitorWorkspaceContainer( monitor_idx, @@ -1309,7 +1309,7 @@ impl WindowManager { to_focus = Some(*window); } else { let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); - window.raise()?; + backend().raise(WindowId::from_hwnd(window.hwnd))?; } } @@ -1317,7 +1317,7 @@ impl WindowManager { // The focused window should be the last one raised to make sure it is // on top let _ = backend().restore(WindowId::from_hwnd(focused_window.hwnd)); - focused_window.raise()?; + backend().raise(WindowId::from_hwnd(focused_window.hwnd))?; } for container in workspace.containers() { @@ -1338,7 +1338,7 @@ impl WindowManager { if let Some(monocle) = &workspace.monocle_container { if let Some(window) = monocle.focused_window() { to_focus = Some(*window); - window.raise()?; + backend().raise(WindowId::from_hwnd(window.hwnd))?; } for window in workspace.floating_windows() { let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); @@ -1351,7 +1351,7 @@ impl WindowManager { if i == focused_container_idx { to_focus = Some(*window); } - window.raise()?; + backend().raise(WindowId::from_hwnd(window.hwnd))?; } } From 8a304c62dc72f894b545a8c0d961987acfc6a937 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:22:28 -0700 Subject: [PATCH 09/33] wip From b580b29f4424adc5e50e14175f695172b663b891 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:23:05 -0700 Subject: [PATCH 10/33] refactor(windows): stackbar_manager/mod.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in stackbar_manager/mod.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: stacking, layouts. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/stackbar_manager/mod.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/komorebi/src/stackbar_manager/mod.rs b/komorebi/src/stackbar_manager/mod.rs index fe56b941..011b9b1f 100644 --- a/komorebi/src/stackbar_manager/mod.rs +++ b/komorebi/src/stackbar_manager/mod.rs @@ -7,10 +7,12 @@ use crate::container::Container; use crate::core::StackbarLabel; use crate::core::StackbarMode; use crate::stackbar_manager::stackbar::Stackbar; +use crate::windows_backend::backend; use crossbeam_channel::Receiver; use crossbeam_channel::Sender; use crossbeam_utils::atomic::AtomicCell; use crossbeam_utils::atomic::AtomicConsume; +use komorebi_backend::WindowId; use lazy_static::lazy_static; use parking_lot::Mutex; use std::collections::HashMap; @@ -206,9 +208,9 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result stackbars_monitors.insert(container.id.clone(), monitor_idx); - let rect = WindowsApi::window_rect( + let rect = backend().frame(WindowId::from_hwnd( container.focused_window().copied().unwrap_or_default().hwnd, - )?; + ))?; stackbar.update(container_padding, container, &rect)?; } From 7ba4327fa0b9f320215bc55e8cb3235e726cf8fe Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:24:14 -0700 Subject: [PATCH 11/33] refactor(windows): stackbar_manager/stackbar.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in stackbar_manager/stackbar.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: stacking. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/stackbar_manager/stackbar.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/komorebi/src/stackbar_manager/stackbar.rs b/komorebi/src/stackbar_manager/stackbar.rs index 4d5ecb48..8edacd9f 100644 --- a/komorebi/src/stackbar_manager/stackbar.rs +++ b/komorebi/src/stackbar_manager/stackbar.rs @@ -343,10 +343,11 @@ impl Stackbar { let gap = DEFAULT_CONTAINER_PADDING.load_consume(); let focused_window_idx = container.focused_window_idx(); - let focused_window_rect = WindowsApi::window_rect( - container.focused_window().cloned().unwrap_or_default().hwnd, - ) - .unwrap_or_default(); + let focused_window_rect = backend() + .frame(WindowId::from_hwnd( + container.focused_window().cloned().unwrap_or_default().hwnd, + )) + .unwrap_or_default(); for (index, window) in container.windows().iter().enumerate() { let left = gap + (index as i32 * (width + gap)); From 17ecb8787c5f45583b3bc7ab8623f5462e7c567f Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:28:06 -0700 Subject: [PATCH 12/33] refactor(windows): animation/snapshot.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in animation/snapshot.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: animation scenarios, workspaces. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/animation/snapshot.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/komorebi/src/animation/snapshot.rs b/komorebi/src/animation/snapshot.rs index 2be05264..e38df2c7 100644 --- a/komorebi/src/animation/snapshot.rs +++ b/komorebi/src/animation/snapshot.rs @@ -60,6 +60,8 @@ use windows::core::w; use crate::WindowsApi; use crate::border_manager::BorderLook; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; /// Ask for what the window looks like to the compositor, which is the only /// way to capture a window that is drawn with DirectComposition @@ -279,7 +281,7 @@ fn render(hwnd: isize) -> eyre::Result { let window_height = window.bottom - window.top; // what is on screen is the extended frame, inside the invisible borders - let frame = WindowsApi::window_rect(hwnd)?; + let frame = backend().frame(WindowId::from_hwnd(hwnd))?; let x = (frame.left - window.left).clamp(0, window_width); let y = (frame.top - window.top).clamp(0, window_height); let width = frame.right.min(window_width - x); From 07d61544835ba4a32dbe9180c88c1721096bf94f Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:28:32 -0700 Subject: [PATCH 13/33] refactor(windows): live_resize.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in live_resize.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: resize. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/live_resize.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/komorebi/src/live_resize.rs b/komorebi/src/live_resize.rs index c01e7eb1..5cbc6e87 100644 --- a/komorebi/src/live_resize.rs +++ b/komorebi/src/live_resize.rs @@ -29,10 +29,12 @@ use crate::core::Rect; use crate::core::Sizing; use crate::window::Window; use crate::window_manager::WindowManager; +use crate::windows_backend::backend; use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use crossbeam_channel::Sender; use crossbeam_channel::bounded; +use komorebi_backend::WindowId; use komorebi_scrolling::ScrollingSpace; use parking_lot::Mutex; use std::collections::HashMap; @@ -163,7 +165,9 @@ pub fn is_catching_up(hwnd: isize, layout: &Rect) -> bool { return false; }; - let arrived = WindowsApi::window_rect(hwnd).is_ok_and(|rect| rect == target); + let arrived = backend() + .frame(WindowId::from_hwnd(hwnd)) + .is_ok_and(|rect| rect == target); if arrived || at.elapsed() >= IN_FLIGHT { return false; @@ -440,7 +444,7 @@ pub fn cover_all(windows: &[(isize, Rect)]) { .into_iter() .map(|(hwnd, origin)| { std::thread::spawn(move || { - let rect = WindowsApi::window_rect(hwnd).ok()?; + let rect = backend().frame(WindowId::from_hwnd(hwnd)).ok()?; // the picture is taken before the window is touched match GhostWindow::create(hwnd, origin, None) { @@ -897,7 +901,7 @@ impl WindowManager { return Ok(()); } - let now = WindowsApi::window_rect(kept.hwnd)?; + let now = backend().frame(WindowId::from_hwnd(kept.hwnd))?; // a window moved by its title bar changes no tile until it is let go, // and a drag that has gone back to where it began is a step that puts @@ -1032,7 +1036,7 @@ impl WindowManager { continue; } - let Ok(rect) = WindowsApi::window_rect(window.hwnd) else { + let Ok(rect) = backend().frame(WindowId::from_hwnd(window.hwnd)) else { continue; }; From 14b61124533a84c8cb312b234adcf29711dce544 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:28:51 -0700 Subject: [PATCH 14/33] refactor(windows): pan.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in pan.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: scrolling pan. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/pan.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/komorebi/src/pan.rs b/komorebi/src/pan.rs index 48e85eb6..d835cde5 100644 --- a/komorebi/src/pan.rs +++ b/komorebi/src/pan.rs @@ -12,8 +12,9 @@ use crate::core::Rect; use crate::live_resize; use crate::live_resize::Snapping; use crate::window_manager::WindowManager; -use crate::windows_api::WindowsApi; +use crate::windows_backend::backend; use color_eyre::eyre; +use komorebi_backend::WindowId; use komorebi_scrolling::ScrollingSpace; use komorebi_scrolling::SwipeTracker; use parking_lot::Mutex; @@ -97,7 +98,7 @@ impl WindowManager { let work_area = self.focused_monitor_work_area()?; let workspace = self.focused_workspace()?; let near: Vec<_> = origins(&workspace.scrolling_lefts(), |hwnd| { - WindowsApi::window_rect(hwnd).ok() + backend().frame(WindowId::from_hwnd(hwnd)).ok() }) .into_iter() .filter(|(_, origin)| live_resize::is_near(origin, &work_area)) From 6a4db7dc5e2d83e8ccab293b4dd2466915505cea Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:29:00 -0700 Subject: [PATCH 15/33] refactor(windows): scrolling.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in scrolling.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: scrolling. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/scrolling.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/komorebi/src/scrolling.rs b/komorebi/src/scrolling.rs index 5e07e6b7..51994f50 100644 --- a/komorebi/src/scrolling.rs +++ b/komorebi/src/scrolling.rs @@ -18,9 +18,10 @@ use crate::core::Rect; use crate::core::ScrollingLayoutOptions; use crate::core::Sizing; use crate::core::WindowHandlingBehaviour; -use crate::windows_api::WindowsApi; +use crate::windows_backend::backend; use crate::workspace::Workspace; use color_eyre::eyre; +use komorebi_backend::WindowId; use komorebi_layouts::scrolling; use komorebi_layouts::scrolling::ScrollingPlacement; use komorebi_scrolling::ColumnWidth; @@ -201,7 +202,7 @@ impl Workspace { .iter() // a window that is hidden has not been where it was told to be .filter(|window| !crate::HIDDEN_HWNDS.lock().contains(&window.hwnd)) - .filter_map(|window| WindowsApi::window_rect(window.hwnd).ok()) + .filter_map(|window| backend().frame(WindowId::from_hwnd(window.hwnd)).ok()) .map(|actual| actual.right - placed.right) .max() .unwrap_or_default(); From 387d780aa7b16b167f269da0173cdf43b59426fc Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:29:32 -0700 Subject: [PATCH 16/33] refactor(windows): animation/ghost_dispatcher.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in animation/ghost_dispatcher.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: animation scenarios. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/animation/ghost_dispatcher.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/komorebi/src/animation/ghost_dispatcher.rs b/komorebi/src/animation/ghost_dispatcher.rs index e91a1639..d0023164 100644 --- a/komorebi/src/animation/ghost_dispatcher.rs +++ b/komorebi/src/animation/ghost_dispatcher.rs @@ -26,7 +26,9 @@ use crate::stackbar_manager; use crate::transparency_manager; use crate::window::Window; use crate::windows_api::WindowsApi; +use crate::windows_backend::backend; use color_eyre::eyre; +use komorebi_backend::WindowId; use parking_lot::Mutex; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; @@ -320,8 +322,9 @@ impl GhostDispatcher { /// render target. Those that do have to be laid out are not until they are /// shown. fn lay_out_entering_window(&self) { - let is_there = - WindowsApi::window_rect(self.hwnd).is_ok_and(|rect| rect == self.target_rect); + let is_there = backend() + .frame(WindowId::from_hwnd(self.hwnd)) + .is_ok_and(|rect| rect == self.target_rect); if is_there { return; @@ -491,8 +494,9 @@ impl GhostDispatcher { /// swap chain is shown before it is laid out, and not after: laying one out /// while it is hidden is what leaves it blank or drawn off its place. fn show_entered_at_once(&self) { - let is_there = - WindowsApi::window_rect(self.hwnd).is_ok_and(|rect| rect == self.target_rect); + let is_there = backend() + .frame(WindowId::from_hwnd(self.hwnd)) + .is_ok_and(|rect| rect == self.target_rect); if is_there { self.show(); From 74652fb451b830f7f9e5cf8e15dc51723d313c7d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:29:53 -0700 Subject: [PATCH 17/33] refactor(windows): process_command.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in process_command.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: commands, resize. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/process_command.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index b123aadb..c7ec8c68 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -401,7 +401,8 @@ impl WindowManager { } SocketMessage::ForceFocus => { let focused_window = self.focused_window()?; - let focused_window_rect = WindowsApi::window_rect(focused_window.hwnd)?; + let focused_window_rect = + backend().frame(WindowId::from_hwnd(focused_window.hwnd))?; WindowsApi::center_cursor_in_rect(&focused_window_rect)?; WindowsApi::left_click(); } @@ -1299,7 +1300,9 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|(_, w)| { - let rect = WindowsApi::window_rect(w.hwnd).unwrap_or_default(); + let rect = backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .unwrap_or_default(); rect.right * rect.bottom }); window_idx_pairs.reverse(); @@ -1363,7 +1366,9 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|w| { - let rect = WindowsApi::window_rect(w.hwnd).unwrap_or_default(); + let rect = backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .unwrap_or_default(); rect.right * rect.bottom }); From c700502f15d45a31a8848aa11de17824947920ec Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:30:10 -0700 Subject: [PATCH 18/33] refactor(windows): border_manager/mod.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in border_manager/mod.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: borders. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/border_manager/mod.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/komorebi/src/border_manager/mod.rs b/komorebi/src/border_manager/mod.rs index eba053d3..0d7649b9 100644 --- a/komorebi/src/border_manager/mod.rs +++ b/komorebi/src/border_manager/mod.rs @@ -8,6 +8,7 @@ use crate::core::BorderStyle; use crate::core::WindowKind; use crate::ring::Ring; use crate::windows_api; +use crate::windows_backend::backend; use crate::workspace::Workspace; use crate::workspace::WorkspaceLayer; pub use border::Border; @@ -16,6 +17,7 @@ use crossbeam_channel::Receiver; use crossbeam_channel::Sender; use crossbeam_utils::atomic::AtomicCell; use crossbeam_utils::atomic::AtomicConsume; +use komorebi_backend::WindowId; pub use komorebi_config::behaviour::ZOrder; use komorebi_themes::colour::Colour; use komorebi_themes::colour::Rgb; @@ -678,7 +680,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result ); border.window_rect } else { - WindowsApi::window_rect(focused_window_hwnd)? + backend().frame(WindowId::from_hwnd(focused_window_hwnd))? }; border.window_rect = rect; @@ -857,7 +859,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result ); border.window_rect } else { - match WindowsApi::window_rect(focused_window_hwnd) { + match backend().frame(WindowId::from_hwnd(focused_window_hwnd)) { Ok(rect) => rect, Err(_) => { remove_border(&c.id, &mut borders, &mut windows_borders)?; @@ -963,7 +965,7 @@ fn handle_floating_borders( ); border.window_rect } else { - WindowsApi::window_rect(window.hwnd)? + backend().frame(WindowId::from_hwnd(window.hwnd))? }; border.window_rect = rect; From 370dab364a536013dbfed4275c0f59c2546edaeb Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:30:21 -0700 Subject: [PATCH 19/33] refactor(windows): animation/ghost.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in animation/ghost.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: animation scenarios. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/animation/ghost.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/komorebi/src/animation/ghost.rs b/komorebi/src/animation/ghost.rs index 0a9d7716..d35714fb 100644 --- a/komorebi/src/animation/ghost.rs +++ b/komorebi/src/animation/ghost.rs @@ -940,6 +940,8 @@ pub fn nudge_swap_chain_window(hwnd: isize, rect: &Rect, top: bool) { #[cfg(test)] mod tests { use super::*; + use crate::windows_backend::backend; + use komorebi_backend::WindowId; #[test] fn swap_chain_classes() { @@ -1193,7 +1195,8 @@ mod tests { // the screen is read in pixels, and the windows were put where they are in // the units of a process that the display's scaling is applied to - let scale = WindowsApi::window_rect(host.0 as isize) + let scale = backend() + .frame(WindowId::from_hwnd(host.0 as isize)) .map(|rect| f64::from(rect.right) / 800.0) .unwrap_or(1.0); From d395b0e5950c98c1a9388f7d554a1da4d4e7a46a Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:30:29 -0700 Subject: [PATCH 20/33] refactor(windows): process_event.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in process_event.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: commands, lifecycle, resize, move. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/process_event.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 6c00c302..4aff0d79 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -658,7 +658,7 @@ impl WindowManager { WindowsApi::bring_window_to_top(window.hwnd)?; - let started_from = WindowsApi::window_rect(window.hwnd)?; + let started_from = backend().frame(WindowId::from_hwnd(window.hwnd))?; let pending_move_op = Arc::make_mut(&mut self.pending_move_op); *pending_move_op = @@ -701,7 +701,7 @@ impl WindowManager { let workspace = self.focused_workspace_mut()?; let focused_container_idx = workspace.focused_container_idx(); - let new_position = WindowsApi::window_rect(window.hwnd)?; + let new_position = backend().frame(WindowId::from_hwnd(window.hwnd))?; // Measure against the rect the window had when the drag started, which is what // the user had under the pointer; a window is not always exactly on its tile // (cell grids, minimum sizes, border insets) From 63904b736d21ad4d3a5f9d01bd555d7543c43b52 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:30:39 -0700 Subject: [PATCH 21/33] refactor(windows): border_manager/border.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in border_manager/border.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: borders. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/border_manager/border.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/komorebi/src/border_manager/border.rs b/komorebi/src/border_manager/border.rs index 98307ab6..3723681f 100644 --- a/komorebi/src/border_manager/border.rs +++ b/komorebi/src/border_manager/border.rs @@ -9,6 +9,8 @@ use crate::border_manager::window_kind_colour; use crate::core::BorderStyle; use crate::core::Rect; use crate::windows_api; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; use std::collections::HashMap; use std::ops::Deref; use std::sync::Arc; @@ -308,7 +310,9 @@ impl Border { monitor_idx: Some(monitor_idx), render_target: None, tracking_hwnd, - window_rect: WindowsApi::window_rect(tracking_hwnd).unwrap_or_default(), + window_rect: backend() + .frame(WindowId::from_hwnd(tracking_hwnd)) + .unwrap_or_default(), rendered_rect: Rect::default(), window_kind: WindowKind::Unfocused, style: STYLE.load(), @@ -566,7 +570,9 @@ impl Border { return LRESULT(0); } - let rect = WindowsApi::window_rect(reference_hwnd).unwrap_or_default(); + let rect = backend() + .frame(WindowId::from_hwnd(reference_hwnd)) + .unwrap_or_default(); apply_tracked_rect(border_pointer, rect); LRESULT(0) } @@ -593,14 +599,14 @@ impl Border { } WM_PAINT => { tracing::trace!("border {}: WM_PAINT", window.0 as isize); - if let Err(error) = WindowsApi::window_rect(window.0 as isize) { + if let Err(error) = backend().frame(WindowId::from_hwnd(window.0 as isize)) { tracing::trace!( "border {}: not painted, its own rect cannot be read: {error}", window.0 as isize ); } - if let Ok(rect) = WindowsApi::window_rect(window.0 as isize) { + if let Ok(rect) = backend().frame(WindowId::from_hwnd(window.0 as isize)) { let border_pointer: *mut Border = GetWindowLongPtrW(window, GWLP_USERDATA) as _; From a43d39635b2931500eb90f1da538715d3d0a230d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:30:47 -0700 Subject: [PATCH 22/33] refactor(windows): window_manager.rs reads frames through backend().frame() Every WindowsApi::window_rect(hwnd) in window_manager.rs becomes backend().frame(WindowId::from_hwnd(hwnd)). WindowsBackend::frame is Window::window_rect, i.e. the same DWM call with the Win32 error kept; the callers' ?, ok(), unwrap_or_default() and is_ok_and() behave as before (only the error text can differ: a window that died meanwhile reports WindowGone). BEHAVIOUR: none intended; e2e gate needed: commands, layouts, workspaces, stacking. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/window_manager.rs | 41 ++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 85bc4fea..47183dde 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1219,7 +1219,7 @@ impl WindowManager { for window in workspace.floating_windows().iter() { if window.hwnd == focused_hwnd { - let mut rect = WindowsApi::window_rect(window.hwnd)?; + let mut rect = backend().frame(WindowId::from_hwnd(window.hwnd))?; match (direction, sizing) { (OperationDirection::Left, Sizing::Increase) => { if rect.left - delta < focused_monitor_work_area.left { @@ -1897,7 +1897,7 @@ impl WindowManager { if len > 1 { let focused_hwnd = WindowsApi::foreground_window()?; - let focused_rect = WindowsApi::window_rect(focused_hwnd)?; + let focused_rect = backend().frame(WindowId::from_hwnd(focused_hwnd))?; match direction { OperationDirection::Left => { let mut windows_in_direction = focused_workspace @@ -1905,8 +1905,12 @@ impl WindowManager { .iter() .enumerate() .flat_map(|(idx, w)| { - (w.hwnd != focused_hwnd) - .then_some(WindowsApi::window_rect(w.hwnd).ok().map(|r| (idx, r))) + (w.hwnd != focused_hwnd).then_some( + backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .ok() + .map(|r| (idx, r)), + ) }) .flatten() .flat_map(|(idx, r)| { @@ -1928,8 +1932,12 @@ impl WindowManager { .iter() .enumerate() .flat_map(|(idx, w)| { - (w.hwnd != focused_hwnd) - .then_some(WindowsApi::window_rect(w.hwnd).ok().map(|r| (idx, r))) + (w.hwnd != focused_hwnd).then_some( + backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .ok() + .map(|r| (idx, r)), + ) }) .flatten() .flat_map(|(idx, r)| { @@ -1951,8 +1959,12 @@ impl WindowManager { .iter() .enumerate() .flat_map(|(idx, w)| { - (w.hwnd != focused_hwnd) - .then_some(WindowsApi::window_rect(w.hwnd).ok().map(|r| (idx, r))) + (w.hwnd != focused_hwnd).then_some( + backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .ok() + .map(|r| (idx, r)), + ) }) .flatten() .flat_map(|(idx, r)| { @@ -1974,8 +1986,12 @@ impl WindowManager { .iter() .enumerate() .flat_map(|(idx, w)| { - (w.hwnd != focused_hwnd) - .then_some(WindowsApi::window_rect(w.hwnd).ok().map(|r| (idx, r))) + (w.hwnd != focused_hwnd).then_some( + backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .ok() + .map(|r| (idx, r)), + ) }) .flatten() .flat_map(|(idx, r)| { @@ -2367,7 +2383,7 @@ impl WindowManager { let focused_hwnd = WindowsApi::foreground_window()?; for window in focused_workspace.floating_windows().iter() { if window.hwnd == focused_hwnd { - let mut rect = WindowsApi::window_rect(window.hwnd)?; + let mut rect = backend().frame(WindowId::from_hwnd(window.hwnd))?; match direction { OperationDirection::Left => { if rect.left - delta < focused_monitor_work_area.left { @@ -4066,7 +4082,8 @@ fn workspace_transition_plan( .into_iter() .filter(|window| !window.is_miminized()) .filter_map(|window| { - WindowsApi::window_rect(window.hwnd) + backend() + .frame(WindowId::from_hwnd(window.hwnd)) .ok() .map(|rect| (window.hwnd, rect)) }) From 5bffe0e93e3cf72fd637ebd4edb5b51681a5b0bc Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:31:33 -0700 Subject: [PATCH 23/33] refactor(windows): maximize and unmaximize go through backend() The five window.maximize() / unmaximize() calls in workspace.rs become let _ = backend().maximize(id, true/false). The trait already has the capability query (Backend::supports(Capability::Maximize), true on Windows), so no trait change; the Windows daemon does not need to ask, the shared core will. WindowsBackend::maximize runs Window::maximize / unmaximize, which keep the HIDDEN_HWNDS bookkeeping. set_opacity is NOT switched: the adapter's set_opacity is the plain write, while Window::transparent/opaque take the alpha from the transparency manager and animate. BEHAVIOUR: a dead window is skipped (IsWindow first). e2e gate needed: maximizing, commands, workspaces. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- komorebi/src/workspace.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index ec69d747..4eba3431 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -729,7 +729,7 @@ impl Workspace { window.set_position(&adjusted_work_area, true)?; }; } else if let Some(window) = &mut self.maximized_window { - window.maximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), true); } else if !self.containers().is_empty() { // windows that were not what they were told to be since the last layout, which // is something that animations only show once they are done @@ -1198,7 +1198,7 @@ impl Workspace { if let Some(window) = self.maximized_window && window.hwnd == hwnd { - window.unmaximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), false); self.maximized_window = None; self.maximized_window_restore_idx = None; return Ok(()); @@ -1888,7 +1888,7 @@ impl Workspace { self.maximized_window = floating_window; self.maximized_window_restore_idx = Option::from(focused_idx); if let Some(window) = self.maximized_window { - window.maximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), true); } return Ok(()); @@ -1910,7 +1910,7 @@ impl Workspace { self.maximized_window = Option::from(window); self.maximized_window_restore_idx = monocle_restore_idx; if let Some(window) = self.maximized_window { - window.maximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), true); } return Ok(()); @@ -1940,7 +1940,7 @@ impl Workspace { self.maximized_window_restore_idx = Option::from(focused_idx); if let Some(window) = self.maximized_window { - window.maximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), true); } self.focus_previous_container(); From 292a9ed56767532f301395c117d060ba1ccc6f54 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:32:29 -0700 Subject: [PATCH 24/33] docs(windows): record which call sites go through backend() docs/dev/backend-switch.md now has the table of what is switched (focus, set_rect with top = false, frame reads, plain hide/restore, minimize, close, raise, maximize), what is left in the Windows crate on purpose (top = true set_position, the *_with_border calls, transition and ghost machinery, set_opacity: border and animation subsystems are platform-owned, seam.md rule 5), and, for each query not switched (foreground_window, cursor_pos, monitors, window, monitor_from_point), what the trait would need so step 9 can decide. Docs only. --- docs/dev/backend-switch.md | 48 +++++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/docs/dev/backend-switch.md b/docs/dev/backend-switch.md index b60b26d2..c817f644 100644 --- a/docs/dev/backend-switch.md +++ b/docs/dev/backend-switch.md @@ -5,17 +5,39 @@ Step 8 of the unified-binaries plan. `komorebi::windows_backend::backend()` retu is switched one cluster at a time; each switch is its own revision marked BEHAVIOUR. What every switched call changes in the Windows daemon: `WindowsBackend` first asks `IsWindow` and -fails with `Error::WindowGone` for a dead window, and a failure of a window that died meanwhile is -reported as `WindowGone` (the error text changes from the Win32 one). Call sites use `?` or ignore the -result; none inspects the error. The operations return `Result` where `Window::hide`, `restore` and -`minimize` returned `()`: those sites ignore it (`let _ =`), as the old code could not fail. +fails with `Error::WindowGone` for a dead window (hide, restore, minimize, maximize and the other `()` +returning operations are then skipped: before, `Window::hide` of a dead window still ran +`ShowWindow` on it, a no-op, and recorded its handle in `HIDDEN_HWNDS`), and a failure of a window +that died meanwhile is reported as `WindowGone` (the error text changes from the Win32 one). Call sites +use `?` or ignore the result; none inspects the error. `frame` is the exception: it does not ask +`IsWindow` first, so the Win32 error is what callers get. -| Cluster | Operation | Status | Sites | Left on `Window` / `WindowsApi`, and why | e2e needed | -|---|---|---|---|---|---| -| focus | `focus(id, mouse_follows)` | switched | process_event 4, process_command 3, workspace 7, window_manager 24, focus_manager 1, stackbar 1 | `animation/transition.rs:534` calls `Window::focus` from inside the slide-in code that `Window::focus` itself defers to | commands, focus, focus_follows_mouse, stacking, workspaces, lifecycle | -| frame | `set_rect(id, rect)` | switched for `top = false` | workspace.rs (layout update), stackbar tab click | `set_position(.., true)` callers (window.rs `move_to_area`/`center`, workspace maximize area): the shared `set_rect` has no `top` flag | commands, resize, layouts, stacking, scrolling, workspaces | -| frame | `window_rect(id)` | NOT switched | 0 of about 60 | the shared `window_rect` is built on `window(id)`, which asks title, class, exe and path of the window, gives `None` for a failure and the call sites rely on `Err` or `unwrap_or_default`. Needs a cheap frame query on the trait (a `frame(id) -> Result`) or an override of the provided method with an error | | -| hide / show | `hide`, `restore` | switched for the plain forms | container, workspace, monitor, process_command, process_event, window_manager (23) | `hide_with_border` and `restore_with_border` (no border flag in the trait); `animation/transition.rs` and `ghost_dispatcher.rs` (inside the slide-in machinery); the `Container`/`Workspace` methods stay, they call these | commands, workspaces, stacking, lifecycle_hidden | -| hide / show | `minimize`, `close`, `raise` | switched | process_command (close 1, minimize 1, raise 4), monitor_reconciliator (minimize 4) | | commands, monitor reconciliation, lifecycle | -| hide / show | `unminimize`, `maximize` | not switched | | `unminimize` has no daemon caller (the daemon uses `restore`); `maximize`/`unmaximize` need the `Capability::Maximize` check and keep their own bookkeeping in workspace.rs | | -| queries | `foreground_window`, `cursor_pos`, `monitors`, `monitor_from_point`, `window` | NOT switched | 0 | `WindowsApi::foreground_window` is `Result` (null handle is an `Err` with a message the callers pass on), the trait gives `Option`; `cursor_pos` is `Result` vs `Option<(i32, i32)>`; `monitors` rebuilds `MonitorInfo` (drops the `Monitor` fields the daemon needs); `monitor_from_point` is never `None` on Windows. Each switch would drop an error the caller reports or fabricate a default | | +## Switched + +| Cluster | Operation | Sites | Notes | e2e needed | +|---|---|---|---|---| +| focus | `focus(id, mouse_follows)` | 40 (process_event, process_command, workspace, window_manager, focus_manager, stackbar) | `animation/transition.rs` calls `Window::focus` from the slide-in code `Window::focus` defers to: left | commands, focus, focus_follows_mouse, stacking, workspaces, lifecycle | +| frame write | `set_rect(id, rect)` | 2 (workspace layout update, stackbar tab click) | `top = false` only | commands, resize, layouts, stacking, scrolling, workspaces | +| frame read | `frame(id)` | about 55, one revision per file: stackbar_manager (2 files), animation (snapshot, ghost_dispatcher, ghost test), live_resize, pan, scrolling, process_command, process_event, window_manager, border_manager (2 files) | `frame` is a provided method added to the trait for this (WindowsBackend: `Window::window_rect`, one DWM call; error kept). `Window::window_rect`/`WindowsApi::window_rect` remain only inside `window.rs` (the implementation, and `Window::set_position`/`move_to_area`/`center`/`focus` internals) | resize, layouts, stacking, scrolling, borders, animation, commands, lifecycle | +| hide / show | `hide`, `restore` (plain forms) | 23 | | commands, workspaces, stacking, lifecycle_hidden | +| hide / show | `minimize`, `close`, `raise` | 1 + 1 + 4 (process_command), 4 minimize (monitor_reconciliator) | | commands, monitor reconciliation, lifecycle | +| maximize | `maximize(id, bool)` | 5 (workspace.rs) | capability query already in the trait (`supports(Capability::Maximize)`, true here) | maximizing, commands, workspaces | + +## Left on purpose (platform-owned subsystems, seam.md rule 5) + +- `set_position(.., true)` (window.rs `move_to_area`, `center`, workspace maximize area): the raise-to-front + flag is a Windows detail of the layout/animation code, the shared `set_rect` has none. +- `hide_with_border`, `restore_with_border`: borders are a platform subsystem (own windows and threads). +- `animation/transition.rs`, `animation/ghost*.rs` (except the frame reads above): the DWM ghost and + slide-in machinery. +- `set_opacity`: the adapter writes the plain alpha, `Window::transparent`/`opaque` take the alpha from the + transparency manager and animate. + +## Not switched, and what the trait would need (for step 9) + +| Operation | Why it stays on the platform API | What the trait would need | +|---|---|---| +| `foreground_window` | `WindowsApi::foreground_window() -> Result`: a null handle is an `Err` whose message callers pass on; the trait has `Option` | a `Result` variant (`Error::Platform` for "no foreground window"), or accept losing the message | +| `cursor_pos` | `Result` vs `Option<(i32, i32)>`; callers `?` it | same: a `Result` return | +| `monitors` / `window` | `monitors()` rebuilds `MonitorInfo` and drops the `Monitor` fields the daemon needs (device id, serial, device, work-area offsets); `window()` asks title, class, exe, path | the daemon-side `Monitor` fields in `MonitorInfo` (or a platform extension), and for step 9 the monitor model moving to the core | +| `monitor_from_point` | never `None` on Windows (`MONITOR_DEFAULTTONEAREST`), `None` outside every monitor on KDE and macOS | an explicit "nearest" flag or two methods | From f49a335256d9c3addea54175821cf6aeffc1d027 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:11:47 -0700 Subject: [PATCH 25/33] refactor(windows): Container.windows is pub, as in KDE KDE's Container and the Windows one already have the same method set and signatures (add_window(Window), hide, restore and load_focused_window return nothing; the earlier backend() switches made hide/restore the same calls). The last field-level difference was the visibility of windows: pub on KDE, private here. Make it pub; the Ring accessors (windows(), windows_mut()) stay. Not converged, on purpose: Window::exe() is eyre::Result here and Option on KDE; it has 33 callers that use ? or Ok(..) patterns, so changing it is its own revision (not mechanical in the container alone); hwnd_from_exe (2 callers in workspace.rs) and the hwnd/WindowId parameter types wait for the shared core. Not a behaviour change. Verified: Windows clippy -D warnings via tools/fast-check PASS. --- komorebi/src/container.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs index ebb9707a..baa8f72a 100644 --- a/komorebi/src/container.rs +++ b/komorebi/src/container.rs @@ -14,7 +14,7 @@ pub struct Container { pub id: String, #[serde(default)] pub locked: bool, - windows: Ring, + pub windows: Ring, } impl_ring_elements!(Container, Window); From c87bdb724192e85600ffcfc17e46532eb59440f2 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:12:03 -0700 Subject: [PATCH 26/33] wip From a2f08e52e705f3d18c7cd2c9a8fee8ae173041ee Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:12:07 -0700 Subject: [PATCH 27/33] refactor(windows): name the long workspace arms of process_command as WindowManager methods ToggleWorkspaceLayer, CycleFocusWorkspace, CycleFocusEmptyWorkspace, CloseWorkspace, FocusLastWorkspace, FocusWorkspaceNumbers and MoveContainerToLastWorkspace / SendContainerToLastWorkspace (one method with a follow flag, as the 20-line arms differed only by true/false) become pub fn toggle_workspace_layer, cycle_focus_workspace(direction), cycle_focus_empty_workspace(direction), close_workspace, focus_last_workspace, focus_workspace_numbers(idx) and move_container_to_last_workspace(follow) in a second impl WindowManager block in process_command.rs. The arm bodies moved unchanged (dedented, ending in Ok(())); each arm is now one self.x(..)? call. Same names as kfde's table in docs/dev/core-model.md where the command is the same (focus_last_workspace and focus_workspace_numbers are Windows names). Not a behaviour change. Verified: Windows clippy -D warnings via tools/fast-check PASS. --- komorebi/src/process_command.rs | 616 ++++++++++++++++---------------- 1 file changed, 314 insertions(+), 302 deletions(-) diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index c7ec8c68..faf27621 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -59,6 +59,7 @@ use crate::build; use crate::config_generation::WorkspaceMatchingRule; use crate::core::ApplicationIdentifier; use crate::core::Axis; +use crate::core::CycleDirection; use crate::core::BorderImplementation; use crate::core::FocusFollowsMouseImplementation; use crate::core::Layout; @@ -710,59 +711,10 @@ impl WindowManager { self.adjust_workspace_padding(sizing, adjustment)?; } SocketMessage::MoveContainerToLastWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.move_container_to_workspace(last_focused_workspace, true, None)?; - } - - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); + self.move_container_to_last_workspace(true)?; } SocketMessage::SendContainerToLastWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.move_container_to_workspace(last_focused_workspace, false, None)?; - } - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); + self.move_container_to_last_workspace(false)?; } SocketMessage::MoveContainerToWorkspaceNumber(workspace_idx) => { self.move_container_to_workspace(workspace_idx, true, None)?; @@ -1084,142 +1036,16 @@ impl WindowManager { } } SocketMessage::CycleFocusWorkspace(direction) => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; - - let focused_workspace_idx = focused_monitor.focused_workspace_idx(); - let workspaces = focused_monitor.workspaces().len(); - - let workspace_idx = direction.next_idx( - focused_workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - - self.focus_workspace(workspace_idx)?; + self.cycle_focus_workspace(direction)?; } SocketMessage::CycleFocusEmptyWorkspace(direction) => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; - - let focused_workspace_idx = focused_monitor.focused_workspace_idx(); - let workspaces = focused_monitor.workspaces().len(); - - let mut empty_workspaces = vec![]; - - for (idx, w) in focused_monitor.workspaces().iter().enumerate() { - if w.is_empty() { - empty_workspaces.push(idx); - } - } - - if !empty_workspaces.is_empty() { - let mut workspace_idx = direction.next_idx( - focused_workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - - while !empty_workspaces.contains(&workspace_idx) { - workspace_idx = direction.next_idx( - workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - } - - self.focus_workspace(workspace_idx)?; - } + self.cycle_focus_empty_workspace(direction)?; } SocketMessage::CloseWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let mut can_close = false; - - if let Some(monitor) = self.focused_monitor_mut() { - let focused_workspace_idx = monitor.focused_workspace_idx(); - let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); - - if let Some(workspace) = monitor.focused_workspace() - && monitor.workspaces().len() > 1 - && workspace.containers().is_empty() - && workspace.floating_windows().is_empty() - && workspace.monocle_container.is_none() - && workspace.maximized_window.is_none() - && workspace.name.is_none() - { - can_close = true; - } - - if can_close - && monitor - .workspaces_mut() - .remove(focused_workspace_idx) - .is_some() - { - self.focus_workspace(next_focused_workspace_idx)?; - } - } + self.close_workspace()?; } SocketMessage::FocusLastWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.focus_workspace(last_focused_workspace)?; - } - - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); + self.focus_last_workspace()?; } SocketMessage::FocusWorkspaceNumber(workspace_idx) => { // This is to ensure that even on an empty workspace on a secondary monitor, the @@ -1239,28 +1065,7 @@ impl WindowManager { } } SocketMessage::FocusWorkspaceNumbers(workspace_idx) => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let focused_monitor_idx = self.focused_monitor_idx(); - - for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { - if i != focused_monitor_idx { - monitor.focus_workspace(workspace_idx)?; - monitor.load_focused_workspace(false)?; - } - } - - self.focus_workspace(workspace_idx)?; + self.focus_workspace_numbers(workspace_idx)?; } SocketMessage::FocusMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { let focused_monitor_idx = self.focused_monitor_idx(); @@ -1282,105 +1087,7 @@ impl WindowManager { } } SocketMessage::ToggleWorkspaceLayer => { - let mouse_follows_focus = self.mouse_follows_focus; - let workspace = self.focused_workspace_mut()?; - - let mut to_focus = None; - match workspace.layer { - WorkspaceLayer::Tiling => { - workspace.layer = WorkspaceLayer::Floating; - - let focused_idx = workspace.focused_floating_window_idx(); - let mut window_idx_pairs = workspace - .floating_windows_mut() - .make_contiguous() - .iter() - .enumerate() - .collect::>(); - - // Sort by window area - window_idx_pairs.sort_by_key(|(_, w)| { - let rect = backend() - .frame(WindowId::from_hwnd(w.hwnd)) - .unwrap_or_default(); - rect.right * rect.bottom - }); - window_idx_pairs.reverse(); - - for (i, window) in window_idx_pairs { - if i == focused_idx { - to_focus = Some(*window); - } else { - let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); - backend().raise(WindowId::from_hwnd(window.hwnd))?; - } - } - - if let Some(focused_window) = &to_focus { - // The focused window should be the last one raised to make sure it is - // on top - let _ = backend().restore(WindowId::from_hwnd(focused_window.hwnd)); - backend().raise(WindowId::from_hwnd(focused_window.hwnd))?; - } - - for container in workspace.containers() { - if let Some(window) = container.focused_window() { - window.lower()?; - } - } - - if let Some(monocle) = &workspace.monocle_container - && let Some(window) = monocle.focused_window() - { - window.lower()?; - } - } - WorkspaceLayer::Floating => { - workspace.layer = WorkspaceLayer::Tiling; - - if let Some(monocle) = &workspace.monocle_container { - if let Some(window) = monocle.focused_window() { - to_focus = Some(*window); - backend().raise(WindowId::from_hwnd(window.hwnd))?; - } - for window in workspace.floating_windows() { - let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); - } - } else { - let focused_container_idx = workspace.focused_container_idx(); - for (i, container) in workspace.containers_mut().iter_mut().enumerate() - { - if let Some(window) = container.focused_window() { - if i == focused_container_idx { - to_focus = Some(*window); - } - backend().raise(WindowId::from_hwnd(window.hwnd))?; - } - } - - let mut window_idx_pairs = workspace - .floating_windows_mut() - .make_contiguous() - .iter() - .collect::>(); - - // Sort by window area - window_idx_pairs.sort_by_key(|w| { - let rect = backend() - .frame(WindowId::from_hwnd(w.hwnd)) - .unwrap_or_default(); - rect.right * rect.bottom - }); - - for window in window_idx_pairs { - window.lower()?; - } - } - } - }; - if let Some(window) = to_focus { - backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; - } + self.toggle_workspace_layer()?; } SocketMessage::Stop => { self.stop(false)?; @@ -2360,6 +2067,311 @@ fn push_simple_rule(rules: &mut Vec, kind: ApplicationIdentifier, } } +// extracted-arms-impl +impl WindowManager { + pub fn move_container_to_last_workspace(&mut self, follow: bool) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.move_container_to_workspace(last_focused_workspace, follow, None)?; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + Ok(()) + } + + pub fn focus_workspace_numbers(&mut self, workspace_idx: usize) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let focused_monitor_idx = self.focused_monitor_idx(); + + for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { + if i != focused_monitor_idx { + monitor.focus_workspace(workspace_idx)?; + monitor.load_focused_workspace(false)?; + } + } + + self.focus_workspace(workspace_idx)?; + Ok(()) + } + + pub fn focus_last_workspace(&mut self) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.focus_workspace(last_focused_workspace)?; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + Ok(()) + } + + pub fn close_workspace(&mut self) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let mut can_close = false; + + if let Some(monitor) = self.focused_monitor_mut() { + let focused_workspace_idx = monitor.focused_workspace_idx(); + let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); + + if let Some(workspace) = monitor.focused_workspace() + && monitor.workspaces().len() > 1 + && workspace.containers().is_empty() + && workspace.floating_windows().is_empty() + && workspace.monocle_container.is_none() + && workspace.maximized_window.is_none() + && workspace.name.is_none() + { + can_close = true; + } + + if can_close + && monitor + .workspaces_mut() + .remove(focused_workspace_idx) + .is_some() + { + self.focus_workspace(next_focused_workspace_idx)?; + } + } + Ok(()) + } + + pub fn cycle_focus_empty_workspace(&mut self, direction: CycleDirection) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let mut empty_workspaces = vec![]; + + for (idx, w) in focused_monitor.workspaces().iter().enumerate() { + if w.is_empty() { + empty_workspaces.push(idx); + } + } + + if !empty_workspaces.is_empty() { + let mut workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces).ok_or_eyre("there must be at least one workspace")?, + ); + + while !empty_workspaces.contains(&workspace_idx) { + workspace_idx = direction.next_idx( + workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + } + + self.focus_workspace(workspace_idx)?; + } + Ok(()) + } + + pub fn cycle_focus_workspace(&mut self, direction: CycleDirection) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces).ok_or_eyre("there must be at least one workspace")?, + ); + + self.focus_workspace(workspace_idx)?; + Ok(()) + } + + pub fn toggle_workspace_layer(&mut self) -> eyre::Result<()> { + let mouse_follows_focus = self.mouse_follows_focus; + let workspace = self.focused_workspace_mut()?; + + let mut to_focus = None; + match workspace.layer { + WorkspaceLayer::Tiling => { + workspace.layer = WorkspaceLayer::Floating; + + let focused_idx = workspace.focused_floating_window_idx(); + let mut window_idx_pairs = workspace + .floating_windows_mut() + .make_contiguous() + .iter() + .enumerate() + .collect::>(); + + // Sort by window area + window_idx_pairs.sort_by_key(|(_, w)| { + let rect = backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .unwrap_or_default(); + rect.right * rect.bottom + }); + window_idx_pairs.reverse(); + + for (i, window) in window_idx_pairs { + if i == focused_idx { + to_focus = Some(*window); + } else { + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); + backend().raise(WindowId::from_hwnd(window.hwnd))?; + } + } + + if let Some(focused_window) = &to_focus { + // The focused window should be the last one raised to make sure it is + // on top + let _ = backend().restore(WindowId::from_hwnd(focused_window.hwnd)); + backend().raise(WindowId::from_hwnd(focused_window.hwnd))?; + } + + for container in workspace.containers() { + if let Some(window) = container.focused_window() { + window.lower()?; + } + } + + if let Some(monocle) = &workspace.monocle_container + && let Some(window) = monocle.focused_window() + { + window.lower()?; + } + } + WorkspaceLayer::Floating => { + workspace.layer = WorkspaceLayer::Tiling; + + if let Some(monocle) = &workspace.monocle_container { + if let Some(window) = monocle.focused_window() { + to_focus = Some(*window); + backend().raise(WindowId::from_hwnd(window.hwnd))?; + } + for window in workspace.floating_windows() { + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); + } + } else { + let focused_container_idx = workspace.focused_container_idx(); + for (i, container) in workspace.containers_mut().iter_mut().enumerate() { + if let Some(window) = container.focused_window() { + if i == focused_container_idx { + to_focus = Some(*window); + } + backend().raise(WindowId::from_hwnd(window.hwnd))?; + } + } + + let mut window_idx_pairs = workspace + .floating_windows_mut() + .make_contiguous() + .iter() + .collect::>(); + + // Sort by window area + window_idx_pairs.sort_by_key(|w| { + let rect = backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .unwrap_or_default(); + rect.right * rect.bottom + }); + + for window in window_idx_pairs { + window.lower()?; + } + } + } + }; + if let Some(window) = to_focus { + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; + } + Ok(()) + } +} + #[cfg(test)] mod tests { use super::push_simple_rule; From 2a5787c2e29de6a1abad3f7883124d4da737c9b3 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:13:40 -0700 Subject: [PATCH 28/33] refactor(windows): name the rule and layout-ratio arms of process_command as WindowManager methods IgnoreRule, SessionFloatRule and LayoutRatios become add_ignore_rule(identifier, id), add_session_float_rule() and set_layout_ratios(columns, rows), the names kfde used. Bodies moved unchanged; each arm is one self.x(..)? call. Not a behaviour change. Verified: Windows clippy -D warnings via tools/fast-check PASS. --- komorebi/src/process_command.rs | 230 +++++++++++++++++--------------- 1 file changed, 125 insertions(+), 105 deletions(-) diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index faf27621..a0bf4062 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -59,8 +59,8 @@ use crate::build; use crate::config_generation::WorkspaceMatchingRule; use crate::core::ApplicationIdentifier; use crate::core::Axis; -use crate::core::CycleDirection; use crate::core::BorderImplementation; +use crate::core::CycleDirection; use crate::core::FocusFollowsMouseImplementation; use crate::core::Layout; use crate::core::LayoutOptions; @@ -585,36 +585,7 @@ impl WindowManager { push_simple_rule(&mut manage_identifiers, identifier, id); } SocketMessage::SessionFloatRule => { - let foreground_window = WindowsApi::foreground_window()?; - let window = Window::from(foreground_window); - if let (Ok(exe), Ok(title), Ok(class)) = - (window.exe(), window.title(), window.class()) - { - let rule = MatchingRule::Composite(vec![ - IdWithIdentifier { - kind: ApplicationIdentifier::Exe, - id: exe, - matching_strategy: Option::from(MatchingStrategy::Equals), - }, - IdWithIdentifier { - kind: ApplicationIdentifier::Title, - id: title, - matching_strategy: Option::from(MatchingStrategy::Equals), - }, - IdWithIdentifier { - kind: ApplicationIdentifier::Class, - id: class, - matching_strategy: Option::from(MatchingStrategy::Equals), - }, - ]); - - let mut floating_applications = FLOATING_APPLICATIONS.lock(); - floating_applications.push(rule.clone()); - let mut session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); - session_floating_applications.push(rule.clone()); - - self.toggle_float(true)?; - } + self.add_session_float_rule()?; } SocketMessage::SessionFloatRules => { let session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); @@ -632,59 +603,7 @@ impl WindowManager { session_floating_applications.clear() } SocketMessage::IgnoreRule(identifier, ref id) => { - let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); - - push_simple_rule(&mut ignore_identifiers, identifier, id); - - let offset = self.work_area_offset; - - let mut hwnds_to_purge = vec![]; - for (i, monitor) in self.monitors().iter().enumerate() { - for container in monitor - .focused_workspace() - .ok_or_eyre("there is no workspace")? - .containers() - { - for window in container.windows() { - match identifier { - ApplicationIdentifier::Path => { - if window.path()? == *id { - hwnds_to_purge.push((i, window.hwnd)); - } - } - ApplicationIdentifier::Exe => { - if window.exe()? == *id { - hwnds_to_purge.push((i, window.hwnd)); - } - } - ApplicationIdentifier::Class => { - if window.class()? == *id { - hwnds_to_purge.push((i, window.hwnd)); - } - } - ApplicationIdentifier::Title => { - if window.title()? == *id { - hwnds_to_purge.push((i, window.hwnd)); - } - } - } - } - } - } - - for (monitor_idx, hwnd) in hwnds_to_purge { - let monitor = self - .monitors_mut() - .get_mut(monitor_idx) - .ok_or_eyre("there is no monitor")?; - - monitor - .focused_workspace_mut() - .ok_or_eyre("there is no focused workspace")? - .remove_window(hwnd)?; - - monitor.update_focused_workspace(offset)?; - } + self.add_ignore_rule(identifier, id)?; } SocketMessage::FocusedWorkspaceContainerPadding(adjustment) => { let focused_monitor_idx = self.focused_monitor_idx(); @@ -916,27 +835,7 @@ impl WindowManager { SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, SocketMessage::CycleLayout(direction) => self.cycle_layout(direction)?, SocketMessage::LayoutRatios(ref columns, ref rows) => { - use crate::core::validate_ratios; - - let focused_workspace = self.focused_workspace_mut()?; - - let mut options = focused_workspace.layout_options.unwrap_or(LayoutOptions { - scrolling: None, - grid: None, - column_ratios: None, - row_ratios: None, - }); - - if let Some(cols) = columns { - options.column_ratios = Some(validate_ratios(cols)); - } - - if let Some(rws) = rows { - options.row_ratios = Some(validate_ratios(rws)); - } - - focused_workspace.layout_options = Some(options); - self.update_focused_workspace(false, false)?; + self.set_layout_ratios(columns, rows)?; } SocketMessage::ChangeLayoutCustom(ref path) => { self.change_workspace_custom_layout(path)?; @@ -2069,6 +1968,127 @@ fn push_simple_rule(rules: &mut Vec, kind: ApplicationIdentifier, // extracted-arms-impl impl WindowManager { + pub fn set_layout_ratios( + &mut self, + columns: &Option>, + rows: &Option>, + ) -> eyre::Result<()> { + use crate::core::validate_ratios; + + let focused_workspace = self.focused_workspace_mut()?; + + let mut options = focused_workspace.layout_options.unwrap_or(LayoutOptions { + scrolling: None, + grid: None, + column_ratios: None, + row_ratios: None, + }); + + if let Some(cols) = columns { + options.column_ratios = Some(validate_ratios(cols)); + } + + if let Some(rws) = rows { + options.row_ratios = Some(validate_ratios(rws)); + } + + focused_workspace.layout_options = Some(options); + self.update_focused_workspace(false, false)?; + Ok(()) + } + + pub fn add_session_float_rule(&mut self) -> eyre::Result<()> { + let foreground_window = WindowsApi::foreground_window()?; + let window = Window::from(foreground_window); + if let (Ok(exe), Ok(title), Ok(class)) = (window.exe(), window.title(), window.class()) { + let rule = MatchingRule::Composite(vec![ + IdWithIdentifier { + kind: ApplicationIdentifier::Exe, + id: exe, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + IdWithIdentifier { + kind: ApplicationIdentifier::Title, + id: title, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + IdWithIdentifier { + kind: ApplicationIdentifier::Class, + id: class, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + ]); + + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + floating_applications.push(rule.clone()); + let mut session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); + session_floating_applications.push(rule.clone()); + + self.toggle_float(true)?; + } + Ok(()) + } + + pub fn add_ignore_rule( + &mut self, + identifier: ApplicationIdentifier, + id: &str, + ) -> eyre::Result<()> { + let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + + push_simple_rule(&mut ignore_identifiers, identifier, id); + + let offset = self.work_area_offset; + + let mut hwnds_to_purge = vec![]; + for (i, monitor) in self.monitors().iter().enumerate() { + for container in monitor + .focused_workspace() + .ok_or_eyre("there is no workspace")? + .containers() + { + for window in container.windows() { + match identifier { + ApplicationIdentifier::Path => { + if window.path()? == *id { + hwnds_to_purge.push((i, window.hwnd)); + } + } + ApplicationIdentifier::Exe => { + if window.exe()? == *id { + hwnds_to_purge.push((i, window.hwnd)); + } + } + ApplicationIdentifier::Class => { + if window.class()? == *id { + hwnds_to_purge.push((i, window.hwnd)); + } + } + ApplicationIdentifier::Title => { + if window.title()? == *id { + hwnds_to_purge.push((i, window.hwnd)); + } + } + } + } + } + } + + for (monitor_idx, hwnd) in hwnds_to_purge { + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + monitor + .focused_workspace_mut() + .ok_or_eyre("there is no focused workspace")? + .remove_window(hwnd)?; + + monitor.update_focused_workspace(offset)?; + } + Ok(()) + } pub fn move_container_to_last_workspace(&mut self, follow: bool) -> eyre::Result<()> { // This is to ensure that even on an empty workspace on a secondary monitor, the // secondary monitor where the cursor is focused will be used as the target for From bc2789de19399ca7ae33699d6d6899b6dd1550cf Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:13:59 -0700 Subject: [PATCH 29/33] refactor(windows): name the focus, resize and focus-follows-mouse arms of process_command as WindowManager methods EagerFocus, ResizeWindowAxis, FocusFollowsMouse and ToggleFocusFollowsMouse become eager_focus(exe), resize_window_axis(axis, sizing), focus_follows_mouse(implementation, enable) and toggle_focus_follows_mouse(implementation). Bodies moved unchanged. Not a behaviour change. Verified: Windows clippy -D warnings via tools/fast-check PASS. --- komorebi/src/process_command.rs | 546 ++++++++++++++++---------------- 1 file changed, 268 insertions(+), 278 deletions(-) diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index a0bf4062..68dcd84a 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -243,84 +243,7 @@ impl WindowManager { self.promote_container_to_front()? } SocketMessage::EagerFocus(ref exe) => { - let focused_monitor_idx = self.focused_monitor_idx(); - - let mut window_location = None; - let mut monitor_to_focus = None; - let mut needs_workspace_loading = false; - - 'search: for (monitor_idx, monitor) in self.monitors_mut().iter_mut().enumerate() { - for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { - if let Some(location) = workspace.location_from_exe(exe) { - window_location = Some(location); - - if monitor_idx != focused_monitor_idx { - monitor_to_focus = Some(monitor_idx); - } - - // Focus workspace if it is not already the focused one, without - // loading it so that we don't give focus to the wrong window, we will - // load it later after focusing the wanted window - let focused_ws_idx = monitor.focused_workspace_idx(); - if focused_ws_idx != workspace_idx { - monitor.last_focused_workspace = Option::from(focused_ws_idx); - monitor.focus_workspace(workspace_idx)?; - needs_workspace_loading = true; - } - - break 'search; - } - } - } - - if let Some(monitor_idx) = monitor_to_focus { - self.focus_monitor(monitor_idx)?; - } - - if let Some(location) = window_location { - match location { - WorkspaceWindowLocation::Monocle(window_idx) => { - self.focus_container_window(window_idx)?; - } - WorkspaceWindowLocation::Maximized => { - if let Some(window) = - &mut self.focused_workspace_mut()?.maximized_window - { - backend().focus( - WindowId::from_hwnd(window.hwnd), - self.mouse_follows_focus, - )?; - } - } - WorkspaceWindowLocation::Container(container_idx, window_idx) => { - let focused_container_idx = self.focused_container_idx()?; - if container_idx != focused_container_idx { - self.focused_workspace_mut()?.focus_container(container_idx); - } - - self.focus_container_window(window_idx)?; - } - WorkspaceWindowLocation::Floating(window_idx) => { - if let Some(window) = self - .focused_workspace_mut()? - .floating_windows_mut() - .get_mut(window_idx) - { - backend().focus( - WindowId::from_hwnd(window.hwnd), - self.mouse_follows_focus, - )?; - } - } - } - - if needs_workspace_loading { - let mouse_follows_focus = self.mouse_follows_focus; - if let Some(monitor) = self.focused_monitor_mut() { - monitor.load_focused_workspace(mouse_follows_focus)?; - } - } - } + self.eager_focus(exe)?; } SocketMessage::FocusWindow(direction) => { let focused_workspace = self.focused_workspace()?; @@ -1131,208 +1054,13 @@ impl WindowManager { self.resize_window(direction, sizing, self.resize_delta, true)?; } SocketMessage::ResizeWindowAxis(axis, sizing) => { - let _in_place = live_resize::InPlace::new(); - - // If the user has a custom layout, allow for the resizing of the primary column - // with this signal - let workspace = self.focused_workspace_mut()?; - let container_len = workspace.containers().len(); - let no_layout_rules = workspace.layout_rules.is_empty(); - - if let Layout::Custom(custom) = &mut workspace.layout { - if matches!(axis, Axis::Horizontal) { - #[allow(clippy::cast_precision_loss)] - let percentage = custom - .primary_width_percentage() - .unwrap_or(100.0 / (custom.len() as f32)); - - if no_layout_rules { - match sizing { - Sizing::Increase => { - custom.set_primary_width_percentage(percentage + 5.0); - } - Sizing::Decrease => { - custom.set_primary_width_percentage(percentage - 5.0); - } - } - } else { - for rule in &mut workspace.layout_rules { - if container_len >= rule.0 - && let Layout::Custom(ref mut custom) = rule.1 - { - match sizing { - Sizing::Increase => { - custom.set_primary_width_percentage(percentage + 5.0); - } - Sizing::Decrease => { - custom.set_primary_width_percentage(percentage - 5.0); - } - } - } - } - } - } - // Otherwise proceed with the resizing logic for individual window containers in the - // assumed BSP layout - } else { - match axis { - Axis::Horizontal => { - self.resize_window( - OperationDirection::Left, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Right, - sizing, - self.resize_delta, - false, - )?; - } - Axis::Vertical => { - self.resize_window( - OperationDirection::Up, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Down, - sizing, - self.resize_delta, - false, - )?; - } - Axis::HorizontalAndVertical => { - self.resize_window( - OperationDirection::Left, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Right, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Up, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Down, - sizing, - self.resize_delta, - false, - )?; - } - } - } - - self.update_focused_workspace(false, false)?; + self.resize_window_axis(axis, sizing)?; } - SocketMessage::FocusFollowsMouse(mut implementation, enable) => { - if !CUSTOM_FFM.load(Ordering::SeqCst) { - tracing::warn!( - "komorebi was not started with the --ffm flag, so the komorebi implementation of focus follows mouse cannot be enabled; defaulting to windows implementation" - ); - implementation = FocusFollowsMouseImplementation::Windows; - } - - match implementation { - FocusFollowsMouseImplementation::Komorebi => { - if WindowsApi::focus_follows_mouse()? { - tracing::warn!( - "the komorebi implementation of focus follows mouse cannot be enabled while the windows implementation is enabled" - ); - } else if enable { - self.focus_follows_mouse = Option::from(implementation); - } else { - self.focus_follows_mouse = None; - self.has_pending_raise_op = false; - } - } - FocusFollowsMouseImplementation::Windows => { - if matches!( - self.focus_follows_mouse, - Some(FocusFollowsMouseImplementation::Komorebi) - ) { - tracing::warn!( - "the windows implementation of focus follows mouse cannot be enabled while the komorebi implementation is enabled" - ); - } else if enable { - WindowsApi::enable_focus_follows_mouse()?; - self.focus_follows_mouse = - Option::from(FocusFollowsMouseImplementation::Windows); - } else { - WindowsApi::disable_focus_follows_mouse()?; - self.focus_follows_mouse = None; - } - } - } + SocketMessage::FocusFollowsMouse(implementation, enable) => { + self.focus_follows_mouse(implementation, enable)?; } - SocketMessage::ToggleFocusFollowsMouse(mut implementation) => { - if !CUSTOM_FFM.load(Ordering::SeqCst) { - tracing::warn!( - "komorebi was not started with the --ffm flag, so the komorebi implementation of focus follows mouse cannot be toggled; defaulting to windows implementation" - ); - implementation = FocusFollowsMouseImplementation::Windows; - } - - match implementation { - FocusFollowsMouseImplementation::Komorebi => { - if WindowsApi::focus_follows_mouse()? { - tracing::warn!( - "the komorebi implementation of focus follows mouse cannot be toggled while the windows implementation is enabled" - ); - } else { - match self.focus_follows_mouse { - None => { - self.focus_follows_mouse = Option::from(implementation); - self.has_pending_raise_op = false; - } - Some(FocusFollowsMouseImplementation::Komorebi) => { - self.focus_follows_mouse = None; - } - Some(FocusFollowsMouseImplementation::Windows) => { - tracing::warn!( - "ignoring command that could mix different focus follows mouse implementations" - ); - } - } - } - } - FocusFollowsMouseImplementation::Windows => { - if matches!( - self.focus_follows_mouse, - Some(FocusFollowsMouseImplementation::Komorebi) - ) { - tracing::warn!( - "the windows implementation of focus follows mouse cannot be toggled while the komorebi implementation is enabled" - ); - } else { - match self.focus_follows_mouse { - None => { - WindowsApi::enable_focus_follows_mouse()?; - self.focus_follows_mouse = Option::from(implementation); - } - Some(FocusFollowsMouseImplementation::Windows) => { - WindowsApi::disable_focus_follows_mouse()?; - self.focus_follows_mouse = None; - } - Some(FocusFollowsMouseImplementation::Komorebi) => { - tracing::warn!( - "ignoring command that could mix different focus follows mouse implementations" - ); - } - } - } - } - } + SocketMessage::ToggleFocusFollowsMouse(implementation) => { + self.toggle_focus_follows_mouse(implementation)?; } SocketMessage::ReloadConfiguration => { Self::reload_configuration(); @@ -1968,6 +1696,268 @@ fn push_simple_rule(rules: &mut Vec, kind: ApplicationIdentifier, // extracted-arms-impl impl WindowManager { + pub fn focus_follows_mouse( + &mut self, + mut implementation: FocusFollowsMouseImplementation, + enable: bool, + ) -> eyre::Result<()> { + if !CUSTOM_FFM.load(Ordering::SeqCst) { + tracing::warn!( + "komorebi was not started with the --ffm flag, so the komorebi implementation of focus follows mouse cannot be enabled; defaulting to windows implementation" + ); + implementation = FocusFollowsMouseImplementation::Windows; + } + + match implementation { + FocusFollowsMouseImplementation::Komorebi => { + if WindowsApi::focus_follows_mouse()? { + tracing::warn!( + "the komorebi implementation of focus follows mouse cannot be enabled while the windows implementation is enabled" + ); + } else if enable { + self.focus_follows_mouse = Option::from(implementation); + } else { + self.focus_follows_mouse = None; + self.has_pending_raise_op = false; + } + } + FocusFollowsMouseImplementation::Windows => { + if matches!( + self.focus_follows_mouse, + Some(FocusFollowsMouseImplementation::Komorebi) + ) { + tracing::warn!( + "the windows implementation of focus follows mouse cannot be enabled while the komorebi implementation is enabled" + ); + } else if enable { + WindowsApi::enable_focus_follows_mouse()?; + self.focus_follows_mouse = + Option::from(FocusFollowsMouseImplementation::Windows); + } else { + WindowsApi::disable_focus_follows_mouse()?; + self.focus_follows_mouse = None; + } + } + } + Ok(()) + } + + pub fn toggle_focus_follows_mouse( + &mut self, + mut implementation: FocusFollowsMouseImplementation, + ) -> eyre::Result<()> { + if !CUSTOM_FFM.load(Ordering::SeqCst) { + tracing::warn!( + "komorebi was not started with the --ffm flag, so the komorebi implementation of focus follows mouse cannot be toggled; defaulting to windows implementation" + ); + implementation = FocusFollowsMouseImplementation::Windows; + } + + match implementation { + FocusFollowsMouseImplementation::Komorebi => { + if WindowsApi::focus_follows_mouse()? { + tracing::warn!( + "the komorebi implementation of focus follows mouse cannot be toggled while the windows implementation is enabled" + ); + } else { + match self.focus_follows_mouse { + None => { + self.focus_follows_mouse = Option::from(implementation); + self.has_pending_raise_op = false; + } + Some(FocusFollowsMouseImplementation::Komorebi) => { + self.focus_follows_mouse = None; + } + Some(FocusFollowsMouseImplementation::Windows) => { + tracing::warn!( + "ignoring command that could mix different focus follows mouse implementations" + ); + } + } + } + } + FocusFollowsMouseImplementation::Windows => { + if matches!( + self.focus_follows_mouse, + Some(FocusFollowsMouseImplementation::Komorebi) + ) { + tracing::warn!( + "the windows implementation of focus follows mouse cannot be toggled while the komorebi implementation is enabled" + ); + } else { + match self.focus_follows_mouse { + None => { + WindowsApi::enable_focus_follows_mouse()?; + self.focus_follows_mouse = Option::from(implementation); + } + Some(FocusFollowsMouseImplementation::Windows) => { + WindowsApi::disable_focus_follows_mouse()?; + self.focus_follows_mouse = None; + } + Some(FocusFollowsMouseImplementation::Komorebi) => { + tracing::warn!( + "ignoring command that could mix different focus follows mouse implementations" + ); + } + } + } + } + } + Ok(()) + } + + pub fn resize_window_axis(&mut self, axis: Axis, sizing: Sizing) -> eyre::Result<()> { + let _in_place = live_resize::InPlace::new(); + + // If the user has a custom layout, allow for the resizing of the primary column + // with this signal + let workspace = self.focused_workspace_mut()?; + let container_len = workspace.containers().len(); + let no_layout_rules = workspace.layout_rules.is_empty(); + + if let Layout::Custom(custom) = &mut workspace.layout { + if matches!(axis, Axis::Horizontal) { + #[allow(clippy::cast_precision_loss)] + let percentage = custom + .primary_width_percentage() + .unwrap_or(100.0 / (custom.len() as f32)); + + if no_layout_rules { + match sizing { + Sizing::Increase => { + custom.set_primary_width_percentage(percentage + 5.0); + } + Sizing::Decrease => { + custom.set_primary_width_percentage(percentage - 5.0); + } + } + } else { + for rule in &mut workspace.layout_rules { + if container_len >= rule.0 + && let Layout::Custom(ref mut custom) = rule.1 + { + match sizing { + Sizing::Increase => { + custom.set_primary_width_percentage(percentage + 5.0); + } + Sizing::Decrease => { + custom.set_primary_width_percentage(percentage - 5.0); + } + } + } + } + } + } + // Otherwise proceed with the resizing logic for individual window containers in the + // assumed BSP layout + } else { + match axis { + Axis::Horizontal => { + self.resize_window(OperationDirection::Left, sizing, self.resize_delta, false)?; + self.resize_window( + OperationDirection::Right, + sizing, + self.resize_delta, + false, + )?; + } + Axis::Vertical => { + self.resize_window(OperationDirection::Up, sizing, self.resize_delta, false)?; + self.resize_window(OperationDirection::Down, sizing, self.resize_delta, false)?; + } + Axis::HorizontalAndVertical => { + self.resize_window(OperationDirection::Left, sizing, self.resize_delta, false)?; + self.resize_window( + OperationDirection::Right, + sizing, + self.resize_delta, + false, + )?; + self.resize_window(OperationDirection::Up, sizing, self.resize_delta, false)?; + self.resize_window(OperationDirection::Down, sizing, self.resize_delta, false)?; + } + } + } + + self.update_focused_workspace(false, false)?; + Ok(()) + } + + pub fn eager_focus(&mut self, exe: &str) -> eyre::Result<()> { + let focused_monitor_idx = self.focused_monitor_idx(); + + let mut window_location = None; + let mut monitor_to_focus = None; + let mut needs_workspace_loading = false; + + 'search: for (monitor_idx, monitor) in self.monitors_mut().iter_mut().enumerate() { + for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { + if let Some(location) = workspace.location_from_exe(exe) { + window_location = Some(location); + + if monitor_idx != focused_monitor_idx { + monitor_to_focus = Some(monitor_idx); + } + + // Focus workspace if it is not already the focused one, without + // loading it so that we don't give focus to the wrong window, we will + // load it later after focusing the wanted window + let focused_ws_idx = monitor.focused_workspace_idx(); + if focused_ws_idx != workspace_idx { + monitor.last_focused_workspace = Option::from(focused_ws_idx); + monitor.focus_workspace(workspace_idx)?; + needs_workspace_loading = true; + } + + break 'search; + } + } + } + + if let Some(monitor_idx) = monitor_to_focus { + self.focus_monitor(monitor_idx)?; + } + + if let Some(location) = window_location { + match location { + WorkspaceWindowLocation::Monocle(window_idx) => { + self.focus_container_window(window_idx)?; + } + WorkspaceWindowLocation::Maximized => { + if let Some(window) = &mut self.focused_workspace_mut()?.maximized_window { + backend() + .focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; + } + } + WorkspaceWindowLocation::Container(container_idx, window_idx) => { + let focused_container_idx = self.focused_container_idx()?; + if container_idx != focused_container_idx { + self.focused_workspace_mut()?.focus_container(container_idx); + } + + self.focus_container_window(window_idx)?; + } + WorkspaceWindowLocation::Floating(window_idx) => { + if let Some(window) = self + .focused_workspace_mut()? + .floating_windows_mut() + .get_mut(window_idx) + { + backend() + .focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; + } + } + } + + if needs_workspace_loading { + let mouse_follows_focus = self.mouse_follows_focus; + if let Some(monitor) = self.focused_monitor_mut() { + monitor.load_focused_workspace(mouse_follows_focus)?; + } + } + } + Ok(()) + } pub fn set_layout_ratios( &mut self, columns: &Option>, From 56e9bf0ff727d725d50449bc89faf243815901a8 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:14:57 -0700 Subject: [PATCH 30/33] refactor(windows): name the query, configuration and border-colour arms of process_command as WindowManager methods Query, ReplaceConfiguration and BorderColour become answer_query(query, reply), replace_configuration(config) and set_border_colour(kind, r, g, b). Bodies moved unchanged. force_update_borders is a local of process_command: the border colour arm sets it after calling the (infallible) method, and replace_configuration returns whether it replaced the configuration, which is exactly where the arm used to set it (Result, where kfde's returns Result<()>). Not a behaviour change. Verified: Windows clippy -D warnings via tools/fast-check PASS. --- komorebi/src/process_command.rs | 331 +++++++++++++++++--------------- 1 file changed, 172 insertions(+), 159 deletions(-) diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 68dcd84a..61b9372b 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -998,56 +998,7 @@ impl WindowManager { reply.write_all(monitors_state.as_bytes())?; } SocketMessage::Query(query) => { - let response = match query { - StateQuery::FocusedMonitorIndex => self.focused_monitor_idx().to_string(), - StateQuery::FocusedWorkspaceIndex => self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx() - .to_string(), - StateQuery::FocusedContainerIndex => self - .focused_workspace()? - .focused_container_idx() - .to_string(), - StateQuery::FocusedWindowIndex => { - self.focused_container()?.focused_window_idx().to_string() - } - StateQuery::FocusedWorkspaceName => { - let focused_monitor = - self.focused_monitor().ok_or_eyre("there is no monitor")?; - - focused_monitor - .focused_workspace_name() - .unwrap_or_else(|| focused_monitor.focused_workspace_idx().to_string()) - } - StateQuery::Version => build::RUST_VERSION.to_string(), - StateQuery::FocusedWorkspaceLayout => { - let focused_monitor = - self.focused_monitor().ok_or_eyre("there is no monitor")?; - - focused_monitor.focused_workspace_layout().map_or_else( - || "None".to_string(), - |layout| match layout { - Layout::Default(default_layout) => default_layout.to_string(), - Layout::Custom(_) => "Custom".to_string(), - }, - ) - } - StateQuery::FocusedContainerKind => { - match self.focused_workspace()?.focused_container() { - None => "None".to_string(), - Some(container) => { - if container.windows().len() > 1 { - "Stack".to_string() - } else { - "Single".to_string() - } - } - } - } - }; - - reply.write_all(response.as_bytes())?; + self.answer_query(query, &mut reply)?; } SocketMessage::ResizeWindowEdge(direction, sizing) => { let _in_place = live_resize::InPlace::new(); @@ -1067,94 +1018,7 @@ impl WindowManager { force_update_borders = true; } SocketMessage::ReplaceConfiguration(ref config) => { - // Check that this is a valid static config file first - if StaticConfig::read(config).is_ok() { - // Clear workspace rules; these will need to be replaced - WORKSPACE_MATCHING_RULES.lock().clear(); - // Pause so that restored windows come to the foreground from all workspaces - self.is_paused = true; - // Bring all windows to the foreground - self.restore_all_windows(false)?; - - // Create a new wm from the config path - let mut wm = StaticConfig::preload( - config, - winevent_listener::event_rx(), - self.command_listener.try_clone().ok(), - )?; - - // Initialize the new wm - wm.init()?; - - wm.restore_all_windows(true)?; - - // This is equivalent to StaticConfig::postload for this use case - StaticConfig::reload(config, &mut wm)?; - - // Set self to the new wm instance - *self = wm; - - // check if there are any bars - let mut system = sysinfo::System::new_all(); - system.refresh_processes(sysinfo::ProcessesToUpdate::All, true); - - let has_bar = system - .processes_by_name("komorebi-bar.exe".as_ref()) - .next() - .is_some(); - - // stop bar(s) - if has_bar { - let script = r" -Stop-Process -Name:komorebi-bar -ErrorAction SilentlyContinue - "; - match powershell_script::run(script) { - Ok(_) => { - println!("{script}"); - - // start new bar(s) - let mut config = StaticConfig::read(config)?; - if let Some(display_bar_configurations) = - &mut config.bar_configurations - { - for config_file_path in &mut *display_bar_configurations { - let script = r#"Start-Process "komorebi-bar" '"--config" "CONFIGFILE"' -WindowStyle hidden"# - .replace("CONFIGFILE", &config_file_path.to_string_lossy()); - - match powershell_script::run(&script) { - Ok(_) => { - println!("{script}"); - } - Err(error) => { - println!("Error: {error}"); - } - } - } - } else { - let script = r" -if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) -{ - Start-Process komorebi-bar -WindowStyle hidden -} - "; - match powershell_script::run(script) { - Ok(_) => { - println!("{script}"); - } - Err(error) => { - println!("Error: {error}"); - } - } - } - } - Err(error) => { - println!("Error: {error}"); - } - } - } - - force_update_borders = true; - } + force_update_borders = self.replace_configuration(config)?; } SocketMessage::ReloadStaticConfiguration(ref pathbuf) => { self.reload_static_configuration(pathbuf)?; @@ -1416,27 +1280,7 @@ if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) } } SocketMessage::BorderColour(kind, r, g, b) => { - match kind { - WindowKind::Single => { - border_manager::FOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Stack => { - border_manager::STACK.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Monocle => { - border_manager::MONOCLE.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Unfocused => { - border_manager::UNFOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::UnfocusedLocked => { - border_manager::UNFOCUSED_LOCKED - .store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Floating => { - border_manager::FLOATING.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - } + self.set_border_colour(kind, r, g, b); force_update_borders = true; } SocketMessage::BorderStyle(style) => { @@ -1696,6 +1540,175 @@ fn push_simple_rule(rules: &mut Vec, kind: ApplicationIdentifier, // extracted-arms-impl impl WindowManager { + pub fn set_border_colour(&mut self, kind: WindowKind, r: u32, g: u32, b: u32) { + match kind { + WindowKind::Single => { + border_manager::FOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Stack => { + border_manager::STACK.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Monocle => { + border_manager::MONOCLE.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Unfocused => { + border_manager::UNFOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::UnfocusedLocked => { + border_manager::UNFOCUSED_LOCKED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Floating => { + border_manager::FLOATING.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + } + } + + pub fn replace_configuration(&mut self, config: &std::path::PathBuf) -> eyre::Result { + let mut force_update_borders = false; + // Check that this is a valid static config file first + if StaticConfig::read(config).is_ok() { + // Clear workspace rules; these will need to be replaced + WORKSPACE_MATCHING_RULES.lock().clear(); + // Pause so that restored windows come to the foreground from all workspaces + self.is_paused = true; + // Bring all windows to the foreground + self.restore_all_windows(false)?; + + // Create a new wm from the config path + let mut wm = StaticConfig::preload( + config, + winevent_listener::event_rx(), + self.command_listener.try_clone().ok(), + )?; + + // Initialize the new wm + wm.init()?; + + wm.restore_all_windows(true)?; + + // This is equivalent to StaticConfig::postload for this use case + StaticConfig::reload(config, &mut wm)?; + + // Set self to the new wm instance + *self = wm; + + // check if there are any bars + let mut system = sysinfo::System::new_all(); + system.refresh_processes(sysinfo::ProcessesToUpdate::All, true); + + let has_bar = system + .processes_by_name("komorebi-bar.exe".as_ref()) + .next() + .is_some(); + + // stop bar(s) + if has_bar { + let script = r" +Stop-Process -Name:komorebi-bar -ErrorAction SilentlyContinue + "; + match powershell_script::run(script) { + Ok(_) => { + println!("{script}"); + + // start new bar(s) + let mut config = StaticConfig::read(config)?; + if let Some(display_bar_configurations) = &mut config.bar_configurations { + for config_file_path in &mut *display_bar_configurations { + let script = r#"Start-Process "komorebi-bar" '"--config" "CONFIGFILE"' -WindowStyle hidden"# + .replace("CONFIGFILE", &config_file_path.to_string_lossy()); + + match powershell_script::run(&script) { + Ok(_) => { + println!("{script}"); + } + Err(error) => { + println!("Error: {error}"); + } + } + } + } else { + let script = r" +if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) +{ + Start-Process komorebi-bar -WindowStyle hidden +} + "; + match powershell_script::run(script) { + Ok(_) => { + println!("{script}"); + } + Err(error) => { + println!("Error: {error}"); + } + } + } + } + Err(error) => { + println!("Error: {error}"); + } + } + } + + force_update_borders = true; + } + Ok(force_update_borders) + } + + pub fn answer_query( + &mut self, + query: StateQuery, + mut reply: impl std::io::Write, + ) -> eyre::Result<()> { + let response = match query { + StateQuery::FocusedMonitorIndex => self.focused_monitor_idx().to_string(), + StateQuery::FocusedWorkspaceIndex => self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx() + .to_string(), + StateQuery::FocusedContainerIndex => self + .focused_workspace()? + .focused_container_idx() + .to_string(), + StateQuery::FocusedWindowIndex => { + self.focused_container()?.focused_window_idx().to_string() + } + StateQuery::FocusedWorkspaceName => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor + .focused_workspace_name() + .unwrap_or_else(|| focused_monitor.focused_workspace_idx().to_string()) + } + StateQuery::Version => build::RUST_VERSION.to_string(), + StateQuery::FocusedWorkspaceLayout => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor.focused_workspace_layout().map_or_else( + || "None".to_string(), + |layout| match layout { + Layout::Default(default_layout) => default_layout.to_string(), + Layout::Custom(_) => "Custom".to_string(), + }, + ) + } + StateQuery::FocusedContainerKind => { + match self.focused_workspace()?.focused_container() { + None => "None".to_string(), + Some(container) => { + if container.windows().len() > 1 { + "Stack".to_string() + } else { + "Single".to_string() + } + } + } + } + }; + + reply.write_all(response.as_bytes())?; + Ok(()) + } pub fn focus_follows_mouse( &mut self, mut implementation: FocusFollowsMouseImplementation, From 12ef908aa97d63cebb58a0c2aced65a734834ad2 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:16:32 -0700 Subject: [PATCH 31/33] test(windows): pin the JSON of Monitor and MonitorInformation Three unit tests in monitor.rs: a Monitor read from the monitor object of a real komorebic state capture (e2e/lib/tests/fixtures/kfw-tiled.json, its workspaces emptied) serializes back to the same JSON value; id and serial_number_id are plain JSON values for ids including isize::MAX, -1 and isize::MIN; MonitorInformation has the six documented fields. They fix the representation before the type of Monitor.id changes. The komorebi crate is Windows-only, so these compile (clippy --all-targets, PASS) but cannot run on this host: they have NOT been run. Not a behaviour change. --- komorebi/src/monitor.rs | 61 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index ee4d2c53..6a769379 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -821,4 +821,65 @@ mod tests { m.ensure_workspace_count(3); assert_eq!(m.workspaces().len(), 5, "Monitor should have 5 workspaces"); } + + /// The monitor object of a real `komorebic state` capture (e2e/lib/tests/fixtures/kfw-tiled.json, + /// workspaces emptied): the JSON a Monitor reads and writes. Pins the representation of `id` (a + /// plain number) and `serial_number_id` (null or a string) so that changing their Rust types + /// cannot change the state JSON. + const MONITOR_JSON: &str = r#"{ + "id": 65537, + "name": "DISPLAY1", + "device": "Default_Monitor", + "device_id": "Default_Monitor-4&183790ca&0&UID0", + "serial_number_id": null, + "size": { "left": 0, "top": 0, "right": 1280, "bottom": 800 }, + "work_area_size": { "left": 0, "top": 0, "right": 1280, "bottom": 752 }, + "work_area_offset": null, + "window_based_work_area_offset": null, + "window_based_work_area_offset_limit": 1, + "workspaces": { "elements": [], "focused": 0 }, + "workspace_names": {}, + "container_padding": null, + "workspace_padding": null, + "wallpaper": null, + "floating_layer_behaviour": null + }"#; + + #[test] + fn a_monitor_serializes_to_the_json_of_the_state_capture() { + let expected: serde_json::Value = serde_json::from_str(MONITOR_JSON).unwrap(); + let monitor: Monitor = serde_json::from_value(expected.clone()).unwrap(); + + assert_eq!(serde_json::to_value(&monitor).unwrap(), expected); + } + + #[test] + fn a_monitor_id_and_serial_are_plain_json_values() { + for id in [0, 1, 65537, isize::MAX, -1, isize::MIN] { + let mut value: serde_json::Value = serde_json::from_str(MONITOR_JSON).unwrap(); + value["id"] = serde_json::json!(id); + value["serial_number_id"] = serde_json::json!("ABC123"); + + let monitor: Monitor = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(serde_json::to_value(&monitor).unwrap(), value, "id {id}"); + } + } + + #[test] + fn monitor_information_has_the_documented_fields() { + let monitor: Monitor = serde_json::from_str(MONITOR_JSON).unwrap(); + let value = serde_json::to_value(MonitorInformation::from(&monitor)).unwrap(); + + assert_eq!( + value, + serde_json::json!({ + "id": 65537, + "name": "DISPLAY1", + "device": "Default_Monitor", + "device_id": "Default_Monitor-4&183790ca&0&UID0", + "serial_number_id": null, + "size": { "left": 0, "top": 0, "right": 1280, "bottom": 800 } + }) + ); + } } From 9daa4d726aede14424e92ef52a12dfe48464ddaa Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:17:29 -0700 Subject: [PATCH 32/33] refactor(windows): Monitor.id is the shared MonitorId, with the same JSON Monitor.id was an isize HMONITOR; it is now komorebi_backend::MonitorId (the type WindowsBackend::monitors already returned). A serde adapter (hmonitor_json) writes it with serialize_i64(to_hmonitor()) and reads an isize through from_hmonitor, bit for bit, so the JSON is the same plain number as before (including negative handles); the schemars schema is declared as isize. serial_number_id was already Option (the shared shape), so it is unchanged. monitor::new / Monitor::new keep an isize parameter (every caller passes an HMONITOR); the 12 uses that need the raw handle call .to_hmonitor() (WindowsApi::monitor, wallpaper, DPI, zoomed checks, ids compared with monitor_from_window/point). MonitorInformation.id stays isize. BEHAVIOUR (JSON-identical by construction, not proven by running): the new unit tests of the previous revision pin the JSON against a real capture, but the Windows crate's tests cannot run on this host. Gate needed: any e2e scenario that reads komorebic state or saves/loads it, and monitor reconciliation / unknown_monitor. Verified: Windows clippy -D warnings via tools/fast-check PASS. --- komorebi/src/border_manager/mod.rs | 4 ++-- komorebi/src/monitor.rs | 29 +++++++++++++++++++---- komorebi/src/monitor_reconciliator/mod.rs | 6 ++--- komorebi/src/window_manager.rs | 14 ++++++----- komorebi/src/windows_backend.rs | 2 +- 5 files changed, 38 insertions(+), 17 deletions(-) diff --git a/komorebi/src/border_manager/mod.rs b/komorebi/src/border_manager/mod.rs index 0d7649b9..b50abe3e 100644 --- a/komorebi/src/border_manager/mod.rs +++ b/komorebi/src/border_manager/mod.rs @@ -741,8 +741,8 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result let foreground_hwnd = WindowsApi::foreground_window().unwrap_or_default(); let foreground_monitor_id = WindowsApi::monitor_from_window(foreground_hwnd); - let is_maximized = - foreground_monitor_id == m.id && WindowsApi::is_zoomed(foreground_hwnd); + let is_maximized = foreground_monitor_id == m.id.to_hmonitor() + && WindowsApi::is_zoomed(foreground_hwnd); if is_maximized { tracing::trace!( diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 6a769379..6e63886e 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -13,6 +13,7 @@ use crate::border_manager::BORDER_OFFSET; use crate::border_manager::BORDER_WIDTH; use crate::core::Rect; use crate::windows_backend::backend; +use komorebi_backend::MonitorId; use komorebi_backend::WindowId; use crate::DEFAULT_CONTAINER_PADDING; @@ -29,10 +30,28 @@ use crate::workspace::Workspace; use crate::workspace::WorkspaceGlobals; use crate::workspace::WorkspaceLayer; +/// `Monitor::id` is a `MonitorId` in Rust and the same plain JSON number as the `isize` handle it +/// was before: `komorebic state` and the saved state files do not change. +mod hmonitor_json { + use komorebi_backend::MonitorId; + use serde::Deserialize; + use serde::Deserializer; + use serde::Serializer; + + pub fn serialize(id: &MonitorId, serializer: S) -> Result { + serializer.serialize_i64(id.to_hmonitor() as i64) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Ok(MonitorId::from_hmonitor(isize::deserialize(deserializer)?)) + } +} #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Monitor { - pub id: isize, + #[serde(with = "hmonitor_json")] + #[cfg_attr(feature = "schemars", schemars(with = "isize"))] + pub id: MonitorId, pub name: String, pub device: String, pub device_id: String, @@ -67,7 +86,7 @@ pub struct MonitorInformation { impl From<&Monitor> for MonitorInformation { fn from(monitor: &Monitor) -> Self { Self { - id: monitor.id, + id: monitor.id.to_hmonitor(), name: monitor.name.clone(), device: monitor.device.clone(), device_id: monitor.device_id.clone(), @@ -90,7 +109,7 @@ pub fn new( workspaces.elements_mut().push_back(Workspace::default()); Monitor { - id, + id: MonitorId::from_hmonitor(id), name, device, device_id, @@ -133,7 +152,7 @@ impl Monitor { pub fn placeholder() -> Self { Self { - id: 0, + id: MonitorId(0), name: "PLACEHOLDER".to_string(), device: "".to_string(), device_id: "".to_string(), @@ -171,7 +190,7 @@ impl Monitor { pub fn load_focused_workspace(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> { let focused_idx = self.focused_workspace_idx(); - let hmonitor = self.id; + let hmonitor = self.id.to_hmonitor(); let monitor_wp = self.wallpaper.clone(); for (i, workspace) in self.workspaces_mut().iter_mut().enumerate() { if i == focused_idx { diff --git a/komorebi/src/monitor_reconciliator/mod.rs b/komorebi/src/monitor_reconciliator/mod.rs index 582b0b98..0974a667 100644 --- a/komorebi/src/monitor_reconciliator/mod.rs +++ b/komorebi/src/monitor_reconciliator/mod.rs @@ -293,7 +293,7 @@ where let mut should_update = false; // Update work areas as necessary - if let Ok(reference) = WindowsApi::monitor(monitor.id) + if let Ok(reference) = WindowsApi::monitor(monitor.id.to_hmonitor()) && reference.work_area_size != monitor.work_area_size { monitor.work_area_size = Rect { @@ -325,7 +325,7 @@ where let mut should_update = false; // Update sizes and work areas as necessary - if let Ok(reference) = WindowsApi::monitor(monitor.id) { + if let Ok(reference) = WindowsApi::monitor(monitor.id.to_hmonitor()) { if reference.work_area_size != monitor.work_area_size { monitor.work_area_size = Rect { left: reference.work_area_size.left, @@ -1275,7 +1275,7 @@ mod tests { assert_eq!(monitors.len(), 1, "Expected one monitor"); // hmonitor - assert_eq!(monitors[0].id, 1); + assert_eq!(monitors[0].id.to_hmonitor(), 1); // device name assert_eq!(monitors[0].name, String::from("DISPLAY1")); diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 47183dde..8f4486ab 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -771,7 +771,7 @@ impl WindowManager { let focused_workspace_idx = monitor.focused_workspace_idx(); monitor.update_workspace_globals(focused_workspace_idx, offset); - let hmonitor = monitor.id; + let hmonitor = monitor.id.to_hmonitor(); let monitor_wp = monitor.wallpaper.clone(); let workspace = monitor .focused_workspace_mut() @@ -1572,7 +1572,7 @@ impl WindowManager { .get_mut(monitor_idx) .ok_or_eyre("there is no monitor")?; - let hmonitor = monitor.id; + let hmonitor = monitor.id.to_hmonitor(); let monitor_wp = monitor.wallpaper.clone(); let workspace = monitor @@ -2589,12 +2589,14 @@ impl WindowManager { let a = self .focused_monitor() .ok_or_eyre("there is no monitor focused monitor")? - .id; + .id + .to_hmonitor(); let b = self .monitors_mut() .get_mut(origin_monitor_idx) .ok_or_eyre("there is no monitor at this index")? - .id; + .id + .to_hmonitor(); if !WindowsApi::monitors_have_same_dpi(a, b)? { self.update_focused_workspace(self.mouse_follows_focus, true)?; @@ -3766,7 +3768,7 @@ impl WindowManager { let hmonitor = WindowsApi::monitor_from_window(window.hwnd); for (i, monitor) in self.monitors().iter().enumerate() { - if monitor.id == hmonitor { + if monitor.id.to_hmonitor() == hmonitor { return Option::from(i); } } @@ -3789,7 +3791,7 @@ impl WindowManager { let hmonitor = WindowsApi::monitor_from_point(WindowsApi::cursor_pos().ok()?); for (i, monitor) in self.monitors().iter().enumerate() { - if monitor.id == hmonitor { + if monitor.id.to_hmonitor() == hmonitor { return Option::from(i); } } diff --git a/komorebi/src/windows_backend.rs b/komorebi/src/windows_backend.rs index 640fca5d..762c0a86 100644 --- a/komorebi/src/windows_backend.rs +++ b/komorebi/src/windows_backend.rs @@ -110,7 +110,7 @@ impl Backend for WindowsBackend { .map(|(_, hmonitor)| { let monitor = WindowsApi::monitor(hmonitor).map_err(platform)?; Ok(MonitorInfo { - id: MonitorId::from_hmonitor(monitor.id), + id: monitor.id, size: monitor.size, work_area: monitor.work_area_size, name: Some(monitor.name), From 18ca78196f38a083f9be429d4b8ba49637fe6e5d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:19:57 -0700 Subject: [PATCH 33/33] refactor(windows): centre cursor, focus-follows-mouse off and unminimize go through backend() window_manager.rs: three WindowsApi::center_cursor_in_rect calls become backend().center_cursor_in(..) and WindowsApi::disable_focus_follows_mouse becomes backend().set_focus_follows_mouse(false); workspace.rs: the WindowsApi::restore_window that unmaximizes a window becomes backend().unminimize(..) (the same ShowWindow call, after an IsWindow check). backend-switch.md now lists every WindowsApi call left in window_manager, workspace and monitor and why each cannot be switched without changing an error, a default or a flag (foreground_window, cursor_pos, focus on the desktop window, position_window flags, start-up enumeration, monitor fields). BEHAVIOUR: a dead window is skipped by the unminimize. e2e gate needed: commands, focus_follows_mouse, maximizing, workspaces. Verified: Windows clippy -D warnings via tools/fast-check PASS; e2e not run. --- docs/dev/backend-switch.md | 17 +++++++++++++++++ komorebi/src/window_manager.rs | 8 ++++---- komorebi/src/workspace.rs | 2 +- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/dev/backend-switch.md b/docs/dev/backend-switch.md index c817f644..2cc78001 100644 --- a/docs/dev/backend-switch.md +++ b/docs/dev/backend-switch.md @@ -41,3 +41,20 @@ use `?` or ignore the result; none inspects the error. `frame` is the exception: | `cursor_pos` | `Result` vs `Option<(i32, i32)>`; callers `?` it | same: a `Result` return | | `monitors` / `window` | `monitors()` rebuilds `MonitorInfo` and drops the `Monitor` fields the daemon needs (device id, serial, device, work-area offsets); `window()` asks title, class, exe, path | the daemon-side `Monitor` fields in `MonitorInfo` (or a platform extension), and for step 9 the monitor model moving to the core | | `monitor_from_point` | never `None` on Windows (`MONITOR_DEFAULTTONEAREST`), `None` outside every monitor on KDE and macOS | an explicit "nearest" flag or two methods | + +## What is left in `window_manager.rs`, `workspace.rs`, `monitor.rs` (checked call by call) + +Switched in the last batch: `center_cursor_in_rect` (3, window_manager), `disable_focus_follows_mouse` (1), +`restore_window` as `unminimize` (1, workspace). The rest names `WindowsApi` for a reason the trait does not +cover yet: + +| Call (sites) | Why it stays | +|---|---| +| `foreground_window` (10 in window_manager, 3 workspace, 1 monitor) | `Result`, a null handle is an `Err` the callers `?` on; trait has `Option` | +| `cursor_pos`, `window_at_cursor_pos`, `monitor_from_window`, `monitor_from_point` | `Result`/never-`None` semantics, see the table above; `window_at_cursor_pos` and `monitor_from_window` have no trait equivalent | +| `raise_and_focus_window(desktop_window)` (4) | `Backend::focus` is `Window::focus`, which skips when the window is already foreground and defers while it slides in; the direct call always raises and focuses | +| `position_window(hwnd, rect, false, true)` (2) | a different flag combination than `set_rect` (`top = false`, the second flag is the layered/shadow handling), not expressible | +| `load_monitor_information`, `load_workspace_information` | start-up enumeration into a `WindowManager`; seam.md 9: `windows()` cannot match the core's filter | +| `monitor(hmonitor)`, `monitor_rects`, `monitors_have_same_dpi` | the `Monitor` fields (device id, DPI) the trait's `MonitorInfo` drops | +| `set_wallpaper` | wallpaper stays KDE-only in the trait (D36) | +| `focus_follows_mouse` (query) | the trait has the setter only | diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 8f4486ab..01cf30fe 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1147,7 +1147,7 @@ impl WindowManager { let desktop_window = Window::from(WindowsApi::desktop_window()?); let rect = self.focused_monitor_size()?; - WindowsApi::center_cursor_in_rect(&rect)?; + backend().center_cursor_in(&rect)?; match WindowsApi::raise_and_focus_window(desktop_window.hwnd) { Ok(()) => {} @@ -1275,7 +1275,7 @@ impl WindowManager { WindowsApi::position_window(window.hwnd, &rect, false, true)?; if mouse_follows_focus { - WindowsApi::center_cursor_in_rect(&rect)?; + backend().center_cursor_in(&rect)?; } break; @@ -1450,7 +1450,7 @@ impl WindowManager { AnimationEngine::wait_for_all_animations(); if WindowsApi::focus_follows_mouse()? { - WindowsApi::disable_focus_follows_mouse()?; + backend().set_focus_follows_mouse(false)?; } let sockets = SUBSCRIPTION_SOCKETS.lock(); @@ -2425,7 +2425,7 @@ impl WindowManager { WindowsApi::position_window(window.hwnd, &rect, false, true)?; if mouse_follows_focus { - WindowsApi::center_cursor_in_rect(&rect)?; + backend().center_cursor_in(&rect)?; } break; diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 4eba3431..1d5e83cf 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -835,7 +835,7 @@ impl Workspace { // If a window has been unmaximized via toggle-maximize, this block // will make sure that it is unmaximized via restore_window if window.is_maximized() && !managed_maximized_window { - WindowsApi::restore_window(window.hwnd); + let _ = backend().unminimize(WindowId::from_hwnd(window.hwnd)); } } if hidden.get(i).copied().unwrap_or_default() {