fix(wm): respect workspace window rules

This commit adds window ID tracking like we do in komorebi for Windows
and fixes a bunch of bugs that were happening when a window on another
workspace was focused either via the Dock or cmd+tab, and also a bug in
workspace rules where on launch, a window would not respect workspace
rules due to another workaround that had been added to make Apple apps
work nicely.
This commit is contained in:
LGUG2Z committed 2025-09-22 13:31:45 -07:00
1 parent 02523d8b34
commit f6997577f1
8 files changed
+174 -15

No files matched your search

+3
View File
@@ -8,6 +8,9 @@ fmt:
cargo +stable clippy
prettier --write README.md
fix:
cargo clippy --fix --allow-dirty
clean:
cargo clean
+6 -2
View File
@@ -1,4 +1,5 @@
use crate::app_kit_notification_constants::AppKitWorkspaceNotification;
use crate::application::Application;
use crate::ax_event_listener::event_tx;
use crate::window_manager_event::SystemNotification;
use crate::window_manager_event::WindowManagerEvent;
@@ -33,6 +34,7 @@ define_class! {
fn handle_notification(&self, notif: &NSNotification) {
unsafe {
let mut process_id = None;
let mut window_id = None;
let mut valid_keys = vec![];
if let Some(user_info) = notif.userInfo() {
@@ -48,7 +50,9 @@ define_class! {
&& let Some(application) = application_key.downcast_ref::<NSRunningApplication>()
{
process_id = Some(application.processIdentifier());
// TODO: maybe get the window IDs here too?
if let Ok(application) = Application::new(application.processIdentifier()) {
window_id = application.main_window_id();
}
}
}
@@ -68,7 +72,7 @@ define_class! {
&& let Some(event) = WindowManagerEvent::from_system_notification(
SystemNotification::AppKitWorkspace(notification),
process_id,
None,
window_id,
)
&& let Err(error) = event_tx().send(event)
{
+2
View File
@@ -849,6 +849,8 @@ impl WindowManager {
}
}
self.update_known_window_ids();
Ok(())
}
+73 -8
View File
@@ -1,6 +1,8 @@
use crate::WORKSPACE_MATCHING_RULES;
use crate::accessibility::AccessibilityApi;
use crate::accessibility::notification_constants::AccessibilityNotification;
use crate::ax_event_listener::event_tx;
use crate::core::config_generation::MatchingRule;
use crate::core::default_layout::DefaultLayout;
use crate::core::layout::Layout;
use crate::window::Window;
@@ -11,6 +13,7 @@ use crate::workspace::WorkspaceLayer;
use color_eyre::eyre;
use parking_lot::Mutex;
use std::sync::Arc;
use tracing::instrument;
#[tracing::instrument]
pub fn listen_for_events(wm: Arc<Mutex<WindowManager>>) {
@@ -37,6 +40,7 @@ pub fn listen_for_events(wm: Arc<Mutex<WindowManager>>) {
}
impl WindowManager {
#[instrument(skip_all)]
pub fn process_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> {
if self.is_paused {
tracing::trace!("ignoring while paused");
@@ -65,8 +69,9 @@ impl WindowManager {
}
tracing::info!(
"processing event: {event} for process {}",
event.process_id()
"processing event: {event} for process {} with notification {}",
event.process_id(),
event.notification(),
);
self.enforce_workspace_rules()?;
@@ -74,8 +79,12 @@ impl WindowManager {
match event {
WindowManagerEvent::FocusChange(notification, process_id, _) => {
let application = self.application(process_id)?;
let application_name = application.name().unwrap_or_default().clone();
if let Some(window_id) = application.main_window_id() {
let is_known = self.known_window_ids.get(&window_id).cloned();
let mut is_on_current_workspace = false;
// TODO: figure out if this applies on macOS too
// don't want to trigger the full workspace updates when there are no managed
// containers - this makes floating windows on empty workspaces go into very
@@ -89,6 +98,10 @@ impl WindowManager {
}
let workspace = self.focused_workspace_mut()?;
if workspace.contains_window(window_id) {
is_on_current_workspace = true;
}
let floating_window_idx = workspace
.floating_windows()
.iter()
@@ -106,11 +119,37 @@ impl WindowManager {
if let Some(window) = monocle.focused_window() {
window.focus(false)?;
}
} else {
// if this fails, the app was probably open but windowless when komorebi
// launched, so the window hasn't been registered - we should treat it
// as a "Show" event
if workspace.focus_container_by_window(window_id).is_err() {
} else if !is_on_current_workspace && is_known.is_none() {
// thanks, I hate it - need to do this so that we don't mess up
// the workspace rules, but also don't miss events from dumb
// apps like notes, mail etc.
let mut has_matching_workspace_rule = false;
let workspace_rules = WORKSPACE_MATCHING_RULES.lock();
for rule in &*workspace_rules {
match &rule.matching_rule {
MatchingRule::Simple(r) => {
if r.id.trim_end_matches(".exe") == application_name {
has_matching_workspace_rule = true;
}
}
// TODO: this is pretty coarse
MatchingRule::Composite(rules) => {
for r in rules {
if r.id.trim_end_matches(".exe") == application_name
{
has_matching_workspace_rule = true;
}
}
}
}
}
if !has_matching_workspace_rule
&& workspace.focus_container_by_window(window_id).is_err()
{
// if this fails, the app was probably open but windowless when komorebi
// launched, so the window hasn't been registered - we should treat it
// as a "Show" event
event_tx().send(WindowManagerEvent::Show(
notification,
event.process_id(),
@@ -128,12 +167,19 @@ impl WindowManager {
self.update_focused_workspace(self.mouse_follows_focus, false)?;
}
}
Some(idx) => {
if let Some(_window) = workspace.floating_windows().get(idx) {
workspace.layer = WorkspaceLayer::Floating;
}
}
}
// maybe we don't need a separate reconciliator module?? this works pretty well!
if !is_on_current_workspace && let Some((m_idx, w_idx)) = is_known {
self.focus_monitor(m_idx)?;
self.focus_workspace(w_idx)?;
}
}
if matches!(
@@ -162,13 +208,29 @@ impl WindowManager {
}
}
if let Some(window_id) = window_id {
if let (Some(window_id), Some(element)) = (window_id, &window_element) {
let workspace = self.focused_workspace()?;
if workspace.contains_window(window_id) {
// ignore bogus show events
tracing::debug!("ignoring show event for window already on workspace");
create = false;
}
if let Some((m_idx, w_idx)) = self.known_window_ids.get(&window_id)
&& let Some(focused_workspace_idx) = self
.monitors()
.get(*m_idx)
.map(|m| m.focused_workspace_idx())
&& *m_idx != self.focused_monitor_idx()
&& *w_idx != focused_workspace_idx
{
tracing::debug!(
"ignoring show event for window already associated with another workspace"
);
Window::hide_adhoc(window_id, element)?;
create = false;
}
}
if create {
@@ -205,6 +267,9 @@ impl WindowManager {
}
}
self.enforce_workspace_rules()?;
self.update_known_window_ids();
Ok(())
}
}
+1
View File
@@ -1155,6 +1155,7 @@ impl StaticConfig {
run_loop: CoreFoundationRunLoop(run_loop.clone()),
minimized_windows: Default::default(),
already_moved_window_handles: Default::default(),
known_window_ids: Default::default(),
};
// match value.focus_follows_mouse {
+40
View File
@@ -355,6 +355,46 @@ impl Window {
Ok(())
}
#[tracing::instrument(skip_all)]
pub fn hide_adhoc(
id: u32,
element: &CFRetained<AXUIElement>,
) -> 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;
+36 -5
View File
@@ -65,6 +65,8 @@ pub struct WindowManager {
pub incoming_events: Receiver<WindowManagerEvent>,
pub minimized_windows: HashMap<u32, Window>,
pub already_moved_window_handles: Arc<Mutex<HashSet<u32>>>,
/// Maps each known window id to the (monitor, workspace) index pair managing it
pub known_window_ids: HashMap<u32, (usize, usize)>,
}
impl_ring_elements!(WindowManager, Monitor);
@@ -142,6 +144,7 @@ impl WindowManager {
incoming_events: incoming,
minimized_windows: HashMap::new(),
already_moved_window_handles: Default::default(),
known_window_ids: Default::default(),
})
}
@@ -2034,11 +2037,6 @@ impl WindowManager {
.get_mut(op.origin_workspace_idx)
.ok_or_eyre("there is no workspace with that index")?;
// TODO: need to find a way to construct a lightweight window that can be operated on
// let mut window = Window::new(origin_workspace
// .window_by_id(op.window_id)
// .ok_or_eyre("there is no window with the requested id")?);
let mut window = origin_workspace.remove_window(op.window_id)?;
// If it is a floating window move it to the target area
@@ -2162,4 +2160,37 @@ impl WindowManager {
Ok(())
}
pub fn update_known_window_ids(&mut self) {
tracing::trace!("updating list of known window_ids");
let mut known_window_ids = HashMap::new();
for (m_idx, monitor) in self.monitors().iter().enumerate() {
for (w_idx, workspace) in monitor.workspaces().iter().enumerate() {
for container in workspace.containers() {
for window in container.windows() {
known_window_ids.insert(window.id, (m_idx, w_idx));
}
}
for window in workspace.floating_windows() {
known_window_ids.insert(window.id, (m_idx, w_idx));
}
if let Some(window) = &workspace.maximized_window {
known_window_ids.insert(window.id, (m_idx, w_idx));
}
if let Some(container) = &workspace.monocle_container {
for window in container.windows() {
known_window_ids.insert(window.id, (m_idx, w_idx));
}
}
}
}
if self.known_window_ids != known_window_ids {
// Store new window_ids
self.known_window_ids = known_window_ids;
}
}
}
+13
View File
@@ -78,4 +78,17 @@ impl WindowManagerEvent {
| WindowManagerEvent::Restore(_, process_id, _) => *process_id,
}
}
pub fn notification(&self) -> String {
match self {
WindowManagerEvent::FocusChange(n, _, _)
| WindowManagerEvent::Show(n, _)
| WindowManagerEvent::Destroy(n, _)
| WindowManagerEvent::Minimize(n, _, _)
| WindowManagerEvent::Restore(n, _, _) => match n {
SystemNotification::Accessibility(a) => a.to_string(),
SystemNotification::AppKitWorkspace(a) => a.to_string(),
},
}
}
}