diff --git a/Cargo.lock b/Cargo.lock index 01c15071..6c66057a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -536,6 +536,7 @@ dependencies = [ "objc2-application-services", "objc2-core-foundation", "objc2-core-graphics", + "objc2-foundation", "parking_lot", "pastey", "serde", @@ -800,6 +801,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "900831247d2fe1a09a683278e5384cfb8c80c79fe6b166f9d14bfdde0ea1b03c" dependencies = [ "bitflags", + "block2", + "libc", "objc2", "objc2-core-foundation", ] diff --git a/justfile b/justfile index 35a89b32..0beb52cf 100644 --- a/justfile +++ b/justfile @@ -2,6 +2,8 @@ export RUST_BACKTRACE := "full" fmt: test -z "$(rg 'eyre!' --type rust)" || (echo "eyre! macro not allowed"; false) + test -z "$(rg 'dbg!' --type rust)" || (echo "dbg! macro not allowed"; false) + test -z "$(rg 'println!' --type rust)" || (echo "println! macro not allowed"; false) cargo +nightly fmt cargo +stable clippy prettier --write README.md diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index c6c3a98d..ff957cc5 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -13,6 +13,7 @@ lazy_static = { workspace = true } objc2 = "0.6" objc2-app-kit = "0.3" objc2-application-services = "0.3" +objc2-foundation = "0.3" objc2-core-foundation = { version = "0.3", features = ["CFDictionary", "CFString"] } objc2-core-graphics = { version = "0.3", features = ["CGWindow", "alloc"] } parking_lot = "0.12" diff --git a/komorebi/src/app_kit_notification_constants.rs b/komorebi/src/app_kit_notification_constants.rs new file mode 100644 index 00000000..d77c328e --- /dev/null +++ b/komorebi/src/app_kit_notification_constants.rs @@ -0,0 +1,75 @@ +#![allow(clippy::enum_variant_names)] + +use objc2::rc::Retained; +use objc2_foundation::NSNotification; +use objc2_foundation::NSNotificationName; +use serde::Deserialize; +use serde::Serialize; +use std::str::FromStr; +use strum::Display; +use strum::EnumString; + +#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, EnumString)] +pub enum AppKitWorkspaceNotification { + // A notification that the workspace posts when any of the accessibility display options change. + NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification, + // A notification that the workspace posts when a Spaces change occurs. + NSWorkspaceActiveSpaceDidChangeNotification, + // A notification that the workspace posts when the Finder is about to activate an app. + NSWorkspaceDidActivateApplicationNotification, + // A notification that the workspace posts when the Finder file labels or colors change. + NSWorkspaceDidChangeFileLabelsNotification, + // A notification that the workspace posts when the Finder deactivates an app. + NSWorkspaceDidDeactivateApplicationNotification, + // A notification that the workspace posts when the Finder hides an app. + NSWorkspaceDidHideApplicationNotification, + // A notification that the workspace posts when a new app starts up. + NSWorkspaceDidLaunchApplicationNotification, + // A notification that the workspace posts when a new device mounts. + NSWorkspaceDidMountNotification, + // Posted when a file operation has been performed in the receiving app. + // #[deprecated] + // NSWorkspaceDidPerformFileOperationNotification, + // A notification that the workspace posts when a volume changes its name or mount path. + NSWorkspaceDidRenameVolumeNotification, + // A notification that the workspace posts when an app finishes executing. + NSWorkspaceDidTerminateApplicationNotification, + // A notification that the workspace posts when the Finder unhides an app. + NSWorkspaceDidUnhideApplicationNotification, + // A notification that the workspace posts when the Finder unmounts a device. + NSWorkspaceDidUnmountNotification, + // A notification that the workspace posts when the device wakes from sleep. + NSWorkspaceDidWakeNotification, + // A notification that the workspace posts when the device’s screen goes to sleep. + NSWorkspaceScreensDidSleepNotification, + // A notification that the workspace posts when the device’s screens wake. + NSWorkspaceScreensDidWakeNotification, + // A notification that the workspace posts after a user session switches in. + NSWorkspaceSessionDidBecomeActiveNotification, + // A notification that the workspace posts before a user session switches out. + NSWorkspaceSessionDidResignActiveNotification, + // A notification that the workspace posts when the Finder is about to launch an app. + NSWorkspaceWillLaunchApplicationNotification, + // A notification that the workspace posts when the user requests a logout or powers off the device. + NSWorkspaceWillPowerOffNotification, + // A notification that the workspace posts before the device goes to sleep. + NSWorkspaceWillSleepNotification, + // A notification that the workspace posts when the Finder is about to unmount a device. + NSWorkspaceWillUnmountNotification, +} + +impl From for Retained { + fn from(value: AppKitWorkspaceNotification) -> Self { + NSNotificationName::from_str(&value.to_string()) + } +} + +impl TryFrom for AppKitWorkspaceNotification { + type Error = strum::ParseError; + + fn try_from(value: NSNotification) -> Result { + let name = unsafe { value.name().to_string() }; + + AppKitWorkspaceNotification::from_str(&name) + } +} diff --git a/komorebi/src/application.rs b/komorebi/src/application.rs index 85224b83..ec8e51d7 100644 --- a/komorebi/src/application.rs +++ b/komorebi/src/application.rs @@ -15,6 +15,7 @@ use crate::accessibility::notification_constants::kAXUIElementDestroyedNotificat use crate::accessibility::notification_constants::kAXWindowCreatedNotification; use crate::ax_event_listener::event_tx; use crate::window::Window; +use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; use objc2_application_services::AXObserver; use objc2_application_services::AXUIElement; @@ -69,8 +70,11 @@ unsafe extern "C-unwind" fn application_observer_callback( if let Ok(notification) = AccessibilityNotification::from_str(¬ification.as_ref().to_string()) - && let Some(event) = - WindowManagerEvent::from_ax_notification(notification, process_id, None) + && let Some(event) = WindowManagerEvent::from_system_notification( + SystemNotification::Accessibility(notification), + process_id, + None, + ) { if let Err(error) = event_tx().send(event) { tracing::error!("failed to send window manager event: {error}"); diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 3055f20d..ea511ff5 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -28,6 +28,7 @@ use std::sync::atomic::AtomicI32; pub mod ring; pub mod accessibility; +mod app_kit_notification_constants; pub mod application; pub mod ax_event_listener; mod container; @@ -35,7 +36,8 @@ pub mod core; pub mod core_graphics; pub mod lockable_sequence; pub mod macos_api; -mod monitor; +pub mod monitor; +pub mod notification_center_listener; pub mod process_command; pub mod process_event; pub mod window; diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 24d41cee..d8907b5b 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -4,6 +4,7 @@ use color_eyre::eyre; use color_eyre::eyre::OptionExt; use komorebi::DATA_DIR; use komorebi::ax_event_listener; +use komorebi::notification_center_listener::NotificationCenterListener; use komorebi::process_command::listen_for_commands; use komorebi::process_event::listen_for_events; use komorebi::window_manager::WindowManager; @@ -99,6 +100,8 @@ fn main() -> eyre::Result<()> { std::fs::create_dir_all(&*DATA_DIR)?; } + let _notification_center_listener = NotificationCenterListener::init(); + let display_size = unsafe { CGDisplayBounds(CGMainDisplayID()) }; tracing::info!("display size for main display is: {:?}", display_size); diff --git a/komorebi/src/notification_center_listener.rs b/komorebi/src/notification_center_listener.rs new file mode 100644 index 00000000..f97c94fe --- /dev/null +++ b/komorebi/src/notification_center_listener.rs @@ -0,0 +1,172 @@ +use crate::app_kit_notification_constants::AppKitWorkspaceNotification; +use crate::ax_event_listener::event_tx; +use crate::window_manager_event::SystemNotification; +use crate::window_manager_event::WindowManagerEvent; +use objc2::AnyThread; +use objc2::define_class; +use objc2::msg_send; +use objc2::rc::Retained; +use objc2::runtime::NSObject; +use objc2::sel; +use objc2_app_kit::NSApplication; +use objc2_app_kit::NSRunningApplication; +use objc2_app_kit::NSWorkspace; +use objc2_foundation::NSDistributedNotificationCenter; +use objc2_foundation::NSNotification; +use objc2_foundation::NSNotificationCenter; +use objc2_foundation::NSNotificationName; +use objc2_foundation::NSString; +use std::str::FromStr; + +#[derive(Debug, Clone)] +pub struct Ivars {} + +// this is gross, auto formatting doesn't work inside here +define_class! { + #[unsafe(super(NSObject))] + #[ivars = Ivars] + #[derive(Debug)] + pub struct NotificationCenterListenerNsObject; + + impl NotificationCenterListenerNsObject { + #[unsafe(method(handleNotification:))] + fn handle_notification(&self, notif: &NSNotification) { + unsafe { + let mut process_id = None; + let mut valid_keys = vec![]; + + if let Some(user_info) = notif.userInfo() { + let all_keys = user_info.allKeys(); + for k in all_keys { + if let Some(key) = k.downcast_ref::() { + valid_keys.push(key.to_string()); + } + } + + if let Some(application_key) = + user_info.valueForKey(&NSString::from_str("NSWorkspaceApplicationKey")) + && let Some(application) = application_key.downcast_ref::() + { + process_id = Some(application.processIdentifier()); + // TODO: maybe get the window IDs here too? + } + } + + tracing::trace!("received {} with keys {}", notif.name(), valid_keys.join(", ")); + + match process_id { + None => { + tracing::debug!( + "notification: {}, skipping as there is no associated process id", + notif.name() + ); + } + Some(process_id) => { + tracing::debug!("notification: {}, process: {process_id}", notif.name()); + if let Ok(notification) = + AppKitWorkspaceNotification::from_str(¬if.name().to_string()) + && let Some(event) = WindowManagerEvent::from_system_notification( + SystemNotification::AppKitWorkspace(notification), + process_id, + None, + ) + && let Err(error) = event_tx().send(event) + { + tracing::error!("failed to send window manager event: {error}"); + }; + } + } + } + } + } +} + +#[derive(Debug)] +pub struct NotificationCenterListener { + pub inner: Retained, +} + +impl Drop for NotificationCenterListener { + fn drop(&mut self) { + tracing::info!("removing notification center observer"); + unsafe { + NSWorkspace::sharedWorkspace() + .notificationCenter() + .removeObserver(&self.inner); + NSNotificationCenter::defaultCenter().removeObserver(&self.inner); + NSDistributedNotificationCenter::defaultCenter().removeObserver(&self.inner); + } + } +} + +impl NotificationCenterListenerNsObject { + fn new() -> Retained { + // if we don't set ivars here this fails to compile + let this = Self::alloc().set_ivars(Ivars {}); + unsafe { msg_send![super(this), init] } + } +} + +impl NotificationCenterListener { + pub fn init() -> Self { + let observer = NotificationCenterListener { + inner: NotificationCenterListenerNsObject::new(), + }; + + unsafe { + // this is needed to get the spice flowing?? + if !NSApplication::load() { + panic!("NSApplicationLoad failed"); + } + + let shared_workspace = NSWorkspace::sharedWorkspace(); + let notification_center = shared_workspace.notificationCenter(); + + // https://developer.apple.com/documentation/appkit/nsworkspace/willlaunchapplicationnotification?language=objc + for notification in [ + // A notification that the workspace posts when a new app starts up. + AppKitWorkspaceNotification::NSWorkspaceDidLaunchApplicationNotification, + // A notification that the workspace posts when an app finishes executing. + AppKitWorkspaceNotification::NSWorkspaceDidTerminateApplicationNotification, + // A notification that the workspace posts after a user session switches in. + AppKitWorkspaceNotification::NSWorkspaceSessionDidBecomeActiveNotification, + // A notification that the workspace posts before a user session switches out. + AppKitWorkspaceNotification::NSWorkspaceSessionDidResignActiveNotification, + // A notification that the workspace posts when the Finder hides an app. + AppKitWorkspaceNotification::NSWorkspaceDidHideApplicationNotification, + // A notification that the workspace posts when the Finder unhides an app. + AppKitWorkspaceNotification::NSWorkspaceDidUnhideApplicationNotification, + // A notification that the workspace posts when the Finder is about to activate an app. + AppKitWorkspaceNotification::NSWorkspaceDidActivateApplicationNotification, + // A notification that the workspace posts when the Finder deactivates an app. + AppKitWorkspaceNotification::NSWorkspaceDidDeactivateApplicationNotification, + // A notification that the workspace posts when a volume changes its name or mount path. + AppKitWorkspaceNotification::NSWorkspaceDidRenameVolumeNotification, + // A notification that the workspace posts when a new device mounts. + AppKitWorkspaceNotification::NSWorkspaceDidMountNotification, + // A notification that the workspace posts when the Finder is about to unmount a device. + AppKitWorkspaceNotification::NSWorkspaceWillUnmountNotification, + // A notification that the workspace posts when the Finder unmounts a device. + AppKitWorkspaceNotification::NSWorkspaceDidUnmountNotification, + // A notification that the workspace posts when the Finder file labels or colors change. + AppKitWorkspaceNotification::NSWorkspaceDidChangeFileLabelsNotification, + // A notification that the workspace posts when a Spaces change occurs. + AppKitWorkspaceNotification::NSWorkspaceActiveSpaceDidChangeNotification, + // A notification that the workspace posts when the device wakes from sleep. + AppKitWorkspaceNotification::NSWorkspaceDidWakeNotification, + ] { + let notification_name: Retained = notification.into(); + + // thanks, I hate it + notification_center.addObserver_selector_name_object( + &observer.inner, + sel!(handleNotification:), + Some(¬ification_name), + None, + ); + } + } + + observer + } +} diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 61e615dd..86532d93 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -4,6 +4,7 @@ use crate::core::default_layout::DefaultLayout; use crate::core::layout::Layout; use crate::window::Window; use crate::window_manager::WindowManager; +use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; use crate::workspace::WorkspaceLayer; use color_eyre::eyre; @@ -103,7 +104,12 @@ impl WindowManager { } } - if matches!(notification, AccessibilityNotification::AXMainWindowChanged) { + if matches!( + notification, + SystemNotification::Accessibility( + AccessibilityNotification::AXMainWindowChanged + ) + ) { self.reap_invalid_windows_for_application(process_id)?; self.update_focused_workspace(false, false)?; } diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index fb67b849..709bb4c0 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -25,6 +25,7 @@ use crate::core::rect::Rect; use crate::core_graphics::CoreGraphicsApi; use crate::hidden_frame_bottom_left; use crate::macos_api::MacosApi; +use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; use objc2_app_kit::NSApplicationActivationOptions; use objc2_app_kit::NSRunningApplication; @@ -85,8 +86,11 @@ unsafe extern "C-unwind" fn window_observer_callback( if let Ok(notification) = AccessibilityNotification::from_str(¬ification.as_ref().to_string()) - && let Some(event) = - WindowManagerEvent::from_ax_notification(notification, process_id, window_id) + && let Some(event) = WindowManagerEvent::from_system_notification( + SystemNotification::Accessibility(notification), + process_id, + window_id, + ) { if let Err(error) = event_tx().send(event) { tracing::error!("failed to send window manager event: {error}"); @@ -148,7 +152,6 @@ impl WindowInfo { } #[derive(Debug, Clone)] -#[allow(unused)] pub struct Window { pub id: u32, pub element: AccessibilityUiElement, @@ -459,7 +462,6 @@ impl From<&CFDictionary> for WindowInfo { } #[derive(Default, Debug, Copy, Clone)] -#[allow(unused)] pub struct WindowBounds { pub height: f32, pub width: f32, diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index c06cc7c3..8cd9b1cd 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -1,41 +1,62 @@ #![allow(non_upper_case_globals)] use crate::accessibility::notification_constants::AccessibilityNotification; +use crate::app_kit_notification_constants::AppKitWorkspaceNotification; use serde::Deserialize; use serde::Serialize; use strum::Display; +#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] +#[serde(tag = "type", content = "content")] +pub enum SystemNotification { + Accessibility(AccessibilityNotification), + AppKitWorkspace(AppKitWorkspaceNotification), +} + #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] #[serde(tag = "type", content = "content")] pub enum WindowManagerEvent { - FocusChange(AccessibilityNotification, i32, Option), - Show(AccessibilityNotification, i32), - Destroy(AccessibilityNotification, i32), - Minimize(AccessibilityNotification, i32, u32), - Restore(AccessibilityNotification, i32, u32), + FocusChange(SystemNotification, i32, Option), + Show(SystemNotification, i32), + Destroy(SystemNotification, i32), + Minimize(SystemNotification, i32, u32), + Restore(SystemNotification, i32, u32), } impl WindowManagerEvent { - pub fn from_ax_notification( - notification: AccessibilityNotification, + pub fn from_system_notification( + notification: SystemNotification, process_id: i32, window_id: Option, ) -> Option { match notification { - AccessibilityNotification::AXMainWindowChanged - | AccessibilityNotification::AXApplicationActivated => Some( - WindowManagerEvent::FocusChange(notification, process_id, window_id), - ), - AccessibilityNotification::AXWindowCreated - | AccessibilityNotification::AXApplicationShown => { - Some(WindowManagerEvent::Show(notification, process_id)) + SystemNotification::Accessibility(AccessibilityNotification::AXMainWindowChanged) + | SystemNotification::Accessibility( + AccessibilityNotification::AXApplicationActivated, + ) => Some(WindowManagerEvent::FocusChange( + notification, + process_id, + window_id, + )), + SystemNotification::Accessibility(AccessibilityNotification::AXWindowCreated) + | SystemNotification::Accessibility(AccessibilityNotification::AXApplicationShown) + | SystemNotification::AppKitWorkspace( + AppKitWorkspaceNotification::NSWorkspaceDidLaunchApplicationNotification, + ) => Some(WindowManagerEvent::Show(notification, process_id)), + SystemNotification::Accessibility(AccessibilityNotification::AXUIElementDestroyed) + | SystemNotification::AppKitWorkspace( + AppKitWorkspaceNotification::NSWorkspaceDidTerminateApplicationNotification, + ) => Some(WindowManagerEvent::Destroy(notification, process_id)), + // TODO: figure out if we wanna handle the hide/unhide notifications separately + // TODO: maybe turn window id into a vec of window IDs for hidden apps + SystemNotification::Accessibility(AccessibilityNotification::AXWindowMiniaturized) => { + window_id.map(|window_id| { + WindowManagerEvent::Minimize(notification, process_id, window_id) + }) } - AccessibilityNotification::AXUIElementDestroyed => { - Some(WindowManagerEvent::Destroy(notification, process_id)) - } - AccessibilityNotification::AXWindowMiniaturized => window_id - .map(|window_id| WindowManagerEvent::Minimize(notification, process_id, window_id)), - AccessibilityNotification::AXWindowDeminiaturized => window_id + SystemNotification::Accessibility( + AccessibilityNotification::AXWindowDeminiaturized, + ) => window_id .map(|window_id| WindowManagerEvent::Restore(notification, process_id, window_id)), // kAXWindowMovedNotification => {} // kAXWindowResizedNotification => {} diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 4408040e..1b413c08 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -227,9 +227,16 @@ impl Workspace { for container in self.containers() { if let Some(focused_window) = container.focused_window() && focused_window.application.process_id == process_id - && !valid_window_ids.contains(&focused_window.id) { - invalid_window_ids.push(focused_window.id); + if !valid_window_ids.contains(&focused_window.id) { + invalid_window_ids.push(focused_window.id); + } + + // if accessibility API calls fail on AXError::InvalidUIElement + // let's try and nuke these early + if !focused_window.is_valid() { + invalid_window_ids.push(focused_window.id); + } } }