From 01b9cbed911a2b0aac07ace0eeb14cd4bd9605c4 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 09:53:37 -0700 Subject: [PATCH 01/44] fix(mac): take the rule-list locks in one order, so a rule check and a config load cannot deadlock BEHAVIOUR (lock order only). window.rs (should_manage rule check) took the regex list, then ignore, then manage, then floating; static_config.rs (apply_globals) took ignore, regex, manage, floating. Two threads, one checking a window and one loading the config, could each hold what the other waits for. Same defect as the KDE fix ef1d3ef0; the order is now the KDE one minus the lists macOS lacks: floating, (session floating), ignore, manage, (workspace rules), regex. Both sites acquire in that order and the order is documented at the statics in lib.rs. The other holders (process_event.rs floating -> regex, process_command.rs floating -> session floating, window_manager.rs workspace rules -> regex) already follow it; every other site takes a single rule list. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run on Linux; a deadlock is not reproducible by reading anyway. Gate needed: none runnable here; hand check on a Mac (docs/dev/macos-handcheck.md): reload the config while windows open/close. --- komorebi-for-mac/komorebi/src/lib.rs | 4 ++++ komorebi-for-mac/komorebi/src/static_config.rs | 6 ++++-- komorebi-for-mac/komorebi/src/window.rs | 9 ++++++--- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/lib.rs b/komorebi-for-mac/komorebi/src/lib.rs index 55cf64de..c71b0d16 100644 --- a/komorebi-for-mac/komorebi/src/lib.rs +++ b/komorebi-for-mac/komorebi/src/lib.rs @@ -122,6 +122,10 @@ lazy_static! { Arc::new(Mutex::new(HashMap::new())); static ref WORKSPACE_MATCHING_RULES: Arc>> = Arc::new(Mutex::new(Vec::new())); + // LOCK ORDER for the rule lists (as in the KDE tree, minus the lists macOS does not have): + // FLOATING_APPLICATIONS, SESSION_FLOATING_APPLICATIONS, IGNORE_IDENTIFIERS, MANAGE_IDENTIFIERS, + // WORKSPACE_MATCHING_RULES, REGEX_IDENTIFIERS. Take the ones you need in that order and never + // the other way round; a thread that does can deadlock with one that does not. static ref REGEX_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(HashMap::new())); static ref MANAGE_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(vec![])); diff --git a/komorebi-for-mac/komorebi/src/static_config.rs b/komorebi-for-mac/komorebi/src/static_config.rs index 5fe68137..3cd71ee4 100644 --- a/komorebi-for-mac/komorebi/src/static_config.rs +++ b/komorebi-for-mac/komorebi/src/static_config.rs @@ -545,16 +545,18 @@ impl ApplyGlobals for StaticConfig { // transparency_manager::TRANSPARENCY_ALPHA // .store(self.transparency_alpha.unwrap_or(200), Ordering::SeqCst); + // the order every other place takes them in (floating, ignore, manage, regex; see lib.rs): + // a thread that takes two in another order can wait for one that holds what it needs + let mut floating_applications = FLOATING_APPLICATIONS.lock(); let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); - let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); let mut manage_identifiers = MANAGE_IDENTIFIERS.lock(); + let mut regex_identifiers = REGEX_IDENTIFIERS.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 titleless_applications = TITLELESS_APPLICATIONS.lock(); let mut tabbed_applications = TABBED_APPLICATIONS.lock(); diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 90e80ad2..4b91c92b 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -1641,9 +1641,14 @@ fn window_is_eligible( } } + // Every place that holds two of the rule lists takes them in this order: floating, ignore, + // manage, regex (see the statics in lib.rs). A thread that takes two in another order can wait + // for one that holds what it needs, and both wait for ever. + let floating_identifiers = FLOATING_APPLICATIONS.lock(); + let ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + let manage_identifiers = MANAGE_IDENTIFIERS.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, @@ -1658,7 +1663,6 @@ fn window_is_eligible( false }; - let manage_identifiers = MANAGE_IDENTIFIERS.lock(); let managed_override = if let Some(rule) = should_act( title, exe_name, @@ -1673,7 +1677,6 @@ fn window_is_eligible( false }; - let floating_identifiers = FLOATING_APPLICATIONS.lock(); if let Some(rule) = should_act( title, exe_name, From 796c3832b7d511413a3804f5357e18629e632380 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 09:54:18 -0700 Subject: [PATCH 02/44] refactor(mac): ask a Window for its frame instead of reading the AX element Adds Window::frame(), the frame query (Backend::window_rect), and routes the 28 sites that read a Window's frame through MacosApi::window_rect(&w.element) (window.rs, window_manager.rs, workspace.rs, process_event.rs, process_command.rs, settle.rs, macos_backend.rs) through it. frame() is the same call on the same element, so nothing changes at runtime. Sites that hold a bare element rather than a Window (tabs in process_event.rs, borders, the animator, AdhocWindow) are left as they are. Step 6 of the consolidation, macOS, one operation per revision. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run or unit-test on Linux. --- .../komorebi/src/macos_backend.rs | 2 +- .../komorebi/src/process_command.rs | 4 ++-- .../komorebi/src/process_event.rs | 12 +++++------ komorebi-for-mac/komorebi/src/settle.rs | 3 +-- komorebi-for-mac/komorebi/src/window.rs | 21 ++++++++++++------- .../komorebi/src/window_manager.rs | 14 ++++++------- komorebi-for-mac/komorebi/src/workspace.rs | 6 +++--- 7 files changed, 33 insertions(+), 29 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/macos_backend.rs b/komorebi-for-mac/komorebi/src/macos_backend.rs index 2a3bca30..4811c567 100644 --- a/komorebi-for-mac/komorebi/src/macos_backend.rs +++ b/komorebi-for-mac/komorebi/src/macos_backend.rs @@ -140,7 +140,7 @@ impl MacosBackend { id: WindowId::from_u32(window.id), pid: window.application.process_id, // the Accessibility position and size, in points; a failure leaves the default - rect: MacosApi::window_rect(&window.element) + rect: window.frame() .map(Rect::from) .unwrap_or_default(), minimized, diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index 276d9ada..7841d495 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -637,7 +637,7 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|(_, w)| { let rect = - Rect::from(MacosApi::window_rect(&w.element).unwrap_or_default()); + Rect::from(w.frame().unwrap_or_default()); rect.right * rect.bottom }); window_idx_pairs.reverse(); @@ -707,7 +707,7 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|w| { let rect = Rect::from( - MacosApi::window_rect(&w.element).unwrap_or_default(), + w.frame().unwrap_or_default(), ); rect.right * rect.bottom }); diff --git a/komorebi-for-mac/komorebi/src/process_event.rs b/komorebi-for-mac/komorebi/src/process_event.rs index ac23ca20..4a6b063d 100644 --- a/komorebi-for-mac/komorebi/src/process_event.rs +++ b/komorebi-for-mac/komorebi/src/process_event.rs @@ -260,7 +260,7 @@ impl WindowManager { && window.application.process_id == process_id { let tab_rect = MacosApi::window_rect(&element)?; - let main_rect = match MacosApi::window_rect(&window.element) { + let main_rect = match window.frame() { Ok(rect) => rect, Err(AccessibilityError::Api( AccessibilityApiError::InvalidUIElement, @@ -328,7 +328,7 @@ impl WindowManager { && window.application.process_id == process_id { let tab_rect = MacosApi::window_rect(&element)?; - let main_rect = match MacosApi::window_rect(&window.element) { + let main_rect = match window.frame() { Ok(rect) => rect, Err(AccessibilityError::Api( AccessibilityApiError::InvalidUIElement, @@ -553,7 +553,7 @@ impl WindowManager { if window.application.name().unwrap_or_default() == application_name { let tab_rect = MacosApi::window_rect(element)?; - let main_rect = MacosApi::window_rect(&window.element)?; + let main_rect = window.frame()?; // BOTH conditions must be true: // 1. Geometry matches (original check - preserves existing behavior) // 2. Window IDs match (new check - prevents false positives) @@ -897,7 +897,7 @@ impl WindowManager { { // TODO: not sure about this clone let window = window.clone(); - let new_position = Rect::from(MacosApi::window_rect(&window.element)?); + let new_position = Rect::from(window.frame()?); let old_position = *workspace .latest_layout .get(focused_container_idx) @@ -1102,7 +1102,7 @@ impl WindowManager { && let Some(window) = container.windows().iter().find(|w| w.id == window_id) { - let started_from = Rect::from(MacosApi::window_rect(&window.element)?); + let started_from = Rect::from(window.frame()?); let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); *pending_resize_op = Option::from((window_id, Some(started_from))); @@ -1162,7 +1162,7 @@ impl WindowManager { && let Some(window) = container.windows().iter().find(|w| w.id == window_id) { - let ended_at = Rect::from(MacosApi::window_rect(&window.element)?); + let ended_at = Rect::from(window.frame()?); tracing::info!("resizing with mouse"); redraw |= self.resize_by_drag(window_id, started_from, ended_at)?; diff --git a/komorebi-for-mac/komorebi/src/settle.rs b/komorebi-for-mac/komorebi/src/settle.rs index d72f2991..38294b3d 100644 --- a/komorebi-for-mac/komorebi/src/settle.rs +++ b/komorebi-for-mac/komorebi/src/settle.rs @@ -11,7 +11,6 @@ use crate::accessibility::AccessibilityApi; use crate::animation::animator; use crate::core::Rect; -use crate::macos_api::MacosApi; use crate::window::Snapping; use crate::window::dragged_window; use crate::window::is_parked; @@ -186,7 +185,7 @@ impl WindowManager { } let _ = AccessibilityApi::set_messaging_timeout(&window.element, LOOK_TIMEOUT); - let rect = MacosApi::window_rect(&window.element).map(Rect::from); + let rect = window.frame().map(Rect::from); let _ = AccessibilityApi::set_messaging_timeout(&window.element, 0.0); if let Ok(rect) = rect diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 4b91c92b..49c0fe4d 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -520,7 +520,7 @@ impl Serialize for Window { state.serialize_field("id", &self.id)?; state.serialize_field( "rect", - &Rect::from(MacosApi::window_rect(&self.element).unwrap_or_default()), + &Rect::from(self.frame().unwrap_or_default()), )?; state.serialize_field("details", &WindowDetails::from(self))?; state.end() @@ -569,6 +569,11 @@ impl Window { }) } + /// The frame query (`Backend::window_rect`): the Accessibility position and size, in points. + pub fn frame(&self) -> Result { + MacosApi::window_rect(&self.element) + } + pub fn is_valid(&self) -> bool { AccessibilityApi::copy_attribute_names(&self.element).is_some() } @@ -622,7 +627,7 @@ impl Window { // it happened to be when it was hidden let rect = match animator::take_over(self.id) { Some(target) => CGRect::from(target), - None => MacosApi::window_rect(&self.element)?, + None => self.frame()?, }; let mut window_restore_positions = WINDOW_RESTORE_POSITIONS.lock(); @@ -706,7 +711,7 @@ impl Window { let rect = match animator::target(self.id) { Some(target) => CGRect::from(target), - None => MacosApi::window_rect(&self.element)?, + None => self.frame()?, }; let Some(screen) = screen.or_else(|| CoreGraphicsApi::display_bounds_for_window_rect(rect)) @@ -956,7 +961,7 @@ impl Window { // the window manager is waiting for this, and so is every window after this one let _ = AccessibilityApi::set_messaging_timeout(&self.element, ARRIVAL_TIMEOUT); - match MacosApi::window_rect(&self.element) { + match self.frame() { Ok(actual) => arrival::report(self.id, *target, Rect::from(actual)), Err(error) => { tracing::debug!( @@ -985,7 +990,7 @@ impl Window { return; } - let Ok(current) = MacosApi::window_rect(&self.element) else { + let Ok(current) = self.frame() else { return; }; @@ -1077,7 +1082,7 @@ impl Window { motion, after: None, }, - || MacosApi::window_rect(&self.element).map(Rect::from), + || self.frame().map(Rect::from), ) } @@ -1192,7 +1197,7 @@ impl Window { let target_width = (target_height * aspect_ratio_width) / aspect_ratio_height; (target_width, target_height) } else { - let current_rect = Rect::from(MacosApi::window_rect(&self.element)?); + let current_rect = Rect::from(self.frame()?); (current_rect.right, current_rect.bottom) }; @@ -1212,7 +1217,7 @@ impl Window { current_area: &Rect, target_area: &Rect, ) -> Result<(), AccessibilityError> { - let current_rect = Rect::from(MacosApi::window_rect(&self.element)?); + let current_rect = Rect::from(self.frame()?); let x_diff = target_area.left - current_area.left; let y_diff = target_area.top - current_area.top; let x_ratio = f32::abs((target_area.right as f32) / (current_area.right as f32)); diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index 3bd9cd3a..3fd668b8 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -279,7 +279,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - MacosApi::window_rect(&w.element) + w.frame() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -305,7 +305,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - MacosApi::window_rect(&w.element) + w.frame() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -331,7 +331,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - MacosApi::window_rect(&w.element) + w.frame() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -357,7 +357,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - MacosApi::window_rect(&w.element) + w.frame() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -747,7 +747,7 @@ impl WindowManager { MacosApi::foreground_window_id().ok_or_eyre("no foreground window")?; for window in focused_workspace.floating_windows().iter() { if window.id == focused_window_id { - let mut rect = Rect::from(MacosApi::window_rect(&window.element)?); + let mut rect = Rect::from(window.frame()?); match direction { OperationDirection::Left => { if rect.left - delta < focused_monitor_work_area.left { @@ -1475,7 +1475,7 @@ impl WindowManager { .into_iter() .flatten() .filter_map(|window| { - MacosApi::window_rect(&window.element) + window.frame() .ok() .map(|rect| (window.id, Rect::from(rect))) }) @@ -1696,7 +1696,7 @@ impl WindowManager { for window in workspace.floating_windows().iter() { if window.id == focused_window_id { - let mut rect = Rect::from(MacosApi::window_rect(&window.element)?); + let mut rect = Rect::from(window.frame()?); match (direction, sizing) { (OperationDirection::Left, Sizing::Increase) => { if rect.left - delta < focused_monitor_work_area.left { diff --git a/komorebi-for-mac/komorebi/src/workspace.rs b/komorebi-for-mac/komorebi/src/workspace.rs index 042eb7b9..d6d29ab7 100644 --- a/komorebi-for-mac/komorebi/src/workspace.rs +++ b/komorebi-for-mac/komorebi/src/workspace.rs @@ -553,7 +553,7 @@ impl Workspace { && focused_window.application.process_id == process_id { if !valid_window_ids.contains(&focused_window.id) { - if let Ok(rect) = MacosApi::window_rect(&focused_window.element) { + if let Ok(rect) = focused_window.frame() { tracing::debug!( "reaping window {} ({}): rect = {:?}", focused_window.id, @@ -578,7 +578,7 @@ impl Workspace { if focused_window.application.process_id == process_id && !valid_window_ids.contains(&focused_window.id) { - if let Ok(rect) = MacosApi::window_rect(&focused_window.element) { + if let Ok(rect) = focused_window.frame() { tracing::debug!( "reaping monocle window {} ({}): rect = {:?}", focused_window.id, @@ -599,7 +599,7 @@ impl Workspace { for window in self.floating_windows() { if window.application.process_id == process_id { if !valid_window_ids.contains(&window.id) { - if let Ok(rect) = MacosApi::window_rect(&window.element) { + if let Ok(rect) = window.frame() { tracing::debug!( "reaping floating window {} ({}): rect = {:?}", window.id, From 7c2e1bea8a603728ae58a20c0d8e26c398216a54 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 09:59:11 -0700 Subject: [PATCH 03/44] refactor(mac): name the Window liveness check alive, as the shared Backend does Renames Window::is_valid to Window::alive (window.rs, reaper.rs, workspace.rs, macos_backend.rs). Same body (the element still answers a copy-attribute-names query), so nothing changes at runtime. Application::is_valid is a different type and keeps its name. This is the 'alive' operation of the step 6 list. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run or unit-test on Linux. --- komorebi-for-mac/komorebi/src/macos_backend.rs | 4 ++-- komorebi-for-mac/komorebi/src/reaper.rs | 2 +- komorebi-for-mac/komorebi/src/window.rs | 6 +++--- komorebi-for-mac/komorebi/src/workspace.rs | 6 +++--- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/macos_backend.rs b/komorebi-for-mac/komorebi/src/macos_backend.rs index 4811c567..3bef4cd4 100644 --- a/komorebi-for-mac/komorebi/src/macos_backend.rs +++ b/komorebi-for-mac/komorebi/src/macos_backend.rs @@ -118,7 +118,7 @@ impl MacosBackend { window: &Window, error: impl std::error::Error + Send + Sync + 'static, ) -> Error { - if window.is_valid() { + if window.alive() { platform(error) } else { Error::WindowGone(id) @@ -126,7 +126,7 @@ impl MacosBackend { } fn info(window: &Window) -> Option { - if !window.is_valid() { + if !window.alive() { return None; } diff --git a/komorebi-for-mac/komorebi/src/reaper.rs b/komorebi-for-mac/komorebi/src/reaper.rs index 8f88b0c9..9f06b359 100644 --- a/komorebi-for-mac/komorebi/src/reaper.rs +++ b/komorebi-for-mac/komorebi/src/reaper.rs @@ -64,7 +64,7 @@ fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> continue 'notification; } - handle_notification(&mut wm, notification, Window::is_valid)?; + handle_notification(&mut wm, notification, Window::alive)?; } Ok(()) diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 49c0fe4d..de2ce50b 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -465,7 +465,7 @@ impl Drop for Window { fn drop(&mut self) { // this gets called when a cloned Window is dropped, so we need to make sure it only // invalidates the observer if the Window is no longer open - if !self.is_valid() { + if !self.alive() { tracing::info!( "invalidating window observer for {}", self.title() @@ -574,7 +574,7 @@ impl Window { MacosApi::window_rect(&self.element) } - pub fn is_valid(&self) -> bool { + pub fn alive(&self) -> bool { AccessibilityApi::copy_attribute_names(&self.element).is_some() } @@ -1290,7 +1290,7 @@ impl Window { event: Option, debug: &mut RuleDebug, ) -> eyre::Result { - if !self.is_valid() { + if !self.alive() { return Ok(false); } diff --git a/komorebi-for-mac/komorebi/src/workspace.rs b/komorebi-for-mac/komorebi/src/workspace.rs index d6d29ab7..a66674d1 100644 --- a/komorebi-for-mac/komorebi/src/workspace.rs +++ b/komorebi-for-mac/komorebi/src/workspace.rs @@ -566,7 +566,7 @@ impl Workspace { // if accessibility API calls fail on AXError::InvalidUIElement // let's try and nuke these early - if !focused_window.is_valid() { + if !focused_window.alive() { invalid_window_ids.push(focused_window.id); } } @@ -591,7 +591,7 @@ impl Workspace { // if accessibility API calls fail on AXError::InvalidUIElement // let's try and nuke these early - if !focused_window.is_valid() { + if !focused_window.alive() { invalid_window_ids.push(focused_window.id); } } @@ -612,7 +612,7 @@ impl Workspace { // if accessibility API calls fail on AXError::InvalidUIElement // let's try and nuke these early - if !window.is_valid() { + if !window.alive() { invalid_floating_window_ids.push(window.id); } } From 49a6dbdabbbdb71ffc99b5640bb0c975c7c2ce78 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 09:59:49 -0700 Subject: [PATCH 04/44] refactor(mac): name the Window set-frame operation set_rect, as the shared Backend does Renames Window::set_position(&Rect) to Window::set_rect (window.rs and its 9 callers in workspace.rs, window_manager.rs, scrolling.rs, settle.rs and macos_backend.rs). Body untouched: the direct path (set_point, set_size) or the animator, as before; nothing changes at runtime. The animator's own free function set_position, set_point and set_size stay as they are (they are the AX writes, not the Window operation). Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run or unit-test on Linux. --- komorebi-for-mac/komorebi/src/macos_backend.rs | 4 ++-- komorebi-for-mac/komorebi/src/scrolling.rs | 4 ++-- komorebi-for-mac/komorebi/src/settle.rs | 2 +- komorebi-for-mac/komorebi/src/window.rs | 10 +++++----- komorebi-for-mac/komorebi/src/window_manager.rs | 4 ++-- komorebi-for-mac/komorebi/src/workspace.rs | 4 ++-- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/macos_backend.rs b/komorebi-for-mac/komorebi/src/macos_backend.rs index 3bef4cd4..b1b32f0f 100644 --- a/komorebi-for-mac/komorebi/src/macos_backend.rs +++ b/komorebi-for-mac/komorebi/src/macos_backend.rs @@ -194,11 +194,11 @@ impl Backend for MacosBackend { } fn set_rect(&self, id: WindowId, rect: &Rect) -> Result<()> { - // `Window::set_position` writes directly (two Accessibility writes) or hands the move to + // `Window::set_rect` writes directly (two Accessibility writes) or hands the move to // the animator, depending on the animation settings; both are requests let window = self.lookup(id)?; window - .set_position(rect) + .set_rect(rect) .map_err(|e| Self::failed(id, &window, e)) } diff --git a/komorebi-for-mac/komorebi/src/scrolling.rs b/komorebi-for-mac/komorebi/src/scrolling.rs index a11ae9c3..c87bc504 100644 --- a/komorebi-for-mac/komorebi/src/scrolling.rs +++ b/komorebi-for-mac/komorebi/src/scrolling.rs @@ -303,7 +303,7 @@ impl Workspace { for window in container.windows_mut() { let result = match placement.visibility { Visibility::Visible => window - .set_position(&rect) + .set_rect(&rect) .map(|()| window.note_arrival(&rect, resized)), Visibility::Clipped => { // part of it is in view and the rest is past the edge of the screen, @@ -315,7 +315,7 @@ impl Workspace { } window - .set_position(&target) + .set_rect(&target) .map(|()| window.note_arrival(&target, resized)) } Visibility::OffLeft => { diff --git a/komorebi-for-mac/komorebi/src/settle.rs b/komorebi-for-mac/komorebi/src/settle.rs index 38294b3d..8c9fd60a 100644 --- a/komorebi-for-mac/komorebi/src/settle.rs +++ b/komorebi-for-mac/komorebi/src/settle.rs @@ -207,7 +207,7 @@ impl WindowManager { let _snapping = Snapping::end(); for (window, layout) in &off { - if let Err(error) = window.set_position(layout) { + if let Err(error) = window.set_rect(layout) { tracing::debug!( "live resize: could not send window {} again: {error}", window.id diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index de2ce50b..1b9b441b 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -917,7 +917,7 @@ impl Window { )) } - pub fn set_position(&self, rect: &Rect) -> Result<(), AccessibilityError> { + pub fn set_rect(&self, rect: &Rect) -> Result<(), AccessibilityError> { match snap() { Snap::Step(dragged) => return self.set_position_for_step(dragged, rect), Snap::End => { @@ -1204,7 +1204,7 @@ impl Window { let x = work_area.left + ((work_area.right - target_width) / 2); let y = work_area.top + ((work_area.bottom - target_height) / 2); - self.set_position(&Rect { + self.set_rect(&Rect { left: x, top: y, right: target_width, @@ -1255,7 +1255,7 @@ impl Window { // let anim_count = ANIMATION_MANAGER // .lock() // .count_in_progress(MovementRenderDispatcher::PREFIX); - // self.set_position(&new_rect, true)?; + // self.set_rect(&new_rect, true)?; // let hwnd = self.hwnd; // // Wait for the animation to finish before maximizing the window again, otherwise // // we would be maximizing the window on the current monitor anyway @@ -1274,11 +1274,11 @@ impl Window { // windows_api::WindowsApi::maximize_window(hwnd); // }); // } else { - // self.set_position(&new_rect, true)?; + // self.set_rect(&new_rect, true)?; // windows_api::WindowsApi::maximize_window(self.hwnd); // } // } else { - self.set_position(&new_rect)?; + self.set_rect(&new_rect)?; // } Ok(()) diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index 3fd668b8..c7e08c74 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -787,7 +787,7 @@ impl WindowManager { } } - window.set_position(&rect)?; + window.set_rect(&rect)?; if mouse_follows_focus { MacosApi::center_cursor_in_rect(&rect)?; @@ -1750,7 +1750,7 @@ impl WindowManager { } } - window.set_position(&rect)?; + window.set_rect(&rect)?; if mouse_follows_focus { MacosApi::center_cursor_in_rect(&rect)?; diff --git a/komorebi-for-mac/komorebi/src/workspace.rs b/komorebi-for-mac/komorebi/src/workspace.rs index a66674d1..4f93785b 100644 --- a/komorebi-for-mac/komorebi/src/workspace.rs +++ b/komorebi-for-mac/komorebi/src/workspace.rs @@ -1476,7 +1476,7 @@ impl Workspace { adjusted_work_area.add_padding(container_padding); adjusted_work_area.add_padding(border_offset); adjusted_work_area.add_padding(border_width); - window.set_position(&adjusted_work_area)?; + window.set_rect(&adjusted_work_area)?; }; } else if !self.containers().is_empty() { if self.is_scrolling() { @@ -1503,7 +1503,7 @@ impl Workspace { layout.add_padding(border_width); for window in container.windows_mut() { - if let Err(error) = window.set_position(layout) { + if let Err(error) = window.set_rect(layout) { tracing::warn!("failed to set window position: {error}") } } From 803a141088a63078704a2b7c3f9a7ad5cd5344a0 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:00:03 -0700 Subject: [PATCH 05/44] refactor(mac): set a window's AX messaging timeout through Window Adds Window::set_messaging_timeout and uses it in settle.rs (the look at a window after a drag, 3 raw AX sites) and in Window::note_arrival. Same call on the same element; nothing changes at runtime. It is not one of the shared Backend operations, but it bounds the frame query, so the raw AX call leaves settle.rs with the frame read. The window manager's timeouts list and the animator keep calling AccessibilityApi: they hold elements (app elements, lane handles), not Windows. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run or unit-test on Linux. --- komorebi-for-mac/komorebi/src/settle.rs | 5 ++--- komorebi-for-mac/komorebi/src/window.rs | 8 +++++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/settle.rs b/komorebi-for-mac/komorebi/src/settle.rs index 8c9fd60a..75492363 100644 --- a/komorebi-for-mac/komorebi/src/settle.rs +++ b/komorebi-for-mac/komorebi/src/settle.rs @@ -8,7 +8,6 @@ //! and any that are not where they are to be are sent there again, and looked at once more after //! that. -use crate::accessibility::AccessibilityApi; use crate::animation::animator; use crate::core::Rect; use crate::window::Snapping; @@ -184,9 +183,9 @@ impl WindowManager { return Ok(0); } - let _ = AccessibilityApi::set_messaging_timeout(&window.element, LOOK_TIMEOUT); + let _ = window.set_messaging_timeout(LOOK_TIMEOUT); let rect = window.frame().map(Rect::from); - let _ = AccessibilityApi::set_messaging_timeout(&window.element, 0.0); + let _ = window.set_messaging_timeout(0.0); if let Ok(rect) = rect && is_off(&rect, &layout) diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 1b9b441b..51aabbad 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -574,6 +574,12 @@ impl Window { MacosApi::window_rect(&self.element) } + /// How long an Accessibility call to this window's app may block, in seconds (0 restores the + /// system default). Not an operation of the shared `Backend`; it bounds the frame query. + pub fn set_messaging_timeout(&self, seconds: f32) -> Result<(), AccessibilityError> { + AccessibilityApi::set_messaging_timeout(&self.element, seconds) + } + pub fn alive(&self) -> bool { AccessibilityApi::copy_attribute_names(&self.element).is_some() } @@ -959,7 +965,7 @@ impl Window { } // the window manager is waiting for this, and so is every window after this one - let _ = AccessibilityApi::set_messaging_timeout(&self.element, ARRIVAL_TIMEOUT); + let _ = self.set_messaging_timeout(ARRIVAL_TIMEOUT); match self.frame() { Ok(actual) => arrival::report(self.id, *target, Rect::from(actual)), From ecaa3e15160566ab9b6f28e2046fe95defa12b77 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:00:34 -0700 Subject: [PATCH 06/44] refactor(mac): give Window a close operation Adds Window::close (Backend::close): the same press of the close button that AdhocWindow::close does on a bare element, applied to the Window's element. Nothing calls it yet; MacosBackend switches to it in the next step. No behaviour change: the daemon's own close command still goes through AdhocWindow on the foreground element, because it has no Window there. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run or unit-test on Linux. --- komorebi-for-mac/komorebi/src/window.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 51aabbad..3ea82eab 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -814,6 +814,11 @@ impl Window { AccessibilityApi::set_attribute_cf_value(&self.element, kAXMinimizedAttribute, value) } + /// Closes the window by pressing its close button (`Backend::close`); `Ok` when it has none. + pub fn close(&self) -> Result<(), AccessibilityError> { + AdhocWindow::close(&self.element.0) + } + #[tracing::instrument(skip_all)] pub fn restore(&mut self) -> Result<(), AccessibilityError> { // waiting for what is on its way to the window is not something to do with a lock held From d30a3eb6868188cb38b4fa23d0d24b61e2663f64 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:01:05 -0700 Subject: [PATCH 07/44] refactor(mac): MacosBackend reaches a window only through Window methods Step 11(i). The compile-only adapter still read the Accessibility element for two things: the minimized flag (copy_attribute_value of kAXMinimized) and close (AdhocWindow::close on the element). Window::minimized is added (the same query, on self.element) and the adapter now calls it and Window::close; with set_rect, focus, raise, hide, restore, minimize, unminimize, alive and frame (earlier revisions) every operation of the adapter is a Window method and the file imports no AccessibilityApi. The adapter is still not used by the daemon, so nothing changes at runtime. Steps 11(ii) (id registry) and (iii) are not started. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run or unit-test on Linux. --- .../komorebi/src/macos_backend.rs | 19 +++++-------------- komorebi-for-mac/komorebi/src/window.rs | 6 ++++++ 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/macos_backend.rs b/komorebi-for-mac/komorebi/src/macos_backend.rs index b1b32f0f..aa12546e 100644 --- a/komorebi-for-mac/komorebi/src/macos_backend.rs +++ b/komorebi-for-mac/komorebi/src/macos_backend.rs @@ -1,5 +1,6 @@ -//! `MacosBackend`: the shared [`komorebi_backend::Backend`] over the existing [`MacosApi`], -//! [`Window`] and [`AdhocWindow`] functions. +//! `MacosBackend`: the shared [`komorebi_backend::Backend`] over the existing [`MacosApi`] and +//! [`Window`] methods (set_rect, focus, raise, hide, restore, minimize, unminimize, close, alive, +//! frame and minimized): it holds no Accessibility call of its own. //! //! **Nothing uses it yet.** The daemon still holds `Window` values (element, application and //! observer) and calls them directly; this adapter exists so that the trait is known to be @@ -19,13 +20,10 @@ //! callback refreshes on main with [`MacosBackend::refresh_monitors`]. use crate::LibraryError; -use crate::accessibility::AccessibilityApi; -use crate::accessibility::attribute_constants::kAXMinimizedAttribute; use crate::core::Rect; use crate::core::WindowHidingPosition; use crate::macos_api::MacosApi; use crate::skylight::BatchedUpdates; -use crate::window::AdhocWindow; use crate::window::Window; use komorebi_backend::Backend; use komorebi_backend::Error; @@ -35,7 +33,6 @@ use komorebi_backend::Result; use komorebi_backend::WindowId; use komorebi_backend::WindowInfo; use objc2::MainThreadMarker; -use objc2_core_foundation::CFBoolean; use parking_lot::Mutex; use std::collections::HashMap; @@ -130,12 +127,6 @@ impl MacosBackend { return None; } - let minimized = AccessibilityApi::copy_attribute_value::( - &window.element, - kAXMinimizedAttribute, - ) - .is_some_and(|b| b.as_bool()); - Some(WindowInfo { id: WindowId::from_u32(window.id), pid: window.application.process_id, @@ -143,7 +134,7 @@ impl MacosBackend { rect: window.frame() .map(Rect::from) .unwrap_or_default(), - minimized, + minimized: window.minimized(), alive: true, title: window.title(), // macOS has no window class: a bundle identifier, role and subrole instead @@ -243,7 +234,7 @@ impl Backend for MacosBackend { fn close(&self, id: WindowId) -> Result<()> { // presses the close button; `Ok` when the window has none let window = self.lookup(id)?; - AdhocWindow::close(&window.element.0).map_err(|e| Self::failed(id, &window, e)) + window.close().map_err(|e| Self::failed(id, &window, e)) } fn center_cursor_in(&self, rect: &Rect) -> Result<()> { diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 3ea82eab..2f1ad9a6 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -802,6 +802,12 @@ impl Window { Ok(()) } + /// Whether the window is minimized (the `WindowInfo::minimized` field of the shared `Backend`). + pub fn minimized(&self) -> bool { + AccessibilityApi::copy_attribute_value::(&self.element, kAXMinimizedAttribute) + .is_some_and(|b| b.as_bool()) + } + pub fn minimize(&mut self) -> Result<(), AccessibilityError> { let cf_boolean = CFBoolean::new(true); let value = &**cf_boolean; From 931b17d748c9e7ea5bf3b1e71a0d832286ec6f05 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:01:30 -0700 Subject: [PATCH 08/44] refactor(mac): name the Window frame query window_rect, as the Backend and the Windows Window do Renames Window::frame (added two revisions back) to Window::window_rect and its 28 callers: Backend::window_rect is the shared name, and the Windows Window got the same one (wip-u-kfw mkwoqsvs). Same body; nothing changes at runtime. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run or unit-test on Linux. --- komorebi-for-mac/komorebi/src/macos_backend.rs | 4 ++-- .../komorebi/src/process_command.rs | 4 ++-- komorebi-for-mac/komorebi/src/process_event.rs | 12 ++++++------ komorebi-for-mac/komorebi/src/settle.rs | 2 +- komorebi-for-mac/komorebi/src/window.rs | 18 +++++++++--------- .../komorebi/src/window_manager.rs | 14 +++++++------- komorebi-for-mac/komorebi/src/workspace.rs | 6 +++--- 7 files changed, 30 insertions(+), 30 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/macos_backend.rs b/komorebi-for-mac/komorebi/src/macos_backend.rs index aa12546e..c6b8e352 100644 --- a/komorebi-for-mac/komorebi/src/macos_backend.rs +++ b/komorebi-for-mac/komorebi/src/macos_backend.rs @@ -1,6 +1,6 @@ //! `MacosBackend`: the shared [`komorebi_backend::Backend`] over the existing [`MacosApi`] and //! [`Window`] methods (set_rect, focus, raise, hide, restore, minimize, unminimize, close, alive, -//! frame and minimized): it holds no Accessibility call of its own. +//! window_rect and minimized): it holds no Accessibility call of its own. //! //! **Nothing uses it yet.** The daemon still holds `Window` values (element, application and //! observer) and calls them directly; this adapter exists so that the trait is known to be @@ -131,7 +131,7 @@ impl MacosBackend { id: WindowId::from_u32(window.id), pid: window.application.process_id, // the Accessibility position and size, in points; a failure leaves the default - rect: window.frame() + rect: window.window_rect() .map(Rect::from) .unwrap_or_default(), minimized: window.minimized(), diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index 7841d495..686be380 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -637,7 +637,7 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|(_, w)| { let rect = - Rect::from(w.frame().unwrap_or_default()); + Rect::from(w.window_rect().unwrap_or_default()); rect.right * rect.bottom }); window_idx_pairs.reverse(); @@ -707,7 +707,7 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|w| { let rect = Rect::from( - w.frame().unwrap_or_default(), + w.window_rect().unwrap_or_default(), ); rect.right * rect.bottom }); diff --git a/komorebi-for-mac/komorebi/src/process_event.rs b/komorebi-for-mac/komorebi/src/process_event.rs index 4a6b063d..7c72b2f0 100644 --- a/komorebi-for-mac/komorebi/src/process_event.rs +++ b/komorebi-for-mac/komorebi/src/process_event.rs @@ -260,7 +260,7 @@ impl WindowManager { && window.application.process_id == process_id { let tab_rect = MacosApi::window_rect(&element)?; - let main_rect = match window.frame() { + let main_rect = match window.window_rect() { Ok(rect) => rect, Err(AccessibilityError::Api( AccessibilityApiError::InvalidUIElement, @@ -328,7 +328,7 @@ impl WindowManager { && window.application.process_id == process_id { let tab_rect = MacosApi::window_rect(&element)?; - let main_rect = match window.frame() { + let main_rect = match window.window_rect() { Ok(rect) => rect, Err(AccessibilityError::Api( AccessibilityApiError::InvalidUIElement, @@ -553,7 +553,7 @@ impl WindowManager { if window.application.name().unwrap_or_default() == application_name { let tab_rect = MacosApi::window_rect(element)?; - let main_rect = window.frame()?; + let main_rect = window.window_rect()?; // BOTH conditions must be true: // 1. Geometry matches (original check - preserves existing behavior) // 2. Window IDs match (new check - prevents false positives) @@ -897,7 +897,7 @@ impl WindowManager { { // TODO: not sure about this clone let window = window.clone(); - let new_position = Rect::from(window.frame()?); + let new_position = Rect::from(window.window_rect()?); let old_position = *workspace .latest_layout .get(focused_container_idx) @@ -1102,7 +1102,7 @@ impl WindowManager { && let Some(window) = container.windows().iter().find(|w| w.id == window_id) { - let started_from = Rect::from(window.frame()?); + let started_from = Rect::from(window.window_rect()?); let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); *pending_resize_op = Option::from((window_id, Some(started_from))); @@ -1162,7 +1162,7 @@ impl WindowManager { && let Some(window) = container.windows().iter().find(|w| w.id == window_id) { - let ended_at = Rect::from(window.frame()?); + let ended_at = Rect::from(window.window_rect()?); tracing::info!("resizing with mouse"); redraw |= self.resize_by_drag(window_id, started_from, ended_at)?; diff --git a/komorebi-for-mac/komorebi/src/settle.rs b/komorebi-for-mac/komorebi/src/settle.rs index 75492363..1f1f6f67 100644 --- a/komorebi-for-mac/komorebi/src/settle.rs +++ b/komorebi-for-mac/komorebi/src/settle.rs @@ -184,7 +184,7 @@ impl WindowManager { } let _ = window.set_messaging_timeout(LOOK_TIMEOUT); - let rect = window.frame().map(Rect::from); + let rect = window.window_rect().map(Rect::from); let _ = window.set_messaging_timeout(0.0); if let Ok(rect) = rect diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 2f1ad9a6..83279064 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -520,7 +520,7 @@ impl Serialize for Window { state.serialize_field("id", &self.id)?; state.serialize_field( "rect", - &Rect::from(self.frame().unwrap_or_default()), + &Rect::from(self.window_rect().unwrap_or_default()), )?; state.serialize_field("details", &WindowDetails::from(self))?; state.end() @@ -570,7 +570,7 @@ impl Window { } /// The frame query (`Backend::window_rect`): the Accessibility position and size, in points. - pub fn frame(&self) -> Result { + pub fn window_rect(&self) -> Result { MacosApi::window_rect(&self.element) } @@ -633,7 +633,7 @@ impl Window { // it happened to be when it was hidden let rect = match animator::take_over(self.id) { Some(target) => CGRect::from(target), - None => self.frame()?, + None => self.window_rect()?, }; let mut window_restore_positions = WINDOW_RESTORE_POSITIONS.lock(); @@ -717,7 +717,7 @@ impl Window { let rect = match animator::target(self.id) { Some(target) => CGRect::from(target), - None => self.frame()?, + None => self.window_rect()?, }; let Some(screen) = screen.or_else(|| CoreGraphicsApi::display_bounds_for_window_rect(rect)) @@ -978,7 +978,7 @@ impl Window { // the window manager is waiting for this, and so is every window after this one let _ = self.set_messaging_timeout(ARRIVAL_TIMEOUT); - match self.frame() { + match self.window_rect() { Ok(actual) => arrival::report(self.id, *target, Rect::from(actual)), Err(error) => { tracing::debug!( @@ -1007,7 +1007,7 @@ impl Window { return; } - let Ok(current) = self.frame() else { + let Ok(current) = self.window_rect() else { return; }; @@ -1099,7 +1099,7 @@ impl Window { motion, after: None, }, - || self.frame().map(Rect::from), + || self.window_rect().map(Rect::from), ) } @@ -1214,7 +1214,7 @@ impl Window { let target_width = (target_height * aspect_ratio_width) / aspect_ratio_height; (target_width, target_height) } else { - let current_rect = Rect::from(self.frame()?); + let current_rect = Rect::from(self.window_rect()?); (current_rect.right, current_rect.bottom) }; @@ -1234,7 +1234,7 @@ impl Window { current_area: &Rect, target_area: &Rect, ) -> Result<(), AccessibilityError> { - let current_rect = Rect::from(self.frame()?); + let current_rect = Rect::from(self.window_rect()?); let x_diff = target_area.left - current_area.left; let y_diff = target_area.top - current_area.top; let x_ratio = f32::abs((target_area.right as f32) / (current_area.right as f32)); diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index c7e08c74..5c2e8b4b 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -279,7 +279,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - w.frame() + w.window_rect() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -305,7 +305,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - w.frame() + w.window_rect() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -331,7 +331,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - w.frame() + w.window_rect() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -357,7 +357,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - w.frame() + w.window_rect() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -747,7 +747,7 @@ impl WindowManager { MacosApi::foreground_window_id().ok_or_eyre("no foreground window")?; for window in focused_workspace.floating_windows().iter() { if window.id == focused_window_id { - let mut rect = Rect::from(window.frame()?); + let mut rect = Rect::from(window.window_rect()?); match direction { OperationDirection::Left => { if rect.left - delta < focused_monitor_work_area.left { @@ -1475,7 +1475,7 @@ impl WindowManager { .into_iter() .flatten() .filter_map(|window| { - window.frame() + window.window_rect() .ok() .map(|rect| (window.id, Rect::from(rect))) }) @@ -1696,7 +1696,7 @@ impl WindowManager { for window in workspace.floating_windows().iter() { if window.id == focused_window_id { - let mut rect = Rect::from(window.frame()?); + let mut rect = Rect::from(window.window_rect()?); match (direction, sizing) { (OperationDirection::Left, Sizing::Increase) => { if rect.left - delta < focused_monitor_work_area.left { diff --git a/komorebi-for-mac/komorebi/src/workspace.rs b/komorebi-for-mac/komorebi/src/workspace.rs index 4f93785b..7666bf3b 100644 --- a/komorebi-for-mac/komorebi/src/workspace.rs +++ b/komorebi-for-mac/komorebi/src/workspace.rs @@ -553,7 +553,7 @@ impl Workspace { && focused_window.application.process_id == process_id { if !valid_window_ids.contains(&focused_window.id) { - if let Ok(rect) = focused_window.frame() { + if let Ok(rect) = focused_window.window_rect() { tracing::debug!( "reaping window {} ({}): rect = {:?}", focused_window.id, @@ -578,7 +578,7 @@ impl Workspace { if focused_window.application.process_id == process_id && !valid_window_ids.contains(&focused_window.id) { - if let Ok(rect) = focused_window.frame() { + if let Ok(rect) = focused_window.window_rect() { tracing::debug!( "reaping monocle window {} ({}): rect = {:?}", focused_window.id, @@ -599,7 +599,7 @@ impl Workspace { for window in self.floating_windows() { if window.application.process_id == process_id { if !valid_window_ids.contains(&window.id) { - if let Ok(rect) = window.frame() { + if let Ok(rect) = window.window_rect() { tracing::debug!( "reaping floating window {} ({}): rect = {:?}", window.id, From f157aa34e9552821baa5b6816a409e8af781ee20 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:02:36 -0700 Subject: [PATCH 09/44] docs(macos): the hand-check list for a real Mac Lists what must be checked on a Mac once the unified binaries exist: every macOS revision that changes runtime behaviour (the rule-list lock order, the shared command listener, pause filter, subscriber push, EventChannel, SocketMessage, animation prefix, StaticConfig, komorebic launcher, bar-core hooks and library bumps), the mechanical Step 6/11(i) revisions of this stack, the walk-through the plan names (focus, move, stack, workspaces, scrolling, pan, borders, animations, display change, sleep and wake), and the bugs noticed: the main-queue/WM-lock deadlock of seam.md 3.3, cmd.exe and explorer.exe in the macOS bar, the update widget's wrong repo, the raw AX sites that remain outside Window. Nothing in it was run: macOS cannot be built or tested on this host. Verified: documentation only. --- docs/dev/macos-handcheck.md | 66 +++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 docs/dev/macos-handcheck.md diff --git a/docs/dev/macos-handcheck.md b/docs/dev/macos-handcheck.md new file mode 100644 index 00000000..96a8933b --- /dev/null +++ b/docs/dev/macos-handcheck.md @@ -0,0 +1,66 @@ +# macOS hand-check list + +Status: written by the `kfm` agent for the user, 2026-10-31. Nothing here has been run: macOS cannot be built, linked or tested on the Linux host, only type-checked through a fake C compiler (`tools/fast-check`). Every revision below is `type-checks, not run`. Revision ids are jj change ids (stable) with the commit id they had when this was written (commit ids change when a revision is rewritten; use `jj log -r `). + +How to use it: build the unified (or, until they exist, the per-tree) macOS `komorebi`, `komorebic` and `komorebi-bar`, run `cargo test --workspace` on the Mac first (the 399+ unit tests have never run against these changes), then walk the sections in order. For before/after capture use `komorebi-recorder` against a build of the baseline `wip-main` ancestor `ff3711dc` and the tip. A section is done when the "look for" column is true. + +## A. Revisions that change what the daemon does (BEHAVIOUR) + +| Revision | What changed | Look for on a Mac | +|---|---|---| +| `ummqkuvp` 01b9cbed `fix(mac): take the rule-list locks in one order...` | `window_is_eligible` (window.rs) and `apply_globals` (static_config.rs) now lock floating, ignore, manage, regex in that order; before they locked regex, ignore, manage and ignore, regex, manage. The order is documented at the statics in lib.rs. Same fix as the KDE `ef1d3ef0`. | Run `komorebic reload-configuration` (and `komorebic replace-configuration`) in a loop of 50 while opening and closing windows (new Finder windows, Terminal tabs) at the same time. Before the fix this could hang the daemon (the command is never answered, new windows are not tiled). Expected: no hang, every reload answered. Also check that float rules, ignore rules and manage rules from the config and from `komorebic float-rule`/`ignore-rule`/`manage-rule` still apply to new windows. | +| `nvwvptpv` 866b2840 `use the shared command listener` | The UDS command accept loop and per-client reader are the shared `komorebi-transport` code (`NoPolicy`: no read timeouts, as before); `WindowManager` is a `CommandTarget` (lock with `try_lock_for`). | Every `komorebic` command is answered; a command sent while the daemon is busy gets an answer or a clean error, not a hang; kill the daemon mid-command: the client returns. | +| `ywwwwpwm` 587defe3 `use the shared pause filter` | `allowed_while_paused` lists the commands allowed while paused. | `komorebic toggle-pause`; while paused only `toggle-pause`, `state`, `global-state`, `stop` work, everything else is ignored (and the connection ends); unpause and check windows tile again. | +| `kzynysto` b85827e6 `use the shared subscriber push` | Subscriber sockets are pushed to by the shared `notify_sockets`; the macOS override events are kept. | `komorebic subscribe-socket` (and `subscribe-socket-with-options`): events arrive for focus, move, workspace change, monitor change, theme and config reload; a subscriber that goes away is dropped without breaking the others. The bar is a subscriber, so the bar updating is the check. | +| `ovsplvmn` 5cc38da6 `use EventChannel for the window events` | The window-event channel (capacity 20, try_send, drop warning, `ResizeStep` claim flag) is `komorebi_transport::EventChannel`. | Drag a window edge continuously (live resize) and pan with the trackpad: no stalls, no repeated drop warnings in the log, the layout follows. Move many windows at once (workspace switch with 10+ windows). | +| `lrqkuuzq` a4996ac6 `use SocketMessage from komorebi-protocol` and `sowrttxs` 5c129ab5 `carry DebugWindow as i64` | One `SocketMessage` for all platforms; the wire format must be unchanged. `DebugWindow` takes an i64 (a negative id parses and matches nothing). | Every command of the `komorebic` help works against the daemon; `komorebic debug-window ` for a real id; `komorebic state` and `global-state` JSON parse. | +| `qqwoptqt` 975f007a, `yptnnkxv` eb903bcc (animation prefix, Bezier doc) | `AnimationPrefix` gains `Transparency` (ignored by the daemon); schema.json changed the shape of per-prefix animation settings. | Config with `animation.style` / `duration` per prefix (movement, workspace) still loads; animations behave as before. Run `komorebic static-config-schema` and diff with `komorebi-for-mac/schema.json` (two description-level changes and the per-prefix shape are intended). | +| `kvtvnouo` 93e4d511, `stxmqnop` dec91984 (StaticConfig from komorebi-config) | The config data types and their defaults come from `komorebi-config`; `komorebic static-config-schema` prints the macOS view. | A real `komorebi.json` of yours loads with no new warning and every key still takes effect (borders, padding, animations, scrolling, rules, workspaces); `komorebic static-config-schema` matches the checked-in `schema.json` up to the intended description lines. | +| `qukywpss` c46320ea, `zwkwptox` 1e902542, `sxptsttt` 0345fccb (komorebic shares clap definitions, launcher, pan) | `komorebic start` and `stop` use the shared Launcher skeleton (the odd `--config` arguments are kept; "Waiting for komorebi to start..." is flushed); pan commands use the shared module. | `komorebic start --bar`, `start --await-configuration`, `stop`, `stop --bar`; `komorebic pan-*` commands; `komorebic --help` and a few ` --help` texts (about 15 help texts changed to the Windows wording). | +| Bar: `nottqpms` 086833af, `zvuyspku` b8de056b, `uxzpkmnk` 7cd85bd4, `yopuwouu` 6da27dda (bar-core, platform hooks) | macOS now builds `sysinfo` 0.39 and `starship-battery` 0.11 (the Windows versions); cpu, battery, memory, date, update widgets are the shared code. | Bar renders; CPU %, memory, battery % and charging state show sane values; date and the calendar icon; clicking CPU, battery, network, update (see bug list D below: these click handlers are broken on macOS and stay broken). | + +Revisions in section B change no behaviour on purpose (rename, move, route); they still need the sections C walk-through, because a mechanical mistake would show there. + +## B. Mechanical macOS revisions of the `kfm` agent (Step 6 and 11(i)) + +| Revision | Change | +|---|---| +| `vzxkxzzy` 796c3832 | `Window::frame()` (renamed `window_rect` below) for the 28 sites that read a Window's frame through `MacosApi::window_rect(&w.element)` (window.rs, window_manager.rs, workspace.rs, process_event.rs, process_command.rs, settle.rs, macos_backend.rs) | +| `oootynxk` 7c2e1bea | `Window::is_valid` renamed `Window::alive` | +| `roxrxtru` 49a6dbda | `Window::set_position` renamed `Window::set_rect` (10 callers) | +| `vmnnuzzu` 803a1410 | `Window::set_messaging_timeout` (settle.rs: 3 raw AX sites) | +| `upylxxuw` ecaa3e15 | `Window::close` (the same close-button press as `AdhocWindow::close`) | +| `tsymmvll` d30a3eb6 | step 11(i): `MacosBackend` calls only `Window` methods (new `Window::minimized`); still unused by the daemon | +| `qsrxvsmv` 931b17d7 | `Window::frame` renamed `Window::window_rect` (the Backend and the Windows Window use that name) | + +Hand check: C below. If something breaks and is not the lock order, bisect among these seven first: they only rename and route, so a regression means a call was routed to the wrong receiver (type-check cannot tell a Window from another window of the same type). + +## C. Walk-through (the list the plan names) + +Do each with the baseline build and the tip build and compare (or record with `komorebi-recorder`). + +1. **Focus**: `komorebic focus left|right|up|down`, `cycle-focus`, `focus-window `; mouse-follows-focus on/off (the cursor centres in the window: uses the window frame query); focus a window of a tabbed app (Terminal, Finder): the focus uses `element_to_focus`, check the right tab. +2. **Move and resize**: `move`, `resize-axis`, `resize-edge` and a manual drag of a window; after a drag the layout puts the window back (settle reads the frame with a timeout); live resize of one edge moves the neighbour. A window that refuses a width (a fixed size app) is read back and the neighbours adapt. +3. **Stack**: `stack`, `unstack`, `cycle-stack`, `stack-all`; hidden stack members are parked off-screen (`hide`) and restored (`restore`) correctly; no window left at a hidden corner after unstack or quit. +4. **Workspaces**: switch (`focus-workspace`), send a window (`send-to-workspace`), `move-to-workspace`, with 2 monitors if possible; windows of the workspace you left are hidden, those of the new one restored to where they were; workspace rules after a monitor change. +5. **Scrolling layout**: the scrolling layout, `pan` commands, `scroll-*`; windows slide in from the edge (the arrival/slide code reads the frame). +6. **Pan** (trackpad gesture) and **live resize**: `komorebic pan-*`, three-finger style gestures as you configured them. +7. **Borders**: focused/unfocused/stack colours follow focus and follow animated windows; borders vanish and come back on workspace switch; no border left behind after closing a window (the window's close and borders share the observer code). +8. **Animations**: movement and workspace animations on and off; the ghost images; cancel an animation by issuing a new command in the middle. +9. **Display change**: plug or unplug a monitor or change the resolution: work areas update, workspaces go to the right monitors, workspace rules re-apply. (This is the thread that can deadlock, see bug list A.) +10. **Sleep and wake**: close the lid or sleep, wake: windows are where they were, the daemon answers, the bar returns. +11. **Minimize, unminimize, close**: `komorebic minimize`, `close` (the foreground window), un-minimize a window from the Dock; closing a window removes it from its container (the reaper uses `Window::alive`). +12. **Reload the config** repeatedly (see section A, first row). + +## D. Bugs noticed, not fixed here + +A. **Possible deadlock, main queue against the window-manager lock** (`docs/dev/seam.md` section 3.3, by reading only, never reproduced). A thread holding the WM lock calls a blocking main-queue dispatch (`destroy_all_borders` at process_event.rs lines about 128/139, process_command.rs, `retile_all`; `hide_borders_on` in window_manager.rs; `activate_finder` in process_event.rs) while the monitor reconciliator has dispatched a closure to main that itself takes the WM lock (monitor_reconciliator.rs about 106 and 383). Then the event thread waits for main, main waits for the lock. `parking_lot`'s deadlock detector cannot see it (the dispatch is a semaphore). Window of exposure: a display change at the instant of one of those events. Structural fix: no closure that runs on main may take the WM lock (or dispatch to main only after the lock is dropped). How to provoke it: spam `komorebic retile` / workspace switches (with ghosts) while plugging or unplugging a monitor; the symptom is a daemon that answers no command (`komorebic state` hangs). +B. **cmd.exe and explorer.exe in the macOS bar** (`komorebi-for-mac/komorebi-bar/src/os.rs`, `BarPlatform::open_system_tool`): the battery click spawns `cmd.exe` (power settings), the update click spawns `explorer.exe` with the release URL; neither exists on macOS. The same file's CPU (task manager) and network settings tools should be Activity Monitor and System Settings. The fix is one function in that file; it was preserved on purpose during the bar move. +C. **Update widget refresh thread polls the Windows repo's GitHub API** on macOS too (update.rs has a second URL that does not go through the hook), and the macOS update link is `.../releases/v..` built for the Windows repo. +D. **Other raw AX sites remain outside `Window`**: window.rs (38 inside `Window`/`AdhocWindow`, expected), application.rs 11 (`Application`, not a window), process_event.rs 7 (events that hand over a bare element: `window_id` of an element, the tab check `AccessibilityApi::window_id(&window.element.0)`), animation/animator.rs 6 (lane threads hold `WindowHandle` clones of the element), border_manager 7 (observers on tracked elements), window_manager.rs 4 (timeouts list holds elements, `window_id` of an element), reaper.rs 2 (`notify_if_gone` takes an element so lanes can use it), input_event_listener.rs 1, process_command.rs 1. They need either an id to AX registry (step 11(ii), not started) or a `WindowHandle` type; they were left alone because routing them changes who owns the element. +E. `MacosBackend` (step 7c/11(i)) needs 11(ii) before it can be used: `windows()` answers only what was `register`ed, `hide` needs the corner, `raise` also focuses, `monitors()` reads a cache nobody fills yet (seam.md section 9.2). `AdhocWindow` (bare foreground element) still has its own minimize, close, hide, restore, raise. +F. In `window.rs` `AdhocWindow::hide` / `Window::hide` duplicate the restore-position bookkeeping (`WINDOW_RESTORE_POSITIONS`), one on a `Window` and one on a bare element; they must stay in step. + +## E. What is not checked at all + +Everything above. In particular: no macOS test (399+ unit tests incl. those in window.rs for drag state) has run against any of these revisions; the unified binaries do not exist yet; no real Accessibility call was made; `komorebi-recorder` captures need a Mac. From 4c9094d776bc72f89f1c9ea265fd34cb8805bf7f Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:08:54 -0700 Subject: [PATCH 10/44] feat(backend): Registry, a thread-safe table from WindowId to a platform handle Step 11(ii), the pure part. macOS cannot act on a window from its id: it needs the Accessibility element, the pid and the observer. Registry is that table, generic over the handle so that its rules run on any host. Rules, written at the top of registry.rs and tested: thread-safe; a lookup clones the handle and releases the lock before anything is done to it; a removed or replaced handle is handed back to the caller instead of being dropped under the lock (dropping a macOS handle can make an AX round trip, which must never happen with a lock held: seam.md 3.3); a stale or unknown id is Error::WindowGone, never a panic; an entry ends on remove, remove_pid (application quit) or a failed call; re-inserting replaces. Nothing uses it yet; no daemon changes. Verified: native cargo test -p komorebi-backend: 38 unit (9 new) + 7 doc (1 new) + 1 compile_fail passed, 0 failed. Not run: the Windows, KDE and macOS checks (the new module is std-only and no other file changed). --- crates/komorebi-backend/src/lib.rs | 2 + crates/komorebi-backend/src/registry.rs | 312 ++++++++++++++++++++++++ 2 files changed, 314 insertions(+) create mode 100644 crates/komorebi-backend/src/registry.rs diff --git a/crates/komorebi-backend/src/lib.rs b/crates/komorebi-backend/src/lib.rs index 8fbde7df..20ce1958 100644 --- a/crates/komorebi-backend/src/lib.rs +++ b/crates/komorebi-backend/src/lib.rs @@ -31,6 +31,7 @@ mod error; pub mod fake; mod id; mod info; +mod registry; pub use backend::Backend; pub use backend::Batch; @@ -41,4 +42,5 @@ pub use id::MonitorId; pub use id::WindowId; pub use info::MonitorInfo; pub use info::WindowInfo; +pub use registry::Registry; pub use komorebi_layouts::Rect; diff --git a/crates/komorebi-backend/src/registry.rs b/crates/komorebi-backend/src/registry.rs new file mode 100644 index 00000000..aae9940c --- /dev/null +++ b/crates/komorebi-backend/src/registry.rs @@ -0,0 +1,312 @@ +//! A thread-safe table from a [`WindowId`] to whatever a platform needs in order to act on that +//! window from nothing but the id. +//! +//! macOS is the platform that needs it: a window there is an Accessibility element with the pid +//! of its application and the observer that reports its events, and nothing can be done to a +//! window without them. The table is generic over the handle (`H`) so that its rules can be +//! tested on any host with a stand-in handle; macOS instantiates it with its Accessibility types. +//! +//! # Rules +//! +//! 1. **Thread-safe.** Any thread may call any method. +//! 2. **Nothing of the platform runs under the lock.** [`Registry::get`] clones the handle (the +//! handle must be cheap to clone: a retained reference) and returns; the caller acts on the +//! clone with the lock released. A method that removes an entry hands the removed handle back +//! to the caller instead of dropping it inside, because dropping a macOS handle can make an +//! Accessibility round trip. This is what keeps a registry call from ever waiting on the main +//! queue, or on an application, while holding the lock (`docs/dev/seam.md` section 3.3). +//! 3. **A stale id is an error, not a panic.** Looking up an id that was never registered, was +//! removed, or was removed with its application answers [`Error::WindowGone`]. +//! 4. **Entries end** when the window is destroyed ([`Registry::remove`]), when its application +//! quits ([`Registry::remove_pid`]), and when a call on the window shows that it is gone. An +//! entry that nobody removes is a leak of a retained element; the platform removes at every +//! place it learns of a death. +//! 5. **Re-registering an id replaces the entry** and returns the old handle (a tab that is +//! now shown by another element keeps the window id). +//! +//! ``` +//! use komorebi_backend::Registry; +//! use komorebi_backend::WindowId; +//! +//! let registry: Registry<&'static str> = Registry::new(); +//! let id = WindowId::from_u32(7); +//! registry.insert(id, 100, "element"); +//! assert_eq!(registry.get(id).unwrap(), "element"); +//! +//! registry.remove(id); +//! assert!(registry.get(id).unwrap_err().is_window_gone()); +//! ``` + +use crate::Error; +use crate::Result; +use crate::WindowId; +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::MutexGuard; + +struct Entry { + pid: i32, + handle: H, +} + +/// The table. See the [module documentation](self) for its rules. +pub struct Registry { + entries: Mutex>>, +} + +impl Default for Registry { + fn default() -> Self { + Self::new() + } +} + +impl Registry { + /// Returns an empty registry. + pub fn new() -> Self { + Self { + entries: Mutex::new(HashMap::new()), + } + } + + // a thread that panicked while holding the lock cannot have left an entry half written (every + // method is a single map operation), so a poisoned lock is still good + fn lock(&self) -> MutexGuard<'_, HashMap>> { + self.entries.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Registers the window, owned by the process `pid`. Returns the handle that this replaces, + /// if the id was registered: the caller drops it, with no lock held. + #[must_use = "drop the replaced handle yourself: it is not dropped under the lock"] + pub fn insert(&self, id: WindowId, pid: i32, handle: H) -> Option { + self.lock().insert(id, Entry { pid, handle }).map(|e| e.handle) + } + + /// Replaces the handle of a window that is registered, keeping its pid. Returns the old + /// handle, or [`Error::WindowGone`] (and registers nothing) if the id is not registered. + pub fn replace(&self, id: WindowId, handle: H) -> Result { + match self.lock().get_mut(&id) { + Some(entry) => Ok(std::mem::replace(&mut entry.handle, handle)), + None => Err(Error::WindowGone(id)), + } + } + + /// Forgets the window. Returns its handle (for the caller to drop with no lock held), or + /// `None` if it was not registered, which is not an error: a death is usually seen twice. + #[must_use = "drop the removed handle yourself: it is not dropped under the lock"] + pub fn remove(&self, id: WindowId) -> Option { + self.lock().remove(&id).map(|e| e.handle) + } + + /// Forgets every window of the process, as when its application quits. Returns the ids and + /// handles removed, sorted by id. + #[must_use = "drop the removed handles yourself: they are not dropped under the lock"] + pub fn remove_pid(&self, pid: i32) -> Vec<(WindowId, H)> { + let mut entries = self.lock(); + let ids: Vec = entries + .iter() + .filter(|(_, e)| e.pid == pid) + .map(|(id, _)| *id) + .collect(); + let mut removed: Vec<(WindowId, H)> = ids + .into_iter() + .filter_map(|id| entries.remove(&id).map(|e| (id, e.handle))) + .collect(); + drop(entries); + removed.sort_by_key(|(id, _)| *id); + removed + } + + /// Whether the id is registered. + pub fn contains(&self, id: WindowId) -> bool { + self.lock().contains_key(&id) + } + + /// The pid of the registered window, or [`Error::WindowGone`]. + pub fn pid(&self, id: WindowId) -> Result { + self.lock() + .get(&id) + .map(|e| e.pid) + .ok_or(Error::WindowGone(id)) + } + + /// How many windows are registered. + pub fn len(&self) -> usize { + self.lock().len() + } + + /// Whether nothing is registered. + pub fn is_empty(&self) -> bool { + self.lock().is_empty() + } + + /// The registered ids, sorted. + pub fn ids(&self) -> Vec { + let mut ids: Vec<_> = self.lock().keys().copied().collect(); + ids.sort(); + ids + } +} + +impl Registry { + /// A clone of the handle of the window, or [`Error::WindowGone`] for an id that is not + /// registered. The lock is released before this returns. + pub fn get(&self, id: WindowId) -> Result { + self.lock() + .get(&id) + .map(|e| e.handle.clone()) + .ok_or(Error::WindowGone(id)) + } + + /// Clones of every handle with their ids, sorted by id. + pub fn snapshot(&self) -> Vec<(WindowId, H)> { + let mut all: Vec<_> = self + .lock() + .iter() + .map(|(id, e)| (*id, e.handle.clone())) + .collect(); + all.sort_by_key(|(id, _)| *id); + all + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + + fn id(n: u32) -> WindowId { + WindowId::from_u32(n) + } + + #[test] + fn a_registered_window_is_found_by_its_id() { + let r = Registry::new(); + assert!(r.insert(id(1), 10, "a").is_none()); + assert!(matches!(r.get(id(1)), Ok("a"))); + assert!(matches!(r.pid(id(1)), Ok(10))); + assert!(r.contains(id(1))); + } + + #[test] + fn an_unknown_id_is_window_gone_and_not_a_panic() { + let r: Registry<&str> = Registry::new(); + assert!(matches!(r.get(id(9)), Err(Error::WindowGone(w)) if w == id(9))); + assert!(matches!(r.pid(id(9)), Err(Error::WindowGone(_)))); + assert!(r.get(id(9)).unwrap_err().is_window_gone()); + } + + #[test] + fn a_removed_window_is_stale() { + let r = Registry::new(); + let _ = r.insert(id(1), 10, "a"); + assert_eq!(r.remove(id(1)), Some("a")); + assert!(r.get(id(1)).unwrap_err().is_window_gone()); + // a death seen twice is not an error + assert_eq!(r.remove(id(1)), None); + } + + #[test] + fn reinserting_replaces_and_hands_back_the_old_handle() { + let r = Registry::new(); + let _ = r.insert(id(1), 10, "tab one"); + assert_eq!(r.insert(id(1), 10, "tab two"), Some("tab one")); + assert!(matches!(r.get(id(1)), Ok("tab two"))); + assert_eq!(r.len(), 1); + } + + #[test] + fn replace_keeps_the_pid_and_refuses_a_stale_id() { + let r = Registry::new(); + let _ = r.insert(id(1), 10, "a"); + assert!(matches!(r.replace(id(1), "b"), Ok("a"))); + assert!(matches!(r.pid(id(1)), Ok(10))); + assert!(r.replace(id(2), "c").unwrap_err().is_window_gone()); + assert!(!r.contains(id(2))); + } + + #[test] + fn an_application_quitting_takes_all_its_windows_and_only_them() { + let r = Registry::new(); + let _ = r.insert(id(3), 10, "c"); + let _ = r.insert(id(1), 10, "a"); + let _ = r.insert(id(2), 20, "b"); + + assert_eq!(r.remove_pid(10), vec![(id(1), "a"), (id(3), "c")]); + assert_eq!(r.ids(), vec![id(2)]); + assert!(r.get(id(1)).unwrap_err().is_window_gone()); + assert_eq!(r.remove_pid(10), vec![]); + } + + #[test] + fn snapshot_is_sorted_and_independent_of_later_changes() { + let r = Registry::new(); + let _ = r.insert(id(2), 1, "b"); + let _ = r.insert(id(1), 1, "a"); + let snap = r.snapshot(); + let _ = r.remove(id(1)); + assert_eq!(snap, vec![(id(1), "a"), (id(2), "b")]); + } + + /// A handle whose drop would, on macOS, make a round trip: it must not run under the lock. + struct Probe { + registry: Arc>>, + drops: Arc, + } + + impl Drop for Probe { + fn drop(&mut self) { + // would deadlock if the registry dropped the handle while holding its lock + let _ = self.registry.len(); + self.drops.fetch_add(1, Ordering::SeqCst); + } + } + + #[test] + fn handles_are_never_dropped_under_the_lock() { + let registry = Arc::new(Registry::new()); + let drops = Arc::new(AtomicUsize::new(0)); + let probe = |_: u32| { + Arc::new(Probe { + registry: registry.clone(), + drops: drops.clone(), + }) + }; + + let _ = registry.insert(id(1), 10, probe(1)); + // the replaced and the removed handles come back to us, so their drop runs here + drop(registry.insert(id(1), 10, probe(2))); + drop(registry.remove(id(1))); + let _ = registry.insert(id(2), 10, probe(3)); + drop(registry.remove_pid(10)); + + assert_eq!(drops.load(Ordering::SeqCst), 3); + assert!(registry.is_empty()); + } + + #[test] + fn many_threads_can_register_look_up_and_remove() { + let r = Arc::new(Registry::new()); + let threads: Vec<_> = (0..8u32) + .map(|t| { + let r = r.clone(); + std::thread::spawn(move || { + for n in 0..200u32 { + let wid = id(t * 1000 + n); + let _ = r.insert(wid, t as i32, n); + assert!(matches!(r.get(wid), Ok(v) if v == n)); + assert_eq!(r.remove(wid), Some(n)); + assert!(r.get(wid).unwrap_err().is_window_gone()); + } + }) + }) + .collect(); + + for t in threads { + t.join().unwrap(); + } + + assert!(r.is_empty()); + } +} From 386c5a79c619da076ba58034cf7fea652979a4b4 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:08:57 -0700 Subject: [PATCH 11/44] refactor(mac): ax_registry, the id -> {element, observer, application} table Step 11(ii), first part. New module ax_registry.rs instantiates komorebi_backend::Registry (rules tested natively in 4c9094d7) with AxEntry {element, observer, application with its pid}; lifetime and thread rules are written at the top of the file: entries end on Window::drop of a dead window, reaper reaping and application termination (wired in the next revisions); nothing in it dispatches to main or takes the WM lock; removed entries are dropped after the table's lock is released. Window gets entry() and from_entry() to convert. MacosBackend drops its private HashMap and looks windows up here (register and forget delegate), so the compile-only adapter now resolves an id the same way the daemon will. BEHAVIOUR: none yet, nothing registers (the adapter is still unused by the daemon). Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run on Linux. --- komorebi-for-mac/komorebi/src/ax_registry.rs | 104 ++++++++++++++++++ komorebi-for-mac/komorebi/src/lib.rs | 1 + .../komorebi/src/macos_backend.rs | 20 ++-- komorebi-for-mac/komorebi/src/window.rs | 20 ++++ 4 files changed, 132 insertions(+), 13 deletions(-) create mode 100644 komorebi-for-mac/komorebi/src/ax_registry.rs diff --git a/komorebi-for-mac/komorebi/src/ax_registry.rs b/komorebi-for-mac/komorebi/src/ax_registry.rs new file mode 100644 index 00000000..b72a13eb --- /dev/null +++ b/komorebi-for-mac/komorebi/src/ax_registry.rs @@ -0,0 +1,104 @@ +//! The id -> {AX element, pid, observer} table of step 11(ii): what lets anything act on a +//! window from nothing but its `WindowId`. +//! +//! It is `komorebi_backend::Registry` (whose rules are tested natively: thread-safe, nothing of +//! the platform runs under its lock, stale ids are `Error::WindowGone`) instantiated with +//! [`AxEntry`]. +//! +//! # Lifetime +//! +//! An entry is created by `Window::new` and by [`sync`] when a window's element or id changes +//! (a native tab). It ends at every place the daemon learns of a death: +//! +//! - `Window::drop`, when the window is no longer alive ([`forget`]); +//! - the reaper, when it reaps a window ([`forget`]); +//! - an application terminating ([`forget_pid`], from `WindowManagerEvent::Destroy`). +//! +//! A window that is alive and never managed stays registered until it dies or its application +//! quits: the entry only holds retained references that the `Window` clones held anyway. +//! +//! # Threads +//! +//! Callable from any thread. Nothing here dispatches to the main queue or takes the window +//! manager's lock (`docs/dev/seam.md` section 3.3); a closure that runs on the main thread may +//! call it. Handles removed from the table are dropped after the table's lock is released. + +use crate::AccessibilityObserver; +use crate::AccessibilityUiElement; +use crate::application::Application; +use crate::window::Window; +use komorebi_backend::Registry; +use komorebi_backend::Result; +use komorebi_backend::WindowId; +use std::sync::LazyLock; + +/// What it takes to act on one window: its element and observer, and its application (whose +/// element and observer are the application's, and whose `process_id` is the pid). +#[derive(Debug, Clone)] +pub struct AxEntry { + /// The window's Accessibility element + pub element: AccessibilityUiElement, + /// The observer that reports the window's events + pub observer: AccessibilityObserver, + /// The application that owns the window + pub application: Application, +} + +impl AxEntry { + /// The pid of the owning application + pub fn pid(&self) -> i32 { + self.application.process_id + } +} + +static WINDOWS: LazyLock> = LazyLock::new(Registry::new); + +/// Registers the window under its id, replacing what was registered under it. +pub fn register(window: &Window) { + let entry = window.entry(); + let pid = entry.pid(); + // the replaced entry is dropped here, with the table's lock released + drop(WINDOWS.insert(WindowId::from_u32(window.id), pid, entry)); +} + +/// A window changed its id or its element in place (a native tab that is now shown by another +/// element): forget the old id and register the window as it is. +pub fn sync(old_id: u32, window: &Window) { + if old_id != window.id { + forget(old_id); + } + + register(window); +} + +/// Forgets a window that is gone. A second call is not an error. +pub fn forget(id: u32) { + drop(WINDOWS.remove(WindowId::from_u32(id))); +} + +/// Forgets every window of a process that quit. +pub fn forget_pid(pid: i32) { + drop(WINDOWS.remove_pid(pid)); +} + +/// The entry of a window, or `Error::WindowGone` if the id is stale. +pub fn get(id: WindowId) -> Result { + WINDOWS.get(id) +} + +/// A `Window` made from the entry of the id, or `Error::WindowGone` if the id is stale. +pub fn window(id: WindowId) -> Result { + let entry = WINDOWS.get(id)?; + // an id that does not fit a `CGWindowID` cannot have been registered + let raw = id.to_u32().ok_or(komorebi_backend::Error::WindowGone(id))?; + Ok(Window::from_entry(raw, entry)) +} + +/// Every registered window, by id. +pub fn windows() -> Vec { + WINDOWS + .snapshot() + .into_iter() + .filter_map(|(id, entry)| Some(Window::from_entry(id.to_u32()?, entry))) + .collect() +} diff --git a/komorebi-for-mac/komorebi/src/lib.rs b/komorebi-for-mac/komorebi/src/lib.rs index c71b0d16..91909a7e 100644 --- a/komorebi-for-mac/komorebi/src/lib.rs +++ b/komorebi-for-mac/komorebi/src/lib.rs @@ -54,6 +54,7 @@ pub mod animation; pub mod app_kit_notification_constants; pub mod application; pub mod arrival; +pub mod ax_registry; pub mod border_manager; pub mod container; pub mod core; diff --git a/komorebi-for-mac/komorebi/src/macos_backend.rs b/komorebi-for-mac/komorebi/src/macos_backend.rs index c6b8e352..ea4096ef 100644 --- a/komorebi-for-mac/komorebi/src/macos_backend.rs +++ b/komorebi-for-mac/komorebi/src/macos_backend.rs @@ -9,7 +9,8 @@ //! `docs/dev/seam.md`, section 9, and commented where they are. //! //! The trait names a window by an id, and nothing on macOS acts from a bare id: a window is its -//! Accessibility element. So the adapter owns the **id registry** of consequence (1): the daemon +//! Accessibility element. So the backend looks windows up in the **id registry** of consequence +//! (1), `ax_registry`: the daemon //! registers each `Window` it learns of ([`MacosBackend::register`]) and forgets it when it is //! gone, and every method looks the element up by id. An id the registry does not hold is a //! window that is gone. @@ -34,7 +35,6 @@ use komorebi_backend::WindowId; use komorebi_backend::WindowInfo; use objc2::MainThreadMarker; use parking_lot::Mutex; -use std::collections::HashMap; /// The shared [`Backend`] for macOS. /// @@ -42,7 +42,6 @@ use std::collections::HashMap; /// opacity and no focus follows mouse (`docs/dev/seam.md` section 2.1), so those methods answer /// `Unsupported`. pub struct MacosBackend { - windows: Mutex>, monitors: Mutex>, hiding_position: WindowHidingPosition, batches: Mutex>, @@ -64,7 +63,6 @@ impl MacosBackend { /// the monitor's configuration, and the trait has no place for it. pub fn new(hiding_position: WindowHidingPosition) -> Self { Self { - windows: Mutex::new(HashMap::new()), monitors: Mutex::new(Vec::new()), hiding_position, batches: Mutex::new(Vec::new()), @@ -73,12 +71,12 @@ impl MacosBackend { /// Makes the window known to the backend, by its `CGWindowID`. pub fn register(&self, window: Window) { - self.windows.lock().insert(window.id, window); + crate::ax_registry::register(&window); } /// Forgets a window that is gone. pub fn forget(&self, id: u32) { - self.windows.lock().remove(&id); + crate::ax_registry::forget(id); } /// Reads the monitors from `NSScreen` into the cache that [`Backend::monitors`] answers @@ -102,9 +100,7 @@ impl MacosBackend { } fn lookup(&self, id: WindowId) -> Result { - id.to_u32() - .and_then(|raw| self.windows.lock().get(&raw).cloned()) - .ok_or(Error::WindowGone(id)) + crate::ax_registry::window(id) } /// Says why a call about a window failed. A failed write is how macOS finds out that a window @@ -131,9 +127,7 @@ impl MacosBackend { id: WindowId::from_u32(window.id), pid: window.application.process_id, // the Accessibility position and size, in points; a failure leaves the default - rect: window.window_rect() - .map(Rect::from) - .unwrap_or_default(), + rect: window.window_rect().map(Rect::from).unwrap_or_default(), minimized: window.minimized(), alive: true, title: window.title(), @@ -153,7 +147,7 @@ impl Backend for MacosBackend { // The registry is the only list there is: the CoreGraphics list joined with the // Accessibility elements by title lives inside `load_workspace_information`, which fills // a `WindowManager`, and the daemon registers what it finds - let registered: Vec<_> = self.windows.lock().values().cloned().collect(); + let registered = crate::ax_registry::windows(); let mut windows: Vec<_> = registered.iter().filter_map(Self::info).collect(); windows.sort_by_key(|w| w.id); windows diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 83279064..8dc9420e 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -569,6 +569,26 @@ impl Window { }) } + /// The handles that act on this window, as the registry keeps them + pub(crate) fn entry(&self) -> crate::ax_registry::AxEntry { + crate::ax_registry::AxEntry { + element: self.element.clone(), + observer: self.observer.clone(), + application: self.application.clone(), + } + } + + /// A window made from a registry entry + pub(crate) fn from_entry(id: u32, entry: crate::ax_registry::AxEntry) -> Self { + Self { + id, + element: entry.element, + application: entry.application, + observer: entry.observer, + details: None, + } + } + /// The frame query (`Backend::window_rect`): the Accessibility position and size, in points. pub fn window_rect(&self) -> Result { MacosApi::window_rect(&self.element) From f0b1a448d485d48645454a410ef47ffc38488143 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:10:16 -0700 Subject: [PATCH 12/44] refactor(mac): register every Window in ax_registry and forget the dead Step 11(ii), second part. BEHAVIOUR (memory and bookkeeping only; no AX call is added anywhere, and no existing call reads the table yet except the still-unused MacosBackend). Window::new registers the window under its id. Entries end where the daemon learns of a death: Window::drop when the window is no longer alive (next to the InvalidWindow notification it already sends), reap_window in the reaper, and WindowManagerEvent::Destroy for NSWorkspaceDidTerminateApplication (forget_pid, next to enhanced_ui::forget: a new process may reuse the pid). A live window that is never managed stays registered until it dies or its application quits; the table holds retained references that the Window clones held anyway. The native tab case (id and element changed in place) follows in its own revision. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run on Linux. Gate needed: the Mac hand check, see docs/dev/macos-handcheck.md (open and close many windows and quit apps; the daemon's memory must not grow; nothing else should look different). --- komorebi-for-mac/komorebi/src/process_event.rs | 1 + komorebi-for-mac/komorebi/src/reaper.rs | 3 +++ komorebi-for-mac/komorebi/src/window.rs | 12 ++++++++++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/process_event.rs b/komorebi-for-mac/komorebi/src/process_event.rs index 7c72b2f0..5467f52f 100644 --- a/komorebi-for-mac/komorebi/src/process_event.rs +++ b/komorebi-for-mac/komorebi/src/process_event.rs @@ -745,6 +745,7 @@ impl WindowManager { ) ) { enhanced_ui::forget(process_id); + crate::ax_registry::forget_pid(process_id); } // some apps like Discord in all of their relentless Electron slop stupidity diff --git a/komorebi-for-mac/komorebi/src/reaper.rs b/komorebi-for-mac/komorebi/src/reaper.rs index 9f06b359..362c95b1 100644 --- a/komorebi-for-mac/komorebi/src/reaper.rs +++ b/komorebi-for-mac/komorebi/src/reaper.rs @@ -111,6 +111,9 @@ fn invalid_window_ids( } fn reap_window(wm: &mut WindowManager, window_id: u32) -> color_eyre::Result<()> { + // whatever else happens to the window, the id no longer names anything + crate::ax_registry::forget(window_id); + let mut should_update = false; for monitor in wm.monitors_mut() { for workspace in monitor.workspaces_mut() { diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 8dc9420e..247b887e 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -476,6 +476,9 @@ impl Drop for Window { // for now - hopefully it doesn't break anything else reaper::send_notification(ReaperNotification::InvalidWindow(self.id)); + // and the id no longer names anything + crate::ax_registry::forget(self.id); + // make sure the observer gets removed from any run loops AccessibilityApi::invalidate_observer(&self.observer); } @@ -560,13 +563,18 @@ impl Window { Some(window_observer_callback), )?; - Ok(Self { + let window = Self { id: AccessibilityApi::window_id(&element)?, element: AccessibilityUiElement(element), application, observer: AccessibilityObserver(Some(observer)), details: None, - }) + }; + + // so that the window can be found again from its id alone + crate::ax_registry::register(&window); + + Ok(window) } /// The handles that act on this window, as the registry keeps them From e0687167b4ea50bf8c06a2c30175457e5d75d3f7 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:10:39 -0700 Subject: [PATCH 13/44] refactor(mac): keep ax_registry in step when a native tab changes a window's id Step 11(ii), third part. BEHAVIOUR (bookkeeping only). The two places in process_event.rs that swap a window's id and element in place when a native tabbed application shows another tab now call ax_registry::sync(old_id, window): the old id is forgotten and the window registered as it now is, so the table never names an element that the model has replaced. No AX call is added. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run on Linux. Gate needed: Mac hand check with a tabbed app (Terminal or Finder tabs; see docs/dev/macos-handcheck.md): switch tabs, close the first tab, focus the window by command; behaviour must match the baseline. --- komorebi-for-mac/komorebi/src/process_event.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/komorebi-for-mac/komorebi/src/process_event.rs b/komorebi-for-mac/komorebi/src/process_event.rs index 5467f52f..47f25fb4 100644 --- a/komorebi-for-mac/komorebi/src/process_event.rs +++ b/komorebi-for-mac/komorebi/src/process_event.rs @@ -316,8 +316,10 @@ impl WindowManager { workspace.containers_mut().get_mut(container_idx) && let Some(window) = container.focused_window_mut() { + let old_id = window.id; window.id = window_id; window.element = AccessibilityUiElement(element.clone()); + crate::ax_registry::sync(old_id, window); } // check monocle_container for tabbed applications @@ -349,8 +351,10 @@ impl WindowManager { && let Some(monocle) = workspace.monocle_container.as_mut() && let Some(window) = monocle.focused_window_mut() { + let old_id = window.id; window.id = window_id; window.element = AccessibilityUiElement(element.clone()); + crate::ax_registry::sync(old_id, window); } if first_tab_destroyed { From ba22e8dc5a3067df56ad8f69e16fc3723ad20a53 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:10:53 -0700 Subject: [PATCH 14/44] refactor(mac): turn a system-handed element into a window id in one place Step 11(ii), fourth part. The seven sites that derive a CGWindowID from an element that the system handed over (event tap, observer callbacks, the focused window of an app, the tab check) call ax_registry::identify instead of AccessibilityApi::window_id: input_event_listener.rs, process_command.rs, process_event.rs (5), window_manager.rs. It is the same call; the point is that an element becomes an id only here, which is the key the registry is filled under. Not behaviour: nothing changes at runtime. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run on Linux. --- komorebi-for-mac/komorebi/src/ax_registry.rs | 10 ++++++++++ komorebi-for-mac/komorebi/src/input_event_listener.rs | 3 +-- komorebi-for-mac/komorebi/src/process_command.rs | 3 +-- komorebi-for-mac/komorebi/src/process_event.rs | 9 ++++----- komorebi-for-mac/komorebi/src/window_manager.rs | 2 +- 5 files changed, 17 insertions(+), 10 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/ax_registry.rs b/komorebi-for-mac/komorebi/src/ax_registry.rs index b72a13eb..a3159dac 100644 --- a/komorebi-for-mac/komorebi/src/ax_registry.rs +++ b/komorebi-for-mac/komorebi/src/ax_registry.rs @@ -102,3 +102,13 @@ pub fn windows() -> Vec { .filter_map(|(id, entry)| Some(Window::from_entry(id.to_u32()?, entry))) .collect() } + +/// The `CGWindowID` of the window that an Accessibility element is, as handed over by the system +/// (an observer callback, the event tap, the focused window of an application). This is the one +/// way to turn an element into the key of the table; a window is registered under what it +/// returns. +pub fn identify( + element: &objc2_application_services::AXUIElement, +) -> std::result::Result { + crate::accessibility::AccessibilityApi::window_id(element) +} diff --git a/komorebi-for-mac/komorebi/src/input_event_listener.rs b/komorebi-for-mac/komorebi/src/input_event_listener.rs index f6154849..f2031c64 100644 --- a/komorebi-for-mac/komorebi/src/input_event_listener.rs +++ b/komorebi-for-mac/komorebi/src/input_event_listener.rs @@ -1,4 +1,3 @@ -use crate::accessibility::AccessibilityApi; use crate::macos_api::MacosApi; use crate::reaper; use crate::reaper::ReaperNotification; @@ -93,7 +92,7 @@ extern "C-unwind" fn callback( } if pid != 0 { - let window_id = AccessibilityApi::window_id(&element).ok(); + let window_id = crate::ax_registry::identify(&element).ok(); // Send MoveEnd to handle pending drag-to-swap operations // macOS doesn't reliably fire AXWindowMoved after mouse release diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index 686be380..f32d3680 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -9,7 +9,6 @@ use crate::SESSION_FLOATING_APPLICATIONS; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; use crate::WORKSPACE_MATCHING_RULES; -use crate::accessibility::AccessibilityApi; use crate::animation; use crate::animation::ANIMATION_DURATION_GLOBAL; use crate::animation::ANIMATION_DURATION_PER_ANIMATION; @@ -1718,7 +1717,7 @@ impl WindowManager { let application = Application::new(raw_info.owner_pid)?; if let Some(elements) = application.window_elements() { for element in elements { - if let Ok(wid) = AccessibilityApi::window_id(&element) + if let Ok(wid) = crate::ax_registry::identify(&element) && i64::from(wid) == window_id && let Ok(window) = Window::new(element, application.clone()) { diff --git a/komorebi-for-mac/komorebi/src/process_event.rs b/komorebi-for-mac/komorebi/src/process_event.rs index 47f25fb4..0a03bcd5 100644 --- a/komorebi-for-mac/komorebi/src/process_event.rs +++ b/komorebi-for-mac/komorebi/src/process_event.rs @@ -6,7 +6,6 @@ use crate::REGEX_IDENTIFIERS; use crate::TABBED_APPLICATIONS; use crate::UNMANAGED_WINDOW_IDS; use crate::WORKSPACE_MATCHING_RULES; -use crate::accessibility::AccessibilityApi; use crate::accessibility::enhanced_ui; use crate::accessibility::error::AccessibilityApiError; use crate::accessibility::error::AccessibilityError; @@ -182,7 +181,7 @@ impl WindowManager { { let application = self.application(event.process_id())?; if let Some(element) = application.main_window() - && let Ok(wid) = AccessibilityApi::window_id(&element) + && let Ok(wid) = crate::ax_registry::identify(&element) { window_id = Some(wid); window_element = Some(AccessibilityUiElement(element.clone())); @@ -296,7 +295,7 @@ impl WindowManager { // Additional check: verify the stored element belongs to this container // This prevents treating separate windows as tabs when they have matching geometry if let Ok(stored_window_id) = - AccessibilityApi::window_id(&window.element.0) + crate::ax_registry::identify(&window.element.0) && stored_window_id == window.id { // All checks pass: stored element matches container ID = true tab change @@ -538,7 +537,7 @@ impl WindowManager { { let application = self.application(process_id)?; if let Some(element) = application.main_window() - && let Ok(wid) = AccessibilityApi::window_id(&element) + && let Ok(wid) = crate::ax_registry::identify(&element) { window_id = Some(wid); window_element = Some(element.clone()); @@ -552,7 +551,7 @@ impl WindowManager { let tabbed_applications = TABBED_APPLICATIONS.lock(); if tabbed_applications.contains(&application_name) { // Get the window_id for the new window - if let Ok(new_window_id) = AccessibilityApi::window_id(element) { + if let Ok(new_window_id) = crate::ax_registry::identify(element) { for window in workspace.visible_windows().iter().flatten() { if window.application.name().unwrap_or_default() == application_name { diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index 5c2e8b4b..e3c29fe8 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -1180,7 +1180,7 @@ impl WindowManager { let mut valid_window_ids = vec![]; if let Some(elements) = application.window_elements() { for element in elements { - if let Ok(window_id) = AccessibilityApi::window_id(&element) { + if let Ok(window_id) = crate::ax_registry::identify(&element) { valid_window_ids.push(window_id); } } From 01b3bd5cea9a586bab6f876269430c01e702150a Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:11:28 -0700 Subject: [PATCH 15/44] refactor(mac): the live-resize step reads the dragged window's frame through Window Step 11(ii), fifth part. window_manager.rs cloned the dragged window's element out of the workspace only to call MacosApi::window_rect on it; it now asks the Window found in the container for window_rect (the same call on the same element). One raw AX site fewer outside Window. The error is the same one the old call returned, still propagated with ?. Not behaviour. Verified: macOS fake-CC type-check (tools/fast-check) PASS. Not verified: cannot run on Linux. --- komorebi-for-mac/komorebi/src/window_manager.rs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index e3c29fe8..c7435da3 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -2190,14 +2190,13 @@ impl WindowManager { return Ok(()); } - let element = self - .focused_workspace()? - .container_for_window(window_id) - .and_then(|container| container.windows().iter().find(|w| w.id == window_id)) - .map(|window| window.element.clone()) - .ok_or_eyre("the dragged window is not in a container on the focused workspace")?; - - let now = Rect::from(MacosApi::window_rect(&element)?); + let now = Rect::from( + self.focused_workspace()? + .container_for_window(window_id) + .and_then(|container| container.windows().iter().find(|w| w.id == window_id)) + .ok_or_eyre("the dragged window is not in a container on the focused workspace")? + .window_rect()?, + ); if !self.live_resize_apply(now)? { return Ok(()); From ec0d3923e52bbc72a27dc2b481013a8ad54974a8 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:12:30 -0700 Subject: [PATCH 16/44] docs(macos): add the id registry revisions to the hand-check list Adds the three BEHAVIOUR-relevant registry revisions (registration and forgetting, native-tab sync) with what to look for on a Mac, the mechanical ones to section B, and a status entry in the bug list saying what of step 11(ii) is done and what is deliberately not (animator lanes, borders, reaper/live-resize timeouts, the model holding bare ids). Verified: documentation only. --- docs/dev/macos-handcheck.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/dev/macos-handcheck.md b/docs/dev/macos-handcheck.md index 96a8933b..026ed895 100644 --- a/docs/dev/macos-handcheck.md +++ b/docs/dev/macos-handcheck.md @@ -17,6 +17,8 @@ How to use it: build the unified (or, until they exist, the per-tree) macOS `kom | `qqwoptqt` 975f007a, `yptnnkxv` eb903bcc (animation prefix, Bezier doc) | `AnimationPrefix` gains `Transparency` (ignored by the daemon); schema.json changed the shape of per-prefix animation settings. | Config with `animation.style` / `duration` per prefix (movement, workspace) still loads; animations behave as before. Run `komorebic static-config-schema` and diff with `komorebi-for-mac/schema.json` (two description-level changes and the per-prefix shape are intended). | | `kvtvnouo` 93e4d511, `stxmqnop` dec91984 (StaticConfig from komorebi-config) | The config data types and their defaults come from `komorebi-config`; `komorebic static-config-schema` prints the macOS view. | A real `komorebi.json` of yours loads with no new warning and every key still takes effect (borders, padding, animations, scrolling, rules, workspaces); `komorebic static-config-schema` matches the checked-in `schema.json` up to the intended description lines. | | `qukywpss` c46320ea, `zwkwptox` 1e902542, `sxptsttt` 0345fccb (komorebic shares clap definitions, launcher, pan) | `komorebic start` and `stop` use the shared Launcher skeleton (the odd `--config` arguments are kept; "Waiting for komorebi to start..." is flushed); pan commands use the shared module. | `komorebic start --bar`, `start --await-configuration`, `stop`, `stop --bar`; `komorebic pan-*` commands; `komorebic --help` and a few ` --help` texts (about 15 help texts changed to the Windows wording). | +| `oywqqkuy` f0b1a448 `register every Window in ax_registry and forget the dead` | `Window::new` registers the window in the id registry (`ax_registry`); entries are removed in `Window::drop` of a dead window, in `reap_window`, and (`forget_pid`) when an application terminates. No AX call is added; the table holds retained AX references and observers. | Open and close 50 windows (Finder, Terminal, Safari) and quit several apps, then check the daemon's memory in Activity Monitor does not climb and nothing behaves differently (focus, tiling, borders). If a quit app's windows were not forgotten the symptom is memory growth only. Run with `RUST_LOG=debug` and check no new errors at app quit. | +| `oqnvyqvw` e0687167 `keep ax_registry in step when a native tab changes a window's id` | The two places that swap a window's id and element in place for native tabs also update the registry (`sync`). | A native-tabbed app (Terminal, Finder, Safari tabs): switch tabs, close the first tab, open a new tab, focus the window with `komorebic focus ...`, move and resize it. Must behave as on the baseline (no window lost, no stuck border). | | Bar: `nottqpms` 086833af, `zvuyspku` b8de056b, `uxzpkmnk` 7cd85bd4, `yopuwouu` 6da27dda (bar-core, platform hooks) | macOS now builds `sysinfo` 0.39 and `starship-battery` 0.11 (the Windows versions); cpu, battery, memory, date, update widgets are the shared code. | Bar renders; CPU %, memory, battery % and charging state show sane values; date and the calendar icon; clicking CPU, battery, network, update (see bug list D below: these click handlers are broken on macOS and stay broken). | Revisions in section B change no behaviour on purpose (rename, move, route); they still need the sections C walk-through, because a mechanical mistake would show there. @@ -32,6 +34,10 @@ Revisions in section B change no behaviour on purpose (rename, move, route); the | `upylxxuw` ecaa3e15 | `Window::close` (the same close-button press as `AdhocWindow::close`) | | `tsymmvll` d30a3eb6 | step 11(i): `MacosBackend` calls only `Window` methods (new `Window::minimized`); still unused by the daemon | | `qsrxvsmv` 931b17d7 | `Window::frame` renamed `Window::window_rect` (the Backend and the Windows Window use that name) | +| `xrtqmxkp` 4c9094d7 | native: `komorebi_backend::Registry` (the rules of the id registry; 9 unit and 1 doc test run on Linux) | +| `tmmtuosy` 386c5a79 | `ax_registry` module; `MacosBackend` resolves ids through it (the adapter is still unused by the daemon) | +| `kvkxkqnx` ba22e8dc | `ax_registry::identify`: the 7 sites that turn a system-handed element into a window id (input_event_listener, process_command, process_event x5, window_manager) | +| `kpopuvoy` 01b3bd5c | live-resize step (window_manager.rs) reads the dragged window's frame through `Window::window_rect` | Hand check: C below. If something breaks and is not the lock order, bisect among these seven first: they only rename and route, so a regression means a call was routed to the wrong receiver (type-check cannot tell a Window from another window of the same type). @@ -58,6 +64,7 @@ A. **Possible deadlock, main queue against the window-manager lock** (`docs/dev/ B. **cmd.exe and explorer.exe in the macOS bar** (`komorebi-for-mac/komorebi-bar/src/os.rs`, `BarPlatform::open_system_tool`): the battery click spawns `cmd.exe` (power settings), the update click spawns `explorer.exe` with the release URL; neither exists on macOS. The same file's CPU (task manager) and network settings tools should be Activity Monitor and System Settings. The fix is one function in that file; it was preserved on purpose during the bar move. C. **Update widget refresh thread polls the Windows repo's GitHub API** on macOS too (update.rs has a second URL that does not go through the hook), and the macOS update link is `.../releases/v..` built for the Windows repo. D. **Other raw AX sites remain outside `Window`**: window.rs (38 inside `Window`/`AdhocWindow`, expected), application.rs 11 (`Application`, not a window), process_event.rs 7 (events that hand over a bare element: `window_id` of an element, the tab check `AccessibilityApi::window_id(&window.element.0)`), animation/animator.rs 6 (lane threads hold `WindowHandle` clones of the element), border_manager 7 (observers on tracked elements), window_manager.rs 4 (timeouts list holds elements, `window_id` of an element), reaper.rs 2 (`notify_if_gone` takes an element so lanes can use it), input_event_listener.rs 1, process_command.rs 1. They need either an id to AX registry (step 11(ii), not started) or a `WindowHandle` type; they were left alone because routing them changes who owns the element. +D2. **Step 11(ii) status.** Done: the id registry (`ax_registry`, over the tested `komorebi_backend::Registry`), populated at `Window::new`, kept in step for native tabs, emptied on death, reap and application quit; `MacosBackend` resolves ids through it. NOT done, on purpose, because each needs a decision that cannot be verified without a Mac: (a) the animator lanes (`WindowHandle`) keep their own snapshot of the element: a lane must keep writing to the element of the move it was given even if a tab swap replaced the registry entry, and replacing the snapshot by a lookup per write changes what a late write hits; (b) borders keep `tracking_element` (observer sources are added and removed on that exact element, on main); (c) `reaper::notify_if_gone` and the window manager's live-resize `timeouts` list take elements, including application elements, that are not registry entries; (d) `application.rs` is the application, not a window. (e) The model (`Window`, containers, workspaces) still holds `Window` values, not bare `WindowId`s: that is step 11(iii), after steps 8-9. A stale registry id answers `Error::WindowGone` (no panic); a window that was deserialised from state (default system-wide element) is never registered. E. `MacosBackend` (step 7c/11(i)) needs 11(ii) before it can be used: `windows()` answers only what was `register`ed, `hide` needs the corner, `raise` also focuses, `monitors()` reads a cache nobody fills yet (seam.md section 9.2). `AdhocWindow` (bare foreground element) still has its own minimize, close, hide, restore, raise. F. In `window.rs` `AdhocWindow::hide` / `Window::hide` duplicate the restore-position bookkeeping (`WINDOW_RESTORE_POSITIONS`), one on a `Window` and one on a bare element; they must stay in step. From 8f37b9aea6b54c84dbe97454cc252dad6d0999fb Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:00:18 -0700 Subject: [PATCH 17/44] 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 18/44] 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 19/44] 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 20/44] 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 21/44] 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 22/44] 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 23/44] 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 24/44] 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 25/44] wip From b580b29f4424adc5e50e14175f695172b663b891 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 10:23:05 -0700 Subject: [PATCH 26/44] 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 27/44] 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 28/44] 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 29/44] 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 30/44] 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 31/44] 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 32/44] 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 33/44] 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 34/44] 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 35/44] 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 36/44] 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 37/44] 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 38/44] 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 39/44] 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 40/44] 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 f861a03adb7045f97bc7c7d472817fa8a1b9cdc9 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:10:03 -0700 Subject: [PATCH 41/44] perf(nix): stamp the commit only into the final Windows package COMMIT_HASH was in commonArgs, so buildDepsOnly (about 1000 dependencies) and every check (clippy, nextest, fmt, deny) got a new derivation for every commit, even a docs-only one, and rebuilt in full. commonArgs now carries the constant "nix-check" (as the KDE flake already does) and only fullBuild, and so packages.default and the extracted binaries, gets the real commit. The e2e build keeps its own constant through the existing `commit` argument. Nothing the checks compile or test changes; only the string shadow_rs stamps into the check binaries. Verified (nix eval of drvPath in a throwaway git copy, 7 commits): the deps derivation is identical for a docs edit, a Windows source edit, another docs edit, a bar-core edit and a KDE-crate edit; clippy, nextest and fmt are unchanged by the docs edit and change only for source edits; packages.default changes with every commit (real commit embedded). Not verified by a build: needs one idle-host nix build (commands in tools/README.md). --- flake.nix | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/flake.nix b/flake.nix index 264b0d41..260f996b 100644 --- a/flake.nix +++ b/flake.nix @@ -235,7 +235,9 @@ # komorebic/build.rs downloads applications.json if it is missing, which # is not possible in the sandbox, so provide the pinned copy instead preBuild = "mkdir -p komorebic && cp ${inputs.asc}/applications.json komorebic/applications.json"; - COMMIT_HASH = commit; + # a constant, so that the dependencies and every check are the same + # derivations for every commit; only fullBuild stamps the real one + COMMIT_HASH = "nix-check"; # build inputs for cross-compilation nativeBuildInputs = [ @@ -278,6 +280,7 @@ individualCrateArgs // { pname = "komorebi-workspace"; + COMMIT_HASH = commit; } ); From 262f44d2b6431f5a312b1346a1a7e5e1e79a45cf Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:10:14 -0700 Subject: [PATCH 42/44] perf(nix): keep the VM library's unit tests out of the suites' source komorebiVm (the python package every KDE VM suite imports) took all of lib/, including lib/tests. The VM never runs those tests and setuptools does not package them, but editing one changed komorebiVm and so rebuilt every suite (34 of 34, about 50 min of the fast tier). It now takes lib/ minus lib/tests. libCheck (vm-lib) keeps its own source, so the unit tests still run. Verified (nix eval of drvPath in a throwaway git copy): an edit of lib/tests/test_keys.py leaves kfde-vm.stacks and kfde-vm.commands unchanged (before: both changed). Not verified by a build. --- komorebi-for-kde/nix/tests/vm/default.nix | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/komorebi-for-kde/nix/tests/vm/default.nix b/komorebi-for-kde/nix/tests/vm/default.nix index 0f50c371..79a8b274 100644 --- a/komorebi-for-kde/nix/tests/vm/default.nix +++ b/komorebi-for-kde/nix/tests/vm/default.nix @@ -40,7 +40,9 @@ let pyproject = true; src = lib.fileset.toSource { root = ./lib; - fileset = ./lib; + # not the unit tests: the VM never runs them (setuptools does not package them), so + # editing one must not rebuild every suite; `libCheck` keeps them + fileset = lib.fileset.difference ./lib ./lib/tests; }; build-system = [ ps.setuptools ]; dependencies = [ ps.pillow ]; From 50029890538568935a76c66167435d139dbdcc9a Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:10:14 -0700 Subject: [PATCH 43/44] perf(nix): narrow the KDE source to its cargo closure The KDE source filter took all of crates/, so an edit of crates/komorebi-bar-core, which KDE does not depend on, changed every KDE check and VM suite derivation. The filter now takes the nine crates of the root workspace in the KDE cargo closure, listed in komorebi-for-kde/nix/root-crates.json (read by the flake and by tools/kde-closure-check, which fails if the list differs from `cargo metadata` of the KDE workspace; a new dependency is therefore a check failure, not a silent skip). The crates/ directory itself still passes the filter so that its listed members are reached. Safety: komorebi-gui, komorebi-bar and the e2e crates are already absent from the KDE source while the root manifest lists them as members, so a missing member directory is already tolerated. Not proven by a build. Verified (nix eval of drvPath in a throwaway git copy, 7 commits): an edit of crates/komorebi-bar-core leaves kfde clippy, nextest, the packages and kfde-vm.stacks and .commands unchanged (before: all changed); an edit of crates/komorebi-config changes them; the kfde package still evaluates. tools/kde-closure-check passes, and fails when a crate is removed from the list. --- komorebi-for-kde/flake.nix | 14 +++++++------- komorebi-for-kde/nix/root-crates.json | 11 +++++++++++ 2 files changed, 18 insertions(+), 7 deletions(-) create mode 100644 komorebi-for-kde/nix/root-crates.json diff --git a/komorebi-for-kde/flake.nix b/komorebi-for-kde/flake.nix index ea34b59a..1672f309 100644 --- a/komorebi-for-kde/flake.nix +++ b/komorebi-for-kde/flake.nix @@ -36,12 +36,10 @@ crane rust-overlay ; - rootCrates = [ - "crates" - "komorebi-layouts" - "komorebi-scrolling" - "komorebi-themes" - ]; + # the crates of the root workspace that this workspace depends on, by path, directly or not. + # Only these are in the source, so that an edit of another crate (the bar's) changes nothing + # here. `tools/kde-closure-check` fails if this list and `cargo metadata` differ. + rootCrates = builtins.fromJSON (builtins.readFile ./nix/root-crates.json); mkPkgs = system: import nixpkgs { @@ -73,8 +71,10 @@ rootCrate = builtins.any ( crate: relative == crate || pkgs.lib.hasPrefix "${crate}/" relative ) rootCrates; + # the directory that holds the crates of crates/, to reach the listed ones + rootCrateParent = relative == "crates"; in - (rootCrate && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || inTree) + ((rootCrate || rootCrateParent) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || inTree) && # the VM tests (their library, scripts and the states they keep) are not built, so # editing one does not change the source the daemon is built from diff --git a/komorebi-for-kde/nix/root-crates.json b/komorebi-for-kde/nix/root-crates.json new file mode 100644 index 00000000..a764d830 --- /dev/null +++ b/komorebi-for-kde/nix/root-crates.json @@ -0,0 +1,11 @@ +[ + "crates/komorebi-backend", + "crates/komorebi-collections", + "crates/komorebi-config", + "crates/komorebi-protocol", + "crates/komorebi-transport", + "crates/komorebic-core", + "komorebi-layouts", + "komorebi-scrolling", + "komorebi-themes" +] From 374269646ed5fd6373f3406071fb0cd8299a619f Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 11:26:24 -0700 Subject: [PATCH 44/44] docs: unified komorebi, komorebic and komorebi-bar packages (layout, migration order, risks) Records the spike (revisions on wip-u-pkg-spike, nothing landed on wip-main): one root workspace holds the Windows, KDE and macOS crates with one Cargo.lock (+41 packages), the unified komorebic builds on all three targets, KDE tests pass unchanged except one test that reads the package name. Recommends komorebic and bar as one crate with cfg(target_os) modules and the daemon as three gated libraries behind one thin binary, lists the migration order, risks, gates (compile, S oracle, nix, e2e, KDE VM, Mac hand check) and the file moves that conflict with the open wip-u-* stacks. Verified: Windows cargo check -p komorebic, KDE check and 879 of 880 tests, macOS fake-CC check, all on the spike tree. Not verified: nix builds, e2e, VM, any macOS link or run. --- docs/dev/unified-binaries.md | 177 +++++++++++++++++++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 docs/dev/unified-binaries.md diff --git a/docs/dev/unified-binaries.md b/docs/dev/unified-binaries.md new file mode 100644 index 00000000..e76b84b9 --- /dev/null +++ b/docs/dev/unified-binaries.md @@ -0,0 +1,177 @@ +# One `komorebi`, one `komorebic`, one `komorebi-bar` + +Goal: three packages and three binaries that build on Windows, KDE (Linux) and macOS, the platform +chosen by `cfg(target_os)` (generics, `cfg_select!`, exhaustive `match`; no macros as a design tool). +This file records a spike (throwaway revisions on bookmark `wip-u-pkg-spike`, titled `spike:`; nothing +landed on `wip-main`), the layout it recommends, the migration order, the risks and the gates. + +Measured on `wip-main` 633e7453 with the light gates only (`nice -n 19`, 3 jobs, persistent target +dirs, `COMMIT_HASH=dev`); no nix build, no e2e, no VM. macOS is type-checked with the fake CC only: it +was never linked or run. + +## What the spike did + +1. `spike: one root workspace ...` (rev `yuuyzssl`): the 10 KDE and macOS member crates became members + of the root workspace. Their two `[workspace]` manifests were deleted, their `workspace = true` + dependencies were written out, packages renamed (`komorebi-linux`, `komorebic-linux`, + `komorebi-client-linux`, `komorebi-hotkeys-linux`, `version-linux`, and `-macos` for the macOS + ones including `komorebi-bar-macos`); binary and lib names stayed (`[lib] name`, `[[bin]] name`) so + no source file changed. One `Cargo.lock`. +2. `spike: unified komorebic package by #[path] includes`: the root `komorebic` package became the + unified one. `src/main.rs` is a `cfg_select!` over `target_os` that includes the old Windows + `main.rs` (moved to `windows.rs`) and, by `#[path]`, the KDE and macOS `main.rs` where they live. + Dependencies are in `[target.'cfg(...)'.dependencies]` tables. Edits to the old files: `fn main` + became `pub fn main`; `crate::HOME_DIR` became `super::HOME_DIR` in KDE `hotkeys.rs`. +3. `spike: target-gate the macOS daemon crate`: objc2 and friends under + `[target.'cfg(target_os = "macos")'.dependencies]` plus `#![cfg(target_os = "macos")]` in + `komorebi-macos`, to test `cargo check --workspace` on a foreign target. + +The script that did step 1 is `S/pkg-spike.py` (scratchpad; rerunnable on a fresh `wip-main`). + +## Results + +| question | result | +|---|---| +| One lock resolves? | Yes. 859 packages (root) -> 900. All 859 Windows entries unchanged. The KDE lock had 644 and the macOS lock 786 entries, so +41 only. Crates with more than one version: 81 -> 95 (the `sysinfo` 0.38/0.39/0.40, `dirs` 6/7, `parking_lot` 0.12/0.13, `shadow-rs` 1/2, `netdev` 0.40/0.46 splits coexist; nothing needs unifying). | +| Locked versions kept? | Not exactly: crates that only KDE or macOS use were re-resolved to newest: `zbus`/`zbus_macros` 6.1 -> 6.2, `zbus_utils`, `zruntime`, `sysinfo` 0.40.0 -> 0.40.1, `libz-sys`, `unicode-width`. Pin with `cargo update zbus@6.2.0 --precise 6.1.0` (needs the `name@version` spelling) if the VM suites must see the old versions. | +| Windows `cargo check -p komorebic --target x86_64-pc-windows-msvc` (nix develop) | passes, 14.8 s wall warm (11.2 s compile); unified `komorebic` also passes, 7 s. | +| KDE native `cargo check -p komorebi-linux -p komorebic-linux` | passes; 1 m 38 s cold into a fresh lite target dir. Unified `komorebic` on Linux passes (1.4 s after touch) when openssl is available (see risk 2). | +| KDE tests unchanged | `cargo test -p komorebi-linux --lib`: 294 passed. `--test schemas -- --test-threads=1`: 5 passed. All four KDE packages, `--no-fail-fast`, 1 m 26 s warm: 879 passed, 1 failed. The failure is `tests/version.rs`: `komorebi-linux 0.1.0` instead of `komorebi 0.1.0` (clap takes the command name from `CARGO_PKG_NAME`); a renamed package needs `#[command(name = "komorebi")]`. Nothing else depends on the package name. | +| macOS fake-CC `cargo check --target aarch64-apple-darwin -p komorebi-macos -p komorebic-macos -p komorebi-bar-macos --all-targets --locked` | passes, 32 s warm (6 warnings in the bar, as before). Unified `komorebic` on macOS passes, 12 s. Type-check only. | +| Feature unification | Resolver 2 keeps `komorebi-layouts/darwin` off Windows: `cargo tree -p komorebic --target x86_64-pc-windows-msvc -e features -i komorebi-layouts` shows only `default`, the macOS package shows `darwin`. This holds only while the package that asks for `darwin` is not in the same build; `cargo ... --workspace` on one target selects them all (see risk 3). | +| `cargo check --workspace` for Windows (what clippy, fmt, nextest and crane do today) | FAILS in 52 s: `objc2 only works on Apple platforms`. With objc2 target-gated and `#![cfg(target_os = "macos")]`, `komorebi-macos` compiles empty on Windows (spike 3), so the fix is to gate every foreign-platform crate, not to exclude them. Done for one crate only. | +| Same dependency key, different path per target | REJECTED by cargo: `Dependency 'komorebi-client' has different source paths depending on the build target`. Same for `version`. So the unified package must use one key per platform (`komorebi-client-linux`, `komorebi-client-macos`, ...) and the platform module must alias it (`extern crate komorebi_client_linux as komorebi_client;` at the root, or `use komorebi_linux as komorebi;` at the top of each platform module). The spike used `extern crate`. | +| Compile time | No extra cost on a target: a build selects its own target's dependency tables, so Windows never sees zbus or objc2 and Linux never sees `windows`. The only added cost is resolution (`cargo metadata` 6.5 s with the network). | + +## Option A or B + +Measured size of what would have to move into `#[cfg(target_os)] mod` of one crate (Option B): +daemon `crate::` paths: Windows 669, KDE 447, macOS 587 (35,149 / 32,932 / 34,505 lines, 3 lib+bin +crates each with their own tests and a `komorebi-client` that re-exports them); bar 111 / 90 (7,710 / +5,551 lines); `komorebic` 0 (1,467 / 807 / 1,537 lines). + +Recommendation: + +- `komorebic`: B. One package `komorebic`, `src/main.rs` = `cfg_select!` choosing `mod windows`, + `mod linux`, `mod macos` (each the present `main.rs`, `hotkeys.rs` for Linux), one clap command name, + target-gated dependencies. Zero `crate::` rewrites, so the files move whole. This is what the spike + built (with `#[path]` instead of the final moves). +- `komorebi-bar`: B, as `bar-unification.md` already plans (`src/bar/{mod,windows,macos}.rs`, + `os/{windows,macos}.rs`); needs the bar stack integrated first. +- `komorebi` (daemon): A. Keep three library crates, rename to `komorebi-windows`, `komorebi-linux`, + `komorebi-macos` (distinct lib names, `komorebi_windows` etc.), each gated to its OS + (`#![cfg(target_os = ...)]`, target-gated dependencies, so `--workspace` works everywhere), each + keeping its own `crate::` paths and its own tests (KDE's 881 run unchanged but for the name). One + thin `komorebi` binary package: `src/main.rs` is a `cfg_select!` over the three daemons' + `main` bodies (each daemon's present `main.rs` becomes `pub fn run()` of its library). Option B for + the daemon would be a rewrite of about 1,700 `crate::` paths (669 + 447 + 587) for no behavioural gain, and it would + put KDE's tests and the VM suites on a moving target. +- `komorebi-client`: one package with `src/{windows,linux,macos}.rs` (211 / 394 / 225 lines, almost all + `pub use komorebi::...`), each starting with `use komorebi_windows as komorebi;` and so on. + +## Migration order + +Every revision keeps the three existing trees building with their present gates. "Gate" says what +must pass before it counts as landed: `C` compile (fast-check, the three checks), `S` the CLI oracle +(`S/step4/oracle-check.sh`, byte-identical for all three platforms; it reads `komorebic/src/main.rs` +of each tree, so it needs its paths updated in the revision that moves a file), `N` nix evaluation +(`nix flake show`), `NB` a nix build of the checks in an idle window, `E` Windows e2e, `V` KDE VM `fast`. + +0. Prerequisites, no moves (any time, small): explicit `#[command(name = ...)]` on the three CLIs; + `build.rs` of `komorebic` stops fetching `applications.json` over the network (the file is checked + in; a build script that needs `reqwest`, and so openssl, on Linux is what stopped the unified + package building natively); `pub fn main` and `crate::` -> `super::` in the `komorebic` files. + Gates C, S. Not behaviour. +1. Package renames inside the present workspaces (KDE: `komorebi-linux` and so on; macOS the same; + Windows daemon `komorebi-windows` last), with `[lib] name` and `[[bin]] name` unchanged. Gates C, + N; the Windows daemon rename is `E` (the executable's inputs change). +2. Workspace merge: delete `komorebi-for-kde/Cargo.toml` and `komorebi-for-mac/Cargo.toml`, add their + crates to the root members, write out the inherited dependencies, one lock (+41 packages), add + `.cargo/config.toml` with `[env] COMMIT_HASH` (KDE's file moves from `komorebi-for-kde/.cargo`; + cargo reads it from the working directory upward only). Same revision gates every foreign crate + (`#![cfg(target_os)]`, target-gated dependencies) so `--workspace` works on all targets. Gates C on + all three, plus KDE tests unchanged. Cargo-wise this is one revision (the spike's script); it must + not be split without breaking `--locked`. +3. Flakes, same integration as 2 (nix cannot be half-merged): the root flake builds all three; the two + nested flakes already take the whole repository as their source (`lib.mkOutputs`), so they become + thin: `workspaceArgs` change from a subdirectory workspace to `-p `. The KDE source filter + must list the new member directories. Gates N, then `NB` (deps, clippy, nextest of each system), + then `V`. +4. `komorebic` unified by `#[path]` (spike 2, minus the hacks): new `komorebic/src/main.rs`, target + tables, aliases. The old `komorebic-linux`/`-macos` packages stay until step 5 so the old names + work. Gates C, S, and `E` for `komorebic.exe` (the Windows main moves to `windows.rs`). +5. `komorebic` real moves, one platform per revision: `komorebi-for-kde/komorebic/src/*` to + `komorebic/src/linux/`, the macOS one to `komorebic/src/macos/`, tests with them, then delete the old + packages. Pure moves (jj does not follow moves, so each is a delete/modify conflict if another stack + touches those files; today none does). Gates C, S, tests. +6. `komorebi-client` unified (modules per platform), same pattern. Gates C, E (Windows client is in the + closure of `komorebi.exe`). +7. `komorebi-bar` unified after the bar stack integrates: `bar-unification.md` plan; Windows bar + screenshot gate and the Mac hand check are owed by that stack. +8. Daemon: three libraries gated to their OS and one thin `komorebi` package with the `cfg_select!` + `main`. KDE `main.rs` and the Windows `main.rs` become `run()` in their libraries. Gates C, `E`, `V`, + Mac hand check. +9. Cutover: one flake output per binary, old per-platform package names, `justfile`, CI + (`.github/workflows`), docs paths, release version (0.1.42 / 0.1.0 / 0.1.1 become one). + +## Risks + +1. One lock for three platforms: a `cargo update` for one platform moves the others; crane's dummy + source includes every member's manifest and the lock, so any dependency change rebuilds the + dependency derivation of all three systems (today a KDE-only lock change cannot touch Windows). The + `COMMIT_HASH`-constant fix (flow finding 1) must be in first or every commit rebuilds ~1,000 crates. +2. `build.rs` fetching over the network is not usable in a unified package (openssl on Linux); see step 0. +3. `--workspace` commands (clippy, fmt, nextest, crane) select every member on every target: every + foreign crate must compile empty (spike 3 shows it works for the daemon; only one crate was + converted). Without it, feature unification would also turn `komorebi-layouts/darwin` on for + Windows in a whole-workspace build. +4. The one-key-one-path rule forces distinct dependency keys and aliases per platform module. +5. `CARGO_BUILD_TARGET` is set by the root `nix develop` shell, so native Linux checks must run outside it + (as `fast-check` does) or pass `--target x86_64-unknown-linux-gnu`. +6. Command names and `--version` text come from `CARGO_PKG_NAME`/the version crate: pin them or the KDE + `version` test and the docs oracle change. `shadow-rs` major versions differ (2 on Windows, 1 on + macOS); the unified `komorebic` build script can only use one. +7. The KDE VM suites rebuild on any change to the KDE closure: the merge is one full `V` run. +8. Tests that use `CARGO_BIN_EXE_*` or relative paths (`tests/schemas.rs` writes beside the manifest) + must move with their package; not exercised beyond the spike. + +## Gates by step, in short + +Compile only: 0, 4 (but see `E`), 5, 6 at the Rust level; nix evaluation only: 3 until built. Needs +e2e (Windows guest): anything that changes an input of `komorebi.exe`, `komorebic.exe` or the client +(`tools/e2e-needed` says: 1 for the Windows daemon, 4, 6, 8). Needs the KDE VM: 2, 3, 8. Needs a Mac, +by hand: 4, 7, 8, 9. + +Mac hand check (type-check proves none of it): `komorebic --version` and `--help` show the macOS +command set and the name `komorebic`; `komorebic start` finds and starts `komorebi`, `stop` stops it; +`komorebic docgen` unchanged; `komorebi --version`; the daemon starts, tiles and `komorebic state` +answers; `komorebi-bar` opens, `--schema` equals `komorebi-for-mac/schema.bar.json`; +the embedded `applications.json` is the macOS one; +`otool -L` of each binary lists no Windows or Linux-only library. + +## Conflicts with the open stacks (sequence in a quiet period) + +Paths touched by each bookmark relative to `wip-main`: + +| bookmark | touches | moves in this plan that conflict | +|---|---|---| +| wip-u-kfw | `komorebi/src/**`, `crates/komorebi-backend/**` | daemon rename and any move of `komorebi/` (steps 1 Windows, 8) | +| wip-u-kfm | `komorebi-for-mac/komorebi/src/**`, `crates/komorebi-backend/**` | macOS daemon rename and moves (1, 8) | +| wip-u-kfde | `komorebi-for-kde/komorebi/{src,tests}/**` | KDE daemon rename (1) and moves (8); tests are edited | +| wip-u-bar | `Cargo.lock`, `komorebi-for-mac/Cargo.lock`, `komorebi-bar/src/**`, `komorebi-for-mac/komorebi-bar/src/**`, `crates/komorebi-bar-core` | step 2 (locks, manifests) and step 7 | +| wip-u-settings | `Cargo.toml`, `Cargo.lock`, `crates/komorebi-settings` | step 2 (root manifest and lock) | +| wip-u-nix | `flake.nix`, `komorebi-for-kde/flake.nix`, `komorebi-for-kde/nix/**` | step 3 | + +Not touched by any open stack, so safe now: `komorebic/**` (all three), the `komorebic` tests, the +`version` crates, the `komorebi-client` crates (steps 0, 4, 5, 6 are free of conflicts except the lock +and root manifest lines of step 2/4). Hard conflicts: every `Cargo.lock` and the root `Cargo.toml` +`members` list (resolve by taking one side and running `cargo metadata`; never hand-merge a lock), +`flake.nix` lines for the extracted binaries. Suggested order: integrate kfw, kfm, kfde, bar, settings, +nix first; then steps 0 and 1; then 2 and 3 as one integration; the rest in any order, daemon (8) +last. + +## What landed + +Only this file. The spike revisions are on `wip-u-pkg-spike` and can be dropped or cherry-picked. +Step 0 and the renames were not landed because they only pay off with step 2, which edits the locks +and manifests that three open stacks edit.