diff --git a/komorebi/src/display_reconfiguration_listener.rs b/komorebi/src/display_reconfiguration_listener.rs index 0683f2d3..0056d3a5 100644 --- a/komorebi/src/display_reconfiguration_listener.rs +++ b/komorebi/src/display_reconfiguration_listener.rs @@ -18,19 +18,45 @@ unsafe extern "C-unwind" fn callback( tracing::debug!("display: {display_id} resized"); monitor_reconciliator::send_notification(MonitorNotification::Resize(display_id)); } + if flags.contains(CGDisplayChangeSummaryFlags::AddFlag) { + tracing::debug!("display: {display_id} added"); + monitor_reconciliator::send_notification(MonitorNotification::DisplayConnectionChange( + display_id, + )); + } + + if flags.contains(CGDisplayChangeSummaryFlags::RemoveFlag) { + tracing::debug!("display: {display_id} removed"); + monitor_reconciliator::send_notification(MonitorNotification::DisplayConnectionChange( + display_id, + )); + } + + if flags.contains(CGDisplayChangeSummaryFlags::EnabledFlag) { + tracing::debug!("display: {display_id} enabled"); + monitor_reconciliator::send_notification(MonitorNotification::DisplayConnectionChange( + display_id, + )); + } + + if flags.contains(CGDisplayChangeSummaryFlags::DisabledFlag) { + tracing::debug!("display: {display_id} disabled"); + monitor_reconciliator::send_notification(MonitorNotification::DisplayConnectionChange( + display_id, + )); + } + + if flags.contains(CGDisplayChangeSummaryFlags::MovedFlag) { + tracing::debug!("display: {display_id} moved"); + monitor_reconciliator::send_notification(MonitorNotification::DisplayConnectionChange( + display_id, + )); + } // if flags.contains(CGDisplayChangeSummaryFlags::BeginConfigurationFlag) { // tracing::debug!("display: {display_id} configured"); // } // - // if flags.contains(CGDisplayChangeSummaryFlags::AddFlag) { - // tracing::debug!("display: {display_id} added"); - // } - // - // if flags.contains(CGDisplayChangeSummaryFlags::RemoveFlag) { - // tracing::debug!("display: {display_id} removed"); - // } - // // if flags.contains(CGDisplayChangeSummaryFlags::MirrorFlag) { // tracing::debug!("display: {display_id} mirrored"); // } @@ -39,18 +65,6 @@ unsafe extern "C-unwind" fn callback( // tracing::debug!("display: {display_id} unmirrored"); // } // - // if flags.contains(CGDisplayChangeSummaryFlags::EnabledFlag) { - // tracing::debug!("display: {display_id} enabled"); - // } - // - // if flags.contains(CGDisplayChangeSummaryFlags::DisabledFlag) { - // tracing::debug!("display: {display_id} disabled"); - // } - // - // if flags.contains(CGDisplayChangeSummaryFlags::DisabledFlag) { - // tracing::debug!("display: {display_id} disabled"); - // } - // // tracing::trace!("display: {display_id}, flags: {flags:?}"); } diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index e7c157ba..04b1e9fb 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -10,6 +10,7 @@ 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; @@ -100,6 +101,10 @@ lazy_static! { 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 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/macos_api.rs b/komorebi/src/macos_api.rs index 23652e2d..b5888e17 100644 --- a/komorebi/src/macos_api.rs +++ b/komorebi/src/macos_api.rs @@ -1,3 +1,4 @@ +use crate::DISPLAY_INDEX_PREFERENCES; use crate::LibraryError; use crate::accessibility::AccessibilityApi; use crate::accessibility::attribute_constants::kAXFocusedApplicationAttribute; @@ -39,6 +40,172 @@ pub struct MacosApi; impl MacosApi { #[tracing::instrument(skip_all)] pub fn load_monitor_information(wm: &mut WindowManager) -> Result<(), LibraryError> { + 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) { + continue 'read; + } + } + + let m = device.clone(); + + let mut index_preference = None; + let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + for (index, id) in &*display_index_preferences { + if m.serial_number_id.eq(id) { + index_preference = Option::from(index); + } + } + + if let Some(preference) = index_preference { + while *preference >= monitors.elements().len() { + monitors.elements_mut().push_back(Monitor::placeholder()); + } + + let current_serial_id = monitors + .elements_mut() + .get(*preference) + .map_or("", |m| &m.serial_number_id); + if current_serial_id == "PLACEHOLDER" { + let _ = monitors.elements_mut().remove(*preference); + monitors.elements_mut().insert(*preference, m); + } else { + monitors.elements_mut().insert(*preference, m); + } + } else { + monitors.elements_mut().push_back(m); + } + } + + monitors + .elements_mut() + .retain(|m| m.serial_number_id.ne("PLACEHOLDER")); + + // Rebuild monitor index map + *monitor_usr_idx_map = HashMap::new(); + let mut added_monitor_idxs = Vec::new(); + for (index, id) in &*DISPLAY_INDEX_PREFERENCES.read() { + if let Some(m_idx) = monitors + .elements() + .iter() + .position(|m| m.serial_number_id.eq(id)) + { + monitor_usr_idx_map.insert(*index, m_idx); + added_monitor_idxs.push(m_idx); + } + } + + let max_usr_idx = monitors + .elements() + .len() + .max(monitor_usr_idx_map.keys().max().map_or(0, |v| *v)); + + let mut available_usr_idxs = (0..max_usr_idx) + .filter(|i| !monitor_usr_idx_map.contains_key(i)) + .collect::>(); + + let not_added_monitor_idxs = (0..monitors.elements().len()) + .filter(|i| !added_monitor_idxs.contains(i)) + .collect::>(); + + for i in not_added_monitor_idxs { + if let Some(next_usr_idx) = available_usr_idxs.first() { + monitor_usr_idx_map.insert(*next_usr_idx, i); + available_usr_idxs.remove(0); + } else if let Some(idx) = monitor_usr_idx_map.keys().max() { + monitor_usr_idx_map.insert(*idx, i); + } + } + + Ok(()) + } + + pub fn update_monitor_work_areas(wm: Arc>) -> 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}" + ) + } + } + } + + let focus_follows_mouse = wm.mouse_follows_focus; + wm.update_focused_workspace(focus_follows_mouse, true)?; + } + + Ok(()) + } + + pub fn latest_monitor_information() -> Result, LibraryError> { + let mut monitors = vec![]; + let monitor_info = IoReg::query_monitors()?; let mut monitor_info_map = HashMap::new(); for m in monitor_info { @@ -70,16 +237,17 @@ impl MacosApi { &info.product_name, &info.alphanumeric_serial_number, ); - wm.monitors.elements_mut().push_back(monitor); + + monitors.push(monitor); } } } } - Ok(()) + Ok(monitors) } - pub fn update_monitor_work_areas(wm: Arc>) -> eyre::Result<()> { + pub fn reconile_monitors(wm: Arc>) -> eyre::Result<()> { let screens = NSScreen::screens(MainThreadMarker::new().unwrap()); for display_id in CoreGraphicsApi::connected_display_ids()? { diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index e06b0026..7de7467e 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -6,6 +6,8 @@ use color_eyre::eyre; use color_eyre::eyre::OptionExt; use komorebi::DATA_DIR; use komorebi::HOME_DIR; +use komorebi::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; @@ -277,6 +279,12 @@ fn main() -> eyre::Result<()> { 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()?); + } + // this gets our observer notification callbacks firing autoreleasepool(|_| unsafe { CFRunLoop::run_in_mode(kCFRunLoopDefaultMode, 2.0, false) }); } diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index bd632388..09d80c2a 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -70,6 +70,33 @@ pub struct Monitor { pub floating_layer_behaviour: Option, } +pub fn new( + id: u32, + size: Rect, + work_area_size: Rect, + device: String, + serial_number_id: String, +) -> Monitor { + let mut workspaces = Ring::default(); + workspaces.elements_mut().push_back(Workspace::default()); + + Monitor { + id, + device, + serial_number_id, + size, + work_area_size, + work_area_offset: None, + window_based_work_area_offset: None, + window_based_work_area_offset_limit: 1, + workspaces, + last_focused_workspace: None, + container_padding: None, + workspace_padding: None, + floating_layer_behaviour: None, + } +} + impl Monitor { #[allow(clippy::field_reassign_with_default)] pub fn new( @@ -104,6 +131,25 @@ impl Monitor { } } + pub fn placeholder() -> Self { + Self { + // temp + id: 2051316, + device: "".to_string(), + serial_number_id: "PLACEHOLDER".to_string(), + size: Default::default(), + work_area_size: Default::default(), + work_area_offset: None, + window_based_work_area_offset: None, + window_based_work_area_offset_limit: 0, + workspaces: Default::default(), + last_focused_workspace: None, + container_padding: None, + workspace_padding: None, + floating_layer_behaviour: None, + } + } + #[tracing::instrument(skip_all)] pub fn update_focused_workspace(&mut self, offset: Option) -> eyre::Result<()> { let offset = if self.work_area_offset.is_some() { diff --git a/komorebi/src/monitor_reconciliator.rs b/komorebi/src/monitor_reconciliator.rs index dc7ce7d8..04d69da1 100644 --- a/komorebi/src/monitor_reconciliator.rs +++ b/komorebi/src/monitor_reconciliator.rs @@ -1,6 +1,12 @@ +use crate::DISPLAY_INDEX_PREFERENCES; +use crate::LATEST_MONITOR_INFORMATION; use crate::Notification; use crate::NotificationEvent; 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; @@ -10,6 +16,7 @@ use objc2_core_graphics::CGDirectDisplayID; use parking_lot::Mutex; use serde::Deserialize; use serde::Serialize; +use std::collections::HashMap; use std::sync::Arc; use std::sync::OnceLock; use std::sync::atomic::Ordering; @@ -19,10 +26,14 @@ use strum::Display; #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum MonitorNotification { Resize(CGDirectDisplayID), + DisplayConnectionChange(CGDirectDisplayID), } static CHANNEL: OnceLock<(Sender, Receiver)> = OnceLock::new(); + +static MONITOR_CACHE: OnceLock>> = OnceLock::new(); + pub fn channel() -> &'static (Sender, Receiver) { CHANNEL.get_or_init(|| crossbeam_channel::bounded(20)) } @@ -35,6 +46,22 @@ fn event_rx() -> Receiver { channel().1.clone() } +pub fn insert_in_monitor_cache(serial_number_id: &str, monitor: Monitor) { + let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + let mut dip_ids = display_index_preferences.values(); + let preferred_id = if dip_ids.any(|id| id == serial_number_id) { + monitor.serial_number_id.clone() + } else { + serial_number_id.to_string() + }; + + let mut monitor_cache = MONITOR_CACHE + .get_or_init(|| Mutex::new(HashMap::new())) + .lock(); + + monitor_cache.insert(preferred_id, monitor); +} + pub fn send_notification(notification: MonitorNotification) { if event_tx().try_send(notification).is_err() { tracing::warn!("channel is full; dropping notification") @@ -67,8 +94,8 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result let receiver = event_rx(); - for notification in receiver { - let wm = wm.lock(); + 'receiver: for notification in receiver { + let mut wm = wm.lock(); let initial_state = State::from(wm.as_ref()); @@ -77,6 +104,448 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result tracing::debug!("handling resize notification"); UPDATE_MONITOR_WORK_AREAS.store(true, Ordering::Relaxed); } + MonitorNotification::DisplayConnectionChange(_) => { + tracing::debug!("handling display connection change notification"); + let mut monitor_cache = MONITOR_CACHE + .get_or_init(|| Mutex::new(HashMap::new())) + .lock(); + + let initial_monitor_count = wm.monitors().len(); + + // Get the currently attached display devices + // 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; + + UPDATE_MONITOR_WORK_AREAS.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_MONITOR_WORK_AREAS.store(false, Ordering::Relaxed); + + // Make sure that in our state any attached displays have the latest Win32 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)) = + // (&attached.serial_number_id, &monitor.serial_number_id) + // { + // attached_snid.eq(m_snid) + // } else { + // false + // }; + + let serial_number_ids_match = + attached.serial_number_id == monitor.serial_number_id; + + if serial_number_ids_match { + monitor.id = attached.id; + monitor.device = attached.device.clone(); + // monitor.device_id = attached.device_id.clone(); + monitor.serial_number_id = attached.serial_number_id.clone(); + // monitor.name = attached.name.clone(); + monitor.size = attached.size; + monitor.work_area_size = attached.work_area_size; + } + } + } + + if initial_monitor_count == attached_devices.len() { + tracing::debug!("monitor counts match, reconciliation not required"); + drop(wm); + continue 'receiver; + } + + if attached_devices.is_empty() { + tracing::debug!( + "no devices found, skipping reconciliation to avoid breaking state" + ); + drop(wm); + continue 'receiver; + } + + if initial_monitor_count > attached_devices.len() { + tracing::info!( + "monitor count mismatch ({initial_monitor_count} vs {}), removing disconnected monitors", + attached_devices.len() + ); + + // Windows to remove from `known_hwnds` + let mut windows_to_remove = Vec::new(); + + // Collect the ids in our state which aren't in the current attached display ids + // These are monitors that have been removed + let mut newly_removed_displays = vec![]; + + for (m_idx, m) in wm.monitors().iter().enumerate() { + if !attached_devices + .iter() + .any(|attached| attached.serial_number_id.eq(&m.serial_number_id)) + { + let id = m.serial_number_id.clone(); + + newly_removed_displays.push(id.clone()); + + let focused_workspace_idx = m.focused_workspace_idx(); + + for (idx, workspace) in m.workspaces().iter().enumerate() { + let is_focused_workspace = idx == focused_workspace_idx; + let focused_container_idx = workspace.focused_container_idx(); + for (c_idx, container) in workspace.containers().iter().enumerate() + { + let focused_window_idx = container.focused_window_idx(); + for (w_idx, window) in container.windows().iter().enumerate() { + windows_to_remove.push(window.id); + if is_focused_workspace + && c_idx == focused_container_idx + && w_idx == focused_window_idx + { + // TODO: Do we need this on macOS? + // Minimize the focused window since Windows might try + // to move it to another monitor if it was focused. + // if window.is_focused() { + // window.minimize()?; + // } + } + } + } + + // TODO: might not support maximization on macOS + // if let Some(maximized) = &workspace.maximized_window { + // windows_to_remove.push(maximized.id); + // // Minimize the focused window since Windows might try + // // to move it to another monitor if it was focused. + // if maximized.is_focused() { + // maximized.minimize(); + // } + // } + + if let Some(container) = &workspace.monocle_container { + for window in container.windows() { + windows_to_remove.push(window.id); + } + if let Some(_window) = container.focused_window() { + // TODO: Do we need this on macOS? + // Minimize the focused window since Windows might try + // to move it to another monitor if it was focused. + // if window.is_focused() { + // window.minimize(); + // } + } + } + + for window in workspace.floating_windows() { + windows_to_remove.push(window.id); + // TODO: Do we need this on macOS? + // Minimize the focused window since Windows might try + // to move it to another monitor if it was focused. + // if window.is_focused() { + // window.minimize(); + // } + } + } + + // Remove any workspace_rules for this specific monitor + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + let mut rules_to_remove = Vec::new(); + for (i, rule) in workspace_rules.iter().enumerate().rev() { + if rule.monitor_index == m_idx { + rules_to_remove.push(i); + } + } + for i in rules_to_remove { + workspace_rules.remove(i); + } + + // Let's add their state to the cache for later, make sure to use what + // the user set as preference as the id. + let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + let mut dip_ids = display_index_preferences.values(); + + let preferred_id = if dip_ids.any(|id| m.serial_number_id.eq(id)) { + m.serial_number_id.clone() + } else { + id.to_string() + }; + + monitor_cache.insert(preferred_id, m.clone()); + } + } + + // Update known_hwnds + wm.known_window_ids + .retain(|i, _| !windows_to_remove.contains(i)); + + if !newly_removed_displays.is_empty() { + // After we have cached them, remove them from our state + wm.monitors_mut().retain(|m| { + !newly_removed_displays + .iter() + .any(|id| m.serial_number_id.eq(id)) + }); + } + + let post_removal_monitor_count = wm.monitors().len(); + let focused_monitor_idx = wm.focused_monitor_idx(); + if focused_monitor_idx >= post_removal_monitor_count { + wm.focus_monitor(0)?; + } + + let offset = wm.work_area_offset; + + for monitor in wm.monitors_mut() { + // If we have lost a monitor, update everything to filter out any jank + if initial_monitor_count != post_removal_monitor_count { + monitor.update_focused_workspace(offset)?; + } + } + } + + let post_removal_monitor_count = wm.monitors().len(); + + // // This is the list of device ids after we have removed detached displays. We can + // // keep this with just the device_ids without the serial numbers since this is used + // // only to check which one is the newly added monitor below if there is a new + // // monitor. Everything done after with said new monitor will again consider both + // // serial number and device ids. + // let post_removal_device_ids = wm + // .monitors() + // .iter() + // .map(|m| &m.device_id) + // .cloned() + // .collect::>(); + let post_removal_serial_ids = []; + + // // 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)?; + + let post_addition_monitor_count = wm.monitors().len(); + + if post_addition_monitor_count > post_removal_monitor_count { + tracing::info!( + "monitor count mismatch ({post_removal_monitor_count} vs {post_addition_monitor_count}), adding connected monitors", + ); + + let known_window_ids = wm.known_window_ids.clone(); + let offset = wm.work_area_offset; + let mouse_follows_focus = wm.mouse_follows_focus; + let focused_monitor_idx = wm.focused_monitor_idx(); + let focused_workspace_idx = wm.focused_workspace_idx()?; + + // Look in the updated state for new monitors + for (i, m) in wm.monitors_mut().iter_mut().enumerate() { + // let device_id = &m.device_id; + let serial_id = m.serial_number_id.clone(); + // We identify a new monitor when we encounter a new device id + if !post_removal_serial_ids.contains(&serial_id) { + let mut cache_hit = false; + let mut cached_id = String::new(); + // Check if that device id exists in the cache for this session + if let Some((id, cached)) = monitor_cache.get_key_value(&serial_id) { + cache_hit = true; + cached_id = id.clone(); + + tracing::info!( + "found monitor and workspace configuration for {id} in the monitor cache, applying" + ); + + // If it does, update the cached monitor info with the new one and + // load the cached monitor removing any window that has since been + // closed or moved to another workspace + *m = Monitor { + // Data that should be the one just read from `win32-display-data` + id: m.id, + // name: m.name.clone(), + device: m.device.clone(), + // device_id: m.device_id.clone(), + serial_number_id: m.serial_number_id.clone(), + size: m.size, + work_area_size: m.work_area_size, + + // The rest should come from the cached monitor + work_area_offset: cached.work_area_offset, + window_based_work_area_offset: cached + .window_based_work_area_offset, + window_based_work_area_offset_limit: cached + .window_based_work_area_offset_limit, + workspaces: cached.workspaces.clone(), + last_focused_workspace: cached.last_focused_workspace, + // workspace_names: cached.workspace_names.clone(), + container_padding: cached.container_padding, + workspace_padding: cached.workspace_padding, + // wallpaper: cached.wallpaper.clone(), + floating_layer_behaviour: cached.floating_layer_behaviour, + }; + + let focused_workspace_idx = m.focused_workspace_idx(); + + for (j, workspace) in m.workspaces_mut().iter_mut().enumerate() { + // If this is the focused workspace we need to show (restore) all + // windows that were visible since they were probably minimized by + // Windows. + let is_focused_workspace = j == focused_workspace_idx; + let focused_container_idx = workspace.focused_container_idx(); + + let mut empty_containers = Vec::new(); + for (idx, container) in + workspace.containers_mut().iter_mut().enumerate() + { + container.windows_mut().retain(|window| { + window.exe().is_some() + && !known_window_ids.contains_key(&window.id) + }); + + if container.windows().is_empty() { + empty_containers.push(idx); + } + + if is_focused_workspace { + if let Some(_window) = container.focused_window() { + // TODO: do we need to do this on macOS? + // tracing::debug!( + // "restoring window: {}", + // window.id + // ); + // WindowsApi::restore_window(window.hwnd); + } else { + // If the focused window was moved or removed by + // the user after the disconnect then focus the + // first window and show that one + container.focus_window(0); + // + // if let Some(window) = container.focused_window() { + // WindowsApi::restore_window(window.hwnd); + // } + } + } + } + + // Remove empty containers + for empty_idx in empty_containers { + if empty_idx == focused_container_idx { + workspace.remove_container(empty_idx); + } else { + workspace.remove_container_by_idx(empty_idx); + } + } + + // if let Some(window) = &workspace.maximized_window { + // if window.exe().is_none() + // || known_window_ids.contains_key(&window.id) + // { + // workspace.maximized_window = None; + // } else if is_focused_workspace { + // WindowsApi::restore_window(window.hwnd); + // } + // } + + if let Some(container) = &mut workspace.monocle_container { + container.windows_mut().retain(|window| { + window.exe().is_some() + && !known_window_ids.contains_key(&window.id) + }); + + if container.windows().is_empty() { + workspace.monocle_container = None; + } else if is_focused_workspace { + if let Some(_window) = container.focused_window() { + // WindowsApi::restore_window(window.hwnd); + } else { + // If the focused window was moved or removed by + // the user after the disconnect then focus the + // first window and show that one + container.focus_window(0); + + if let Some(_window) = container.focused_window() { + // WindowsApi::restore_window(window.hwnd); + } + } + } + } + + workspace.floating_windows_mut().retain(|window| { + window.exe().is_some() + && !known_window_ids.contains_key(&window.id) + }); + + if is_focused_workspace { + for _window in workspace.floating_windows() { + // WindowsApi::restore_window(window.hwnd); + } + } + + // Apply workspace rules + let mut workspace_matching_rules = + WORKSPACE_MATCHING_RULES.lock(); + if let Some(rules) = workspace + .workspace_config + .as_ref() + .and_then(|c| c.workspace_rules.as_ref()) + { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: false, + }); + } + } + + if let Some(rules) = workspace + .workspace_config + .as_ref() + .and_then(|c| c.initial_workspace_rules.as_ref()) + { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: true, + }); + } + } + } + + // Restore windows from new monitor and update the focused + // workspace + m.load_focused_workspace(mouse_follows_focus)?; + m.update_focused_workspace(offset)?; + } + + // Entries in the cache should only be used once; remove the entry there was a cache hit + if cache_hit && !cached_id.is_empty() { + monitor_cache.remove(&cached_id); + } + } + } + + // Refocus the previously focused monitor since the code above might + // steal the focus away. + wm.focus_monitor(focused_monitor_idx)?; + wm.focus_workspace(focused_workspace_idx)?; + } + + let final_count = wm.monitors().len(); + + if post_removal_monitor_count != final_count { + wm.retile_all(true)?; + // Second retile to fix DPI/resolution related jank + // wm.retile_all(true)?; + // Border updates to fix DPI/resolution related jank + // border_manager::send_notification(None); + } + } } notify_subscribers( diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 9aa3f083..d6627ff4 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -1,4 +1,5 @@ use crate::DATA_DIR; +use crate::DISPLAY_INDEX_PREFERENCES; use crate::HOME_DIR; use crate::IGNORE_IDENTIFIERS; use crate::MANAGE_IDENTIFIERS; @@ -15,6 +16,7 @@ use crate::window_manager::WindowManager; use crate::workspace::Workspace; use serde::Deserialize; use serde::Serialize; +use std::collections::HashMap; use std::collections::VecDeque; use std::path::PathBuf; @@ -44,7 +46,7 @@ pub struct GlobalState { // pub tray_and_multi_window_identifiers: Vec, // pub name_change_on_launch_identifiers: Vec, // pub monitor_index_preferences: HashMap, - // pub display_index_preferences: HashMap, + pub display_index_preferences: HashMap, // pub ignored_duplicate_monitor_serial_ids: Vec, pub workspace_rules: Vec, // pub window_hiding_behaviour: HidingBehaviour, @@ -58,6 +60,7 @@ impl Default for GlobalState { Self { ignore_identifiers: IGNORE_IDENTIFIERS.lock().clone(), manage_identifiers: MANAGE_IDENTIFIERS.lock().clone(), + display_index_preferences: DISPLAY_INDEX_PREFERENCES.read().clone(), workspace_rules: WORKSPACE_MATCHING_RULES.lock().clone(), configuration_dir: HOME_DIR.clone(), data_dir: DATA_DIR.clone(), @@ -70,7 +73,7 @@ impl Default for GlobalState { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct State { pub monitors: Ring, - // pub monitor_usr_idx_map: HashMap, + pub monitor_usr_idx_map: HashMap, pub is_paused: bool, pub resize_delta: i32, pub new_window_behaviour: WindowContainerBehaviour, @@ -154,7 +157,7 @@ impl From<&WindowManager> for State { Self { monitors: stripped_monitors, - // monitor_usr_idx_map: wm.monitor_usr_idx_map.clone(), + monitor_usr_idx_map: wm.monitor_usr_idx_map.clone(), is_paused: wm.is_paused, work_area_offset: wm.work_area_offset, resize_delta: wm.resize_delta, diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index b0030726..0fb87c49 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -28,7 +28,9 @@ use crate::core::default_layout::LayoutOptions; use crate::core::layout::Layout; use crate::core::pathext::ResolvedPathBuf; use crate::core::rect::Rect; +use crate::monitor; use crate::monitor::Monitor; +use crate::monitor_reconciliator; use crate::ring::Ring; use crate::window::AspectRatio; use crate::window::PredefinedAspectRatio; @@ -1120,7 +1122,7 @@ impl StaticConfig { let mut wm = WindowManager { monitors: Ring::default(), - // monitor_usr_idx_map: HashMap::new(), + monitor_usr_idx_map: HashMap::new(), applications: Default::default(), incoming_events: incoming, command_listener: listener, @@ -1275,13 +1277,10 @@ impl StaticConfig { // Check if this monitor config is the preferred config for this monitor and store // a copy of the monitor itself on the monitor cache if it is. - // if idx == preferred_config_idx { - // let id = monitor - // .serial_number_id - // .as_ref() - // .map_or(&monitor.device_id, |sn| sn); - // monitor_reconciliator::insert_in_monitor_cache(id, monitor.clone()); - // } + if idx == preferred_config_idx { + let id = &monitor.serial_number_id; + monitor_reconciliator::insert_in_monitor_cache(id, monitor.clone()); + } let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); for (j, ws) in monitor_config.workspaces.iter().enumerate() { @@ -1313,53 +1312,46 @@ impl StaticConfig { // Check for configs that should be tied to a specific display that isn't loaded right now // and cache a monitor with those configs with the specific `serial_number_id` so that when // those devices are connected later we can use the correct config from the cache. - // if configs_with_preference.len() > configs_used.len() { - // for i in configs_with_preference - // .iter() - // .filter(|i| !configs_used.contains(i)) - // { - // let id = { - // let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); - // display_index_preferences.get(i).cloned() - // }; - // if let (Some(id), Some(monitor_config)) = - // (id, value.monitors.as_ref().and_then(|ms| ms.get(*i))) - // { - // // The name, device, device_id and serial_number_id can be empty here since - // // once the monitor with this preferred index actually connects the - // // `load_monitor_information` function will update these fields. - // let mut m = monitor::new( - // 0, - // Rect::default(), - // Rect::default(), - // "".into(), - // "".into(), - // "".into(), - // None, - // ); - // - // m.ensure_workspace_count(monitor_config.workspaces.len()); - // m.work_area_offset = monitor_config.work_area_offset; - // m.window_based_work_area_offset = monitor_config.window_based_work_area_offset; - // m.window_based_work_area_offset_limit = monitor_config - // .window_based_work_area_offset_limit - // .unwrap_or(1); - // m.container_padding = monitor_config.container_padding; - // m.workspace_padding = monitor_config.workspace_padding; - // m.floating_layer_behaviour = monitor_config.floating_layer_behaviour; - // - // m.update_workspaces_globals(offset); - // - // for (j, ws) in m.workspaces_mut().iter_mut().enumerate() { - // if let Some(workspace_config) = monitor_config.workspaces.get(j) { - // ws.load_static_config(workspace_config)?; - // } - // } - // - // monitor_reconciliator::insert_in_monitor_cache(&id, m); - // } - // } - // } + if configs_with_preference.len() > configs_used.len() { + for i in configs_with_preference + .iter() + .filter(|i| !configs_used.contains(i)) + { + let id = { + let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + display_index_preferences.get(i).cloned() + }; + if let (Some(id), Some(monitor_config)) = + (id, value.monitors.as_ref().and_then(|ms| ms.get(*i))) + { + // The name, device, device_id and serial_number_id can be empty here since + // once the monitor with this preferred index actually connects the + // `load_monitor_information` function will update these fields. + let mut m = + monitor::new(0, Rect::default(), Rect::default(), "".into(), "".into()); + + m.ensure_workspace_count(monitor_config.workspaces.len()); + m.work_area_offset = monitor_config.work_area_offset; + m.window_based_work_area_offset = monitor_config.window_based_work_area_offset; + m.window_based_work_area_offset_limit = monitor_config + .window_based_work_area_offset_limit + .unwrap_or(1); + m.container_padding = monitor_config.container_padding; + m.workspace_padding = monitor_config.workspace_padding; + m.floating_layer_behaviour = monitor_config.floating_layer_behaviour; + + m.update_workspaces_globals(offset); + + for (j, ws) in m.workspaces_mut().iter_mut().enumerate() { + if let Some(workspace_config) = monitor_config.workspaces.get(j) { + ws.load_static_config(workspace_config)?; + } + } + + monitor_reconciliator::insert_in_monitor_cache(&id, m); + } + } + } wm.enforce_workspace_rules()?; diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 848abf59..2eb9dfa3 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -59,6 +59,7 @@ use std::sync::Arc; #[derive(Debug)] pub struct WindowManager { pub monitors: Ring, + pub monitor_usr_idx_map: HashMap, pub applications: HashMap, pub run_loop: CoreFoundationRunLoop, pub command_listener: UnixListener, @@ -138,6 +139,7 @@ impl WindowManager { Ok(Self { monitors: Ring::default(), + monitor_usr_idx_map: HashMap::new(), applications: Default::default(), run_loop: CoreFoundationRunLoop(run_loop.clone()), command_listener: listener, diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index c3401f10..c1cae466 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -741,6 +741,13 @@ impl Workspace { container } + pub fn remove_container(&mut self, idx: usize) -> Option { + let container = self.remove_container_by_idx(idx); + self.focus_previous_container(); + + container + } + pub fn promote_container(&mut self) -> eyre::Result<()> { let resize = self.resize_dimensions.remove(0); let container = self