diff --git a/komorebi/src/application.rs b/komorebi/src/application.rs index ec8e51d7..38fa4bfc 100644 --- a/komorebi/src/application.rs +++ b/komorebi/src/application.rs @@ -131,22 +131,30 @@ impl Application { .unwrap_or_else(|| String::from("")) ); - match AccessibilityApi::add_observer_to_run_loop( - &self.observer, - &self.element, - NOTIFICATIONS, - run_loop, - ) { - Ok(_) => { - self.is_observable = true; - } - Err(error) => { - tracing::warn!( - "failed to register observer for process {} ({}): {error}", - self.process_id, - self.name() - .unwrap_or_else(|| String::from("")) - ); + let mut retries = 5; + + while retries > 0 { + match AccessibilityApi::add_observer_to_run_loop( + &self.observer, + &self.element, + NOTIFICATIONS, + run_loop, + ) { + Ok(_) => { + self.is_observable = true; + break; + } + Err(error) => { + // Chromium apps are still gross on macOS too + retries -= 1; + std::thread::sleep(std::time::Duration::from_millis(100)); + tracing::warn!( + "failed to register observer for process {} ({}): {error}, {retries} retries left", + self.process_id, + self.name() + .unwrap_or_else(|| String::from("")) + ); + } } } } diff --git a/komorebi/src/input_event_listener.rs b/komorebi/src/input_event_listener.rs new file mode 100644 index 00000000..f6f466a1 --- /dev/null +++ b/komorebi/src/input_event_listener.rs @@ -0,0 +1,67 @@ +use crate::reaper; +use crate::reaper::ReaperNotification; +use objc2_core_foundation::CFMachPort; +use objc2_core_foundation::CFRetained; +use objc2_core_foundation::CFRunLoop; +use objc2_core_foundation::kCFRunLoopDefaultMode; +use objc2_core_graphics::CGEvent; +use objc2_core_graphics::CGEventTapLocation; +use objc2_core_graphics::CGEventTapOptions; +use objc2_core_graphics::CGEventTapPlacement; +use objc2_core_graphics::CGEventTapProxy; +use objc2_core_graphics::CGEventType; +use std::ffi::c_void; +use std::ptr::NonNull; + +pub struct InputEventListener { + port: CFRetained, +} + +extern "C-unwind" fn callback( + _: CGEventTapProxy, + _event_type: CGEventType, + mut event_ref: NonNull, + _listener: *mut c_void, +) -> *mut CGEvent { + reaper::send_notification(ReaperNotification::MouseUpKeyUp); + unsafe { event_ref.as_mut() } +} +impl InputEventListener { + pub fn init(run_loop: &CFRunLoop) -> Option { + let mouse_event_mask = (1 << CGEventType::LeftMouseUp.0) | (1 << CGEventType::KeyUp.0); + let mut port = None; + + unsafe { + let tap_port = CGEvent::tap_create( + CGEventTapLocation::HIDEventTap, + CGEventTapPlacement::HeadInsertEventTap, + CGEventTapOptions::Default, + mouse_event_mask, + Some(callback), + std::ptr::null_mut(), + ); + + if let Some(tap_port) = &tap_port { + port = Some(tap_port.clone()); + } + + match CFMachPort::new_run_loop_source(None, tap_port.as_deref(), 0) { + None => {} + Some(source) => { + CFRunLoop::add_source(run_loop, Some(&source), kCFRunLoopDefaultMode); + } + } + } + + port.map(|port| Self { port }) + } +} + +impl Drop for InputEventListener { + fn drop(&mut self) { + CFMachPort::invalidate(&self.port); + unsafe { + CGEvent::tap_enable(&self.port, false); + } + } +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index bdc42f49..2e31192d 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -36,6 +36,7 @@ mod container; pub mod core; pub mod core_graphics; pub mod display_reconfiguration_listener; +pub mod input_event_listener; pub mod lockable_sequence; pub mod macos_api; pub mod monitor; @@ -43,6 +44,7 @@ pub mod monitor_reconciliator; pub mod notification_center_listener; pub mod process_command; pub mod process_event; +pub mod reaper; pub mod window; pub mod window_manager; pub mod window_manager_event; diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 9cf0f0c9..910dc0b1 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -6,11 +6,13 @@ use komorebi::DATA_DIR; use komorebi::UPDATE_MONITOR_WORK_AREAS; use komorebi::ax_event_listener; use komorebi::display_reconfiguration_listener::DisplayReconfigurationListener; +use komorebi::input_event_listener::InputEventListener; use komorebi::macos_api::MacosApi; use komorebi::monitor_reconciliator; use komorebi::notification_center_listener::NotificationCenterListener; use komorebi::process_command::listen_for_commands; use komorebi::process_event::listen_for_events; +use komorebi::reaper; use komorebi::window_manager::WindowManager; use objc2::rc::autoreleasepool; use objc2_application_services::AXIsProcessTrusted; @@ -111,17 +113,21 @@ fn main() -> eyre::Result<()> { tracing::info!("display size for main display is: {:?}", display_size); let run_loop = CFRunLoop::current().ok_or_eyre("couldn't get CFRunLoop::current")?; + let _input_listener = InputEventListener::init(&run_loop); + let wm = Arc::new(Mutex::new(WindowManager::new( &run_loop, ax_event_listener::event_rx(), None, )?)); + wm.lock().init()?; wm.lock().update_focused_workspace(true, true)?; listen_for_commands(wm.clone()); listen_for_events(wm.clone()); monitor_reconciliator::listen_for_notifications(wm.clone())?; + reaper::listen_for_notifications(wm.clone()); let quit_ctrlc = Arc::new(AtomicBool::new(false)); let quit_thread = quit_ctrlc.clone(); diff --git a/komorebi/src/notification_center_listener.rs b/komorebi/src/notification_center_listener.rs index f97c94fe..22bf5d3f 100644 --- a/komorebi/src/notification_center_listener.rs +++ b/komorebi/src/notification_center_listener.rs @@ -165,8 +165,8 @@ impl NotificationCenterListener { None, ); } - } - observer + observer + } } } diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 86532d93..9f95b888 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -1,5 +1,6 @@ use crate::accessibility::AccessibilityApi; use crate::accessibility::notification_constants::AccessibilityNotification; +use crate::ax_event_listener::event_tx; use crate::core::default_layout::DefaultLayout; use crate::core::layout::Layout; use crate::window::Window; @@ -83,7 +84,15 @@ impl WindowManager { window.focus(false)?; } } else { - workspace.focus_container_by_window(window_id)?; + // 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() { + event_tx().send(WindowManagerEvent::Show( + notification, + event.process_id(), + ))? + } } workspace.layer = WorkspaceLayer::Tiling; diff --git a/komorebi/src/reaper.rs b/komorebi/src/reaper.rs new file mode 100644 index 00000000..2dfb62b5 --- /dev/null +++ b/komorebi/src/reaper.rs @@ -0,0 +1,89 @@ +use crate::window_manager::WindowManager; +use crossbeam_channel::Receiver; +use crossbeam_channel::Sender; +use parking_lot::Mutex; +use std::sync::Arc; +use std::sync::OnceLock; + +pub enum ReaperNotification { + InvalidWindow(u32), + MouseUpKeyUp, +} + +static CHANNEL: OnceLock<(Sender, Receiver)> = + OnceLock::new(); + +pub fn channel() -> &'static (Sender, Receiver) { + CHANNEL.get_or_init(|| crossbeam_channel::bounded(50)) +} + +fn event_tx() -> Sender { + channel().0.clone() +} + +fn event_rx() -> Receiver { + channel().1.clone() +} + +pub fn send_notification(notification: ReaperNotification) { + if event_tx().try_send(notification).is_err() { + tracing::warn!("channel is full; dropping notification") + } +} + +pub fn listen_for_notifications(wm: Arc>) { + std::thread::spawn(move || { + loop { + match handle_notifications(wm.clone()) { + Ok(()) => { + tracing::warn!("restarting finished thread"); + } + Err(error) => { + tracing::warn!("restarting failed thread: {}", error); + } + } + } + }); +} + +fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> { + tracing::info!("listening"); + + let receiver = event_rx(); + + for notification in receiver { + let mut wm = wm.lock(); + + match notification { + ReaperNotification::InvalidWindow(window_id) => { + let mut should_update = false; + for monitor in wm.monitors_mut() { + for workspace in monitor.workspaces_mut() { + for container in workspace.containers_mut() { + container.windows_mut().retain(|w| { + if w.id == window_id { + should_update = true; + tracing::info!("reaping window: {window_id}"); + } + + w.id != window_id + }); + } + } + } + + // If an invalid window was cleaned up, we update the workspace + wm.update_focused_workspace(false, false)?; + } + ReaperNotification::MouseUpKeyUp => { + // this first one will do a "nothing" update to check if any windows failed + // to have their positions set - the failures will trigger an InvalidWindow + // notification + // TODO: maybe replace this with something a bit more lightweight + wm.update_focused_workspace(false, false)?; + } + } + } + + Ok(()) +} diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 709bb4c0..77f4763e 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -25,6 +25,8 @@ use crate::core::rect::Rect; use crate::core_graphics::CoreGraphicsApi; use crate::hidden_frame_bottom_left; use crate::macos_api::MacosApi; +use crate::reaper; +use crate::reaper::ReaperNotification; use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; use objc2_app_kit::NSApplicationActivationOptions; @@ -284,8 +286,21 @@ impl Window { } pub fn set_position(&self, rect: &Rect) -> Result<(), AccessibilityError> { - self.set_point(CGPoint::new(rect.left as CGFloat, rect.top as CGFloat))?; - self.set_size(CGSize::new(rect.right as CGFloat, rect.bottom as CGFloat)) + match self.set_point(CGPoint::new(rect.left as CGFloat, rect.top as CGFloat)) { + Ok(_) => {} + Err(error) => { + reaper::send_notification(ReaperNotification::InvalidWindow(self.id)); + return Err(error); + } + } + + match self.set_size(CGSize::new(rect.right as CGFloat, rect.bottom as CGFloat)) { + Ok(_) => Ok(()), + Err(error) => { + reaper::send_notification(ReaperNotification::InvalidWindow(self.id)); + Err(error) + } + } } pub fn focus(&self, mouse_follows_focus: bool) -> Result<(), LibraryError> { diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 15fe829b..4791901c 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -510,8 +510,6 @@ impl WindowManager { follow_focus: bool, trigger_focus: bool, ) -> eyre::Result<()> { - tracing::info!("updating"); - let offset = self.work_area_offset; let mouse_follows_focus = self.mouse_follows_focus; diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index 8cd9b1cd..e9c4d764 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -33,6 +33,9 @@ impl WindowManagerEvent { SystemNotification::Accessibility(AccessibilityNotification::AXMainWindowChanged) | SystemNotification::Accessibility( AccessibilityNotification::AXApplicationActivated, + ) + | SystemNotification::AppKitWorkspace( + AppKitWorkspaceNotification::NSWorkspaceDidActivateApplicationNotification, ) => Some(WindowManagerEvent::FocusChange( notification, process_id,