diff --git a/Cargo.lock b/Cargo.lock index cd2874b8..a29ca2e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -247,6 +247,21 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "crossbeam-channel" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + [[package]] name = "ctrlc" version = "3.5.0" @@ -512,6 +527,7 @@ version = "0.1.0" dependencies = [ "clap", "color-eyre", + "crossbeam-channel", "ctrlc", "dirs", "lazy_static", diff --git a/justfile b/justfile index 6a068793..7af0ca48 100644 --- a/justfile +++ b/justfile @@ -9,7 +9,7 @@ fmt: prettier --write README.md install target: - cargo +stable install --path {{ target }} --locked + cargo +stable install --path {{ target }} --locked --target-dir ~/.cargo/bin build target: cargo +stable build --package {{ target }} --locked --release diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 41542be9..c6c3a98d 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -6,6 +6,7 @@ edition = "2024" [dependencies] clap = { workspace = true } color-eyre = { workspace = true } +crossbeam-channel = "0.5" ctrlc = { version = "3", features = ["termination"] } dirs = { workspace = true } lazy_static = { workspace = true } diff --git a/komorebi/src/accessibility/mod.rs b/komorebi/src/accessibility/mod.rs index 998c2648..fac385d6 100644 --- a/komorebi/src/accessibility/mod.rs +++ b/komorebi/src/accessibility/mod.rs @@ -1,3 +1,4 @@ +use crate::accessibility::private::_AXUIElementGetWindow; use error::AccessibilityApiError; use error::AccessibilityCustomError; use error::AccessibilityError; @@ -6,21 +7,34 @@ use objc2_application_services::AXObserverCallback; use objc2_application_services::AXUIElement; use objc2_application_services::AXValue; use objc2_application_services::AXValueType; +use objc2_core_foundation::CFArray; use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFRunLoop; use objc2_core_foundation::CFRunLoopSource; use objc2_core_foundation::CFString; use objc2_core_foundation::CFType; use objc2_core_foundation::kCFRunLoopDefaultMode; +use objc2_core_graphics::CGWindowID; use std::ptr::NonNull; pub mod attribute_constants; pub mod error; pub mod notification_constants; +pub mod private; pub struct AccessibilityApi; impl AccessibilityApi { + pub fn window_id(element: &AXUIElement) -> Result { + let mut window_id = CGWindowID::default(); + unsafe { + match AccessibilityError::from(_AXUIElementGetWindow(element, &mut window_id)) { + AccessibilityError::Api(AccessibilityApiError::Success) => Ok(window_id), + error => Err(error), + } + } + } + pub fn copy_attribute_value( element: &AXUIElement, attribute: &'static str, @@ -38,6 +52,17 @@ impl AccessibilityApi { } } + pub fn copy_attribute_names(element: &AXUIElement) -> Option> { + let mut receiver = std::ptr::null(); + + unsafe { + element.copy_attribute_names(NonNull::from(&mut receiver)); + + NonNull::new(receiver.cast::().cast_mut()) + .map(|cf_type| CFRetained::from_raw(cf_type)) + } + } + pub fn set_attribute_ax_value( element: &AXUIElement, attribute: &'static str, diff --git a/komorebi/src/accessibility/notification_constants.rs b/komorebi/src/accessibility/notification_constants.rs index 6837505d..8bd11d37 100644 --- a/komorebi/src/accessibility/notification_constants.rs +++ b/komorebi/src/accessibility/notification_constants.rs @@ -1,5 +1,10 @@ #![allow(non_upper_case_globals, unused)] +use serde::Deserialize; +use serde::Serialize; +use strum::Display; +use strum::EnumString; + pub const kAXMainWindowChangedNotification: &str = "AXMainWindowChanged"; pub const kAXFocusedWindowChangedNotification: &str = "AXFocusedWindowChanged"; pub const kAXFocusedUIElementChangedNotification: &str = "AXFocusedUIElementChanged"; @@ -41,3 +46,48 @@ pub const kAXUIElementsKey: &str = "AXUIElementsKey"; pub const kAXPriorityKey: &str = "AXPriorityKey"; pub const kAXAnnouncementKey: &str = "AXAnnouncementKey"; pub const kAXUIElementTitleKey: &str = "AXUIElementTitleKey"; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, EnumString, Display, Serialize, Deserialize)] +pub enum AccessibilityNotification { + AXMainWindowChanged, + AXFocusedWindowChanged, + AXFocusedUIElementChanged, + AXApplicationActivated, + AXApplicationDeactivated, + AXApplicationHidden, + AXApplicationShown, + AXWindowCreated, + AXWindowMoved, + AXWindowResized, + AXWindowMiniaturized, + AXWindowDeminiaturized, + AXDrawerCreated, + AXSheetCreated, + AXHelpTagCreated, + AXValueChanged, + AXUIElementDestroyed, + AXElementBusyChanged, + AXMenuOpened, + AXMenuClosed, + AXMenuItemSelected, + AXRowCountChanged, + AXRowExpanded, + AXRowCollapsed, + AXSelectedCellsChanged, + AXUnitsChanged, + AXSelectedChildrenMoved, + AXSelectedChildrenChanged, + AXResized, + AXMoved, + AXCreated, + AXSelectedRowsChanged, + AXSelectedColumnsChanged, + AXSelectedTextChanged, + AXTitleChanged, + AXLayoutChanged, + AXAnnouncementRequested, + AXUIElementsKey, + AXPriorityKey, + AXAnnouncementKey, + AXUIElementTitleKey, +} diff --git a/komorebi/src/accessibility/private.rs b/komorebi/src/accessibility/private.rs new file mode 100644 index 00000000..5e1eab7c --- /dev/null +++ b/komorebi/src/accessibility/private.rs @@ -0,0 +1,10 @@ +use objc2_application_services::AXError; +use objc2_application_services::AXUIElement; +use objc2_core_graphics::CGWindowID; + +// this is the only private API call Aerospace uses, so I think we're ok to use it too +// https://github.com/nikitabobko/AeroSpace?tab=readme-ov-file#project-values +unsafe extern "C" { + /// Extract `window_id` from an AXUIElement. + pub(crate) fn _AXUIElementGetWindow(elem: &AXUIElement, window_id: *mut CGWindowID) -> AXError; +} diff --git a/komorebi/src/application.rs b/komorebi/src/application.rs index f76f9684..377562cb 100644 --- a/komorebi/src/application.rs +++ b/komorebi/src/application.rs @@ -1,9 +1,11 @@ use crate::AccessibilityObserver; use crate::AccessibilityUiElement; use crate::accessibility::AccessibilityApi; +use crate::accessibility::attribute_constants::kAXMainWindowAttribute; use crate::accessibility::attribute_constants::kAXTitleAttribute; use crate::accessibility::attribute_constants::kAXWindowsAttribute; use crate::accessibility::error::AccessibilityError; +use crate::accessibility::notification_constants::AccessibilityNotification; use crate::accessibility::notification_constants::kAXApplicationActivatedNotification; use crate::accessibility::notification_constants::kAXApplicationDeactivatedNotification; use crate::accessibility::notification_constants::kAXApplicationHiddenNotification; @@ -11,7 +13,9 @@ use crate::accessibility::notification_constants::kAXApplicationShownNotificatio use crate::accessibility::notification_constants::kAXMainWindowChangedNotification; use crate::accessibility::notification_constants::kAXUIElementDestroyedNotification; use crate::accessibility::notification_constants::kAXWindowCreatedNotification; +use crate::ax_event_listener::event_tx; use crate::window::Window; +use crate::window_manager_event::WindowManagerEvent; use objc2_application_services::AXObserver; use objc2_application_services::AXUIElement; use objc2_core_foundation::CFArray; @@ -20,6 +24,7 @@ use objc2_core_foundation::CFRunLoop; use objc2_core_foundation::CFString; use std::ffi::c_void; use std::ptr::NonNull; +use std::str::FromStr; use tracing::instrument; const NOTIFICATIONS: &[&str] = &[ @@ -55,31 +60,42 @@ unsafe extern "C-unwind" fn application_observer_callback( AccessibilityApi::copy_attribute_value::(element.as_ref(), kAXTitleAttribute) .map(|s| s.to_string()); - let mut pid = 0; - - element.as_ref().pid(NonNull::from_mut(&mut pid)); - if let Some(name) = name && !name.is_empty() { - tracing::info!( - "notification: {}, process: {pid}, name: \"{name}\"", - notification.as_ref() - ); - } else { - tracing::info!("notification: {}, process: {pid}", notification.as_ref()); + let mut process_id = 0; + element.as_ref().pid(NonNull::from_mut(&mut process_id)); + + if let Ok(notification) = + AccessibilityNotification::from_str(¬ification.as_ref().to_string()) + && let Some(event) = + WindowManagerEvent::from_ax_notification(notification, process_id, None) + { + if let Err(error) = event_tx().send(event) { + tracing::error!("failed to send window manager event: {error}"); + } else { + tracing::debug!( + "notification: {notification}, process: {process_id}, name: \"{name}\"", + ); + } + } } } } impl Drop for Application { fn drop(&mut self) { - tracing::info!( - "invalidating application observer for process id {}", - self.process_id - ); - // make sure the observer gets removed from any run loops - AccessibilityApi::invalidate_observer(&self.observer); + // this gets called when an Application clone on a Window is dropped, so we need + // to make sure it only invalidates the observer if the Application is no longer + // running + if !self.is_valid() { + tracing::info!( + "invalidating application observer for process id {}", + self.process_id + ); + // make sure the observer gets removed from any run loops + AccessibilityApi::invalidate_observer(&self.observer); + } } } @@ -117,13 +133,29 @@ impl Application { ) } - fn window_elements(&self) -> Option>> { + pub fn is_valid(&self) -> bool { + AccessibilityApi::copy_attribute_names(&self.element).is_some() + } + + pub fn window_elements(&self) -> Option>> { AccessibilityApi::copy_attribute_value::>( &self.element, kAXWindowsAttribute, ) } + pub fn main_window(&self) -> Option> { + AccessibilityApi::copy_attribute_value::(&self.element, kAXMainWindowAttribute) + } + + pub fn main_window_id(&self) -> Option { + let window = AccessibilityApi::copy_attribute_value::( + &self.element, + kAXMainWindowAttribute, + )?; + AccessibilityApi::window_id(window.as_ref()).ok() + } + pub fn window_by_title(&self, title: &str) -> Option { let mut target = None; diff --git a/komorebi/src/ax_event_listener.rs b/komorebi/src/ax_event_listener.rs new file mode 100644 index 00000000..2afdd702 --- /dev/null +++ b/komorebi/src/ax_event_listener.rs @@ -0,0 +1,19 @@ +use crate::window_manager_event::WindowManagerEvent; +use crossbeam_channel::Receiver; +use crossbeam_channel::Sender; +use std::sync::OnceLock; + +static CHANNEL: OnceLock<(Sender, Receiver)> = + OnceLock::new(); + +fn channel() -> &'static (Sender, Receiver) { + CHANNEL.get_or_init(|| crossbeam_channel::bounded(20)) +} + +pub fn event_tx() -> Sender { + channel().0.clone() +} + +pub fn event_rx() -> Receiver { + channel().1.clone() +} diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs new file mode 100644 index 00000000..a0b57c6e --- /dev/null +++ b/komorebi/src/container.rs @@ -0,0 +1,83 @@ +use crate::lockable_sequence::Lockable; +use crate::ring::Ring; +use crate::window::Window; + +impl_ring_elements!(Container, Window); + +#[derive(Debug, Default)] +pub struct Container { + pub windows: Ring, + pub locked: bool, +} + +impl Lockable for Container { + fn locked(&self) -> bool { + self.locked + } + + fn set_locked(&mut self, locked: bool) -> &mut Self { + self.locked = locked; + self + } +} + +impl Container { + pub fn contains_window(&self, window_id: u32) -> bool { + for window in self.windows() { + if window.id == window_id { + return true; + } + } + + false + } + + pub fn idx_for_window(&self, window_id: u32) -> Option { + for (i, window) in self.windows().iter().enumerate() { + if window.id == window_id { + return Option::from(i); + } + } + + None + } + + pub fn add_window(&mut self, window: Window) { + self.windows_mut().push_back(window); + self.focus_window(self.windows().len().saturating_sub(1)); + // let focused_window_idx = self.focused_window_idx(); + + // for (i, window) in self.windows().iter().enumerate() { + // if i != focused_window_idx { + // window.hide(); + // } + // } + } + + #[tracing::instrument(skip(self))] + pub fn focus_window(&mut self, idx: usize) { + tracing::info!("focusing window"); + self.windows.focus(idx); + } + + /// Hides the unfocused windows of the container and restores the focused one. This function + /// is used to make sure we update the window that should be shown on a stack. If the container + /// isn't a stack this function won't change anything. + pub fn load_focused_window(&mut self) { + // let focused_idx = self.focused_window_idx(); + + // for (i, window) in self.windows_mut().iter_mut().enumerate() { + // if i == focused_idx { + // window.restore_with_border(false); + // } else { + // window.hide_with_border(false); + // } + // } + } + + pub fn remove_window_by_idx(&mut self, idx: usize) -> Option { + let window = self.windows_mut().remove(idx); + self.focus_window(idx.saturating_sub(1)); + window + } +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index ac464246..72a7db55 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -21,14 +21,18 @@ pub mod ring; pub mod accessibility; pub mod application; +pub mod ax_event_listener; +mod container; pub mod core; pub mod core_graphics; pub mod lockable_sequence; pub mod macos_api; mod monitor; pub mod process_command; +pub mod process_event; pub mod window; pub mod window_manager; +pub mod window_manager_event; pub mod workspace; lazy_static! { diff --git a/komorebi/src/macos_api.rs b/komorebi/src/macos_api.rs index cb5df965..697f449a 100644 --- a/komorebi/src/macos_api.rs +++ b/komorebi/src/macos_api.rs @@ -3,11 +3,11 @@ use crate::accessibility::attribute_constants::kAXPositionAttribute; use crate::accessibility::attribute_constants::kAXSizeAttribute; use crate::application::Application; use crate::cf_array_as; +use crate::container::Container; use crate::core::rect::Rect; use crate::core_graphics::CoreGraphicsApi; use crate::monitor::Monitor; use crate::window::WindowInfo; -use crate::window_manager::Container; use crate::window_manager::WindowManager; use objc2::MainThreadMarker; use objc2_app_kit::NSScreen; diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index da29eb61..d98df720 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -3,7 +3,9 @@ use color_eyre::eyre; use color_eyre::eyre::eyre; use komorebi::DATA_DIR; +use komorebi::ax_event_listener; use komorebi::process_command::listen_for_commands; +use komorebi::process_event::listen_for_events; use komorebi::window_manager::WindowManager; use objc2::rc::autoreleasepool; use objc2_application_services::AXIsProcessTrusted; @@ -101,11 +103,16 @@ 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 wm = Arc::new(Mutex::new(WindowManager::new(&run_loop, None)?)); + 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()); let quit_ctrlc = Arc::new(AtomicBool::new(false)); let quit_thread = quit_ctrlc.clone(); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs new file mode 100644 index 00000000..7560895f --- /dev/null +++ b/komorebi/src/process_event.rs @@ -0,0 +1,132 @@ +use crate::accessibility::AccessibilityApi; +use crate::accessibility::notification_constants::AccessibilityNotification; +use crate::application::Application; +use crate::window::Window; +use crate::window_manager::WindowManager; +use crate::window_manager_event::WindowManagerEvent; +use color_eyre::eyre; +use parking_lot::Mutex; +use std::sync::Arc; + +#[tracing::instrument] +pub fn listen_for_events(wm: Arc>) { + let receiver = wm.lock().incoming_events.clone(); + + std::thread::spawn(move || { + tracing::info!("listening"); + loop { + if let Ok(event) = receiver.recv() { + let mut guard = wm.lock(); + match guard.process_event(event) { + Ok(()) => {} + Err(error) => { + if cfg!(debug_assertions) { + tracing::error!("{:?}", error) + } else { + tracing::error!("{}", error) + } + } + } + } + } + }); +} + +impl WindowManager { + pub fn process_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> { + if self.is_paused { + tracing::trace!("ignoring while paused"); + return Ok(()); + } + + tracing::info!("processing event: {event}"); + + match event { + WindowManagerEvent::FocusChange(notification, process_id, _) => { + if let Some(application) = self.applications.get(&process_id) + && let Some(window_id) = application.main_window_id() + { + self.focused_workspace_mut()? + .focus_container_by_window(window_id)?; + } + + if matches!(notification, AccessibilityNotification::AXMainWindowChanged) { + self.reap_invalid_windows_for_application(process_id)?; + self.update_focused_workspace(false, false)?; + } + } + WindowManagerEvent::Show(_, process_id) => { + let mut window_id = None; + let mut create = true; + + { + let application = self.applications.entry(process_id).or_insert_with(|| { + let application = + Application::new(process_id).expect("could not create application"); + application + .observe(&self.run_loop) + .expect("could not observe application"); + application + }); + + if let Some(element) = application.main_window() + && let Ok(wid) = AccessibilityApi::window_id(&element) + { + window_id = Some(wid); + } + } + + if let Some(window_id) = window_id { + 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 create { + let application = self.applications.entry(process_id).or_insert_with(|| { + let application = + Application::new(process_id).expect("could not create application"); + application + .observe(&self.run_loop) + .expect("could not observe application"); + application + }); + + if let Some(element) = application.main_window() + && let Ok(window) = Window::new(element, application.clone()) + { + window.observe(&self.run_loop)?; + + let workspace = self.focused_workspace_mut()?; + workspace.new_container_for_window(window); + + self.update_focused_workspace(false, false)?; + } + } + } + WindowManagerEvent::Destroy(_, process_id) => { + self.reap_invalid_windows_for_application(process_id)?; + self.update_focused_workspace(false, false)?; + } + WindowManagerEvent::Minimize(_, _, window_id) => { + self.extract_minimized_window(window_id)?; + self.update_focused_workspace(false, false)?; + } + WindowManagerEvent::Restore(_, _, window_id) => { + match self.minimized_windows.remove(&window_id) { + None => {} + Some(window) => { + let workspace = self.focused_workspace_mut()?; + workspace.new_container_for_window(window); + self.update_focused_workspace(false, false)?; + } + } + } + } + + Ok(()) + } +} diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 38dc9c07..6017789b 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -8,14 +8,17 @@ use crate::accessibility::attribute_constants::kAXSizeAttribute; use crate::accessibility::attribute_constants::kAXTitleAttribute; use crate::accessibility::error::AccessibilityCustomError; use crate::accessibility::error::AccessibilityError; +use crate::accessibility::notification_constants::AccessibilityNotification; use crate::accessibility::notification_constants::kAXTitleChangedNotification; use crate::accessibility::notification_constants::kAXWindowDeminiaturizedNotification; use crate::accessibility::notification_constants::kAXWindowMiniaturizedNotification; use crate::accessibility::notification_constants::kAXWindowMovedNotification; use crate::accessibility::notification_constants::kAXWindowResizedNotification; use crate::application::Application; +use crate::ax_event_listener::event_tx; use crate::cf_dictionary_value; use crate::core::rect::Rect; +use crate::window_manager_event::WindowManagerEvent; use objc2_app_kit::NSApplicationActivationOptions; use objc2_app_kit::NSRunningApplication; use objc2_application_services::AXObserver; @@ -37,6 +40,7 @@ use objc2_core_graphics::kCGWindowOwnerName; use objc2_core_graphics::kCGWindowOwnerPID; use std::ffi::c_void; use std::ptr::NonNull; +use std::str::FromStr; use tracing::instrument; const NOTIFICATIONS: &[&str] = &[ @@ -55,23 +59,32 @@ unsafe extern "C-unwind" fn window_observer_callback( _context: *mut c_void, ) { unsafe { - let title = + let name = AccessibilityApi::copy_attribute_value::(element.as_ref(), kAXTitleAttribute) .map(|s| s.to_string()); - let mut pid = 0; - - element.as_ref().pid(NonNull::from_mut(&mut pid)); - - if let Some(title) = title - && !title.is_empty() + if let Some(name) = name + && !name.is_empty() { - tracing::info!( - "notification: {}, process: {pid}, title: \"{title}\"", - notification.as_ref() - ); - } else { - tracing::info!("notification: {}, process: {pid}", notification.as_ref()); + let mut process_id = 0; + element.as_ref().pid(NonNull::from_mut(&mut process_id)); + + let window_id = AccessibilityApi::window_id(element.as_ref()).ok(); + + if let Ok(notification) = + AccessibilityNotification::from_str(¬ification.as_ref().to_string()) + && let Some(event) = + WindowManagerEvent::from_ax_notification(notification, process_id, window_id) + { + if let Err(error) = event_tx().send(event) { + tracing::error!("failed to send window manager event: {error}"); + } else { + tracing::debug!( + "notification: {}, process: {process_id}, name: \"{name}\"", + notification, + ); + } + } } } } @@ -125,8 +138,9 @@ impl WindowInfo { #[derive(Debug)] #[allow(unused)] pub struct Window { + pub id: u32, element: AccessibilityUiElement, - application: Application, + pub application: Application, observer: AccessibilityObserver, } @@ -153,12 +167,17 @@ impl Window { )?; Ok(Self { + id: AccessibilityApi::window_id(&element)?, element: AccessibilityUiElement(element), application, observer: AccessibilityObserver(observer), }) } + pub fn is_valid(&self) -> bool { + AccessibilityApi::copy_attribute_names(&self.element).is_some() + } + #[tracing::instrument(skip_all)] pub fn observe(&self, run_loop: &CFRunLoop) -> Result<(), AccessibilityError> { tracing::info!( diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 4fc5b3aa..36bc99bd 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1,19 +1,22 @@ use crate::CoreFoundationRunLoop; use crate::DATA_DIR; use crate::LibraryError; +use crate::accessibility::AccessibilityApi; use crate::application::Application; +use crate::container::Container; use crate::core::default_layout::DefaultLayout; use crate::core::layout::Layout; use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; -use crate::lockable_sequence::Lockable; use crate::macos_api::MacosApi; use crate::monitor::Monitor; use crate::ring::Ring; use crate::window::Window; +use crate::window_manager_event::WindowManagerEvent; use crate::workspace::Workspace; use color_eyre::eyre; use color_eyre::eyre::eyre; +use crossbeam_channel::Receiver; use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFRunLoop; use std::collections::HashMap; @@ -30,6 +33,8 @@ pub struct WindowManager { pub is_paused: bool, pub mouse_follows_focus: bool, pub work_area_offset: Option, + pub incoming_events: Receiver, + pub minimized_windows: HashMap, } impl_ring_elements!(WindowManager, Monitor); @@ -37,6 +42,7 @@ impl_ring_elements!(WindowManager, Monitor); impl WindowManager { pub fn new( run_loop: &CFRetained, + incoming: Receiver, custom_socket_path: Option, ) -> eyre::Result { let socket = custom_socket_path.unwrap_or_else(|| DATA_DIR.join("komorebi.sock")); @@ -61,6 +67,8 @@ impl WindowManager { is_paused: false, mouse_follows_focus: true, work_area_offset: None, + incoming_events: incoming, + minimized_windows: HashMap::new(), }) } @@ -241,22 +249,32 @@ impl WindowManager { .focused_window_mut() .ok_or_else(|| eyre!("there is no window")) } -} -impl_ring_elements!(Container, Window); -#[derive(Debug, Default)] -pub struct Container { - pub windows: Ring, - pub locked: bool, -} + pub fn extract_minimized_window(&mut self, window_id: u32) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + let window = workspace.remove_window(window_id)?; + self.minimized_windows.insert(window_id, window); -impl Lockable for Container { - fn locked(&self) -> bool { - self.locked + Ok(()) } - fn set_locked(&mut self, locked: bool) -> &mut Self { - self.locked = locked; - self + pub fn reap_invalid_windows_for_application(&mut self, process_id: i32) -> eyre::Result<()> { + if let Some(application) = self.applications.get(&process_id) { + let mut valid_window_ids = vec![]; + if let Some(elements) = application.window_elements() { + for element in elements { + if let Ok(window_id) = AccessibilityApi::window_id(&element) { + valid_window_ids.push(window_id); + } + } + } + + let focused_workspace = self.focused_workspace_mut()?; + focused_workspace + .reap_invalid_windows_for_application(process_id, &valid_window_ids)?; + self.update_focused_workspace(false, false)?; + } + + Ok(()) } } diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs new file mode 100644 index 00000000..8f11c7ca --- /dev/null +++ b/komorebi/src/window_manager_event.rs @@ -0,0 +1,47 @@ +#![allow(non_upper_case_globals)] + +use crate::accessibility::notification_constants::AccessibilityNotification; +use serde::Deserialize; +use serde::Serialize; +use strum::Display; + +#[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), +} + +impl WindowManagerEvent { + pub fn from_ax_notification( + notification: AccessibilityNotification, + 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)) + } + 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 + .map(|window_id| WindowManagerEvent::Restore(notification, process_id, window_id)), + // kAXWindowMovedNotification => {} + // kAXWindowResizedNotification => {} + // kAXTitleChangedNotification => {} + // kAXApplicationDeactivatedNotification => {} + _ => None, + } + } +} diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 012f8e7f..82b9180a 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -1,3 +1,4 @@ +use crate::container::Container; use crate::core::arrangement::Axis; use crate::core::default_layout::DefaultLayout; use crate::core::default_layout::LayoutOptions; @@ -6,7 +7,7 @@ use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; use crate::lockable_sequence::LockableSequence; use crate::ring::Ring; -use crate::window_manager::Container; +use crate::window::Window; use color_eyre::eyre; use color_eyre::eyre::eyre; use std::num::NonZeroUsize; @@ -153,4 +154,159 @@ impl Workspace { len, ) } + + pub fn container_idx_for_window(&self, window_id: u32) -> Option { + let mut idx = None; + for (i, x) in self.containers().iter().enumerate() { + if x.contains_window(window_id) { + idx = Option::from(i); + } + } + + idx + } + + pub fn focus_container_by_window(&mut self, window_id: u32) -> eyre::Result<()> { + let container_idx = self + .container_idx_for_window(window_id) + .ok_or_else(|| eyre!("there is no container/window"))?; + + let container = self + .containers_mut() + .get_mut(container_idx) + .ok_or_else(|| eyre!("there is no container"))?; + + let window_idx = container + .idx_for_window(window_id) + .ok_or_else(|| eyre!("there is no window"))?; + + let mut should_load = false; + + if container.focused_window_idx() != window_idx { + should_load = true + } + + container.focus_window(window_idx); + + if should_load { + container.load_focused_window(); + } + + self.focus_container(container_idx); + + Ok(()) + } + + pub fn new_container_for_window(&mut self, window: Window) { + let next_idx = if self.containers().is_empty() { + 0 + } else { + self.focused_container_idx() + 1 + }; + + let mut container = Container::default(); + container.add_window(window); + + self.insert_container_at_idx(next_idx, container); + } + + // this fn respects locked container indexes - we should use it for pretty much everything + // except monocle and maximize toggles + pub fn insert_container_at_idx(&mut self, idx: usize, container: Container) -> usize { + let insertion_idx = self + .containers_mut() + .insert_respecting_locks(idx, container); + + if insertion_idx > self.resize_dimensions.len() { + self.resize_dimensions.push(None); + } else { + self.resize_dimensions.insert(insertion_idx, None); + } + + self.focus_container(insertion_idx); + + insertion_idx + } + + pub fn reap_invalid_windows_for_application( + &mut self, + process_id: i32, + valid_window_ids: &[u32], + ) -> eyre::Result<()> { + let mut invalid_window_ids = vec![]; + 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); + } + } + + for window_id in invalid_window_ids { + self.remove_window(window_id)?; + } + + Ok(()) + } + + pub fn remove_window(&mut self, window_id: u32) -> eyre::Result { + let container_idx = self + .container_idx_for_window(window_id) + .ok_or_else(|| eyre!("there is no window"))?; + + let container = self + .containers_mut() + .get_mut(container_idx) + .ok_or_else(|| eyre!("there is no container"))?; + + let window_idx = container + .windows() + .iter() + .position(|window| window.id == window_id) + .ok_or_else(|| eyre!("there is no window"))?; + + let window = container + .remove_window_by_idx(window_idx) + .ok_or_else(|| eyre!("there is no window"))?; + + if container.windows().is_empty() { + self.remove_container_by_idx(container_idx); + self.focus_previous_container(); + } else { + container.load_focused_window(); + if let Some(window) = container.focused_window() { + window.focus(false)?; + } + } + + Ok(window) + } + + // this fn respects locked container indexes - we should use it for pretty much everything + // except monocle and maximize toggles + pub fn remove_container_by_idx(&mut self, idx: usize) -> Option { + let container = self.containers_mut().remove_respecting_locks(idx); + + if idx < self.resize_dimensions.len() { + self.resize_dimensions.remove(idx); + } + + container + } + + pub fn focus_previous_container(&mut self) { + let focused_idx = self.focused_container_idx(); + self.focus_container(focused_idx.saturating_sub(1)); + } + + pub fn contains_window(&self, window_id: u32) -> bool { + for container in self.containers() { + if container.contains_window(window_id) { + return true; + } + } + + false + } }