fix(wm): use absolute monitor sizes and fix deadlock

This commit switches to using absolute intead of relative monitor sizes,
I don't fully understand by the NS APIs and the CG APIs return totally
different coordinate systems.

There was also a deadlock in the monitor reconciliator which I think I
figured out; it's a little ugly both in code and in execution but the
deadlocks and pkill -9s can be put away from now.

Cross-monitor moves aren't working which I'll look into next.
This commit is contained in:
LGUG2Z committed 2025-09-26 09:53:37 -07:00
1 parent f7afe4f8ec
commit fa6ce669f7
7 files changed
+213 -113

No files matched your search

Generated
+29
View File
@@ -492,6 +492,12 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ced73b1dacfc750a6db6c0a0c3a3853c8b41997e2e2c563dc90804ae6867959"
[[package]]
name = "fixedbitset"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "fnv"
version = "1.0.7"
@@ -1671,10 +1677,13 @@ version = "0.9.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5"
dependencies = [
"backtrace",
"cfg-if",
"libc",
"petgraph",
"redox_syscall",
"smallvec",
"thread-id",
"windows-targets 0.52.6",
]
@@ -1690,6 +1699,16 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "petgraph"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"
dependencies = [
"fixedbitset",
"indexmap 2.11.4",
]
[[package]]
name = "pin-project-lite"
version = "0.2.16"
@@ -2430,6 +2449,16 @@ dependencies = [
"syn",
]
[[package]]
name = "thread-id"
version = "4.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe8f25bbdd100db7e1d34acf7fd2dc59c4bf8f7483f505eaa7d4f12f76cc0ea"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "thread_local"
version = "1.1.9"
+3
View File
@@ -39,6 +39,9 @@ debug target $RUST_LOG="debug":
trace target $RUST_LOG="trace":
just run {{ target }}
deadlock $RUST_LOG="trace":
cargo +stable run --bin komorebi --locked --no-default-features --features deadlock_detection
depgen:
cargo deny check
cargo deny list --format json | jq 'del(.unlicensed)' > dependencies.json
+1
View File
@@ -42,4 +42,5 @@ shadow-rs = { workspace = true }
[features]
default = ["schemars"]
deadlock_detection = ["parking_lot/deadlock_detection"]
schemars = ["dep:schemars"]
+2
View File
@@ -103,6 +103,8 @@ lazy_static! {
pub static ref UPDATE_MONITOR_WORK_AREAS: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
pub static ref UPDATE_LATEST_MONITOR_INFORMATION: Arc<AtomicBool> =
Arc::new(AtomicBool::new(false));
pub static ref LOAD_LATEST_MONITOR_INFORMATION: Arc<AtomicBool> =
Arc::new(AtomicBool::new(false));
pub static ref LATEST_MONITOR_INFORMATION: Arc<RwLock<Option<Vec<Monitor>>>> =
Arc::new(RwLock::new(None));
static ref WORKSPACE_MATCHING_RULES: Arc<Mutex<Vec<WorkspaceMatchingRule>>> =
+95 -92
View File
@@ -14,10 +14,12 @@ use crate::core::rect::Rect;
use crate::core_graphics::CoreGraphicsApi;
use crate::ioreg::IoReg;
use crate::monitor::Monitor;
use crate::monitor::MonitorInfo;
use crate::window::WindowInfo;
use crate::window_manager::WindowManager;
use color_eyre::eyre;
use objc2::MainThreadMarker;
use objc2_app_kit::NSDeviceDescriptionKey;
use objc2_app_kit::NSEvent;
use objc2_app_kit::NSScreen;
use objc2_application_services::AXUIElement;
@@ -28,6 +30,9 @@ use objc2_core_foundation::CFRetained;
use objc2_core_foundation::CFString;
use objc2_core_foundation::CGPoint;
use objc2_core_foundation::CGRect;
use objc2_core_foundation::CGSize;
use objc2_core_graphics::CGMainDisplayID;
use objc2_foundation::NSNumber;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
@@ -40,50 +45,11 @@ pub struct MacosApi;
impl MacosApi {
#[tracing::instrument(skip_all)]
pub fn load_monitor_information(wm: &mut WindowManager) -> Result<(), LibraryError> {
let all_devices = Self::latest_monitor_information()?;
let monitors = &mut wm.monitors;
let monitor_usr_idx_map = &mut wm.monitor_usr_idx_map;
let monitor_info = IoReg::query_monitors()?;
let mut monitor_info_map = HashMap::new();
for m in monitor_info {
monitor_info_map.insert(m.serial_number, m);
}
let mut all_devices = vec![];
let screens = NSScreen::screens(MainThreadMarker::new().unwrap());
for display_id in CoreGraphicsApi::connected_display_ids()? {
let display_bounds = CoreGraphicsApi::display_bounds(display_id);
let serial_number = CoreGraphicsApi::display_serial_number(display_id);
if let Some(info) = monitor_info_map.get(&serial_number) {
for screen in &screens {
let menu_bar_height = screen.frame().size.height
- screen.visibleFrame().size.height
- screen.visibleFrame().origin.y;
if screen.frame() == display_bounds {
let size = Rect::from(display_bounds);
let mut work_area_size = Rect::from(display_bounds);
work_area_size.top += menu_bar_height as i32;
work_area_size.bottom = screen.visibleFrame().size.height as i32;
let monitor = Monitor::new(
display_id,
size,
work_area_size,
&info.product_name,
&info.alphanumeric_serial_number,
);
all_devices.push(monitor);
}
}
}
}
'read: for device in all_devices {
for monitor in monitors.elements() {
if device.serial_number_id.eq(&monitor.serial_number_id) {
@@ -164,36 +130,19 @@ impl MacosApi {
Ok(())
}
pub fn update_monitor_work_areas(wm: Arc<Mutex<WindowManager>>) -> eyre::Result<()> {
let screens = NSScreen::screens(MainThreadMarker::new().unwrap());
for display_id in CoreGraphicsApi::connected_display_ids()? {
let display_bounds = CoreGraphicsApi::display_bounds(display_id);
let mut wm = wm.lock();
for screen in &screens {
let menu_bar_height = screen.frame().size.height
- screen.visibleFrame().size.height
- screen.visibleFrame().origin.y;
if screen.frame() == display_bounds {
let size = Rect::from(display_bounds);
let mut work_area_size = Rect::from(display_bounds);
work_area_size.top += menu_bar_height as i32;
work_area_size.bottom = screen.visibleFrame().size.height as i32;
for monitor in wm.monitors_mut() {
if monitor.id == display_id {
monitor.size = size;
monitor.work_area_size = work_area_size;
}
tracing::info!(
"updated monitor size and work area for monitor {display_id}"
)
}
pub fn update_monitor_work_areas(wm: &mut WindowManager) -> eyre::Result<()> {
let all_devices = Self::latest_monitor_information()?;
for device in all_devices {
for monitor in wm.monitors_mut() {
if monitor.id == device.id {
monitor.size = device.size;
monitor.work_area_size = device.work_area_size;
}
tracing::info!(
"updated monitor size and work area for monitor {}",
monitor.serial_number_id
);
}
let focus_follows_mouse = wm.mouse_follows_focus;
@@ -204,47 +153,102 @@ impl MacosApi {
}
pub fn latest_monitor_information() -> Result<Vec<Monitor>, LibraryError> {
let mut monitors = vec![];
let screens = NSScreen::screens(MainThreadMarker::new().unwrap());
let mut network_attached_screens = vec![];
for display_id in CoreGraphicsApi::connected_display_ids()? {
let serial_number = CoreGraphicsApi::display_serial_number(display_id);
network_attached_screens.push((serial_number, display_id));
}
let monitor_info = IoReg::query_monitors()?;
let mut monitor_info_map = HashMap::new();
for m in monitor_info {
monitor_info_map.insert(m.serial_number, m);
}
let screens = NSScreen::screens(MainThreadMarker::new().unwrap());
// total hackery for iPad second screen stuff over the network
for info in monitor_info_map.values() {
network_attached_screens
.retain(|(serial_number, _)| serial_number != &info.serial_number);
}
for (serial_number, display_id) in network_attached_screens {
for screen in &screens {
if let Some(did) = screen
.deviceDescription()
.objectForKey(&NSDeviceDescriptionKey::from_str("NSScreenNumber"))
&& let Ok(did) = did.downcast::<NSNumber>()
&& did.as_u32() == display_id
{
monitor_info_map.insert(
serial_number,
MonitorInfo {
alphanumeric_serial_number: serial_number.to_string(),
manufacturer_id: "".to_string(),
product_name: unsafe { screen.localizedName() }.to_string(),
legacy_manufacturer_id: "".to_string(),
product_id: "".to_string(),
serial_number,
week_of_manufacture: "".to_string(),
year_of_manufacture: "".to_string(),
},
);
}
}
}
let mut all_devices = vec![];
for display_id in CoreGraphicsApi::connected_display_ids()? {
let display_bounds = CoreGraphicsApi::display_bounds(display_id);
let serial_number = CoreGraphicsApi::display_serial_number(display_id);
if let Some(info) = monitor_info_map.get(&serial_number) {
for screen in &screens {
let menu_bar_height = screen.frame().size.height
- screen.visibleFrame().size.height
- screen.visibleFrame().origin.y;
if let Some(did) = screen
.deviceDescription()
.objectForKey(&NSDeviceDescriptionKey::from_str("NSScreenNumber"))
{
let display_bounds = CoreGraphicsApi::display_bounds(display_id);
if let Ok(did) = did.downcast::<NSNumber>()
&& did.as_u32() == display_id
{
let size = Rect::from(display_bounds);
if screen.frame() == display_bounds {
let size = Rect::from(display_bounds);
let mut work_area_size = Rect::from(display_bounds);
work_area_size.top += menu_bar_height as i32;
work_area_size.bottom = screen.visibleFrame().size.height as i32;
let visible_frame = screen.visibleFrame();
let primary_display_height =
CoreGraphicsApi::display_bounds(unsafe { CGMainDisplayID() })
.size
.height;
let monitor = Monitor::new(
display_id,
size,
work_area_size,
&info.product_name,
&info.alphanumeric_serial_number,
);
let quartz_visible_frame = CGRect::new(
CGPoint::new(
visible_frame.origin.x,
primary_display_height
- visible_frame.origin.y
- visible_frame.size.height,
),
CGSize::new(visible_frame.size.width, visible_frame.size.height),
);
monitors.push(monitor);
let work_area_size = Rect::from(quartz_visible_frame);
let monitor = Monitor::new(
display_id,
size,
work_area_size,
&info.product_name,
&info.alphanumeric_serial_number,
);
all_devices.push(monitor);
}
}
}
}
}
Ok(monitors)
Ok(all_devices)
}
pub fn reconile_monitors(wm: Arc<Mutex<WindowManager>>) -> eyre::Result<()> {
@@ -252,7 +256,6 @@ impl MacosApi {
for display_id in CoreGraphicsApi::connected_display_ids()? {
let display_bounds = CoreGraphicsApi::display_bounds(display_id);
let mut wm = wm.lock();
for screen in &screens {
+46 -4
View File
@@ -7,6 +7,7 @@ use color_eyre::eyre::OptionExt;
use komorebi::DATA_DIR;
use komorebi::HOME_DIR;
use komorebi::LATEST_MONITOR_INFORMATION;
use komorebi::LOAD_LATEST_MONITOR_INFORMATION;
use komorebi::UPDATE_LATEST_MONITOR_INFORMATION;
use komorebi::UPDATE_MONITOR_WORK_AREAS;
use komorebi::core::pathext::replace_env_in_path;
@@ -138,6 +139,31 @@ fn setup(log_level: LogLevel) -> eyre::Result<(WorkerGuard, WorkerGuard)> {
Ok((guard, color_guard))
}
#[cfg(feature = "deadlock_detection")]
#[tracing::instrument]
fn detect_deadlocks() {
// Create a background thread which checks for deadlocks every 10s
std::thread::spawn(move || {
loop {
tracing::info!("running deadlock detector");
std::thread::sleep(std::time::Duration::from_secs(5));
let deadlocks = parking_lot::deadlock::check_deadlock();
if deadlocks.is_empty() {
continue;
}
tracing::error!("{} deadlocks detected", deadlocks.len());
for (i, threads) in deadlocks.iter().enumerate() {
tracing::error!("deadlock #{}", i);
for t in threads {
tracing::error!("thread id: {:#?}", t.thread_id());
tracing::error!("{:#?}", t.backtrace());
}
}
}
});
}
#[derive(Default, Deserialize, ValueEnum, Clone)]
#[serde(rename_all = "snake_case")]
enum LogLevel {
@@ -197,6 +223,9 @@ fn main() -> eyre::Result<()> {
let run_loop = CFRunLoop::current().ok_or_eyre("couldn't get CFRunLoop::current")?;
let _input_listener = InputEventListener::init(&run_loop);
#[cfg(feature = "deadlock_detection")]
detect_deadlocks();
let static_config = opts.config.map_or_else(
|| {
let komorebi_json = HOME_DIR.join("komorebi.json");
@@ -272,11 +301,13 @@ fn main() -> eyre::Result<()> {
if UPDATE_MONITOR_WORK_AREAS.load(Ordering::Relaxed) {
// this can only be called on the main thread
if let Err(error) = MacosApi::update_monitor_work_areas(wm.clone()) {
tracing::error!("failed to update montior work areas: {error}");
}
if let Some(mut wm) = wm.try_lock() {
if let Err(error) = MacosApi::update_monitor_work_areas(&mut wm) {
tracing::error!("failed to update monitor work areas: {error}");
}
UPDATE_MONITOR_WORK_AREAS.store(false, Ordering::Relaxed);
UPDATE_MONITOR_WORK_AREAS.store(false, Ordering::Relaxed);
}
}
if UPDATE_LATEST_MONITOR_INFORMATION.load(Ordering::Relaxed) {
@@ -285,6 +316,17 @@ fn main() -> eyre::Result<()> {
*latest_monitor_information = Some(MacosApi::latest_monitor_information()?);
}
if LOAD_LATEST_MONITOR_INFORMATION.load(Ordering::Relaxed) {
// this can only be called on the main thread
if let Some(mut wm) = wm.try_lock() {
if let Err(error) = MacosApi::load_monitor_information(&mut wm) {
tracing::error!("failed to update load monitor information: {error}");
}
LOAD_LATEST_MONITOR_INFORMATION.store(false, Ordering::Relaxed);
}
}
// this gets our observer notification callbacks firing
autoreleasepool(|_| unsafe { CFRunLoop::run_in_mode(kCFRunLoopDefaultMode, 2.0, false) });
}
+37 -17
View File
@@ -1,11 +1,12 @@
use crate::DISPLAY_INDEX_PREFERENCES;
use crate::LATEST_MONITOR_INFORMATION;
use crate::LOAD_LATEST_MONITOR_INFORMATION;
use crate::Notification;
use crate::NotificationEvent;
use crate::UPDATE_LATEST_MONITOR_INFORMATION;
use crate::UPDATE_MONITOR_WORK_AREAS;
use crate::WORKSPACE_MATCHING_RULES;
use crate::core::config_generation::WorkspaceMatchingRule;
use crate::macos_api::MacosApi;
use crate::monitor::Monitor;
use crate::notify_subscribers;
use crate::state::State;
@@ -91,13 +92,15 @@ pub fn listen_for_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Re
pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result<()> {
tracing::info!("listening");
let arc = wm.clone();
let receiver = event_rx();
'receiver: for notification in receiver {
let mut wm = wm.lock();
let initial_state = State::from(wm.as_ref());
let initial_state = {
let wm = wm.lock();
State::from(wm.as_ref())
};
match notification {
MonitorNotification::Resize(_display_id) => {
@@ -105,6 +108,7 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result
UPDATE_MONITOR_WORK_AREAS.store(true, Ordering::Relaxed);
}
MonitorNotification::DisplayConnectionChange(_) => {
let mut wm = wm.lock();
tracing::debug!("handling display connection change notification");
let mut monitor_cache = MONITOR_CACHE
.get_or_init(|| Mutex::new(HashMap::new()))
@@ -116,10 +120,12 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result
// TODO: I think because of the way the threading model works on macOS we'll
// need to run this on the main thread to get access to info from NSScreen
// let attached_devices = attached_display_devices(display_provider)?;
let mut latest_monitor_information = LATEST_MONITOR_INFORMATION.write();
*latest_monitor_information = None;
{
let mut latest_monitor_information = LATEST_MONITOR_INFORMATION.write();
*latest_monitor_information = None;
}
UPDATE_MONITOR_WORK_AREAS.store(true, Ordering::Relaxed);
UPDATE_LATEST_MONITOR_INFORMATION.store(true, Ordering::Relaxed);
let mut attached_devices = vec![];
while attached_devices.is_empty() {
@@ -130,9 +136,9 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result
std::thread::sleep(std::time::Duration::from_millis(100));
}
UPDATE_MONITOR_WORK_AREAS.store(false, Ordering::Relaxed);
UPDATE_LATEST_MONITOR_INFORMATION.store(false, Ordering::Relaxed);
// Make sure that in our state any attached displays have the latest Win32 data
// Make sure that in our state any attached displays have the latest macOS API data
for monitor in wm.monitors_mut() {
for attached in &attached_devices {
// let serial_number_ids_match = if let (Some(attached_snid), Some(m_snid)) =
@@ -326,7 +332,18 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result
// // Check for and add any new monitors that may have been plugged in
// // Monitor and display index preferences get applied in this function
MacosApi::load_monitor_information(&mut wm)?;
// MacosApi::load_monitor_information(&mut wm)?;
// need to drop here because the main thread needs the lock to load the latest
// monitor info into the wm state
drop(wm);
LOAD_LATEST_MONITOR_INFORMATION.store(true, Ordering::Relaxed);
while LOAD_LATEST_MONITOR_INFORMATION.load(Ordering::Relaxed) {
std::thread::sleep(std::time::Duration::from_millis(100));
tracing::trace!("waiting for latest monitor info to be loaded {}", line!());
}
let mut wm = arc.lock();
let post_addition_monitor_count = wm.monitors().len();
@@ -548,13 +565,16 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result
}
}
notify_subscribers(
Notification {
event: NotificationEvent::Monitor(notification),
state: wm.as_ref().into(),
},
initial_state.has_been_modified(&wm),
)?;
{
let wm = wm.lock();
notify_subscribers(
Notification {
event: NotificationEvent::Monitor(notification),
state: wm.as_ref().into(),
},
initial_state.has_been_modified(&wm),
)?;
}
}
Ok(())