diff --git a/crates/komorebi-backend/src/backend.rs b/crates/komorebi-backend/src/backend.rs index 83e7ce74..a9df374a 100644 --- a/crates/komorebi-backend/src/backend.rs +++ b/crates/komorebi-backend/src/backend.rs @@ -325,6 +325,22 @@ pub trait Backend: Send + Sync + 'static { self.window(id).map(|w| w.rect) } + /// Returns the window's frame, or why there is none: [`Error::WindowGone`] when the backend + /// does not know the window, [`Error::Platform`] when the platform could not say. A **cheap + /// live frame query**: unlike [`Backend::window`] it never asks for the title, class, + /// executable or path, and unlike [`Backend::window_rect`] it keeps the reason for a failure. + /// + /// The frame is the same value as the `rect` of [`Backend::window`]: Windows the visible + /// bounds (`DWMWA_EXTENDED_FRAME_BOUNDS`, fallback `GetWindowRect`), macOS the Accessibility + /// position and size (two round trips), KDE the daemon's table (the requested rect until an + /// event corrects it, see "Reads after writes"). + /// + /// The default goes through [`Backend::window`], which is a table lookup on KDE and the fake; + /// Windows and macOS override it. + fn frame(&self, id: WindowId) -> Result { + self.window(id).map(|w| w.rect).ok_or(Error::WindowGone(id)) + } + /// Returns the id of the monitor whose bounds contain the point. A point outside every /// monitor gives `None` on KDE and macOS, and the **nearest** monitor on Windows /// (`MONITOR_DEFAULTTONEAREST`), so callers must not use `None` to detect "off screen". diff --git a/crates/komorebi-backend/src/contract.rs b/crates/komorebi-backend/src/contract.rs index 5c9b3441..d7bb47b0 100644 --- a/crates/komorebi-backend/src/contract.rs +++ b/crates/komorebi-backend/src/contract.rs @@ -208,6 +208,7 @@ fn window_agrees_with_windows() { assert!(info.alive); assert!(h.backend().is_window(id)); assert_eq!(h.backend().window_rect(id), Some(info.rect)); + assert_eq!(h.backend().frame(id).ok(), Some(info.rect)); assert!(h.backend().windows().iter().any(|w| w.id == id)); } @@ -219,6 +220,11 @@ fn an_unknown_window_is_not_a_window() { assert!(h.backend().window(unknown).is_none()); assert!(!h.backend().is_window(unknown)); assert!(h.backend().window_rect(unknown).is_none()); + assert!( + h.backend() + .frame(unknown) + .is_err_and(|e| e.is_window_gone()) + ); } fn commands_on_an_unknown_window() { diff --git a/crates/komorebi-backend/src/fake.rs b/crates/komorebi-backend/src/fake.rs index 9d9821b6..67c9a829 100644 --- a/crates/komorebi-backend/src/fake.rs +++ b/crates/komorebi-backend/src/fake.rs @@ -1056,6 +1056,17 @@ mod tests { Ok(()) } + #[test] + fn frame_is_the_requested_rect_and_an_unknown_window_is_gone() -> Result<()> { + let fake = fake_with(&[1]); + + fake.set_rect(ONE, &tile(10, 500))?; + + assert_eq!(fake.frame(ONE)?, tile(10, 500)); + assert!(fake.frame(WindowId(99)).is_err_and(|e| e.is_window_gone())); + Ok(()) + } + #[test] fn a_window_keeps_to_its_minimum_size() -> Result<()> { let fake = fake_with(&[1]); diff --git a/docs/dev/backend-switch.md b/docs/dev/backend-switch.md new file mode 100644 index 00000000..2cc78001 --- /dev/null +++ b/docs/dev/backend-switch.md @@ -0,0 +1,60 @@ +# Windows: which call sites go through `backend()` + +Step 8 of the unified-binaries plan. `komorebi::windows_backend::backend()` returns the shared +`komorebi_backend::Backend` (a stateless `WindowsBackend` over `WindowsApi` and `Window`). The daemon +is switched one cluster at a time; each switch is its own revision marked BEHAVIOUR. + +What every switched call changes in the Windows daemon: `WindowsBackend` first asks `IsWindow` and +fails with `Error::WindowGone` for a dead window (hide, restore, minimize, maximize and the other `()` +returning operations are then skipped: before, `Window::hide` of a dead window still ran +`ShowWindow` on it, a no-op, and recorded its handle in `HIDDEN_HWNDS`), and a failure of a window +that died meanwhile is reported as `WindowGone` (the error text changes from the Win32 one). Call sites +use `?` or ignore the result; none inspects the error. `frame` is the exception: it does not ask +`IsWindow` first, so the Win32 error is what callers get. + +## Switched + +| Cluster | Operation | Sites | Notes | e2e needed | +|---|---|---|---|---| +| focus | `focus(id, mouse_follows)` | 40 (process_event, process_command, workspace, window_manager, focus_manager, stackbar) | `animation/transition.rs` calls `Window::focus` from the slide-in code `Window::focus` defers to: left | commands, focus, focus_follows_mouse, stacking, workspaces, lifecycle | +| frame write | `set_rect(id, rect)` | 2 (workspace layout update, stackbar tab click) | `top = false` only | commands, resize, layouts, stacking, scrolling, workspaces | +| frame read | `frame(id)` | about 55, one revision per file: stackbar_manager (2 files), animation (snapshot, ghost_dispatcher, ghost test), live_resize, pan, scrolling, process_command, process_event, window_manager, border_manager (2 files) | `frame` is a provided method added to the trait for this (WindowsBackend: `Window::window_rect`, one DWM call; error kept). `Window::window_rect`/`WindowsApi::window_rect` remain only inside `window.rs` (the implementation, and `Window::set_position`/`move_to_area`/`center`/`focus` internals) | resize, layouts, stacking, scrolling, borders, animation, commands, lifecycle | +| hide / show | `hide`, `restore` (plain forms) | 23 | | commands, workspaces, stacking, lifecycle_hidden | +| hide / show | `minimize`, `close`, `raise` | 1 + 1 + 4 (process_command), 4 minimize (monitor_reconciliator) | | commands, monitor reconciliation, lifecycle | +| maximize | `maximize(id, bool)` | 5 (workspace.rs) | capability query already in the trait (`supports(Capability::Maximize)`, true here) | maximizing, commands, workspaces | + +## Left on purpose (platform-owned subsystems, seam.md rule 5) + +- `set_position(.., true)` (window.rs `move_to_area`, `center`, workspace maximize area): the raise-to-front + flag is a Windows detail of the layout/animation code, the shared `set_rect` has none. +- `hide_with_border`, `restore_with_border`: borders are a platform subsystem (own windows and threads). +- `animation/transition.rs`, `animation/ghost*.rs` (except the frame reads above): the DWM ghost and + slide-in machinery. +- `set_opacity`: the adapter writes the plain alpha, `Window::transparent`/`opaque` take the alpha from the + transparency manager and animate. + +## Not switched, and what the trait would need (for step 9) + +| Operation | Why it stays on the platform API | What the trait would need | +|---|---|---| +| `foreground_window` | `WindowsApi::foreground_window() -> Result`: a null handle is an `Err` whose message callers pass on; the trait has `Option` | a `Result` variant (`Error::Platform` for "no foreground window"), or accept losing the message | +| `cursor_pos` | `Result` vs `Option<(i32, i32)>`; callers `?` it | same: a `Result` return | +| `monitors` / `window` | `monitors()` rebuilds `MonitorInfo` and drops the `Monitor` fields the daemon needs (device id, serial, device, work-area offsets); `window()` asks title, class, exe, path | the daemon-side `Monitor` fields in `MonitorInfo` (or a platform extension), and for step 9 the monitor model moving to the core | +| `monitor_from_point` | never `None` on Windows (`MONITOR_DEFAULTTONEAREST`), `None` outside every monitor on KDE and macOS | an explicit "nearest" flag or two methods | + +## What is left in `window_manager.rs`, `workspace.rs`, `monitor.rs` (checked call by call) + +Switched in the last batch: `center_cursor_in_rect` (3, window_manager), `disable_focus_follows_mouse` (1), +`restore_window` as `unminimize` (1, workspace). The rest names `WindowsApi` for a reason the trait does not +cover yet: + +| Call (sites) | Why it stays | +|---|---| +| `foreground_window` (10 in window_manager, 3 workspace, 1 monitor) | `Result`, a null handle is an `Err` the callers `?` on; trait has `Option` | +| `cursor_pos`, `window_at_cursor_pos`, `monitor_from_window`, `monitor_from_point` | `Result`/never-`None` semantics, see the table above; `window_at_cursor_pos` and `monitor_from_window` have no trait equivalent | +| `raise_and_focus_window(desktop_window)` (4) | `Backend::focus` is `Window::focus`, which skips when the window is already foreground and defers while it slides in; the direct call always raises and focuses | +| `position_window(hwnd, rect, false, true)` (2) | a different flag combination than `set_rect` (`top = false`, the second flag is the layered/shadow handling), not expressible | +| `load_monitor_information`, `load_workspace_information` | start-up enumeration into a `WindowManager`; seam.md 9: `windows()` cannot match the core's filter | +| `monitor(hmonitor)`, `monitor_rects`, `monitors_have_same_dpi` | the `Monitor` fields (device id, DPI) the trait's `MonitorInfo` drops | +| `set_wallpaper` | wallpaper stays KDE-only in the trait (D36) | +| `focus_follows_mouse` (query) | the trait has the setter only | diff --git a/komorebi-for-mac/komorebi/src/macos_backend.rs b/komorebi-for-mac/komorebi/src/macos_backend.rs index 2a3bca30..6e9fc14d 100644 --- a/komorebi-for-mac/komorebi/src/macos_backend.rs +++ b/komorebi-for-mac/komorebi/src/macos_backend.rs @@ -187,6 +187,15 @@ impl Backend for MacosBackend { Ok(monitors) } + fn frame(&self, id: WindowId) -> Result { + // the Accessibility position and size only, without the title, executable and path + // lookups of `window` + let window = self.lookup(id)?; + MacosApi::window_rect(&window.element) + .map(Rect::from) + .map_err(|e| Self::failed(id, &window, e)) + } + fn cursor_pos(&self) -> Option<(i32, i32)> { let point = MacosApi::cursor_pos(); #[allow(clippy::cast_possible_truncation)] diff --git a/komorebi/src/animation/ghost.rs b/komorebi/src/animation/ghost.rs index 0a9d7716..d35714fb 100644 --- a/komorebi/src/animation/ghost.rs +++ b/komorebi/src/animation/ghost.rs @@ -940,6 +940,8 @@ pub fn nudge_swap_chain_window(hwnd: isize, rect: &Rect, top: bool) { #[cfg(test)] mod tests { use super::*; + use crate::windows_backend::backend; + use komorebi_backend::WindowId; #[test] fn swap_chain_classes() { @@ -1193,7 +1195,8 @@ mod tests { // the screen is read in pixels, and the windows were put where they are in // the units of a process that the display's scaling is applied to - let scale = WindowsApi::window_rect(host.0 as isize) + let scale = backend() + .frame(WindowId::from_hwnd(host.0 as isize)) .map(|rect| f64::from(rect.right) / 800.0) .unwrap_or(1.0); diff --git a/komorebi/src/animation/ghost_dispatcher.rs b/komorebi/src/animation/ghost_dispatcher.rs index e91a1639..d0023164 100644 --- a/komorebi/src/animation/ghost_dispatcher.rs +++ b/komorebi/src/animation/ghost_dispatcher.rs @@ -26,7 +26,9 @@ use crate::stackbar_manager; use crate::transparency_manager; use crate::window::Window; use crate::windows_api::WindowsApi; +use crate::windows_backend::backend; use color_eyre::eyre; +use komorebi_backend::WindowId; use parking_lot::Mutex; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; @@ -320,8 +322,9 @@ impl GhostDispatcher { /// render target. Those that do have to be laid out are not until they are /// shown. fn lay_out_entering_window(&self) { - let is_there = - WindowsApi::window_rect(self.hwnd).is_ok_and(|rect| rect == self.target_rect); + let is_there = backend() + .frame(WindowId::from_hwnd(self.hwnd)) + .is_ok_and(|rect| rect == self.target_rect); if is_there { return; @@ -491,8 +494,9 @@ impl GhostDispatcher { /// swap chain is shown before it is laid out, and not after: laying one out /// while it is hidden is what leaves it blank or drawn off its place. fn show_entered_at_once(&self) { - let is_there = - WindowsApi::window_rect(self.hwnd).is_ok_and(|rect| rect == self.target_rect); + let is_there = backend() + .frame(WindowId::from_hwnd(self.hwnd)) + .is_ok_and(|rect| rect == self.target_rect); if is_there { self.show(); diff --git a/komorebi/src/animation/snapshot.rs b/komorebi/src/animation/snapshot.rs index 2be05264..e38df2c7 100644 --- a/komorebi/src/animation/snapshot.rs +++ b/komorebi/src/animation/snapshot.rs @@ -60,6 +60,8 @@ use windows::core::w; use crate::WindowsApi; use crate::border_manager::BorderLook; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; /// Ask for what the window looks like to the compositor, which is the only /// way to capture a window that is drawn with DirectComposition @@ -279,7 +281,7 @@ fn render(hwnd: isize) -> eyre::Result { let window_height = window.bottom - window.top; // what is on screen is the extended frame, inside the invisible borders - let frame = WindowsApi::window_rect(hwnd)?; + let frame = backend().frame(WindowId::from_hwnd(hwnd))?; let x = (frame.left - window.left).clamp(0, window_width); let y = (frame.top - window.top).clamp(0, window_height); let width = frame.right.min(window_width - x); diff --git a/komorebi/src/border_manager/border.rs b/komorebi/src/border_manager/border.rs index 98307ab6..3723681f 100644 --- a/komorebi/src/border_manager/border.rs +++ b/komorebi/src/border_manager/border.rs @@ -9,6 +9,8 @@ use crate::border_manager::window_kind_colour; use crate::core::BorderStyle; use crate::core::Rect; use crate::windows_api; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; use std::collections::HashMap; use std::ops::Deref; use std::sync::Arc; @@ -308,7 +310,9 @@ impl Border { monitor_idx: Some(monitor_idx), render_target: None, tracking_hwnd, - window_rect: WindowsApi::window_rect(tracking_hwnd).unwrap_or_default(), + window_rect: backend() + .frame(WindowId::from_hwnd(tracking_hwnd)) + .unwrap_or_default(), rendered_rect: Rect::default(), window_kind: WindowKind::Unfocused, style: STYLE.load(), @@ -566,7 +570,9 @@ impl Border { return LRESULT(0); } - let rect = WindowsApi::window_rect(reference_hwnd).unwrap_or_default(); + let rect = backend() + .frame(WindowId::from_hwnd(reference_hwnd)) + .unwrap_or_default(); apply_tracked_rect(border_pointer, rect); LRESULT(0) } @@ -593,14 +599,14 @@ impl Border { } WM_PAINT => { tracing::trace!("border {}: WM_PAINT", window.0 as isize); - if let Err(error) = WindowsApi::window_rect(window.0 as isize) { + if let Err(error) = backend().frame(WindowId::from_hwnd(window.0 as isize)) { tracing::trace!( "border {}: not painted, its own rect cannot be read: {error}", window.0 as isize ); } - if let Ok(rect) = WindowsApi::window_rect(window.0 as isize) { + if let Ok(rect) = backend().frame(WindowId::from_hwnd(window.0 as isize)) { let border_pointer: *mut Border = GetWindowLongPtrW(window, GWLP_USERDATA) as _; diff --git a/komorebi/src/border_manager/mod.rs b/komorebi/src/border_manager/mod.rs index eba053d3..b50abe3e 100644 --- a/komorebi/src/border_manager/mod.rs +++ b/komorebi/src/border_manager/mod.rs @@ -8,6 +8,7 @@ use crate::core::BorderStyle; use crate::core::WindowKind; use crate::ring::Ring; use crate::windows_api; +use crate::windows_backend::backend; use crate::workspace::Workspace; use crate::workspace::WorkspaceLayer; pub use border::Border; @@ -16,6 +17,7 @@ use crossbeam_channel::Receiver; use crossbeam_channel::Sender; use crossbeam_utils::atomic::AtomicCell; use crossbeam_utils::atomic::AtomicConsume; +use komorebi_backend::WindowId; pub use komorebi_config::behaviour::ZOrder; use komorebi_themes::colour::Colour; use komorebi_themes::colour::Rgb; @@ -678,7 +680,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result ); border.window_rect } else { - WindowsApi::window_rect(focused_window_hwnd)? + backend().frame(WindowId::from_hwnd(focused_window_hwnd))? }; border.window_rect = rect; @@ -739,8 +741,8 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result let foreground_hwnd = WindowsApi::foreground_window().unwrap_or_default(); let foreground_monitor_id = WindowsApi::monitor_from_window(foreground_hwnd); - let is_maximized = - foreground_monitor_id == m.id && WindowsApi::is_zoomed(foreground_hwnd); + let is_maximized = foreground_monitor_id == m.id.to_hmonitor() + && WindowsApi::is_zoomed(foreground_hwnd); if is_maximized { tracing::trace!( @@ -857,7 +859,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result ); border.window_rect } else { - match WindowsApi::window_rect(focused_window_hwnd) { + match backend().frame(WindowId::from_hwnd(focused_window_hwnd)) { Ok(rect) => rect, Err(_) => { remove_border(&c.id, &mut borders, &mut windows_borders)?; @@ -963,7 +965,7 @@ fn handle_floating_borders( ); border.window_rect } else { - WindowsApi::window_rect(window.hwnd)? + backend().frame(WindowId::from_hwnd(window.hwnd))? }; border.window_rect = rect; diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs index 2e56eef1..baa8f72a 100644 --- a/komorebi/src/container.rs +++ b/komorebi/src/container.rs @@ -5,6 +5,8 @@ use serde::Serialize; use crate::Lockable; use crate::ring::Ring; use crate::window::Window; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] @@ -12,7 +14,7 @@ pub struct Container { pub id: String, #[serde(default)] pub locked: bool, - windows: Ring, + pub windows: Ring, } impl_ring_elements!(Container, Window); @@ -63,14 +65,14 @@ impl Container { } if should_hide { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } } pub fn restore(&self) { if let Some(window) = self.focused_window() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } } @@ -151,7 +153,7 @@ impl Container { for (i, window) in self.windows().iter().enumerate() { if i != focused_window_idx { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } } diff --git a/komorebi/src/focus_manager.rs b/komorebi/src/focus_manager.rs index e6055ff8..d6e3bf98 100644 --- a/komorebi/src/focus_manager.rs +++ b/komorebi/src/focus_manager.rs @@ -7,8 +7,9 @@ use std::ops::Deref; use std::sync::Arc; use std::sync::OnceLock; -use crate::Window; use crate::WindowManager; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; pub struct Notification(isize); @@ -65,7 +66,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result for notification in receiver { let mouse_follows_focus = wm.lock().mouse_follows_focus; - let _ = Window::from(*notification).focus(mouse_follows_focus); + let _ = backend().focus(WindowId::from_hwnd(*notification), mouse_follows_focus); } Ok(()) diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 9b4d0865..ba20ddfe 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -86,6 +86,23 @@ use which::which; use winreg::RegKey; use winreg::enums::HKEY_CURRENT_USER; +// LOCK ORDER of the rule lists. A thread that holds one of these and takes another must take them +// in this order (a thread that takes two in another order can wait for one that holds what it +// needs, and both wait for ever): +// +// FLOATING_APPLICATIONS, SESSION_FLOATING_APPLICATIONS, TRANSPARENCY_BLACKLIST, +// IGNORE_IDENTIFIERS, MANAGE_IDENTIFIERS, LAYERED_WHITELIST, TRAY_AND_MULTI_WINDOW_IDENTIFIERS, +// OBJECT_NAME_CHANGE_ON_LAUNCH, OBJECT_NAME_CHANGE_TITLE_IGNORE_LIST, +// SLOW_APPLICATION_IDENTIFIERS, NO_TITLEBAR, WORKSPACE_MATCHING_RULES, REGEX_IDENTIFIERS +// +// REGEX_IDENTIFIERS is last: every rule check holds the list it matches against and then the +// compiled regexes. PERMAIGNORE_CLASSES and WSL2_UI_PROCESSES are leaves (nothing is taken while +// they are held). Places that nest the others: window.rs (window_is_eligible), static_config.rs +// (apply_globals), +// state.rs (the State snapshot), process_command.rs (session float rules), process_event.rs, +// window_manager_event.rs, transparency_manager.rs, window_manager.rs. The same rule applies to +// any new place: lock in this order, or lock one at a time. + lazy_static! { static ref HIDDEN_HWNDS: Arc>> = Arc::new(Mutex::new(vec![])); static ref LAYERED_WHITELIST: Arc>> = Arc::new(Mutex::new(vec![ diff --git a/komorebi/src/live_resize.rs b/komorebi/src/live_resize.rs index c01e7eb1..5cbc6e87 100644 --- a/komorebi/src/live_resize.rs +++ b/komorebi/src/live_resize.rs @@ -29,10 +29,12 @@ use crate::core::Rect; use crate::core::Sizing; use crate::window::Window; use crate::window_manager::WindowManager; +use crate::windows_backend::backend; use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use crossbeam_channel::Sender; use crossbeam_channel::bounded; +use komorebi_backend::WindowId; use komorebi_scrolling::ScrollingSpace; use parking_lot::Mutex; use std::collections::HashMap; @@ -163,7 +165,9 @@ pub fn is_catching_up(hwnd: isize, layout: &Rect) -> bool { return false; }; - let arrived = WindowsApi::window_rect(hwnd).is_ok_and(|rect| rect == target); + let arrived = backend() + .frame(WindowId::from_hwnd(hwnd)) + .is_ok_and(|rect| rect == target); if arrived || at.elapsed() >= IN_FLIGHT { return false; @@ -440,7 +444,7 @@ pub fn cover_all(windows: &[(isize, Rect)]) { .into_iter() .map(|(hwnd, origin)| { std::thread::spawn(move || { - let rect = WindowsApi::window_rect(hwnd).ok()?; + let rect = backend().frame(WindowId::from_hwnd(hwnd)).ok()?; // the picture is taken before the window is touched match GhostWindow::create(hwnd, origin, None) { @@ -897,7 +901,7 @@ impl WindowManager { return Ok(()); } - let now = WindowsApi::window_rect(kept.hwnd)?; + let now = backend().frame(WindowId::from_hwnd(kept.hwnd))?; // a window moved by its title bar changes no tile until it is let go, // and a drag that has gone back to where it began is a step that puts @@ -1032,7 +1036,7 @@ impl WindowManager { continue; } - let Ok(rect) = WindowsApi::window_rect(window.hwnd) else { + let Ok(rect) = backend().frame(WindowId::from_hwnd(window.hwnd)) else { continue; }; diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 945c70ae..6e63886e 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -12,6 +12,9 @@ use crate::border_manager::BORDER_ENABLED; use crate::border_manager::BORDER_OFFSET; use crate::border_manager::BORDER_WIDTH; use crate::core::Rect; +use crate::windows_backend::backend; +use komorebi_backend::MonitorId; +use komorebi_backend::WindowId; use crate::DEFAULT_CONTAINER_PADDING; use crate::DEFAULT_WORKSPACE_PADDING; @@ -27,10 +30,28 @@ use crate::workspace::Workspace; use crate::workspace::WorkspaceGlobals; use crate::workspace::WorkspaceLayer; +/// `Monitor::id` is a `MonitorId` in Rust and the same plain JSON number as the `isize` handle it +/// was before: `komorebic state` and the saved state files do not change. +mod hmonitor_json { + use komorebi_backend::MonitorId; + use serde::Deserialize; + use serde::Deserializer; + use serde::Serializer; + + pub fn serialize(id: &MonitorId, serializer: S) -> Result { + serializer.serialize_i64(id.to_hmonitor() as i64) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Ok(MonitorId::from_hmonitor(isize::deserialize(deserializer)?)) + } +} #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Monitor { - pub id: isize, + #[serde(with = "hmonitor_json")] + #[cfg_attr(feature = "schemars", schemars(with = "isize"))] + pub id: MonitorId, pub name: String, pub device: String, pub device_id: String, @@ -65,7 +86,7 @@ pub struct MonitorInformation { impl From<&Monitor> for MonitorInformation { fn from(monitor: &Monitor) -> Self { Self { - id: monitor.id, + id: monitor.id.to_hmonitor(), name: monitor.name.clone(), device: monitor.device.clone(), device_id: monitor.device_id.clone(), @@ -88,7 +109,7 @@ pub fn new( workspaces.elements_mut().push_back(Workspace::default()); Monitor { - id, + id: MonitorId::from_hmonitor(id), name, device, device_id, @@ -131,7 +152,7 @@ impl Monitor { pub fn placeholder() -> Self { Self { - id: 0, + id: MonitorId(0), name: "PLACEHOLDER".to_string(), device: "".to_string(), device_id: "".to_string(), @@ -169,7 +190,7 @@ impl Monitor { pub fn load_focused_workspace(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> { let focused_idx = self.focused_workspace_idx(); - let hmonitor = self.id; + let hmonitor = self.id.to_hmonitor(); let monitor_wp = self.wallpaper.clone(); for (i, workspace) in self.workspaces_mut().iter_mut().enumerate() { if i == focused_idx { @@ -438,7 +459,7 @@ impl Monitor { } for window in target_workspace.floating_windows_mut() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } target_workspace.reintegrate_monocle_container()?; @@ -819,4 +840,65 @@ mod tests { m.ensure_workspace_count(3); assert_eq!(m.workspaces().len(), 5, "Monitor should have 5 workspaces"); } + + /// The monitor object of a real `komorebic state` capture (e2e/lib/tests/fixtures/kfw-tiled.json, + /// workspaces emptied): the JSON a Monitor reads and writes. Pins the representation of `id` (a + /// plain number) and `serial_number_id` (null or a string) so that changing their Rust types + /// cannot change the state JSON. + const MONITOR_JSON: &str = r#"{ + "id": 65537, + "name": "DISPLAY1", + "device": "Default_Monitor", + "device_id": "Default_Monitor-4&183790ca&0&UID0", + "serial_number_id": null, + "size": { "left": 0, "top": 0, "right": 1280, "bottom": 800 }, + "work_area_size": { "left": 0, "top": 0, "right": 1280, "bottom": 752 }, + "work_area_offset": null, + "window_based_work_area_offset": null, + "window_based_work_area_offset_limit": 1, + "workspaces": { "elements": [], "focused": 0 }, + "workspace_names": {}, + "container_padding": null, + "workspace_padding": null, + "wallpaper": null, + "floating_layer_behaviour": null + }"#; + + #[test] + fn a_monitor_serializes_to_the_json_of_the_state_capture() { + let expected: serde_json::Value = serde_json::from_str(MONITOR_JSON).unwrap(); + let monitor: Monitor = serde_json::from_value(expected.clone()).unwrap(); + + assert_eq!(serde_json::to_value(&monitor).unwrap(), expected); + } + + #[test] + fn a_monitor_id_and_serial_are_plain_json_values() { + for id in [0, 1, 65537, isize::MAX, -1, isize::MIN] { + let mut value: serde_json::Value = serde_json::from_str(MONITOR_JSON).unwrap(); + value["id"] = serde_json::json!(id); + value["serial_number_id"] = serde_json::json!("ABC123"); + + let monitor: Monitor = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(serde_json::to_value(&monitor).unwrap(), value, "id {id}"); + } + } + + #[test] + fn monitor_information_has_the_documented_fields() { + let monitor: Monitor = serde_json::from_str(MONITOR_JSON).unwrap(); + let value = serde_json::to_value(MonitorInformation::from(&monitor)).unwrap(); + + assert_eq!( + value, + serde_json::json!({ + "id": 65537, + "name": "DISPLAY1", + "device": "Default_Monitor", + "device_id": "Default_Monitor-4&183790ca&0&UID0", + "serial_number_id": null, + "size": { "left": 0, "top": 0, "right": 1280, "bottom": 800 } + }) + ); + } } diff --git a/komorebi/src/monitor_reconciliator/mod.rs b/komorebi/src/monitor_reconciliator/mod.rs index bb00eacb..0974a667 100644 --- a/komorebi/src/monitor_reconciliator/mod.rs +++ b/komorebi/src/monitor_reconciliator/mod.rs @@ -15,9 +15,11 @@ use crate::monitor::Monitor; use crate::monitor_reconciliator::hidden::Hidden; use crate::notify_subscribers; use crate::state::State; +use crate::windows_backend::backend; use crossbeam_channel::Receiver; use crossbeam_channel::Sender; use crossbeam_utils::atomic::AtomicConsume; +use komorebi_backend::WindowId; use parking_lot::Mutex; use serde::Deserialize; use serde::Serialize; @@ -291,7 +293,7 @@ where let mut should_update = false; // Update work areas as necessary - if let Ok(reference) = WindowsApi::monitor(monitor.id) + if let Ok(reference) = WindowsApi::monitor(monitor.id.to_hmonitor()) && reference.work_area_size != monitor.work_area_size { monitor.work_area_size = Rect { @@ -323,7 +325,7 @@ where let mut should_update = false; // Update sizes and work areas as necessary - if let Ok(reference) = WindowsApi::monitor(monitor.id) { + if let Ok(reference) = WindowsApi::monitor(monitor.id.to_hmonitor()) { if reference.work_area_size != monitor.work_area_size { monitor.work_area_size = Rect { left: reference.work_area_size.left, @@ -593,7 +595,8 @@ where // Minimize the focused window since Windows might try // to move it to another monitor if it was focused. if window.is_focused() { - window.minimize(); + let _ = backend() + .minimize(WindowId::from_hwnd(window.hwnd)); } } } @@ -604,7 +607,8 @@ where // Minimize the focused window since Windows might try // to move it to another monitor if it was focused. if maximized.is_focused() { - maximized.minimize(); + let _ = + backend().minimize(WindowId::from_hwnd(maximized.hwnd)); } } @@ -616,7 +620,8 @@ where // Minimize the focused window since Windows might try // to move it to another monitor if it was focused. if window.is_focused() { - window.minimize(); + let _ = backend() + .minimize(WindowId::from_hwnd(window.hwnd)); } } } @@ -626,7 +631,8 @@ where // Minimize the focused window since Windows might try // to move it to another monitor if it was focused. if window.is_focused() { - window.minimize(); + let _ = + backend().minimize(WindowId::from_hwnd(window.hwnd)); } } } @@ -1269,7 +1275,7 @@ mod tests { assert_eq!(monitors.len(), 1, "Expected one monitor"); // hmonitor - assert_eq!(monitors[0].id, 1); + assert_eq!(monitors[0].id.to_hmonitor(), 1); // device name assert_eq!(monitors[0].name, String::from("DISPLAY1")); diff --git a/komorebi/src/pan.rs b/komorebi/src/pan.rs index 48e85eb6..d835cde5 100644 --- a/komorebi/src/pan.rs +++ b/komorebi/src/pan.rs @@ -12,8 +12,9 @@ use crate::core::Rect; use crate::live_resize; use crate::live_resize::Snapping; use crate::window_manager::WindowManager; -use crate::windows_api::WindowsApi; +use crate::windows_backend::backend; use color_eyre::eyre; +use komorebi_backend::WindowId; use komorebi_scrolling::ScrollingSpace; use komorebi_scrolling::SwipeTracker; use parking_lot::Mutex; @@ -97,7 +98,7 @@ impl WindowManager { let work_area = self.focused_monitor_work_area()?; let workspace = self.focused_workspace()?; let near: Vec<_> = origins(&workspace.scrolling_lefts(), |hwnd| { - WindowsApi::window_rect(hwnd).ok() + backend().frame(WindowId::from_hwnd(hwnd)).ok() }) .into_iter() .filter(|(_, origin)| live_resize::is_near(origin, &work_area)) diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 7362499b..61b9372b 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -60,6 +60,7 @@ use crate::config_generation::WorkspaceMatchingRule; use crate::core::ApplicationIdentifier; use crate::core::Axis; use crate::core::BorderImplementation; +use crate::core::CycleDirection; use crate::core::FocusFollowsMouseImplementation; use crate::core::Layout; use crate::core::LayoutOptions; @@ -93,9 +94,11 @@ use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; use crate::windows_api::WindowsApi; +use crate::windows_backend::backend; use crate::winevent_listener; use crate::workspace::WorkspaceLayer; use crate::workspace::WorkspaceWindowLocation; +use komorebi_backend::WindowId; use stackbar_manager::STACKBAR_FOCUSED_TEXT_COLOUR; use stackbar_manager::STACKBAR_LABEL; use stackbar_manager::STACKBAR_MODE; @@ -240,78 +243,7 @@ impl WindowManager { self.promote_container_to_front()? } SocketMessage::EagerFocus(ref exe) => { - let focused_monitor_idx = self.focused_monitor_idx(); - - let mut window_location = None; - let mut monitor_to_focus = None; - let mut needs_workspace_loading = false; - - 'search: for (monitor_idx, monitor) in self.monitors_mut().iter_mut().enumerate() { - for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { - if let Some(location) = workspace.location_from_exe(exe) { - window_location = Some(location); - - if monitor_idx != focused_monitor_idx { - monitor_to_focus = Some(monitor_idx); - } - - // Focus workspace if it is not already the focused one, without - // loading it so that we don't give focus to the wrong window, we will - // load it later after focusing the wanted window - let focused_ws_idx = monitor.focused_workspace_idx(); - if focused_ws_idx != workspace_idx { - monitor.last_focused_workspace = Option::from(focused_ws_idx); - monitor.focus_workspace(workspace_idx)?; - needs_workspace_loading = true; - } - - break 'search; - } - } - } - - if let Some(monitor_idx) = monitor_to_focus { - self.focus_monitor(monitor_idx)?; - } - - if let Some(location) = window_location { - match location { - WorkspaceWindowLocation::Monocle(window_idx) => { - self.focus_container_window(window_idx)?; - } - WorkspaceWindowLocation::Maximized => { - if let Some(window) = - &mut self.focused_workspace_mut()?.maximized_window - { - window.focus(self.mouse_follows_focus)?; - } - } - WorkspaceWindowLocation::Container(container_idx, window_idx) => { - let focused_container_idx = self.focused_container_idx()?; - if container_idx != focused_container_idx { - self.focused_workspace_mut()?.focus_container(container_idx); - } - - self.focus_container_window(window_idx)?; - } - WorkspaceWindowLocation::Floating(window_idx) => { - if let Some(window) = self - .focused_workspace_mut()? - .floating_windows_mut() - .get_mut(window_idx) - { - window.focus(self.mouse_follows_focus)?; - } - } - } - - if needs_workspace_loading { - let mouse_follows_focus = self.mouse_follows_focus; - if let Some(monitor) = self.focused_monitor_mut() { - monitor.load_focused_workspace(mouse_follows_focus)?; - } - } - } + self.eager_focus(exe)?; } SocketMessage::FocusWindow(direction) => { let focused_workspace = self.focused_workspace()?; @@ -393,15 +325,16 @@ impl WindowManager { } SocketMessage::ForceFocus => { let focused_window = self.focused_window()?; - let focused_window_rect = WindowsApi::window_rect(focused_window.hwnd)?; + let focused_window_rect = + backend().frame(WindowId::from_hwnd(focused_window.hwnd))?; WindowsApi::center_cursor_in_rect(&focused_window_rect)?; WindowsApi::left_click(); } SocketMessage::Close => { - Window::from(WindowsApi::foreground_window()?).close()?; + backend().close(WindowId::from_hwnd(WindowsApi::foreground_window()?))?; } SocketMessage::Minimize => { - Window::from(WindowsApi::foreground_window()?).minimize(); + let _ = backend().minimize(WindowId::from_hwnd(WindowsApi::foreground_window()?)); } SocketMessage::LockMonitorWorkspaceContainer( monitor_idx, @@ -575,36 +508,7 @@ impl WindowManager { push_simple_rule(&mut manage_identifiers, identifier, id); } SocketMessage::SessionFloatRule => { - let foreground_window = WindowsApi::foreground_window()?; - let window = Window::from(foreground_window); - if let (Ok(exe), Ok(title), Ok(class)) = - (window.exe(), window.title(), window.class()) - { - let rule = MatchingRule::Composite(vec![ - IdWithIdentifier { - kind: ApplicationIdentifier::Exe, - id: exe, - matching_strategy: Option::from(MatchingStrategy::Equals), - }, - IdWithIdentifier { - kind: ApplicationIdentifier::Title, - id: title, - matching_strategy: Option::from(MatchingStrategy::Equals), - }, - IdWithIdentifier { - kind: ApplicationIdentifier::Class, - id: class, - matching_strategy: Option::from(MatchingStrategy::Equals), - }, - ]); - - let mut floating_applications = FLOATING_APPLICATIONS.lock(); - floating_applications.push(rule.clone()); - let mut session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); - session_floating_applications.push(rule.clone()); - - self.toggle_float(true)?; - } + self.add_session_float_rule()?; } SocketMessage::SessionFloatRules => { let session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); @@ -622,59 +526,7 @@ impl WindowManager { session_floating_applications.clear() } SocketMessage::IgnoreRule(identifier, ref id) => { - let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); - - push_simple_rule(&mut ignore_identifiers, identifier, id); - - let offset = self.work_area_offset; - - let mut hwnds_to_purge = vec![]; - for (i, monitor) in self.monitors().iter().enumerate() { - for container in monitor - .focused_workspace() - .ok_or_eyre("there is no workspace")? - .containers() - { - for window in container.windows() { - match identifier { - ApplicationIdentifier::Path => { - if window.path()? == *id { - hwnds_to_purge.push((i, window.hwnd)); - } - } - ApplicationIdentifier::Exe => { - if window.exe()? == *id { - hwnds_to_purge.push((i, window.hwnd)); - } - } - ApplicationIdentifier::Class => { - if window.class()? == *id { - hwnds_to_purge.push((i, window.hwnd)); - } - } - ApplicationIdentifier::Title => { - if window.title()? == *id { - hwnds_to_purge.push((i, window.hwnd)); - } - } - } - } - } - } - - for (monitor_idx, hwnd) in hwnds_to_purge { - let monitor = self - .monitors_mut() - .get_mut(monitor_idx) - .ok_or_eyre("there is no monitor")?; - - monitor - .focused_workspace_mut() - .ok_or_eyre("there is no focused workspace")? - .remove_window(hwnd)?; - - monitor.update_focused_workspace(offset)?; - } + self.add_ignore_rule(identifier, id)?; } SocketMessage::FocusedWorkspaceContainerPadding(adjustment) => { let focused_monitor_idx = self.focused_monitor_idx(); @@ -701,59 +553,10 @@ impl WindowManager { self.adjust_workspace_padding(sizing, adjustment)?; } SocketMessage::MoveContainerToLastWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.move_container_to_workspace(last_focused_workspace, true, None)?; - } - - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); + self.move_container_to_last_workspace(true)?; } SocketMessage::SendContainerToLastWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.move_container_to_workspace(last_focused_workspace, false, None)?; - } - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); + self.move_container_to_last_workspace(false)?; } SocketMessage::MoveContainerToWorkspaceNumber(workspace_idx) => { self.move_container_to_workspace(workspace_idx, true, None)?; @@ -955,27 +758,7 @@ impl WindowManager { SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, SocketMessage::CycleLayout(direction) => self.cycle_layout(direction)?, SocketMessage::LayoutRatios(ref columns, ref rows) => { - use crate::core::validate_ratios; - - let focused_workspace = self.focused_workspace_mut()?; - - let mut options = focused_workspace.layout_options.unwrap_or(LayoutOptions { - scrolling: None, - grid: None, - column_ratios: None, - row_ratios: None, - }); - - if let Some(cols) = columns { - options.column_ratios = Some(validate_ratios(cols)); - } - - if let Some(rws) = rows { - options.row_ratios = Some(validate_ratios(rws)); - } - - focused_workspace.layout_options = Some(options); - self.update_focused_workspace(false, false)?; + self.set_layout_ratios(columns, rows)?; } SocketMessage::ChangeLayoutCustom(ref path) => { self.change_workspace_custom_layout(path)?; @@ -1075,142 +858,16 @@ impl WindowManager { } } SocketMessage::CycleFocusWorkspace(direction) => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; - - let focused_workspace_idx = focused_monitor.focused_workspace_idx(); - let workspaces = focused_monitor.workspaces().len(); - - let workspace_idx = direction.next_idx( - focused_workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - - self.focus_workspace(workspace_idx)?; + self.cycle_focus_workspace(direction)?; } SocketMessage::CycleFocusEmptyWorkspace(direction) => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; - - let focused_workspace_idx = focused_monitor.focused_workspace_idx(); - let workspaces = focused_monitor.workspaces().len(); - - let mut empty_workspaces = vec![]; - - for (idx, w) in focused_monitor.workspaces().iter().enumerate() { - if w.is_empty() { - empty_workspaces.push(idx); - } - } - - if !empty_workspaces.is_empty() { - let mut workspace_idx = direction.next_idx( - focused_workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - - while !empty_workspaces.contains(&workspace_idx) { - workspace_idx = direction.next_idx( - workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - } - - self.focus_workspace(workspace_idx)?; - } + self.cycle_focus_empty_workspace(direction)?; } SocketMessage::CloseWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let mut can_close = false; - - if let Some(monitor) = self.focused_monitor_mut() { - let focused_workspace_idx = monitor.focused_workspace_idx(); - let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); - - if let Some(workspace) = monitor.focused_workspace() - && monitor.workspaces().len() > 1 - && workspace.containers().is_empty() - && workspace.floating_windows().is_empty() - && workspace.monocle_container.is_none() - && workspace.maximized_window.is_none() - && workspace.name.is_none() - { - can_close = true; - } - - if can_close - && monitor - .workspaces_mut() - .remove(focused_workspace_idx) - .is_some() - { - self.focus_workspace(next_focused_workspace_idx)?; - } - } + self.close_workspace()?; } SocketMessage::FocusLastWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.focus_workspace(last_focused_workspace)?; - } - - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); + self.focus_last_workspace()?; } SocketMessage::FocusWorkspaceNumber(workspace_idx) => { // This is to ensure that even on an empty workspace on a secondary monitor, the @@ -1230,28 +887,7 @@ impl WindowManager { } } SocketMessage::FocusWorkspaceNumbers(workspace_idx) => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let focused_monitor_idx = self.focused_monitor_idx(); - - for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { - if i != focused_monitor_idx { - monitor.focus_workspace(workspace_idx)?; - monitor.load_focused_workspace(false)?; - } - } - - self.focus_workspace(workspace_idx)?; + self.focus_workspace_numbers(workspace_idx)?; } SocketMessage::FocusMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { let focused_monitor_idx = self.focused_monitor_idx(); @@ -1273,101 +909,7 @@ impl WindowManager { } } SocketMessage::ToggleWorkspaceLayer => { - let mouse_follows_focus = self.mouse_follows_focus; - let workspace = self.focused_workspace_mut()?; - - let mut to_focus = None; - match workspace.layer { - WorkspaceLayer::Tiling => { - workspace.layer = WorkspaceLayer::Floating; - - let focused_idx = workspace.focused_floating_window_idx(); - let mut window_idx_pairs = workspace - .floating_windows_mut() - .make_contiguous() - .iter() - .enumerate() - .collect::>(); - - // Sort by window area - window_idx_pairs.sort_by_key(|(_, w)| { - let rect = WindowsApi::window_rect(w.hwnd).unwrap_or_default(); - rect.right * rect.bottom - }); - window_idx_pairs.reverse(); - - for (i, window) in window_idx_pairs { - if i == focused_idx { - to_focus = Some(*window); - } else { - window.restore(); - window.raise()?; - } - } - - if let Some(focused_window) = &to_focus { - // The focused window should be the last one raised to make sure it is - // on top - focused_window.restore(); - focused_window.raise()?; - } - - for container in workspace.containers() { - if let Some(window) = container.focused_window() { - window.lower()?; - } - } - - if let Some(monocle) = &workspace.monocle_container - && let Some(window) = monocle.focused_window() - { - window.lower()?; - } - } - WorkspaceLayer::Floating => { - workspace.layer = WorkspaceLayer::Tiling; - - if let Some(monocle) = &workspace.monocle_container { - if let Some(window) = monocle.focused_window() { - to_focus = Some(*window); - window.raise()?; - } - for window in workspace.floating_windows() { - window.hide(); - } - } else { - let focused_container_idx = workspace.focused_container_idx(); - for (i, container) in workspace.containers_mut().iter_mut().enumerate() - { - if let Some(window) = container.focused_window() { - if i == focused_container_idx { - to_focus = Some(*window); - } - window.raise()?; - } - } - - let mut window_idx_pairs = workspace - .floating_windows_mut() - .make_contiguous() - .iter() - .collect::>(); - - // Sort by window area - window_idx_pairs.sort_by_key(|w| { - let rect = WindowsApi::window_rect(w.hwnd).unwrap_or_default(); - rect.right * rect.bottom - }); - - for window in window_idx_pairs { - window.lower()?; - } - } - } - }; - if let Some(window) = to_focus { - window.focus(mouse_follows_focus)?; - } + self.toggle_workspace_layer()?; } SocketMessage::Stop => { self.stop(false)?; @@ -1456,358 +998,27 @@ impl WindowManager { reply.write_all(monitors_state.as_bytes())?; } SocketMessage::Query(query) => { - let response = match query { - StateQuery::FocusedMonitorIndex => self.focused_monitor_idx().to_string(), - StateQuery::FocusedWorkspaceIndex => self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx() - .to_string(), - StateQuery::FocusedContainerIndex => self - .focused_workspace()? - .focused_container_idx() - .to_string(), - StateQuery::FocusedWindowIndex => { - self.focused_container()?.focused_window_idx().to_string() - } - StateQuery::FocusedWorkspaceName => { - let focused_monitor = - self.focused_monitor().ok_or_eyre("there is no monitor")?; - - focused_monitor - .focused_workspace_name() - .unwrap_or_else(|| focused_monitor.focused_workspace_idx().to_string()) - } - StateQuery::Version => build::RUST_VERSION.to_string(), - StateQuery::FocusedWorkspaceLayout => { - let focused_monitor = - self.focused_monitor().ok_or_eyre("there is no monitor")?; - - focused_monitor.focused_workspace_layout().map_or_else( - || "None".to_string(), - |layout| match layout { - Layout::Default(default_layout) => default_layout.to_string(), - Layout::Custom(_) => "Custom".to_string(), - }, - ) - } - StateQuery::FocusedContainerKind => { - match self.focused_workspace()?.focused_container() { - None => "None".to_string(), - Some(container) => { - if container.windows().len() > 1 { - "Stack".to_string() - } else { - "Single".to_string() - } - } - } - } - }; - - reply.write_all(response.as_bytes())?; + self.answer_query(query, &mut reply)?; } SocketMessage::ResizeWindowEdge(direction, sizing) => { let _in_place = live_resize::InPlace::new(); self.resize_window(direction, sizing, self.resize_delta, true)?; } SocketMessage::ResizeWindowAxis(axis, sizing) => { - let _in_place = live_resize::InPlace::new(); - - // If the user has a custom layout, allow for the resizing of the primary column - // with this signal - let workspace = self.focused_workspace_mut()?; - let container_len = workspace.containers().len(); - let no_layout_rules = workspace.layout_rules.is_empty(); - - if let Layout::Custom(custom) = &mut workspace.layout { - if matches!(axis, Axis::Horizontal) { - #[allow(clippy::cast_precision_loss)] - let percentage = custom - .primary_width_percentage() - .unwrap_or(100.0 / (custom.len() as f32)); - - if no_layout_rules { - match sizing { - Sizing::Increase => { - custom.set_primary_width_percentage(percentage + 5.0); - } - Sizing::Decrease => { - custom.set_primary_width_percentage(percentage - 5.0); - } - } - } else { - for rule in &mut workspace.layout_rules { - if container_len >= rule.0 - && let Layout::Custom(ref mut custom) = rule.1 - { - match sizing { - Sizing::Increase => { - custom.set_primary_width_percentage(percentage + 5.0); - } - Sizing::Decrease => { - custom.set_primary_width_percentage(percentage - 5.0); - } - } - } - } - } - } - // Otherwise proceed with the resizing logic for individual window containers in the - // assumed BSP layout - } else { - match axis { - Axis::Horizontal => { - self.resize_window( - OperationDirection::Left, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Right, - sizing, - self.resize_delta, - false, - )?; - } - Axis::Vertical => { - self.resize_window( - OperationDirection::Up, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Down, - sizing, - self.resize_delta, - false, - )?; - } - Axis::HorizontalAndVertical => { - self.resize_window( - OperationDirection::Left, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Right, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Up, - sizing, - self.resize_delta, - false, - )?; - self.resize_window( - OperationDirection::Down, - sizing, - self.resize_delta, - false, - )?; - } - } - } - - self.update_focused_workspace(false, false)?; + self.resize_window_axis(axis, sizing)?; } - SocketMessage::FocusFollowsMouse(mut implementation, enable) => { - if !CUSTOM_FFM.load(Ordering::SeqCst) { - tracing::warn!( - "komorebi was not started with the --ffm flag, so the komorebi implementation of focus follows mouse cannot be enabled; defaulting to windows implementation" - ); - implementation = FocusFollowsMouseImplementation::Windows; - } - - match implementation { - FocusFollowsMouseImplementation::Komorebi => { - if WindowsApi::focus_follows_mouse()? { - tracing::warn!( - "the komorebi implementation of focus follows mouse cannot be enabled while the windows implementation is enabled" - ); - } else if enable { - self.focus_follows_mouse = Option::from(implementation); - } else { - self.focus_follows_mouse = None; - self.has_pending_raise_op = false; - } - } - FocusFollowsMouseImplementation::Windows => { - if matches!( - self.focus_follows_mouse, - Some(FocusFollowsMouseImplementation::Komorebi) - ) { - tracing::warn!( - "the windows implementation of focus follows mouse cannot be enabled while the komorebi implementation is enabled" - ); - } else if enable { - WindowsApi::enable_focus_follows_mouse()?; - self.focus_follows_mouse = - Option::from(FocusFollowsMouseImplementation::Windows); - } else { - WindowsApi::disable_focus_follows_mouse()?; - self.focus_follows_mouse = None; - } - } - } + SocketMessage::FocusFollowsMouse(implementation, enable) => { + self.focus_follows_mouse(implementation, enable)?; } - SocketMessage::ToggleFocusFollowsMouse(mut implementation) => { - if !CUSTOM_FFM.load(Ordering::SeqCst) { - tracing::warn!( - "komorebi was not started with the --ffm flag, so the komorebi implementation of focus follows mouse cannot be toggled; defaulting to windows implementation" - ); - implementation = FocusFollowsMouseImplementation::Windows; - } - - match implementation { - FocusFollowsMouseImplementation::Komorebi => { - if WindowsApi::focus_follows_mouse()? { - tracing::warn!( - "the komorebi implementation of focus follows mouse cannot be toggled while the windows implementation is enabled" - ); - } else { - match self.focus_follows_mouse { - None => { - self.focus_follows_mouse = Option::from(implementation); - self.has_pending_raise_op = false; - } - Some(FocusFollowsMouseImplementation::Komorebi) => { - self.focus_follows_mouse = None; - } - Some(FocusFollowsMouseImplementation::Windows) => { - tracing::warn!( - "ignoring command that could mix different focus follows mouse implementations" - ); - } - } - } - } - FocusFollowsMouseImplementation::Windows => { - if matches!( - self.focus_follows_mouse, - Some(FocusFollowsMouseImplementation::Komorebi) - ) { - tracing::warn!( - "the windows implementation of focus follows mouse cannot be toggled while the komorebi implementation is enabled" - ); - } else { - match self.focus_follows_mouse { - None => { - WindowsApi::enable_focus_follows_mouse()?; - self.focus_follows_mouse = Option::from(implementation); - } - Some(FocusFollowsMouseImplementation::Windows) => { - WindowsApi::disable_focus_follows_mouse()?; - self.focus_follows_mouse = None; - } - Some(FocusFollowsMouseImplementation::Komorebi) => { - tracing::warn!( - "ignoring command that could mix different focus follows mouse implementations" - ); - } - } - } - } - } + SocketMessage::ToggleFocusFollowsMouse(implementation) => { + self.toggle_focus_follows_mouse(implementation)?; } SocketMessage::ReloadConfiguration => { Self::reload_configuration(); force_update_borders = true; } SocketMessage::ReplaceConfiguration(ref config) => { - // Check that this is a valid static config file first - if StaticConfig::read(config).is_ok() { - // Clear workspace rules; these will need to be replaced - WORKSPACE_MATCHING_RULES.lock().clear(); - // Pause so that restored windows come to the foreground from all workspaces - self.is_paused = true; - // Bring all windows to the foreground - self.restore_all_windows(false)?; - - // Create a new wm from the config path - let mut wm = StaticConfig::preload( - config, - winevent_listener::event_rx(), - self.command_listener.try_clone().ok(), - )?; - - // Initialize the new wm - wm.init()?; - - wm.restore_all_windows(true)?; - - // This is equivalent to StaticConfig::postload for this use case - StaticConfig::reload(config, &mut wm)?; - - // Set self to the new wm instance - *self = wm; - - // check if there are any bars - let mut system = sysinfo::System::new_all(); - system.refresh_processes(sysinfo::ProcessesToUpdate::All, true); - - let has_bar = system - .processes_by_name("komorebi-bar.exe".as_ref()) - .next() - .is_some(); - - // stop bar(s) - if has_bar { - let script = r" -Stop-Process -Name:komorebi-bar -ErrorAction SilentlyContinue - "; - match powershell_script::run(script) { - Ok(_) => { - println!("{script}"); - - // start new bar(s) - let mut config = StaticConfig::read(config)?; - if let Some(display_bar_configurations) = - &mut config.bar_configurations - { - for config_file_path in &mut *display_bar_configurations { - let script = r#"Start-Process "komorebi-bar" '"--config" "CONFIGFILE"' -WindowStyle hidden"# - .replace("CONFIGFILE", &config_file_path.to_string_lossy()); - - match powershell_script::run(&script) { - Ok(_) => { - println!("{script}"); - } - Err(error) => { - println!("Error: {error}"); - } - } - } - } else { - let script = r" -if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) -{ - Start-Process komorebi-bar -WindowStyle hidden -} - "; - match powershell_script::run(script) { - Ok(_) => { - println!("{script}"); - } - Err(error) => { - println!("Error: {error}"); - } - } - } - } - Err(error) => { - println!("Error: {error}"); - } - } - } - - force_update_borders = true; - } + force_update_borders = self.replace_configuration(config)?; } SocketMessage::ReloadStaticConfiguration(ref pathbuf) => { self.reload_static_configuration(pathbuf)?; @@ -2069,27 +1280,7 @@ if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) } } SocketMessage::BorderColour(kind, r, g, b) => { - match kind { - WindowKind::Single => { - border_manager::FOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Stack => { - border_manager::STACK.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Monocle => { - border_manager::MONOCLE.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Unfocused => { - border_manager::UNFOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::UnfocusedLocked => { - border_manager::UNFOCUSED_LOCKED - .store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Floating => { - border_manager::FLOATING.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - } + self.set_border_colour(kind, r, g, b); force_update_borders = true; } SocketMessage::BorderStyle(style) => { @@ -2283,10 +1474,7 @@ if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) } } -pub fn read_commands_uds( - wm: &Arc>, - stream: UnixStream, -) -> eyre::Result<()> { +pub fn read_commands_uds(wm: &Arc>, stream: UnixStream) -> eyre::Result<()> { komorebi_transport::read_commands::(wm, stream, &WindowsConnectionPolicy) } @@ -2350,6 +1538,863 @@ fn push_simple_rule(rules: &mut Vec, kind: ApplicationIdentifier, } } +// extracted-arms-impl +impl WindowManager { + pub fn set_border_colour(&mut self, kind: WindowKind, r: u32, g: u32, b: u32) { + match kind { + WindowKind::Single => { + border_manager::FOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Stack => { + border_manager::STACK.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Monocle => { + border_manager::MONOCLE.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Unfocused => { + border_manager::UNFOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::UnfocusedLocked => { + border_manager::UNFOCUSED_LOCKED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Floating => { + border_manager::FLOATING.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + } + } + + pub fn replace_configuration(&mut self, config: &std::path::PathBuf) -> eyre::Result { + let mut force_update_borders = false; + // Check that this is a valid static config file first + if StaticConfig::read(config).is_ok() { + // Clear workspace rules; these will need to be replaced + WORKSPACE_MATCHING_RULES.lock().clear(); + // Pause so that restored windows come to the foreground from all workspaces + self.is_paused = true; + // Bring all windows to the foreground + self.restore_all_windows(false)?; + + // Create a new wm from the config path + let mut wm = StaticConfig::preload( + config, + winevent_listener::event_rx(), + self.command_listener.try_clone().ok(), + )?; + + // Initialize the new wm + wm.init()?; + + wm.restore_all_windows(true)?; + + // This is equivalent to StaticConfig::postload for this use case + StaticConfig::reload(config, &mut wm)?; + + // Set self to the new wm instance + *self = wm; + + // check if there are any bars + let mut system = sysinfo::System::new_all(); + system.refresh_processes(sysinfo::ProcessesToUpdate::All, true); + + let has_bar = system + .processes_by_name("komorebi-bar.exe".as_ref()) + .next() + .is_some(); + + // stop bar(s) + if has_bar { + let script = r" +Stop-Process -Name:komorebi-bar -ErrorAction SilentlyContinue + "; + match powershell_script::run(script) { + Ok(_) => { + println!("{script}"); + + // start new bar(s) + let mut config = StaticConfig::read(config)?; + if let Some(display_bar_configurations) = &mut config.bar_configurations { + for config_file_path in &mut *display_bar_configurations { + let script = r#"Start-Process "komorebi-bar" '"--config" "CONFIGFILE"' -WindowStyle hidden"# + .replace("CONFIGFILE", &config_file_path.to_string_lossy()); + + match powershell_script::run(&script) { + Ok(_) => { + println!("{script}"); + } + Err(error) => { + println!("Error: {error}"); + } + } + } + } else { + let script = r" +if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) +{ + Start-Process komorebi-bar -WindowStyle hidden +} + "; + match powershell_script::run(script) { + Ok(_) => { + println!("{script}"); + } + Err(error) => { + println!("Error: {error}"); + } + } + } + } + Err(error) => { + println!("Error: {error}"); + } + } + } + + force_update_borders = true; + } + Ok(force_update_borders) + } + + pub fn answer_query( + &mut self, + query: StateQuery, + mut reply: impl std::io::Write, + ) -> eyre::Result<()> { + let response = match query { + StateQuery::FocusedMonitorIndex => self.focused_monitor_idx().to_string(), + StateQuery::FocusedWorkspaceIndex => self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx() + .to_string(), + StateQuery::FocusedContainerIndex => self + .focused_workspace()? + .focused_container_idx() + .to_string(), + StateQuery::FocusedWindowIndex => { + self.focused_container()?.focused_window_idx().to_string() + } + StateQuery::FocusedWorkspaceName => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor + .focused_workspace_name() + .unwrap_or_else(|| focused_monitor.focused_workspace_idx().to_string()) + } + StateQuery::Version => build::RUST_VERSION.to_string(), + StateQuery::FocusedWorkspaceLayout => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor.focused_workspace_layout().map_or_else( + || "None".to_string(), + |layout| match layout { + Layout::Default(default_layout) => default_layout.to_string(), + Layout::Custom(_) => "Custom".to_string(), + }, + ) + } + StateQuery::FocusedContainerKind => { + match self.focused_workspace()?.focused_container() { + None => "None".to_string(), + Some(container) => { + if container.windows().len() > 1 { + "Stack".to_string() + } else { + "Single".to_string() + } + } + } + } + }; + + reply.write_all(response.as_bytes())?; + Ok(()) + } + pub fn focus_follows_mouse( + &mut self, + mut implementation: FocusFollowsMouseImplementation, + enable: bool, + ) -> eyre::Result<()> { + if !CUSTOM_FFM.load(Ordering::SeqCst) { + tracing::warn!( + "komorebi was not started with the --ffm flag, so the komorebi implementation of focus follows mouse cannot be enabled; defaulting to windows implementation" + ); + implementation = FocusFollowsMouseImplementation::Windows; + } + + match implementation { + FocusFollowsMouseImplementation::Komorebi => { + if WindowsApi::focus_follows_mouse()? { + tracing::warn!( + "the komorebi implementation of focus follows mouse cannot be enabled while the windows implementation is enabled" + ); + } else if enable { + self.focus_follows_mouse = Option::from(implementation); + } else { + self.focus_follows_mouse = None; + self.has_pending_raise_op = false; + } + } + FocusFollowsMouseImplementation::Windows => { + if matches!( + self.focus_follows_mouse, + Some(FocusFollowsMouseImplementation::Komorebi) + ) { + tracing::warn!( + "the windows implementation of focus follows mouse cannot be enabled while the komorebi implementation is enabled" + ); + } else if enable { + WindowsApi::enable_focus_follows_mouse()?; + self.focus_follows_mouse = + Option::from(FocusFollowsMouseImplementation::Windows); + } else { + WindowsApi::disable_focus_follows_mouse()?; + self.focus_follows_mouse = None; + } + } + } + Ok(()) + } + + pub fn toggle_focus_follows_mouse( + &mut self, + mut implementation: FocusFollowsMouseImplementation, + ) -> eyre::Result<()> { + if !CUSTOM_FFM.load(Ordering::SeqCst) { + tracing::warn!( + "komorebi was not started with the --ffm flag, so the komorebi implementation of focus follows mouse cannot be toggled; defaulting to windows implementation" + ); + implementation = FocusFollowsMouseImplementation::Windows; + } + + match implementation { + FocusFollowsMouseImplementation::Komorebi => { + if WindowsApi::focus_follows_mouse()? { + tracing::warn!( + "the komorebi implementation of focus follows mouse cannot be toggled while the windows implementation is enabled" + ); + } else { + match self.focus_follows_mouse { + None => { + self.focus_follows_mouse = Option::from(implementation); + self.has_pending_raise_op = false; + } + Some(FocusFollowsMouseImplementation::Komorebi) => { + self.focus_follows_mouse = None; + } + Some(FocusFollowsMouseImplementation::Windows) => { + tracing::warn!( + "ignoring command that could mix different focus follows mouse implementations" + ); + } + } + } + } + FocusFollowsMouseImplementation::Windows => { + if matches!( + self.focus_follows_mouse, + Some(FocusFollowsMouseImplementation::Komorebi) + ) { + tracing::warn!( + "the windows implementation of focus follows mouse cannot be toggled while the komorebi implementation is enabled" + ); + } else { + match self.focus_follows_mouse { + None => { + WindowsApi::enable_focus_follows_mouse()?; + self.focus_follows_mouse = Option::from(implementation); + } + Some(FocusFollowsMouseImplementation::Windows) => { + WindowsApi::disable_focus_follows_mouse()?; + self.focus_follows_mouse = None; + } + Some(FocusFollowsMouseImplementation::Komorebi) => { + tracing::warn!( + "ignoring command that could mix different focus follows mouse implementations" + ); + } + } + } + } + } + Ok(()) + } + + pub fn resize_window_axis(&mut self, axis: Axis, sizing: Sizing) -> eyre::Result<()> { + let _in_place = live_resize::InPlace::new(); + + // If the user has a custom layout, allow for the resizing of the primary column + // with this signal + let workspace = self.focused_workspace_mut()?; + let container_len = workspace.containers().len(); + let no_layout_rules = workspace.layout_rules.is_empty(); + + if let Layout::Custom(custom) = &mut workspace.layout { + if matches!(axis, Axis::Horizontal) { + #[allow(clippy::cast_precision_loss)] + let percentage = custom + .primary_width_percentage() + .unwrap_or(100.0 / (custom.len() as f32)); + + if no_layout_rules { + match sizing { + Sizing::Increase => { + custom.set_primary_width_percentage(percentage + 5.0); + } + Sizing::Decrease => { + custom.set_primary_width_percentage(percentage - 5.0); + } + } + } else { + for rule in &mut workspace.layout_rules { + if container_len >= rule.0 + && let Layout::Custom(ref mut custom) = rule.1 + { + match sizing { + Sizing::Increase => { + custom.set_primary_width_percentage(percentage + 5.0); + } + Sizing::Decrease => { + custom.set_primary_width_percentage(percentage - 5.0); + } + } + } + } + } + } + // Otherwise proceed with the resizing logic for individual window containers in the + // assumed BSP layout + } else { + match axis { + Axis::Horizontal => { + self.resize_window(OperationDirection::Left, sizing, self.resize_delta, false)?; + self.resize_window( + OperationDirection::Right, + sizing, + self.resize_delta, + false, + )?; + } + Axis::Vertical => { + self.resize_window(OperationDirection::Up, sizing, self.resize_delta, false)?; + self.resize_window(OperationDirection::Down, sizing, self.resize_delta, false)?; + } + Axis::HorizontalAndVertical => { + self.resize_window(OperationDirection::Left, sizing, self.resize_delta, false)?; + self.resize_window( + OperationDirection::Right, + sizing, + self.resize_delta, + false, + )?; + self.resize_window(OperationDirection::Up, sizing, self.resize_delta, false)?; + self.resize_window(OperationDirection::Down, sizing, self.resize_delta, false)?; + } + } + } + + self.update_focused_workspace(false, false)?; + Ok(()) + } + + pub fn eager_focus(&mut self, exe: &str) -> eyre::Result<()> { + let focused_monitor_idx = self.focused_monitor_idx(); + + let mut window_location = None; + let mut monitor_to_focus = None; + let mut needs_workspace_loading = false; + + 'search: for (monitor_idx, monitor) in self.monitors_mut().iter_mut().enumerate() { + for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { + if let Some(location) = workspace.location_from_exe(exe) { + window_location = Some(location); + + if monitor_idx != focused_monitor_idx { + monitor_to_focus = Some(monitor_idx); + } + + // Focus workspace if it is not already the focused one, without + // loading it so that we don't give focus to the wrong window, we will + // load it later after focusing the wanted window + let focused_ws_idx = monitor.focused_workspace_idx(); + if focused_ws_idx != workspace_idx { + monitor.last_focused_workspace = Option::from(focused_ws_idx); + monitor.focus_workspace(workspace_idx)?; + needs_workspace_loading = true; + } + + break 'search; + } + } + } + + if let Some(monitor_idx) = monitor_to_focus { + self.focus_monitor(monitor_idx)?; + } + + if let Some(location) = window_location { + match location { + WorkspaceWindowLocation::Monocle(window_idx) => { + self.focus_container_window(window_idx)?; + } + WorkspaceWindowLocation::Maximized => { + if let Some(window) = &mut self.focused_workspace_mut()?.maximized_window { + backend() + .focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; + } + } + WorkspaceWindowLocation::Container(container_idx, window_idx) => { + let focused_container_idx = self.focused_container_idx()?; + if container_idx != focused_container_idx { + self.focused_workspace_mut()?.focus_container(container_idx); + } + + self.focus_container_window(window_idx)?; + } + WorkspaceWindowLocation::Floating(window_idx) => { + if let Some(window) = self + .focused_workspace_mut()? + .floating_windows_mut() + .get_mut(window_idx) + { + backend() + .focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; + } + } + } + + if needs_workspace_loading { + let mouse_follows_focus = self.mouse_follows_focus; + if let Some(monitor) = self.focused_monitor_mut() { + monitor.load_focused_workspace(mouse_follows_focus)?; + } + } + } + Ok(()) + } + pub fn set_layout_ratios( + &mut self, + columns: &Option>, + rows: &Option>, + ) -> eyre::Result<()> { + use crate::core::validate_ratios; + + let focused_workspace = self.focused_workspace_mut()?; + + let mut options = focused_workspace.layout_options.unwrap_or(LayoutOptions { + scrolling: None, + grid: None, + column_ratios: None, + row_ratios: None, + }); + + if let Some(cols) = columns { + options.column_ratios = Some(validate_ratios(cols)); + } + + if let Some(rws) = rows { + options.row_ratios = Some(validate_ratios(rws)); + } + + focused_workspace.layout_options = Some(options); + self.update_focused_workspace(false, false)?; + Ok(()) + } + + pub fn add_session_float_rule(&mut self) -> eyre::Result<()> { + let foreground_window = WindowsApi::foreground_window()?; + let window = Window::from(foreground_window); + if let (Ok(exe), Ok(title), Ok(class)) = (window.exe(), window.title(), window.class()) { + let rule = MatchingRule::Composite(vec![ + IdWithIdentifier { + kind: ApplicationIdentifier::Exe, + id: exe, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + IdWithIdentifier { + kind: ApplicationIdentifier::Title, + id: title, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + IdWithIdentifier { + kind: ApplicationIdentifier::Class, + id: class, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + ]); + + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + floating_applications.push(rule.clone()); + let mut session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); + session_floating_applications.push(rule.clone()); + + self.toggle_float(true)?; + } + Ok(()) + } + + pub fn add_ignore_rule( + &mut self, + identifier: ApplicationIdentifier, + id: &str, + ) -> eyre::Result<()> { + let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + + push_simple_rule(&mut ignore_identifiers, identifier, id); + + let offset = self.work_area_offset; + + let mut hwnds_to_purge = vec![]; + for (i, monitor) in self.monitors().iter().enumerate() { + for container in monitor + .focused_workspace() + .ok_or_eyre("there is no workspace")? + .containers() + { + for window in container.windows() { + match identifier { + ApplicationIdentifier::Path => { + if window.path()? == *id { + hwnds_to_purge.push((i, window.hwnd)); + } + } + ApplicationIdentifier::Exe => { + if window.exe()? == *id { + hwnds_to_purge.push((i, window.hwnd)); + } + } + ApplicationIdentifier::Class => { + if window.class()? == *id { + hwnds_to_purge.push((i, window.hwnd)); + } + } + ApplicationIdentifier::Title => { + if window.title()? == *id { + hwnds_to_purge.push((i, window.hwnd)); + } + } + } + } + } + } + + for (monitor_idx, hwnd) in hwnds_to_purge { + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + monitor + .focused_workspace_mut() + .ok_or_eyre("there is no focused workspace")? + .remove_window(hwnd)?; + + monitor.update_focused_workspace(offset)?; + } + Ok(()) + } + pub fn move_container_to_last_workspace(&mut self, follow: bool) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.move_container_to_workspace(last_focused_workspace, follow, None)?; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + Ok(()) + } + + pub fn focus_workspace_numbers(&mut self, workspace_idx: usize) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let focused_monitor_idx = self.focused_monitor_idx(); + + for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { + if i != focused_monitor_idx { + monitor.focus_workspace(workspace_idx)?; + monitor.load_focused_workspace(false)?; + } + } + + self.focus_workspace(workspace_idx)?; + Ok(()) + } + + pub fn focus_last_workspace(&mut self) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.focus_workspace(last_focused_workspace)?; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + Ok(()) + } + + pub fn close_workspace(&mut self) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let mut can_close = false; + + if let Some(monitor) = self.focused_monitor_mut() { + let focused_workspace_idx = monitor.focused_workspace_idx(); + let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); + + if let Some(workspace) = monitor.focused_workspace() + && monitor.workspaces().len() > 1 + && workspace.containers().is_empty() + && workspace.floating_windows().is_empty() + && workspace.monocle_container.is_none() + && workspace.maximized_window.is_none() + && workspace.name.is_none() + { + can_close = true; + } + + if can_close + && monitor + .workspaces_mut() + .remove(focused_workspace_idx) + .is_some() + { + self.focus_workspace(next_focused_workspace_idx)?; + } + } + Ok(()) + } + + pub fn cycle_focus_empty_workspace(&mut self, direction: CycleDirection) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let mut empty_workspaces = vec![]; + + for (idx, w) in focused_monitor.workspaces().iter().enumerate() { + if w.is_empty() { + empty_workspaces.push(idx); + } + } + + if !empty_workspaces.is_empty() { + let mut workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces).ok_or_eyre("there must be at least one workspace")?, + ); + + while !empty_workspaces.contains(&workspace_idx) { + workspace_idx = direction.next_idx( + workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + } + + self.focus_workspace(workspace_idx)?; + } + Ok(()) + } + + pub fn cycle_focus_workspace(&mut self, direction: CycleDirection) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces).ok_or_eyre("there must be at least one workspace")?, + ); + + self.focus_workspace(workspace_idx)?; + Ok(()) + } + + pub fn toggle_workspace_layer(&mut self) -> eyre::Result<()> { + let mouse_follows_focus = self.mouse_follows_focus; + let workspace = self.focused_workspace_mut()?; + + let mut to_focus = None; + match workspace.layer { + WorkspaceLayer::Tiling => { + workspace.layer = WorkspaceLayer::Floating; + + let focused_idx = workspace.focused_floating_window_idx(); + let mut window_idx_pairs = workspace + .floating_windows_mut() + .make_contiguous() + .iter() + .enumerate() + .collect::>(); + + // Sort by window area + window_idx_pairs.sort_by_key(|(_, w)| { + let rect = backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .unwrap_or_default(); + rect.right * rect.bottom + }); + window_idx_pairs.reverse(); + + for (i, window) in window_idx_pairs { + if i == focused_idx { + to_focus = Some(*window); + } else { + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); + backend().raise(WindowId::from_hwnd(window.hwnd))?; + } + } + + if let Some(focused_window) = &to_focus { + // The focused window should be the last one raised to make sure it is + // on top + let _ = backend().restore(WindowId::from_hwnd(focused_window.hwnd)); + backend().raise(WindowId::from_hwnd(focused_window.hwnd))?; + } + + for container in workspace.containers() { + if let Some(window) = container.focused_window() { + window.lower()?; + } + } + + if let Some(monocle) = &workspace.monocle_container + && let Some(window) = monocle.focused_window() + { + window.lower()?; + } + } + WorkspaceLayer::Floating => { + workspace.layer = WorkspaceLayer::Tiling; + + if let Some(monocle) = &workspace.monocle_container { + if let Some(window) = monocle.focused_window() { + to_focus = Some(*window); + backend().raise(WindowId::from_hwnd(window.hwnd))?; + } + for window in workspace.floating_windows() { + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); + } + } else { + let focused_container_idx = workspace.focused_container_idx(); + for (i, container) in workspace.containers_mut().iter_mut().enumerate() { + if let Some(window) = container.focused_window() { + if i == focused_container_idx { + to_focus = Some(*window); + } + backend().raise(WindowId::from_hwnd(window.hwnd))?; + } + } + + let mut window_idx_pairs = workspace + .floating_windows_mut() + .make_contiguous() + .iter() + .collect::>(); + + // Sort by window area + window_idx_pairs.sort_by_key(|w| { + let rect = backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .unwrap_or_default(); + rect.right * rect.bottom + }); + + for window in window_idx_pairs { + window.lower()?; + } + } + } + }; + if let Some(window) = to_focus { + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; + } + Ok(()) + } +} + #[cfg(test)] mod tests { use super::push_simple_rule; diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 86813656..4aff0d79 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -8,6 +8,8 @@ use parking_lot::Mutex; use crate::core::Rect; use crate::core::WindowContainerBehaviour; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; use crate::CURRENT_VIRTUAL_DESKTOP; use crate::DefaultLayout; @@ -301,7 +303,7 @@ impl WindowManager { match event { WindowManagerEvent::Raise(window) => { - window.focus(false)?; + backend().focus(WindowId::from_hwnd(window.hwnd), false)?; self.has_pending_raise_op = false; } WindowManagerEvent::Destroy(_, window) | WindowManagerEvent::Unmanage(window) => { @@ -435,7 +437,7 @@ impl WindowManager { if let Some(monocle) = &workspace.monocle_container { if let Some(window) = monocle.focused_window() { - window.focus(false)?; + backend().focus(WindowId::from_hwnd(window.hwnd), false)?; } } else { workspace.focus_container_by_window(window.hwnd)?; @@ -509,7 +511,7 @@ impl WindowManager { "ignoring show event for window already associated with another workspace" ); - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); proceed = false; } @@ -621,7 +623,10 @@ impl WindowManager { // first send the `FocusChange` event and only the `Show` event after // and we will be focusing the desktop on the `FocusChange` event since // it is still empty. - window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(window.hwnd), + self.mouse_follows_focus, + )?; } } @@ -638,7 +643,7 @@ impl WindowManager { if !(monocle_window_event || workspace.layer != WorkspaceLayer::Tiling) && monocle_container.is_some() { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } } @@ -653,7 +658,7 @@ impl WindowManager { WindowsApi::bring_window_to_top(window.hwnd)?; - let started_from = WindowsApi::window_rect(window.hwnd)?; + let started_from = backend().frame(WindowId::from_hwnd(window.hwnd))?; let pending_move_op = Arc::make_mut(&mut self.pending_move_op); *pending_move_op = @@ -696,7 +701,7 @@ impl WindowManager { let workspace = self.focused_workspace_mut()?; let focused_container_idx = workspace.focused_container_idx(); - let new_position = WindowsApi::window_rect(window.hwnd)?; + let new_position = backend().frame(WindowId::from_hwnd(window.hwnd))?; // Measure against the rect the window had when the drag started, which is what // the user had under the pointer; a window is not always exactly on its tile // (cell grids, minimum sizes, border insets) @@ -812,7 +817,10 @@ impl WindowManager { self.update_focused_workspace(false, false)?; // Make sure to give focus to the moved window again - window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(window.hwnd), + self.mouse_follows_focus, + )?; } } else if window_management_behaviour.float_override { workspace.floating_windows_mut().push_back(window); @@ -1055,7 +1063,7 @@ impl WindowManager { container.restore(); } for window in workspace.floating_windows_mut() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } workspace.reintegrate_monocle_container()?; } diff --git a/komorebi/src/scrolling.rs b/komorebi/src/scrolling.rs index 5e07e6b7..51994f50 100644 --- a/komorebi/src/scrolling.rs +++ b/komorebi/src/scrolling.rs @@ -18,9 +18,10 @@ use crate::core::Rect; use crate::core::ScrollingLayoutOptions; use crate::core::Sizing; use crate::core::WindowHandlingBehaviour; -use crate::windows_api::WindowsApi; +use crate::windows_backend::backend; use crate::workspace::Workspace; use color_eyre::eyre; +use komorebi_backend::WindowId; use komorebi_layouts::scrolling; use komorebi_layouts::scrolling::ScrollingPlacement; use komorebi_scrolling::ColumnWidth; @@ -201,7 +202,7 @@ impl Workspace { .iter() // a window that is hidden has not been where it was told to be .filter(|window| !crate::HIDDEN_HWNDS.lock().contains(&window.hwnd)) - .filter_map(|window| WindowsApi::window_rect(window.hwnd).ok()) + .filter_map(|window| backend().frame(WindowId::from_hwnd(window.hwnd)).ok()) .map(|actual| actual.right - placed.right) .max() .unwrap_or_default(); diff --git a/komorebi/src/stackbar_manager/mod.rs b/komorebi/src/stackbar_manager/mod.rs index fe56b941..011b9b1f 100644 --- a/komorebi/src/stackbar_manager/mod.rs +++ b/komorebi/src/stackbar_manager/mod.rs @@ -7,10 +7,12 @@ use crate::container::Container; use crate::core::StackbarLabel; use crate::core::StackbarMode; use crate::stackbar_manager::stackbar::Stackbar; +use crate::windows_backend::backend; use crossbeam_channel::Receiver; use crossbeam_channel::Sender; use crossbeam_utils::atomic::AtomicCell; use crossbeam_utils::atomic::AtomicConsume; +use komorebi_backend::WindowId; use lazy_static::lazy_static; use parking_lot::Mutex; use std::collections::HashMap; @@ -206,9 +208,9 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result stackbars_monitors.insert(container.id.clone(), monitor_idx); - let rect = WindowsApi::window_rect( + let rect = backend().frame(WindowId::from_hwnd( container.focused_window().copied().unwrap_or_default().hwnd, - )?; + ))?; stackbar.update(container_padding, container, &rect)?; } diff --git a/komorebi/src/stackbar_manager/stackbar.rs b/komorebi/src/stackbar_manager/stackbar.rs index 68543ff2..8edacd9f 100644 --- a/komorebi/src/stackbar_manager/stackbar.rs +++ b/komorebi/src/stackbar_manager/stackbar.rs @@ -18,7 +18,9 @@ use crate::stackbar_manager::STACKBAR_TAB_WIDTH; use crate::stackbar_manager::STACKBAR_UNFOCUSED_TEXT_COLOUR; use crate::stackbar_manager::STACKBARS_CONTAINERS; use crate::windows_api; +use crate::windows_backend::backend; use crossbeam_utils::atomic::AtomicConsume; +use komorebi_backend::WindowId; use std::os::windows::ffi::OsStrExt; use std::sync::atomic::Ordering; use std::sync::mpsc; @@ -341,10 +343,11 @@ impl Stackbar { let gap = DEFAULT_CONTAINER_PADDING.load_consume(); let focused_window_idx = container.focused_window_idx(); - let focused_window_rect = WindowsApi::window_rect( - container.focused_window().cloned().unwrap_or_default().hwnd, - ) - .unwrap_or_default(); + let focused_window_rect = backend() + .frame(WindowId::from_hwnd( + container.focused_window().cloned().unwrap_or_default().hwnd, + )) + .unwrap_or_default(); for (index, window) in container.windows().iter().enumerate() { let left = gap + (index as i32 * (width + gap)); @@ -358,8 +361,10 @@ impl Stackbar { // on top of other tiles before eventually ending up in the correct // tile if index != focused_window_idx - && let Err(err) = - window.set_position(&focused_window_rect, false) + && let Err(err) = backend().set_rect( + WindowId::from_hwnd(window.hwnd), + &focused_window_rect, + ) { tracing::error!( "stackbar WM_LBUTTONDOWN repositioning error: hwnd {} ({})", @@ -370,7 +375,9 @@ impl Stackbar { // Restore the window corresponding to the tab we have clicked window.restore_with_border(false); - if let Err(err) = window.focus(false) { + if let Err(err) = + backend().focus(WindowId::from_hwnd(window.hwnd), false) + { tracing::error!( "stackbar WMLBUTTONDOWN focus error: hwnd {} ({})", *window, diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index c84b98e9..a9f3beea 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -559,17 +559,18 @@ impl ApplyGlobals for StaticConfig { transparency_manager::TRANSPARENCY_ALPHA.store(transparency_alpha, Ordering::SeqCst); } + // the order documented at the statics in lib.rs + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + let mut transparency_blacklist = TRANSPARENCY_BLACKLIST.lock(); let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); - let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); let mut manage_identifiers = MANAGE_IDENTIFIERS.lock(); + let mut layered_identifiers = LAYERED_WHITELIST.lock(); let mut tray_and_multi_window_identifiers = TRAY_AND_MULTI_WINDOW_IDENTIFIERS.lock(); let mut object_name_change_identifiers = OBJECT_NAME_CHANGE_ON_LAUNCH.lock(); let mut object_name_change_title_ignore_list = OBJECT_NAME_CHANGE_TITLE_IGNORE_LIST.lock(); - let mut layered_identifiers = LAYERED_WHITELIST.lock(); - let mut transparency_blacklist = TRANSPARENCY_BLACKLIST.lock(); let mut slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); - let mut floating_applications = FLOATING_APPLICATIONS.lock(); let mut no_titlebar_applications = NO_TITLEBAR.lock(); + let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); if let Some(rules) = &mut self.ignore_rules { populate_rules(rules, &mut ignore_identifiers, &mut regex_identifiers)?; diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 321b599c..576067a0 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -725,6 +725,31 @@ impl Window { WindowsApi::is_window(self.hwnd) } + // The operation names of the shared `komorebi_backend::Backend` (docs/dev/seam.md, section 2). + // `set_rect`, `alive`, `window_rect` and `unminimize` only delegate; `focus`, `raise`, `hide`, + // `restore`, `minimize` and `close` above already carry the shared name. + + /// Set frame: `set_position` without raising the window to the front. + pub fn set_rect(self, rect: &Rect) -> eyre::Result<()> { + self.set_position(rect, false) + } + + /// Alive check: Windows still has the window (`IsWindow`). + pub fn alive(self) -> bool { + self.is_window() + } + + /// Frame query: the visible bounds (without the shadow), see `WindowsApi::window_rect`. + pub fn window_rect(self) -> eyre::Result { + WindowsApi::window_rect(self.hwnd) + } + + /// Windows has no unminimize of its own: `SW_SHOWNOACTIVATE`, as `restore` ends in for the + /// `Hide` and `Minimize` hiding behaviours, without the `HIDDEN_HWNDS` and border bookkeeping. + pub fn unminimize(self) { + WindowsApi::restore_window(self.hwnd); + } + pub fn remove_title_bar(self) -> eyre::Result<()> { let mut style = self.style()?; style.remove(WindowStyle::CAPTION); @@ -886,9 +911,16 @@ fn window_is_eligible( } } + // Every place that holds two of the rule lists takes them in the order documented at the + // statics in lib.rs, so all the lists this check reads are taken up front, in that order. + let floating_identifiers = FLOATING_APPLICATIONS.lock(); + let ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + let manage_identifiers = MANAGE_IDENTIFIERS.lock(); + let layered_whitelist = LAYERED_WHITELIST.lock(); + let slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); + let titlebars_removed = NO_TITLEBAR.lock(); let regex_identifiers = REGEX_IDENTIFIERS.lock(); - let ignore_identifiers = IGNORE_IDENTIFIERS.lock(); let should_ignore = if let Some(rule) = should_act( title, exe_name, @@ -903,7 +935,6 @@ fn window_is_eligible( false }; - let manage_identifiers = MANAGE_IDENTIFIERS.lock(); let managed_override = if let Some(rule) = should_act( title, exe_name, @@ -918,7 +949,6 @@ fn window_is_eligible( false }; - let floating_identifiers = FLOATING_APPLICATIONS.lock(); if let Some(rule) = should_act( title, exe_name, @@ -934,7 +964,6 @@ fn window_is_eligible( return false; } - let layered_whitelist = LAYERED_WHITELIST.lock(); let mut allow_layered = if let Some(rule) = should_act( title, exe_name, @@ -972,7 +1001,6 @@ fn window_is_eligible( allow }; - let titlebars_removed = NO_TITLEBAR.lock(); let allow_titlebar_removed = if let Some(rule) = should_act( title, exe_name, @@ -987,23 +1015,30 @@ fn window_is_eligible( false }; - { - let slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); - let should_sleep = should_act( - title, - exe_name, - class, - path, - &slow_application_identifiers, - ®ex_identifiers, - ) - .is_some(); + let should_sleep = should_act( + title, + exe_name, + class, + path, + &slow_application_identifiers, + ®ex_identifiers, + ) + .is_some(); - if should_sleep { - std::thread::sleep(Duration::from_millis( - SLOW_APPLICATION_COMPENSATION_TIME.load(Ordering::SeqCst), - )); - } + // Nothing below reads a rule list: release them all before sleeping, so a config load or a + // rule command is never kept waiting for the slow-application compensation time. + drop(floating_identifiers); + drop(ignore_identifiers); + drop(manage_identifiers); + drop(layered_whitelist); + drop(slow_application_identifiers); + drop(titlebars_removed); + drop(regex_identifiers); + + if should_sleep { + std::thread::sleep(Duration::from_millis( + SLOW_APPLICATION_COMPENSATION_TIME.load(Ordering::SeqCst), + )); } if (allow_wsl2_gui || allow_titlebar_removed || style.contains(WindowStyle::CAPTION) && ex_style.contains(ExtendedWindowStyle::WINDOWEDGE)) diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index a4e6502c..01cf30fe 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -48,6 +48,8 @@ use crate::core::Sizing; use crate::core::WindowContainerBehaviour; use crate::core::WindowManagementBehaviour; use crate::core::config_generation::MatchingRule; +use crate::windows_backend::backend; +use komorebi_backend::WindowId; use crate::CrossBoundaryBehaviour; use crate::DATA_DIR; @@ -700,7 +702,7 @@ impl WindowManager { // Hide the window we are about to remove if it is on the currently focused workspace if op.is_origin(focused_monitor_idx, focused_workspace_idx) { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); should_update_focused_workspace = true; } @@ -769,7 +771,7 @@ impl WindowManager { let focused_workspace_idx = monitor.focused_workspace_idx(); monitor.update_workspace_globals(focused_workspace_idx, offset); - let hmonitor = monitor.id; + let hmonitor = monitor.id.to_hmonitor(); let monitor_wp = monitor.wallpaper.clone(); let workspace = monitor .focused_workspace_mut() @@ -1129,23 +1131,23 @@ impl WindowManager { if follow_focus { if let Some(window) = self.focused_workspace()?.maximized_window { if trigger_focus { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else if let Some(container) = &self.focused_workspace()?.monocle_container { if let Some(window) = container.focused_window() && trigger_focus { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else if let Ok(window) = self.focused_window_mut() { if trigger_focus { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else { let desktop_window = Window::from(WindowsApi::desktop_window()?); let rect = self.focused_monitor_size()?; - WindowsApi::center_cursor_in_rect(&rect)?; + backend().center_cursor_in(&rect)?; match WindowsApi::raise_and_focus_window(desktop_window.hwnd) { Ok(()) => {} @@ -1179,7 +1181,7 @@ impl WindowManager { && let Ok(window) = self.focused_window_mut() && trigger_focus { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } } @@ -1217,7 +1219,7 @@ impl WindowManager { for window in workspace.floating_windows().iter() { if window.hwnd == focused_hwnd { - let mut rect = WindowsApi::window_rect(window.hwnd)?; + let mut rect = backend().frame(WindowId::from_hwnd(window.hwnd))?; match (direction, sizing) { (OperationDirection::Left, Sizing::Increase) => { if rect.left - delta < focused_monitor_work_area.left { @@ -1273,7 +1275,7 @@ impl WindowManager { WindowsApi::position_window(window.hwnd, &rect, false, true)?; if mouse_follows_focus { - WindowsApi::center_cursor_in_rect(&rect)?; + backend().center_cursor_in(&rect)?; } break; @@ -1448,7 +1450,7 @@ impl WindowManager { AnimationEngine::wait_for_all_animations(); if WindowsApi::focus_follows_mouse()? { - WindowsApi::disable_focus_follows_mouse()?; + backend().set_focus_follows_mouse(false)?; } let sockets = SUBSCRIPTION_SOCKETS.lock(); @@ -1508,7 +1510,7 @@ impl WindowManager { } if !ignore_restore { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } } } @@ -1570,7 +1572,7 @@ impl WindowManager { .get_mut(monitor_idx) .ok_or_eyre("there is no monitor")?; - let hmonitor = monitor.id; + let hmonitor = monitor.id.to_hmonitor(); let monitor_wp = monitor.wallpaper.clone(); let workspace = monitor @@ -1756,7 +1758,7 @@ impl WindowManager { } for window in target_workspace.floating_windows_mut() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } target_workspace.reintegrate_monocle_container()?; @@ -1895,7 +1897,7 @@ impl WindowManager { if len > 1 { let focused_hwnd = WindowsApi::foreground_window()?; - let focused_rect = WindowsApi::window_rect(focused_hwnd)?; + let focused_rect = backend().frame(WindowId::from_hwnd(focused_hwnd))?; match direction { OperationDirection::Left => { let mut windows_in_direction = focused_workspace @@ -1903,8 +1905,12 @@ impl WindowManager { .iter() .enumerate() .flat_map(|(idx, w)| { - (w.hwnd != focused_hwnd) - .then_some(WindowsApi::window_rect(w.hwnd).ok().map(|r| (idx, r))) + (w.hwnd != focused_hwnd).then_some( + backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .ok() + .map(|r| (idx, r)), + ) }) .flatten() .flat_map(|(idx, r)| { @@ -1926,8 +1932,12 @@ impl WindowManager { .iter() .enumerate() .flat_map(|(idx, w)| { - (w.hwnd != focused_hwnd) - .then_some(WindowsApi::window_rect(w.hwnd).ok().map(|r| (idx, r))) + (w.hwnd != focused_hwnd).then_some( + backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .ok() + .map(|r| (idx, r)), + ) }) .flatten() .flat_map(|(idx, r)| { @@ -1949,8 +1959,12 @@ impl WindowManager { .iter() .enumerate() .flat_map(|(idx, w)| { - (w.hwnd != focused_hwnd) - .then_some(WindowsApi::window_rect(w.hwnd).ok().map(|r| (idx, r))) + (w.hwnd != focused_hwnd).then_some( + backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .ok() + .map(|r| (idx, r)), + ) }) .flatten() .flat_map(|(idx, r)| { @@ -1972,8 +1986,12 @@ impl WindowManager { .iter() .enumerate() .flat_map(|(idx, w)| { - (w.hwnd != focused_hwnd) - .then_some(WindowsApi::window_rect(w.hwnd).ok().map(|r| (idx, r))) + (w.hwnd != focused_hwnd).then_some( + backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .ok() + .map(|r| (idx, r)), + ) }) .flatten() .flat_map(|(idx, r)| { @@ -1995,7 +2013,7 @@ impl WindowManager { if let Some(idx) = target_idx { focused_workspace.floating_windows.focus(idx); if let Some(window) = focused_workspace.floating_windows().get(idx) { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; } return Ok(()); } @@ -2055,11 +2073,11 @@ impl WindowManager { if let Ok(focused_workspace) = self.focused_workspace_mut() { if let Some(window) = focused_workspace.maximized_window { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; cross_monitor_monocle_or_max = true; } else if let Some(monocle) = &focused_workspace.monocle_container { if let Some(window) = monocle.focused_window() { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; cross_monitor_monocle_or_max = true; } } else if focused_workspace.layer == WorkspaceLayer::Tiling { @@ -2111,12 +2129,15 @@ impl WindowManager { } } else if ws.layer == WorkspaceLayer::Floating && !ws.floating_windows().is_empty() { if let Some(window) = ws.focused_floating_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else { ws.layer = WorkspaceLayer::Tiling; if let Ok(focused_window) = self.focused_window() { - focused_window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(focused_window.hwnd), + self.mouse_follows_focus, + )?; } } } @@ -2258,11 +2279,12 @@ impl WindowManager { if let Ok(focused_workspace) = self.focused_workspace_mut() { if let Some(window) = focused_workspace.maximized_window { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; cross_monitor_monocle_or_max = true; } else if let Some(monocle) = &focused_workspace.monocle_container { if let Some(window) = monocle.focused_window() { - window.focus(mouse_follows_focus)?; + backend() + .focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; cross_monitor_monocle_or_max = true; } } else if focused_workspace.layer == WorkspaceLayer::Tiling { @@ -2320,12 +2342,15 @@ impl WindowManager { } } else if ws.layer == WorkspaceLayer::Floating && !ws.floating_windows().is_empty() { if let Some(window) = ws.focused_floating_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } else { ws.layer = WorkspaceLayer::Tiling; if let Ok(focused_window) = self.focused_window() { - focused_window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(focused_window.hwnd), + self.mouse_follows_focus, + )?; } } } @@ -2358,7 +2383,7 @@ impl WindowManager { let focused_hwnd = WindowsApi::foreground_window()?; for window in focused_workspace.floating_windows().iter() { if window.hwnd == focused_hwnd { - let mut rect = WindowsApi::window_rect(window.hwnd)?; + let mut rect = backend().frame(WindowId::from_hwnd(window.hwnd))?; match direction { OperationDirection::Left => { if rect.left - delta < focused_monitor_work_area.left { @@ -2400,7 +2425,7 @@ impl WindowManager { WindowsApi::position_window(window.hwnd, &rect, false, true)?; if mouse_follows_focus { - WindowsApi::center_cursor_in_rect(&rect)?; + backend().center_cursor_in(&rect)?; } break; @@ -2564,12 +2589,14 @@ impl WindowManager { let a = self .focused_monitor() .ok_or_eyre("there is no monitor focused monitor")? - .id; + .id + .to_hmonitor(); let b = self .monitors_mut() .get_mut(origin_monitor_idx) .ok_or_eyre("there is no monitor at this index")? - .id; + .id + .to_hmonitor(); if !WindowsApi::monitors_have_same_dpi(a, b)? { self.update_focused_workspace(self.mouse_follows_focus, true)?; @@ -2634,7 +2661,7 @@ impl WindowManager { if let Some(idx) = target_idx && let Some(window) = focused_workspace.floating_windows().get(idx) { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; } Ok(()) @@ -2674,7 +2701,8 @@ impl WindowManager { } else if monocle_next { self.toggle_monocle()?; } else { - self.focused_window_mut()?.focus(self.mouse_follows_focus)?; + let hwnd = self.focused_window_mut()?.hwnd; + backend().focus(WindowId::from_hwnd(hwnd), self.mouse_follows_focus)?; } Ok(()) @@ -2734,7 +2762,7 @@ impl WindowManager { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } self.update_focused_workspace(self.mouse_follows_focus, true) @@ -2771,7 +2799,7 @@ impl WindowManager { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } self.update_focused_workspace(self.mouse_follows_focus, true) @@ -2804,7 +2832,7 @@ impl WindowManager { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } self.update_focused_workspace(self.mouse_follows_focus, true) @@ -2948,7 +2976,7 @@ impl WindowManager { if changed_focus && let Some(container) = workspace.focused_container_mut() { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; } } @@ -3110,7 +3138,7 @@ impl WindowManager { if toggle_float_placement.should_center() { window.center(&work_area, toggle_float_placement.should_resize())?; } - window.focus(self.mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), self.mouse_follows_focus)?; Ok(()) } @@ -3150,7 +3178,7 @@ impl WindowManager { } for window in workspace.floating_windows_mut() { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } Ok(()) @@ -3167,7 +3195,7 @@ impl WindowManager { } for window in workspace.floating_windows_mut() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } workspace.reintegrate_monocle_container() @@ -3740,7 +3768,7 @@ impl WindowManager { let hmonitor = WindowsApi::monitor_from_window(window.hwnd); for (i, monitor) in self.monitors().iter().enumerate() { - if monitor.id == hmonitor { + if monitor.id.to_hmonitor() == hmonitor { return Option::from(i); } } @@ -3763,7 +3791,7 @@ impl WindowManager { let hmonitor = WindowsApi::monitor_from_point(WindowsApi::cursor_pos().ok()?); for (i, monitor) in self.monitors().iter().enumerate() { - if monitor.id == hmonitor { + if monitor.id.to_hmonitor() == hmonitor { return Option::from(i); } } @@ -4056,7 +4084,8 @@ fn workspace_transition_plan( .into_iter() .filter(|window| !window.is_miminized()) .filter_map(|window| { - WindowsApi::window_rect(window.hwnd) + backend() + .frame(WindowId::from_hwnd(window.hwnd)) .ok() .map(|rect| (window.hwnd, rect)) }) diff --git a/komorebi/src/windows_backend.rs b/komorebi/src/windows_backend.rs index 7df5c753..762c0a86 100644 --- a/komorebi/src/windows_backend.rs +++ b/komorebi/src/windows_backend.rs @@ -54,7 +54,7 @@ fn platform(report: eyre::Report) -> Error { impl WindowsBackend { fn info(window: Window) -> Option { let hwnd = window.hwnd; - if !WindowsApi::is_window(hwnd) { + if !window.alive() { return None; } @@ -63,7 +63,7 @@ impl WindowsBackend { pid: i32::try_from(window.process_id()).unwrap_or_default(), // Windows reports the visible bounds (without the shadow); an error leaves the // default, which a caller cannot tell from a window at the origin: see seam.md 9 - rect: WindowsApi::window_rect(hwnd).unwrap_or_default(), + rect: window.window_rect().unwrap_or_default(), minimized: window.is_miminized(), alive: true, title: window.title().ok(), @@ -110,7 +110,7 @@ impl Backend for WindowsBackend { .map(|(_, hmonitor)| { let monitor = WindowsApi::monitor(hmonitor).map_err(platform)?; Ok(MonitorInfo { - id: MonitorId::from_hmonitor(monitor.id), + id: monitor.id, size: monitor.size, work_area: monitor.work_area_size, name: Some(monitor.name), @@ -126,6 +126,15 @@ impl Backend for WindowsBackend { Ok(monitors) } + fn frame(&self, id: WindowId) -> Result { + // one `DwmGetWindowAttribute` (fallback `GetWindowRect`), no title, class or exe lookups, + // and no `IsWindow` first: the Win32 error is the answer, as for every `window_rect` + // caller; `failed` says whether the window died + Window::from(id.to_hwnd()) + .window_rect() + .map_err(|e| failed(id, e)) + } + fn cursor_pos(&self) -> Option<(i32, i32)> { WindowsApi::cursor_pos().ok().map(|p| (p.x, p.y)) } @@ -136,7 +145,7 @@ impl Backend for WindowsBackend { // contract does not have: it is false here and a caller raises with `raise`. // `Window::set_position` also keeps its animation, slide-in and live-resize guards // and skips the write when the frame is already right: see seam.md 9. - window.set_position(rect, false).map_err(|e| failed(id, e)) + window.set_rect(rect).map_err(|e| failed(id, e)) } fn focus(&self, id: WindowId, mouse_follows_focus: bool) -> Result<()> { @@ -172,7 +181,7 @@ impl Backend for WindowsBackend { // for the `Hide` and `Minimize` hiding behaviours, and without the HIDDEN_HWNDS and // border bookkeeping of `Window::restore` live(id)?; - WindowsApi::restore_window(id.to_hwnd()); + Window::from(id.to_hwnd()).unminimize(); Ok(()) } @@ -232,3 +241,12 @@ impl Backend for WindowsBackend { ))) } } + +static BACKEND: WindowsBackend = WindowsBackend; + +/// The backend the daemon calls, like `backend()` on KDE. Stateless, so one static serves every +/// thread. Call sites are being switched to it one cluster at a time: see +/// `docs/dev/backend-switch.md` for which are. +pub fn backend() -> &'static dyn Backend { + &BACKEND +} diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 9b2bd4c7..1d5e83cf 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -46,8 +46,10 @@ use crate::static_config::WorkspaceConfig; use crate::window::Window; use crate::window::WindowDetails; use crate::windows_api::WindowsApi; +use crate::windows_backend::backend; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use komorebi_backend::WindowId; use komorebi_scrolling::ScrollingSpace; use komorebi_themes::Base16ColourPalette; use komorebi_themes::KomorebiThemeCustom as Custom; @@ -406,7 +408,7 @@ impl Workspace { } if should_hide { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } @@ -415,7 +417,7 @@ impl Workspace { } if let Some(window) = self.maximized_window { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } if let Some(container) = &self.monocle_container { @@ -553,7 +555,7 @@ impl Workspace { && let Some(window) = container.focused_window() { container.restore(); - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; return self.apply_wallpaper(hmonitor, monitor_wp); } @@ -575,7 +577,7 @@ impl Workspace { } for window in self.floating_windows() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } // Do this here to make sure that an error doesn't stop the restoration of other windows @@ -583,18 +585,30 @@ impl Workspace { // when switching to a workspace if let Some(window) = to_focus { if self.maximized_window.is_none() && matches!(self.layer, WorkspaceLayer::Tiling) { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; } else if let Some(maximized_window) = self.maximized_window { - maximized_window.restore(); - maximized_window.focus(mouse_follows_focus)?; + let _ = backend().restore(WindowId::from_hwnd(maximized_window.hwnd)); + backend().focus( + WindowId::from_hwnd(maximized_window.hwnd), + mouse_follows_focus, + )?; } else if let Some(floating_window) = self.focused_floating_window() { - floating_window.focus(mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(floating_window.hwnd), + mouse_follows_focus, + )?; } } else if let Some(maximized_window) = self.maximized_window { - maximized_window.restore(); - maximized_window.focus(mouse_follows_focus)?; + let _ = backend().restore(WindowId::from_hwnd(maximized_window.hwnd)); + backend().focus( + WindowId::from_hwnd(maximized_window.hwnd), + mouse_follows_focus, + )?; } else if let Some(floating_window) = self.focused_floating_window() { - floating_window.focus(mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(floating_window.hwnd), + mouse_follows_focus, + )?; } self.apply_wallpaper(hmonitor, monitor_wp) @@ -715,7 +729,7 @@ impl Workspace { window.set_position(&adjusted_work_area, true)?; }; } else if let Some(window) = &mut self.maximized_window { - window.maximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), true); } else if !self.containers().is_empty() { // windows that were not what they were told to be since the last layout, which // is something that animations only show once they are done @@ -821,22 +835,22 @@ impl Workspace { // If a window has been unmaximized via toggle-maximize, this block // will make sure that it is unmaximized via restore_window if window.is_maximized() && !managed_maximized_window { - WindowsApi::restore_window(window.hwnd); + let _ = backend().unminimize(WindowId::from_hwnd(window.hwnd)); } } if hidden.get(i).copied().unwrap_or_default() { // it is seen on another monitor wherever it rests here - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } else { if crate::scrolling::should_restore_when_placed( window.hwnd, container.focused_window().map(|w| w.hwnd), &HIDDEN_HWNDS.lock(), ) { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } - window.set_position(layout, false)?; + backend().set_rect(WindowId::from_hwnd(window.hwnd), layout)?; } } } @@ -1184,7 +1198,7 @@ impl Workspace { if let Some(window) = self.maximized_window && window.hwnd == hwnd { - window.unmaximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), false); self.maximized_window = None; self.maximized_window_restore_idx = None; return Ok(()); @@ -1219,7 +1233,7 @@ impl Workspace { } else { container.load_focused_window(); if let Some(window) = container.focused_window() { - window.focus(false)?; + backend().focus(WindowId::from_hwnd(window.hwnd), false)?; } } @@ -1874,7 +1888,7 @@ impl Workspace { self.maximized_window = floating_window; self.maximized_window_restore_idx = Option::from(focused_idx); if let Some(window) = self.maximized_window { - window.maximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), true); } return Ok(()); @@ -1896,7 +1910,7 @@ impl Workspace { self.maximized_window = Option::from(window); self.maximized_window_restore_idx = monocle_restore_idx; if let Some(window) = self.maximized_window { - window.maximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), true); } return Ok(()); @@ -1926,7 +1940,7 @@ impl Workspace { self.maximized_window_restore_idx = Option::from(focused_idx); if let Some(window) = self.maximized_window { - window.maximize(); + let _ = backend().maximize(WindowId::from_hwnd(window.hwnd), true); } self.focus_previous_container();