From d49de398b6e8927f5f67cdcbe94a99456c9160bc Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 23 Sep 2025 14:17:57 -0700 Subject: [PATCH] feat(wm): handle various ws overrides for new windows This commit migrates a bunch of code from komorebi that deals with how new windows should be handled according to the various floating and container behaviour overrides. To help test this functionality I also finished migrating the SessionFloatRule, SessionFloatRules and ClearSessionFloatRules SocketMessage variants. --- komorebi/src/core/mod.rs | 3 + komorebi/src/process_command.rs | 56 +++++++++++++ komorebi/src/process_event.rs | 139 +++++++++++++++++++++++++++++++- komorebi/src/window.rs | 136 ++++++++++++++++++++++--------- komorebi/src/window_manager.rs | 75 +++++++++++++++++ komorebic/src/main.rs | 15 ++++ 6 files changed, 380 insertions(+), 44 deletions(-) diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 5a1c4cad..dcdb4c7c 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -249,6 +249,9 @@ pub enum SocketMessage { VisibleWindows, MonitorInformation, Query(StateQuery), + SessionFloatRule, + SessionFloatRules, + ClearSessionFloatRules, } impl SocketMessage { diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index a9ac0cc8..7384fcd5 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -1,9 +1,15 @@ +use crate::FLOATING_APPLICATIONS; +use crate::SESSION_FLOATING_APPLICATIONS; use crate::build; +use crate::core::ApplicationIdentifier; use crate::core::MoveBehaviour; use crate::core::SocketMessage; use crate::core::StateQuery; use crate::core::WindowContainerBehaviour; use crate::core::arrangement::Axis; +use crate::core::config_generation::IdWithIdentifier; +use crate::core::config_generation::MatchingRule; +use crate::core::config_generation::MatchingStrategy; use crate::core::layout::Layout; use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; @@ -12,6 +18,7 @@ use crate::monitor::Monitor; use crate::monitor::MonitorInformation; use crate::state::GlobalState; use crate::state::State; +use crate::window::AdhocWindow; use crate::window_manager::WindowManager; use crate::workspace::Workspace; use crate::workspace::WorkspaceLayer; @@ -901,6 +908,55 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::SessionFloatRule => { + let foreground_window = + MacosApi::foreground_window().ok_or_eyre("there is no foreground window")?; + let (exe, title, role) = ( + AdhocWindow::exe(&foreground_window), + AdhocWindow::title(&foreground_window), + AdhocWindow::role(&foreground_window), + ); + + if let (Some(exe), Some(title), Some(role)) = (exe, title, role) { + let rule = MatchingRule::Composite(vec![ + IdWithIdentifier { + kind: ApplicationIdentifier::Exe, + id: exe, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + IdWithIdentifier { + kind: ApplicationIdentifier::Title, + id: title, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + IdWithIdentifier { + kind: ApplicationIdentifier::Class, + id: role, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + ]); + + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + floating_applications.push(rule.clone()); + let mut session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); + session_floating_applications.push(rule.clone()); + + self.toggle_float(true)?; + } + } + SocketMessage::SessionFloatRules => { + let session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); + let rules = serde_json::to_string_pretty(&*session_floating_applications) + .unwrap_or_else(|error| error.to_string()); + + reply.write_all(rules.as_bytes())?; + } + SocketMessage::ClearSessionFloatRules => { + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + let mut session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); + floating_applications.retain(|r| !session_floating_applications.contains(r)); + session_floating_applications.clear() + } } self.update_known_window_ids(); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 66c1e518..217470d7 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -1,14 +1,19 @@ +use crate::FLOATING_APPLICATIONS; +use crate::REGEX_IDENTIFIERS; use crate::TABBED_APPLICATIONS; use crate::WORKSPACE_MATCHING_RULES; use crate::accessibility::AccessibilityApi; use crate::accessibility::error::AccessibilityApiError; use crate::accessibility::error::AccessibilityError; use crate::accessibility::notification_constants::AccessibilityNotification; +use crate::core::WindowContainerBehaviour; use crate::core::config_generation::MatchingRule; use crate::core::default_layout::DefaultLayout; use crate::core::layout::Layout; use crate::macos_api::MacosApi; +use crate::window::AdhocWindow; use crate::window::Window; +use crate::window::should_act; use crate::window_manager::WindowManager; use crate::window_manager_event::ManualNotification; use crate::window_manager_event::SystemNotification; @@ -16,6 +21,7 @@ use crate::window_manager_event::WindowManagerEvent; use crate::window_manager_event_listener; use crate::workspace::WorkspaceLayer; use color_eyre::eyre; +use color_eyre::eyre::OptionExt; use parking_lot::Mutex; use std::sync::Arc; use tracing::instrument; @@ -287,6 +293,10 @@ impl WindowManager { } // TODO: update this to work with floating applications / rules WindowManagerEvent::Show(_, process_id) => { + let focused_monitor_idx = self.focused_monitor_idx(); + let focused_workspace_idx = + self.focused_workspace_idx_for_monitor_idx(focused_monitor_idx)?; + let mut window_id = None; let mut window_element = None; let mut application_name = String::new(); @@ -348,7 +358,7 @@ impl WindowManager { "ignoring show event for window already associated with another workspace" ); - Window::hide_adhoc(window_id, element)?; + AdhocWindow::hide(window_id, element)?; create = false; } } @@ -356,14 +366,135 @@ impl WindowManager { if create && !tabbed_window { let application = self.application(process_id)?; if let Some(element) = window_element - && let Ok(window) = Window::new(element, application.clone()) + && let Ok(mut window) = Window::new(element, application.clone()) { window.observe(&self.run_loop)?; + let behaviour = self.window_management_behaviour( + focused_monitor_idx, + focused_workspace_idx, + ); let workspace = self.focused_workspace_mut()?; - workspace.new_container_for_window(&window)?; + let workspace_contains_window = workspace.contains_window(window.id); + let monocle_container = workspace.monocle_container.clone(); - self.update_focused_workspace(false, false)?; + let floating_applications = FLOATING_APPLICATIONS.lock(); + let mut should_float = false; + + if !floating_applications.is_empty() { + let regex_identifiers = REGEX_IDENTIFIERS.lock(); + + if let ( + Some(title), + Some(exe_name), + Some(role), + Some(subrole), + Some(path), + ) = ( + window.title(), + window.exe(), + window.role(), + window.subrole(), + window.path(), + ) { + should_float = should_act( + &title, + &exe_name, + &[&role, &subrole], + &path.to_string_lossy(), + &floating_applications, + ®ex_identifiers, + ) + .is_some(); + } + } + + if behaviour.float_override + || behaviour.floating_layer_override + // TODO: look into if we want to have a Manage command here too + || (should_float /*&& !matches!(event, WindowManagerEvent::Manage(_))*/ ) + { + let placement = if behaviour.floating_layer_override { + // Floating layer override placement + behaviour.floating_layer_placement + } else if behaviour.float_override { + // Float override placement + behaviour.float_override_placement + } else { + // Float rule placement + behaviour.float_rule_placement + }; + // Center floating windows according to the proper placement if not + // on a floating workspace + let center_spawned_floats = placement.should_center() && workspace.tile; + workspace.floating_windows_mut().push_back(window.clone()); + workspace.layer = WorkspaceLayer::Floating; + if center_spawned_floats { + let mut floating_window = window.clone(); + floating_window.center( + &workspace.globals.work_area, + placement.should_resize(), + )?; + } + + self.update_focused_workspace(false, false)?; + } else { + match behaviour.current_behaviour { + WindowContainerBehaviour::Create => { + workspace.new_container_for_window(&window)?; + workspace.layer = WorkspaceLayer::Tiling; + self.update_focused_workspace(false, false)?; + } + WindowContainerBehaviour::Append => { + workspace + .focused_container_mut() + .ok_or_eyre("there is no focused container")? + .add_window(&window)?; + workspace.layer = WorkspaceLayer::Tiling; + self.update_focused_workspace(true, false)?; + } + } + + // TODO: not sure if this is needed on macOS + if (self.focused_workspace()?.containers().len() == 1 + && self.focused_workspace()?.floating_windows().is_empty()) + || (self.focused_workspace()?.containers().is_empty() + && self.focused_workspace()?.floating_windows().len() == 1) + { + // If after adding this window the workspace only contains 1 window, it + // means it was previously empty and we focused the desktop to unfocus + // any previous window from other workspace, so now we need to focus + // this window again. This is needed because sometimes some windows + // 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)?; + } + } + + if workspace_contains_window { + let mut monocle_window_event = false; + if let Some(ref monocle) = monocle_container + && let Some(monocle_window) = monocle.focused_window() + { + // we should have the window_id at this point + if monocle_window.id == window_id.unwrap_or_default() { + monocle_window_event = true; + } + } + + let workspace = self.focused_workspace()?; + if !(monocle_window_event || workspace.layer != WorkspaceLayer::Tiling) + && monocle_container.is_some() + { + window.hide()?; + } + } + + // let workspace = self.focused_workspace_mut()?; + // workspace.new_container_for_window(&window)?; + // + // self.update_focused_workspace(false, false)?; } } } diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 8c32f202..f9f4d908 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -12,6 +12,7 @@ use crate::accessibility::AccessibilityApi; use crate::accessibility::attribute_constants::kAXFocusedAttribute; use crate::accessibility::attribute_constants::kAXMainAttribute; use crate::accessibility::attribute_constants::kAXMinimizedAttribute; +use crate::accessibility::attribute_constants::kAXParentAttribute; use crate::accessibility::attribute_constants::kAXPositionAttribute; use crate::accessibility::attribute_constants::kAXRoleAttribute; use crate::accessibility::attribute_constants::kAXSizeAttribute; @@ -352,46 +353,6 @@ impl Window { Ok(()) } - #[tracing::instrument(skip_all)] - pub fn hide_adhoc( - id: u32, - element: &CFRetained, - ) -> Result<(), AccessibilityError> { - let mut window_restore_positions = WINDOW_RESTORE_POSITIONS.lock(); - if let Entry::Vacant(entry) = window_restore_positions.entry(id) { - let rect = MacosApi::window_rect(element)?; - if let Some(monitor_size) = CoreGraphicsApi::display_bounds_for_window_rect(rect) { - entry.insert(rect); - drop(window_restore_positions); - - // I don't love this, but it's basically what Aerospace does in lieu of an actual "Hide" API - let hidden_rect = hidden_frame_bottom_left(monitor_size, rect.size); - - tracing::debug!( - "hiding window with id {id} and setting restore point to {},{}", - rect.origin.x, - rect.origin.y, - ); - - AccessibilityApi::set_attribute_ax_value( - element, - kAXPositionAttribute, - AXValueType::CGPoint, - hidden_rect.origin, - )?; - - AccessibilityApi::set_attribute_ax_value( - element, - kAXSizeAttribute, - AXValueType::CGSize, - hidden_rect.size, - )?; - } - } - - Ok(()) - } - pub fn minimize(&mut self) -> Result<(), AccessibilityError> { let cf_boolean = CFBoolean::new(true); let value = &**cf_boolean; @@ -742,6 +703,101 @@ impl Window { } } +pub struct AdhocWindow; + +impl AdhocWindow { + pub fn exe(element: &CFRetained) -> Option { + let parent = + AccessibilityApi::copy_attribute_value::(element, kAXParentAttribute)?; + + AccessibilityApi::copy_attribute_value::(&parent, kAXTitleAttribute) + .map(|s| s.to_string()) + } + + pub fn role(element: &CFRetained) -> Option { + AccessibilityApi::copy_attribute_value::(element, kAXRoleAttribute) + .map(|s| s.to_string()) + } + + pub fn subrole(element: &CFRetained) -> Option { + AccessibilityApi::copy_attribute_value::(element, kAXSubroleAttribute) + .map(|s| s.to_string()) + } + + pub fn title(element: &CFRetained) -> Option { + AccessibilityApi::copy_attribute_value::(element, kAXTitleAttribute) + .map(|s| s.to_string()) + } + + #[tracing::instrument(skip_all)] + pub fn hide(id: u32, element: &CFRetained) -> Result<(), AccessibilityError> { + let mut window_restore_positions = WINDOW_RESTORE_POSITIONS.lock(); + if let Entry::Vacant(entry) = window_restore_positions.entry(id) { + let rect = MacosApi::window_rect(element)?; + if let Some(monitor_size) = CoreGraphicsApi::display_bounds_for_window_rect(rect) { + entry.insert(rect); + drop(window_restore_positions); + + // I don't love this, but it's basically what Aerospace does in lieu of an actual "Hide" API + let hidden_rect = hidden_frame_bottom_left(monitor_size, rect.size); + + tracing::debug!( + "hiding window with id {id} and setting restore point to {},{}", + rect.origin.x, + rect.origin.y, + ); + + AccessibilityApi::set_attribute_ax_value( + element, + kAXPositionAttribute, + AXValueType::CGPoint, + hidden_rect.origin, + )?; + + AccessibilityApi::set_attribute_ax_value( + element, + kAXSizeAttribute, + AXValueType::CGSize, + hidden_rect.size, + )?; + } + } + + Ok(()) + } + + #[tracing::instrument(skip_all)] + pub fn restore(id: u32, element: &CFRetained) -> Result<(), AccessibilityError> { + let mut should_remove_restore_position = false; + let mut window_restore_positions = WINDOW_RESTORE_POSITIONS.lock(); + if let Some(cg_rect) = window_restore_positions.get(&id) { + tracing::debug!("restoring window with id {id} to {cg_rect:?}",); + + AccessibilityApi::set_attribute_ax_value( + element, + kAXPositionAttribute, + AXValueType::CGPoint, + cg_rect.origin, + )?; + + AccessibilityApi::set_attribute_ax_value( + element, + kAXSizeAttribute, + AXValueType::CGSize, + cg_rect.size, + )?; + + should_remove_restore_position = true; + } + + if should_remove_restore_position { + window_restore_positions.remove(&id); + } + + Ok(()) + } +} + impl From<&CFDictionary> for WindowInfo { fn from(value: &CFDictionary) -> Self { unsafe { diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 1e3116fe..b30c265c 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -11,6 +11,7 @@ use crate::core::MoveBehaviour; use crate::core::OperationBehaviour; use crate::core::Placement; use crate::core::Sizing; +use crate::core::WindowContainerBehaviour; use crate::core::WindowManagementBehaviour; use crate::core::arrangement::Arrangement; use crate::core::arrangement::Axis; @@ -2193,4 +2194,78 @@ impl WindowManager { self.known_window_ids = known_window_ids; } } + + pub fn window_management_behaviour( + &self, + monitor_idx: usize, + workspace_idx: usize, + ) -> WindowManagementBehaviour { + if let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.workspaces().get(workspace_idx) + { + let current_behaviour = if let Some(behaviour) = workspace.window_container_behaviour { + if workspace.containers().is_empty() + && matches!(behaviour, WindowContainerBehaviour::Append) + { + // You can't append to an empty workspace + WindowContainerBehaviour::Create + } else { + behaviour + } + } else if workspace.containers().is_empty() + && matches!( + self.window_management_behaviour.current_behaviour, + WindowContainerBehaviour::Append + ) + { + // You can't append to an empty workspace + WindowContainerBehaviour::Create + } else { + self.window_management_behaviour.current_behaviour + }; + + let float_override = if let Some(float_override) = workspace.float_override { + float_override + } else { + self.window_management_behaviour.float_override + }; + + let floating_layer_behaviour = + if let Some(behaviour) = workspace.floating_layer_behaviour { + behaviour + } else { + monitor + .floating_layer_behaviour + .unwrap_or(self.window_management_behaviour.floating_layer_behaviour) + }; + + // If the workspace layer is `Floating` and the floating layer behaviour should + // float then change floating_layer_override to true so that new windows spawn + // as floating + let floating_layer_override = matches!(workspace.layer, WorkspaceLayer::Floating) + && floating_layer_behaviour.should_float(); + + return WindowManagementBehaviour { + current_behaviour, + float_override, + floating_layer_override, + floating_layer_behaviour, + toggle_float_placement: self.window_management_behaviour.toggle_float_placement, + floating_layer_placement: self.window_management_behaviour.floating_layer_placement, + float_override_placement: self.window_management_behaviour.float_override_placement, + float_rule_placement: self.window_management_behaviour.float_rule_placement, + }; + } + + WindowManagementBehaviour { + current_behaviour: WindowContainerBehaviour::Create, + float_override: self.window_management_behaviour.float_override, + floating_layer_override: self.window_management_behaviour.floating_layer_override, + floating_layer_behaviour: self.window_management_behaviour.floating_layer_behaviour, + toggle_float_placement: self.window_management_behaviour.toggle_float_placement, + floating_layer_placement: self.window_management_behaviour.floating_layer_placement, + float_override_placement: self.window_management_behaviour.float_override_placement, + float_rule_placement: self.window_management_behaviour.float_rule_placement, + } + } } diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 1772babc..bcb1c6ce 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -392,6 +392,12 @@ enum SubCommand { /// Fetch the latest version of applications.json from komorebi-application-specific-configuration #[clap(alias = "fetch-asc")] FetchAppSpecificConfiguration, + /// Add a rule to float the foreground window for the rest of this session + SessionFloatRule, + /// Show all session float rules + SessionFloatRules, + /// Clear all session float rules + ClearSessionFloatRules, } fn print_query(message: &SocketMessage) { @@ -760,6 +766,15 @@ fn main() -> eyre::Result<()> { output_file.display().to_string().replace("\\", "/") ); } + SubCommand::SessionFloatRule => { + send_message(&SocketMessage::SessionFloatRule)?; + } + SubCommand::SessionFloatRules => { + print_query(&SocketMessage::SessionFloatRules); + } + SubCommand::ClearSessionFloatRules => { + send_message(&SocketMessage::ClearSessionFloatRules)?; + } } Ok(())