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/crates/komorebi-backend/src/lib.rs b/crates/komorebi-backend/src/lib.rs index 8fbde7df..20ce1958 100644 --- a/crates/komorebi-backend/src/lib.rs +++ b/crates/komorebi-backend/src/lib.rs @@ -31,6 +31,7 @@ mod error; pub mod fake; mod id; mod info; +mod registry; pub use backend::Backend; pub use backend::Batch; @@ -41,4 +42,5 @@ pub use id::MonitorId; pub use id::WindowId; pub use info::MonitorInfo; pub use info::WindowInfo; +pub use registry::Registry; pub use komorebi_layouts::Rect; diff --git a/crates/komorebi-backend/src/registry.rs b/crates/komorebi-backend/src/registry.rs new file mode 100644 index 00000000..aae9940c --- /dev/null +++ b/crates/komorebi-backend/src/registry.rs @@ -0,0 +1,312 @@ +//! A thread-safe table from a [`WindowId`] to whatever a platform needs in order to act on that +//! window from nothing but the id. +//! +//! macOS is the platform that needs it: a window there is an Accessibility element with the pid +//! of its application and the observer that reports its events, and nothing can be done to a +//! window without them. The table is generic over the handle (`H`) so that its rules can be +//! tested on any host with a stand-in handle; macOS instantiates it with its Accessibility types. +//! +//! # Rules +//! +//! 1. **Thread-safe.** Any thread may call any method. +//! 2. **Nothing of the platform runs under the lock.** [`Registry::get`] clones the handle (the +//! handle must be cheap to clone: a retained reference) and returns; the caller acts on the +//! clone with the lock released. A method that removes an entry hands the removed handle back +//! to the caller instead of dropping it inside, because dropping a macOS handle can make an +//! Accessibility round trip. This is what keeps a registry call from ever waiting on the main +//! queue, or on an application, while holding the lock (`docs/dev/seam.md` section 3.3). +//! 3. **A stale id is an error, not a panic.** Looking up an id that was never registered, was +//! removed, or was removed with its application answers [`Error::WindowGone`]. +//! 4. **Entries end** when the window is destroyed ([`Registry::remove`]), when its application +//! quits ([`Registry::remove_pid`]), and when a call on the window shows that it is gone. An +//! entry that nobody removes is a leak of a retained element; the platform removes at every +//! place it learns of a death. +//! 5. **Re-registering an id replaces the entry** and returns the old handle (a tab that is +//! now shown by another element keeps the window id). +//! +//! ``` +//! use komorebi_backend::Registry; +//! use komorebi_backend::WindowId; +//! +//! let registry: Registry<&'static str> = Registry::new(); +//! let id = WindowId::from_u32(7); +//! registry.insert(id, 100, "element"); +//! assert_eq!(registry.get(id).unwrap(), "element"); +//! +//! registry.remove(id); +//! assert!(registry.get(id).unwrap_err().is_window_gone()); +//! ``` + +use crate::Error; +use crate::Result; +use crate::WindowId; +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::MutexGuard; + +struct Entry { + pid: i32, + handle: H, +} + +/// The table. See the [module documentation](self) for its rules. +pub struct Registry { + entries: Mutex>>, +} + +impl Default for Registry { + fn default() -> Self { + Self::new() + } +} + +impl Registry { + /// Returns an empty registry. + pub fn new() -> Self { + Self { + entries: Mutex::new(HashMap::new()), + } + } + + // a thread that panicked while holding the lock cannot have left an entry half written (every + // method is a single map operation), so a poisoned lock is still good + fn lock(&self) -> MutexGuard<'_, HashMap>> { + self.entries.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Registers the window, owned by the process `pid`. Returns the handle that this replaces, + /// if the id was registered: the caller drops it, with no lock held. + #[must_use = "drop the replaced handle yourself: it is not dropped under the lock"] + pub fn insert(&self, id: WindowId, pid: i32, handle: H) -> Option { + self.lock().insert(id, Entry { pid, handle }).map(|e| e.handle) + } + + /// Replaces the handle of a window that is registered, keeping its pid. Returns the old + /// handle, or [`Error::WindowGone`] (and registers nothing) if the id is not registered. + pub fn replace(&self, id: WindowId, handle: H) -> Result { + match self.lock().get_mut(&id) { + Some(entry) => Ok(std::mem::replace(&mut entry.handle, handle)), + None => Err(Error::WindowGone(id)), + } + } + + /// Forgets the window. Returns its handle (for the caller to drop with no lock held), or + /// `None` if it was not registered, which is not an error: a death is usually seen twice. + #[must_use = "drop the removed handle yourself: it is not dropped under the lock"] + pub fn remove(&self, id: WindowId) -> Option { + self.lock().remove(&id).map(|e| e.handle) + } + + /// Forgets every window of the process, as when its application quits. Returns the ids and + /// handles removed, sorted by id. + #[must_use = "drop the removed handles yourself: they are not dropped under the lock"] + pub fn remove_pid(&self, pid: i32) -> Vec<(WindowId, H)> { + let mut entries = self.lock(); + let ids: Vec = entries + .iter() + .filter(|(_, e)| e.pid == pid) + .map(|(id, _)| *id) + .collect(); + let mut removed: Vec<(WindowId, H)> = ids + .into_iter() + .filter_map(|id| entries.remove(&id).map(|e| (id, e.handle))) + .collect(); + drop(entries); + removed.sort_by_key(|(id, _)| *id); + removed + } + + /// Whether the id is registered. + pub fn contains(&self, id: WindowId) -> bool { + self.lock().contains_key(&id) + } + + /// The pid of the registered window, or [`Error::WindowGone`]. + pub fn pid(&self, id: WindowId) -> Result { + self.lock() + .get(&id) + .map(|e| e.pid) + .ok_or(Error::WindowGone(id)) + } + + /// How many windows are registered. + pub fn len(&self) -> usize { + self.lock().len() + } + + /// Whether nothing is registered. + pub fn is_empty(&self) -> bool { + self.lock().is_empty() + } + + /// The registered ids, sorted. + pub fn ids(&self) -> Vec { + let mut ids: Vec<_> = self.lock().keys().copied().collect(); + ids.sort(); + ids + } +} + +impl Registry { + /// A clone of the handle of the window, or [`Error::WindowGone`] for an id that is not + /// registered. The lock is released before this returns. + pub fn get(&self, id: WindowId) -> Result { + self.lock() + .get(&id) + .map(|e| e.handle.clone()) + .ok_or(Error::WindowGone(id)) + } + + /// Clones of every handle with their ids, sorted by id. + pub fn snapshot(&self) -> Vec<(WindowId, H)> { + let mut all: Vec<_> = self + .lock() + .iter() + .map(|(id, e)| (*id, e.handle.clone())) + .collect(); + all.sort_by_key(|(id, _)| *id); + all + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + + fn id(n: u32) -> WindowId { + WindowId::from_u32(n) + } + + #[test] + fn a_registered_window_is_found_by_its_id() { + let r = Registry::new(); + assert!(r.insert(id(1), 10, "a").is_none()); + assert!(matches!(r.get(id(1)), Ok("a"))); + assert!(matches!(r.pid(id(1)), Ok(10))); + assert!(r.contains(id(1))); + } + + #[test] + fn an_unknown_id_is_window_gone_and_not_a_panic() { + let r: Registry<&str> = Registry::new(); + assert!(matches!(r.get(id(9)), Err(Error::WindowGone(w)) if w == id(9))); + assert!(matches!(r.pid(id(9)), Err(Error::WindowGone(_)))); + assert!(r.get(id(9)).unwrap_err().is_window_gone()); + } + + #[test] + fn a_removed_window_is_stale() { + let r = Registry::new(); + let _ = r.insert(id(1), 10, "a"); + assert_eq!(r.remove(id(1)), Some("a")); + assert!(r.get(id(1)).unwrap_err().is_window_gone()); + // a death seen twice is not an error + assert_eq!(r.remove(id(1)), None); + } + + #[test] + fn reinserting_replaces_and_hands_back_the_old_handle() { + let r = Registry::new(); + let _ = r.insert(id(1), 10, "tab one"); + assert_eq!(r.insert(id(1), 10, "tab two"), Some("tab one")); + assert!(matches!(r.get(id(1)), Ok("tab two"))); + assert_eq!(r.len(), 1); + } + + #[test] + fn replace_keeps_the_pid_and_refuses_a_stale_id() { + let r = Registry::new(); + let _ = r.insert(id(1), 10, "a"); + assert!(matches!(r.replace(id(1), "b"), Ok("a"))); + assert!(matches!(r.pid(id(1)), Ok(10))); + assert!(r.replace(id(2), "c").unwrap_err().is_window_gone()); + assert!(!r.contains(id(2))); + } + + #[test] + fn an_application_quitting_takes_all_its_windows_and_only_them() { + let r = Registry::new(); + let _ = r.insert(id(3), 10, "c"); + let _ = r.insert(id(1), 10, "a"); + let _ = r.insert(id(2), 20, "b"); + + assert_eq!(r.remove_pid(10), vec![(id(1), "a"), (id(3), "c")]); + assert_eq!(r.ids(), vec![id(2)]); + assert!(r.get(id(1)).unwrap_err().is_window_gone()); + assert_eq!(r.remove_pid(10), vec![]); + } + + #[test] + fn snapshot_is_sorted_and_independent_of_later_changes() { + let r = Registry::new(); + let _ = r.insert(id(2), 1, "b"); + let _ = r.insert(id(1), 1, "a"); + let snap = r.snapshot(); + let _ = r.remove(id(1)); + assert_eq!(snap, vec![(id(1), "a"), (id(2), "b")]); + } + + /// A handle whose drop would, on macOS, make a round trip: it must not run under the lock. + struct Probe { + registry: Arc>>, + drops: Arc, + } + + impl Drop for Probe { + fn drop(&mut self) { + // would deadlock if the registry dropped the handle while holding its lock + let _ = self.registry.len(); + self.drops.fetch_add(1, Ordering::SeqCst); + } + } + + #[test] + fn handles_are_never_dropped_under_the_lock() { + let registry = Arc::new(Registry::new()); + let drops = Arc::new(AtomicUsize::new(0)); + let probe = |_: u32| { + Arc::new(Probe { + registry: registry.clone(), + drops: drops.clone(), + }) + }; + + let _ = registry.insert(id(1), 10, probe(1)); + // the replaced and the removed handles come back to us, so their drop runs here + drop(registry.insert(id(1), 10, probe(2))); + drop(registry.remove(id(1))); + let _ = registry.insert(id(2), 10, probe(3)); + drop(registry.remove_pid(10)); + + assert_eq!(drops.load(Ordering::SeqCst), 3); + assert!(registry.is_empty()); + } + + #[test] + fn many_threads_can_register_look_up_and_remove() { + let r = Arc::new(Registry::new()); + let threads: Vec<_> = (0..8u32) + .map(|t| { + let r = r.clone(); + std::thread::spawn(move || { + for n in 0..200u32 { + let wid = id(t * 1000 + n); + let _ = r.insert(wid, t as i32, n); + assert!(matches!(r.get(wid), Ok(v) if v == n)); + assert_eq!(r.remove(wid), Some(n)); + assert!(r.get(wid).unwrap_err().is_window_gone()); + } + }) + }) + .collect(); + + for t in threads { + t.join().unwrap(); + } + + assert!(r.is_empty()); + } +} diff --git a/docs/dev/backend-switch.md b/docs/dev/backend-switch.md new file mode 100644 index 00000000..c817f644 --- /dev/null +++ b/docs/dev/backend-switch.md @@ -0,0 +1,43 @@ +# 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 | diff --git a/docs/dev/macos-handcheck.md b/docs/dev/macos-handcheck.md new file mode 100644 index 00000000..026ed895 --- /dev/null +++ b/docs/dev/macos-handcheck.md @@ -0,0 +1,73 @@ +# macOS hand-check list + +Status: written by the `kfm` agent for the user, 2026-10-31. Nothing here has been run: macOS cannot be built, linked or tested on the Linux host, only type-checked through a fake C compiler (`tools/fast-check`). Every revision below is `type-checks, not run`. Revision ids are jj change ids (stable) with the commit id they had when this was written (commit ids change when a revision is rewritten; use `jj log -r `). + +How to use it: build the unified (or, until they exist, the per-tree) macOS `komorebi`, `komorebic` and `komorebi-bar`, run `cargo test --workspace` on the Mac first (the 399+ unit tests have never run against these changes), then walk the sections in order. For before/after capture use `komorebi-recorder` against a build of the baseline `wip-main` ancestor `ff3711dc` and the tip. A section is done when the "look for" column is true. + +## A. Revisions that change what the daemon does (BEHAVIOUR) + +| Revision | What changed | Look for on a Mac | +|---|---|---| +| `ummqkuvp` 01b9cbed `fix(mac): take the rule-list locks in one order...` | `window_is_eligible` (window.rs) and `apply_globals` (static_config.rs) now lock floating, ignore, manage, regex in that order; before they locked regex, ignore, manage and ignore, regex, manage. The order is documented at the statics in lib.rs. Same fix as the KDE `ef1d3ef0`. | Run `komorebic reload-configuration` (and `komorebic replace-configuration`) in a loop of 50 while opening and closing windows (new Finder windows, Terminal tabs) at the same time. Before the fix this could hang the daemon (the command is never answered, new windows are not tiled). Expected: no hang, every reload answered. Also check that float rules, ignore rules and manage rules from the config and from `komorebic float-rule`/`ignore-rule`/`manage-rule` still apply to new windows. | +| `nvwvptpv` 866b2840 `use the shared command listener` | The UDS command accept loop and per-client reader are the shared `komorebi-transport` code (`NoPolicy`: no read timeouts, as before); `WindowManager` is a `CommandTarget` (lock with `try_lock_for`). | Every `komorebic` command is answered; a command sent while the daemon is busy gets an answer or a clean error, not a hang; kill the daemon mid-command: the client returns. | +| `ywwwwpwm` 587defe3 `use the shared pause filter` | `allowed_while_paused` lists the commands allowed while paused. | `komorebic toggle-pause`; while paused only `toggle-pause`, `state`, `global-state`, `stop` work, everything else is ignored (and the connection ends); unpause and check windows tile again. | +| `kzynysto` b85827e6 `use the shared subscriber push` | Subscriber sockets are pushed to by the shared `notify_sockets`; the macOS override events are kept. | `komorebic subscribe-socket` (and `subscribe-socket-with-options`): events arrive for focus, move, workspace change, monitor change, theme and config reload; a subscriber that goes away is dropped without breaking the others. The bar is a subscriber, so the bar updating is the check. | +| `ovsplvmn` 5cc38da6 `use EventChannel for the window events` | The window-event channel (capacity 20, try_send, drop warning, `ResizeStep` claim flag) is `komorebi_transport::EventChannel`. | Drag a window edge continuously (live resize) and pan with the trackpad: no stalls, no repeated drop warnings in the log, the layout follows. Move many windows at once (workspace switch with 10+ windows). | +| `lrqkuuzq` a4996ac6 `use SocketMessage from komorebi-protocol` and `sowrttxs` 5c129ab5 `carry DebugWindow as i64` | One `SocketMessage` for all platforms; the wire format must be unchanged. `DebugWindow` takes an i64 (a negative id parses and matches nothing). | Every command of the `komorebic` help works against the daemon; `komorebic debug-window ` for a real id; `komorebic state` and `global-state` JSON parse. | +| `qqwoptqt` 975f007a, `yptnnkxv` eb903bcc (animation prefix, Bezier doc) | `AnimationPrefix` gains `Transparency` (ignored by the daemon); schema.json changed the shape of per-prefix animation settings. | Config with `animation.style` / `duration` per prefix (movement, workspace) still loads; animations behave as before. Run `komorebic static-config-schema` and diff with `komorebi-for-mac/schema.json` (two description-level changes and the per-prefix shape are intended). | +| `kvtvnouo` 93e4d511, `stxmqnop` dec91984 (StaticConfig from komorebi-config) | The config data types and their defaults come from `komorebi-config`; `komorebic static-config-schema` prints the macOS view. | A real `komorebi.json` of yours loads with no new warning and every key still takes effect (borders, padding, animations, scrolling, rules, workspaces); `komorebic static-config-schema` matches the checked-in `schema.json` up to the intended description lines. | +| `qukywpss` c46320ea, `zwkwptox` 1e902542, `sxptsttt` 0345fccb (komorebic shares clap definitions, launcher, pan) | `komorebic start` and `stop` use the shared Launcher skeleton (the odd `--config` arguments are kept; "Waiting for komorebi to start..." is flushed); pan commands use the shared module. | `komorebic start --bar`, `start --await-configuration`, `stop`, `stop --bar`; `komorebic pan-*` commands; `komorebic --help` and a few ` --help` texts (about 15 help texts changed to the Windows wording). | +| `oywqqkuy` f0b1a448 `register every Window in ax_registry and forget the dead` | `Window::new` registers the window in the id registry (`ax_registry`); entries are removed in `Window::drop` of a dead window, in `reap_window`, and (`forget_pid`) when an application terminates. No AX call is added; the table holds retained AX references and observers. | Open and close 50 windows (Finder, Terminal, Safari) and quit several apps, then check the daemon's memory in Activity Monitor does not climb and nothing behaves differently (focus, tiling, borders). If a quit app's windows were not forgotten the symptom is memory growth only. Run with `RUST_LOG=debug` and check no new errors at app quit. | +| `oqnvyqvw` e0687167 `keep ax_registry in step when a native tab changes a window's id` | The two places that swap a window's id and element in place for native tabs also update the registry (`sync`). | A native-tabbed app (Terminal, Finder, Safari tabs): switch tabs, close the first tab, open a new tab, focus the window with `komorebic focus ...`, move and resize it. Must behave as on the baseline (no window lost, no stuck border). | +| Bar: `nottqpms` 086833af, `zvuyspku` b8de056b, `uxzpkmnk` 7cd85bd4, `yopuwouu` 6da27dda (bar-core, platform hooks) | macOS now builds `sysinfo` 0.39 and `starship-battery` 0.11 (the Windows versions); cpu, battery, memory, date, update widgets are the shared code. | Bar renders; CPU %, memory, battery % and charging state show sane values; date and the calendar icon; clicking CPU, battery, network, update (see bug list D below: these click handlers are broken on macOS and stay broken). | + +Revisions in section B change no behaviour on purpose (rename, move, route); they still need the sections C walk-through, because a mechanical mistake would show there. + +## B. Mechanical macOS revisions of the `kfm` agent (Step 6 and 11(i)) + +| Revision | Change | +|---|---| +| `vzxkxzzy` 796c3832 | `Window::frame()` (renamed `window_rect` below) for the 28 sites that read a Window's frame through `MacosApi::window_rect(&w.element)` (window.rs, window_manager.rs, workspace.rs, process_event.rs, process_command.rs, settle.rs, macos_backend.rs) | +| `oootynxk` 7c2e1bea | `Window::is_valid` renamed `Window::alive` | +| `roxrxtru` 49a6dbda | `Window::set_position` renamed `Window::set_rect` (10 callers) | +| `vmnnuzzu` 803a1410 | `Window::set_messaging_timeout` (settle.rs: 3 raw AX sites) | +| `upylxxuw` ecaa3e15 | `Window::close` (the same close-button press as `AdhocWindow::close`) | +| `tsymmvll` d30a3eb6 | step 11(i): `MacosBackend` calls only `Window` methods (new `Window::minimized`); still unused by the daemon | +| `qsrxvsmv` 931b17d7 | `Window::frame` renamed `Window::window_rect` (the Backend and the Windows Window use that name) | +| `xrtqmxkp` 4c9094d7 | native: `komorebi_backend::Registry` (the rules of the id registry; 9 unit and 1 doc test run on Linux) | +| `tmmtuosy` 386c5a79 | `ax_registry` module; `MacosBackend` resolves ids through it (the adapter is still unused by the daemon) | +| `kvkxkqnx` ba22e8dc | `ax_registry::identify`: the 7 sites that turn a system-handed element into a window id (input_event_listener, process_command, process_event x5, window_manager) | +| `kpopuvoy` 01b3bd5c | live-resize step (window_manager.rs) reads the dragged window's frame through `Window::window_rect` | + +Hand check: C below. If something breaks and is not the lock order, bisect among these seven first: they only rename and route, so a regression means a call was routed to the wrong receiver (type-check cannot tell a Window from another window of the same type). + +## C. Walk-through (the list the plan names) + +Do each with the baseline build and the tip build and compare (or record with `komorebi-recorder`). + +1. **Focus**: `komorebic focus left|right|up|down`, `cycle-focus`, `focus-window `; mouse-follows-focus on/off (the cursor centres in the window: uses the window frame query); focus a window of a tabbed app (Terminal, Finder): the focus uses `element_to_focus`, check the right tab. +2. **Move and resize**: `move`, `resize-axis`, `resize-edge` and a manual drag of a window; after a drag the layout puts the window back (settle reads the frame with a timeout); live resize of one edge moves the neighbour. A window that refuses a width (a fixed size app) is read back and the neighbours adapt. +3. **Stack**: `stack`, `unstack`, `cycle-stack`, `stack-all`; hidden stack members are parked off-screen (`hide`) and restored (`restore`) correctly; no window left at a hidden corner after unstack or quit. +4. **Workspaces**: switch (`focus-workspace`), send a window (`send-to-workspace`), `move-to-workspace`, with 2 monitors if possible; windows of the workspace you left are hidden, those of the new one restored to where they were; workspace rules after a monitor change. +5. **Scrolling layout**: the scrolling layout, `pan` commands, `scroll-*`; windows slide in from the edge (the arrival/slide code reads the frame). +6. **Pan** (trackpad gesture) and **live resize**: `komorebic pan-*`, three-finger style gestures as you configured them. +7. **Borders**: focused/unfocused/stack colours follow focus and follow animated windows; borders vanish and come back on workspace switch; no border left behind after closing a window (the window's close and borders share the observer code). +8. **Animations**: movement and workspace animations on and off; the ghost images; cancel an animation by issuing a new command in the middle. +9. **Display change**: plug or unplug a monitor or change the resolution: work areas update, workspaces go to the right monitors, workspace rules re-apply. (This is the thread that can deadlock, see bug list A.) +10. **Sleep and wake**: close the lid or sleep, wake: windows are where they were, the daemon answers, the bar returns. +11. **Minimize, unminimize, close**: `komorebic minimize`, `close` (the foreground window), un-minimize a window from the Dock; closing a window removes it from its container (the reaper uses `Window::alive`). +12. **Reload the config** repeatedly (see section A, first row). + +## D. Bugs noticed, not fixed here + +A. **Possible deadlock, main queue against the window-manager lock** (`docs/dev/seam.md` section 3.3, by reading only, never reproduced). A thread holding the WM lock calls a blocking main-queue dispatch (`destroy_all_borders` at process_event.rs lines about 128/139, process_command.rs, `retile_all`; `hide_borders_on` in window_manager.rs; `activate_finder` in process_event.rs) while the monitor reconciliator has dispatched a closure to main that itself takes the WM lock (monitor_reconciliator.rs about 106 and 383). Then the event thread waits for main, main waits for the lock. `parking_lot`'s deadlock detector cannot see it (the dispatch is a semaphore). Window of exposure: a display change at the instant of one of those events. Structural fix: no closure that runs on main may take the WM lock (or dispatch to main only after the lock is dropped). How to provoke it: spam `komorebic retile` / workspace switches (with ghosts) while plugging or unplugging a monitor; the symptom is a daemon that answers no command (`komorebic state` hangs). +B. **cmd.exe and explorer.exe in the macOS bar** (`komorebi-for-mac/komorebi-bar/src/os.rs`, `BarPlatform::open_system_tool`): the battery click spawns `cmd.exe` (power settings), the update click spawns `explorer.exe` with the release URL; neither exists on macOS. The same file's CPU (task manager) and network settings tools should be Activity Monitor and System Settings. The fix is one function in that file; it was preserved on purpose during the bar move. +C. **Update widget refresh thread polls the Windows repo's GitHub API** on macOS too (update.rs has a second URL that does not go through the hook), and the macOS update link is `.../releases/v..` built for the Windows repo. +D. **Other raw AX sites remain outside `Window`**: window.rs (38 inside `Window`/`AdhocWindow`, expected), application.rs 11 (`Application`, not a window), process_event.rs 7 (events that hand over a bare element: `window_id` of an element, the tab check `AccessibilityApi::window_id(&window.element.0)`), animation/animator.rs 6 (lane threads hold `WindowHandle` clones of the element), border_manager 7 (observers on tracked elements), window_manager.rs 4 (timeouts list holds elements, `window_id` of an element), reaper.rs 2 (`notify_if_gone` takes an element so lanes can use it), input_event_listener.rs 1, process_command.rs 1. They need either an id to AX registry (step 11(ii), not started) or a `WindowHandle` type; they were left alone because routing them changes who owns the element. +D2. **Step 11(ii) status.** Done: the id registry (`ax_registry`, over the tested `komorebi_backend::Registry`), populated at `Window::new`, kept in step for native tabs, emptied on death, reap and application quit; `MacosBackend` resolves ids through it. NOT done, on purpose, because each needs a decision that cannot be verified without a Mac: (a) the animator lanes (`WindowHandle`) keep their own snapshot of the element: a lane must keep writing to the element of the move it was given even if a tab swap replaced the registry entry, and replacing the snapshot by a lookup per write changes what a late write hits; (b) borders keep `tracking_element` (observer sources are added and removed on that exact element, on main); (c) `reaper::notify_if_gone` and the window manager's live-resize `timeouts` list take elements, including application elements, that are not registry entries; (d) `application.rs` is the application, not a window. (e) The model (`Window`, containers, workspaces) still holds `Window` values, not bare `WindowId`s: that is step 11(iii), after steps 8-9. A stale registry id answers `Error::WindowGone` (no panic); a window that was deserialised from state (default system-wide element) is never registered. +E. `MacosBackend` (step 7c/11(i)) needs 11(ii) before it can be used: `windows()` answers only what was `register`ed, `hide` needs the corner, `raise` also focuses, `monitors()` reads a cache nobody fills yet (seam.md section 9.2). `AdhocWindow` (bare foreground element) still has its own minimize, close, hide, restore, raise. +F. In `window.rs` `AdhocWindow::hide` / `Window::hide` duplicate the restore-position bookkeeping (`WINDOW_RESTORE_POSITIONS`), one on a `Window` and one on a bare element; they must stay in step. + +## E. What is not checked at all + +Everything above. In particular: no macOS test (399+ unit tests incl. those in window.rs for drag state) has run against any of these revisions; the unified binaries do not exist yet; no real Accessibility call was made; `komorebi-recorder` captures need a Mac. diff --git a/docs/dev/unified-binaries.md b/docs/dev/unified-binaries.md new file mode 100644 index 00000000..e76b84b9 --- /dev/null +++ b/docs/dev/unified-binaries.md @@ -0,0 +1,177 @@ +# One `komorebi`, one `komorebic`, one `komorebi-bar` + +Goal: three packages and three binaries that build on Windows, KDE (Linux) and macOS, the platform +chosen by `cfg(target_os)` (generics, `cfg_select!`, exhaustive `match`; no macros as a design tool). +This file records a spike (throwaway revisions on bookmark `wip-u-pkg-spike`, titled `spike:`; nothing +landed on `wip-main`), the layout it recommends, the migration order, the risks and the gates. + +Measured on `wip-main` 633e7453 with the light gates only (`nice -n 19`, 3 jobs, persistent target +dirs, `COMMIT_HASH=dev`); no nix build, no e2e, no VM. macOS is type-checked with the fake CC only: it +was never linked or run. + +## What the spike did + +1. `spike: one root workspace ...` (rev `yuuyzssl`): the 10 KDE and macOS member crates became members + of the root workspace. Their two `[workspace]` manifests were deleted, their `workspace = true` + dependencies were written out, packages renamed (`komorebi-linux`, `komorebic-linux`, + `komorebi-client-linux`, `komorebi-hotkeys-linux`, `version-linux`, and `-macos` for the macOS + ones including `komorebi-bar-macos`); binary and lib names stayed (`[lib] name`, `[[bin]] name`) so + no source file changed. One `Cargo.lock`. +2. `spike: unified komorebic package by #[path] includes`: the root `komorebic` package became the + unified one. `src/main.rs` is a `cfg_select!` over `target_os` that includes the old Windows + `main.rs` (moved to `windows.rs`) and, by `#[path]`, the KDE and macOS `main.rs` where they live. + Dependencies are in `[target.'cfg(...)'.dependencies]` tables. Edits to the old files: `fn main` + became `pub fn main`; `crate::HOME_DIR` became `super::HOME_DIR` in KDE `hotkeys.rs`. +3. `spike: target-gate the macOS daemon crate`: objc2 and friends under + `[target.'cfg(target_os = "macos")'.dependencies]` plus `#![cfg(target_os = "macos")]` in + `komorebi-macos`, to test `cargo check --workspace` on a foreign target. + +The script that did step 1 is `S/pkg-spike.py` (scratchpad; rerunnable on a fresh `wip-main`). + +## Results + +| question | result | +|---|---| +| One lock resolves? | Yes. 859 packages (root) -> 900. All 859 Windows entries unchanged. The KDE lock had 644 and the macOS lock 786 entries, so +41 only. Crates with more than one version: 81 -> 95 (the `sysinfo` 0.38/0.39/0.40, `dirs` 6/7, `parking_lot` 0.12/0.13, `shadow-rs` 1/2, `netdev` 0.40/0.46 splits coexist; nothing needs unifying). | +| Locked versions kept? | Not exactly: crates that only KDE or macOS use were re-resolved to newest: `zbus`/`zbus_macros` 6.1 -> 6.2, `zbus_utils`, `zruntime`, `sysinfo` 0.40.0 -> 0.40.1, `libz-sys`, `unicode-width`. Pin with `cargo update zbus@6.2.0 --precise 6.1.0` (needs the `name@version` spelling) if the VM suites must see the old versions. | +| Windows `cargo check -p komorebic --target x86_64-pc-windows-msvc` (nix develop) | passes, 14.8 s wall warm (11.2 s compile); unified `komorebic` also passes, 7 s. | +| KDE native `cargo check -p komorebi-linux -p komorebic-linux` | passes; 1 m 38 s cold into a fresh lite target dir. Unified `komorebic` on Linux passes (1.4 s after touch) when openssl is available (see risk 2). | +| KDE tests unchanged | `cargo test -p komorebi-linux --lib`: 294 passed. `--test schemas -- --test-threads=1`: 5 passed. All four KDE packages, `--no-fail-fast`, 1 m 26 s warm: 879 passed, 1 failed. The failure is `tests/version.rs`: `komorebi-linux 0.1.0` instead of `komorebi 0.1.0` (clap takes the command name from `CARGO_PKG_NAME`); a renamed package needs `#[command(name = "komorebi")]`. Nothing else depends on the package name. | +| macOS fake-CC `cargo check --target aarch64-apple-darwin -p komorebi-macos -p komorebic-macos -p komorebi-bar-macos --all-targets --locked` | passes, 32 s warm (6 warnings in the bar, as before). Unified `komorebic` on macOS passes, 12 s. Type-check only. | +| Feature unification | Resolver 2 keeps `komorebi-layouts/darwin` off Windows: `cargo tree -p komorebic --target x86_64-pc-windows-msvc -e features -i komorebi-layouts` shows only `default`, the macOS package shows `darwin`. This holds only while the package that asks for `darwin` is not in the same build; `cargo ... --workspace` on one target selects them all (see risk 3). | +| `cargo check --workspace` for Windows (what clippy, fmt, nextest and crane do today) | FAILS in 52 s: `objc2 only works on Apple platforms`. With objc2 target-gated and `#![cfg(target_os = "macos")]`, `komorebi-macos` compiles empty on Windows (spike 3), so the fix is to gate every foreign-platform crate, not to exclude them. Done for one crate only. | +| Same dependency key, different path per target | REJECTED by cargo: `Dependency 'komorebi-client' has different source paths depending on the build target`. Same for `version`. So the unified package must use one key per platform (`komorebi-client-linux`, `komorebi-client-macos`, ...) and the platform module must alias it (`extern crate komorebi_client_linux as komorebi_client;` at the root, or `use komorebi_linux as komorebi;` at the top of each platform module). The spike used `extern crate`. | +| Compile time | No extra cost on a target: a build selects its own target's dependency tables, so Windows never sees zbus or objc2 and Linux never sees `windows`. The only added cost is resolution (`cargo metadata` 6.5 s with the network). | + +## Option A or B + +Measured size of what would have to move into `#[cfg(target_os)] mod` of one crate (Option B): +daemon `crate::` paths: Windows 669, KDE 447, macOS 587 (35,149 / 32,932 / 34,505 lines, 3 lib+bin +crates each with their own tests and a `komorebi-client` that re-exports them); bar 111 / 90 (7,710 / +5,551 lines); `komorebic` 0 (1,467 / 807 / 1,537 lines). + +Recommendation: + +- `komorebic`: B. One package `komorebic`, `src/main.rs` = `cfg_select!` choosing `mod windows`, + `mod linux`, `mod macos` (each the present `main.rs`, `hotkeys.rs` for Linux), one clap command name, + target-gated dependencies. Zero `crate::` rewrites, so the files move whole. This is what the spike + built (with `#[path]` instead of the final moves). +- `komorebi-bar`: B, as `bar-unification.md` already plans (`src/bar/{mod,windows,macos}.rs`, + `os/{windows,macos}.rs`); needs the bar stack integrated first. +- `komorebi` (daemon): A. Keep three library crates, rename to `komorebi-windows`, `komorebi-linux`, + `komorebi-macos` (distinct lib names, `komorebi_windows` etc.), each gated to its OS + (`#![cfg(target_os = ...)]`, target-gated dependencies, so `--workspace` works everywhere), each + keeping its own `crate::` paths and its own tests (KDE's 881 run unchanged but for the name). One + thin `komorebi` binary package: `src/main.rs` is a `cfg_select!` over the three daemons' + `main` bodies (each daemon's present `main.rs` becomes `pub fn run()` of its library). Option B for + the daemon would be a rewrite of about 1,700 `crate::` paths (669 + 447 + 587) for no behavioural gain, and it would + put KDE's tests and the VM suites on a moving target. +- `komorebi-client`: one package with `src/{windows,linux,macos}.rs` (211 / 394 / 225 lines, almost all + `pub use komorebi::...`), each starting with `use komorebi_windows as komorebi;` and so on. + +## Migration order + +Every revision keeps the three existing trees building with their present gates. "Gate" says what +must pass before it counts as landed: `C` compile (fast-check, the three checks), `S` the CLI oracle +(`S/step4/oracle-check.sh`, byte-identical for all three platforms; it reads `komorebic/src/main.rs` +of each tree, so it needs its paths updated in the revision that moves a file), `N` nix evaluation +(`nix flake show`), `NB` a nix build of the checks in an idle window, `E` Windows e2e, `V` KDE VM `fast`. + +0. Prerequisites, no moves (any time, small): explicit `#[command(name = ...)]` on the three CLIs; + `build.rs` of `komorebic` stops fetching `applications.json` over the network (the file is checked + in; a build script that needs `reqwest`, and so openssl, on Linux is what stopped the unified + package building natively); `pub fn main` and `crate::` -> `super::` in the `komorebic` files. + Gates C, S. Not behaviour. +1. Package renames inside the present workspaces (KDE: `komorebi-linux` and so on; macOS the same; + Windows daemon `komorebi-windows` last), with `[lib] name` and `[[bin]] name` unchanged. Gates C, + N; the Windows daemon rename is `E` (the executable's inputs change). +2. Workspace merge: delete `komorebi-for-kde/Cargo.toml` and `komorebi-for-mac/Cargo.toml`, add their + crates to the root members, write out the inherited dependencies, one lock (+41 packages), add + `.cargo/config.toml` with `[env] COMMIT_HASH` (KDE's file moves from `komorebi-for-kde/.cargo`; + cargo reads it from the working directory upward only). Same revision gates every foreign crate + (`#![cfg(target_os)]`, target-gated dependencies) so `--workspace` works on all targets. Gates C on + all three, plus KDE tests unchanged. Cargo-wise this is one revision (the spike's script); it must + not be split without breaking `--locked`. +3. Flakes, same integration as 2 (nix cannot be half-merged): the root flake builds all three; the two + nested flakes already take the whole repository as their source (`lib.mkOutputs`), so they become + thin: `workspaceArgs` change from a subdirectory workspace to `-p `. The KDE source filter + must list the new member directories. Gates N, then `NB` (deps, clippy, nextest of each system), + then `V`. +4. `komorebic` unified by `#[path]` (spike 2, minus the hacks): new `komorebic/src/main.rs`, target + tables, aliases. The old `komorebic-linux`/`-macos` packages stay until step 5 so the old names + work. Gates C, S, and `E` for `komorebic.exe` (the Windows main moves to `windows.rs`). +5. `komorebic` real moves, one platform per revision: `komorebi-for-kde/komorebic/src/*` to + `komorebic/src/linux/`, the macOS one to `komorebic/src/macos/`, tests with them, then delete the old + packages. Pure moves (jj does not follow moves, so each is a delete/modify conflict if another stack + touches those files; today none does). Gates C, S, tests. +6. `komorebi-client` unified (modules per platform), same pattern. Gates C, E (Windows client is in the + closure of `komorebi.exe`). +7. `komorebi-bar` unified after the bar stack integrates: `bar-unification.md` plan; Windows bar + screenshot gate and the Mac hand check are owed by that stack. +8. Daemon: three libraries gated to their OS and one thin `komorebi` package with the `cfg_select!` + `main`. KDE `main.rs` and the Windows `main.rs` become `run()` in their libraries. Gates C, `E`, `V`, + Mac hand check. +9. Cutover: one flake output per binary, old per-platform package names, `justfile`, CI + (`.github/workflows`), docs paths, release version (0.1.42 / 0.1.0 / 0.1.1 become one). + +## Risks + +1. One lock for three platforms: a `cargo update` for one platform moves the others; crane's dummy + source includes every member's manifest and the lock, so any dependency change rebuilds the + dependency derivation of all three systems (today a KDE-only lock change cannot touch Windows). The + `COMMIT_HASH`-constant fix (flow finding 1) must be in first or every commit rebuilds ~1,000 crates. +2. `build.rs` fetching over the network is not usable in a unified package (openssl on Linux); see step 0. +3. `--workspace` commands (clippy, fmt, nextest, crane) select every member on every target: every + foreign crate must compile empty (spike 3 shows it works for the daemon; only one crate was + converted). Without it, feature unification would also turn `komorebi-layouts/darwin` on for + Windows in a whole-workspace build. +4. The one-key-one-path rule forces distinct dependency keys and aliases per platform module. +5. `CARGO_BUILD_TARGET` is set by the root `nix develop` shell, so native Linux checks must run outside it + (as `fast-check` does) or pass `--target x86_64-unknown-linux-gnu`. +6. Command names and `--version` text come from `CARGO_PKG_NAME`/the version crate: pin them or the KDE + `version` test and the docs oracle change. `shadow-rs` major versions differ (2 on Windows, 1 on + macOS); the unified `komorebic` build script can only use one. +7. The KDE VM suites rebuild on any change to the KDE closure: the merge is one full `V` run. +8. Tests that use `CARGO_BIN_EXE_*` or relative paths (`tests/schemas.rs` writes beside the manifest) + must move with their package; not exercised beyond the spike. + +## Gates by step, in short + +Compile only: 0, 4 (but see `E`), 5, 6 at the Rust level; nix evaluation only: 3 until built. Needs +e2e (Windows guest): anything that changes an input of `komorebi.exe`, `komorebic.exe` or the client +(`tools/e2e-needed` says: 1 for the Windows daemon, 4, 6, 8). Needs the KDE VM: 2, 3, 8. Needs a Mac, +by hand: 4, 7, 8, 9. + +Mac hand check (type-check proves none of it): `komorebic --version` and `--help` show the macOS +command set and the name `komorebic`; `komorebic start` finds and starts `komorebi`, `stop` stops it; +`komorebic docgen` unchanged; `komorebi --version`; the daemon starts, tiles and `komorebic state` +answers; `komorebi-bar` opens, `--schema` equals `komorebi-for-mac/schema.bar.json`; +the embedded `applications.json` is the macOS one; +`otool -L` of each binary lists no Windows or Linux-only library. + +## Conflicts with the open stacks (sequence in a quiet period) + +Paths touched by each bookmark relative to `wip-main`: + +| bookmark | touches | moves in this plan that conflict | +|---|---|---| +| wip-u-kfw | `komorebi/src/**`, `crates/komorebi-backend/**` | daemon rename and any move of `komorebi/` (steps 1 Windows, 8) | +| wip-u-kfm | `komorebi-for-mac/komorebi/src/**`, `crates/komorebi-backend/**` | macOS daemon rename and moves (1, 8) | +| wip-u-kfde | `komorebi-for-kde/komorebi/{src,tests}/**` | KDE daemon rename (1) and moves (8); tests are edited | +| wip-u-bar | `Cargo.lock`, `komorebi-for-mac/Cargo.lock`, `komorebi-bar/src/**`, `komorebi-for-mac/komorebi-bar/src/**`, `crates/komorebi-bar-core` | step 2 (locks, manifests) and step 7 | +| wip-u-settings | `Cargo.toml`, `Cargo.lock`, `crates/komorebi-settings` | step 2 (root manifest and lock) | +| wip-u-nix | `flake.nix`, `komorebi-for-kde/flake.nix`, `komorebi-for-kde/nix/**` | step 3 | + +Not touched by any open stack, so safe now: `komorebic/**` (all three), the `komorebic` tests, the +`version` crates, the `komorebi-client` crates (steps 0, 4, 5, 6 are free of conflicts except the lock +and root manifest lines of step 2/4). Hard conflicts: every `Cargo.lock` and the root `Cargo.toml` +`members` list (resolve by taking one side and running `cargo metadata`; never hand-merge a lock), +`flake.nix` lines for the extracted binaries. Suggested order: integrate kfw, kfm, kfde, bar, settings, +nix first; then steps 0 and 1; then 2 and 3 as one integration; the rest in any order, daemon (8) +last. + +## What landed + +Only this file. The spike revisions are on `wip-u-pkg-spike` and can be dropped or cherry-picked. +Step 0 and the renames were not landed because they only pay off with step 2, which edits the locks +and manifests that three open stacks edit. diff --git a/flake.nix b/flake.nix index 264b0d41..260f996b 100644 --- a/flake.nix +++ b/flake.nix @@ -235,7 +235,9 @@ # komorebic/build.rs downloads applications.json if it is missing, which # is not possible in the sandbox, so provide the pinned copy instead preBuild = "mkdir -p komorebic && cp ${inputs.asc}/applications.json komorebic/applications.json"; - COMMIT_HASH = commit; + # a constant, so that the dependencies and every check are the same + # derivations for every commit; only fullBuild stamps the real one + COMMIT_HASH = "nix-check"; # build inputs for cross-compilation nativeBuildInputs = [ @@ -278,6 +280,7 @@ individualCrateArgs // { pname = "komorebi-workspace"; + COMMIT_HASH = commit; } ); diff --git a/komorebi-for-kde/flake.nix b/komorebi-for-kde/flake.nix index ea34b59a..1672f309 100644 --- a/komorebi-for-kde/flake.nix +++ b/komorebi-for-kde/flake.nix @@ -36,12 +36,10 @@ crane rust-overlay ; - rootCrates = [ - "crates" - "komorebi-layouts" - "komorebi-scrolling" - "komorebi-themes" - ]; + # the crates of the root workspace that this workspace depends on, by path, directly or not. + # Only these are in the source, so that an edit of another crate (the bar's) changes nothing + # here. `tools/kde-closure-check` fails if this list and `cargo metadata` differ. + rootCrates = builtins.fromJSON (builtins.readFile ./nix/root-crates.json); mkPkgs = system: import nixpkgs { @@ -73,8 +71,10 @@ rootCrate = builtins.any ( crate: relative == crate || pkgs.lib.hasPrefix "${crate}/" relative ) rootCrates; + # the directory that holds the crates of crates/, to reach the listed ones + rootCrateParent = relative == "crates"; in - (rootCrate && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || inTree) + ((rootCrate || rootCrateParent) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || inTree) && # the VM tests (their library, scripts and the states they keep) are not built, so # editing one does not change the source the daemon is built from diff --git a/komorebi-for-kde/nix/root-crates.json b/komorebi-for-kde/nix/root-crates.json new file mode 100644 index 00000000..a764d830 --- /dev/null +++ b/komorebi-for-kde/nix/root-crates.json @@ -0,0 +1,11 @@ +[ + "crates/komorebi-backend", + "crates/komorebi-collections", + "crates/komorebi-config", + "crates/komorebi-protocol", + "crates/komorebi-transport", + "crates/komorebic-core", + "komorebi-layouts", + "komorebi-scrolling", + "komorebi-themes" +] diff --git a/komorebi-for-kde/nix/tests/vm/default.nix b/komorebi-for-kde/nix/tests/vm/default.nix index 0f50c371..79a8b274 100644 --- a/komorebi-for-kde/nix/tests/vm/default.nix +++ b/komorebi-for-kde/nix/tests/vm/default.nix @@ -40,7 +40,9 @@ let pyproject = true; src = lib.fileset.toSource { root = ./lib; - fileset = ./lib; + # not the unit tests: the VM never runs them (setuptools does not package them), so + # editing one must not rebuild every suite; `libCheck` keeps them + fileset = lib.fileset.difference ./lib ./lib/tests; }; build-system = [ ps.setuptools ]; dependencies = [ ps.pillow ]; diff --git a/komorebi-for-mac/komorebi/src/ax_registry.rs b/komorebi-for-mac/komorebi/src/ax_registry.rs new file mode 100644 index 00000000..a3159dac --- /dev/null +++ b/komorebi-for-mac/komorebi/src/ax_registry.rs @@ -0,0 +1,114 @@ +//! The id -> {AX element, pid, observer} table of step 11(ii): what lets anything act on a +//! window from nothing but its `WindowId`. +//! +//! It is `komorebi_backend::Registry` (whose rules are tested natively: thread-safe, nothing of +//! the platform runs under its lock, stale ids are `Error::WindowGone`) instantiated with +//! [`AxEntry`]. +//! +//! # Lifetime +//! +//! An entry is created by `Window::new` and by [`sync`] when a window's element or id changes +//! (a native tab). It ends at every place the daemon learns of a death: +//! +//! - `Window::drop`, when the window is no longer alive ([`forget`]); +//! - the reaper, when it reaps a window ([`forget`]); +//! - an application terminating ([`forget_pid`], from `WindowManagerEvent::Destroy`). +//! +//! A window that is alive and never managed stays registered until it dies or its application +//! quits: the entry only holds retained references that the `Window` clones held anyway. +//! +//! # Threads +//! +//! Callable from any thread. Nothing here dispatches to the main queue or takes the window +//! manager's lock (`docs/dev/seam.md` section 3.3); a closure that runs on the main thread may +//! call it. Handles removed from the table are dropped after the table's lock is released. + +use crate::AccessibilityObserver; +use crate::AccessibilityUiElement; +use crate::application::Application; +use crate::window::Window; +use komorebi_backend::Registry; +use komorebi_backend::Result; +use komorebi_backend::WindowId; +use std::sync::LazyLock; + +/// What it takes to act on one window: its element and observer, and its application (whose +/// element and observer are the application's, and whose `process_id` is the pid). +#[derive(Debug, Clone)] +pub struct AxEntry { + /// The window's Accessibility element + pub element: AccessibilityUiElement, + /// The observer that reports the window's events + pub observer: AccessibilityObserver, + /// The application that owns the window + pub application: Application, +} + +impl AxEntry { + /// The pid of the owning application + pub fn pid(&self) -> i32 { + self.application.process_id + } +} + +static WINDOWS: LazyLock> = LazyLock::new(Registry::new); + +/// Registers the window under its id, replacing what was registered under it. +pub fn register(window: &Window) { + let entry = window.entry(); + let pid = entry.pid(); + // the replaced entry is dropped here, with the table's lock released + drop(WINDOWS.insert(WindowId::from_u32(window.id), pid, entry)); +} + +/// A window changed its id or its element in place (a native tab that is now shown by another +/// element): forget the old id and register the window as it is. +pub fn sync(old_id: u32, window: &Window) { + if old_id != window.id { + forget(old_id); + } + + register(window); +} + +/// Forgets a window that is gone. A second call is not an error. +pub fn forget(id: u32) { + drop(WINDOWS.remove(WindowId::from_u32(id))); +} + +/// Forgets every window of a process that quit. +pub fn forget_pid(pid: i32) { + drop(WINDOWS.remove_pid(pid)); +} + +/// The entry of a window, or `Error::WindowGone` if the id is stale. +pub fn get(id: WindowId) -> Result { + WINDOWS.get(id) +} + +/// A `Window` made from the entry of the id, or `Error::WindowGone` if the id is stale. +pub fn window(id: WindowId) -> Result { + let entry = WINDOWS.get(id)?; + // an id that does not fit a `CGWindowID` cannot have been registered + let raw = id.to_u32().ok_or(komorebi_backend::Error::WindowGone(id))?; + Ok(Window::from_entry(raw, entry)) +} + +/// Every registered window, by id. +pub fn windows() -> Vec { + WINDOWS + .snapshot() + .into_iter() + .filter_map(|(id, entry)| Some(Window::from_entry(id.to_u32()?, entry))) + .collect() +} + +/// The `CGWindowID` of the window that an Accessibility element is, as handed over by the system +/// (an observer callback, the event tap, the focused window of an application). This is the one +/// way to turn an element into the key of the table; a window is registered under what it +/// returns. +pub fn identify( + element: &objc2_application_services::AXUIElement, +) -> std::result::Result { + crate::accessibility::AccessibilityApi::window_id(element) +} diff --git a/komorebi-for-mac/komorebi/src/input_event_listener.rs b/komorebi-for-mac/komorebi/src/input_event_listener.rs index f6154849..f2031c64 100644 --- a/komorebi-for-mac/komorebi/src/input_event_listener.rs +++ b/komorebi-for-mac/komorebi/src/input_event_listener.rs @@ -1,4 +1,3 @@ -use crate::accessibility::AccessibilityApi; use crate::macos_api::MacosApi; use crate::reaper; use crate::reaper::ReaperNotification; @@ -93,7 +92,7 @@ extern "C-unwind" fn callback( } if pid != 0 { - let window_id = AccessibilityApi::window_id(&element).ok(); + let window_id = crate::ax_registry::identify(&element).ok(); // Send MoveEnd to handle pending drag-to-swap operations // macOS doesn't reliably fire AXWindowMoved after mouse release diff --git a/komorebi-for-mac/komorebi/src/lib.rs b/komorebi-for-mac/komorebi/src/lib.rs index a59194ba..8ebc30db 100644 --- a/komorebi-for-mac/komorebi/src/lib.rs +++ b/komorebi-for-mac/komorebi/src/lib.rs @@ -54,6 +54,7 @@ pub mod animation; pub mod app_kit_notification_constants; pub mod application; pub mod arrival; +pub mod ax_registry; pub mod border_manager; pub mod container; pub mod core; @@ -123,6 +124,10 @@ lazy_static! { Arc::new(Mutex::new(HashMap::new())); static ref WORKSPACE_MATCHING_RULES: Arc>> = Arc::new(Mutex::new(Vec::new())); + // LOCK ORDER for the rule lists (as in the KDE tree, minus the lists macOS does not have): + // FLOATING_APPLICATIONS, SESSION_FLOATING_APPLICATIONS, IGNORE_IDENTIFIERS, MANAGE_IDENTIFIERS, + // WORKSPACE_MATCHING_RULES, REGEX_IDENTIFIERS. Take the ones you need in that order and never + // the other way round; a thread that does can deadlock with one that does not. static ref REGEX_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(HashMap::new())); static ref MANAGE_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(vec![])); diff --git a/komorebi-for-mac/komorebi/src/macos_backend.rs b/komorebi-for-mac/komorebi/src/macos_backend.rs index 2a3bca30..ae73aef9 100644 --- a/komorebi-for-mac/komorebi/src/macos_backend.rs +++ b/komorebi-for-mac/komorebi/src/macos_backend.rs @@ -1,5 +1,6 @@ -//! `MacosBackend`: the shared [`komorebi_backend::Backend`] over the existing [`MacosApi`], -//! [`Window`] and [`AdhocWindow`] functions. +//! `MacosBackend`: the shared [`komorebi_backend::Backend`] over the existing [`MacosApi`] and +//! [`Window`] methods (set_rect, focus, raise, hide, restore, minimize, unminimize, close, alive, +//! window_rect and minimized): it holds no Accessibility call of its own. //! //! **Nothing uses it yet.** The daemon still holds `Window` values (element, application and //! observer) and calls them directly; this adapter exists so that the trait is known to be @@ -8,7 +9,8 @@ //! `docs/dev/seam.md`, section 9, and commented where they are. //! //! The trait names a window by an id, and nothing on macOS acts from a bare id: a window is its -//! Accessibility element. So the adapter owns the **id registry** of consequence (1): the daemon +//! Accessibility element. So the backend looks windows up in the **id registry** of consequence +//! (1), `ax_registry`: the daemon //! registers each `Window` it learns of ([`MacosBackend::register`]) and forgets it when it is //! gone, and every method looks the element up by id. An id the registry does not hold is a //! window that is gone. @@ -19,13 +21,10 @@ //! callback refreshes on main with [`MacosBackend::refresh_monitors`]. use crate::LibraryError; -use crate::accessibility::AccessibilityApi; -use crate::accessibility::attribute_constants::kAXMinimizedAttribute; use crate::core::Rect; use crate::core::WindowHidingPosition; use crate::macos_api::MacosApi; use crate::skylight::BatchedUpdates; -use crate::window::AdhocWindow; use crate::window::Window; use komorebi_backend::Backend; use komorebi_backend::Error; @@ -35,9 +34,7 @@ use komorebi_backend::Result; use komorebi_backend::WindowId; use komorebi_backend::WindowInfo; use objc2::MainThreadMarker; -use objc2_core_foundation::CFBoolean; use parking_lot::Mutex; -use std::collections::HashMap; /// The shared [`Backend`] for macOS. /// @@ -45,7 +42,6 @@ use std::collections::HashMap; /// opacity and no focus follows mouse (`docs/dev/seam.md` section 2.1), so those methods answer /// `Unsupported`. pub struct MacosBackend { - windows: Mutex>, monitors: Mutex>, hiding_position: WindowHidingPosition, batches: Mutex>, @@ -67,7 +63,6 @@ impl MacosBackend { /// the monitor's configuration, and the trait has no place for it. pub fn new(hiding_position: WindowHidingPosition) -> Self { Self { - windows: Mutex::new(HashMap::new()), monitors: Mutex::new(Vec::new()), hiding_position, batches: Mutex::new(Vec::new()), @@ -76,12 +71,12 @@ impl MacosBackend { /// Makes the window known to the backend, by its `CGWindowID`. pub fn register(&self, window: Window) { - self.windows.lock().insert(window.id, window); + crate::ax_registry::register(&window); } /// Forgets a window that is gone. pub fn forget(&self, id: u32) { - self.windows.lock().remove(&id); + crate::ax_registry::forget(id); } /// Reads the monitors from `NSScreen` into the cache that [`Backend::monitors`] answers @@ -105,9 +100,7 @@ impl MacosBackend { } fn lookup(&self, id: WindowId) -> Result { - id.to_u32() - .and_then(|raw| self.windows.lock().get(&raw).cloned()) - .ok_or(Error::WindowGone(id)) + crate::ax_registry::window(id) } /// Says why a call about a window failed. A failed write is how macOS finds out that a window @@ -118,7 +111,7 @@ impl MacosBackend { window: &Window, error: impl std::error::Error + Send + Sync + 'static, ) -> Error { - if window.is_valid() { + if window.alive() { platform(error) } else { Error::WindowGone(id) @@ -126,24 +119,16 @@ impl MacosBackend { } fn info(window: &Window) -> Option { - if !window.is_valid() { + if !window.alive() { return None; } - let minimized = AccessibilityApi::copy_attribute_value::( - &window.element, - kAXMinimizedAttribute, - ) - .is_some_and(|b| b.as_bool()); - Some(WindowInfo { id: WindowId::from_u32(window.id), pid: window.application.process_id, // the Accessibility position and size, in points; a failure leaves the default - rect: MacosApi::window_rect(&window.element) - .map(Rect::from) - .unwrap_or_default(), - minimized, + rect: window.window_rect().map(Rect::from).unwrap_or_default(), + minimized: window.minimized(), alive: true, title: window.title(), // macOS has no window class: a bundle identifier, role and subrole instead @@ -162,7 +147,7 @@ impl Backend for MacosBackend { // The registry is the only list there is: the CoreGraphics list joined with the // Accessibility elements by title lives inside `load_workspace_information`, which fills // a `WindowManager`, and the daemon registers what it finds - let registered: Vec<_> = self.windows.lock().values().cloned().collect(); + let registered = crate::ax_registry::windows(); let mut windows: Vec<_> = registered.iter().filter_map(Self::info).collect(); windows.sort_by_key(|w| w.id); windows @@ -187,6 +172,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)] @@ -194,11 +188,11 @@ impl Backend for MacosBackend { } fn set_rect(&self, id: WindowId, rect: &Rect) -> Result<()> { - // `Window::set_position` writes directly (two Accessibility writes) or hands the move to + // `Window::set_rect` writes directly (two Accessibility writes) or hands the move to // the animator, depending on the animation settings; both are requests let window = self.lookup(id)?; window - .set_position(rect) + .set_rect(rect) .map_err(|e| Self::failed(id, &window, e)) } @@ -243,7 +237,7 @@ impl Backend for MacosBackend { fn close(&self, id: WindowId) -> Result<()> { // presses the close button; `Ok` when the window has none let window = self.lookup(id)?; - AdhocWindow::close(&window.element.0).map_err(|e| Self::failed(id, &window, e)) + window.close().map_err(|e| Self::failed(id, &window, e)) } fn center_cursor_in(&self, rect: &Rect) -> Result<()> { diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index 276d9ada..f32d3680 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -9,7 +9,6 @@ use crate::SESSION_FLOATING_APPLICATIONS; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; use crate::WORKSPACE_MATCHING_RULES; -use crate::accessibility::AccessibilityApi; use crate::animation; use crate::animation::ANIMATION_DURATION_GLOBAL; use crate::animation::ANIMATION_DURATION_PER_ANIMATION; @@ -637,7 +636,7 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|(_, w)| { let rect = - Rect::from(MacosApi::window_rect(&w.element).unwrap_or_default()); + Rect::from(w.window_rect().unwrap_or_default()); rect.right * rect.bottom }); window_idx_pairs.reverse(); @@ -707,7 +706,7 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|w| { let rect = Rect::from( - MacosApi::window_rect(&w.element).unwrap_or_default(), + w.window_rect().unwrap_or_default(), ); rect.right * rect.bottom }); @@ -1718,7 +1717,7 @@ impl WindowManager { let application = Application::new(raw_info.owner_pid)?; if let Some(elements) = application.window_elements() { for element in elements { - if let Ok(wid) = AccessibilityApi::window_id(&element) + if let Ok(wid) = crate::ax_registry::identify(&element) && i64::from(wid) == window_id && let Ok(window) = Window::new(element, application.clone()) { diff --git a/komorebi-for-mac/komorebi/src/process_event.rs b/komorebi-for-mac/komorebi/src/process_event.rs index ac23ca20..0a03bcd5 100644 --- a/komorebi-for-mac/komorebi/src/process_event.rs +++ b/komorebi-for-mac/komorebi/src/process_event.rs @@ -6,7 +6,6 @@ use crate::REGEX_IDENTIFIERS; use crate::TABBED_APPLICATIONS; use crate::UNMANAGED_WINDOW_IDS; use crate::WORKSPACE_MATCHING_RULES; -use crate::accessibility::AccessibilityApi; use crate::accessibility::enhanced_ui; use crate::accessibility::error::AccessibilityApiError; use crate::accessibility::error::AccessibilityError; @@ -182,7 +181,7 @@ impl WindowManager { { let application = self.application(event.process_id())?; if let Some(element) = application.main_window() - && let Ok(wid) = AccessibilityApi::window_id(&element) + && let Ok(wid) = crate::ax_registry::identify(&element) { window_id = Some(wid); window_element = Some(AccessibilityUiElement(element.clone())); @@ -260,7 +259,7 @@ impl WindowManager { && window.application.process_id == process_id { let tab_rect = MacosApi::window_rect(&element)?; - let main_rect = match MacosApi::window_rect(&window.element) { + let main_rect = match window.window_rect() { Ok(rect) => rect, Err(AccessibilityError::Api( AccessibilityApiError::InvalidUIElement, @@ -296,7 +295,7 @@ impl WindowManager { // Additional check: verify the stored element belongs to this container // This prevents treating separate windows as tabs when they have matching geometry if let Ok(stored_window_id) = - AccessibilityApi::window_id(&window.element.0) + crate::ax_registry::identify(&window.element.0) && stored_window_id == window.id { // All checks pass: stored element matches container ID = true tab change @@ -316,8 +315,10 @@ impl WindowManager { workspace.containers_mut().get_mut(container_idx) && let Some(window) = container.focused_window_mut() { + let old_id = window.id; window.id = window_id; window.element = AccessibilityUiElement(element.clone()); + crate::ax_registry::sync(old_id, window); } // check monocle_container for tabbed applications @@ -328,7 +329,7 @@ impl WindowManager { && window.application.process_id == process_id { let tab_rect = MacosApi::window_rect(&element)?; - let main_rect = match MacosApi::window_rect(&window.element) { + let main_rect = match window.window_rect() { Ok(rect) => rect, Err(AccessibilityError::Api( AccessibilityApiError::InvalidUIElement, @@ -349,8 +350,10 @@ impl WindowManager { && let Some(monocle) = workspace.monocle_container.as_mut() && let Some(window) = monocle.focused_window_mut() { + let old_id = window.id; window.id = window_id; window.element = AccessibilityUiElement(element.clone()); + crate::ax_registry::sync(old_id, window); } if first_tab_destroyed { @@ -534,7 +537,7 @@ impl WindowManager { { let application = self.application(process_id)?; if let Some(element) = application.main_window() - && let Ok(wid) = AccessibilityApi::window_id(&element) + && let Ok(wid) = crate::ax_registry::identify(&element) { window_id = Some(wid); window_element = Some(element.clone()); @@ -548,12 +551,12 @@ impl WindowManager { let tabbed_applications = TABBED_APPLICATIONS.lock(); if tabbed_applications.contains(&application_name) { // Get the window_id for the new window - if let Ok(new_window_id) = AccessibilityApi::window_id(element) { + if let Ok(new_window_id) = crate::ax_registry::identify(element) { for window in workspace.visible_windows().iter().flatten() { if window.application.name().unwrap_or_default() == application_name { let tab_rect = MacosApi::window_rect(element)?; - let main_rect = MacosApi::window_rect(&window.element)?; + let main_rect = window.window_rect()?; // BOTH conditions must be true: // 1. Geometry matches (original check - preserves existing behavior) // 2. Window IDs match (new check - prevents false positives) @@ -745,6 +748,7 @@ impl WindowManager { ) ) { enhanced_ui::forget(process_id); + crate::ax_registry::forget_pid(process_id); } // some apps like Discord in all of their relentless Electron slop stupidity @@ -897,7 +901,7 @@ impl WindowManager { { // TODO: not sure about this clone let window = window.clone(); - let new_position = Rect::from(MacosApi::window_rect(&window.element)?); + let new_position = Rect::from(window.window_rect()?); let old_position = *workspace .latest_layout .get(focused_container_idx) @@ -1102,7 +1106,7 @@ impl WindowManager { && let Some(window) = container.windows().iter().find(|w| w.id == window_id) { - let started_from = Rect::from(MacosApi::window_rect(&window.element)?); + let started_from = Rect::from(window.window_rect()?); let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); *pending_resize_op = Option::from((window_id, Some(started_from))); @@ -1162,7 +1166,7 @@ impl WindowManager { && let Some(window) = container.windows().iter().find(|w| w.id == window_id) { - let ended_at = Rect::from(MacosApi::window_rect(&window.element)?); + let ended_at = Rect::from(window.window_rect()?); tracing::info!("resizing with mouse"); redraw |= self.resize_by_drag(window_id, started_from, ended_at)?; diff --git a/komorebi-for-mac/komorebi/src/reaper.rs b/komorebi-for-mac/komorebi/src/reaper.rs index 8f88b0c9..362c95b1 100644 --- a/komorebi-for-mac/komorebi/src/reaper.rs +++ b/komorebi-for-mac/komorebi/src/reaper.rs @@ -64,7 +64,7 @@ fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> continue 'notification; } - handle_notification(&mut wm, notification, Window::is_valid)?; + handle_notification(&mut wm, notification, Window::alive)?; } Ok(()) @@ -111,6 +111,9 @@ fn invalid_window_ids( } fn reap_window(wm: &mut WindowManager, window_id: u32) -> color_eyre::Result<()> { + // whatever else happens to the window, the id no longer names anything + crate::ax_registry::forget(window_id); + let mut should_update = false; for monitor in wm.monitors_mut() { for workspace in monitor.workspaces_mut() { diff --git a/komorebi-for-mac/komorebi/src/scrolling.rs b/komorebi-for-mac/komorebi/src/scrolling.rs index a11ae9c3..c87bc504 100644 --- a/komorebi-for-mac/komorebi/src/scrolling.rs +++ b/komorebi-for-mac/komorebi/src/scrolling.rs @@ -303,7 +303,7 @@ impl Workspace { for window in container.windows_mut() { let result = match placement.visibility { Visibility::Visible => window - .set_position(&rect) + .set_rect(&rect) .map(|()| window.note_arrival(&rect, resized)), Visibility::Clipped => { // part of it is in view and the rest is past the edge of the screen, @@ -315,7 +315,7 @@ impl Workspace { } window - .set_position(&target) + .set_rect(&target) .map(|()| window.note_arrival(&target, resized)) } Visibility::OffLeft => { diff --git a/komorebi-for-mac/komorebi/src/settle.rs b/komorebi-for-mac/komorebi/src/settle.rs index d72f2991..1f1f6f67 100644 --- a/komorebi-for-mac/komorebi/src/settle.rs +++ b/komorebi-for-mac/komorebi/src/settle.rs @@ -8,10 +8,8 @@ //! and any that are not where they are to be are sent there again, and looked at once more after //! that. -use crate::accessibility::AccessibilityApi; use crate::animation::animator; use crate::core::Rect; -use crate::macos_api::MacosApi; use crate::window::Snapping; use crate::window::dragged_window; use crate::window::is_parked; @@ -185,9 +183,9 @@ impl WindowManager { return Ok(0); } - let _ = AccessibilityApi::set_messaging_timeout(&window.element, LOOK_TIMEOUT); - let rect = MacosApi::window_rect(&window.element).map(Rect::from); - let _ = AccessibilityApi::set_messaging_timeout(&window.element, 0.0); + let _ = window.set_messaging_timeout(LOOK_TIMEOUT); + let rect = window.window_rect().map(Rect::from); + let _ = window.set_messaging_timeout(0.0); if let Ok(rect) = rect && is_off(&rect, &layout) @@ -208,7 +206,7 @@ impl WindowManager { let _snapping = Snapping::end(); for (window, layout) in &off { - if let Err(error) = window.set_position(layout) { + if let Err(error) = window.set_rect(layout) { tracing::debug!( "live resize: could not send window {} again: {error}", window.id diff --git a/komorebi-for-mac/komorebi/src/static_config.rs b/komorebi-for-mac/komorebi/src/static_config.rs index 5fe68137..3cd71ee4 100644 --- a/komorebi-for-mac/komorebi/src/static_config.rs +++ b/komorebi-for-mac/komorebi/src/static_config.rs @@ -545,16 +545,18 @@ impl ApplyGlobals for StaticConfig { // transparency_manager::TRANSPARENCY_ALPHA // .store(self.transparency_alpha.unwrap_or(200), Ordering::SeqCst); + // the order every other place takes them in (floating, ignore, manage, regex; see lib.rs): + // a thread that takes two in another order can wait for one that holds what it needs + let mut floating_applications = FLOATING_APPLICATIONS.lock(); let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); - let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); let mut manage_identifiers = MANAGE_IDENTIFIERS.lock(); + let mut regex_identifiers = REGEX_IDENTIFIERS.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 titleless_applications = TITLELESS_APPLICATIONS.lock(); let mut tabbed_applications = TABBED_APPLICATIONS.lock(); diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 90e80ad2..247b887e 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -465,7 +465,7 @@ impl Drop for Window { fn drop(&mut self) { // this gets called when a cloned Window is dropped, so we need to make sure it only // invalidates the observer if the Window is no longer open - if !self.is_valid() { + if !self.alive() { tracing::info!( "invalidating window observer for {}", self.title() @@ -476,6 +476,9 @@ impl Drop for Window { // for now - hopefully it doesn't break anything else reaper::send_notification(ReaperNotification::InvalidWindow(self.id)); + // and the id no longer names anything + crate::ax_registry::forget(self.id); + // make sure the observer gets removed from any run loops AccessibilityApi::invalidate_observer(&self.observer); } @@ -520,7 +523,7 @@ impl Serialize for Window { state.serialize_field("id", &self.id)?; state.serialize_field( "rect", - &Rect::from(MacosApi::window_rect(&self.element).unwrap_or_default()), + &Rect::from(self.window_rect().unwrap_or_default()), )?; state.serialize_field("details", &WindowDetails::from(self))?; state.end() @@ -560,16 +563,52 @@ impl Window { Some(window_observer_callback), )?; - Ok(Self { + let window = Self { id: AccessibilityApi::window_id(&element)?, element: AccessibilityUiElement(element), application, observer: AccessibilityObserver(Some(observer)), details: None, - }) + }; + + // so that the window can be found again from its id alone + crate::ax_registry::register(&window); + + Ok(window) } - pub fn is_valid(&self) -> bool { + /// The handles that act on this window, as the registry keeps them + pub(crate) fn entry(&self) -> crate::ax_registry::AxEntry { + crate::ax_registry::AxEntry { + element: self.element.clone(), + observer: self.observer.clone(), + application: self.application.clone(), + } + } + + /// A window made from a registry entry + pub(crate) fn from_entry(id: u32, entry: crate::ax_registry::AxEntry) -> Self { + Self { + id, + element: entry.element, + application: entry.application, + observer: entry.observer, + details: None, + } + } + + /// The frame query (`Backend::window_rect`): the Accessibility position and size, in points. + pub fn window_rect(&self) -> Result { + MacosApi::window_rect(&self.element) + } + + /// How long an Accessibility call to this window's app may block, in seconds (0 restores the + /// system default). Not an operation of the shared `Backend`; it bounds the frame query. + pub fn set_messaging_timeout(&self, seconds: f32) -> Result<(), AccessibilityError> { + AccessibilityApi::set_messaging_timeout(&self.element, seconds) + } + + pub fn alive(&self) -> bool { AccessibilityApi::copy_attribute_names(&self.element).is_some() } @@ -622,7 +661,7 @@ impl Window { // it happened to be when it was hidden let rect = match animator::take_over(self.id) { Some(target) => CGRect::from(target), - None => MacosApi::window_rect(&self.element)?, + None => self.window_rect()?, }; let mut window_restore_positions = WINDOW_RESTORE_POSITIONS.lock(); @@ -706,7 +745,7 @@ impl Window { let rect = match animator::target(self.id) { Some(target) => CGRect::from(target), - None => MacosApi::window_rect(&self.element)?, + None => self.window_rect()?, }; let Some(screen) = screen.or_else(|| CoreGraphicsApi::display_bounds_for_window_rect(rect)) @@ -791,6 +830,12 @@ impl Window { Ok(()) } + /// Whether the window is minimized (the `WindowInfo::minimized` field of the shared `Backend`). + pub fn minimized(&self) -> bool { + AccessibilityApi::copy_attribute_value::(&self.element, kAXMinimizedAttribute) + .is_some_and(|b| b.as_bool()) + } + pub fn minimize(&mut self) -> Result<(), AccessibilityError> { let cf_boolean = CFBoolean::new(true); let value = &**cf_boolean; @@ -803,6 +848,11 @@ impl Window { AccessibilityApi::set_attribute_cf_value(&self.element, kAXMinimizedAttribute, value) } + /// Closes the window by pressing its close button (`Backend::close`); `Ok` when it has none. + pub fn close(&self) -> Result<(), AccessibilityError> { + AdhocWindow::close(&self.element.0) + } + #[tracing::instrument(skip_all)] pub fn restore(&mut self) -> Result<(), AccessibilityError> { // waiting for what is on its way to the window is not something to do with a lock held @@ -912,7 +962,7 @@ impl Window { )) } - pub fn set_position(&self, rect: &Rect) -> Result<(), AccessibilityError> { + pub fn set_rect(&self, rect: &Rect) -> Result<(), AccessibilityError> { match snap() { Snap::Step(dragged) => return self.set_position_for_step(dragged, rect), Snap::End => { @@ -954,9 +1004,9 @@ impl Window { } // the window manager is waiting for this, and so is every window after this one - let _ = AccessibilityApi::set_messaging_timeout(&self.element, ARRIVAL_TIMEOUT); + let _ = self.set_messaging_timeout(ARRIVAL_TIMEOUT); - match MacosApi::window_rect(&self.element) { + match self.window_rect() { Ok(actual) => arrival::report(self.id, *target, Rect::from(actual)), Err(error) => { tracing::debug!( @@ -985,7 +1035,7 @@ impl Window { return; } - let Ok(current) = MacosApi::window_rect(&self.element) else { + let Ok(current) = self.window_rect() else { return; }; @@ -1077,7 +1127,7 @@ impl Window { motion, after: None, }, - || MacosApi::window_rect(&self.element).map(Rect::from), + || self.window_rect().map(Rect::from), ) } @@ -1192,14 +1242,14 @@ impl Window { let target_width = (target_height * aspect_ratio_width) / aspect_ratio_height; (target_width, target_height) } else { - let current_rect = Rect::from(MacosApi::window_rect(&self.element)?); + let current_rect = Rect::from(self.window_rect()?); (current_rect.right, current_rect.bottom) }; let x = work_area.left + ((work_area.right - target_width) / 2); let y = work_area.top + ((work_area.bottom - target_height) / 2); - self.set_position(&Rect { + self.set_rect(&Rect { left: x, top: y, right: target_width, @@ -1212,7 +1262,7 @@ impl Window { current_area: &Rect, target_area: &Rect, ) -> Result<(), AccessibilityError> { - let current_rect = Rect::from(MacosApi::window_rect(&self.element)?); + let current_rect = Rect::from(self.window_rect()?); let x_diff = target_area.left - current_area.left; let y_diff = target_area.top - current_area.top; let x_ratio = f32::abs((target_area.right as f32) / (current_area.right as f32)); @@ -1250,7 +1300,7 @@ impl Window { // let anim_count = ANIMATION_MANAGER // .lock() // .count_in_progress(MovementRenderDispatcher::PREFIX); - // self.set_position(&new_rect, true)?; + // self.set_rect(&new_rect, true)?; // let hwnd = self.hwnd; // // Wait for the animation to finish before maximizing the window again, otherwise // // we would be maximizing the window on the current monitor anyway @@ -1269,11 +1319,11 @@ impl Window { // windows_api::WindowsApi::maximize_window(hwnd); // }); // } else { - // self.set_position(&new_rect, true)?; + // self.set_rect(&new_rect, true)?; // windows_api::WindowsApi::maximize_window(self.hwnd); // } // } else { - self.set_position(&new_rect)?; + self.set_rect(&new_rect)?; // } Ok(()) @@ -1285,7 +1335,7 @@ impl Window { event: Option, debug: &mut RuleDebug, ) -> eyre::Result { - if !self.is_valid() { + if !self.alive() { return Ok(false); } @@ -1641,9 +1691,14 @@ fn window_is_eligible( } } + // Every place that holds two of the rule lists takes them in this order: floating, ignore, + // manage, regex (see the statics in lib.rs). A thread that takes two in another order can wait + // for one that holds what it needs, and both wait for ever. + let floating_identifiers = FLOATING_APPLICATIONS.lock(); + let ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + let manage_identifiers = MANAGE_IDENTIFIERS.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, @@ -1658,7 +1713,6 @@ fn window_is_eligible( false }; - let manage_identifiers = MANAGE_IDENTIFIERS.lock(); let managed_override = if let Some(rule) = should_act( title, exe_name, @@ -1673,7 +1727,6 @@ fn window_is_eligible( false }; - let floating_identifiers = FLOATING_APPLICATIONS.lock(); if let Some(rule) = should_act( title, exe_name, diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index 3bd9cd3a..c7435da3 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -279,7 +279,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - MacosApi::window_rect(&w.element) + w.window_rect() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -305,7 +305,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - MacosApi::window_rect(&w.element) + w.window_rect() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -331,7 +331,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - MacosApi::window_rect(&w.element) + w.window_rect() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -357,7 +357,7 @@ impl WindowManager { .enumerate() .flat_map(|(idx, w)| { (w.id != focused_window_id).then_some( - MacosApi::window_rect(&w.element) + w.window_rect() .ok() .map(|r| (idx, Rect::from(r))), ) @@ -747,7 +747,7 @@ impl WindowManager { MacosApi::foreground_window_id().ok_or_eyre("no foreground window")?; for window in focused_workspace.floating_windows().iter() { if window.id == focused_window_id { - let mut rect = Rect::from(MacosApi::window_rect(&window.element)?); + let mut rect = Rect::from(window.window_rect()?); match direction { OperationDirection::Left => { if rect.left - delta < focused_monitor_work_area.left { @@ -787,7 +787,7 @@ impl WindowManager { } } - window.set_position(&rect)?; + window.set_rect(&rect)?; if mouse_follows_focus { MacosApi::center_cursor_in_rect(&rect)?; @@ -1180,7 +1180,7 @@ impl WindowManager { let mut valid_window_ids = vec![]; if let Some(elements) = application.window_elements() { for element in elements { - if let Ok(window_id) = AccessibilityApi::window_id(&element) { + if let Ok(window_id) = crate::ax_registry::identify(&element) { valid_window_ids.push(window_id); } } @@ -1475,7 +1475,7 @@ impl WindowManager { .into_iter() .flatten() .filter_map(|window| { - MacosApi::window_rect(&window.element) + window.window_rect() .ok() .map(|rect| (window.id, Rect::from(rect))) }) @@ -1696,7 +1696,7 @@ impl WindowManager { for window in workspace.floating_windows().iter() { if window.id == focused_window_id { - let mut rect = Rect::from(MacosApi::window_rect(&window.element)?); + let mut rect = Rect::from(window.window_rect()?); match (direction, sizing) { (OperationDirection::Left, Sizing::Increase) => { if rect.left - delta < focused_monitor_work_area.left { @@ -1750,7 +1750,7 @@ impl WindowManager { } } - window.set_position(&rect)?; + window.set_rect(&rect)?; if mouse_follows_focus { MacosApi::center_cursor_in_rect(&rect)?; @@ -2190,14 +2190,13 @@ impl WindowManager { return Ok(()); } - let element = self - .focused_workspace()? - .container_for_window(window_id) - .and_then(|container| container.windows().iter().find(|w| w.id == window_id)) - .map(|window| window.element.clone()) - .ok_or_eyre("the dragged window is not in a container on the focused workspace")?; - - let now = Rect::from(MacosApi::window_rect(&element)?); + let now = Rect::from( + self.focused_workspace()? + .container_for_window(window_id) + .and_then(|container| container.windows().iter().find(|w| w.id == window_id)) + .ok_or_eyre("the dragged window is not in a container on the focused workspace")? + .window_rect()?, + ); if !self.live_resize_apply(now)? { return Ok(()); diff --git a/komorebi-for-mac/komorebi/src/workspace.rs b/komorebi-for-mac/komorebi/src/workspace.rs index 042eb7b9..7666bf3b 100644 --- a/komorebi-for-mac/komorebi/src/workspace.rs +++ b/komorebi-for-mac/komorebi/src/workspace.rs @@ -553,7 +553,7 @@ impl Workspace { && focused_window.application.process_id == process_id { if !valid_window_ids.contains(&focused_window.id) { - if let Ok(rect) = MacosApi::window_rect(&focused_window.element) { + if let Ok(rect) = focused_window.window_rect() { tracing::debug!( "reaping window {} ({}): rect = {:?}", focused_window.id, @@ -566,7 +566,7 @@ impl Workspace { // if accessibility API calls fail on AXError::InvalidUIElement // let's try and nuke these early - if !focused_window.is_valid() { + if !focused_window.alive() { invalid_window_ids.push(focused_window.id); } } @@ -578,7 +578,7 @@ impl Workspace { if focused_window.application.process_id == process_id && !valid_window_ids.contains(&focused_window.id) { - if let Ok(rect) = MacosApi::window_rect(&focused_window.element) { + if let Ok(rect) = focused_window.window_rect() { tracing::debug!( "reaping monocle window {} ({}): rect = {:?}", focused_window.id, @@ -591,7 +591,7 @@ impl Workspace { // if accessibility API calls fail on AXError::InvalidUIElement // let's try and nuke these early - if !focused_window.is_valid() { + if !focused_window.alive() { invalid_window_ids.push(focused_window.id); } } @@ -599,7 +599,7 @@ impl Workspace { for window in self.floating_windows() { if window.application.process_id == process_id { if !valid_window_ids.contains(&window.id) { - if let Ok(rect) = MacosApi::window_rect(&window.element) { + if let Ok(rect) = window.window_rect() { tracing::debug!( "reaping floating window {} ({}): rect = {:?}", window.id, @@ -612,7 +612,7 @@ impl Workspace { // if accessibility API calls fail on AXError::InvalidUIElement // let's try and nuke these early - if !window.is_valid() { + if !window.alive() { invalid_floating_window_ids.push(window.id); } } @@ -1476,7 +1476,7 @@ impl Workspace { adjusted_work_area.add_padding(container_padding); adjusted_work_area.add_padding(border_offset); adjusted_work_area.add_padding(border_width); - window.set_position(&adjusted_work_area)?; + window.set_rect(&adjusted_work_area)?; }; } else if !self.containers().is_empty() { if self.is_scrolling() { @@ -1503,7 +1503,7 @@ impl Workspace { layout.add_padding(border_width); for window in container.windows_mut() { - if let Err(error) = window.set_position(layout) { + if let Err(error) = window.set_rect(layout) { tracing::warn!("failed to set window position: {error}") } } 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..0d7649b9 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; @@ -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..ebb9707a 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))] @@ -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..ee4d2c53 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -12,6 +12,8 @@ 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::WindowId; use crate::DEFAULT_CONTAINER_PADDING; use crate::DEFAULT_WORKSPACE_PADDING; @@ -438,7 +440,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()?; diff --git a/komorebi/src/monitor_reconciliator/mod.rs b/komorebi/src/monitor_reconciliator/mod.rs index bb00eacb..582b0b98 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; @@ -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)); } } } 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..c7ec8c68 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -93,9 +93,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; @@ -283,7 +285,10 @@ impl WindowManager { if let Some(window) = &mut self.focused_workspace_mut()?.maximized_window { - window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(window.hwnd), + self.mouse_follows_focus, + )?; } } WorkspaceWindowLocation::Container(container_idx, window_idx) => { @@ -300,7 +305,10 @@ impl WindowManager { .floating_windows_mut() .get_mut(window_idx) { - window.focus(self.mouse_follows_focus)?; + backend().focus( + WindowId::from_hwnd(window.hwnd), + self.mouse_follows_focus, + )?; } } } @@ -393,15 +401,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, @@ -1291,7 +1300,9 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|(_, w)| { - let rect = WindowsApi::window_rect(w.hwnd).unwrap_or_default(); + let rect = backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .unwrap_or_default(); rect.right * rect.bottom }); window_idx_pairs.reverse(); @@ -1300,16 +1311,16 @@ impl WindowManager { if i == focused_idx { to_focus = Some(*window); } else { - window.restore(); - window.raise()?; + 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 - focused_window.restore(); - focused_window.raise()?; + let _ = backend().restore(WindowId::from_hwnd(focused_window.hwnd)); + backend().raise(WindowId::from_hwnd(focused_window.hwnd))?; } for container in workspace.containers() { @@ -1330,10 +1341,10 @@ impl WindowManager { if let Some(monocle) = &workspace.monocle_container { if let Some(window) = monocle.focused_window() { to_focus = Some(*window); - window.raise()?; + backend().raise(WindowId::from_hwnd(window.hwnd))?; } for window in workspace.floating_windows() { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } } else { let focused_container_idx = workspace.focused_container_idx(); @@ -1343,7 +1354,7 @@ impl WindowManager { if i == focused_container_idx { to_focus = Some(*window); } - window.raise()?; + backend().raise(WindowId::from_hwnd(window.hwnd))?; } } @@ -1355,7 +1366,9 @@ impl WindowManager { // Sort by window area window_idx_pairs.sort_by_key(|w| { - let rect = WindowsApi::window_rect(w.hwnd).unwrap_or_default(); + let rect = backend() + .frame(WindowId::from_hwnd(w.hwnd)) + .unwrap_or_default(); rect.right * rect.bottom }); @@ -1366,7 +1379,7 @@ impl WindowManager { } }; if let Some(window) = to_focus { - window.focus(mouse_follows_focus)?; + backend().focus(WindowId::from_hwnd(window.hwnd), mouse_follows_focus)?; } } SocketMessage::Stop => { @@ -2283,10 +2296,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) } 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..47183dde 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; } @@ -1129,17 +1131,17 @@ 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()?); @@ -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 { @@ -1508,7 +1510,7 @@ impl WindowManager { } if !ignore_restore { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } } } @@ -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 { @@ -2634,7 +2659,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 +2699,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 +2760,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 +2797,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 +2830,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 +2974,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 +3136,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 +3176,7 @@ impl WindowManager { } for window in workspace.floating_windows_mut() { - window.hide(); + let _ = backend().hide(WindowId::from_hwnd(window.hwnd)); } Ok(()) @@ -3167,7 +3193,7 @@ impl WindowManager { } for window in workspace.floating_windows_mut() { - window.restore(); + let _ = backend().restore(WindowId::from_hwnd(window.hwnd)); } workspace.reintegrate_monocle_container() @@ -4056,7 +4082,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..640fca5d 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(), @@ -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..4eba3431 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 @@ -826,17 +840,17 @@ impl Workspace { } 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();