mirror of
https://github.com/LGUG2Z/komorebi.git
synced 2026-11-20 15:41:38 +01:00
feat(wm): add basic window manager event handling
This commit adds a WindowManagerEvent enum and a channel to send and receive variants of it on. The skeleton of process_event has been migrated from komorebi and a few basic implementations of handlers for core events like FocusChange, Show, Destroy, Minimize and Restore have been added. Due to the way the window observers work, in komorebi for Mac we'll need to keep track of minimized Windows so that we don't drop their observers (otherwise we won't receive a notification when they are restored). Most of the code added in this commit around modifying state in response to these events has been migrated from komorebi.
This commit is contained in:
1 parent
df9ceee17e
commit
4f6267b56e
17 files changed
+668
-49
No files matched your search
Generated
+16
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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<u32, AccessibilityError> {
|
||||
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<T: objc2_core_foundation::Type>(
|
||||
element: &AXUIElement,
|
||||
attribute: &'static str,
|
||||
@@ -38,6 +52,17 @@ impl AccessibilityApi {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn copy_attribute_names(element: &AXUIElement) -> Option<CFRetained<CFArray>> {
|
||||
let mut receiver = std::ptr::null();
|
||||
|
||||
unsafe {
|
||||
element.copy_attribute_names(NonNull::from(&mut receiver));
|
||||
|
||||
NonNull::new(receiver.cast::<CFArray>().cast_mut())
|
||||
.map(|cf_type| CFRetained::from_raw(cf_type))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_attribute_ax_value<T>(
|
||||
element: &AXUIElement,
|
||||
attribute: &'static str,
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+49
-17
@@ -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::<CFString>(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<CFRetained<CFArray<AXUIElement>>> {
|
||||
pub fn is_valid(&self) -> bool {
|
||||
AccessibilityApi::copy_attribute_names(&self.element).is_some()
|
||||
}
|
||||
|
||||
pub fn window_elements(&self) -> Option<CFRetained<CFArray<AXUIElement>>> {
|
||||
AccessibilityApi::copy_attribute_value::<CFArray<AXUIElement>>(
|
||||
&self.element,
|
||||
kAXWindowsAttribute,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn main_window(&self) -> Option<CFRetained<AXUIElement>> {
|
||||
AccessibilityApi::copy_attribute_value::<AXUIElement>(&self.element, kAXMainWindowAttribute)
|
||||
}
|
||||
|
||||
pub fn main_window_id(&self) -> Option<u32> {
|
||||
let window = AccessibilityApi::copy_attribute_value::<AXUIElement>(
|
||||
&self.element,
|
||||
kAXMainWindowAttribute,
|
||||
)?;
|
||||
AccessibilityApi::window_id(window.as_ref()).ok()
|
||||
}
|
||||
|
||||
pub fn window_by_title(&self, title: &str) -> Option<Window> {
|
||||
let mut target = None;
|
||||
|
||||
|
||||
@@ -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<WindowManagerEvent>, Receiver<WindowManagerEvent>)> =
|
||||
OnceLock::new();
|
||||
|
||||
fn channel() -> &'static (Sender<WindowManagerEvent>, Receiver<WindowManagerEvent>) {
|
||||
CHANNEL.get_or_init(|| crossbeam_channel::bounded(20))
|
||||
}
|
||||
|
||||
pub fn event_tx() -> Sender<WindowManagerEvent> {
|
||||
channel().0.clone()
|
||||
}
|
||||
|
||||
pub fn event_rx() -> Receiver<WindowManagerEvent> {
|
||||
channel().1.clone()
|
||||
}
|
||||
@@ -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<Window>,
|
||||
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<usize> {
|
||||
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<Window> {
|
||||
let window = self.windows_mut().remove(idx);
|
||||
self.focus_window(idx.saturating_sub(1));
|
||||
window
|
||||
}
|
||||
}
|
||||
@@ -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! {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Mutex<WindowManager>>) {
|
||||
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(())
|
||||
}
|
||||
}
|
||||
+33
-14
@@ -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::<CFString>(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!(
|
||||
|
||||
@@ -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<Rect>,
|
||||
pub incoming_events: Receiver<WindowManagerEvent>,
|
||||
pub minimized_windows: HashMap<u32, Window>,
|
||||
}
|
||||
|
||||
impl_ring_elements!(WindowManager, Monitor);
|
||||
@@ -37,6 +42,7 @@ impl_ring_elements!(WindowManager, Monitor);
|
||||
impl WindowManager {
|
||||
pub fn new(
|
||||
run_loop: &CFRetained<CFRunLoop>,
|
||||
incoming: Receiver<WindowManagerEvent>,
|
||||
custom_socket_path: Option<PathBuf>,
|
||||
) -> eyre::Result<Self> {
|
||||
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<Window>,
|
||||
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(())
|
||||
}
|
||||
}
|
||||
@@ -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<u32>),
|
||||
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<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))
|
||||
}
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
-1
@@ -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<usize> {
|
||||
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<Window> {
|
||||
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<Container> {
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user