feat(wm): add notification center listener

This commit adds a listener for the NotificationCenter of the
SharedWorkspace, which allows us to be notified of acts like new app
creation, app termination (different from app window destruction),
application hides and application unhides, among many others.

There are a lot of the AppKit notifications which can be registered with
observers on the notification center; for now I have just modeled the
AppKitWorkspaceNotification enum which seems to hold the most
interesting notifications for our use case.

NSWorkspaceDidLaunchApplicationNotification and
NSWorkspaceDidTerminateApplicationNotification are now hooked in to the
Show and Destroy WindowManagerEvents, but I still need to think about
how to hook in the events around hiding and unhiding as these are
temporary/reversible actions which operate across multiple application
windows, unlike minimize/restore which only operate on one application
window at a time.
This commit is contained in:
LGUG2Z committed 2025-09-21 09:22:54 -07:00
1 parent b7ce8c03b5
commit a4bc40aa5e
12 files changed
+328 -30

No files matched your search

Generated
+3
View File
@@ -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",
]
+2
View File
@@ -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
+1
View File
@@ -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"
@@ -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<AppKitWorkspaceNotification> for Retained<NSNotificationName> {
fn from(value: AppKitWorkspaceNotification) -> Self {
NSNotificationName::from_str(&value.to_string())
}
}
impl TryFrom<NSNotification> for AppKitWorkspaceNotification {
type Error = strum::ParseError;
fn try_from(value: NSNotification) -> Result<Self, Self::Error> {
let name = unsafe { value.name().to_string() };
AppKitWorkspaceNotification::from_str(&name)
}
}
+6 -2
View File
@@ -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(&notification.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}");
+3 -1
View File
@@ -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;
+3
View File
@@ -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);
@@ -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::<NSString>() {
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::<NSRunningApplication>()
{
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(&notif.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<NotificationCenterListenerNsObject>,
}
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<Self> {
// 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<NSNotificationName> = notification.into();
// thanks, I hate it
notification_center.addObserver_selector_name_object(
&observer.inner,
sel!(handleNotification:),
Some(&notification_name),
None,
);
}
}
observer
}
}
+7 -1
View File
@@ -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)?;
}
+6 -4
View File
@@ -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(&notification.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,
+41 -20
View File
@@ -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<u32>),
Show(AccessibilityNotification, i32),
Destroy(AccessibilityNotification, i32),
Minimize(AccessibilityNotification, i32, u32),
Restore(AccessibilityNotification, i32, u32),
FocusChange(SystemNotification, i32, Option<u32>),
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<u32>,
) -> Option<Self> {
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 => {}
+9 -2
View File
@@ -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);
}
}
}