feat(wm): add initial skeleton of wm state and initialization

This commit is contained in:
LGUG2Z committed 2025-09-17 09:07:45 -07:00
1 parent a2b0207c28
commit 326c419666
12 files changed
+433 -76

No files matched your search

Generated
+42 -4
View File
@@ -155,6 +155,8 @@ dependencies = [
"objc2-application-services",
"objc2-core-foundation",
"objc2-core-graphics",
"pastey",
"serde",
"thiserror",
"tracing",
"tracing-subscriber",
@@ -421,6 +423,12 @@ version = "4.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48dd4f4a2c8405440fd0462561f0e5806bd0f77e86f51c761481bdd4018b545e"
[[package]]
name = "pastey"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
[[package]]
name = "pin-project-lite"
version = "0.2.16"
@@ -468,6 +476,36 @@ version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace"
[[package]]
name = "serde"
version = "1.0.225"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd6c24dee235d0da097043389623fb913daddf92c76e9f5a1db88607a0bcbd1d"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.225"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "659356f9a0cb1e529b24c01e43ad2bdf520ec4ceaf83047b83ddcc2251f96383"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.225"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ea936adf78b1f766949a4977b91d2f5595825bd6ec079aa9543ad2685fc4516"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "sharded-slab"
version = "0.1.7"
@@ -496,18 +534,18 @@ dependencies = [
[[package]]
name = "thiserror"
version = "1.0.69"
version = "2.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
checksum = "3467d614147380f2e4e374161426ff399c91084acd2363eaf549172b3d5e60c0"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
version = "2.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960"
dependencies = [
"proc-macro2",
"quote",
+8
View File
@@ -37,12 +37,16 @@
"objc2-quartz-core 0.3.1 registry+https://github.com/rust-lang/crates.io-index",
"object 0.36.7 registry+https://github.com/rust-lang/crates.io-index",
"once_cell 1.21.3 registry+https://github.com/rust-lang/crates.io-index",
"pastey 0.1.1 registry+https://github.com/rust-lang/crates.io-index",
"pin-project-lite 0.2.16 registry+https://github.com/rust-lang/crates.io-index",
"proc-macro2 1.0.101 registry+https://github.com/rust-lang/crates.io-index",
"quote 1.0.40 registry+https://github.com/rust-lang/crates.io-index",
"regex-automata 0.4.10 registry+https://github.com/rust-lang/crates.io-index",
"regex-syntax 0.8.6 registry+https://github.com/rust-lang/crates.io-index",
"rustc-demangle 0.1.26 registry+https://github.com/rust-lang/crates.io-index",
"serde 1.0.225 registry+https://github.com/rust-lang/crates.io-index",
"serde_core 1.0.225 registry+https://github.com/rust-lang/crates.io-index",
"serde_derive 1.0.225 registry+https://github.com/rust-lang/crates.io-index",
"smallvec 1.15.1 registry+https://github.com/rust-lang/crates.io-index",
"syn 2.0.106 registry+https://github.com/rust-lang/crates.io-index",
"thiserror 1.0.69 registry+https://github.com/rust-lang/crates.io-index",
@@ -93,12 +97,16 @@
"object 0.36.7 registry+https://github.com/rust-lang/crates.io-index",
"once_cell 1.21.3 registry+https://github.com/rust-lang/crates.io-index",
"owo-colors 4.2.2 registry+https://github.com/rust-lang/crates.io-index",
"pastey 0.1.1 registry+https://github.com/rust-lang/crates.io-index",
"pin-project-lite 0.2.16 registry+https://github.com/rust-lang/crates.io-index",
"proc-macro2 1.0.101 registry+https://github.com/rust-lang/crates.io-index",
"quote 1.0.40 registry+https://github.com/rust-lang/crates.io-index",
"regex-automata 0.4.10 registry+https://github.com/rust-lang/crates.io-index",
"regex-syntax 0.8.6 registry+https://github.com/rust-lang/crates.io-index",
"rustc-demangle 0.1.26 registry+https://github.com/rust-lang/crates.io-index",
"serde 1.0.225 registry+https://github.com/rust-lang/crates.io-index",
"serde_core 1.0.225 registry+https://github.com/rust-lang/crates.io-index",
"serde_derive 1.0.225 registry+https://github.com/rust-lang/crates.io-index",
"sharded-slab 0.1.7 registry+https://github.com/rust-lang/crates.io-index",
"smallvec 1.15.1 registry+https://github.com/rust-lang/crates.io-index",
"syn 2.0.106 registry+https://github.com/rust-lang/crates.io-index",
+3 -1
View File
@@ -11,6 +11,8 @@ objc2-app-kit = "0.3"
objc2-application-services = "0.3"
objc2-core-foundation = { version = "0.3", features = ["CFDictionary", "CFString"] }
objc2-core-graphics = { version = "0.3", features = ["CGWindow", "alloc"] }
thiserror = "1"
pastey = "0.1"
serde = { version = "1", features = ["derive"]}
thiserror = "2"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+2 -2
View File
@@ -3,9 +3,9 @@ use objc2_application_services::AXError;
#[derive(thiserror::Error, Debug)]
pub enum AccessibilityError {
#[error(transparent)]
Api(AccessibilityApiError),
Api(#[from] AccessibilityApiError),
#[error(transparent)]
Custom(AccessibilityCustomError),
Custom(#[from] AccessibilityCustomError),
}
#[derive(thiserror::Error, Debug)]
+11
View File
@@ -1,7 +1,10 @@
use crate::core_graphics::error::CoreGraphicsError;
use objc2_core_foundation::CFArray;
use objc2_core_foundation::CFRetained;
use objc2_core_foundation::CGRect;
use objc2_core_graphics::CGDisplayBounds;
use objc2_core_graphics::CGGetOnlineDisplayList;
use objc2_core_graphics::CGRectIntersectsRect;
use objc2_core_graphics::CGWindowListCopyWindowInfo;
use objc2_core_graphics::CGWindowListOption;
use objc2_core_graphics::kCGNullWindowID;
@@ -11,6 +14,10 @@ pub mod error;
pub struct CoreGraphicsApi;
impl CoreGraphicsApi {
pub fn contains_rect(smaller: CGRect, bigger: CGRect) -> bool {
unsafe { CGRectIntersectsRect(smaller, bigger) }
}
pub fn connected_display_ids() -> Result<Vec<u32>, CoreGraphicsError> {
let mut displays: Vec<u32> = Vec::with_capacity(16);
let mut display_count = 0;
@@ -30,6 +37,10 @@ impl CoreGraphicsApi {
}
}
pub fn display_bounds(display_id: u32) -> CGRect {
unsafe { CGDisplayBounds(display_id) }
}
pub fn window_list_info() -> Option<CFRetained<CFArray>> {
unsafe {
CGWindowListCopyWindowInfo(
+15
View File
@@ -1,16 +1,23 @@
#![warn(clippy::all)]
use crate::accessibility::error::AccessibilityError;
use crate::core_graphics::error::CoreGraphicsError;
use objc2_core_foundation::CFArray;
use objc2_core_foundation::CFDictionary;
use objc2_core_foundation::CFString;
use std::ptr::NonNull;
#[macro_use]
pub mod ring;
pub mod accessibility;
pub mod application;
pub mod core_graphics;
pub mod layout;
pub mod macos_api;
pub mod rect;
pub mod window;
pub mod window_manager;
pub fn cf_array_as<T>(array: &CFArray) -> impl Iterator<Item = NonNull<T>> + use<'_, T> {
let count = CFArray::count(array);
@@ -24,3 +31,11 @@ pub fn cf_dictionary_value<T>(dict: &CFDictionary, key: &CFString) -> Option<Non
let ptr = unsafe { CFDictionary::value(dict, NonNull::from(key).as_ptr().cast()) };
NonNull::new(ptr.cast_mut()).map(|ptr| ptr.cast::<T>())
}
#[derive(thiserror::Error, Debug)]
pub enum LibraryError {
#[error(transparent)]
Accessibility(#[from] AccessibilityError),
#[error(transparent)]
CoreGraphics(#[from] CoreGraphicsError),
}
+94
View File
@@ -0,0 +1,94 @@
use crate::LibraryError;
use crate::application::Application;
use crate::cf_array_as;
use crate::core_graphics::CoreGraphicsApi;
use crate::rect::Rect;
use crate::ring::Ring;
use crate::window::WindowInfo;
use crate::window_manager::Container;
use crate::window_manager::Monitor;
use crate::window_manager::WindowManager;
use objc2_core_foundation::CFDictionary;
use std::collections::HashMap;
pub struct MacosApi;
impl MacosApi {
pub fn load_monitor_information(wm: &mut WindowManager) -> Result<(), LibraryError> {
for display_id in CoreGraphicsApi::connected_display_ids()? {
let size = Rect::from(CoreGraphicsApi::display_bounds(display_id));
let monitor = Monitor::new(display_id, size);
wm.monitors.elements_mut().push_back(monitor);
}
Ok(())
}
pub fn load_workspace_information(wm: &mut WindowManager) -> Result<(), LibraryError> {
let mut monitor_size_map = HashMap::new();
let mut monitor_workspace_map = HashMap::new();
let mut monitor_window_map = HashMap::new();
let mut valid_window_count = 0;
for (idx, monitor) in wm.monitors.elements_mut().iter_mut().enumerate() {
monitor_size_map.insert(idx, monitor.size);
monitor_workspace_map.insert(idx, monitor.focused_workspace_mut());
}
if let Some(window_list_info) = CoreGraphicsApi::window_list_info() {
tracing::info!("{} windows found", window_list_info.len());
for raw_window_info in cf_array_as::<CFDictionary>(&window_list_info) {
if let Some(info) = WindowInfo::new(raw_window_info).validated() {
let window_rect = Rect::from(info.bounds);
for (monitor_idx, monitor_size) in &monitor_size_map {
if monitor_size.contains(&window_rect) {
let entry = monitor_window_map
.entry(monitor_idx)
.or_insert_with(Vec::new);
let application =
wm.applications.entry(info.owner_pid).or_insert_with(|| {
let application = Application::new(info.owner_pid)
.unwrap_or_else(|_| {
panic!(
"failed to create application from pid {}",
info.owner_pid
)
});
application
.observe(&wm.run_loop)
.expect("application must be observable");
application
});
if let Some(window) = application.window_by_title(&info.name) {
window.observe(&wm.run_loop)?;
entry.push(window);
valid_window_count += 1
}
}
}
}
}
tracing::info!("{valid_window_count} valid windows identified");
}
for (monitor_idx, windows) in monitor_window_map {
for window in windows {
let mut container = Container {
windows: Ring::default(),
};
container.windows_mut().push_back(window);
if let Some(Some(workspace)) = monitor_workspace_map.get_mut(monitor_idx) {
workspace.containers_mut().push_back(container);
}
}
}
Ok(())
}
}
+43 -62
View File
@@ -2,22 +2,17 @@
use color_eyre::eyre;
use color_eyre::eyre::eyre;
use komorebi::application::Application;
use komorebi::cf_array_as;
use komorebi::core_graphics::CoreGraphicsApi;
use komorebi::layout;
use komorebi::rect::Rect;
use komorebi::window::WindowInfo;
use komorebi::window_manager::WindowManager;
use objc2::rc::autoreleasepool;
use objc2_application_services::AXIsProcessTrusted;
use objc2_core_foundation::CFDictionary;
use objc2_core_foundation::CFRunLoop;
use objc2_core_foundation::kCFRunLoopDefaultMode;
use objc2_core_graphics::CGDisplayBounds;
use objc2_core_graphics::CGMainDisplayID;
use objc2_core_graphics::CGPreflightScreenCaptureAccess;
use objc2_core_graphics::CGRequestScreenCaptureAccess;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
@@ -101,38 +96,27 @@ 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 mut wm = WindowManager::new(&run_loop);
wm.init()?;
if let Some(window_info_list) = CoreGraphicsApi::window_list_info() {
tracing::info!("{} windows found", window_info_list.len());
let containers = wm
.monitors
.focused()
.expect("must have a monitor at this point")
.focused_workspace()
.expect("must have a workspace at this point")
.containers();
let mut windows = vec![];
let mut applications = HashMap::new();
let layouts =
layout::recursive_fibonacci(0, containers.len(), &Rect::from(display_size), vec![]);
for entry in cf_array_as::<CFDictionary>(window_info_list.as_ref()) {
if let Some(info) = WindowInfo::new(entry).validated() {
let application = applications.entry(info.owner_pid).or_insert_with(|| {
let application = Application::new(info.owner_pid).unwrap_or_else(|_| {
panic!("failed to create application from pid {}", info.owner_pid)
});
application
.observe(&run_loop)
.expect("application must be observable");
application
});
if let Some(window) = application.window_by_title(&info.name) {
window.observe(&run_loop)?;
windows.push(window);
}
}
}
tracing::info!("{} valid windows identified", windows.len());
let layouts =
layout::recursive_fibonacci(0, windows.len(), &Rect::from(display_size), vec![]);
windows.iter().zip(layouts).for_each(|(window, layout)| {
containers
.iter()
.zip(layouts)
.for_each(|(container, layout)| {
let window = container
.focused_window()
.expect("must have a window at this point");
if let Err(error) = window.set_position(&layout) {
tracing::error!(
"failed to position window: {} ({error})",
@@ -167,39 +151,36 @@ fn main() -> eyre::Result<()> {
// }
});
let quit_ctrlc = Arc::new(AtomicBool::new(false));
let quit_thread = quit_ctrlc.clone();
let quit_ctrlc = Arc::new(AtomicBool::new(false));
let quit_thread = quit_ctrlc.clone();
std::thread::spawn(move || {
let (ctrlc_sender, ctrlc_receiver) = mpsc::channel();
ctrlc::set_handler(move || {
ctrlc_sender
.send(())
.expect("could not send signal on ctrl-c channel");
})
.expect("could not set ctrl-c handler");
std::thread::spawn(move || {
let (ctrlc_sender, ctrlc_receiver) = mpsc::channel();
ctrlc::set_handler(move || {
ctrlc_sender
.send(())
.expect("could not send signal on ctrl-c channel");
})
.expect("could not set ctrl-c handler");
ctrlc_receiver
.recv()
.expect("could not receive signal on ctrl-c channel");
ctrlc_receiver
.recv()
.expect("could not receive signal on ctrl-c channel");
tracing::info!("ctrl-c signal received");
quit_ctrlc.store(true, Ordering::Relaxed);
});
tracing::info!("ctrl-c signal received");
quit_ctrlc.store(true, Ordering::Relaxed);
});
tracing::info!("starting CFRunLoop to receive observer notifications");
tracing::info!("starting CFRunLoop to receive observer notifications");
loop {
if quit_thread.load(Ordering::Relaxed) {
tracing::info!("stopping CFRunLoop");
break;
}
// this gets our observer notification callbacks firing
autoreleasepool(|_| unsafe {
CFRunLoop::run_in_mode(kCFRunLoopDefaultMode, 2.0, false)
});
loop {
if quit_thread.load(Ordering::Relaxed) {
tracing::info!("stopping CFRunLoop");
break;
}
// this gets our observer notification callbacks firing
autoreleasepool(|_| unsafe { CFRunLoop::run_in_mode(kCFRunLoopDefaultMode, 2.0, false) });
}
Ok(())
+36
View File
@@ -1,3 +1,7 @@
use crate::core_graphics::CoreGraphicsApi;
use crate::window::WindowBounds;
use objc2_core_foundation::CGFloat;
use objc2_core_foundation::CGPoint;
use objc2_core_foundation::CGRect;
use objc2_core_foundation::CGSize;
@@ -30,3 +34,35 @@ impl From<CGRect> for Rect {
}
}
}
impl From<&Rect> for CGRect {
fn from(value: &Rect) -> Self {
Self {
origin: CGPoint {
x: value.left as CGFloat,
y: value.top as CGFloat,
},
size: CGSize {
width: value.right as CGFloat,
height: value.bottom as CGFloat,
},
}
}
}
impl From<WindowBounds> for Rect {
fn from(value: WindowBounds) -> Self {
Self {
left: value.x,
top: value.y,
right: value.width,
bottom: value.height,
}
}
}
impl Rect {
pub fn contains(&self, other: &Rect) -> bool {
CoreGraphicsApi::contains_rect(other.into(), self.into())
}
}
+106
View File
@@ -0,0 +1,106 @@
use std::collections::VecDeque;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Ring<T> {
elements: VecDeque<T>,
focused: usize,
}
impl<T> Default for Ring<T> {
fn default() -> Self {
Self {
elements: VecDeque::default(),
focused: 0,
}
}
}
impl<T> Ring<T> {
pub const fn elements(&self) -> &VecDeque<T> {
&self.elements
}
pub fn elements_mut(&mut self) -> &mut VecDeque<T> {
&mut self.elements
}
pub fn focus(&mut self, idx: usize) {
self.focused = idx;
}
pub fn focused(&self) -> Option<&T> {
self.elements.get(self.focused)
}
pub const fn focused_idx(&self) -> usize {
self.focused
}
pub fn focused_mut(&mut self) -> Option<&mut T> {
self.elements.get_mut(self.focused)
}
}
macro_rules! impl_ring_elements {
($name:ty, $element:ident) => {
pastey::paste! {
impl $name {
pub const fn [<$element:lower s>](&self) -> &std::collections::VecDeque<$element> {
self.[<$element:lower s>].elements()
}
pub fn [<$element:lower s_mut>](&mut self) -> &mut std::collections::VecDeque<$element> {
self.[<$element:lower s>].elements_mut()
}
#[allow(dead_code)]
pub fn [<focused_ $element:lower>](&self) -> Option<&$element> {
self.[<$element:lower s>].focused()
}
pub const fn [<focused_ $element:lower _idx>](&self) -> usize {
self.[<$element:lower s>].focused_idx()
}
pub fn [<focused_ $element:lower _mut>](&mut self) -> Option<&mut $element> {
self.[<$element:lower s>].focused_mut()
}
}
}
};
// This allows passing a different name to be used for the functions. For instance, the
// `floating_windows` ring calls this as:
// ```rust
// impl_ring_elements!(Workspace, Window, "floating_window");
// ```
// Which allows using the `Window` element but name the functions as `floating_window`
($name:ty, $element:ident, $el_name:literal) => {
pastey::paste! {
impl $name {
pub const fn [<$el_name:lower s>](&self) -> &std::collections::VecDeque<$element> {
self.[<$el_name:lower s>].elements()
}
pub fn [<$el_name:lower s_mut>](&mut self) -> &mut std::collections::VecDeque<$element> {
self.[<$el_name:lower s>].elements_mut()
}
#[allow(dead_code)]
pub fn [<focused_ $el_name:lower>](&self) -> Option<&$element> {
self.[<$el_name:lower s>].focused()
}
pub const fn [<focused_ $el_name:lower _idx>](&self) -> usize {
self.[<$el_name:lower s>].focused_idx()
}
pub fn [<focused_ $el_name:lower _mut>](&mut self) -> Option<&mut $element> {
self.[<$el_name:lower s>].focused_mut()
}
}
}
};
}
+7 -7
View File
@@ -95,7 +95,7 @@ pub struct ValidWindowInfo {
pub owner_pid: i32,
owner_name: String,
alpha: f32,
bounds: WindowBounds,
pub bounds: WindowBounds,
}
impl WindowInfo {
@@ -247,13 +247,13 @@ impl From<&CFDictionary> for WindowInfo {
}
}
#[derive(Default, Debug)]
#[derive(Default, Debug, Copy, Clone)]
#[allow(unused)]
struct WindowBounds {
height: f32,
width: f32,
x: f32,
y: f32,
pub struct WindowBounds {
pub height: f32,
pub width: f32,
pub x: f32,
pub y: f32,
}
impl From<&CFDictionary> for WindowBounds {
+66
View File
@@ -0,0 +1,66 @@
use crate::LibraryError;
use crate::application::Application;
use crate::macos_api::MacosApi;
use crate::rect::Rect;
use crate::ring::Ring;
use crate::window::Window;
use objc2_core_foundation::CFRetained;
use objc2_core_foundation::CFRunLoop;
use std::collections::HashMap;
#[derive(Debug)]
pub struct WindowManager {
pub monitors: Ring<Monitor>,
pub applications: HashMap<i32, Application>,
pub run_loop: CFRetained<CFRunLoop>,
}
impl WindowManager {
pub fn new(run_loop: &CFRetained<CFRunLoop>) -> Self {
Self {
monitors: Ring::default(),
applications: Default::default(),
run_loop: run_loop.clone(),
}
}
#[tracing::instrument(skip(self))]
pub fn init(&mut self) -> Result<(), LibraryError> {
tracing::info!("initializing");
MacosApi::load_monitor_information(self)?;
MacosApi::load_workspace_information(self)
}
}
impl_ring_elements!(Monitor, Workspace);
#[derive(Debug)]
pub struct Monitor {
pub id: u32,
pub workspaces: Ring<Workspace>,
pub size: Rect,
}
impl Monitor {
pub fn new(id: u32, size: Rect) -> Self {
let mut workspaces = Ring::default();
workspaces.elements_mut().push_back(Workspace::default());
Self {
id,
workspaces,
size,
}
}
}
impl_ring_elements!(Workspace, Container);
#[derive(Debug, Default)]
pub struct Workspace {
pub containers: Ring<Container>,
}
impl_ring_elements!(Container, Window);
#[derive(Debug)]
pub struct Container {
pub windows: Ring<Window>,
}