From a398609071b18af087f77c5ab8659702f860a064 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Mon, 29 Sep 2025 10:35:24 -0700 Subject: [PATCH] refactor(wm): start using gcd dispatch This commit switches from executing things which need a MainThreadMarker in our main loop in main.rs to executing them via Grand Central Dispatch using the dispatch2 crate. All the monitor reconciliator stuff is now much faster. --- Cargo.lock | 3 ++ komorebi/Cargo.toml | 1 + komorebi/src/lib.rs | 9 ----- komorebi/src/main.rs | 33 ----------------- komorebi/src/monitor_reconciliator.rs | 53 ++++++++++++--------------- 5 files changed, 28 insertions(+), 71 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1a0abddb..22f2e922 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -404,6 +404,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec" dependencies = [ "bitflags 2.9.4", + "block2", + "libc", "objc2", ] @@ -1072,6 +1074,7 @@ dependencies = [ "crossbeam-channel", "ctrlc", "dirs", + "dispatch2", "hotwatch", "lazy_static", "nanoid", diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index d7b9b651..c49a9fb2 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -9,6 +9,7 @@ clap = { workspace = true } color-eyre = { workspace = true } crossbeam-channel = "0.5" ctrlc = { version = "3", features = ["termination"] } +dispatch2 = "0.3" dirs = { workspace = true } hotwatch = "0.5" lazy_static = { workspace = true } diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 6c58f538..85bb7068 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -10,7 +10,6 @@ use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; use crate::core::config_generation::WorkspaceMatchingRule; use crate::core_graphics::error::CoreGraphicsError; -use crate::monitor::Monitor; use crate::monitor_reconciliator::MonitorNotification; use crate::state::State; use crate::window::AspectRatio; @@ -42,7 +41,6 @@ use std::panic; use std::path::PathBuf; use std::ptr::NonNull; use std::sync::Arc; -use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicI32; #[macro_use] @@ -109,13 +107,6 @@ lazy_static! { Arc::new(RwLock::new(HashMap::new())); static ref WINDOW_RESTORE_POSITIONS: Arc>> = Arc::new(Mutex::new(HashMap::new())); - pub static ref UPDATE_MONITOR_WORK_AREAS: Arc = Arc::new(AtomicBool::new(false)); - pub static ref UPDATE_LATEST_MONITOR_INFORMATION: Arc = - Arc::new(AtomicBool::new(false)); - pub static ref LOAD_LATEST_MONITOR_INFORMATION: Arc = - Arc::new(AtomicBool::new(false)); - pub static ref LATEST_MONITOR_INFORMATION: Arc>>> = - Arc::new(RwLock::new(None)); static ref WORKSPACE_MATCHING_RULES: Arc>> = Arc::new(Mutex::new(Vec::new())); static ref REGEX_IDENTIFIERS: Arc>> = diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index faa6b574..8ef4e568 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -6,14 +6,9 @@ use color_eyre::eyre; 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; use komorebi::display_reconfiguration_listener::DisplayReconfigurationListener; use komorebi::input_event_listener::InputEventListener; -use komorebi::macos_api::MacosApi; use komorebi::monitor_reconciliator; use komorebi::notification_center_listener::NotificationCenterListener; use komorebi::process_command::listen_for_commands; @@ -294,34 +289,6 @@ fn main() -> eyre::Result<()> { break; } - if UPDATE_MONITOR_WORK_AREAS.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::update_monitor_work_areas(&mut wm) { - tracing::error!("failed to update monitor work areas: {error}"); - } - - UPDATE_MONITOR_WORK_AREAS.store(false, Ordering::Relaxed); - } - } - - if UPDATE_LATEST_MONITOR_INFORMATION.load(Ordering::Relaxed) { - let mut latest_monitor_information = LATEST_MONITOR_INFORMATION.write(); - // this can only be called on the main thread - *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) }); } diff --git a/komorebi/src/monitor_reconciliator.rs b/komorebi/src/monitor_reconciliator.rs index 49f666d2..f407214a 100644 --- a/komorebi/src/monitor_reconciliator.rs +++ b/komorebi/src/monitor_reconciliator.rs @@ -1,18 +1,16 @@ 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; use crate::window_manager::WindowManager; use crossbeam_channel::Receiver; use crossbeam_channel::Sender; +use dispatch2::DispatchQueue; use objc2_core_graphics::CGDirectDisplayID; use parking_lot::Mutex; use serde::Deserialize; @@ -20,7 +18,6 @@ use serde::Serialize; use std::collections::HashMap; use std::sync::Arc; use std::sync::OnceLock; -use std::sync::atomic::Ordering; use strum::Display; #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] @@ -105,34 +102,30 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result match notification { MonitorNotification::Resize(_display_id) => { tracing::debug!("handling resize notification"); - UPDATE_MONITOR_WORK_AREAS.store(true, Ordering::Relaxed); + DispatchQueue::main().exec_sync(|| { + let mut wm = wm.lock(); + if let Err(error) = MacosApi::update_monitor_work_areas(&mut wm) { + tracing::error!("failed to update monitor work areas: {error}"); + } + }); } MonitorNotification::DisplayConnectionChange(_) => { - let mut wm = wm.lock(); tracing::debug!("handling display connection change notification"); + + let mut attached_devices = vec![]; + DispatchQueue::main().exec_sync(|| { + if let Ok(latest) = MacosApi::latest_monitor_information() { + attached_devices = latest.clone(); + } + }); + + let mut wm = wm.lock(); let mut monitor_cache = MONITOR_CACHE .get_or_init(|| Mutex::new(HashMap::new())) .lock(); let initial_monitor_count = wm.monitors().len(); - { - let mut latest_monitor_information = LATEST_MONITOR_INFORMATION.write(); - *latest_monitor_information = None; - UPDATE_LATEST_MONITOR_INFORMATION.store(true, Ordering::Relaxed); - } - - let mut attached_devices = vec![]; - while attached_devices.is_empty() { - if let Some(latest) = &*LATEST_MONITOR_INFORMATION.read() { - attached_devices = latest.clone(); - } - - std::thread::sleep(std::time::Duration::from_millis(100)); - } - - UPDATE_LATEST_MONITOR_INFORMATION.store(false, Ordering::Relaxed); - // 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 { @@ -321,11 +314,13 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result // 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(50)); - tracing::trace!("waiting for latest monitor info to be loaded {}", line!()); - } + + DispatchQueue::main().exec_sync(|| { + let mut wm = arc.lock(); + if let Err(error) = MacosApi::load_monitor_information(&mut wm) { + tracing::error!("failed to update load monitor information: {error}"); + } + }); } // regain the lock here once the monitor information has been updated