From 28db46e4f1fd61d7865978fd2cd96f012039aa5c Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 15:33:53 -0700 Subject: [PATCH 01/37] refactor(kde): move transparency enabled and alpha to settings Plan step 10, S4. TRANSPARENCY_ENABLED and TRANSPARENCY_ALPHA are no longer statics: the Transparency and TransparencyAlpha commands and ToggleTransparency write settings().shared.transparency with one update, the load applies both keys as one update, the transparency manager reads the flag and the alpha from one snapshot, and state and the config dump use the accessors. KDE's load RESETS both keys when absent (false, 200), unlike Windows which keeps the value; the delta passed to SharedDelta::apply is built with unwrap_or so that stays exactly as it was. tests/transparency.rs and transparency_config.rs use settings() (the latter pins the load with and without the keys). BEHAVIOUR: (1) ToggleTransparency was a load then a store and is now one update, so two toggles cannot lose each other; (2) the load publishes both keys together. Gate: KDE VM suite for transparency/opacity. Verified: KDE cargo test --locked -p komorebi-linux --lib --tests (lite env): 58 binaries, 623 passed, 0 failed. VM suites not run. --- .../komorebi/src/process_command.rs | 9 +++++---- komorebi-for-kde/komorebi/src/settings.rs | 10 ++++++++++ komorebi-for-kde/komorebi/src/state.rs | 6 ++---- komorebi-for-kde/komorebi/src/static_config.rs | 18 +++++++++++------- .../komorebi/src/transparency_manager.rs | 11 ++++------- .../komorebi/tests/transparency.rs | 8 ++++---- .../komorebi/tests/transparency_config.rs | 10 ++++------ 7 files changed, 40 insertions(+), 32 deletions(-) diff --git a/komorebi-for-kde/komorebi/src/process_command.rs b/komorebi-for-kde/komorebi/src/process_command.rs index 9d2595b8..4d5af6af 100644 --- a/komorebi-for-kde/komorebi/src/process_command.rs +++ b/komorebi-for-kde/komorebi/src/process_command.rs @@ -2048,14 +2048,15 @@ impl WindowManager { theme_manager::send_notification(*theme.clone()); } SocketMessage::Transparency(enable) => { - transparency_manager::TRANSPARENCY_ENABLED.store(enable, Ordering::SeqCst); + crate::settings::settings().update(|settings| settings.shared.transparency.enabled = enable); } SocketMessage::ToggleTransparency => { - let current = transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst); - transparency_manager::TRANSPARENCY_ENABLED.store(!current, Ordering::SeqCst); + crate::settings::settings().update(|settings| { + settings.shared.transparency.enabled = !settings.shared.transparency.enabled; + }); } SocketMessage::TransparencyAlpha(alpha) => { - transparency_manager::TRANSPARENCY_ALPHA.store(alpha, Ordering::SeqCst); + crate::settings::settings().update(|settings| settings.shared.transparency.alpha = alpha); } SocketMessage::BorderColour(kind, r, g, b) => self.set_border_colour(kind, r, g, b), SocketMessage::BorderWidth(width) => { diff --git a/komorebi-for-kde/komorebi/src/settings.rs b/komorebi-for-kde/komorebi/src/settings.rs index 11ce4186..43cb3dc3 100644 --- a/komorebi-for-kde/komorebi/src/settings.rs +++ b/komorebi-for-kde/komorebi/src/settings.rs @@ -67,6 +67,16 @@ pub fn display_index_preferences() -> HashMap { .clone() } +/// `transparency`: whether windows that are not focused are made see-through. +pub fn transparency_enabled() -> bool { + settings().snapshot().shared.transparency.enabled +} + +/// `transparency_alpha`: the opacity, 0 to 255, of a see-through window. +pub fn transparency_alpha() -> u8 { + settings().snapshot().shared.transparency.alpha +} + #[cfg(test)] mod tests { use std::sync::atomic::Ordering; diff --git a/komorebi-for-kde/komorebi/src/state.rs b/komorebi-for-kde/komorebi/src/state.rs index 2d37869d..dc45d00b 100644 --- a/komorebi-for-kde/komorebi/src/state.rs +++ b/komorebi-for-kde/komorebi/src/state.rs @@ -101,10 +101,8 @@ pub struct GlobalState { impl Default for GlobalState { fn default() -> Self { Self { - transparency_enabled: crate::transparency_manager::TRANSPARENCY_ENABLED - .load(std::sync::atomic::Ordering::SeqCst), - transparency_alpha: crate::transparency_manager::TRANSPARENCY_ALPHA - .load(std::sync::atomic::Ordering::SeqCst), + transparency_enabled: crate::settings::transparency_enabled(), + transparency_alpha: crate::settings::transparency_alpha(), transparency_blacklist: TRANSPARENCY_BLACKLIST.lock().clone(), ignore_identifiers: IGNORE_IDENTIFIERS.lock().clone(), manage_identifiers: MANAGE_IDENTIFIERS.lock().clone(), diff --git a/komorebi-for-kde/komorebi/src/static_config.rs b/komorebi-for-kde/komorebi/src/static_config.rs index 42cdbe65..0f199f2f 100644 --- a/komorebi-for-kde/komorebi/src/static_config.rs +++ b/komorebi-for-kde/komorebi/src/static_config.rs @@ -64,7 +64,6 @@ use crate::monitor::MonitorExt; use crate::monitor_reconciliator; use crate::ring::Ring; use crate::theme_manager; -use crate::transparency_manager; use crate::window_manager::WindowManager; use crate::window_manager_event::WindowManagerEvent; use crate::workspace::Workspace; @@ -351,10 +350,10 @@ impl From<&WindowManager> for StaticConfig { border: Option::from(border_manager::BORDER_ENABLED.load(Ordering::SeqCst)), border_colours, transparency: Option::from( - transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst), + crate::settings::transparency_enabled(), ), transparency_alpha: Option::from( - transparency_manager::TRANSPARENCY_ALPHA.load(Ordering::SeqCst), + crate::settings::transparency_alpha(), ), transparency_ignore_rules: None, // border_style: Option::from(STYLE.load()), @@ -555,10 +554,15 @@ impl ApplyGlobals for StaticConfig { // border_manager::send_notification(None); // } // - transparency_manager::TRANSPARENCY_ENABLED - .store(self.transparency.unwrap_or(false), Ordering::SeqCst); - transparency_manager::TRANSPARENCY_ALPHA - .store(self.transparency_alpha.unwrap_or(200), Ordering::SeqCst); + // KDE resets both when the key is absent (unlike Windows, which keeps the value) + crate::settings::settings().update(|settings| { + SharedDelta { + transparency: Some(self.transparency.unwrap_or(false)), + transparency_alpha: Some(self.transparency_alpha.unwrap_or(200)), + ..SharedDelta::default() + } + .apply(&mut settings.shared); + }); // the order every other place takes them in (floating, transparency, ignore, manage, regex): // a thread that takes two in another order can wait for one that holds what it needs diff --git a/komorebi-for-kde/komorebi/src/transparency_manager.rs b/komorebi-for-kde/komorebi/src/transparency_manager.rs index 00d26d02..33518f56 100644 --- a/komorebi-for-kde/komorebi/src/transparency_manager.rs +++ b/komorebi-for-kde/komorebi/src/transparency_manager.rs @@ -19,12 +19,7 @@ use crate::window::should_act; use crate::window_manager::WindowManager; use komorebi_backend::WindowId; use std::collections::HashSet; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU8; -use std::sync::atomic::Ordering; -pub static TRANSPARENCY_ENABLED: AtomicBool = AtomicBool::new(false); -pub static TRANSPARENCY_ALPHA: AtomicU8 = AtomicU8::new(200); /// The opacity of a window that is not see-through at all. const OPAQUE: u8 = 255; @@ -107,8 +102,10 @@ pub fn transparent_windows(wm: &WindowManager) -> Vec { /// are made opaque, and the others are given [`TRANSPARENCY_ALPHA`]. With transparency off, every /// window is opaque. A failure is logged. pub fn apply(wm: &mut WindowManager) { - let alpha = TRANSPARENCY_ALPHA.load(Ordering::SeqCst); - let wanted: HashSet = if TRANSPARENCY_ENABLED.load(Ordering::SeqCst) { + // one snapshot, so the flag and the alpha are from the same configuration + let settings = crate::settings::settings().snapshot(); + let alpha = settings.shared.transparency.alpha; + let wanted: HashSet = if settings.shared.transparency.enabled { transparent_windows(wm).into_iter().collect() } else { HashSet::new() diff --git a/komorebi-for-kde/komorebi/tests/transparency.rs b/komorebi-for-kde/komorebi/tests/transparency.rs index 016a6b6f..8b35cc57 100644 --- a/komorebi-for-kde/komorebi/tests/transparency.rs +++ b/komorebi-for-kde/komorebi/tests/transparency.rs @@ -13,8 +13,6 @@ use komorebi::core::config_generation::MatchingRule; use komorebi::core::config_generation::MatchingStrategy; use komorebi::state::GlobalState; use komorebi::transparency_manager; -use komorebi::transparency_manager::TRANSPARENCY_ALPHA; -use komorebi::transparency_manager::TRANSPARENCY_ENABLED; use komorebi::window::Window; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event::KWinNotification; @@ -75,8 +73,10 @@ static TRANSPARENCY: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// The settings are process-wide, as they are on Windows: one test at a time, from the defaults fn transparency_settings() -> std::sync::MutexGuard<'static, ()> { let guard = TRANSPARENCY.lock().unwrap_or_else(|e| e.into_inner()); - TRANSPARENCY_ENABLED.store(false, std::sync::atomic::Ordering::SeqCst); - TRANSPARENCY_ALPHA.store(200, std::sync::atomic::Ordering::SeqCst); + komorebi::settings::settings().update(|settings| { + settings.shared.transparency.enabled = false; + settings.shared.transparency.alpha = 200; + }); TRANSPARENCY_BLACKLIST.lock().clear(); guard } diff --git a/komorebi-for-kde/komorebi/tests/transparency_config.rs b/komorebi-for-kde/komorebi/tests/transparency_config.rs index 8d138ee4..111d593a 100644 --- a/komorebi-for-kde/komorebi/tests/transparency_config.rs +++ b/komorebi-for-kde/komorebi/tests/transparency_config.rs @@ -12,7 +12,6 @@ use komorebi::backend::with_backend; use komorebi::core::SocketMessage; use komorebi::static_config::StaticConfig; use komorebi::static_config::StaticConfigExt; -use komorebi::transparency_manager; use komorebi::window::Window; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event::KWinNotification; @@ -22,7 +21,6 @@ use parking_lot::Mutex; use std::os::unix::net::UnixListener; use std::path::PathBuf; use std::sync::Arc; -use std::sync::atomic::Ordering; fn write_config(name: &str, json: &str) -> PathBuf { let path = PathBuf::from(format!( @@ -61,9 +59,9 @@ fn the_transparency_keys_of_the_file_are_the_transparency_settings() { with_backend(fake.clone(), || StaticConfig::postload(&path, &wm)).unwrap(); let _ = std::fs::remove_file(&socket); - assert!(transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst)); + assert!(komorebi::settings::transparency_enabled()); assert_eq!( - transparency_manager::TRANSPARENCY_ALPHA.load(Ordering::SeqCst), + komorebi::settings::transparency_alpha(), 120 ); @@ -98,9 +96,9 @@ fn the_transparency_keys_of_the_file_are_the_transparency_settings() { ) .unwrap(); }); - assert!(!transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst)); + assert!(!komorebi::settings::transparency_enabled()); assert_eq!( - transparency_manager::TRANSPARENCY_ALPHA.load(Ordering::SeqCst), + komorebi::settings::transparency_alpha(), 200 ); assert_eq!(fake.opacity_of(46_002), 255, "opaque again"); From b3b7f6c6738118a59f18980a6ec51d4d654fe235 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 15:53:53 -0700 Subject: [PATCH 02/37] fix(nix): give the macOS build the toolchain of the other platforms The first darwin build of the root flake failed in komorebi-workspace-deps: rustc 1.92.0 is not supported by sysinfo@0.39.6 (requires rustc 1.95). rust-toolchain.toml says channel = stable, and kfm-rust-overlay was pinned to 1d3f83ba (January 2026), whose stable is 1.92.0, while the unified lock now has sysinfo 0.39/0.40 and parking_lot 0.13 (rust-version 1.95, the highest in the macOS and the KDE closures by cargo metadata). kfm-rust-overlay (flake.nix, flake.lock, and the pin in komorebi-for-mac/flake.lock) now uses 19ecdd08, the revision the root flake's own rust-overlay and kfde-rust-overlay lock; its stable is 1.99.1. kfm-nixpkgs and every other input are unchanged. Verified (nix eval of drvPath, throwaway git copy before/after): the Windows deps, clippy and nextest, and the kfde deps, clippy, nextest and VM suite stacks are identical; kfm deny, fmt and toml-fmt change (the toolchain). rust-bin.stable.latest version evaluated: 1.99.1 at the new rev, 1.92.0 at the old one. Not verified: the darwin clippy, nextest and deps drvPaths cannot be evaluated on this Linux host (the stub source is a derivation the host cannot build); no build run. --- flake.lock | 8 ++++---- flake.nix | 2 +- komorebi-for-mac/flake.lock | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/flake.lock b/flake.lock index 97e4f01b..383acebe 100644 --- a/flake.lock +++ b/flake.lock @@ -401,17 +401,17 @@ ] }, "locked": { - "lastModified": 1767581716, - "narHash": "sha256-FUbiUzdrGkLou37OGfb4vCLPnqdSIvtmJBxjh2iljiE=", + "lastModified": 1793174968, + "narHash": "sha256-u5nUf4cewaT36iIzG1s/VECktqUMiZaGF5BsgervsvQ=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "1d3f83babdd21e16bf5cfe0f1efcb4f49ee1bc2c", + "rev": "19ecdd08213836b36c4296a3a4f4af5a3d5308db", "type": "github" }, "original": { "owner": "oxalica", "repo": "rust-overlay", - "rev": "1d3f83babdd21e16bf5cfe0f1efcb4f49ee1bc2c", + "rev": "19ecdd08213836b36c4296a3a4f4af5a3d5308db", "type": "github" } }, diff --git a/flake.nix b/flake.nix index d390194c..6433156d 100644 --- a/flake.nix +++ b/flake.nix @@ -41,7 +41,7 @@ kfm-flake-parts.url = "github:hercules-ci/flake-parts/a34fae9c08a15ad73f295041fec82323541400a9"; kfm-flake-parts.inputs.nixpkgs-lib.follows = "kfm-nixpkgs-lib"; kfm-crane.url = "github:ipetkov/crane/7d59256814085fd9666a2ae3e774dc5ee216b630"; - kfm-rust-overlay.url = "github:oxalica/rust-overlay/1d3f83babdd21e16bf5cfe0f1efcb4f49ee1bc2c"; + kfm-rust-overlay.url = "github:oxalica/rust-overlay/19ecdd08213836b36c4296a3a4f4af5a3d5308db"; kfm-rust-overlay.inputs.nixpkgs.follows = "kfm-nixpkgs"; kfm-treefmt-nix.url = "github:numtide/treefmt-nix/d56486eb9493ad9c4777c65932618e9c2d0468fc"; kfm-treefmt-nix.inputs.nixpkgs.follows = "kfm-nixpkgs"; diff --git a/komorebi-for-mac/flake.lock b/komorebi-for-mac/flake.lock index cca90379..66e26c7e 100644 --- a/komorebi-for-mac/flake.lock +++ b/komorebi-for-mac/flake.lock @@ -140,11 +140,11 @@ ] }, "locked": { - "lastModified": 1767581716, - "narHash": "sha256-FUbiUzdrGkLou37OGfb4vCLPnqdSIvtmJBxjh2iljiE=", + "lastModified": 1793174968, + "narHash": "sha256-u5nUf4cewaT36iIzG1s/VECktqUMiZaGF5BsgervsvQ=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "1d3f83babdd21e16bf5cfe0f1efcb4f49ee1bc2c", + "rev": "19ecdd08213836b36c4296a3a4f4af5a3d5308db", "type": "github" }, "original": { From 3c1339a5a448e7c05174433ce6b9f0bc34afb904 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 15:36:09 -0700 Subject: [PATCH 03/37] refactor(kde): move the animation settings to settings, scoped guard for stacking Plan step 10, S5 for KDE. The seven ANIMATION_* statics are gone. The Animation, AnimationDuration, AnimationFps and AnimationStyle commands each write settings().shared.animation with one update (a global value clears that setting's per-prefix map, a prefix inserts one entry, as before); the animation block of a load is one update through SharedDelta::apply (a global value clears the map, a map replaces it, a block without fps has the default, no block keeps everything); movement_animation and movement_style read one snapshot (Animation::motion_for). The seven commands that rearrange a stack (StackWindow, UnstackWindow, StackAll, UnstackAll, CycleStack, CycleStackIndex, FocusStackWindow) used ANIMATION_ENABLED_GLOBAL.swap(false) and store(restore), which overwrote a reload or command that ran in between, and was skipped by an early return. They now hold settings::animation_off(): Handle::scoped on the global enabled flag, which puts the previous value back on drop only if the field still holds false (a change made meanwhile wins, an early return still restores). Same scope as before: the global flag only, not the per-animation map. BEHAVIOUR: (1) one publish per load / command; (2) the restore no longer clobbers a concurrent change; (3) an error return in a stack command now restores the flag. Gate: KDE VM suites that stack windows (stacks, animation). Verified: KDE cargo test --locked -p komorebi-linux --lib --tests (lite env): 58 binaries, 623 passed, 0 failed; the existing tests animation.rs, animation_config.rs (reload: global versus per-kind, fps default) and animation_stack.rs (animation back on after each stack command) read through settings(). VM suites not run. --- .../komorebi/src/animation/mod.rs | 55 ++------- .../komorebi/src/process_command.rs | 107 +++++++++--------- komorebi-for-kde/komorebi/src/settings.rs | 17 +++ .../komorebi/src/static_config.rs | 59 +++------- komorebi-for-kde/komorebi/tests/animation.rs | 4 +- .../komorebi/tests/animation_config.rs | 6 +- .../komorebi/tests/animation_stack.rs | 4 +- 7 files changed, 99 insertions(+), 153 deletions(-) diff --git a/komorebi-for-kde/komorebi/src/animation/mod.rs b/komorebi-for-kde/komorebi/src/animation/mod.rs index 3946ec98..66bdd4d0 100644 --- a/komorebi-for-kde/komorebi/src/animation/mod.rs +++ b/komorebi-for-kde/komorebi/src/animation/mod.rs @@ -10,14 +10,8 @@ use crate::core::animation::AnimationStyle; -use parking_lot::Mutex; pub use prefix::AnimationPrefix; pub use komorebi_config::animation::PerAnimationPrefixConfig; -use std::collections::HashMap; -use std::sync::Arc; -use std::sync::LazyLock; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU64; pub mod prefix; @@ -27,52 +21,27 @@ pub const DEFAULT_ANIMATION_STYLE: AnimationStyle = AnimationStyle::Linear; pub const DEFAULT_ANIMATION_DURATION: u64 = 250; pub const DEFAULT_ANIMATION_FPS: u64 = 60; -pub static ANIMATION_STYLE_GLOBAL: LazyLock>> = - LazyLock::new(|| Arc::new(Mutex::new(DEFAULT_ANIMATION_STYLE))); - -pub static ANIMATION_ENABLED_GLOBAL: LazyLock> = - LazyLock::new(|| Arc::new(AtomicBool::new(DEFAULT_ANIMATION_ENABLED))); - -pub static ANIMATION_DURATION_GLOBAL: LazyLock> = - LazyLock::new(|| Arc::new(AtomicU64::new(DEFAULT_ANIMATION_DURATION))); - -pub static ANIMATION_STYLE_PER_ANIMATION: LazyLock< - Arc>>, -> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new()))); - -pub static ANIMATION_ENABLED_PER_ANIMATION: LazyLock>>> = - LazyLock::new(|| Arc::new(Mutex::new(HashMap::new()))); - -pub static ANIMATION_DURATION_PER_ANIMATION: LazyLock>>> = - LazyLock::new(|| Arc::new(Mutex::new(HashMap::new()))); - -pub static ANIMATION_FPS: AtomicU64 = AtomicU64::new(DEFAULT_ANIMATION_FPS); - /// Returns how long window movement is animated for, in milliseconds, or `None` when it is not /// animated. /// /// The `movement` settings win over the global ones, for whether it is animated and for how long. pub fn movement_animation() -> Option { - let enabled = ANIMATION_ENABLED_PER_ANIMATION - .lock() - .get(&AnimationPrefix::Movement) - .copied() - .unwrap_or_else(|| ANIMATION_ENABLED_GLOBAL.load(std::sync::atomic::Ordering::SeqCst)); - - enabled.then(|| { - ANIMATION_DURATION_PER_ANIMATION - .lock() - .get(&AnimationPrefix::Movement) - .copied() - .unwrap_or_else(|| ANIMATION_DURATION_GLOBAL.load(std::sync::atomic::Ordering::SeqCst)) - }) + crate::settings::settings() + .snapshot() + .shared + .animation + .motion_for(AnimationPrefix::Movement) + .map(|motion| motion.duration_ms) } /// Returns the easing of window movement: the `movement` style, else the global one. pub fn movement_style() -> AnimationStyle { - ANIMATION_STYLE_PER_ANIMATION - .lock() + let snapshot = crate::settings::settings().snapshot(); + let animation = &snapshot.shared.animation; + + animation + .style_per_animation .get(&AnimationPrefix::Movement) .copied() - .unwrap_or_else(|| *ANIMATION_STYLE_GLOBAL.lock()) + .unwrap_or(animation.style) } diff --git a/komorebi-for-kde/komorebi/src/process_command.rs b/komorebi-for-kde/komorebi/src/process_command.rs index 4d5af6af..8a9d0c66 100644 --- a/komorebi-for-kde/komorebi/src/process_command.rs +++ b/komorebi-for-kde/komorebi/src/process_command.rs @@ -219,6 +219,7 @@ //! Once a message has been handled, every subscriber is sent a notification of it //! ([`notify_subscribers`]). +use crate::settings::animation_off; use crate::DATA_DIR; use crate::FLOATING_APPLICATIONS; use crate::IGNORE_IDENTIFIERS; @@ -229,13 +230,6 @@ use crate::SESSION_FLOATING_APPLICATIONS; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; use crate::WORKSPACE_MATCHING_RULES; -use crate::animation::ANIMATION_DURATION_GLOBAL; -use crate::animation::ANIMATION_DURATION_PER_ANIMATION; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; -use crate::animation::ANIMATION_FPS; -use crate::animation::ANIMATION_STYLE_GLOBAL; -use crate::animation::ANIMATION_STYLE_PER_ANIMATION; use crate::backend::backend; use crate::border_manager; use crate::core::ApplicationIdentifier; @@ -1174,36 +1168,30 @@ impl WindowManager { self.move_container_in_cycle_direction(direction)?; } SocketMessage::StackWindow(direction) => { - let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst); + let _animation_off = animation_off(); self.add_window_to_container(direction)?; - ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst); } SocketMessage::UnstackWindow => { - let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst); + let _animation_off = animation_off(); self.remove_window_from_container()?; border_manager::destroy_all_borders()?; - ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst); } SocketMessage::StackAll => { - let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst); + let _animation_off = animation_off(); self.stack_all()?; - ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst); } SocketMessage::UnstackAll => { - let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst); + let _animation_off = animation_off(); self.unstack_all(true)?; border_manager::destroy_all_borders()?; - ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst); } SocketMessage::CycleStack(direction) => { - let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst); + let _animation_off = animation_off(); self.cycle_container_window_in_direction(direction)?; - ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst); } SocketMessage::CycleStackIndex(direction) => { - let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst); + let _animation_off = animation_off(); self.cycle_container_window_index_in_direction(direction)?; - ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst); } SocketMessage::FocusStackWindow(idx) => { // In case you are using this command on a bar on a monitor @@ -1213,9 +1201,8 @@ impl WindowManager { if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { self.focus_monitor(monitor_idx)?; } - let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst); + let _animation_off = animation_off(); self.focus_container_window(idx)?; - ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst); } SocketMessage::CycleFocusMonitor(direction) => { let monitor_idx = direction.next_idx( @@ -2067,41 +2054,51 @@ impl WindowManager { border_manager::BORDER_OFFSET.store(offset, Ordering::SeqCst); border_manager::destroy_all_borders()?; } - SocketMessage::Animation(enable, prefix) => match prefix { - Some(prefix) => { - ANIMATION_ENABLED_PER_ANIMATION - .lock() - .insert(prefix, enable); - } - None => { - ANIMATION_ENABLED_GLOBAL.store(enable, Ordering::SeqCst); - ANIMATION_ENABLED_PER_ANIMATION.lock().clear(); - } - }, - SocketMessage::AnimationDuration(duration, prefix) => match prefix { - Some(prefix) => { - ANIMATION_DURATION_PER_ANIMATION - .lock() - .insert(prefix, duration); - } - None => { - ANIMATION_DURATION_GLOBAL.store(duration, Ordering::SeqCst); - ANIMATION_DURATION_PER_ANIMATION.lock().clear(); - } - }, - SocketMessage::AnimationFps(fps) => { - ANIMATION_FPS.store(fps, Ordering::SeqCst); + SocketMessage::Animation(enable, prefix) => { + crate::settings::settings().update(|settings| { + let animation = &mut settings.shared.animation; + match prefix { + Some(prefix) => { + animation.enabled_per_animation.insert(prefix, enable); + } + None => { + animation.enabled = enable; + animation.enabled_per_animation.clear(); + } + } + }); + } + SocketMessage::AnimationDuration(duration, prefix) => { + crate::settings::settings().update(|settings| { + let animation = &mut settings.shared.animation; + match prefix { + Some(prefix) => { + animation.duration_per_animation.insert(prefix, duration); + } + None => { + animation.duration = duration; + animation.duration_per_animation.clear(); + } + } + }); + } + SocketMessage::AnimationFps(fps) => { + crate::settings::settings().update(|settings| settings.shared.animation.fps = fps); + } + SocketMessage::AnimationStyle(style, prefix) => { + crate::settings::settings().update(|settings| { + let animation = &mut settings.shared.animation; + match prefix { + Some(prefix) => { + animation.style_per_animation.insert(prefix, style); + } + None => { + animation.style = style; + animation.style_per_animation.clear(); + } + } + }); } - SocketMessage::AnimationStyle(style, prefix) => match prefix { - Some(prefix) => { - ANIMATION_STYLE_PER_ANIMATION.lock().insert(prefix, style); - } - None => { - let mut animation_style = ANIMATION_STYLE_GLOBAL.lock(); - *animation_style = style; - ANIMATION_STYLE_PER_ANIMATION.lock().clear(); - } - }, SocketMessage::ReloadHotkeys => crate::kwin::hotkeys::reload()?, SocketMessage::HotkeysState => { let state = serde_json::to_string_pretty(&crate::kwin::hotkeys::state())?; diff --git a/komorebi-for-kde/komorebi/src/settings.rs b/komorebi-for-kde/komorebi/src/settings.rs index 43cb3dc3..a4cf0136 100644 --- a/komorebi-for-kde/komorebi/src/settings.rs +++ b/komorebi-for-kde/komorebi/src/settings.rs @@ -77,6 +77,23 @@ pub fn transparency_alpha() -> u8 { settings().snapshot().shared.transparency.alpha } +/// Turns the global animation off until the guard is dropped, then puts back what it was unless +/// something changed it meanwhile (a reload or a command wins). Per-animation values are not touched. +/// This replaces the `swap(false)` and `store(restore)` pair of the commands that rearrange a stack. +pub fn animation_off() -> komorebi_settings::Scoped<'static, KdeSettings, bool> { + settings().scoped(|settings| &mut settings.shared.animation.enabled, false) +} + +/// `animation.fps`. +pub fn animation_fps() -> u64 { + settings().snapshot().shared.animation.fps +} + +/// The global `animation.enabled`. +pub fn animation_enabled() -> bool { + settings().snapshot().shared.animation.enabled +} + #[cfg(test)] mod tests { use std::sync::atomic::Ordering; diff --git a/komorebi-for-kde/komorebi/src/static_config.rs b/komorebi-for-kde/komorebi/src/static_config.rs index 0f199f2f..ebfb3011 100644 --- a/komorebi-for-kde/komorebi/src/static_config.rs +++ b/komorebi-for-kde/komorebi/src/static_config.rs @@ -33,15 +33,6 @@ use crate::MANAGE_IDENTIFIERS; use crate::REGEX_IDENTIFIERS; use crate::TRANSPARENCY_BLACKLIST; use crate::WORKSPACE_MATCHING_RULES; -use crate::animation::ANIMATION_DURATION_GLOBAL; -use crate::animation::ANIMATION_DURATION_PER_ANIMATION; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; -use crate::animation::ANIMATION_FPS; -use crate::animation::ANIMATION_STYLE_GLOBAL; -use crate::animation::ANIMATION_STYLE_PER_ANIMATION; -use crate::animation::DEFAULT_ANIMATION_FPS; -use crate::animation::PerAnimationPrefixConfig; use crate::backend::backend; use crate::border_manager; use crate::core::CrossBoundaryBehaviour; @@ -72,6 +63,7 @@ use color_eyre::eyre; use crossbeam_channel::Receiver; use hotwatch::EventKind; use hotwatch::Hotwatch; +use komorebi_settings::shared::AnimationDelta; use komorebi_settings::shared::SharedDelta; use komorebi_themes::colour::Colour; use parking_lot::Mutex; @@ -446,44 +438,21 @@ impl ApplyGlobals for StaticConfig { // window::MINIMUM_WIDTH.store(width, Ordering::SeqCst); // } + // the animation block, as one update: a global value clears its per-animation map, a map + // replaces the map, and a block without `fps` has the default (`SharedDelta::apply`) if let Some(animations) = &self.animation { - match &animations.enabled { - PerAnimationPrefixConfig::Prefix(enabled) => { - ANIMATION_ENABLED_PER_ANIMATION.lock().clone_from(enabled); + crate::settings::settings().update(|settings| { + SharedDelta { + animation: Some(AnimationDelta { + enabled: animations.enabled.clone(), + style: animations.style.clone(), + duration: animations.duration.clone(), + fps: animations.fps, + }), + ..SharedDelta::default() } - PerAnimationPrefixConfig::Global(enabled) => { - ANIMATION_ENABLED_GLOBAL.store(*enabled, Ordering::SeqCst); - ANIMATION_ENABLED_PER_ANIMATION.lock().clear(); - } - } - - match &animations.style { - Some(PerAnimationPrefixConfig::Prefix(style)) => { - ANIMATION_STYLE_PER_ANIMATION.lock().clone_from(style); - } - Some(PerAnimationPrefixConfig::Global(style)) => { - let mut animation_style = ANIMATION_STYLE_GLOBAL.lock(); - *animation_style = *style; - ANIMATION_STYLE_PER_ANIMATION.lock().clear(); - } - None => {} - } - - match &animations.duration { - Some(PerAnimationPrefixConfig::Prefix(duration)) => { - ANIMATION_DURATION_PER_ANIMATION.lock().clone_from(duration); - } - Some(PerAnimationPrefixConfig::Global(duration)) => { - ANIMATION_DURATION_GLOBAL.store(*duration, Ordering::SeqCst); - ANIMATION_DURATION_PER_ANIMATION.lock().clear(); - } - None => {} - } - - ANIMATION_FPS.store( - animations.fps.unwrap_or(DEFAULT_ANIMATION_FPS), - Ordering::SeqCst, - ); + .apply(&mut settings.shared); + }); } if let Some(border_width) = self.border_width { diff --git a/komorebi-for-kde/komorebi/tests/animation.rs b/komorebi-for-kde/komorebi/tests/animation.rs index b121b2e1..9ac53f15 100644 --- a/komorebi-for-kde/komorebi/tests/animation.rs +++ b/komorebi-for-kde/komorebi/tests/animation.rs @@ -4,7 +4,6 @@ //! This file has one test because it changes the process-wide animation settings, which every //! other test that asks for the look would see. -use komorebi::animation::ANIMATION_FPS; use komorebi::animation::AnimationPrefix; use komorebi::backend::AnimationLook; use komorebi::backend::fake::Command; @@ -14,7 +13,6 @@ use komorebi::core::SocketMessage; use komorebi::core::animation::AnimationStyle; use komorebi::window_manager::WindowManager; use std::sync::Arc; -use std::sync::atomic::Ordering; #[test] fn the_animation_messages_set_the_animation_and_the_compositor_is_asked_for_it() { @@ -86,6 +84,6 @@ fn the_animation_messages_set_the_animation_and_the_compositor_is_asked_for_it() // the frame rate is kept, and asks nothing of the compositor let asked = fake.commands().len(); send(&mut wm, SocketMessage::AnimationFps(30)); - assert_eq!(ANIMATION_FPS.load(Ordering::SeqCst), 30); + assert_eq!(komorebi::settings::animation_fps(), 30); assert_eq!(fake.commands().len(), asked); } diff --git a/komorebi-for-kde/komorebi/tests/animation_config.rs b/komorebi-for-kde/komorebi/tests/animation_config.rs index 37825de5..adadf3c1 100644 --- a/komorebi-for-kde/komorebi/tests/animation_config.rs +++ b/komorebi-for-kde/komorebi/tests/animation_config.rs @@ -6,7 +6,6 @@ //! other test that asks for the look would see. use color_eyre::eyre; -use komorebi::animation::ANIMATION_FPS; use komorebi::animation::movement_animation; use komorebi::animation::movement_style; use komorebi::backend::fake::FakeBackend; @@ -19,7 +18,6 @@ use parking_lot::Mutex; use std::os::unix::net::UnixListener; use std::path::PathBuf; use std::sync::Arc; -use std::sync::atomic::Ordering; fn write_config(name: &str, json: &str) -> PathBuf { let path = PathBuf::from(format!("/tmp/kmb-anim-{name}-{}.json", std::process::id())); @@ -52,7 +50,7 @@ fn the_animation_key_of_the_file_is_the_animation_settings() { // one value for every kind of animation assert_eq!(movement_animation(), Some(120)); assert_eq!(movement_style(), AnimationStyle::EaseOutExpo); - assert_eq!(ANIMATION_FPS.load(Ordering::SeqCst), 30); + assert_eq!(komorebi::settings::animation_fps(), 30); // a value for the kinds a file names wins over the global ones, which a global value takes away let by_kind = write_config( @@ -66,7 +64,7 @@ fn the_animation_key_of_the_file_is_the_animation_settings() { assert_eq!(movement_animation(), None, "movement is off"); assert_eq!(movement_style(), AnimationStyle::EaseInOutSine); assert_eq!( - ANIMATION_FPS.load(Ordering::SeqCst), + komorebi::settings::animation_fps(), 60, "a file that leaves fps out has the default" ); diff --git a/komorebi-for-kde/komorebi/tests/animation_stack.rs b/komorebi-for-kde/komorebi/tests/animation_stack.rs index 49412f15..58f38ef1 100644 --- a/komorebi-for-kde/komorebi/tests/animation_stack.rs +++ b/komorebi-for-kde/komorebi/tests/animation_stack.rs @@ -5,7 +5,6 @@ //! This file has one test because it changes the process-wide animation settings, which every //! other test that asks for the look would see. -use komorebi::animation::ANIMATION_ENABLED_GLOBAL; use komorebi::backend::AnimationLook; use komorebi::backend::fake::Command; use komorebi::backend::fake::FakeBackend; @@ -19,7 +18,6 @@ use komorebi::window_manager_event::KWinNotification; use komorebi::window_manager_event::SystemNotification; use komorebi::window_manager_event::WindowManagerEvent; use std::sync::Arc; -use std::sync::atomic::Ordering; #[test] fn the_animation_is_on_again_after_a_command_that_changes_a_stack() { @@ -94,7 +92,7 @@ fn the_animation_is_on_again_after_a_command_that_changes_a_stack() { fake.clear_commands(); send(&mut wm, message.clone()); assert!( - ANIMATION_ENABLED_GLOBAL.load(Ordering::SeqCst), + komorebi::settings::animation_enabled(), "the animation is on again after {message:?}" ); assert_eq!( From 6c5945acaee3f8485e237d6085c1a0f08ecca35f Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 17:07:50 -0700 Subject: [PATCH 04/37] test(layouts): every layout, area, count, padding and flip as native checks The layouts, flipping, layout_flip, padding, tiling and closing e2e scenarios assert, among other things, that each layout puts one tile per window inside the work area, none over another, that a flip mirrors the layout and that container padding shrinks each tile. That is arithmetic of komorebi-layouts and needs no window manager. komorebi-layouts/tests/layouts_everywhere.rs runs the eight layouts of the layouts scenario over three work areas (one off the origin, one with negative left), 1 to 12 windows and paddings none/0/10/30, and asserts: one tile per window; inside the area; no overlap; tiles fill the area exactly (all but grid); fewer windows give a tile at least as big; one window has the area less padding; padding shrinks every tile; the three flips equal the unflipped tiles mirrored as a set; a vertical flip only moves tiles up or down. Each test names the e2e checks it mirrors. What stays e2e only: that a daemon hands these rectangles to the OS, and that the OS frames agree (borders, client rounding, timing, the layouts scenario's wait for the windows to settle). Verified: cargo test -p komorebi-layouts --test layouts_everywhere, 8 passed (native, Linux). No source change, no bug found. --- komorebi-layouts/tests/layouts_everywhere.rs | 311 +++++++++++++++++++ 1 file changed, 311 insertions(+) create mode 100644 komorebi-layouts/tests/layouts_everywhere.rs diff --git a/komorebi-layouts/tests/layouts_everywhere.rs b/komorebi-layouts/tests/layouts_everywhere.rs new file mode 100644 index 00000000..4e043697 --- /dev/null +++ b/komorebi-layouts/tests/layouts_everywhere.rs @@ -0,0 +1,311 @@ +//! What the `layouts`, `flipping`, `layout_flip`, `padding` and `tiling` end-to-end scenarios +//! assert about where the layout puts the windows, asserted on the arithmetic alone: every layout, +//! with every count of windows the scenarios use (and more), is inside the work area, with no +//! window over another, and mirrored by a flip. +//! +//! Not covered here, and so still end-to-end: that a daemon takes the layout's rectangles to the +//! operating system and that the operating system's frames agree with them (border widths, client +//! rounding, timing). + +use komorebi_layouts::Arrangement; +use komorebi_layouts::Axis; +use komorebi_layouts::DefaultLayout; +use komorebi_layouts::Rect; +use std::num::NonZeroUsize; + +/// The layouts the `layouts` scenario goes through (its `LAYOUTS`). +const LAYOUTS: [DefaultLayout; 8] = [ + DefaultLayout::BSP, + DefaultLayout::Columns, + DefaultLayout::Rows, + DefaultLayout::VerticalStack, + DefaultLayout::HorizontalStack, + DefaultLayout::UltrawideVerticalStack, + DefaultLayout::Grid, + DefaultLayout::RightMainVerticalStack, +]; + +/// The layouts that tile the whole of the work area (`Grid` leaves a gap with a count it cannot +/// fill with whole cells). +fn fills_the_area(layout: DefaultLayout) -> bool { + layout != DefaultLayout::Grid +} + +const AREAS: [Rect; 3] = [ + Rect { + left: 0, + top: 0, + right: 1920, + bottom: 1080, + }, + // a work area that is not at the origin, as one of a second monitor is + Rect { + left: 1920, + top: 40, + right: 1280, + bottom: 984, + }, + // one that is not a nice number + Rect { + left: -1366, + top: 0, + right: 1366, + bottom: 728, + }, +]; + +fn tiles( + layout: DefaultLayout, + area: &Rect, + count: usize, + padding: Option, + flip: Option, +) -> Vec { + layout.calculate( + area, + NonZeroUsize::new(count).unwrap(), + padding, + flip, + &[], + 0, + None, + &[], + ) +} + +fn inside(r: &Rect, area: &Rect) -> bool { + r.left >= area.left + && r.top >= area.top + && r.left + r.right <= area.left + area.right + && r.top + r.bottom <= area.top + area.bottom +} + +fn overlap(a: &Rect, b: &Rect) -> bool { + a.left < b.left + b.right + && b.left < a.left + a.right + && a.top < b.top + b.bottom + && b.top < a.top + a.bottom +} + +fn area_of(r: &Rect) -> i64 { + i64::from(r.right) * i64::from(r.bottom) +} + +/// `r` mirrored in `area` along `axis`. +fn mirrored(r: &Rect, area: &Rect, axis: Axis) -> Rect { + let mut m = *r; + if matches!(axis, Axis::Horizontal | Axis::HorizontalAndVertical) { + m.left = area.left + (area.left + area.right) - (r.left + r.right); + } + if matches!(axis, Axis::Vertical | Axis::HorizontalAndVertical) { + m.top = area.top + (area.top + area.bottom) - (r.top + r.bottom); + } + m +} + +fn sorted(mut v: Vec) -> Vec { + v.sort_by_key(|r| (r.left, r.top, r.right, r.bottom)); + v +} + +// mirrors: layouts / , windows: every window is where the layout says +#[test] +fn every_layout_gives_one_tile_per_window() { + for layout in LAYOUTS { + for area in &AREAS { + for count in 1..=12 { + assert_eq!( + tiles(layout, area, count, None, None).len(), + count, + "{layout}, {count} windows" + ); + } + } + } +} + +// mirrors: layouts / , windows: ... inside the work area +// mirrors: layouts / , windows: ... and not on each other +// mirrors: tiling / is inside the work area; <a> and <b> do not overlap +#[test] +fn every_layout_keeps_every_tile_inside_the_work_area_and_off_the_others() { + for layout in LAYOUTS { + for area in &AREAS { + for count in 1..=12 { + for padding in [None, Some(0), Some(10), Some(30)] { + let t = tiles(layout, area, count, padding, None); + for (i, r) in t.iter().enumerate() { + assert!( + inside(r, area), + "{layout}, {count} windows, padding {padding:?}: tile {i} {r:?} is outside {area:?}" + ); + // BSP halves a tile per window: past eight windows, with padding on each + // side, a tile of a 1080 px high area is legitimately nothing + assert!( + count > 8 || r.right > 0 && r.bottom > 0, + "{layout}, {count} windows, padding {padding:?}: tile {i} {r:?} is empty" + ); + for (j, o) in t.iter().enumerate().skip(i + 1) { + assert!( + !overlap(r, o), + "{layout}, {count} windows, padding {padding:?}: tiles {i} {r:?} and {j} {o:?} overlap" + ); + } + } + } + } + } + } +} + +// mirrors: tiling / the windows share the work area: none takes all of its width +// mirrors: closing / the windows that are left take more room between them +#[test] +fn without_padding_the_tiles_fill_the_work_area_and_fewer_windows_get_more_room() { + for layout in LAYOUTS.into_iter().filter(|l| fills_the_area(*l)) { + for area in &AREAS { + for count in 1..=12 { + let t = tiles(layout, area, count, None, None); + let total: i64 = t.iter().map(area_of).sum(); + assert_eq!( + total, + area_of(area), + "{layout}, {count} windows leave a gap in {area:?}: {t:?}" + ); + } + // one window fewer: each of the others has at least as much room on average + for count in 2..=12 { + let more = tiles(layout, area, count - 1, None, None); + let less = tiles(layout, area, count, None, None); + let biggest = |v: &[Rect]| v.iter().map(area_of).max().unwrap(); + assert!( + biggest(&more) >= biggest(&less), + "{layout}: {count} windows has a bigger tile than {} windows", + count - 1 + ); + } + } + } +} + +// mirrors: layouts / <layout>, 1 windows: ... (a single window has the whole work area, less +// padding) +#[test] +fn a_single_window_has_the_work_area_less_the_container_padding() { + for layout in LAYOUTS { + for area in &AREAS { + assert_eq!(tiles(layout, area, 1, None, None), vec![*area], "{layout}"); + let p = 10; + let t = tiles(layout, area, 1, Some(p), None); + assert_eq!( + t, + vec![Rect { + left: area.left + p, + top: area.top + p, + right: area.right - 2 * p, + bottom: area.bottom - 2 * p, + }], + "{layout}" + ); + } + } +} + +// mirrors: padding / a container padding 30 px more leaves the windows less room +// mirrors: padding / with the padding as it was, the windows ... have the room they had +#[test] +fn container_padding_takes_room_from_every_tile_and_taking_it_away_gives_it_back() { + for layout in LAYOUTS { + let area = &AREAS[0]; + for count in 1..=8 { + let plain = tiles(layout, area, count, None, None); + let padded = tiles(layout, area, count, Some(30), None); + for (i, (a, b)) in plain.iter().zip(&padded).enumerate() { + assert!( + area_of(b) < area_of(a), + "{layout}, {count} windows: tile {i} did not shrink: {a:?} -> {b:?}" + ); + } + assert_eq!( + plain, + tiles(layout, area, count, None, None), + "{layout}: deterministic" + ); + assert_eq!( + plain, + tiles(layout, area, count, Some(0), None), + "{layout}, {count} windows: padding 0 is no padding" + ); + } + } +} + +// mirrors: flipping / after 'flip-layout horizontal' every window is where the mirror of its place is +// mirrors: flipping / flipped again, every window is where it was +// mirrors: layout_flip / <label>: flipped along both axes +#[test] +fn a_flipped_layout_is_the_layout_mirrored_as_a_set_of_tiles() { + for layout in LAYOUTS { + for area in &AREAS { + for count in 1..=8 { + for axis in [ + Axis::Horizontal, + Axis::Vertical, + Axis::HorizontalAndVertical, + ] { + let plain = tiles(layout, area, count, None, None); + let flipped = tiles(layout, area, count, None, Some(axis)); + let want: Vec<Rect> = plain.iter().map(|r| mirrored(r, area, axis)).collect(); + assert_eq!( + sorted(flipped), + sorted(want), + "{layout}, {count} windows, flip {axis}" + ); + } + } + } + } +} + +// mirrors: layout_flip / <label>: ... the windows have only gone from top to bottom +#[test] +fn a_vertical_flip_only_moves_a_tile_up_or_down() { + for layout in LAYOUTS { + let area = &AREAS[0]; + for count in 1..=8 { + let plain = tiles(layout, area, count, None, None); + let flipped = tiles(layout, area, count, None, Some(Axis::Vertical)); + // the same widths and the same columns: each tile has a partner at the same left and width + let columns = |v: &[Rect]| { + sorted( + v.iter() + .map(|r| Rect { + left: r.left, + top: 0, + right: r.right, + bottom: 0, + }) + .collect(), + ) + }; + assert_eq!( + columns(&plain), + columns(&flipped), + "{layout}, {count} windows" + ); + } + } +} + +// mirrors: layouts / <layout>, <n> windows: every window is where the layout says (the layout +// is the same whenever it is asked for, so the daemon can compare with the OS) +#[test] +fn the_layout_is_a_function_of_its_arguments() { + for layout in LAYOUTS { + for count in 1..=8 { + let a = tiles(layout, &AREAS[1], count, Some(10), Some(Axis::Horizontal)); + let b = tiles(layout, &AREAS[1], count, Some(10), Some(Axis::Horizontal)); + assert_eq!(a, b, "{layout}"); + } + } +} From e7cb3be598eb56a43499c6646b2baaf97b9bb8d7 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 16:31:00 -0700 Subject: [PATCH 05/37] fix(nix): include the pan transcript fixtures in the macOS source The kfm clippy check failed with: couldn't read komorebi-for-mac/komorebi/src/../../komorebic/fixtures/pan3-{long,flick,slow}.transcript.txt. The macOS tests include_str! them, and the source filter drops .txt files (craneLib.filterCargoSources), as the Windows filter did before its own fix. The filter now keeps files under a komorebic/fixtures directory. Verified: the kfm deny drvPath still evaluates (shared source filter); the clippy attribute needs a darwin builder, so it is not verified here. --- komorebi-for-mac/flake.nix | 2 ++ 1 file changed, 2 insertions(+) diff --git a/komorebi-for-mac/flake.nix b/komorebi-for-mac/flake.nix index 7dbe4ab2..80a2c30c 100644 --- a/komorebi-for-mac/flake.nix +++ b/komorebi-for-mac/flake.nix @@ -111,6 +111,8 @@ || (builtins.match ".*/docs/.*" path != null) # embedded by include_str! in komorebic || (pkgs.lib.hasSuffix "/komorebic/src/macos/applications.json" path) + # include_str! by the tests of the macOS daemon + || (builtins.match ".*/komorebic/fixtures/.*" path != null) ); }; From b6c00ef7950b5a61763929563f23255dd2a9eae6 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:38:44 -0700 Subject: [PATCH 06/37] refactor(macos): move the animation settings to settings Plan step 10, S5 for macOS. The seven ANIMATION_* statics are gone. The Animation, AnimationDuration, AnimationFps and AnimationStyle commands each write settings().shared.animation with one update (global value clears the per-prefix map, a prefix inserts one entry); the animation block of a load is one update through SharedDelta::apply (global clears the map, a map replaces it, a block without fps has the default, no block keeps everything). animation::motion_for reads enabled, duration and style from one snapshot (Animation::motion_for) where it read three separate statics, and frame_period reads fps from settings. The suspend() counter (ANIMATIONS_SUSPENDED) is runtime state and stays as it is: it is the model for the KDE and Windows guards. The test-only AnimationsOn helper in window_manager.rs writes through settings(). BEHAVIOUR: the animator, lane and border threads no longer see a half-applied animation reload or command (they can no longer mix the enabled flag of one configuration with the duration or style of another), and a load publishes the block once. Gate: macOS hand check (animation section of the hand-check list). Verified: macOS fake-CC cargo clippy --locked --target aarch64-apple-darwin -p komorebi-macos --all-targets -- -D warnings: clean. Nothing run on a Mac; value semantics rest on the settings crate tests (merge, reset of fps, global clears the map) and the KDE tests that exercise the same delta. --- .../komorebi/src/animation/mod.rs | 58 ++----------- .../komorebi/src/process_command.rs | 85 ++++++++++--------- komorebi-for-mac/komorebi/src/settings.rs | 5 ++ .../komorebi/src/static_config.rs | 59 +++---------- .../komorebi/src/window_manager.rs | 20 +++-- 5 files changed, 86 insertions(+), 141 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/animation/mod.rs b/komorebi-for-mac/komorebi/src/animation/mod.rs index 1213a6d6..5be7b245 100644 --- a/komorebi-for-mac/komorebi/src/animation/mod.rs +++ b/komorebi-for-mac/komorebi/src/animation/mod.rs @@ -1,13 +1,7 @@ use crate::core::animation::AnimationStyle; -use parking_lot::Mutex; pub use prefix::AnimationPrefix; pub use komorebi_config::animation::PerAnimationPrefixConfig; -use std::collections::HashMap; -use std::sync::Arc; -use std::sync::LazyLock; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU64; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::time::Duration; @@ -35,27 +29,6 @@ pub const DEFAULT_ANIMATION_FPS: u64 = 60; /// How many operations have asked for animations to be skipped for as long as they run static ANIMATIONS_SUSPENDED: AtomicUsize = AtomicUsize::new(0); -pub static ANIMATION_STYLE_GLOBAL: LazyLock<Arc<Mutex<AnimationStyle>>> = - LazyLock::new(|| Arc::new(Mutex::new(DEFAULT_ANIMATION_STYLE))); - -pub static ANIMATION_ENABLED_GLOBAL: LazyLock<Arc<AtomicBool>> = - LazyLock::new(|| Arc::new(AtomicBool::new(DEFAULT_ANIMATION_ENABLED))); - -pub static ANIMATION_DURATION_GLOBAL: LazyLock<Arc<AtomicU64>> = - LazyLock::new(|| Arc::new(AtomicU64::new(DEFAULT_ANIMATION_DURATION))); - -pub static ANIMATION_STYLE_PER_ANIMATION: LazyLock< - Arc<Mutex<HashMap<AnimationPrefix, AnimationStyle>>>, -> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new()))); - -pub static ANIMATION_ENABLED_PER_ANIMATION: LazyLock<Arc<Mutex<HashMap<AnimationPrefix, bool>>>> = - LazyLock::new(|| Arc::new(Mutex::new(HashMap::new()))); - -pub static ANIMATION_DURATION_PER_ANIMATION: LazyLock<Arc<Mutex<HashMap<AnimationPrefix, u64>>>> = - LazyLock::new(|| Arc::new(Mutex::new(HashMap::new()))); - -pub static ANIMATION_FPS: AtomicU64 = AtomicU64::new(DEFAULT_ANIMATION_FPS); - /// Skips animations for as long as the guard is held /// /// Some operations, such as stacking windows, rearrange a workspace in a way that animating would @@ -81,29 +54,16 @@ pub fn motion_for(prefix: AnimationPrefix) -> Option<MotionSpec> { return None; } - let enabled = ANIMATION_ENABLED_PER_ANIMATION - .lock() - .get(&prefix) - .copied() - .unwrap_or_else(|| ANIMATION_ENABLED_GLOBAL.load(Ordering::SeqCst)); - - if !enabled { - return None; - } + // one snapshot: enabled, duration and style are read from the same configuration + let motion = crate::settings::settings() + .snapshot() + .shared + .animation + .motion_for(prefix)?; Some(MotionSpec { - duration: Duration::from_millis( - ANIMATION_DURATION_PER_ANIMATION - .lock() - .get(&prefix) - .copied() - .unwrap_or_else(|| ANIMATION_DURATION_GLOBAL.load(Ordering::SeqCst)), - ), - style: ANIMATION_STYLE_PER_ANIMATION - .lock() - .get(&prefix) - .copied() - .unwrap_or_else(|| *ANIMATION_STYLE_GLOBAL.lock()), + duration: Duration::from_millis(motion.duration_ms), + style: motion.style, }) } @@ -114,7 +74,7 @@ pub fn workspace_transitions_enabled() -> bool { /// How long one frame takes, given the configured frames per second pub fn frame_period() -> Duration { - let fps = ANIMATION_FPS.load(Ordering::Relaxed).clamp(1, 240); + let fps = crate::settings::animation_fps().clamp(1, 240); Duration::from_secs_f64(1.0 / fps as f64) } diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index 3d01c6eb..05286068 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -9,13 +9,6 @@ use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; use crate::WORKSPACE_MATCHING_RULES; use crate::animation; -use crate::animation::ANIMATION_DURATION_GLOBAL; -use crate::animation::ANIMATION_DURATION_PER_ANIMATION; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; -use crate::animation::ANIMATION_FPS; -use crate::animation::ANIMATION_STYLE_GLOBAL; -use crate::animation::ANIMATION_STYLE_PER_ANIMATION; use crate::application::Application; use crate::border_manager; use crate::cf_array_as; @@ -1808,41 +1801,51 @@ impl WindowManager { SocketMessage::Theme(ref theme) => { theme_manager::send_notification(*theme.clone()); } - SocketMessage::Animation(enable, prefix) => match prefix { - Some(prefix) => { - ANIMATION_ENABLED_PER_ANIMATION - .lock() - .insert(prefix, enable); - } - None => { - ANIMATION_ENABLED_GLOBAL.store(enable, Ordering::SeqCst); - ANIMATION_ENABLED_PER_ANIMATION.lock().clear(); - } - }, - SocketMessage::AnimationDuration(duration, prefix) => match prefix { - Some(prefix) => { - ANIMATION_DURATION_PER_ANIMATION - .lock() - .insert(prefix, duration); - } - None => { - ANIMATION_DURATION_GLOBAL.store(duration, Ordering::SeqCst); - ANIMATION_DURATION_PER_ANIMATION.lock().clear(); - } - }, - SocketMessage::AnimationFps(fps) => { - ANIMATION_FPS.store(fps, Ordering::SeqCst); + SocketMessage::Animation(enable, prefix) => { + crate::settings::settings().update(|settings| { + let animation = &mut settings.shared.animation; + match prefix { + Some(prefix) => { + animation.enabled_per_animation.insert(prefix, enable); + } + None => { + animation.enabled = enable; + animation.enabled_per_animation.clear(); + } + } + }); + } + SocketMessage::AnimationDuration(duration, prefix) => { + crate::settings::settings().update(|settings| { + let animation = &mut settings.shared.animation; + match prefix { + Some(prefix) => { + animation.duration_per_animation.insert(prefix, duration); + } + None => { + animation.duration = duration; + animation.duration_per_animation.clear(); + } + } + }); + } + SocketMessage::AnimationFps(fps) => { + crate::settings::settings().update(|settings| settings.shared.animation.fps = fps); + } + SocketMessage::AnimationStyle(style, prefix) => { + crate::settings::settings().update(|settings| { + let animation = &mut settings.shared.animation; + match prefix { + Some(prefix) => { + animation.style_per_animation.insert(prefix, style); + } + None => { + animation.style = style; + animation.style_per_animation.clear(); + } + } + }); } - SocketMessage::AnimationStyle(style, prefix) => match prefix { - Some(prefix) => { - ANIMATION_STYLE_PER_ANIMATION.lock().insert(prefix, style); - } - None => { - let mut animation_style = ANIMATION_STYLE_GLOBAL.lock(); - *animation_style = style; - ANIMATION_STYLE_PER_ANIMATION.lock().clear(); - } - }, // Messages of other platforms: answered, and nothing else happens SocketMessage::AddSubscriberPipe(..) | SocketMessage::AltFocusHack(..) diff --git a/komorebi-for-mac/komorebi/src/settings.rs b/komorebi-for-mac/komorebi/src/settings.rs index 1c1f9213..f949c7e6 100644 --- a/komorebi-for-mac/komorebi/src/settings.rs +++ b/komorebi-for-mac/komorebi/src/settings.rs @@ -67,6 +67,11 @@ pub fn display_index_preferences() -> HashMap<usize, String> { .clone() } +/// `animation.fps`. +pub fn animation_fps() -> u64 { + settings().snapshot().shared.animation.fps +} + #[cfg(test)] mod tests { use std::sync::atomic::Ordering; diff --git a/komorebi-for-mac/komorebi/src/static_config.rs b/komorebi-for-mac/komorebi/src/static_config.rs index 018cf428..ffbd9716 100644 --- a/komorebi-for-mac/komorebi/src/static_config.rs +++ b/komorebi-for-mac/komorebi/src/static_config.rs @@ -1,3 +1,4 @@ +use komorebi_settings::shared::AnimationDelta; use komorebi_settings::shared::SharedDelta; use crate::CoreFoundationRunLoop; use crate::DATA_DIR; @@ -10,15 +11,6 @@ use crate::REGEX_IDENTIFIERS; use crate::TABBED_APPLICATIONS; use crate::TITLELESS_APPLICATIONS; use crate::WORKSPACE_MATCHING_RULES; -use crate::animation::ANIMATION_DURATION_GLOBAL; -use crate::animation::ANIMATION_DURATION_PER_ANIMATION; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; -use crate::animation::ANIMATION_FPS; -use crate::animation::ANIMATION_STYLE_GLOBAL; -use crate::animation::ANIMATION_STYLE_PER_ANIMATION; -use crate::animation::DEFAULT_ANIMATION_FPS; -use crate::animation::PerAnimationPrefixConfig; use crate::border_manager; use crate::core::ApplicationIdentifier; use crate::core::CrossBoundaryBehaviour; @@ -421,44 +413,21 @@ impl ApplyGlobals for StaticConfig { // window::MINIMUM_WIDTH.store(width, Ordering::SeqCst); // } + // the animation block, as one update: a global value clears its per-animation map, a map + // replaces the map, and a block without `fps` has the default (`SharedDelta::apply`) if let Some(animations) = &self.animation { - match &animations.enabled { - PerAnimationPrefixConfig::Prefix(enabled) => { - ANIMATION_ENABLED_PER_ANIMATION.lock().clone_from(enabled); + crate::settings::settings().update(|settings| { + SharedDelta { + animation: Some(AnimationDelta { + enabled: animations.enabled.clone(), + style: animations.style.clone(), + duration: animations.duration.clone(), + fps: animations.fps, + }), + ..SharedDelta::default() } - PerAnimationPrefixConfig::Global(enabled) => { - ANIMATION_ENABLED_GLOBAL.store(*enabled, Ordering::SeqCst); - ANIMATION_ENABLED_PER_ANIMATION.lock().clear(); - } - } - - match &animations.style { - Some(PerAnimationPrefixConfig::Prefix(style)) => { - ANIMATION_STYLE_PER_ANIMATION.lock().clone_from(style); - } - Some(PerAnimationPrefixConfig::Global(style)) => { - let mut animation_style = ANIMATION_STYLE_GLOBAL.lock(); - *animation_style = *style; - ANIMATION_STYLE_PER_ANIMATION.lock().clear(); - } - None => {} - } - - match &animations.duration { - Some(PerAnimationPrefixConfig::Prefix(duration)) => { - ANIMATION_DURATION_PER_ANIMATION.lock().clone_from(duration); - } - Some(PerAnimationPrefixConfig::Global(duration)) => { - ANIMATION_DURATION_GLOBAL.store(*duration, Ordering::SeqCst); - ANIMATION_DURATION_PER_ANIMATION.lock().clear(); - } - None => {} - } - - ANIMATION_FPS.store( - animations.fps.unwrap_or(DEFAULT_ANIMATION_FPS), - Ordering::SeqCst, - ); + .apply(&mut settings.shared); + }); } if let Some(border_width) = self.border_width { diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index 2f3f0471..1d6ff564 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -4033,18 +4033,26 @@ mod tests { impl AnimationsOn { fn new() -> Self { - animation::ANIMATION_ENABLED_PER_ANIMATION - .lock() - .insert(AnimationPrefix::Movement, true); + crate::settings::settings().update(|settings| { + settings + .shared + .animation + .enabled_per_animation + .insert(AnimationPrefix::Movement, true); + }); Self } } impl Drop for AnimationsOn { fn drop(&mut self) { - animation::ANIMATION_ENABLED_PER_ANIMATION - .lock() - .remove(&AnimationPrefix::Movement); + crate::settings::settings().update(|settings| { + settings + .shared + .animation + .enabled_per_animation + .remove(&AnimationPrefix::Movement); + }); } } From fcc4da32b9d1e081570836adf8038db8c4e5aaf7 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:34:01 -0700 Subject: [PATCH 07/37] refactor(kde,mac): window_manager.rs asks window::foreground_window_id() for the focus Both daemons' window_manager.rs read the focused window's id the same way: `foreground_window_id()` from their own window.rs (KDE's is the backend query it already had there; macOS gets the one-line wrapper of MacosApi::foreground_window_id). The inline `backend().foreground_window() .and_then(WindowId::to_u32)` chains on KDE and the `MacosApi::` calls on macOS go, which is the first step to the same text in the two files (the Windows one is not touched). No behaviour change. Verified: KDE cargo test -p komorebi-linux (lite env): 664 passed, 0 failed; fake-CC cargo clippy -p komorebi-macos -p komorebic-macos -p komorebi-client-macos -p komorebi-bar-macos --all-targets -D warnings: PASS (type-check only). Not run: the macOS tests (the Mac Mini), VM suites. --- .../komorebi/src/window_manager.rs | 55 +++++-------------- komorebi-for-mac/komorebi/src/window.rs | 5 ++ .../komorebi/src/window_manager.rs | 31 +++++------ 3 files changed, 35 insertions(+), 56 deletions(-) diff --git a/komorebi-for-kde/komorebi/src/window_manager.rs b/komorebi-for-kde/komorebi/src/window_manager.rs index 86776110..2d952b57 100644 --- a/komorebi-for-kde/komorebi/src/window_manager.rs +++ b/komorebi-for-kde/komorebi/src/window_manager.rs @@ -48,9 +48,6 @@ //! //! [`listen_for_commands`]: crate::process_command::listen_for_commands -use crate::monitor::MonitorExt; -use crate::scrolling::WorkspaceScrolling; -use crate::workspace::WorkspaceExt; use crate::DATA_DIR; use crate::HIDDEN_WINDOWS; use crate::LibraryError; @@ -80,21 +77,24 @@ use crate::core::config_generation::MatchingRule; use crate::desktop; use crate::lockable_sequence::Lockable; use crate::monitor::Monitor; +use crate::monitor::MonitorExt; use crate::ring::Ring; +use crate::scrolling::WorkspaceScrolling; use crate::static_config::StaticConfig; use crate::static_config::StaticConfigExt; use crate::window::Window; +use crate::window::foreground_window_id; use crate::window::should_act_individual; use crate::window_manager_event::WindowManagerEvent; use crate::window_manager_event_listener; use crate::workspace::Workspace; +use crate::workspace::WorkspaceExt; use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use color_eyre::eyre::OptionExt; use color_eyre::eyre::bail; use crossbeam_channel::Receiver; use hotwatch::Hotwatch; -use komorebi_backend::WindowId; use parking_lot::Mutex; use std::collections::HashMap; use std::collections::HashSet; @@ -324,10 +324,7 @@ impl WindowManager { let len = focused_workspace.floating_windows().len(); if len > 1 { - let focused_window_id = backend() - .foreground_window() - .and_then(WindowId::to_u32) - .ok_or_eyre("no foreground window")?; + let focused_window_id = foreground_window_id().ok_or_eyre("no foreground window")?; let focused_rect = Window::from(focused_window_id).rect()?; match direction { @@ -800,10 +797,7 @@ impl WindowManager { let focused_workspace = self.focused_workspace()?; let delta = self.resize_delta; - let focused_window_id = backend() - .foreground_window() - .and_then(WindowId::to_u32) - .ok_or_eyre("no foreground window")?; + let focused_window_id = 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 = window.rect()?; @@ -1706,10 +1700,7 @@ impl WindowManager { /// - The workspace cannot be tiled again. #[tracing::instrument(skip(self))] pub fn toggle_float(&mut self, force_float: bool) -> eyre::Result<()> { - let window_id = backend() - .foreground_window() - .and_then(WindowId::to_u32) - .ok_or_eyre("no foreground window")?; + let window_id = foreground_window_id().ok_or_eyre("no foreground window")?; let workspace = self.focused_workspace_mut()?; if workspace.monocle_container.is_some() { @@ -1816,10 +1807,8 @@ impl WindowManager { match workspace.layer { WorkspaceLayer::Floating => { let workspace = self.focused_workspace()?; - let focused_window_id = backend() - .foreground_window() - .and_then(WindowId::to_u32) - .ok_or_eyre("no foreground window")?; + let focused_window_id = + foreground_window_id().ok_or_eyre("no foreground window")?; let border_offset = 0; let border_width = 0; @@ -2476,10 +2465,7 @@ impl WindowManager { eyre::bail!("cannot move native maximized window to another monitor or workspace"); } - let foreground_window_id = backend() - .foreground_window() - .and_then(WindowId::to_u32) - .ok_or_eyre("no foreground window")?; + let foreground_window_id = foreground_window_id().ok_or_eyre("no foreground window")?; let floating_window_index = workspace .floating_windows() .iter() @@ -2772,10 +2758,7 @@ impl WindowManager { let len = focused_workspace.floating_windows().len(); if len > 1 { - let focused_window_id = backend() - .foreground_window() - .and_then(WindowId::to_u32) - .ok_or_eyre("no foreground window")?; + let focused_window_id = foreground_window_id().ok_or_eyre("no foreground window")?; for (idx, window) in focused_workspace.floating_windows().iter().enumerate() { if window.id == focused_window_id { match direction { @@ -3276,10 +3259,8 @@ impl WindowManager { OperationBehaviour::NoOp ) { let workspace = self.focused_workspace()?; - let focused_hwnd = backend() - .foreground_window() - .and_then(WindowId::to_u32) - .ok_or_eyre("there is no foreground window")?; + let focused_hwnd = + foreground_window_id().ok_or_eyre("there is no foreground window")?; if !workspace.contains_managed_window(focused_hwnd) { bail!("ignoring commands while active window is not managed by komorebi"); } @@ -3810,10 +3791,7 @@ impl WindowManager { /// The compositor reports no focused window. #[tracing::instrument(skip(self))] pub fn manage_focused_window(&mut self) -> eyre::Result<()> { - let window_id = backend() - .foreground_window() - .and_then(WindowId::to_u32) - .ok_or_eyre("there is no foreground window")?; + let window_id = foreground_window_id().ok_or_eyre("there is no foreground window")?; UNMANAGED_WINDOW_IDS.lock().retain(|id| *id != window_id); @@ -3833,10 +3811,7 @@ impl WindowManager { /// The compositor reports no focused window. #[tracing::instrument(skip(self))] pub fn unmanage_focused_window(&mut self) -> eyre::Result<()> { - let window_id = backend() - .foreground_window() - .and_then(WindowId::to_u32) - .ok_or_eyre("there is no foreground window")?; + let window_id = foreground_window_id().ok_or_eyre("there is no foreground window")?; window_manager_event_listener::send_notification(WindowManagerEvent::Unmanage( Window::from(window_id), diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 7d1dd991..0684803c 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -551,6 +551,11 @@ impl schemars::JsonSchema for Window { } } +/// The id of the window that has the focus, if any window does +pub fn foreground_window_id() -> Option<u32> { + MacosApi::foreground_window_id() +} + impl Window { pub fn new( element: CFRetained<AXUIElement>, diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index 2f3f0471..a1aba496 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -1,4 +1,3 @@ -use crate::monitor::MonitorExt; use crate::AccessibilityUiElement; use crate::CoreFoundationRunLoop; use crate::DATA_DIR; @@ -41,6 +40,7 @@ use crate::current_space_id; use crate::lockable_sequence::Lockable; use crate::macos_api::MacosApi; use crate::monitor::Monitor; +use crate::monitor::MonitorExt; use crate::pan::Pan; use crate::ring::Ring; use crate::scrolling::WorkspaceScrolling; @@ -52,6 +52,7 @@ use crate::window::AdhocWindow; use crate::window::Snapping; use crate::window::Window; use crate::window::dragged_window; +use crate::window::foreground_window_id; use crate::window::live_resize_begins; use crate::window::live_resize_ends; use crate::window::should_act_individual; @@ -267,8 +268,7 @@ impl WindowManager { let len = focused_workspace.floating_windows().len(); if len > 1 { - let focused_window_id = - MacosApi::foreground_window_id().ok_or_eyre("no foreground window")?; + let focused_window_id = foreground_window_id().ok_or_eyre("no foreground window")?; let focused_rect = Rect::from(MacosApi::window_rect( MacosApi::foreground_window() .ok_or_eyre("no foreground window")? @@ -735,8 +735,7 @@ impl WindowManager { let focused_workspace = self.focused_workspace()?; let delta = self.resize_delta; - let focused_window_id = - MacosApi::foreground_window_id().ok_or_eyre("no foreground window")?; + let focused_window_id = 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(window.window_rect()?); @@ -1548,7 +1547,8 @@ impl WindowManager { let hiding_position = self .focused_monitor() .ok_or_eyre("there is no monitor")? - .extra.window_hiding_position; + .extra + .window_hiding_position; let workspace = self.focused_workspace_mut()?; workspace.new_monocle_container()?; @@ -1584,7 +1584,8 @@ impl WindowManager { let hiding_position = self .focused_monitor() .ok_or_eyre("there is no monitor")? - .extra.window_hiding_position; + .extra + .window_hiding_position; self.focused_workspace_mut()? .cycle_monocle_container(direction)?; @@ -1598,7 +1599,7 @@ impl WindowManager { #[tracing::instrument(skip(self))] pub fn toggle_float(&mut self, force_float: bool) -> eyre::Result<()> { - let window_id = MacosApi::foreground_window_id().ok_or_eyre("no foreground window")?; + let window_id = foreground_window_id().ok_or_eyre("no foreground window")?; let workspace = self.focused_workspace_mut()?; if workspace.monocle_container.is_some() { @@ -1674,7 +1675,7 @@ impl WindowManager { WorkspaceLayer::Floating => { let workspace = self.focused_workspace()?; let focused_window_id = - MacosApi::foreground_window_id().ok_or_eyre("no foreground window")?; + foreground_window_id().ok_or_eyre("no foreground window")?; let border_offset = 0; let border_width = 0; @@ -2570,8 +2571,7 @@ impl WindowManager { eyre::bail!("cannot move native maximized window to another monitor or workspace"); } - let foreground_window_id = - MacosApi::foreground_window_id().ok_or_eyre("no foreground window")?; + let foreground_window_id = foreground_window_id().ok_or_eyre("no foreground window")?; let floating_window_index = workspace .floating_windows() .iter() @@ -2836,8 +2836,7 @@ impl WindowManager { let len = focused_workspace.floating_windows().len(); if len > 1 { - let focused_window_id = - MacosApi::foreground_window_id().ok_or_eyre("no foreground window")?; + let focused_window_id = foreground_window_id().ok_or_eyre("no foreground window")?; for (idx, window) in focused_workspace.floating_windows().iter().enumerate() { if window.id == focused_window_id { match direction { @@ -3270,7 +3269,7 @@ impl WindowManager { ) { let workspace = self.focused_workspace()?; let focused_hwnd = - MacosApi::foreground_window_id().ok_or_eyre("there is no foreground window")?; + foreground_window_id().ok_or_eyre("there is no foreground window")?; if !workspace.contains_managed_window(focused_hwnd) { bail!("ignoring commands while active window is not managed by komorebi"); } @@ -3675,7 +3674,7 @@ impl WindowManager { #[tracing::instrument(skip(self))] pub fn manage_focused_window(&mut self) -> eyre::Result<()> { let element = MacosApi::foreground_window().ok_or_eyre("there is no foreground window")?; - let window_id = MacosApi::foreground_window_id(); + let window_id = foreground_window_id(); if let Some(process_id) = AdhocWindow::process_id(&element) && let Some(event) = WindowManagerEvent::from_system_notification( SystemNotification::Manual(ManualNotification::Manage), @@ -3696,7 +3695,7 @@ impl WindowManager { #[tracing::instrument(skip(self))] pub fn unmanage_focused_window(&mut self) -> eyre::Result<()> { let element = MacosApi::foreground_window().ok_or_eyre("there is no foreground window")?; - let window_id = MacosApi::foreground_window_id(); + let window_id = foreground_window_id(); if let Some(process_id) = AdhocWindow::process_id(&element) && let Some(event) = WindowManagerEvent::from_system_notification( SystemNotification::Manual(ManualNotification::Unmanage), From 827d7b6ffb0833c22dee4c2d55a78a4e58388030 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 17:08:05 -0700 Subject: [PATCH 08/37] test(kde): rule matching by kind, strategy and composite as native checks The rules, rules_class, rules_exe, manage_rules and title_rule e2e scenarios need a real window to decide WHICH window a rule catches; that decision is the pure should_act / should_act_individual of the daemon, which no existing test exercised strategy by strategy (the KDE tests only add a rule or two). komorebi-for-kde/komorebi/tests/rule_matching.rs adds 13 tests: Equals, StartsWith, EndsWith, Contains and the four DoesNot* strategies over title, class, exe and path; each kind reads only its own part of the window; Regex with and without a compiled regex and over several classes; the .exe suffix of an id is ignored; no strategy and Legacy keep the old semantics; simple and composite rules; the last matching rule wins; no rules match nothing; a rule by title follows the title asked about; an ignore rule keeps a window out and a manage rule rescues one (through SocketMessage::IgnoreRule / ManageRule and a FakeBackend desktop). Each test names the e2e check it mirrors. What stays e2e only: that the daemon evaluates rules when a window opens and not when it is renamed, that the window then lands on the right workspace and is put away or shown, and the title, class and exe the real OS reports. The rule matching exists once per platform (no shared function in komorebi-config), so this covers the KDE copy only; the Windows and macOS copies stay unproven natively. Verified: cargo test -p komorebi-linux --test rule_matching in komorebi-for-kde, 13 passed (native, Linux). No source change, no bug found. --- .../komorebi/tests/rule_matching.rs | 468 ++++++++++++++++++ 1 file changed, 468 insertions(+) create mode 100644 komorebi-for-kde/komorebi/tests/rule_matching.rs diff --git a/komorebi-for-kde/komorebi/tests/rule_matching.rs b/komorebi-for-kde/komorebi/tests/rule_matching.rs new file mode 100644 index 00000000..82de0259 --- /dev/null +++ b/komorebi-for-kde/komorebi/tests/rule_matching.rs @@ -0,0 +1,468 @@ +//! How a rule matches a window: the kinds (title, class, exe, path), every matching strategy, +//! composite rules, the last rule that matches winning, and a manage rule rescuing a window an +//! ignore rule covers. These are the pure functions every rule-driven behaviour of the daemon +//! goes through, so what the `rules`, `rules_class`, `rules_exe`, `manage_rules`, `title_rule` +//! and `startup_rules` end-to-end scenarios assert about WHICH window a rule catches is asserted +//! here with no window manager. +//! +//! Not covered here, and so still end-to-end: that the daemon applies the rule at the right moment +//! (when the window opens, not when it is renamed later), that the window then lands on the right +//! workspace and is hidden or shown, and what the OS reports as a window's title, class and +//! executable. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::ApplicationIdentifier; +use komorebi::core::SocketMessage; +use komorebi::core::config_generation::IdWithIdentifier; +use komorebi::core::config_generation::MatchingRule; +use komorebi::core::config_generation::MatchingStrategy; +use komorebi::window::Window; +use komorebi::window::should_act; +use komorebi::window::should_act_individual; +use komorebi::window::should_act_window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use regex::Regex; +use std::collections::HashMap; +use std::sync::Arc; + +fn id( + kind: ApplicationIdentifier, + id: &str, + strategy: Option<MatchingStrategy>, +) -> IdWithIdentifier { + IdWithIdentifier { + kind, + id: id.to_string(), + matching_strategy: strategy, + } +} + +fn simple(kind: ApplicationIdentifier, text: &str, strategy: MatchingStrategy) -> MatchingRule { + MatchingRule::Simple(id(kind, text, Some(strategy))) +} + +fn no_regex() -> HashMap<String, Regex> { + HashMap::new() +} + +/// The window every test asks about. +const TITLE: &str = "komorebi-e2e: rule target"; +const EXE: &str = "kwrite"; +const CLASS: &str = "org.kde.kwrite"; +const PATH: &str = "/usr/bin/kwrite"; + +fn matches(rule: &IdWithIdentifier) -> bool { + should_act_individual(TITLE, EXE, &[CLASS], PATH, rule, &no_regex()) +} + +fn kinds() -> [ApplicationIdentifier; 4] { + [ + ApplicationIdentifier::Title, + ApplicationIdentifier::Class, + ApplicationIdentifier::Exe, + ApplicationIdentifier::Path, + ] +} + +fn text_of(kind: ApplicationIdentifier) -> &'static str { + match kind { + ApplicationIdentifier::Title => TITLE, + ApplicationIdentifier::Class => CLASS, + ApplicationIdentifier::Exe => EXE, + ApplicationIdentifier::Path => PATH, + } +} + +// mirrors: rules / a window an initial rule matches goes to the workspace the rule names (by title) +// mirrors: rules_class / a window a class rule matches goes to the workspace the rule names +// mirrors: rules_exe / a window an exe rule matches goes to the workspace the rule names +#[test] +fn equals_matches_the_whole_text_of_each_kind_and_nothing_else() { + for kind in kinds() { + let text = text_of(kind); + assert!( + matches(&id(kind, text, Some(MatchingStrategy::Equals))), + "{kind:?}" + ); + assert!( + !matches(&id( + kind, + &text[..text.len() - 1], + Some(MatchingStrategy::Equals) + )), + "{kind:?}: a prefix is not equal" + ); + assert!( + !matches(&id( + kind, + &format!("{text}x"), + Some(MatchingStrategy::Equals) + )), + "{kind:?}: a longer text is not equal" + ); + } +} + +// mirrors: rules / a window of another title stays (the rule does not catch it) +// mirrors: rules_class / a window of another class stays on the first workspace +// mirrors: rules_exe / a window of another program stays on the first workspace +#[test] +fn each_kind_looks_at_its_own_part_of_the_window_only() { + // the title of the window as the id of a class rule, and so on: no kind reads another's text + for kind in kinds() { + for other in kinds().into_iter().filter(|o| *o != kind) { + assert!( + !matches(&id(kind, text_of(other), Some(MatchingStrategy::Equals))), + "a {kind:?} rule matched the {other:?} of the window" + ); + } + } +} + +#[test] +fn starts_with_ends_with_and_contains_match_the_part_they_name() { + for kind in kinds() { + let text = text_of(kind); + let head = &text[..4]; + let tail = &text[text.len() - 4..]; + let middle = &text[2..text.len() - 2]; + for (strategy, yes, no) in [ + (MatchingStrategy::StartsWith, head, tail), + (MatchingStrategy::EndsWith, tail, head), + (MatchingStrategy::Contains, middle, "not-in-the-window"), + ] { + assert!( + matches(&id(kind, yes, Some(strategy.clone()))), + "{kind:?} {strategy}" + ); + assert!( + !matches(&id(kind, no, Some(strategy.clone()))), + "{kind:?} {strategy}" + ); + } + } +} + +#[test] +fn every_negated_strategy_is_the_opposite_of_its_positive_one() { + for kind in kinds() { + let text = text_of(kind); + let head = &text[..4]; + let tail = &text[text.len() - 4..]; + for (positive, negative, text) in [ + ( + MatchingStrategy::Equals, + MatchingStrategy::DoesNotEqual, + text, + ), + ( + MatchingStrategy::StartsWith, + MatchingStrategy::DoesNotStartWith, + head, + ), + ( + MatchingStrategy::EndsWith, + MatchingStrategy::DoesNotEndWith, + tail, + ), + ( + MatchingStrategy::Contains, + MatchingStrategy::DoesNotContain, + head, + ), + ] { + for probe in [text, "zzzz-not-there"] { + let p = matches(&id(kind, probe, Some(positive.clone()))); + let n = matches(&id(kind, probe, Some(negative.clone()))); + assert_ne!(p, n, "{kind:?}: {positive} and {negative} for {probe:?}"); + } + } + } +} + +// mirrors: rules / a window a rule by the name of a workspace matches goes to that workspace +#[test] +fn a_regex_rule_matches_with_the_compiled_regex_and_nothing_without_one() { + let pattern = "^komorebi-e2e: .* target$"; + let rule = id( + ApplicationIdentifier::Title, + pattern, + Some(MatchingStrategy::Regex), + ); + let mut compiled = HashMap::new(); + compiled.insert(pattern.to_string(), Regex::new(pattern).unwrap()); + + assert!(should_act_individual( + TITLE, + EXE, + &[CLASS], + PATH, + &rule, + &compiled + )); + assert!(!should_act_individual( + "another", + EXE, + &[CLASS], + PATH, + &rule, + &compiled + )); + // the daemon compiles every regex when it loads the rules: an id it has not compiled matches nothing + assert!(!should_act_individual( + TITLE, + EXE, + &[CLASS], + PATH, + &rule, + &no_regex() + )); +} + +#[test] +fn a_regex_rule_can_catch_any_of_the_classes_of_a_window() { + let pattern = "^org\\.kde\\."; + let rule = id( + ApplicationIdentifier::Class, + pattern, + Some(MatchingStrategy::Regex), + ); + let mut compiled = HashMap::new(); + compiled.insert(pattern.to_string(), Regex::new(pattern).unwrap()); + assert!(should_act_individual( + TITLE, + EXE, + &["x", CLASS], + PATH, + &rule, + &compiled + )); + assert!(!should_act_individual( + TITLE, + EXE, + &["x", "y"], + PATH, + &rule, + &compiled + )); +} + +// mirrors: rules_exe / a window an exe rule matches goes to the workspace the rule names +// (a rule written the Windows way, `kwrite.exe`, names the same program) +#[test] +fn an_exe_suffix_in_a_rule_id_is_ignored() { + assert!(matches(&id( + ApplicationIdentifier::Exe, + "kwrite.exe", + Some(MatchingStrategy::Equals) + ))); + assert!(matches(&id(ApplicationIdentifier::Exe, "kwrite.exe", None))); +} + +#[test] +fn a_rule_without_a_strategy_or_with_legacy_is_the_old_one() { + for strategy in [None, Some(MatchingStrategy::Legacy)] { + // title and class: starts or ends with the id + assert!(matches(&id( + ApplicationIdentifier::Title, + "komorebi-e2e", + strategy.clone() + ))); + assert!(matches(&id( + ApplicationIdentifier::Title, + "rule target", + strategy.clone() + ))); + assert!(!matches(&id( + ApplicationIdentifier::Title, + "e2e: rule", + strategy.clone() + ))); + assert!(matches(&id( + ApplicationIdentifier::Class, + "org.kde", + strategy.clone() + ))); + assert!(matches(&id( + ApplicationIdentifier::Class, + "kwrite", + strategy.clone() + ))); + assert!(!matches(&id( + ApplicationIdentifier::Class, + "kde.kw", + strategy.clone() + ))); + // exe and path: equal to the id + assert!(matches(&id( + ApplicationIdentifier::Exe, + EXE, + strategy.clone() + ))); + assert!(!matches(&id( + ApplicationIdentifier::Exe, + "kwri", + strategy.clone() + ))); + assert!(matches(&id( + ApplicationIdentifier::Path, + PATH, + strategy.clone() + ))); + assert!(!matches(&id( + ApplicationIdentifier::Path, + "/usr/bin", + strategy.clone() + ))); + } +} + +// mirrors: rules / a window an ignore rule matches is not managed (which window) +#[test] +fn a_simple_rule_is_matched_by_one_condition_and_a_composite_by_all_of_them() { + let title = id( + ApplicationIdentifier::Title, + TITLE, + Some(MatchingStrategy::Equals), + ); + let class = id( + ApplicationIdentifier::Class, + CLASS, + Some(MatchingStrategy::Equals), + ); + let other = id( + ApplicationIdentifier::Exe, + "not-kwrite", + Some(MatchingStrategy::Equals), + ); + + let both = MatchingRule::Composite(vec![title.clone(), class.clone()]); + let one_wrong = MatchingRule::Composite(vec![title.clone(), other.clone()]); + let regex = no_regex(); + + assert_eq!( + should_act( + TITLE, + EXE, + &[CLASS], + PATH, + std::slice::from_ref(&both), + ®ex + ), + Some(both.clone()) + ); + assert_eq!( + should_act(TITLE, EXE, &[CLASS], PATH, &[one_wrong], ®ex), + None + ); + assert_eq!( + should_act( + TITLE, + EXE, + &[CLASS], + PATH, + &[MatchingRule::Simple(title.clone())], + ®ex + ), + Some(MatchingRule::Simple(title)) + ); +} + +// mirrors: rules / a rule that is not initial sends the window back at the next event (which +// of two rules wins) +#[test] +fn of_two_rules_that_match_the_last_one_is_the_answer() { + let first = simple( + ApplicationIdentifier::Class, + CLASS, + MatchingStrategy::Equals, + ); + let last = simple( + ApplicationIdentifier::Title, + "komorebi-e2e", + MatchingStrategy::StartsWith, + ); + let rules = [first.clone(), last.clone()]; + assert_eq!( + should_act_window(TITLE, EXE, CLASS, PATH, &rules, &no_regex()), + Some(last) + ); + assert_eq!( + should_act_window(TITLE, EXE, CLASS, PATH, &[first.clone()], &no_regex()), + Some(first) + ); +} + +// mirrors: rules / once the rules are cleared, a window they matched stays on the workspace in view +#[test] +fn no_rules_match_nothing() { + assert_eq!( + should_act_window(TITLE, EXE, CLASS, PATH, &[], &no_regex()), + None + ); +} + +// mirrors: title_rule / a window the ignore rule matches by its title is left alone +// mirrors: title_rule / it gives itself another title (the same rule no longer matches) +#[test] +fn a_rule_by_title_follows_the_title_it_is_asked_about() { + let rule = simple( + ApplicationIdentifier::Title, + "secret", + MatchingStrategy::Contains, + ); + let ask = + |title: &str| should_act_window(title, EXE, CLASS, PATH, &[rule.clone()], &no_regex()); + assert!(ask("a secret window").is_some()); + assert!(ask("a renamed window").is_none()); +} + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +// mirrors: manage_rules / a window an ignore rule by <kind> matches is not managed +// mirrors: manage_rules / with a manage rule by <kind> too, a window it matches is managed +// mirrors: manage_rules / ... and tiled: <base> gives it room +#[test] +fn a_manage_rule_rescues_a_window_an_ignore_rule_covers() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = std::path::PathBuf::from(format!("/tmp/kmr-{}.sock", std::process::id())); + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + fake.open_window(10_901, "kwrite", "org.kde.kwrite", "ignored window"); + fake.open_window(10_902, "kwrite", "org.kde.kwrite", "rescued window"); + + let send = |wm: &mut WindowManager, message| { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); + }; + // the rule tables are process-wide and this is the only test of this file that adds to them + send( + &mut wm, + SocketMessage::IgnoreRule(ApplicationIdentifier::Class, "org.kde.kwrite".to_string()), + ); + + with_backend(fake.clone(), || wm.process_event(added(10_901))).unwrap(); + assert!(!wm.focused_workspace().unwrap().contains_window(10_901)); + + send( + &mut wm, + SocketMessage::ManageRule(ApplicationIdentifier::Title, "rescued window".to_string()), + ); + with_backend(fake.clone(), || wm.process_event(added(10_902))).unwrap(); + + assert!(wm.focused_workspace().unwrap().contains_window(10_902)); + assert!(!wm.focused_workspace().unwrap().contains_window(10_901)); +} From 081e373782cd1a0bf9f9920f114197a7efea074c Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 16:33:09 -0700 Subject: [PATCH 09/37] fix(nix): check the macOS formatting with rustfmt over the macOS files The kfm fmt check ran stable `cargo fmt -p ...` on the stubbed workspace source and failed twice: rustfmt follows the `mod windows;` of the shared entry files (komorebi-bar, komorebi-client; their windows modules are not in the macOS source), and the stable rustfmt ignores the nightly options of this tree's rustfmt.toml. The check is now a runCommand: the nightly rustfmt (already in the flake for treefmt) with --edition 2024 (the edition of the macOS manifests; cargo fmt uses it too) and komorebi-for-mac/rustfmt.toml, over komorebi-for-mac/**/*.rs, komorebic/src/macos, komorebi-bar/src/macos and komorebi-client/src/macos.rs. The entry files of the shared crates are not checked; their macos modules are. The macOS code is not clean under it: the next revision formats it. Verified: the command reproduced locally with the nightly rustfmt (11 files differ). The nix attribute is evaluated in the final eval table. Not built. --- komorebi-for-mac/flake.nix | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/komorebi-for-mac/flake.nix b/komorebi-for-mac/flake.nix index 80a2c30c..82634cc6 100644 --- a/komorebi-for-mac/flake.nix +++ b/komorebi-for-mac/flake.nix @@ -256,7 +256,24 @@ checks = { komorebi-workspace-clippy = build.craneLib.cargoClippy build.individualCrateArgs; - komorebi-workspace-fmt = build.craneLib.cargoFmt (build.workspaceArgs // { inherit (build) src; cargoExtraArgs = build.packages; }); + # rustfmt over the macOS files only, with the nightly rustfmt this tree's rustfmt.toml + # needs and the 2024 edition of the manifests. `cargo fmt` would follow the `mod windows;` + # of the shared entry files (komorebi-bar, komorebi-client), which the macOS source does + # not have. The entry files of the shared crates are not checked; their macos modules are. + komorebi-workspace-fmt = + pkgs.runCommand "komorebi-workspace-fmt" + { + nativeBuildInputs = [ nightlyRustfmt ]; + src = build.real; + } + '' + cd $src + files=$( { find komorebi-for-mac -name '*.rs'; \ + find komorebic/src/macos komorebi-bar/src/macos -name '*.rs'; \ + echo komorebi-client/src/macos.rs; } ) + rustfmt --edition 2024 --config-path komorebi-for-mac/rustfmt.toml --check $files + touch $out + ''; komorebi-workspace-toml-fmt = build.craneLib.taploFmt ( build.workspaceArgs From 2a8b71f1c9318a2f5005265a9d747614aeb10175 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:34:29 -0700 Subject: [PATCH 10/37] build(tools): add the fake C compiler and mac-check.sh for the macOS type-check on Linux macOS cannot be built or linked on the Linux host; the way to type-check it is `cargo check --target aarch64-apple-darwin --all-targets` with a fake C compiler so the C -sys crates' build scripts succeed. That compiler was only a scratchpad file outside the repository and mac-check.sh hardcoded a workspace path. tools/cc-fake.sh: verbatim copy of the scratchpad cc-fake.sh (emits an empty object for every compile, hands -E to the real gcc). No difference. tools/mac-check.sh: new copy of the old script with these differences: - no hardcoded `cd /home/jado/komomono-work/ws-step4/komorebi-for-mac`: the root comes from `jj root` (fallback `git rev-parse --show-toplevel`); - the fake CC is `$HERE/cc-fake.sh` (next to the script) instead of `$S/kfm/cc-fake.sh`; - the target dir is `${FAST_CHECK_SCRATCH:-${XDG_CACHE_HOME:-$HOME/.cache}/komorebi-fast-check}/target-fast-mac` instead of a /tmp/claude-1000 scratchpad; - in the merged tree (komorebi-for-kde has its own Cargo.toml only in the old layout) it checks the packages fast-check checks (-p komorebi -p komorebi-macos -p komorebic-macos -p komorebi-client-macos -p komorebi-bar-macos) from the root; with the old separate workspace it keeps `cd komorebi-for-mac` and --workspace; - /bin/sh became bash with `set -euo pipefail`; the old script's omission of --locked is kept (pass it as an extra argument). Verified: bash -n and shellcheck clean. Not run: the check itself needs nix and the toolchain build. --- tools/cc-fake.sh | 12 ++++++++++++ tools/mac-check.sh | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100755 tools/cc-fake.sh create mode 100755 tools/mac-check.sh diff --git a/tools/cc-fake.sh b/tools/cc-fake.sh new file mode 100755 index 00000000..7edfafd3 --- /dev/null +++ b/tools/cc-fake.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# check-only hack: emit an empty object for every compile so C -sys build scripts "succeed" +out=""; prev=""; compile=0 +for a in "$@"; do + [ "$prev" = "-o" ] && out="$a" + [ "$a" = "-c" ] && compile=1 + [ "$a" = "-E" ] && { exec gcc "${@}" ; } + case "$a" in -Fo*) out="${a#-Fo}";; esac + prev="$a" +done +if [ $compile = 1 ] && [ -n "$out" ]; then exec gcc -x c -c /dev/null -o "$out"; fi +exit 0 diff --git a/tools/mac-check.sh b/tools/mac-check.sh new file mode 100755 index 00000000..c1da3dd3 --- /dev/null +++ b/tools/mac-check.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# usage: tools/mac-check.sh [extra cargo args] +# Type-check of the macOS code on Linux (target aarch64-apple-darwin) through the fake C compiler +# tools/cc-fake.sh. Cannot link or run anything. Same command as the macOS step of tools/fast-check, but +# unconditional. Run from anywhere inside the repository; uses FAST_CHECK_SCRATCH like fast-check. +set -euo pipefail +S="${FAST_CHECK_SCRATCH:-${XDG_CACHE_HOME:-$HOME/.cache}/komorebi-fast-check}" +HERE="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" +ROOT="$(jj root 2>/dev/null || git rev-parse --show-toplevel)" +cd "$ROOT" +# merged root workspace (one Cargo.toml for the three platforms) or the old separate komorebi-for-mac workspace +if [ -f komorebi-for-kde/Cargo.toml ]; then + cd komorebi-for-mac + PKGS=(--workspace) +else + PKGS=(-p komorebi -p komorebi-macos -p komorebic-macos -p komorebi-client-macos -p komorebi-bar-macos) +fi +export CARGO_TARGET_DIR="$S/target-fast-mac" COMMIT_HASH="${COMMIT_HASH:-dev}" +export CC_aarch64_apple_darwin="$HERE/cc-fake.sh" AR_aarch64_apple_darwin=ar +PKG_CONFIG_PATH="$(nix build --no-link --print-out-paths nixpkgs#openssl.dev)/lib/pkgconfig" +export PKG_CONFIG_PATH +exec nix shell nixpkgs#gcc nixpkgs#pkg-config nixpkgs#openssl.dev -c \ + cargo check --target aarch64-apple-darwin "${PKGS[@]}" --all-targets "$@" From 04af7fcbbf0f4ef3c52d908a95e9cebffec995bf Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:39:38 -0700 Subject: [PATCH 11/37] test(settings): pin the transparency and animation load rules tests/reload.rs: transparency is kept by a load without the key when the daemon passes the keys as they are (Windows) and reset to false and 200 when it passes unwrap_or (KDE); an animation block with a per-kind map replaces the map and leaves the global flag, a load with no block keeps everything, a global flag clears the map and a block without fps resets fps to 60. Test only. Verified: native cargo test -p komorebi-settings: 18 unit + 5 integration passed. --- crates/komorebi-settings/tests/reload.rs | 86 ++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/crates/komorebi-settings/tests/reload.rs b/crates/komorebi-settings/tests/reload.rs index 890f4019..c324a0f7 100644 --- a/crates/komorebi-settings/tests/reload.rs +++ b/crates/komorebi-settings/tests/reload.rs @@ -125,3 +125,89 @@ fn a_load_never_touches_the_groups_it_does_not_name() { assert_eq!(after.shared.animation, before.shared.animation); assert_eq!(after.shared.transparency, before.shared.transparency); } + +#[test] +fn transparency_is_kept_by_a_load_without_the_key_unless_the_daemon_resets_it() { + // Windows passes the keys as they are: absent keeps the value + let windows = handle(); + load( + &windows, + SharedDelta { + transparency: Some(true), + transparency_alpha: Some(90), + ..SharedDelta::default() + }, + ); + load(&windows, SharedDelta::default()); + let kept = windows.snapshot().shared.transparency; + assert!(kept.enabled); + assert_eq!(kept.alpha, 90); + + // KDE passes `unwrap_or(false)` and `unwrap_or(200)`: absent resets to the defaults + let kde = handle(); + load( + &kde, + SharedDelta { + transparency: Some(true), + transparency_alpha: Some(90), + ..SharedDelta::default() + }, + ); + let (transparency, alpha): (Option<bool>, Option<u8>) = (None, None); + load( + &kde, + SharedDelta { + transparency: Some(transparency.unwrap_or(false)), + transparency_alpha: Some(alpha.unwrap_or(200)), + ..SharedDelta::default() + }, + ); + let reset = kde.snapshot().shared.transparency; + assert!(!reset.enabled); + assert_eq!(reset.alpha, 200); +} + +#[test] +fn the_animation_block_follows_the_load_rules() { + use komorebi_config::animation::PerAnimationPrefixConfig; + use komorebi_protocol::animation::AnimationStyle; + use komorebi_protocol::animation::prefix::AnimationPrefix; + use komorebi_settings::shared::AnimationDelta; + + let handle = handle(); + let block = |enabled, fps| SharedDelta { + animation: Some(AnimationDelta { + enabled, + style: None, + duration: Some(PerAnimationPrefixConfig::Global(120)), + fps, + }), + ..SharedDelta::default() + }; + + // a per-kind map replaces the map, the global flag is left alone; fps given + load( + &handle, + block( + PerAnimationPrefixConfig::Prefix(HashMap::from([(AnimationPrefix::Movement, true)])), + Some(30), + ), + ); + let first = handle.snapshot().shared.animation.clone(); + assert!(!first.enabled); + assert_eq!(first.enabled_per_animation.len(), 1); + assert_eq!(first.duration, 120); + assert_eq!(first.fps, 30); + assert_eq!(first.style, AnimationStyle::Linear); + + // a load with no animation block keeps all of it + load(&handle, SharedDelta::default()); + assert_eq!(handle.snapshot().shared.animation, first); + + // a global flag clears the map, and a block without fps resets fps + load(&handle, block(PerAnimationPrefixConfig::Global(true), None)); + let second = handle.snapshot().shared.animation.clone(); + assert!(second.enabled); + assert!(second.enabled_per_animation.is_empty()); + assert_eq!(second.fps, 60); +} From ddc1a231c5cdab6f4caa6052572a04490811b1ea Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:41:46 -0700 Subject: [PATCH 12/37] refactor(mac): seven process_command arms call the named methods KDE has Part of the router converge between KDE and macOS: CycleFocusWorkspace, CycleFocusEmptyWorkspace, CloseWorkspace, MoveContainerToLastWorkspace (and SendContainerToLastWorkspace, which is the same method with follow = false), EagerFocus and BorderColour were the same lines inline on macOS as the methods cycle_focus_workspace, cycle_focus_empty_workspace, close_workspace, move_container_to_last_workspace, eager_focus and set_border_colour on KDE (compared with the arms' text, apart from where rustfmt wrapped a line). The macOS arms now call methods with those names and bodies; the arms are byte-identical to KDE's. No behaviour change. Verified: fake-CC cargo clippy -p komorebi-macos -p komorebic-macos -p komorebi-client-macos -p komorebi-bar-macos --all-targets -D warnings: PASS (type-check only). Not run: the macOS tests (the Mac Mini), KDE and Windows gates (no KDE or Windows file changed). --- .../komorebi/src/process_command.rs | 525 +++++++++--------- 1 file changed, 264 insertions(+), 261 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index 3d01c6eb..cc08d759 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -21,6 +21,7 @@ use crate::border_manager; use crate::cf_array_as; use crate::core::ApplicationIdentifier; use crate::core::Axis; +use crate::core::CycleDirection; use crate::core::Layout; use crate::core::LayoutOptions; use crate::core::MonocleFocusBehaviour; @@ -112,6 +113,262 @@ impl CommandTarget for WindowManager { } impl WindowManager { + /// Sets the border colour of one kind of window + pub fn set_border_colour(&mut self, kind: WindowKind, r: u32, g: u32, b: u32) { + match kind { + WindowKind::Single => { + border_manager::FOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Stack => { + border_manager::STACK.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Monocle => { + border_manager::MONOCLE.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Unfocused => { + border_manager::UNFOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::UnfocusedLocked => { + border_manager::UNFOCUSED_LOCKED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + WindowKind::Floating => { + border_manager::FLOATING.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); + } + } + } + + /// Focuses the next or previous workspace of the monitor that is focused, or of the monitor the pointer is on when its workspace is empty + pub fn cycle_focus_workspace(&mut self, direction: CycleDirection) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces).ok_or_eyre("there must be at least one workspace")?, + ); + + self.focus_workspace(workspace_idx)?; + Ok(()) + } + + /// Focuses the next or previous empty workspace of the focused monitor, if it has one + pub fn cycle_focus_empty_workspace(&mut self, direction: CycleDirection) -> eyre::Result<()> { + // TODO: figure out if we need to do this on macOS + // // This is to ensure that even on an empty workspace on a secondary monitor, the + // // secondary monitor where the cursor is focused will be used as the target for + // // the workspace switch op + // if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { + // if monitor_idx != self.focused_monitor_idx() { + // if let Some(monitor) = self.monitors().get(monitor_idx) { + // if let Some(workspace) = monitor.focused_workspace() { + // if workspace.is_empty() { + // self.focus_monitor(monitor_idx)?; + // } + // } + // } + // } + // } + + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let mut empty_workspaces = vec![]; + + for (idx, w) in focused_monitor.workspaces().iter().enumerate() { + if w.is_empty() { + empty_workspaces.push(idx); + } + } + + if !empty_workspaces.is_empty() { + let mut workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces).ok_or_eyre("there must be at least one workspace")?, + ); + + while !empty_workspaces.contains(&workspace_idx) { + workspace_idx = direction.next_idx( + workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + } + + self.focus_workspace(workspace_idx)?; + } + Ok(()) + } + + /// Removes the focused workspace when it is empty, unnamed and not the monitor's only one, and focuses the one before it + pub fn close_workspace(&mut self) -> eyre::Result<()> { + // TODO: figure out if we need to do this on macOS + // // This is to ensure that even on an empty workspace on a secondary monitor, the + // // secondary monitor where the cursor is focused will be used as the target for + // // the workspace switch op + // if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { + // if monitor_idx != self.focused_monitor_idx() { + // if let Some(monitor) = self.monitors().get(monitor_idx) { + // if let Some(workspace) = monitor.focused_workspace() { + // if workspace.is_empty() { + // self.focus_monitor(monitor_idx)?; + // } + // } + // } + // } + // } + + let mut can_close = false; + + if let Some(monitor) = self.focused_monitor_mut() { + let focused_workspace_idx = monitor.focused_workspace_idx(); + let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); + + if let Some(workspace) = monitor.focused_workspace() + && monitor.workspaces().len() > 1 + && workspace.containers().is_empty() + && workspace.floating_windows().is_empty() + && workspace.monocle_container.is_none() + && workspace.maximized_window.is_none() + && workspace.name.is_none() + { + can_close = true; + } + + if can_close + && monitor + .workspaces_mut() + .remove(focused_workspace_idx) + .is_some() + { + self.focus_workspace(next_focused_workspace_idx)?; + } + } + Ok(()) + } + + /// Moves the focused container to the workspace that was focused before this one, and follows it when `follow` is set + pub fn move_container_to_last_workspace(&mut self, follow: bool) -> eyre::Result<()> { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.move_container_to_workspace(last_focused_workspace, follow, None)?; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + Ok(()) + } + + /// Looks for a window of the executable `exe` on every monitor and workspace, and focuses it + pub fn eager_focus(&mut self, exe: &str) -> eyre::Result<()> { + let focused_monitor_idx = self.focused_monitor_idx(); + let mouse_follows_focus = self.mouse_follows_focus; + + let mut window_location = None; + let mut monitor_to_focus = None; + let mut needs_workspace_loading = false; + + 'search: for (monitor_idx, monitor) in self.monitors_mut().iter_mut().enumerate() { + for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { + if let Some(location) = workspace.location_from_exe(exe) { + window_location = Some(location); + + if monitor_idx != focused_monitor_idx { + monitor_to_focus = Some(monitor_idx); + } + + // Focus workspace if it is not already the focused one, without + // loading it so that we don't give focus to the wrong window, we will + // load it later after focusing the wanted window + let focused_ws_idx = monitor.focused_workspace_idx(); + if focused_ws_idx != workspace_idx { + monitor.last_focused_workspace = Option::from(focused_ws_idx); + monitor.focus_workspace(workspace_idx)?; + needs_workspace_loading = true; + } + + break 'search; + } + } + } + + if let Some(monitor_idx) = monitor_to_focus { + self.focus_monitor(monitor_idx)?; + } + + if let Some(location) = window_location { + match location { + WorkspaceWindowLocation::Monocle(window_idx) => { + self.focus_container_window(window_idx)?; + } + WorkspaceWindowLocation::Maximized => { + if let Some(window) = &mut self.focused_workspace_mut()?.maximized_window { + window.focus(mouse_follows_focus)?; + } + } + WorkspaceWindowLocation::Container(container_idx, window_idx) => { + let focused_container_idx = self.focused_container_idx()?; + if container_idx != focused_container_idx { + self.focused_workspace_mut()?.focus_container(container_idx); + } + + self.focus_container_window(window_idx)?; + } + WorkspaceWindowLocation::Floating(window_idx) => { + if let Some(window) = self + .focused_workspace_mut()? + .floating_windows_mut() + .get_mut(window_idx) + { + window.focus(mouse_follows_focus)?; + } + } + } + + if needs_workspace_loading { + let mouse_follows_focus = self.mouse_follows_focus; + if let Some(monitor) = self.focused_monitor_mut() { + monitor.load_focused_workspace(mouse_follows_focus)?; + } + } + } + Ok(()) + } + #[tracing::instrument(skip(self, reply, message))] pub fn process_command( &mut self, @@ -146,81 +403,7 @@ impl WindowManager { self.focus_container_in_direction(direction)?; self.promote_container_to_front()? } - SocketMessage::EagerFocus(ref exe) => { - let focused_monitor_idx = self.focused_monitor_idx(); - let mouse_follows_focus = self.mouse_follows_focus; - - let mut window_location = None; - let mut monitor_to_focus = None; - let mut needs_workspace_loading = false; - - 'search: for (monitor_idx, monitor) in self.monitors_mut().iter_mut().enumerate() { - for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { - if let Some(location) = workspace.location_from_exe(exe) { - window_location = Some(location); - - if monitor_idx != focused_monitor_idx { - monitor_to_focus = Some(monitor_idx); - } - - // Focus workspace if it is not already the focused one, without - // loading it so that we don't give focus to the wrong window, we will - // load it later after focusing the wanted window - let focused_ws_idx = monitor.focused_workspace_idx(); - if focused_ws_idx != workspace_idx { - monitor.last_focused_workspace = Option::from(focused_ws_idx); - monitor.focus_workspace(workspace_idx)?; - needs_workspace_loading = true; - } - - break 'search; - } - } - } - - if let Some(monitor_idx) = monitor_to_focus { - self.focus_monitor(monitor_idx)?; - } - - if let Some(location) = window_location { - match location { - WorkspaceWindowLocation::Monocle(window_idx) => { - self.focus_container_window(window_idx)?; - } - WorkspaceWindowLocation::Maximized => { - if let Some(window) = - &mut self.focused_workspace_mut()?.maximized_window - { - window.focus(mouse_follows_focus)?; - } - } - WorkspaceWindowLocation::Container(container_idx, window_idx) => { - let focused_container_idx = self.focused_container_idx()?; - if container_idx != focused_container_idx { - self.focused_workspace_mut()?.focus_container(container_idx); - } - - self.focus_container_window(window_idx)?; - } - WorkspaceWindowLocation::Floating(window_idx) => { - if let Some(window) = self - .focused_workspace_mut()? - .floating_windows_mut() - .get_mut(window_idx) - { - window.focus(mouse_follows_focus)?; - } - } - } - - if needs_workspace_loading { - let mouse_follows_focus = self.mouse_follows_focus; - if let Some(monitor) = self.focused_monitor_mut() { - monitor.load_focused_workspace(mouse_follows_focus)?; - } - } - } - } + SocketMessage::EagerFocus(ref exe) => self.eager_focus(exe)?, SocketMessage::FocusWindow(direction) => { let focused_workspace = self.focused_workspace()?; match focused_workspace.layer { @@ -394,78 +577,10 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, true)?; } SocketMessage::CycleFocusWorkspace(direction) => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; - - let focused_workspace_idx = focused_monitor.focused_workspace_idx(); - let workspaces = focused_monitor.workspaces().len(); - - let workspace_idx = direction.next_idx( - focused_workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - - self.focus_workspace(workspace_idx)?; + self.cycle_focus_workspace(direction)? } SocketMessage::CycleFocusEmptyWorkspace(direction) => { - // TODO: figure out if we need to do this on macOS - // // This is to ensure that even on an empty workspace on a secondary monitor, the - // // secondary monitor where the cursor is focused will be used as the target for - // // the workspace switch op - // if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { - // if monitor_idx != self.focused_monitor_idx() { - // if let Some(monitor) = self.monitors().get(monitor_idx) { - // if let Some(workspace) = monitor.focused_workspace() { - // if workspace.is_empty() { - // self.focus_monitor(monitor_idx)?; - // } - // } - // } - // } - // } - - let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; - - let focused_workspace_idx = focused_monitor.focused_workspace_idx(); - let workspaces = focused_monitor.workspaces().len(); - - let mut empty_workspaces = vec![]; - - for (idx, w) in focused_monitor.workspaces().iter().enumerate() { - if w.is_empty() { - empty_workspaces.push(idx); - } - } - - if !empty_workspaces.is_empty() { - let mut workspace_idx = direction.next_idx( - focused_workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - - while !empty_workspaces.contains(&workspace_idx) { - workspace_idx = direction.next_idx( - workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - } - - self.focus_workspace(workspace_idx)?; - } + self.cycle_focus_empty_workspace(direction)? } SocketMessage::FocusMonitorNumber(monitor_idx) => { self.focus_monitor(monitor_idx)?; @@ -560,50 +675,7 @@ impl WindowManager { self.focus_workspace(workspace_idx)?; } } - SocketMessage::CloseWorkspace => { - // TODO: figure out if we need to do this on macOS - // // This is to ensure that even on an empty workspace on a secondary monitor, the - // // secondary monitor where the cursor is focused will be used as the target for - // // the workspace switch op - // if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { - // if monitor_idx != self.focused_monitor_idx() { - // if let Some(monitor) = self.monitors().get(monitor_idx) { - // if let Some(workspace) = monitor.focused_workspace() { - // if workspace.is_empty() { - // self.focus_monitor(monitor_idx)?; - // } - // } - // } - // } - // } - - let mut can_close = false; - - if let Some(monitor) = self.focused_monitor_mut() { - let focused_workspace_idx = monitor.focused_workspace_idx(); - let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); - - if let Some(workspace) = monitor.focused_workspace() - && monitor.workspaces().len() > 1 - && workspace.containers().is_empty() - && workspace.floating_windows().is_empty() - && workspace.monocle_container.is_none() - && workspace.maximized_window.is_none() - && workspace.name.is_none() - { - can_close = true; - } - - if can_close - && monitor - .workspaces_mut() - .remove(focused_workspace_idx) - .is_some() - { - self.focus_workspace(next_focused_workspace_idx)?; - } - } - } + SocketMessage::CloseWorkspace => self.close_workspace()?, SocketMessage::MoveContainerToWorkspaceNumber(workspace_idx) => { self.move_container_to_workspace(workspace_idx, true, None)?; @@ -861,59 +933,10 @@ impl WindowManager { self.toggle_tiling()?; } SocketMessage::MoveContainerToLastWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.move_container_to_workspace(last_focused_workspace, true, None)?; - } - - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); + self.move_container_to_last_workspace(true)? } SocketMessage::SendContainerToLastWorkspace => { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.move_container_to_workspace(last_focused_workspace, false, None)?; - } - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); + self.move_container_to_last_workspace(false)?; } SocketMessage::CycleMoveContainerToWorkspace(direction) => { let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; @@ -1776,27 +1799,7 @@ impl WindowManager { border_manager::destroy_all_borders()?; } } - SocketMessage::BorderColour(kind, r, g, b) => match kind { - WindowKind::Single => { - border_manager::FOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Stack => { - border_manager::STACK.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Monocle => { - border_manager::MONOCLE.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Unfocused => { - border_manager::UNFOCUSED.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::UnfocusedLocked => { - border_manager::UNFOCUSED_LOCKED - .store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - WindowKind::Floating => { - border_manager::FLOATING.store(Rgb::new(r, g, b).into(), Ordering::SeqCst); - } - }, + SocketMessage::BorderColour(kind, r, g, b) => self.set_border_colour(kind, r, g, b), SocketMessage::BorderWidth(width) => { border_manager::BORDER_WIDTH.store(width, Ordering::SeqCst); border_manager::destroy_all_borders()?; From 3cc8ff63b3dce0898df4473d763d1d0968d2fc71 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:34:11 -0700 Subject: [PATCH 13/37] fix(core): constrain the main container of the right-main vertical stack at index 0 enforce_resize_for_right_vertical_stack said "Zero is actually on the right" but locked top, bottom and right of resize_dimensions[1], so the main container (index 0, drawn on the right: arrangement.rs primary_left = area.right - primary_width) was never constrained and the first stack container could not be resized at all. Index 0 now loses top, bottom and right (it can only grow to the left); the stack loop over [1..] is unchanged (nothing in it goes left, first not up, last not down). The test that pinned the buggy result is replaced by the previously ignored test of the intended behaviour, un-ignored and extended to 1 to 4 tiles: [l, rb], [l, rb, tr], [l, rb, trb, tr]. BEHAVIOUR (all three daemons share this function): resizing in the right-main-vertical-stack layout changes. Gate: Windows e2e resize scenarios; the ones that run in right-main-vertical-stack are none by name (resize_commands uses the default layout; layouts.py and commands.py only tile and cycle through right-main-vertical-stack), so a pointer or resize-edge scenario in that layout would need adding. Verified: cargo test -p komorebi-core, with and without --features schemars, all pass; no e2e run. --- crates/komorebi-core/src/workspace.rs | 10 +++---- .../komorebi-core/tests/resize_constraints.rs | 27 +++++-------------- 2 files changed, 12 insertions(+), 25 deletions(-) diff --git a/crates/komorebi-core/src/workspace.rs b/crates/komorebi-core/src/workspace.rs index 67e8f689..9462957d 100644 --- a/crates/komorebi-core/src/workspace.rs +++ b/crates/komorebi-core/src/workspace.rs @@ -1378,13 +1378,13 @@ impl<P: WorkspacePlatform> Workspace<P> { 0 | 1 => self.enforce_no_resize(), _ => { // Zero is actually on the right - if let Some(left) = resize_dimensions[1].as_mut() { - left.top = 0; - left.bottom = 0; - left.right = 0; + if let Some(right) = resize_dimensions[0].as_mut() { + right.top = 0; + right.bottom = 0; + right.right = 0; } - // Handle stack on the right + // Handle stack on the left let stack_size = resize_dimensions[1..].len(); for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { if let Some(rect) = rect { diff --git a/crates/komorebi-core/tests/resize_constraints.rs b/crates/komorebi-core/tests/resize_constraints.rs index 7cccee6e..98f8a6bd 100644 --- a/crates/komorebi-core/tests/resize_constraints.rs +++ b/crates/komorebi-core/tests/resize_constraints.rs @@ -128,34 +128,21 @@ fn the_ultrawide_stack_has_its_main_column_in_the_middle() { } #[test] -fn the_right_main_vertical_stack_constrains_index_one_and_leaves_index_zero_free() { - // characterization of what the code does: it follows the comment "Zero is actually on the - // right" but indexes the second container, so the first (the main one) is never constrained - // and the second may not be resized at all; the ignored test below says what the comment asks +fn the_right_main_vertical_stack_constrains_its_main_container_at_index_zero() { + // the main container is index 0 and is drawn on the right (komorebi-layouts arrangement.rs: + // primary_left = area.right - primary_width): it may only be resized to the left. The stack + // is on the left: nothing in it goes left, the first not up, the last not down. check( DefaultLayout::RightMainVerticalStack, &[ &[""], - &["ltrb", ""], - &["ltrb", "", "tr"], - &["ltrb", "", "trb", "tr"], + &["l", "rb"], + &["l", "rb", "tr"], + &["l", "rb", "trb", "tr"], ], ); } -#[test] -#[ignore = "bug: enforce_resize_for_right_vertical_stack indexes resize_dimensions[1] where its \ - comment says zero is on the right; inherited unchanged from the Windows tree"] -fn the_right_main_vertical_stack_constrains_its_main_container_at_index_zero() { - fresh(); - let mut workspace = workspace_with(DefaultLayout::RightMainVerticalStack, 3); - - workspace.enforce_resize_constraints(); - - // the main container is on the right: it cannot go up, down or right - assert_eq!(sides(&workspace)[0], "l"); -} - #[test] fn layouts_without_a_resize_rule_take_every_adjustment_away() { for layout in [DefaultLayout::Grid, DefaultLayout::Scrolling] { From b3589b7b7b54948832aed4174be1eb520d332ddb Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 17:13:23 -0700 Subject: [PATCH 14/37] test(kde): sweep of the model commands through process_command The commands e2e scenario (265 checks, about 7.6 minutes on the Windows gate, a stall-prone sweep) asserts after each of about 216 komorebic commands that the daemon is alive, answers state and manages every window. For the commands that only mutate the model that is not a property of a real OS. komorebi-for-kde/komorebi/tests/command_sweep.rs sends the SocketMessage of each model command of the scenario's SWEEP, in its order (focus, move, stack, resize, promote, flip, layouts, toggles, workspaces, monitors, offsets, padding, behaviours, rules, scrolling), through WindowManager::process_command over a FakeBackend with two monitors and three windows, and after each asserts that every window is still managed (any monitor, workspace, layer), and that the state query answers JSON. A command may refuse (a direction with no window): only that refusal is accepted as an error. The sweep runs in 0.2 s. mirrors: commands / <command> leaves the daemon healthy. What stays e2e only: komorebic parsing each command and writing that message, the pointer, files and config reload commands, a command that stalls the daemon while the socket waits, and everything the real OS does with the windows (the sweep's healthy check against the OS's windows). Verified: cargo test -p komorebi-linux --test command_sweep in komorebi-for-kde, 1 passed (native, Linux). KDE daemon only: the Windows and macOS daemons have no native harness. No source change, no bug found. --- .../komorebi/tests/command_sweep.rs | 577 ++++++++++++++++++ 1 file changed, 577 insertions(+) create mode 100644 komorebi-for-kde/komorebi/tests/command_sweep.rs diff --git a/komorebi-for-kde/komorebi/tests/command_sweep.rs b/komorebi-for-kde/komorebi/tests/command_sweep.rs new file mode 100644 index 00000000..f9be9113 --- /dev/null +++ b/komorebi-for-kde/komorebi/tests/command_sweep.rs @@ -0,0 +1,577 @@ +//! A sweep of the commands that change the model, through [`WindowManager::process_command`] over +//! a fake desktop with two monitors and three windows, the way the `commands` end-to-end scenario +//! sweeps `komorebic` (`SWEEP` in `core/scenarios/commands.py`): after every command the daemon +//! must be alive, answer a state query with JSON, and still manage every window it was given. +//! +//! mirrors: commands / <command> leaves the daemon healthy (the model commands of the sweep, as +//! the `SocketMessage` each `komorebic` command is; the order is the scenario's, the ones that +//! need a window the fake cannot have (the pointer, the real compositor, files) left out) +//! +//! Not covered here, and so still end-to-end: that `komorebic` parses each command and writes +//! that message (see the CLI tests of `komorebic-core`), that the socket answers while a command +//! runs, a command that stalls the daemon, and anything the real OS does with the windows. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::Axis; +use komorebi::core::CycleDirection::Next; +use komorebi::core::CycleDirection::Previous; +use komorebi::core::DefaultLayout; +use komorebi::core::MoveBehaviour; +use komorebi::core::OperationBehaviour; +use komorebi::core::OperationDirection::Down; +use komorebi::core::OperationDirection::Left; +use komorebi::core::OperationDirection::Right; +use komorebi::core::OperationDirection::Up; +use komorebi::core::Rect; +use komorebi::core::Sizing::Decrease; +use komorebi::core::Sizing::Increase; +use komorebi::core::SocketMessage as M; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +const IDS: [u32; 3] = [31_001, 31_002, 31_003]; + +fn rect(left: i32) -> Rect { + Rect { + left, + top: 0, + right: 1920, + bottom: 1080, + } +} + +fn desktop() -> (Arc<FakeBackend>, WindowManager) { + let fake = Arc::new(FakeBackend::new()); + fake.add_monitor(50, "DP-1", rect(0), rect(0)); + fake.add_monitor(51, "DP-2", rect(1920), rect(1920)); + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = std::path::PathBuf::from(format!("/tmp/kcs-{}.sock", std::process::id())); + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + for id in IDS { + fake.open_window( + id, + &format!("exe{id}"), + &format!("class.{id}"), + &format!("window {id}"), + ); + with_backend(fake.clone(), || { + wm.process_event(WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + )) + }) + .unwrap(); + } + (fake, wm) +} + +fn managed(wm: &WindowManager, id: u32) -> bool { + wm.monitors().iter().any(|monitor| { + monitor + .workspaces() + .iter() + .any(|workspace| workspace.contains_window(id)) + }) +} + +/// The messages of the sweep that the fake desktop can run, in the scenario's order. +fn sweep() -> Vec<(&'static str, M)> { + vec![ + ("focus left", M::FocusWindow(Left)), + ("focus right", M::FocusWindow(Right)), + ("focus up", M::FocusWindow(Up)), + ("focus down", M::FocusWindow(Down)), + ("move left", M::MoveWindow(Left)), + ("move right", M::MoveWindow(Right)), + ("move up", M::MoveWindow(Up)), + ("move down", M::MoveWindow(Down)), + ("cycle-focus next", M::CycleFocusWindow(Next)), + ("cycle-focus previous", M::CycleFocusWindow(Previous)), + ("cycle-move next", M::CycleMoveWindow(Next)), + ("cycle-move previous", M::CycleMoveWindow(Previous)), + ("stack left", M::StackWindow(Left)), + ("cycle-stack next", M::CycleStack(Next)), + ("cycle-stack previous", M::CycleStack(Previous)), + ("cycle-stack-index next", M::CycleStackIndex(Next)), + ("focus-stack-window 0", M::FocusStackWindow(0)), + ("unstack", M::UnstackWindow), + ("stack-all", M::StackAll), + ("unstack-all", M::UnstackAll), + ( + "resize-edge left increase", + M::ResizeWindowEdge(Left, Increase), + ), + ( + "resize-edge right decrease", + M::ResizeWindowEdge(Right, Decrease), + ), + ("resize-edge up increase", M::ResizeWindowEdge(Up, Increase)), + ( + "resize-edge down decrease", + M::ResizeWindowEdge(Down, Decrease), + ), + ( + "resize-axis horizontal increase", + M::ResizeWindowAxis(Axis::Horizontal, Increase), + ), + ( + "resize-axis vertical decrease", + M::ResizeWindowAxis(Axis::Vertical, Decrease), + ), + ("resize-delta 50", M::ResizeDelta(50)), + ("resize-delta 100", M::ResizeDelta(100)), + ("promote", M::Promote), + ("promote-swap", M::PromoteSwap), + ("promote-focus", M::PromoteFocus), + ("promote-window left", M::PromoteWindow(Left)), + ("retile", M::Retile), + ("flip-layout horizontal", M::FlipLayout(Axis::Horizontal)), + ("flip-layout vertical", M::FlipLayout(Axis::Vertical)), + ( + "flip-layout horizontal-and-vertical", + M::FlipLayout(Axis::HorizontalAndVertical), + ), + ( + "flip-layout horizontal-and-vertical", + M::FlipLayout(Axis::HorizontalAndVertical), + ), + ("cycle-layout next", M::CycleLayout(Next)), + ("cycle-layout previous", M::CycleLayout(Previous)), + ( + "layout-ratios --columns 0.6 0.4", + M::LayoutRatios(Some(vec![0.6, 0.4]), None), + ), + ( + "change-layout columns", + M::ChangeLayout(DefaultLayout::Columns), + ), + ("change-layout bsp", M::ChangeLayout(DefaultLayout::BSP)), + ("preselect-direction left", M::PreselectDirection(Left)), + ("cancel-preselect", M::CancelPreselect), + ("toggle-monocle", M::ToggleMonocle), + ("toggle-monocle", M::ToggleMonocle), + ("toggle-maximize", M::ToggleMaximize), + ("toggle-maximize", M::ToggleMaximize), + ("toggle-float", M::ToggleFloat), + ("toggle-float", M::ToggleFloat), + ("toggle-lock", M::ToggleLock), + ("toggle-lock", M::ToggleLock), + ("toggle-tiling", M::ToggleTiling), + ("toggle-tiling", M::ToggleTiling), + ("toggle-pause", M::TogglePause), + ("toggle-pause", M::TogglePause), + ("toggle-workspace-layer", M::ToggleWorkspaceLayer), + ("toggle-workspace-layer", M::ToggleWorkspaceLayer), + ( + "toggle-window-container-behaviour", + M::ToggleWindowContainerBehaviour, + ), + ( + "toggle-window-container-behaviour", + M::ToggleWindowContainerBehaviour, + ), + ("toggle-float-override", M::ToggleFloatOverride), + ("toggle-float-override", M::ToggleFloatOverride), + ( + "toggle-workspace-window-container-behaviour", + M::ToggleWorkspaceWindowContainerBehaviour, + ), + ( + "toggle-workspace-window-container-behaviour", + M::ToggleWorkspaceWindowContainerBehaviour, + ), + ( + "toggle-workspace-float-override", + M::ToggleWorkspaceFloatOverride, + ), + ( + "toggle-workspace-float-override", + M::ToggleWorkspaceFloatOverride, + ), + ( + "ensure-named-workspaces 0 one two three", + M::EnsureNamedWorkspaces(0, vec!["one".into(), "two".into(), "three".into()]), + ), + ( + "workspace-name 0 0 one", + M::WorkspaceName(0, 0, "one".into()), + ), + ("ensure-workspaces 0 3", M::EnsureWorkspaces(0, 3)), + ( + "workspace-tiling 0 0 disable", + M::WorkspaceTiling(0, 0, false), + ), + ( + "workspace-tiling 0 0 enable", + M::WorkspaceTiling(0, 0, true), + ), + ( + "named-workspace-tiling one disable", + M::NamedWorkspaceTiling("one".into(), false), + ), + ( + "named-workspace-tiling one enable", + M::NamedWorkspaceTiling("one".into(), true), + ), + ("focus-workspace 1", M::FocusWorkspaceNumber(1)), + ("focus-workspace 0", M::FocusWorkspaceNumber(0)), + ("focus-last-workspace", M::FocusLastWorkspace), + ("focus-last-workspace", M::FocusLastWorkspace), + ("focus-workspaces 1", M::FocusWorkspaceNumbers(1)), + ("focus-workspaces 0", M::FocusWorkspaceNumbers(0)), + ("cycle-workspace next", M::CycleFocusWorkspace(Next)), + ("cycle-workspace previous", M::CycleFocusWorkspace(Previous)), + ( + "cycle-empty-workspace next", + M::CycleFocusEmptyWorkspace(Next), + ), + ("focus-workspace 0", M::FocusWorkspaceNumber(0)), + ( + "focus-named-workspace two", + M::FocusNamedWorkspace("two".into()), + ), + ( + "focus-named-workspace one", + M::FocusNamedWorkspace("one".into()), + ), + ("send-to-workspace 1", M::SendContainerToWorkspaceNumber(1)), + ("focus-workspace 1", M::FocusWorkspaceNumber(1)), + ("move-to-workspace 0", M::MoveContainerToWorkspaceNumber(0)), + ("focus-workspace 0", M::FocusWorkspaceNumber(0)), + ( + "cycle-send-to-workspace next", + M::CycleSendContainerToWorkspace(Next), + ), + ("focus-workspace 1", M::FocusWorkspaceNumber(1)), + ( + "cycle-move-to-workspace previous", + M::CycleMoveContainerToWorkspace(Previous), + ), + ("focus-workspace 0", M::FocusWorkspaceNumber(0)), + ("send-to-last-workspace", M::SendContainerToLastWorkspace), + ("move-to-last-workspace", M::MoveContainerToLastWorkspace), + ("focus-workspace 0", M::FocusWorkspaceNumber(0)), + ("new-workspace", M::NewWorkspace), + ("close-workspace", M::CloseWorkspace), + ("focus-workspace 0", M::FocusWorkspaceNumber(0)), + ( + "workspace-layout 0 0 columns", + M::WorkspaceLayout(0, 0, DefaultLayout::Columns), + ), + ( + "workspace-layout 0 0 bsp", + M::WorkspaceLayout(0, 0, DefaultLayout::BSP), + ), + ( + "named-workspace-layout one columns", + M::NamedWorkspaceLayout("one".into(), DefaultLayout::Columns), + ), + ( + "named-workspace-layout one bsp", + M::NamedWorkspaceLayout("one".into(), DefaultLayout::BSP), + ), + ( + "workspace-layout-rule 0 0 2 rows", + M::WorkspaceLayoutRule(0, 0, 2, DefaultLayout::Rows), + ), + ( + "workspace-layout-rule 0 0 3 columns", + M::WorkspaceLayoutRule(0, 0, 3, DefaultLayout::Columns), + ), + ( + "clear-workspace-layout-rules 0 0", + M::ClearWorkspaceLayoutRules(0, 0), + ), + ( + "named-workspace-layout-rule one 3 columns", + M::NamedWorkspaceLayoutRule("one".into(), 3, DefaultLayout::Columns), + ), + ( + "clear-named-workspace-layout-rules one", + M::ClearNamedWorkspaceLayoutRules("one".into()), + ), + ( + "workspace-layout 0 0 bsp", + M::WorkspaceLayout(0, 0, DefaultLayout::BSP), + ), + ("focus-monitor 1", M::FocusMonitorNumber(1)), + ("focus-monitor 0", M::FocusMonitorNumber(0)), + ("cycle-monitor next", M::CycleFocusMonitor(Next)), + ("cycle-monitor previous", M::CycleFocusMonitor(Previous)), + ( + "focus-monitor-workspace 1 1", + M::FocusMonitorWorkspaceNumber(1, 1), + ), + ( + "focus-monitor-workspace 0 0", + M::FocusMonitorWorkspaceNumber(0, 0), + ), + ("focus-monitor 0", M::FocusMonitorNumber(0)), + ( + "send-to-named-workspace two", + M::SendContainerToNamedWorkspace("two".into()), + ), + ( + "focus-named-workspace two", + M::FocusNamedWorkspace("two".into()), + ), + ( + "move-to-named-workspace one", + M::MoveContainerToNamedWorkspace("one".into()), + ), + ( + "focus-named-workspace one", + M::FocusNamedWorkspace("one".into()), + ), + ("send-to-monitor 1", M::SendContainerToMonitorNumber(1)), + ("focus-monitor 1", M::FocusMonitorNumber(1)), + ("move-to-monitor 0", M::MoveContainerToMonitorNumber(0)), + ("focus-monitor 0", M::FocusMonitorNumber(0)), + ( + "cycle-send-to-monitor next", + M::CycleSendContainerToMonitor(Next), + ), + ("focus-monitor 1", M::FocusMonitorNumber(1)), + ( + "cycle-move-to-monitor next", + M::CycleMoveContainerToMonitor(Next), + ), + ("focus-monitor 0", M::FocusMonitorNumber(0)), + ( + "send-to-monitor-workspace 1 1", + M::SendContainerToMonitorWorkspaceNumber(1, 1), + ), + ( + "focus-monitor-workspace 1 1", + M::FocusMonitorWorkspaceNumber(1, 1), + ), + ( + "move-to-monitor-workspace 0 0", + M::MoveContainerToMonitorWorkspaceNumber(0, 0), + ), + ("focus-monitor 0", M::FocusMonitorNumber(0)), + ("focus-workspace 0", M::FocusWorkspaceNumber(0)), + ( + "move-workspace-to-monitor 1", + M::MoveWorkspaceToMonitorNumber(1), + ), + ( + "cycle-move-workspace-to-monitor next", + M::CycleMoveWorkspaceToMonitor(Next), + ), + ( + "swap-workspaces-with-monitor 1", + M::SwapWorkspacesToMonitorNumber(1), + ), + ( + "swap-workspaces-with-monitor 1", + M::SwapWorkspacesToMonitorNumber(1), + ), + ( + "global-work-area-offset 10 10 20 20", + M::WorkAreaOffset(Rect { + left: 10, + top: 10, + right: 20, + bottom: 20, + }), + ), + ( + "global-work-area-offset 0 0 0 0", + M::WorkAreaOffset(Rect::default()), + ), + ( + "monitor-work-area-offset 0 10 10 20 20", + M::MonitorWorkAreaOffset( + 0, + Rect { + left: 10, + top: 10, + right: 20, + bottom: 20, + }, + ), + ), + ( + "monitor-work-area-offset 0 0 0 0 0", + M::MonitorWorkAreaOffset(0, Rect::default()), + ), + ( + "workspace-work-area-offset 0 0 10 10 20 20", + M::WorkspaceWorkAreaOffset( + 0, + 0, + Rect { + left: 10, + top: 10, + right: 20, + bottom: 20, + }, + ), + ), + ( + "workspace-work-area-offset 0 0 0 0 0 0", + M::WorkspaceWorkAreaOffset(0, 0, Rect::default()), + ), + ( + "toggle-window-based-work-area-offset", + M::ToggleWindowBasedWorkAreaOffset, + ), + ( + "toggle-window-based-work-area-offset", + M::ToggleWindowBasedWorkAreaOffset, + ), + ( + "focused-workspace-container-padding 20", + M::FocusedWorkspaceContainerPadding(20), + ), + ( + "focused-workspace-container-padding 10", + M::FocusedWorkspaceContainerPadding(10), + ), + ( + "focused-workspace-padding 20", + M::FocusedWorkspacePadding(20), + ), + ( + "focused-workspace-padding 10", + M::FocusedWorkspacePadding(10), + ), + ( + "adjust-container-padding increase 5", + M::AdjustContainerPadding(Increase, 5), + ), + ( + "adjust-container-padding decrease 5", + M::AdjustContainerPadding(Decrease, 5), + ), + ( + "adjust-workspace-padding increase 5", + M::AdjustWorkspacePadding(Increase, 5), + ), + ( + "adjust-workspace-padding decrease 5", + M::AdjustWorkspacePadding(Decrease, 5), + ), + ("container-padding 0 0 12", M::ContainerPadding(0, 0, 12)), + ("container-padding 0 0 10", M::ContainerPadding(0, 0, 10)), + ("workspace-padding 0 0 12", M::WorkspacePadding(0, 0, 12)), + ("workspace-padding 0 0 10", M::WorkspacePadding(0, 0, 10)), + ( + "named-workspace-container-padding one 12", + M::NamedWorkspaceContainerPadding("one".into(), 12), + ), + ( + "named-workspace-container-padding one 10", + M::NamedWorkspaceContainerPadding("one".into(), 10), + ), + ( + "named-workspace-padding one 12", + M::NamedWorkspacePadding("one".into(), 12), + ), + ( + "named-workspace-padding one 10", + M::NamedWorkspacePadding("one".into(), 10), + ), + ( + "cross-monitor-move-behaviour insert", + M::CrossMonitorMoveBehaviour(MoveBehaviour::Insert), + ), + ( + "cross-monitor-move-behaviour swap", + M::CrossMonitorMoveBehaviour(MoveBehaviour::Swap), + ), + ( + "toggle-cross-monitor-move-behaviour", + M::ToggleCrossMonitorMoveBehaviour, + ), + ( + "toggle-cross-monitor-move-behaviour", + M::ToggleCrossMonitorMoveBehaviour, + ), + ( + "toggle-monocle-focus-behaviour", + M::ToggleMonocleFocusBehaviour, + ), + ( + "toggle-monocle-focus-behaviour", + M::ToggleMonocleFocusBehaviour, + ), + ( + "unmanaged-window-operation-behaviour op", + M::UnmanagedWindowOperationBehaviour(OperationBehaviour::Op), + ), + ( + "unmanaged-window-operation-behaviour no-op", + M::UnmanagedWindowOperationBehaviour(OperationBehaviour::NoOp), + ), + ( + "unmanaged-window-operation-behaviour op", + M::UnmanagedWindowOperationBehaviour(OperationBehaviour::Op), + ), + ("session-float-rule", M::SessionFloatRule), + ("clear-session-float-rules", M::ClearSessionFloatRules), + ("toggle-float", M::ToggleFloat), + ("enforce-workspace-rules", M::EnforceWorkspaceRules), + ("clear-all-workspace-rules", M::ClearAllWorkspaceRules), + ("manage", M::ManageFocusedWindow), + ("retile", M::Retile), + ( + "scrolling: change-layout scrolling", + M::ChangeLayout(DefaultLayout::Scrolling), + ), + ("scrolling: consume left", M::Consume(Left)), + ("scrolling: expel", M::Expel), + ("scrolling: toggle-column-stack", M::ToggleColumnStack), + ( + "scrolling: scrolling-layout-full-width", + M::ScrollingLayoutFullWidth, + ), + ("scrolling: center-focus", M::CenterFocus), + ("scrolling: expand", M::Expand), + ("change-layout bsp", M::ChangeLayout(DefaultLayout::BSP)), + ] +} + +#[test] +fn no_command_of_the_sweep_breaks_the_daemon() { + let (fake, mut wm) = desktop(); + + let mut errors = Vec::new(); + for (step, (name, message)) in sweep().into_iter().enumerate() { + let mut reply = Vec::new(); + let result = with_backend(fake.clone(), || wm.process_command(message, &mut reply)); + if let Err(error) = result { + errors.push(format!("{step} {name}: {error}")); + } + + for id in IDS { + assert!( + managed(&wm, id), + "after {step} `{name}` the window {id} is not managed" + ); + } + + let mut state = Vec::new(); + with_backend(fake.clone(), || wm.process_command(M::State, &mut state)).unwrap(); + serde_json::from_slice::<serde_json::Value>(&state) + .unwrap_or_else(|error| panic!("after {step} `{name}` the state is not JSON: {error}")); + } + + // a command may refuse (a direction with no window in it), which is not a broken daemon; any + // other error is one the end-to-end scenario would call a command that was not understood + let others: Vec<_> = errors + .iter() + .filter(|e| !e.ends_with("there is no container or monitor in this direction")) + .collect(); + assert!(others.is_empty(), "commands that failed: {others:#?}"); +} From e95d146bae23c2be0b67b8b8a11fb0b98881e8a3 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 16:32:49 -0700 Subject: [PATCH 15/37] style(macos): format the macOS code with the project's rustfmt settings Pure formatting, no other change: nightly rustfmt --edition 2024 with komorebi-for-mac/rustfmt.toml (imports_granularity = Item) over komorebi-for-mac/**/*.rs and the macOS modules in the shared directories komorebic/src/macos and komorebi-bar/src/macos. 11 files; the kfm fmt check of the previous revision reported them. Windows and KDE code is not touched, and the Windows source filter excludes those macos files, so no Windows or KDE derivation changes. Verified: the rustfmt --check command of the fmt check passes on the result locally; nix eval of drvPath in a throwaway git copy: Windows deps and clippy, kfde deps, clippy and vm stacks are identical before and after it. --- komorebi-bar/src/macos/mod.rs | 6 +++-- komorebi-bar/src/macos/widgets/komorebi.rs | 16 ++++++------ komorebi-bar/src/macos/widgets/mod.rs | 1 - komorebi-bar/src/macos/widgets/network.rs | 4 +-- komorebi-bar/src/macos/widgets/widget.rs | 2 +- .../komorebi/src/animation/mod.rs | 3 +-- komorebi-for-mac/komorebi/src/daemon.rs | 8 +++--- komorebi-for-mac/komorebi/src/lib.rs | 2 +- .../komorebi/src/static_config.rs | 26 ++++++++++--------- .../komorebi/src/window_manager.rs | 8 +++--- komorebic/src/macos/mod.rs | 6 +++-- 11 files changed, 44 insertions(+), 38 deletions(-) diff --git a/komorebi-bar/src/macos/mod.rs b/komorebi-bar/src/macos/mod.rs index 8808d49d..f4906b39 100644 --- a/komorebi-bar/src/macos/mod.rs +++ b/komorebi-bar/src/macos/mod.rs @@ -127,7 +127,8 @@ pub fn main() -> eyre::Result<()> { ); if opts.quickstart { - let komorebi_bar_json = include_str!("../../../komorebi-for-mac/docs/komorebi.bar.example.json").to_string(); + let komorebi_bar_json = + include_str!("../../../komorebi-for-mac/docs/komorebi.bar.example.json").to_string(); std::fs::write(home_dir.join("komorebi.bar.json"), komorebi_bar_json)?; println!( "Example komorebi.bar.json file written to {}", @@ -148,7 +149,8 @@ pub fn main() -> eyre::Result<()> { let mut config = match config_path { None => { let komorebi_bar_json = - include_str!("../../../komorebi-for-mac/docs/komorebi.bar.example.json").to_string(); + include_str!("../../../komorebi-for-mac/docs/komorebi.bar.example.json") + .to_string(); std::fs::write(&default_config_path, komorebi_bar_json)?; tracing::info!( diff --git a/komorebi-bar/src/macos/widgets/komorebi.rs b/komorebi-bar/src/macos/widgets/komorebi.rs index 25e6808d..3a6d2175 100644 --- a/komorebi-bar/src/macos/widgets/komorebi.rs +++ b/komorebi-bar/src/macos/widgets/komorebi.rs @@ -7,14 +7,6 @@ use crate::macos::config::WorkspacesDisplayFormat; use crate::macos::render::RenderConfig; use crate::macos::selected_frame::SelectableFrame; use crate::macos::ui::CustomUi; -pub use komorebi_bar_core::widgets::komorebi_config::KomorebiConfig; -pub use komorebi_bar_core::widgets::komorebi_config::KomorebiConfigurationSwitcherConfig; -pub use komorebi_bar_core::widgets::komorebi_config::KomorebiFocusedContainerConfig; -pub use komorebi_bar_core::widgets::komorebi_config::KomorebiLayoutConfig; -pub use komorebi_bar_core::widgets::komorebi_config::KomorebiLockedContainerConfig; -pub use komorebi_bar_core::widgets::komorebi_config::KomorebiWorkspaceLayerConfig; -pub use komorebi_bar_core::widgets::komorebi_config::KomorebiWorkspacesConfig; -pub use komorebi_bar_core::widgets::komorebi_config::KomorebiLayout; use crate::macos::widgets::komorebi_layout::KomorebiLayoutExt; use crate::macos::widgets::widget::BarWidget; use eframe::egui::Align; @@ -39,6 +31,14 @@ use eframe::egui::vec2; use icns::IconFamily; use icns::IconType; use image::RgbaImage; +pub use komorebi_bar_core::widgets::komorebi_config::KomorebiConfig; +pub use komorebi_bar_core::widgets::komorebi_config::KomorebiConfigurationSwitcherConfig; +pub use komorebi_bar_core::widgets::komorebi_config::KomorebiFocusedContainerConfig; +pub use komorebi_bar_core::widgets::komorebi_config::KomorebiLayout; +pub use komorebi_bar_core::widgets::komorebi_config::KomorebiLayoutConfig; +pub use komorebi_bar_core::widgets::komorebi_config::KomorebiLockedContainerConfig; +pub use komorebi_bar_core::widgets::komorebi_config::KomorebiWorkspaceLayerConfig; +pub use komorebi_bar_core::widgets::komorebi_config::KomorebiWorkspacesConfig; use komorebi_client::Container; use komorebi_client::PathExt; use komorebi_client::Rect; diff --git a/komorebi-bar/src/macos/widgets/mod.rs b/komorebi-bar/src/macos/widgets/mod.rs index a429e6b8..3f7ccbec 100644 --- a/komorebi-bar/src/macos/widgets/mod.rs +++ b/komorebi-bar/src/macos/widgets/mod.rs @@ -1,4 +1,3 @@ - pub use komorebi_bar_core::widgets::applications; pub use komorebi_bar_core::widgets::battery; pub use komorebi_bar_core::widgets::cpu; diff --git a/komorebi-bar/src/macos/widgets/network.rs b/komorebi-bar/src/macos/widgets/network.rs index fb7b4041..34438c7b 100644 --- a/komorebi-bar/src/macos/widgets/network.rs +++ b/komorebi-bar/src/macos/widgets/network.rs @@ -1,6 +1,4 @@ use crate::macos::bar::Alignment; -pub use komorebi_bar_core::widgets::network_config::NetworkConfig; -pub use komorebi_bar_core::widgets::network_config::NetworkSelectConfig; use crate::macos::config::LabelPrefix; use crate::macos::render::RenderConfig; use crate::macos::selected_frame::SelectableFrame; @@ -12,6 +10,8 @@ use eframe::egui::Label; use eframe::egui::TextFormat; use eframe::egui::Ui; use eframe::egui::text::LayoutJob; +pub use komorebi_bar_core::widgets::network_config::NetworkConfig; +pub use komorebi_bar_core::widgets::network_config::NetworkSelectConfig; use num_derive::FromPrimitive; use parking_lot::Mutex; use std::fmt; diff --git a/komorebi-bar/src/macos/widgets/widget.rs b/komorebi-bar/src/macos/widgets/widget.rs index e2d56474..21376f32 100644 --- a/komorebi-bar/src/macos/widgets/widget.rs +++ b/komorebi-bar/src/macos/widgets/widget.rs @@ -11,9 +11,9 @@ use crate::macos::widgets::update::Update; use eframe::egui::Context; use eframe::egui::Ui; +use komorebi_bar_core::render::RenderConfig; pub use komorebi_bar_core::widgets::widget::BarWidget; pub use komorebi_bar_core::widgets::widget::WidgetConfig; -use komorebi_bar_core::render::RenderConfig; /// Stands in for a widget that macOS cannot run; `WidgetConfig::enabled` is false for those, so /// this is never built from a configuration that the bar loads. diff --git a/komorebi-for-mac/komorebi/src/animation/mod.rs b/komorebi-for-mac/komorebi/src/animation/mod.rs index 1213a6d6..76c8c6a6 100644 --- a/komorebi-for-mac/komorebi/src/animation/mod.rs +++ b/komorebi-for-mac/komorebi/src/animation/mod.rs @@ -1,8 +1,8 @@ use crate::core::animation::AnimationStyle; +pub use komorebi_config::animation::PerAnimationPrefixConfig; use parking_lot::Mutex; pub use prefix::AnimationPrefix; -pub use komorebi_config::animation::PerAnimationPrefixConfig; use std::collections::HashMap; use std::sync::Arc; use std::sync::LazyLock; @@ -26,7 +26,6 @@ pub mod tracks; pub mod transition; pub mod workspace_transition; - pub const DEFAULT_ANIMATION_ENABLED: bool = false; pub const DEFAULT_ANIMATION_STYLE: AnimationStyle = AnimationStyle::Linear; pub const DEFAULT_ANIMATION_DURATION: u64 = 250; diff --git a/komorebi-for-mac/komorebi/src/daemon.rs b/komorebi-for-mac/komorebi/src/daemon.rs index fc1505b5..7e25a647 100644 --- a/komorebi-for-mac/komorebi/src/daemon.rs +++ b/komorebi-for-mac/komorebi/src/daemon.rs @@ -1,9 +1,5 @@ #![warn(clippy::all)] -use clap::Parser; -use clap::ValueEnum; -use color_eyre::eyre; -use color_eyre::eyre::OptionExt; use crate::CoreFoundationRunLoop; use crate::DATA_DIR; use crate::HOME_DIR; @@ -24,6 +20,10 @@ use crate::theme_manager; use crate::window_manager::WindowManager; use crate::window_manager_event_listener; use crate::workspace_reconciliator; +use clap::Parser; +use clap::ValueEnum; +use color_eyre::eyre; +use color_eyre::eyre::OptionExt; use objc2::MainThreadMarker; use objc2::rc::autoreleasepool; use objc2_app_kit::NSApplication; diff --git a/komorebi-for-mac/komorebi/src/lib.rs b/komorebi-for-mac/komorebi/src/lib.rs index df046e82..e91cca6c 100644 --- a/komorebi-for-mac/komorebi/src/lib.rs +++ b/komorebi-for-mac/komorebi/src/lib.rs @@ -43,7 +43,6 @@ extern crate komorebi_collections; pub use komorebi_collections::ring; -pub mod daemon; pub mod accessibility; pub mod animation; pub mod app_kit_notification_constants; @@ -54,6 +53,7 @@ pub mod border_manager; pub mod container; pub mod core; pub mod core_graphics; +pub mod daemon; pub mod display_reconfiguration_listener; pub mod input_event_listener; pub mod ioreg; diff --git a/komorebi-for-mac/komorebi/src/static_config.rs b/komorebi-for-mac/komorebi/src/static_config.rs index 018cf428..e45c44b5 100644 --- a/komorebi-for-mac/komorebi/src/static_config.rs +++ b/komorebi-for-mac/komorebi/src/static_config.rs @@ -1,4 +1,3 @@ -use komorebi_settings::shared::SharedDelta; use crate::CoreFoundationRunLoop; use crate::DATA_DIR; use crate::DEFAULT_MOUSE_FOLLOWS_FOCUS; @@ -50,6 +49,7 @@ use color_eyre::eyre; use crossbeam_channel::Receiver; use hotwatch::EventKind; use hotwatch::Hotwatch; +use komorebi_settings::shared::SharedDelta; use komorebi_themes::colour::Colour; use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFRunLoop; @@ -332,12 +332,8 @@ impl From<&WindowManager> for StaticConfig { // border_style: Option::from(STYLE.load()), // border_z_order: None, // border_implementation: Option::from(IMPLEMENTATION.load()), - default_workspace_padding: Option::from( - crate::settings::workspace_padding(), - ), - default_container_padding: Option::from( - crate::settings::container_padding(), - ), + default_workspace_padding: Option::from(crate::settings::workspace_padding()), + default_container_padding: Option::from(crate::settings::container_padding()), layout_defaults: { let guard = crate::settings::layout_defaults(); if guard.is_empty() { @@ -369,7 +365,9 @@ impl From<&WindowManager> for StaticConfig { // slow_application_identifiers: Option::from(SLOW_APPLICATION_IDENTIFIERS.lock().clone()), // bar_configurations: None, // remove_titlebar_applications: Option::from(NO_TITLEBAR.lock().clone()), - floating_window_aspect_ratio: Option::from(crate::settings::floating_window_aspect_ratio()), + floating_window_aspect_ratio: Option::from( + crate::settings::floating_window_aspect_ratio(), + ), // window_handling_behaviour: Option::from(WINDOW_HANDLING_BEHAVIOUR.load()), tabbed_applications: None, ..Default::default() @@ -823,8 +821,10 @@ impl StaticConfigExt for StaticConfig { let mut value = Self::read(path)?; let mut wm = wm.lock(); - let configs_with_preference: Vec<_> = - crate::settings::display_index_preferences().keys().copied().collect(); + let configs_with_preference: Vec<_> = crate::settings::display_index_preferences() + .keys() + .copied() + .collect(); let mut configs_used = Vec::new(); let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); @@ -986,8 +986,10 @@ impl StaticConfigExt for StaticConfig { value.apply_globals()?; - let configs_with_preference: Vec<_> = - crate::settings::display_index_preferences().keys().copied().collect(); + let configs_with_preference: Vec<_> = crate::settings::display_index_preferences() + .keys() + .copied() + .collect(); let mut configs_used = Vec::new(); let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index 2f3f0471..20e416a4 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -1,4 +1,3 @@ -use crate::monitor::MonitorExt; use crate::AccessibilityUiElement; use crate::CoreFoundationRunLoop; use crate::DATA_DIR; @@ -41,6 +40,7 @@ use crate::current_space_id; use crate::lockable_sequence::Lockable; use crate::macos_api::MacosApi; use crate::monitor::Monitor; +use crate::monitor::MonitorExt; use crate::pan::Pan; use crate::ring::Ring; use crate::scrolling::WorkspaceScrolling; @@ -1548,7 +1548,8 @@ impl WindowManager { let hiding_position = self .focused_monitor() .ok_or_eyre("there is no monitor")? - .extra.window_hiding_position; + .extra + .window_hiding_position; let workspace = self.focused_workspace_mut()?; workspace.new_monocle_container()?; @@ -1584,7 +1585,8 @@ impl WindowManager { let hiding_position = self .focused_monitor() .ok_or_eyre("there is no monitor")? - .extra.window_hiding_position; + .extra + .window_hiding_position; self.focused_workspace_mut()? .cycle_monocle_container(direction)?; diff --git a/komorebic/src/macos/mod.rs b/komorebic/src/macos/mod.rs index d85b6767..24ad84a3 100644 --- a/komorebic/src/macos/mod.rs +++ b/komorebic/src/macos/mod.rs @@ -278,9 +278,11 @@ pub fn main() -> eyre::Result<()> { std::fs::create_dir_all(data_dir)?; let mut komorebi_json = - include_str!("../../../komorebi-for-mac/docs/komorebi.example.json").to_string(); + include_str!("../../../komorebi-for-mac/docs/komorebi.example.json") + .to_string(); let komorebi_bar_json = - include_str!("../../../komorebi-for-mac/docs/komorebi.bar.example.json").to_string(); + include_str!("../../../komorebi-for-mac/docs/komorebi.bar.example.json") + .to_string(); if std::env::var("KOMOREBI_CONFIG_HOME").is_ok() { komorebi_json = From 131a3cb9f8738da518d75600876761bca03eed11 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:34:29 -0700 Subject: [PATCH 16/37] build(tools): add fast-check, the minimal checks for the touched paths Runs only the checks a jj diff needs (KDE cargo check and tests, macOS type-check, Windows clippy through the nix dev shell, native crate tests, nix evaluation only) with persistent target dirs, and prints the time of each. Copy of the host-side script (the original stays in use outside the repository) with these differences: - FAST_CHECK_SCRATCH defaults to `${XDG_CACHE_HOME:-$HOME/.cache}/komorebi-fast-check` instead of a /tmp/claude-1000/... scratchpad path (usage text updated); - the fake C compiler is `$HERE/cc-fake.sh` (the script directory, resolved with readlink -f) instead of `$S/kfm/cc-fake.sh`; - `tools/*` is classified like docs (no check), so a change to the tools alone prints "nothing to run" instead of listing every file as unclassified; - the second `case` arm lost the patterns `Cargo.toml | Cargo.lock | .cargo/*`, which an earlier arm already catches (shellcheck SC2221/SC2222; no change in behaviour); - header comment: "from anywhere inside a jj workspace of the repository", no mention of komomono. Everything else is byte-identical (diff against the host copy). Verified: bash -n and shellcheck clean; `tools/fast-check --list` from this workspace. --- tools/fast-check | 137 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100755 tools/fast-check diff --git a/tools/fast-check b/tools/fast-check new file mode 100755 index 00000000..21609edb --- /dev/null +++ b/tools/fast-check @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# fast-check: run only the minimal checks for the current jj change. +# Run from anywhere inside a jj workspace of the repository. Never commits, never pushes. +# See tools/README.md. +set -uo pipefail + +S="${FAST_CHECK_SCRATCH:-${XDG_CACHE_HOME:-$HOME/.cache}/komorebi-fast-check}" +HERE="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" +FROM="" +LIST=0 +SELF="$(readlink -f "${BASH_SOURCE[0]}")" + +usage() { + cat <<'USAGE' +usage: fast-check [--list] [--range | --since REV] [--help] + --list dry run: print the checks that would run + --range diff trunk()..@ instead of just @ + --since REV diff REV..@ (REV is a jj revset, e.g. wip-a3b) +Env: FAST_CHECK_SCRATCH base dir for the persistent target dirs (default: ${XDG_CACHE_HOME:-~/.cache}/komorebi-fast-check) +USAGE +} + +# Evaluation-only nix check, attribute level: `nix flake show` (about 9 s, 0.4 GB). `nix flake check +# --no-build` forces every check of the system (15-16 GB RSS for 5-8 minutes, measured by `flow`) and fails +# without .git anyway (decision D9). Not caught here: an error inside a check's derivation body; the +# pre-landing `nix build` of the check still catches that. +nix_eval() { + # current system only: since the source of the merged workspace is a derivation that crane reads at evaluation, + # evaluating another system's checks needs a builder for that system (see docs/dev/unified-binaries.md) + systemd-run --user --scope -q -p MemoryMax=6G nice -n 19 nix flake show >/dev/null || return 1 + [ -d komorebi-for-kde ] || return 0 # a nested flake: attribute level only + for a in checks.x86_64-linux.komorebi-workspace-clippy checks.x86_64-linux.kfde-komorebi-workspace-clippy \ + packages.x86_64-linux.komorebic packages.x86_64-linux.kfde-komorebic; do + systemd-run --user --scope -q -p MemoryMax=6G nice -n 19 nix eval --raw ".#$a.drvPath" >/dev/null || return 1 + done +} + +while [ $# -gt 0 ]; do + case "$1" in + --list) LIST=1 ;; + --range) FROM='trunk()' ;; + --nix-eval) nix_eval; exit $? ;; + --since) shift; FROM="${1:?--since needs a revset}" ;; + -h | --help) usage; exit 0 ;; + *) usage >&2; exit 2 ;; + esac + shift +done + +ROOT="$(jj root 2>/dev/null)" || { echo "fast-check: not in a jj workspace" >&2; exit 2; } +cd "$ROOT" || exit 2 + +if [ -n "$FROM" ]; then + FILES="$(jj diff --name-only --from "$FROM" --to @)" || exit 2 +else + FILES="$(jj diff --name-only -r @)" || exit 2 +fi + +want_kde=0 want_mac=0 want_win=0 want_native=0 want_nix=0 want_nixkde=0 want_nixmac=0 +unclassified=() +while IFS= read -r f; do + [ -z "$f" ] && continue + case "$f" in + komorebi-for-kde/flake.nix | komorebi-for-kde/flake.lock | komorebi-for-kde/nix/*) want_nixkde=1 ;; + komorebi-for-mac/flake.nix | komorebi-for-mac/flake.lock | komorebi-for-mac/nix/*) want_nixmac=1 ;; + komorebi-for-kde/*.md | komorebi-for-kde/docs/* | komorebi-for-kde/LICENSE* | komorebi-for-kde/.github/*) ;; + komorebi-for-mac/*.md | komorebi-for-mac/docs/* | komorebi-for-mac/LICENSE* | komorebi-for-mac/.github/*) ;; + Cargo.toml | Cargo.lock | .cargo/*) want_win=1; want_kde=1; want_mac=1 ;; + komorebi-for-kde/*) want_kde=1 ;; + komorebi-for-mac/*) want_mac=1 ;; + crates/*) want_native=1; want_kde=1; want_mac=1; want_win=1 ;; + komorebi-layouts/* | komorebi-scrolling/*) want_native=1; want_win=1 ;; + flake.nix | flake.lock | *.nix) want_nix=1 ;; + *.md | docs/* | tools/* | LICENSE* | .github/* | *.png | *.jpg | *.gif) ;; + komorebi/* | komorebic/* | komorebi-bar/* | komorebi-client/* | komorebi-gui/* | komorebi-themes/* | e2e/* | rust-toolchain.toml | deny.toml) + want_win=1 ;; + *) unclassified+=("$f") ;; + esac +done <<<"$FILES" + +NAMES=() DIRS=() CMDS=() +add() { NAMES+=("$1"); DIRS+=("$2"); CMDS+=("$3"); } + +if [ "$want_native" = 1 ]; then + add "native: shared crates tests" "." \ + "CARGO_TARGET_DIR=$S/target-fast-native nix shell nixpkgs#gcc -c cargo test --locked -p komorebi-layouts -p komorebi-scrolling" +fi +# One root workspace (after the package merge) or three (before it): detect which, since agents' trees differ. +if [ -f komorebi-for-kde/Cargo.toml ]; then MERGED=0; else MERGED=1; fi +if [ "$want_win" = 1 ]; then + # a bare cargo command builds default-members (the Windows crates) in the merged workspace + WS=--workspace; [ $MERGED = 1 ] && WS= + add "windows: clippy --all-targets -D warnings (dev shell, cross)" "." \ + "CARGO_TARGET_DIR=$S/target-fast-win nix develop --command cargo clippy $WS --locked --all-targets -- -D warnings" +fi +if [ "$want_kde" = 1 ]; then + if [ $MERGED = 1 ]; then KD=.; else KD=komorebi-for-kde; fi + add "kde: cargo check + lib tests (komorebi)" "$KD" \ + "export CARGO_TARGET_DIR=$S/kde-target COMMIT_HASH=\${COMMIT_HASH:-dev}; K=komorebi; grep -q 'name = \"komorebi-linux\"' $( [ $MERGED = 1 ] && echo komorebi-for-kde/ )komorebi/Cargo.toml && K=komorebi-linux; export K; nix shell nixpkgs#gcc -c bash -c 'cargo check --locked -p \$K && { [ -d komorebi-daemon ] && cargo check --locked -p komorebi || true; } && cargo test --locked -p \$K --lib && cargo test --locked -p \$K --test schemas -- --test-threads=1'" +fi +if [ "$want_mac" = 1 ]; then + if [ $MERGED = 1 ]; then MD=.; MP="-p komorebi -p komorebi-macos -p komorebic-macos -p komorebi-client-macos -p komorebi-bar-macos"; else MD=komorebi-for-mac; MP=--workspace; fi + add "macos: type-check only (fake CC, cannot link)" "$MD" \ + "export CARGO_TARGET_DIR=$S/target-fast-mac COMMIT_HASH=\${COMMIT_HASH:-dev} CC_aarch64_apple_darwin=$HERE/cc-fake.sh AR_aarch64_apple_darwin=ar; PKG_CONFIG_PATH=\$(nix build --no-link --print-out-paths nixpkgs#openssl.dev)/lib/pkgconfig; export PKG_CONFIG_PATH; nix shell nixpkgs#gcc nixpkgs#pkg-config nixpkgs#openssl.dev -c cargo check --locked --target aarch64-apple-darwin $MP --all-targets" +fi +if [ "$want_nix" = 1 ] || [ "$want_nixkde" = 1 ] || [ "$want_nixmac" = 1 ]; then + add "nix: root flake evaluation only (flake check --no-build; flake show if dirtyRev missing)" "." "$SELF --nix-eval" +fi +if [ "$want_nixkde" = 1 ] && [ "$want_nix" = 0 ]; then + add "nix: kde flake evaluation only (flake check --no-build; flake show if dirtyRev missing)" "komorebi-for-kde" "$SELF --nix-eval" +fi +if [ "$want_nixmac" = 1 ] && [ "$want_nix" = 0 ]; then + add "nix: mac flake evaluation only (flake check --no-build; flake show if dirtyRev missing)" "komorebi-for-mac" "$SELF --nix-eval" +fi + +if [ "${#unclassified[@]}" -gt 0 ]; then + echo "fast-check: unclassified (no check): ${unclassified[*]}" +fi +if [ "${#NAMES[@]}" -eq 0 ]; then + echo "fast-check: nothing to run for this diff" + exit 0 +fi + +fail=0 +for i in "${!NAMES[@]}"; do + if [ "$LIST" = 1 ]; then + echo "[list] ${NAMES[$i]} (cd ${DIRS[$i]}; ${CMDS[$i]})" + continue + fi + echo "==> ${NAMES[$i]}" + start=$SECONDS + (cd "${DIRS[$i]}" && bash -c "${CMDS[$i]}") + rc=$? + el=$((SECONDS - start)) + if [ $rc -eq 0 ]; then echo "<== PASS ${NAMES[$i]} (${el}s)"; else echo "<== FAIL ${NAMES[$i]} (${el}s, exit $rc)"; fail=1; fi +done +exit $fail From d6c0c6f115331d7ac3a601234c64351295b0048e Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:39:38 -0700 Subject: [PATCH 17/37] refactor(windows): move transparency enabled and alpha to settings Plan step 10, S4 for Windows. TRANSPARENCY_ENABLED and TRANSPARENCY_ALPHA are no longer statics: the Transparency, TransparencyAlpha and ToggleTransparency commands write settings().shared.transparency with one update, the load applies the two keys as one update (Windows keeps the value when a key is absent, unlike KDE), the transparency thread, process_event, window.rs and the state/config dump read through the accessors. BEHAVIOUR: ToggleTransparency was a load then a store and is now one update; a load publishes the two keys together. Gate: Windows e2e (transparency, config_reload). Verified: Windows clippy -D warnings --locked --all-targets on komorebi-windows (cross): clean. e2e not run. --- komorebi/src/process_command.rs | 9 +++++---- komorebi/src/process_event.rs | 3 +-- komorebi/src/settings.rs | 10 ++++++++++ komorebi/src/state.rs | 6 ++---- komorebi/src/static_config.rs | 22 +++++++++++----------- komorebi/src/transparency_manager.rs | 8 +------- komorebi/src/window.rs | 7 +++---- 7 files changed, 33 insertions(+), 32 deletions(-) diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index dffebe53..3848d75f 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -1435,14 +1435,15 @@ impl WindowManager { } }, SocketMessage::ToggleTransparency => { - let current = transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst); - transparency_manager::TRANSPARENCY_ENABLED.store(!current, Ordering::SeqCst); + crate::settings::settings().update(|settings| { + settings.shared.transparency.enabled = !settings.shared.transparency.enabled; + }); } SocketMessage::Transparency(enable) => { - transparency_manager::TRANSPARENCY_ENABLED.store(enable, Ordering::SeqCst); + crate::settings::settings().update(|settings| settings.shared.transparency.enabled = enable); } SocketMessage::TransparencyAlpha(alpha) => { - transparency_manager::TRANSPARENCY_ALPHA.store(alpha, Ordering::SeqCst); + crate::settings::settings().update(|settings| settings.shared.transparency.alpha = alpha); } SocketMessage::StackbarMode(mode) => { STACKBAR_MODE.store(mode); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 43bb0ae5..3fcac487 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -5,7 +5,6 @@ use std::sync::Arc; use color_eyre::eyre; use color_eyre::eyre::OptionExt; -use crossbeam_utils::atomic::AtomicConsume; use parking_lot::Mutex; use crate::core::Rect; @@ -158,7 +157,7 @@ impl WindowManager { if !should_manage { let mut transparency_override = false; - if transparency_manager::TRANSPARENCY_ENABLED.load_consume() { + if crate::settings::transparency_enabled() { for m in self.monitors() { for w in m.workspaces() { let event_hwnd = event.window().hwnd; diff --git a/komorebi/src/settings.rs b/komorebi/src/settings.rs index 5b1e3242..9664abb8 100644 --- a/komorebi/src/settings.rs +++ b/komorebi/src/settings.rs @@ -67,6 +67,16 @@ pub fn display_index_preferences() -> HashMap<usize, String> { .clone() } +/// `transparency`: whether windows that are not focused are made see-through. +pub fn transparency_enabled() -> bool { + settings().snapshot().shared.transparency.enabled +} + +/// `transparency_alpha`: the opacity, 0 to 255, of a see-through window. +pub fn transparency_alpha() -> u8 { + settings().snapshot().shared.transparency.alpha +} + #[cfg(test)] mod tests { use std::sync::atomic::Ordering; diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 82aa53ec..0e8c13b5 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -39,8 +39,6 @@ use crate::stackbar_manager::STACKBAR_TAB_BACKGROUND_COLOUR; use crate::stackbar_manager::STACKBAR_TAB_HEIGHT; use crate::stackbar_manager::STACKBAR_TAB_WIDTH; use crate::stackbar_manager::STACKBAR_UNFOCUSED_TEXT_COLOUR; -use crate::transparency_manager::TRANSPARENCY_ALPHA; -use crate::transparency_manager::TRANSPARENCY_ENABLED; use crate::workspace::Workspace; use komorebi_themes::colour::Colour; use komorebi_themes::colour::Rgb; @@ -200,8 +198,8 @@ impl Default for GlobalState { )), stackbar_tab_width: STACKBAR_TAB_WIDTH.load(Ordering::SeqCst), stackbar_height: STACKBAR_TAB_HEIGHT.load(Ordering::SeqCst), - transparency_enabled: TRANSPARENCY_ENABLED.load(Ordering::SeqCst), - transparency_alpha: TRANSPARENCY_ALPHA.load(Ordering::SeqCst), + transparency_enabled: crate::settings::transparency_enabled(), + transparency_alpha: crate::settings::transparency_alpha(), transparency_blacklist: TRANSPARENCY_BLACKLIST.lock().clone(), remove_titlebars: REMOVE_TITLEBARS.load(Ordering::SeqCst), ignore_identifiers: IGNORE_IDENTIFIERS.lock().clone(), diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index 5f2e1aec..dfbb2888 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -68,7 +68,6 @@ use crate::stackbar_manager::STACKBAR_TAB_HEIGHT; use crate::stackbar_manager::STACKBAR_TAB_WIDTH; use crate::stackbar_manager::STACKBAR_UNFOCUSED_TEXT_COLOUR; use crate::theme_manager; -use crate::transparency_manager; use crate::window; use crate::window_manager::WindowManager; use crate::window_manager_event::WindowManagerEvent; @@ -322,10 +321,10 @@ impl From<&WindowManager> for StaticConfig { border: Option::from(border_manager::BORDER_ENABLED.load(Ordering::SeqCst)), border_colours, transparency: Option::from( - transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst), + crate::settings::transparency_enabled(), ), transparency_alpha: Option::from( - transparency_manager::TRANSPARENCY_ALPHA.load(Ordering::SeqCst), + crate::settings::transparency_alpha(), ), transparency_ignore_rules: None, border_style: Option::from(STYLE.load()), @@ -540,14 +539,15 @@ impl ApplyGlobals for StaticConfig { border_manager::send_notification(None); } - if let Some(transparency_enabled) = self.transparency { - transparency_manager::TRANSPARENCY_ENABLED - .store(transparency_enabled, Ordering::SeqCst); - } - - if let Some(transparency_alpha) = self.transparency_alpha { - transparency_manager::TRANSPARENCY_ALPHA.store(transparency_alpha, Ordering::SeqCst); - } + // Windows keeps the value when the key is absent (unlike KDE, which resets it) + crate::settings::settings().update(|settings| { + SharedDelta { + transparency: self.transparency, + transparency_alpha: self.transparency_alpha, + ..SharedDelta::default() + } + .apply(&mut settings.shared); + }); // the order documented at the statics in lib.rs let mut floating_applications = FLOATING_APPLICATIONS.lock(); diff --git a/komorebi/src/transparency_manager.rs b/komorebi/src/transparency_manager.rs index 8547b84e..dccb9d90 100644 --- a/komorebi/src/transparency_manager.rs +++ b/komorebi/src/transparency_manager.rs @@ -2,12 +2,9 @@ use crossbeam_channel::Receiver; use crossbeam_channel::Sender; -use crossbeam_utils::atomic::AtomicConsume; use parking_lot::Mutex; use std::sync::Arc; use std::sync::OnceLock; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU8; use crate::REGEX_IDENTIFIERS; use crate::TRANSPARENCY_BLACKLIST; @@ -16,9 +13,6 @@ use crate::WindowManager; use crate::WindowsApi; use crate::should_act; -pub static TRANSPARENCY_ENABLED: AtomicBool = AtomicBool::new(false); -pub static TRANSPARENCY_ALPHA: AtomicU8 = AtomicU8::new(200); - static KNOWN_HWNDS: OnceLock<Mutex<Vec<isize>>> = OnceLock::new(); pub struct Notification; @@ -71,7 +65,7 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result 'receiver: for _ in receiver { let known_hwnds = KNOWN_HWNDS.get_or_init(|| Mutex::new(Vec::new())); - if !TRANSPARENCY_ENABLED.load_consume() { + if !crate::settings::transparency_enabled() { for hwnd in known_hwnds.lock().iter() { if let Err(error) = Window::from(*hwnd).opaque() { tracing::error!("failed to make window {hwnd} opaque: {error}") diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 9e084ef6..aabebb0e 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -43,7 +43,6 @@ use crate::windows_api; use crate::windows_api::WindowsApi; use crate::windows_backend::backend; use color_eyre::eyre; -use crossbeam_utils::atomic::AtomicConsume; use komorebi_backend::WindowId; pub use komorebi_config::aspect_ratio::AspectRatio; pub use komorebi_config::aspect_ratio::PredefinedAspectRatio; @@ -632,7 +631,7 @@ impl Window { self.hwnd, false, WindowsApi::get_transparent(self.hwnd).unwrap_or(255), - transparency_manager::TRANSPARENCY_ALPHA.load_consume(), + crate::settings::transparency_alpha(), style, ); @@ -643,7 +642,7 @@ impl Window { self.update_ex_style(&ex_style)?; WindowsApi::set_transparent( self.hwnd, - transparency_manager::TRANSPARENCY_ALPHA.load_consume(), + crate::settings::transparency_alpha(), ) } } @@ -670,7 +669,7 @@ impl Window { self.hwnd, true, WindowsApi::get_transparent(self.hwnd) - .unwrap_or(transparency_manager::TRANSPARENCY_ALPHA.load_consume()), + .unwrap_or(crate::settings::transparency_alpha()), 255, style, ); From 55a57cb030ab9f1e0567775d0a0d303c625d255e Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:43:20 -0700 Subject: [PATCH 18/37] refactor(mac): four more process_command arms call the named methods KDE has LayoutRatios, Query, NamedWorkspaceRule and InitialNamedWorkspaceRule were the same code inline on macOS as set_layout_ratios, answer_query, add_named_workspace_rule and add_initial_named_workspace_rule on KDE (compared with whitespace removed). The macOS arms call methods with those names and bodies and are byte-identical to KDE's. No behaviour change. The other inline macOS arms differ in what they do (ReplaceConfiguration has the run loop and no warning, ToggleWorkspaceWindowContainerBehaviour, SessionFloatRule, IgnoreRule, ToggleWorkspaceLayer and ResizeWindowAxis have other bodies) and stay. Verified: fake-CC cargo clippy -p komorebi-macos ... --all-targets -D warnings: PASS (type-check only). Not run: the macOS tests (the Mac Mini). --- .../komorebi/src/process_command.rs | 256 ++++++++++-------- 1 file changed, 146 insertions(+), 110 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index cc08d759..8415a1f3 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -113,6 +113,148 @@ impl CommandTarget for WindowManager { } impl WindowManager { + /// Sets the column and row ratios of the focused workspace's layout + pub fn set_layout_ratios( + &mut self, + columns: &Option<Vec<f32>>, + rows: &Option<Vec<f32>>, + ) -> eyre::Result<()> { + use crate::core::validate_ratios; + + let focused_workspace = self.focused_workspace_mut()?; + + let mut options = focused_workspace.layout_options.unwrap_or(LayoutOptions { + scrolling: None, + grid: None, + column_ratios: None, + row_ratios: None, + }); + + if let Some(cols) = columns { + options.column_ratios = Some(validate_ratios(cols)); + } + + if let Some(rws) = rows { + options.row_ratios = Some(validate_ratios(rws)); + } + + focused_workspace.layout_options = Some(options); + self.update_focused_workspace(false, false)?; + Ok(()) + } + + /// Writes the answer to a state query to `reply` + pub fn answer_query( + &mut self, + query: StateQuery, + reply: &mut impl std::io::Write, + ) -> eyre::Result<()> { + let response = match query { + StateQuery::FocusedMonitorIndex => self.focused_monitor_idx().to_string(), + StateQuery::FocusedWorkspaceIndex => self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx() + .to_string(), + StateQuery::FocusedContainerIndex => self + .focused_workspace()? + .focused_container_idx() + .to_string(), + StateQuery::FocusedWindowIndex => { + self.focused_container()?.focused_window_idx().to_string() + } + StateQuery::FocusedWorkspaceName => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor + .focused_workspace_name() + .unwrap_or_else(|| focused_monitor.focused_workspace_idx().to_string()) + } + StateQuery::Version => build::VERSION.to_string(), + StateQuery::FocusedWorkspaceLayout => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor.focused_workspace_layout().map_or_else( + || "None".to_string(), + |layout| match layout { + Layout::Default(default_layout) => default_layout.to_string(), + }, + ) + } + StateQuery::FocusedContainerKind => { + match self.focused_workspace()?.focused_container() { + None => "None".to_string(), + Some(container) => { + if container.windows().len() > 1 { + "Stack".to_string() + } else { + "Single".to_string() + } + } + } + } + }; + + reply.write_all(response.as_bytes())?; + Ok(()) + } + + /// Adds a rule that puts the windows matching `id` on a named workspace, if the workspace exists + pub fn add_named_workspace_rule( + &mut self, + identifier: ApplicationIdentifier, + id: &str, + workspace: &str, + ) -> eyre::Result<()> { + if let Some((monitor_idx, workspace_idx)) = self.monitor_workspace_index_by_name(workspace) + { + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + let workspace_matching_rule = WorkspaceMatchingRule { + monitor_index: monitor_idx, + workspace_index: workspace_idx, + matching_rule: MatchingRule::Simple(IdWithIdentifier { + kind: identifier, + id: id.to_string(), + matching_strategy: Some(MatchingStrategy::Legacy), + }), + initial_only: false, + }; + + if !workspace_rules.contains(&workspace_matching_rule) { + workspace_rules.push(workspace_matching_rule); + } + } + Ok(()) + } + + /// Adds a rule that puts a window matching `id` on a named workspace when it first appears, if the workspace exists + pub fn add_initial_named_workspace_rule( + &mut self, + identifier: ApplicationIdentifier, + id: &str, + workspace: &str, + ) -> eyre::Result<()> { + if let Some((monitor_idx, workspace_idx)) = self.monitor_workspace_index_by_name(workspace) + { + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + let workspace_matching_rule = WorkspaceMatchingRule { + monitor_index: monitor_idx, + workspace_index: workspace_idx, + matching_rule: MatchingRule::Simple(IdWithIdentifier { + kind: identifier, + id: id.to_string(), + matching_strategy: Some(MatchingStrategy::Legacy), + }), + initial_only: true, + }; + + if !workspace_rules.contains(&workspace_matching_rule) { + workspace_rules.push(workspace_matching_rule); + } + } + Ok(()) + } + /// Sets the border colour of one kind of window pub fn set_border_colour(&mut self, kind: WindowKind, r: u32, g: u32, b: u32) { match kind { @@ -1107,57 +1249,7 @@ impl WindowManager { reply.write_all(monitors_state.as_bytes())?; } - SocketMessage::Query(query) => { - let response = match query { - StateQuery::FocusedMonitorIndex => self.focused_monitor_idx().to_string(), - StateQuery::FocusedWorkspaceIndex => self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx() - .to_string(), - StateQuery::FocusedContainerIndex => self - .focused_workspace()? - .focused_container_idx() - .to_string(), - StateQuery::FocusedWindowIndex => { - self.focused_container()?.focused_window_idx().to_string() - } - StateQuery::FocusedWorkspaceName => { - let focused_monitor = - self.focused_monitor().ok_or_eyre("there is no monitor")?; - - focused_monitor - .focused_workspace_name() - .unwrap_or_else(|| focused_monitor.focused_workspace_idx().to_string()) - } - StateQuery::Version => build::VERSION.to_string(), - StateQuery::FocusedWorkspaceLayout => { - let focused_monitor = - self.focused_monitor().ok_or_eyre("there is no monitor")?; - - focused_monitor.focused_workspace_layout().map_or_else( - || "None".to_string(), - |layout| match layout { - Layout::Default(default_layout) => default_layout.to_string(), - }, - ) - } - StateQuery::FocusedContainerKind => { - match self.focused_workspace()?.focused_container() { - None => "None".to_string(), - Some(container) => { - if container.windows().len() > 1 { - "Stack".to_string() - } else { - "Single".to_string() - } - } - } - } - }; - - reply.write_all(response.as_bytes())?; - } + SocketMessage::Query(query) => self.answer_query(query, &mut reply)?, SocketMessage::SessionFloatRule => { let foreground_window = MacosApi::foreground_window().ok_or_eyre("there is no foreground window")?; @@ -1225,25 +1317,7 @@ impl WindowManager { } } SocketMessage::InitialNamedWorkspaceRule(identifier, ref id, ref workspace) => { - if let Some((monitor_idx, workspace_idx)) = - self.monitor_workspace_index_by_name(workspace) - { - let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); - let workspace_matching_rule = WorkspaceMatchingRule { - monitor_index: monitor_idx, - workspace_index: workspace_idx, - matching_rule: MatchingRule::Simple(IdWithIdentifier { - kind: identifier, - id: id.to_string(), - matching_strategy: Some(MatchingStrategy::Legacy), - }), - initial_only: true, - }; - - if !workspace_rules.contains(&workspace_matching_rule) { - workspace_rules.push(workspace_matching_rule); - } - } + self.add_initial_named_workspace_rule(identifier, id, workspace)? } SocketMessage::WorkspaceRule(identifier, ref id, monitor_idx, workspace_idx) => { let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); @@ -1263,25 +1337,7 @@ impl WindowManager { } } SocketMessage::NamedWorkspaceRule(identifier, ref id, ref workspace) => { - if let Some((monitor_idx, workspace_idx)) = - self.monitor_workspace_index_by_name(workspace) - { - let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); - let workspace_matching_rule = WorkspaceMatchingRule { - monitor_index: monitor_idx, - workspace_index: workspace_idx, - matching_rule: MatchingRule::Simple(IdWithIdentifier { - kind: identifier, - id: id.to_string(), - matching_strategy: Some(MatchingStrategy::Legacy), - }), - initial_only: false, - }; - - if !workspace_rules.contains(&workspace_matching_rule) { - workspace_rules.push(workspace_matching_rule); - } - } + self.add_named_workspace_rule(identifier, id, workspace)? } SocketMessage::ClearWorkspaceRules(monitor_idx, workspace_idx) => { let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); @@ -1545,27 +1601,7 @@ impl WindowManager { self.update_focused_workspace(false, false)?; } SocketMessage::LayoutRatios(ref columns, ref rows) => { - use crate::core::validate_ratios; - - let focused_workspace = self.focused_workspace_mut()?; - - let mut options = focused_workspace.layout_options.unwrap_or(LayoutOptions { - scrolling: None, - grid: None, - column_ratios: None, - row_ratios: None, - }); - - if let Some(cols) = columns { - options.column_ratios = Some(validate_ratios(cols)); - } - - if let Some(rws) = rows { - options.row_ratios = Some(validate_ratios(rws)); - } - - focused_workspace.layout_options = Some(options); - self.update_focused_workspace(false, false)?; + self.set_layout_ratios(columns, rows)? } SocketMessage::NamedWorkspaceLayoutRule(ref workspace, at_container_count, layout) => { if let Some((monitor_idx, workspace_idx)) = From 0f851bfb0a6429b9140fd85e25518afc7ca3df07 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:38:24 -0700 Subject: [PATCH 19/37] docs(cli): regenerate the stale Windows command pages docs/cli lagged behind the Windows komorebic: 35 pages had out-of-date help text (possible values now listed with their descriptions, new doc comments, the Scrolling commands without the komorebic.exe usage name) and 3 pages did not exist yet. They are regenerated from the current Windows CLI definition (komorebic-core docgen-all example, platform windows, COLUMNS=1000 so nothing is re-wrapped like the existing pages), and the page conventions of each file are kept: header line only where the page had one, komorebic.exe as the binary name, trailing newline. The other 149 pages are byte-identical to the fresh output. The KDE and macOS pages are untouched (decision D20: Windows was the only stale set). Docs only, no behaviour. Verified: regenerated twice, second compare shows no diff; the real Windows binary was not run (the pages come from the shared definition rendered on Linux, class text normalised to the Windows one). --- docs/cli/adjust-container-padding.md | 6 ++- docs/cli/adjust-workspace-padding.md | 6 ++- docs/cli/animation-duration.md | 9 ++-- docs/cli/animation-style.md | 44 ++++++++++++++++--- docs/cli/animation.md | 9 ++-- docs/cli/border-colour.md | 11 ++++- docs/cli/center-focus.md | 4 +- docs/cli/change-layout.md | 13 +++++- docs/cli/consume.md | 4 +- docs/cli/expand.md | 2 +- docs/cli/expel.md | 7 ++- docs/cli/flip-layout.md | 7 ++- docs/cli/identify-layered-application.md | 8 +++- ...identify-object-name-change-application.md | 8 +++- docs/cli/identify-tray-application.md | 8 +++- docs/cli/ignore-rule.md | 8 +++- docs/cli/initial-named-workspace-rule.md | 8 +++- docs/cli/initial-workspace-rule.md | 8 +++- docs/cli/layout-ratios.md | 16 +++++++ docs/cli/manage-rule.md | 8 +++- docs/cli/monocle-focus-behaviour.md | 18 ++++++++ docs/cli/named-workspace-layout-rule.md | 13 +++++- docs/cli/named-workspace-layout.md | 13 +++++- docs/cli/named-workspace-rule.md | 8 +++- docs/cli/pan.md | 2 +- docs/cli/remove-title-bar.md | 8 +++- docs/cli/resize-axis.md | 11 +++-- docs/cli/resize-edge.md | 6 ++- docs/cli/scrolling-layout-full-width.md | 7 ++- docs/cli/stackbar-mode.md | 9 ++-- docs/cli/start.md | 2 +- docs/cli/toggle-column-stack.md | 7 ++- docs/cli/toggle-monocle-focus-behaviour.md | 10 +++++ .../unmanaged-window-operation-behaviour.md | 4 +- docs/cli/window-hiding-behaviour.md | 4 +- docs/cli/workspace-layout-rule.md | 13 +++++- docs/cli/workspace-layout.md | 13 +++++- docs/cli/workspace-rule.md | 8 +++- 38 files changed, 270 insertions(+), 80 deletions(-) create mode 100644 docs/cli/layout-ratios.md create mode 100644 docs/cli/monocle-focus-behaviour.md create mode 100644 docs/cli/toggle-monocle-focus-behaviour.md diff --git a/docs/cli/adjust-container-padding.md b/docs/cli/adjust-container-padding.md index f8bd2796..058231cc 100644 --- a/docs/cli/adjust-container-padding.md +++ b/docs/cli/adjust-container-padding.md @@ -7,13 +7,15 @@ Usage: komorebic.exe adjust-container-padding <SIZING> <ADJUSTMENT> Arguments: <SIZING> - [possible values: increase, decrease] + Possible values: + - increase: Increase + - decrease: Decrease <ADJUSTMENT> Pixels to adjust by as an integer Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/adjust-workspace-padding.md b/docs/cli/adjust-workspace-padding.md index 09fe58c4..ac1aada6 100644 --- a/docs/cli/adjust-workspace-padding.md +++ b/docs/cli/adjust-workspace-padding.md @@ -7,13 +7,15 @@ Usage: komorebic.exe adjust-workspace-padding <SIZING> <ADJUSTMENT> Arguments: <SIZING> - [possible values: increase, decrease] + Possible values: + - increase: Increase + - decrease: Decrease <ADJUSTMENT> Pixels to adjust by as an integer Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/animation-duration.md b/docs/cli/animation-duration.md index e0ec8d34..891e4969 100644 --- a/docs/cli/animation-duration.md +++ b/docs/cli/animation-duration.md @@ -12,10 +12,13 @@ Arguments: Options: -a, --animation-type <ANIMATION_TYPE> Animation type to apply the duration to. If not specified, sets global duration - - [possible values: movement, transparency, workspace] + + Possible values: + - movement + - transparency + - workspace: A workspace sliding in and out of a monitor when it is switched to -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/animation-style.md b/docs/cli/animation-style.md index 11cc3eae..e2f59a12 100644 --- a/docs/cli/animation-style.md +++ b/docs/cli/animation-style.md @@ -8,17 +8,51 @@ Usage: komorebic.exe animation-style [OPTIONS] Options: -s, --style <STYLE> Desired ease function for animation + + Possible values: + - linear: Linear + - ease-in-sine: Ease in sine + - ease-out-sine: Ease out sine + - ease-in-out-sine: Ease in out sine + - ease-in-quad: Ease in quad + - ease-out-quad: Ease out quad + - ease-in-out-quad: Ease in out quad + - ease-in-cubic: Ease in cubic + - ease-out-cubic: Ease out cubic + - ease-in-out-cubic: Ease in out cubic + - ease-in-quart: Ease in quart + - ease-out-quart: Ease out quart + - ease-in-out-quart: Ease in out quart + - ease-in-quint: Ease in quint + - ease-out-quint: Ease out quint + - ease-in-out-quint: Ease in out quint + - ease-in-expo: Ease in expo + - ease-out-expo: Ease out expo + - ease-in-out-expo: Ease in out expo + - ease-in-circ: Ease in circ + - ease-out-circ: Ease out circ + - ease-in-out-circ: Ease in out circ + - ease-in-back: Ease in back + - ease-out-back: Ease out back + - ease-in-out-back: Ease in out back + - ease-in-elastic: Ease in elastic + - ease-out-elastic: Ease out elastic + - ease-in-out-elastic: Ease in out elastic + - ease-in-bounce: Ease in bounce + - ease-out-bounce: Ease out bounce + - ease-in-out-bounce: Ease in out bounce [default: linear] - [possible values: linear, ease-in-sine, ease-out-sine, ease-in-out-sine, ease-in-quad, ease-out-quad, ease-in-out-quad, ease-in-cubic, ease-in-out-cubic, ease-in-quart, ease-out-quart, ease-in-out-quart, ease-in-quint, ease-out-quint, ease-in-out-quint, ease-in-expo, - ease-out-expo, ease-in-out-expo, ease-in-circ, ease-out-circ, ease-in-out-circ, ease-in-back, ease-out-back, ease-in-out-back, ease-in-elastic, ease-out-elastic, ease-in-out-elastic, ease-in-bounce, ease-out-bounce, ease-in-out-bounce] -a, --animation-type <ANIMATION_TYPE> Animation type to apply the style to. If not specified, sets global style - - [possible values: movement, transparency, workspace] + + Possible values: + - movement + - transparency + - workspace: A workspace sliding in and out of a monitor when it is switched to -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/animation.md b/docs/cli/animation.md index 530bcaa8..ab38fe76 100644 --- a/docs/cli/animation.md +++ b/docs/cli/animation.md @@ -12,10 +12,13 @@ Arguments: Options: -a, --animation-type <ANIMATION_TYPE> Animation type to apply the state to. If not specified, sets global state - - [possible values: movement, transparency, workspace] + + Possible values: + - movement + - transparency + - workspace: A workspace sliding in and out of a monitor when it is switched to -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/border-colour.md b/docs/cli/border-colour.md index 55b84d34..84c70bff 100644 --- a/docs/cli/border-colour.md +++ b/docs/cli/border-colour.md @@ -17,10 +17,17 @@ Arguments: Options: -w, --window-kind <WINDOW_KIND> + Possible values: + - single: Single window + - stack: Stack container + - monocle: Monocle container + - unfocused: Unfocused window + - unfocused-locked: Unfocused locked container + - floating: Floating window + [default: single] - [possible values: single, stack, monocle, unfocused, unfocused-locked, floating] -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/center-focus.md b/docs/cli/center-focus.md index 8d321dc9..0f2dfab7 100644 --- a/docs/cli/center-focus.md +++ b/docs/cli/center-focus.md @@ -1,10 +1,10 @@ ``` Scroll the Scrolling layout so that the focused column is in the middle of the screen, once -Usage: center-focus +Usage: komorebic.exe center-focus Options: -h, --help Print help -``` \ No newline at end of file +``` diff --git a/docs/cli/change-layout.md b/docs/cli/change-layout.md index 873214b7..bed3196d 100644 --- a/docs/cli/change-layout.md +++ b/docs/cli/change-layout.md @@ -7,10 +7,19 @@ Usage: komorebic.exe change-layout <DEFAULT_LAYOUT> Arguments: <DEFAULT_LAYOUT> - [possible values: bsp, columns, rows, vertical-stack, horizontal-stack, ultrawide-vertical-stack, grid, right-main-vertical-stack, scrolling] + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/consume.md b/docs/cli/consume.md index 10397301..d66145a0 100644 --- a/docs/cli/consume.md +++ b/docs/cli/consume.md @@ -1,7 +1,7 @@ ``` Take the neighbouring window on one side into the focused column of the Scrolling layout -Usage: consume <OPERATION_DIRECTION> +Usage: komorebic.exe consume <OPERATION_DIRECTION> Arguments: <OPERATION_DIRECTION> @@ -11,4 +11,4 @@ Options: -h, --help Print help -``` \ No newline at end of file +``` diff --git a/docs/cli/expand.md b/docs/cli/expand.md index 6ad3eab3..6acaec9c 100644 --- a/docs/cli/expand.md +++ b/docs/cli/expand.md @@ -1,7 +1,7 @@ ``` Make the focused column of the Scrolling layout fill the room that the columns in view leave on the screen, which does nothing in any other layout -Usage: expand +Usage: komorebic.exe expand Options: -h, --help diff --git a/docs/cli/expel.md b/docs/cli/expel.md index 35c8c142..39b3bf4b 100644 --- a/docs/cli/expel.md +++ b/docs/cli/expel.md @@ -1,11 +1,10 @@ ``` -Take the focused window out of its column in the Scrolling layout and put it in a column of its own -on the right +Take the focused window out of its column in the Scrolling layout and put it in a column of its own on the right -Usage: expel +Usage: komorebic.exe expel Options: -h, --help Print help -``` \ No newline at end of file +``` diff --git a/docs/cli/flip-layout.md b/docs/cli/flip-layout.md index 18e1c265..83e9ada8 100644 --- a/docs/cli/flip-layout.md +++ b/docs/cli/flip-layout.md @@ -7,10 +7,13 @@ Usage: komorebic.exe flip-layout <AXIS> Arguments: <AXIS> - [possible values: horizontal, vertical, horizontal-and-vertical] + Possible values: + - horizontal: Horizontal axis + - vertical: Vertical axis + - horizontal-and-vertical: Both horizontal and vertical axes Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/identify-layered-application.md b/docs/cli/identify-layered-application.md index 0aff6c60..0f88f2bf 100644 --- a/docs/cli/identify-layered-application.md +++ b/docs/cli/identify-layered-application.md @@ -7,13 +7,17 @@ Usage: komorebic.exe identify-layered-application <IDENTIFIER> <ID> Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/identify-object-name-change-application.md b/docs/cli/identify-object-name-change-application.md index 9be3c6cb..c97061bd 100644 --- a/docs/cli/identify-object-name-change-application.md +++ b/docs/cli/identify-object-name-change-application.md @@ -7,13 +7,17 @@ Usage: komorebic.exe identify-object-name-change-application <IDENTIFIER> <ID> Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/identify-tray-application.md b/docs/cli/identify-tray-application.md index 2ce0ab17..8892ce86 100644 --- a/docs/cli/identify-tray-application.md +++ b/docs/cli/identify-tray-application.md @@ -7,13 +7,17 @@ Usage: komorebic.exe identify-tray-application <IDENTIFIER> <ID> Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/ignore-rule.md b/docs/cli/ignore-rule.md index 34693f28..48120ba9 100644 --- a/docs/cli/ignore-rule.md +++ b/docs/cli/ignore-rule.md @@ -7,13 +7,17 @@ Usage: komorebic.exe ignore-rule <IDENTIFIER> <ID> Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/initial-named-workspace-rule.md b/docs/cli/initial-named-workspace-rule.md index 3a3418e3..01b8ee05 100644 --- a/docs/cli/initial-named-workspace-rule.md +++ b/docs/cli/initial-named-workspace-rule.md @@ -7,7 +7,11 @@ Usage: komorebic.exe initial-named-workspace-rule <IDENTIFIER> <ID> <WORKSPACE> Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string @@ -17,6 +21,6 @@ Arguments: Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/initial-workspace-rule.md b/docs/cli/initial-workspace-rule.md index f32b1387..57067407 100644 --- a/docs/cli/initial-workspace-rule.md +++ b/docs/cli/initial-workspace-rule.md @@ -7,7 +7,11 @@ Usage: komorebic.exe initial-workspace-rule <IDENTIFIER> <ID> <MONITOR> <WORKSPA Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string @@ -20,6 +24,6 @@ Arguments: Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/layout-ratios.md b/docs/cli/layout-ratios.md new file mode 100644 index 00000000..92d42da2 --- /dev/null +++ b/docs/cli/layout-ratios.md @@ -0,0 +1,16 @@ +``` +Set the layout column and row ratios for the focused workspace + +Usage: komorebic.exe layout-ratios [OPTIONS] + +Options: + -c, --columns <COLUMNS>... + Column width ratios (space-separated values between 0.1 and 0.9) + + -r, --rows <ROWS>... + Row height ratios (space-separated values between 0.1 and 0.9) + + -h, --help + Print help + +``` diff --git a/docs/cli/manage-rule.md b/docs/cli/manage-rule.md index 84b08135..d7dac7c7 100644 --- a/docs/cli/manage-rule.md +++ b/docs/cli/manage-rule.md @@ -7,13 +7,17 @@ Usage: komorebic.exe manage-rule <IDENTIFIER> <ID> Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/monocle-focus-behaviour.md b/docs/cli/monocle-focus-behaviour.md new file mode 100644 index 00000000..95587fe3 --- /dev/null +++ b/docs/cli/monocle-focus-behaviour.md @@ -0,0 +1,18 @@ +``` +Set the behaviour when focusing in a direction while a monocle container is active + +Usage: komorebic.exe monocle-focus-behaviour <BEHAVIOUR> + +Arguments: + <BEHAVIOUR> + Desired monocle focus behaviour + + Possible values: + - cycle: Cycle the monocle container to the next/previous container in the workspace + - no-op: Do nothing, allowing focus to fall through to cross-monitor logic + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/named-workspace-layout-rule.md b/docs/cli/named-workspace-layout-rule.md index a61d77fd..e7599f4a 100644 --- a/docs/cli/named-workspace-layout-rule.md +++ b/docs/cli/named-workspace-layout-rule.md @@ -13,10 +13,19 @@ Arguments: The number of window containers on-screen required to trigger this layout rule <LAYOUT> - [possible values: bsp, columns, rows, vertical-stack, horizontal-stack, ultrawide-vertical-stack, grid, right-main-vertical-stack, scrolling] + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/named-workspace-layout.md b/docs/cli/named-workspace-layout.md index 4277fb67..aaa65a8c 100644 --- a/docs/cli/named-workspace-layout.md +++ b/docs/cli/named-workspace-layout.md @@ -10,10 +10,19 @@ Arguments: Target workspace name <VALUE> - [possible values: bsp, columns, rows, vertical-stack, horizontal-stack, ultrawide-vertical-stack, grid, right-main-vertical-stack, scrolling] + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/named-workspace-rule.md b/docs/cli/named-workspace-rule.md index e84ad6cf..8f94fe9f 100644 --- a/docs/cli/named-workspace-rule.md +++ b/docs/cli/named-workspace-rule.md @@ -7,7 +7,11 @@ Usage: komorebic.exe named-workspace-rule <IDENTIFIER> <ID> <WORKSPACE> Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string @@ -17,6 +21,6 @@ Arguments: Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/pan.md b/docs/cli/pan.md index 912077d6..4da0a016 100644 --- a/docs/cli/pan.md +++ b/docs/cli/pan.md @@ -1,7 +1,7 @@ ``` Move the view of the Scrolling layout a column to the left or the right, or with the fingers on a touchpad, which does nothing in any other layout -Usage: pan [OPTIONS] [DIRECTION] +Usage: komorebic.exe pan [OPTIONS] [DIRECTION] Arguments: [DIRECTION] diff --git a/docs/cli/remove-title-bar.md b/docs/cli/remove-title-bar.md index 08d19cd5..d0d4e780 100644 --- a/docs/cli/remove-title-bar.md +++ b/docs/cli/remove-title-bar.md @@ -7,13 +7,17 @@ Usage: komorebic.exe remove-title-bar <IDENTIFIER> <ID> Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/resize-axis.md b/docs/cli/resize-axis.md index 8d8a39a9..7ed29b1b 100644 --- a/docs/cli/resize-axis.md +++ b/docs/cli/resize-axis.md @@ -7,13 +7,18 @@ Usage: komorebic.exe resize-axis <AXIS> <SIZING> Arguments: <AXIS> - [possible values: horizontal, vertical, horizontal-and-vertical] + Possible values: + - horizontal: Horizontal axis + - vertical: Vertical axis + - horizontal-and-vertical: Both horizontal and vertical axes <SIZING> - [possible values: increase, decrease] + Possible values: + - increase: Increase + - decrease: Decrease Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/resize-edge.md b/docs/cli/resize-edge.md index c2de22f9..ecf60a71 100644 --- a/docs/cli/resize-edge.md +++ b/docs/cli/resize-edge.md @@ -10,10 +10,12 @@ Arguments: [possible values: left, right, up, down] <SIZING> - [possible values: increase, decrease] + Possible values: + - increase: Increase + - decrease: Decrease Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/scrolling-layout-full-width.md b/docs/cli/scrolling-layout-full-width.md index 8b244afe..7f726020 100644 --- a/docs/cli/scrolling-layout-full-width.md +++ b/docs/cli/scrolling-layout-full-width.md @@ -1,11 +1,10 @@ ``` -Make the focused column of the Scrolling layout as wide as the screen, or put it back to the width -that it had +Make the focused column of the Scrolling layout as wide as the screen, or put it back to the width that it had -Usage: scrolling-layout-full-width +Usage: komorebic.exe scrolling-layout-full-width Options: -h, --help Print help -``` \ No newline at end of file +``` diff --git a/docs/cli/stackbar-mode.md b/docs/cli/stackbar-mode.md index cb880179..c5ae6403 100644 --- a/docs/cli/stackbar-mode.md +++ b/docs/cli/stackbar-mode.md @@ -8,11 +8,14 @@ Usage: komorebic.exe stackbar-mode <MODE> Arguments: <MODE> Desired stackbar mode - - [possible values: always, never, on-stack] + + Possible values: + - always: Always show + - never: Never show + - on-stack: Show on stack Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/start.md b/docs/cli/start.md index 6cfd7cf1..136744b5 100644 --- a/docs/cli/start.md +++ b/docs/cli/start.md @@ -10,7 +10,7 @@ Options: Path to a static configuration JSON file -a, --await-configuration - Wait for 'komorebic complete-configuration' to be sent before processing events + Wait for `komorebic complete-configuration` to be sent before processing events -t, --tcp-port <TCP_PORT> Start a TCP server on the given port to allow the direct sending of SocketMessages diff --git a/docs/cli/toggle-column-stack.md b/docs/cli/toggle-column-stack.md index 3792569c..f3e46b57 100644 --- a/docs/cli/toggle-column-stack.md +++ b/docs/cli/toggle-column-stack.md @@ -1,11 +1,10 @@ ``` -Stack the windows of the focused column of the Scrolling layout, or spread the focused stack out -into a column with a window in each slot +Stack the windows of the focused column of the Scrolling layout, or spread the focused stack out into a column with a window in each slot -Usage: toggle-column-stack +Usage: komorebic.exe toggle-column-stack Options: -h, --help Print help -``` \ No newline at end of file +``` diff --git a/docs/cli/toggle-monocle-focus-behaviour.md b/docs/cli/toggle-monocle-focus-behaviour.md new file mode 100644 index 00000000..7051f12c --- /dev/null +++ b/docs/cli/toggle-monocle-focus-behaviour.md @@ -0,0 +1,10 @@ +``` +Toggle the behaviour when focusing in a direction while a monocle container is active + +Usage: komorebic.exe toggle-monocle-focus-behaviour + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/unmanaged-window-operation-behaviour.md b/docs/cli/unmanaged-window-operation-behaviour.md index c665ae88..5f420117 100644 --- a/docs/cli/unmanaged-window-operation-behaviour.md +++ b/docs/cli/unmanaged-window-operation-behaviour.md @@ -8,8 +8,8 @@ Usage: komorebic.exe unmanaged-window-operation-behaviour <OPERATION_BEHAVIOUR> Arguments: <OPERATION_BEHAVIOUR> Possible values: - - op: Process komorebic commands on temporarily unmanaged/floated windows - - no-op: Ignore komorebic commands on temporarily unmanaged/floated windows + - op: Process commands on temporarily unmanaged/floated windows + - no-op: Ignore commands on temporarily unmanaged/floated windows Options: -h, --help diff --git a/docs/cli/window-hiding-behaviour.md b/docs/cli/window-hiding-behaviour.md index 0aeea569..5c0f40b2 100644 --- a/docs/cli/window-hiding-behaviour.md +++ b/docs/cli/window-hiding-behaviour.md @@ -8,8 +8,8 @@ Usage: komorebic.exe window-hiding-behaviour <HIDING_BEHAVIOUR> Arguments: <HIDING_BEHAVIOUR> Possible values: - - hide: END OF LIFE FEATURE: Use the SW_HIDE flag to hide windows when switching workspaces (has issues with Electron apps) - - minimize: Use the SW_MINIMIZE flag to hide windows when switching workspaces (has issues with frequent workspace switching) + - hide: END OF LIFE FEATURE: Use the `SW_HIDE` flag to hide windows when switching workspaces (has issues with Electron apps) + - minimize: Use the `SW_MINIMIZE` flag to hide windows when switching workspaces (has issues with frequent workspace switching) - cloak: Use the undocumented SetCloak Win32 function to hide windows when switching workspaces Options: diff --git a/docs/cli/workspace-layout-rule.md b/docs/cli/workspace-layout-rule.md index 849d8b33..ce48fffc 100644 --- a/docs/cli/workspace-layout-rule.md +++ b/docs/cli/workspace-layout-rule.md @@ -16,10 +16,19 @@ Arguments: The number of window containers on-screen required to trigger this layout rule <LAYOUT> - [possible values: bsp, columns, rows, vertical-stack, horizontal-stack, ultrawide-vertical-stack, grid, right-main-vertical-stack, scrolling] + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/workspace-layout.md b/docs/cli/workspace-layout.md index 7f6cac7f..8daeda07 100644 --- a/docs/cli/workspace-layout.md +++ b/docs/cli/workspace-layout.md @@ -13,10 +13,19 @@ Arguments: Workspace index on the specified monitor (zero-indexed) <VALUE> - [possible values: bsp, columns, rows, vertical-stack, horizontal-stack, ultrawide-vertical-stack, grid, right-main-vertical-stack, scrolling] + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout Options: -h, --help - Print help + Print help (see a summary with '-h') ``` diff --git a/docs/cli/workspace-rule.md b/docs/cli/workspace-rule.md index db1a9841..f1a925bf 100644 --- a/docs/cli/workspace-rule.md +++ b/docs/cli/workspace-rule.md @@ -7,7 +7,11 @@ Usage: komorebic.exe workspace-rule <IDENTIFIER> <ID> <MONITOR> <WORKSPACE> Arguments: <IDENTIFIER> - [possible values: exe, class, title, path] + Possible values: + - exe: Executable name + - class: Class + - title: Window title + - path: Executable path <ID> Identifier as a string @@ -20,6 +24,6 @@ Arguments: Options: -h, --help - Print help + Print help (see a summary with '-h') ``` From ddc4b95b8de7cdf5eba9043ae5d25fdd11e56fac Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 17:15:39 -0700 Subject: [PATCH 20/37] test(komorebic-core): the commands of the e2e sweep are commands of the command lines The commands e2e scenario learns that a command does not exist in a platform only by running it in a guest (error: unrecognized subcommand, skipped with its name), about 7.6 minutes per Windows run. crates/komorebic-core/tests/e2e_sweep.rs reads SWEEP and PRINTED out of e2e/lib/komorebi_vm/core/scenarios/commands.py (skipped when the e2e library is not in the source tree) and parses each line with the platform's clap command: every one is a command of the Windows komorebic, and the macOS one lacks exactly the eight the scenario would skip there (focus-follows-mouse enable/disable, the Windows implementation of toggle-focus-follows-mouse, toggle-maximize, the transparency commands). 3 tests. mirrors: commands / <command> (the command is understood, for the command line only). Stays e2e only: that the daemon then answers; the KDE komorebic's own command set. Verified: cargo test -p komorebic-core --test e2e_sweep, 3 passed (native Linux; platform independent). No source change. --- crates/komorebic-core/tests/e2e_sweep.rs | 122 +++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 crates/komorebic-core/tests/e2e_sweep.rs diff --git a/crates/komorebic-core/tests/e2e_sweep.rs b/crates/komorebic-core/tests/e2e_sweep.rs new file mode 100644 index 00000000..17aeb36e --- /dev/null +++ b/crates/komorebic-core/tests/e2e_sweep.rs @@ -0,0 +1,122 @@ +//! The commands the `commands` end-to-end scenario sweeps (`SWEEP` and `PRINTED` in +//! `e2e/lib/komorebi_vm/core/scenarios/commands.py`) are commands of the platforms' `komorebic`. +//! +//! The scenario only learns that a command is not one when it runs it in a guest (`error: +//! unrecognized subcommand`, skipped with its name). Here the command lines are parsed with the +//! platform's clap command, so a command that a platform lost, or a typo in the scenario, fails a +//! native test and not a 7 minute guest run. +//! +//! mirrors: commands / <command> (the part "the command is understood: exit status 0", for the +//! command line only; what the daemon does with it is the daemon's tests, see +//! `komorebi-for-kde/komorebi/tests/command_sweep.rs`) + +use komorebic_core::cli::Meta; +use komorebic_core::cli::command; +use komorebic_core::platform::macos::MacosCommands; +use komorebic_core::platform::windows::WindowsCommands; +use std::path::Path; + +const META: Meta = Meta { + name: "komorebic", + about: "", + author: "", + version: "", +}; + +/// The strings of the tuple named `name` in the scenario, or `None` without the e2e library (a +/// source tree that is only the crates, as the nix build of one daemon has). +fn tuple(name: &str) -> Option<Vec<String>> { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../e2e/lib/komorebi_vm/core/scenarios/commands.py"); + let source = std::fs::read_to_string(path).ok()?; + let start = source.find(&format!("{name}: tuple[str, ...] = ("))?; + let body = &source[start..]; + let end = body.find("\n)")?; + Some( + body[..end] + .lines() + .filter_map(|line| { + let line = line.trim(); + line.strip_prefix('"')? + .strip_suffix("\",") + .map(str::to_string) + }) + .collect(), + ) +} + +fn parses(cli: &clap::Command, line: &str) -> Result<(), String> { + let mut args = vec!["komorebic".to_string()]; + args.extend( + line.replace("{config}", "/tmp/komorebi.json") + .split_whitespace() + .map(str::to_string), + ); + cli.clone() + .try_get_matches_from(args) + .map(|_| ()) + .map_err(|e| e.to_string().lines().next().unwrap_or_default().to_string()) +} + +fn lines() -> Option<Vec<String>> { + let mut lines = tuple("SWEEP")?; + lines.extend(tuple("PRINTED")?); + Some(lines) +} + +#[test] +fn the_sweep_was_read() { + if let Some(lines) = lines() { + assert!(lines.len() > 200, "{} lines", lines.len()); + assert!(lines.iter().any(|l| l == "focus left")); + assert!(lines.iter().any(|l| l == "state")); + } +} + +#[test] +fn every_command_of_the_sweep_is_a_command_of_the_windows_komorebic() { + let Some(lines) = lines() else { return }; + let cli = command::<WindowsCommands>(&META); + let missing: Vec<_> = lines + .iter() + .filter_map(|l| parses(&cli, l).err().map(|e| format!("{l}: {e}"))) + .collect(); + assert!(missing.is_empty(), "{missing:#?}"); +} + +#[test] +fn the_sweep_commands_the_macos_komorebic_lacks_are_the_known_eight() { + let Some(lines) = lines() else { return }; + let cli = command::<MacosCommands>(&META); + let mut missing: Vec<_> = lines + .iter() + .filter_map(|l| parses(&cli, l).err().map(|_| l.clone())) + .collect(); + missing.sort(); + missing.dedup(); + // what the macOS command line lacks of the sweep, as of this writing: the scenario skips + // these there (focus follows mouse by the Windows implementation, transparency, maximize) + assert_eq!( + missing, + [ + "focus-follows-mouse disable", + "focus-follows-mouse enable", + "toggle-focus-follows-mouse --implementation windows", + "toggle-maximize", + "toggle-transparency", + "transparency disable", + "transparency enable", + "transparency-alpha 150", + ] + ); + // a command that every platform must have (the sweep's first lines) is one of macOS too + for line in [ + "focus left", + "move right", + "retile", + "toggle-float", + "state", + ] { + assert!(!missing.iter().any(|m| m == line), "{line}"); + } +} From e3c1702aa63927700ac79383af15723b518d8083 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 16:33:32 -0700 Subject: [PATCH 21/37] style(manifests): format six Cargo.toml files with taplo Pure formatting, no other change: taplo fmt (default configuration, taplo 0.10.0) over the manifests that the kfm toml-fmt check reported as not properly formatted: crates/komorebi-bar-core, crates/komorebi-protocol, komorebi-client, komorebi-daemon, komorebi-for-mac/komorebi and komorebi-for-mac/komorebic. The other 19 files that check lists were already clean. Effect on other platforms: the first four are Windows manifests and komorebi-protocol is also in the KDE closure. crane's dependency derivation contains the manifests, so the Windows and KDE dependency derivations and checks change once with this revision (one cold rebuild of the dependencies, then stable again). Verified: taplo fmt --check over the 25 files of the check passes after it (it failed on exactly these six before). --- crates/komorebi-bar-core/Cargo.toml | 8 +++++++- crates/komorebi-protocol/Cargo.toml | 6 +++++- komorebi-client/Cargo.toml | 6 +++++- komorebi-daemon/Cargo.toml | 12 ++++++++++-- komorebi-for-mac/komorebi/Cargo.toml | 23 ++++++++++++++++++----- komorebi-for-mac/komorebic/Cargo.toml | 4 +++- 6 files changed, 48 insertions(+), 11 deletions(-) diff --git a/crates/komorebi-bar-core/Cargo.toml b/crates/komorebi-bar-core/Cargo.toml index c788591e..cac9f4ed 100644 --- a/crates/komorebi-bar-core/Cargo.toml +++ b/crates/komorebi-bar-core/Cargo.toml @@ -28,4 +28,10 @@ schemars = { workspace = true, optional = true } [features] default = ["schemars"] -schemars = ["dep:schemars", "komorebi-config/schemars", "komorebi-layouts/schemars", "komorebi-themes/schemars", "komorebi-protocol/schemars"] +schemars = [ + "dep:schemars", + "komorebi-config/schemars", + "komorebi-layouts/schemars", + "komorebi-themes/schemars", + "komorebi-protocol/schemars", +] diff --git a/crates/komorebi-protocol/Cargo.toml b/crates/komorebi-protocol/Cargo.toml index 59f0505e..8f63b0b7 100644 --- a/crates/komorebi-protocol/Cargo.toml +++ b/crates/komorebi-protocol/Cargo.toml @@ -23,4 +23,8 @@ schemars = { workspace = true } [features] default = ["schemars"] -schemars = ["dep:schemars", "komorebi-layouts/schemars", "komorebi-themes/schemars"] +schemars = [ + "dep:schemars", + "komorebi-layouts/schemars", + "komorebi-themes/schemars", +] diff --git a/komorebi-client/Cargo.toml b/komorebi-client/Cargo.toml index 5b5e1a3b..dde7ede0 100644 --- a/komorebi-client/Cargo.toml +++ b/komorebi-client/Cargo.toml @@ -28,4 +28,8 @@ parking_lot = "0.13" [features] default = ["schemars"] -schemars = ["komorebi/default", "komorebi-linux/default", "komorebi-macos/default"] +schemars = [ + "komorebi/default", + "komorebi-linux/default", + "komorebi-macos/default", +] diff --git a/komorebi-daemon/Cargo.toml b/komorebi-daemon/Cargo.toml index af3e0063..8fd2f8e5 100644 --- a/komorebi-daemon/Cargo.toml +++ b/komorebi-daemon/Cargo.toml @@ -25,8 +25,16 @@ komorebi-macos = { package = "komorebi-macos", path = "../komorebi-for-mac/komor [features] default = ["schemars"] -deadlock_detection = ["komorebi-windows/deadlock_detection", "komorebi-linux/deadlock_detection", "komorebi-macos/deadlock_detection"] -schemars = ["komorebi-windows/schemars", "komorebi-linux/schemars", "komorebi-macos/schemars"] +deadlock_detection = [ + "komorebi-windows/deadlock_detection", + "komorebi-linux/deadlock_detection", + "komorebi-macos/deadlock_detection", +] +schemars = [ + "komorebi-windows/schemars", + "komorebi-linux/schemars", + "komorebi-macos/schemars", +] [target.'cfg(target_os = "linux")'.dev-dependencies] serde_json = { workspace = true } diff --git a/komorebi-for-mac/komorebi/Cargo.toml b/komorebi-for-mac/komorebi/Cargo.toml index bfb1ca57..8dba4ad2 100644 --- a/komorebi-for-mac/komorebi/Cargo.toml +++ b/komorebi-for-mac/komorebi/Cargo.toml @@ -9,10 +9,17 @@ komorebi-themes = { path = "../../komorebi-themes" } komorebi-backend = { path = "../../crates/komorebi-backend" } komorebi-collections = { path = "../../crates/komorebi-collections" } komorebi-core = { path = "../../crates/komorebi-core" } -komorebi-layouts = { path = "../../komorebi-layouts", features = ["darwin", "schemars"] } -komorebi-config = { path = "../../crates/komorebi-config", default-features = false, features = ["schemars"] } +komorebi-layouts = { path = "../../komorebi-layouts", features = [ + "darwin", + "schemars", +] } +komorebi-config = { path = "../../crates/komorebi-config", default-features = false, features = [ + "schemars", +] } komorebi-settings = { path = "../../crates/komorebi-settings" } -komorebi-protocol = { path = "../../crates/komorebi-protocol", default-features = false, features = ["schemars"] } +komorebi-protocol = { path = "../../crates/komorebi-protocol", default-features = false, features = [ + "schemars", +] } komorebi-transport = { path = "../../crates/komorebi-transport" } quickxml_to_serde = { git = "https://github.com/LGUG2Z/quickxml_to_serde.git", version = "0.6.1" } version = { package = "version-macos", path = "../version" } @@ -118,7 +125,9 @@ regex = "1" reqwest = { version = "0.12", features = ["blocking"] } schemars = { version = "1.1", optional = true } serde = { version = "1", features = ["derive"] } -serde_json = { package = "serde_json_lenient", version = "0.2", features = ["preserve_order"] } +serde_json = { package = "serde_json_lenient", version = "0.2", features = [ + "preserve_order", +] } serde_with = { version = "3", features = ["schemars_1"] } shadow-rs = { version = "1" } strum = { version = "0.28", features = ["derive"] } @@ -134,7 +143,11 @@ uuid = { version = "1", features = ["v4"] } [features] default = ["schemars"] deadlock_detection = ["parking_lot/deadlock_detection"] -schemars = ["dep:schemars", "komorebi-collections/schemars", "komorebi-core/schemars"] +schemars = [ + "dep:schemars", + "komorebi-collections/schemars", + "komorebi-core/schemars", +] [lib] name = "komorebi" diff --git a/komorebi-for-mac/komorebic/Cargo.toml b/komorebi-for-mac/komorebic/Cargo.toml index 0b351004..714b4c74 100644 --- a/komorebi-for-mac/komorebic/Cargo.toml +++ b/komorebi-for-mac/komorebic/Cargo.toml @@ -5,7 +5,9 @@ description = "The command-line interface for Komorebi, a tiling window manager edition = "2024" [dependencies] -komorebi-config = { path = "../../crates/komorebi-config", default-features = false, features = ["schemars"] } +komorebi-config = { path = "../../crates/komorebi-config", default-features = false, features = [ + "schemars", +] } komorebi-client = { package = "komorebi-client-macos", path = "../komorebi-client", default-features = false } komorebic-core = { path = "../../crates/komorebic-core" } version = { package = "version-macos", path = "../version" } From 27b36a457efb26bb2a41c6cf4a91ffa8072879dd Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:34:29 -0700 Subject: [PATCH 22/37] build(tools): add kde-closure-check and e2e-needed kde-closure-check fails when komorebi-for-kde/nix/root-crates.json differs from the KDE cargo closure; e2e-needed says whether a diff touches anything the Windows e2e binaries are built from. Copies of the host-side scripts with these differences only: - kde-closure-check: none (it already finds the repository relative to the script); verbatim. - e2e-needed: `tools/*` joins the paths that cannot change the binaries (docs, .github), so a change to the tools is NO instead of "not understood: treated as needed"; - e2e-needed: `# shellcheck disable=SC2001` before `set` (the sed one-liners indent multi-line output); no behaviour change. Verified: bash -n and shellcheck clean; `tools/kde-closure-check .` prints "ok: 11 root crates match the KDE cargo closure"; `tools/e2e-needed --since <rev>` gives the same output as the host copy on a range without tools/ files, and NO for a tools-only range. --- tools/e2e-needed | 97 +++++++++++++++++++++++++++++++++++++++++ tools/kde-closure-check | 26 +++++++++++ 2 files changed, 123 insertions(+) create mode 100755 tools/e2e-needed create mode 100755 tools/kde-closure-check diff --git a/tools/e2e-needed b/tools/e2e-needed new file mode 100755 index 00000000..41c36230 --- /dev/null +++ b/tools/e2e-needed @@ -0,0 +1,97 @@ +#!/usr/bin/env bash +# e2e-needed: does a diff touch anything the Windows e2e binaries are built from? +# e2e-needed [--range | --since REV] [--to REV] [--closure] (run in a jj workspace root) +# The Windows e2e runs komorebi.exe, komorebic.exe and komorebi-testwin.exe (flake e2eBuild). Their +# inputs are (a) the source directories of the workspace crates they depend on, from `cargo tree +# --target x86_64-pc-windows-msvc -e normal,build` (dev-dependencies are not in the binaries), +# (b) files pulled in with include_str!/include_bytes!/include! from those crates, (c) fixed +# inputs: Cargo.lock, the root Cargo.toml, rust-toolchain.toml, flake.nix, flake.lock, build +# scripts, and the e2e harness itself (e2e/). Anything else cannot change those binaries. +# Verdict NO means: every touched file is outside all of that, so a passing e2e of the previous +# binaries carries over unchanged. Verdict YES prints which files decided it. Files that are not +# understood count as YES. Uses `cargo tree --offline` (about 1-2 s, no build). Never writes. +# NOT covered by this verdict: the other gates (nextest, clippy, the bar screenshot, KDE VM, schema oracles). +# shellcheck disable=SC2001 # the sed one-liners indent multi-line output +set -uo pipefail +FROM=""; TO="@"; SHOWCL=0 +while [ $# -gt 0 ]; do + case "$1" in + --range) FROM='trunk()' ;; + --since) shift; FROM="${1:?--since needs a revset}" ;; + --to) shift; TO="${1:?--to needs a revset}" ;; + --closure) SHOWCL=1 ;; + -h|--help) sed -n '2,16p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "usage: e2e-needed [--range | --since REV] [--to REV] [--closure]" >&2; exit 2 ;; + esac + shift +done +ROOT="$(jj root 2>/dev/null)" || { echo "e2e-needed: not in a jj workspace" >&2; exit 2; } +cd "$ROOT" || exit 2 +if [ -n "$FROM" ]; then FILES="$(jj diff --name-only --from "$FROM" --to "$TO")"; else FILES="$(jj diff --name-only -r "$TO")"; fi +[ -n "$FILES" ] || { echo "NO (nothing changed in @; use --since REV)"; exit 0; } + +# (a) closure: workspace crate directories (relative to root) +CL="" +for p in komorebi komorebi-windows komorebic komorebi-testwin; do + CL+="$(CARGO_BUILD_JOBS=1 nice -n 19 cargo tree --offline --locked -p "$p" --target x86_64-pc-windows-msvc \ + --prefix none -e normal,build 2>/dev/null | grep -o "(${ROOT}[^)]*)" | tr -d '()' | sed "s#^${ROOT}/\{0,1\}##")"$'\n' +done +CL="$(echo "$CL" | sed '/^$/d' | sort -u)" +[ -n "$CL" ] || { echo "YES (could not compute the dependency closure: cargo tree failed; treating as needed)"; exit 0; } +[ $SHOWCL = 1 ] && { echo "closure directories:"; echo "$CL" | sed 's/^/ /'; } + +# (b) include!-ed files, resolved against the including file +INC="" +while IFS= read -r d; do + [ -d "$d" ] || continue + while IFS=: read -r f _ rest; do + rel="$(grep -o 'include[a-z_]*!("[^"]*")' <<<"$rest" | sed 's/.*("\(.*\)")/\1/')" + for r in $rel; do + case "$r" in /*) continue ;; esac + INC+="$(realpath -m --relative-to="$ROOT" "$(dirname "$f")/$r")"$'\n' + done + done < <(grep -rn 'include[a-z_]*!(' "$d" --include='*.rs' 2>/dev/null) +done <<<"$CL" +INC="$(echo "$INC" | sed '/^$/d' | sort -u)" +[ $SHOWCL = 1 ] && { echo "include-d files:"; echo "$INC" | sed 's/^/ /'; } + +yes=(); +while IFS= read -r f; do + [ -n "$f" ] || continue + reason="" + case "$f" in + Cargo.lock|Cargo.toml|rust-toolchain.toml|flake.nix|flake.lock) reason="fixed input" ;; + e2e/*) reason="e2e harness / guest" ;; + */build.rs) reason="build script" ;; + komorebi-for-kde/*|komorebi-for-mac/*) ;; # separate trees, not in the Windows closure + *.md|docs/*|tools/*|.github/*) ;; # docs and dev tools (include!-ed docs are caught below) + esac + if [ -z "$reason" ]; then + while IFS= read -r d; do + case "$f" in "$d"/*) reason="in closure crate $d"; break ;; esac + done <<<"$CL" + fi + if [ -z "$reason" ]; then + while IFS= read -r i; do + [ -n "$i" ] || continue + case "$f" in "$i"|"$i"/*) reason="include-d by a closure crate"; break ;; esac + done <<<"$INC" + fi + if [ -z "$reason" ]; then + case "$f" in + komorebi-for-kde/*|komorebi-for-mac/*|*.md|docs/*|tools/*|.github/*) ;; + komorebi-bar/*|komorebi-gui/*|komorebi-shortcuts/*|komorebic-no-console/*|crates/komorebi-bar-core/*|schema*.json|komorebic.lib.ahk|wix/*|justfile|mkdocs.yml|deny.toml|rustfmt.toml|*.json) + # known Windows-tree paths outside the closure (crates not in the closure were checked above) + case "$f" in */*.json|*.json) [ "$f" = dependencies.json ] || [ "${f#schema}" != "$f" ] || reason="json file outside known oracle files: treated as needed" ;; esac ;; + *) reason="not understood: treated as needed" ;; + esac + fi + [ -n "$reason" ] && yes+=("$f ($reason)") +done <<<"$FILES" +if [ ${#yes[@]} -eq 0 ]; then + echo "NO: none of $(echo "$FILES" | wc -l) touched files is an input of komorebi.exe, komorebic.exe or komorebi-testwin.exe" +else + echo "YES: ${#yes[@]} touched file(s) are inputs of the e2e binaries or the harness:" + printf ' %s\n' "${yes[@]}" | head -15 + [ ${#yes[@]} -gt 15 ] && echo " ... and $(( ${#yes[@]} - 15 )) more" +fi diff --git a/tools/kde-closure-check b/tools/kde-closure-check new file mode 100755 index 00000000..87ec0d1b --- /dev/null +++ b/tools/kde-closure-check @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Fails if the crates outside komorebi-for-kde that the KDE packages depend on differ from the list the KDE +# source filter uses (komorebi-for-kde/nix/root-crates.json). +# Usage: tools/kde-closure-check [REPO_ROOT] (default: the repository this script is in) +# Works for the merged workspace (one root Cargo.toml) and for the old KDE workspace. +set -euo pipefail +root=$(cd "${1:-$(dirname "$0")/..}" && pwd) +[ -d "$root/komorebi-for-kde" ] || root=$(cd "$root/.." && pwd) +want=$(jq -r '.[]' "$root/komorebi-for-kde/nix/root-crates.json" | sort) +if [ -f "$root/komorebi-for-kde/Cargo.toml" ]; then + have=$(cd "$root/komorebi-for-kde" && nice -n 19 cargo metadata --offline --format-version 1 \ + | jq -r --arg r "$root/" '.packages[] | select(.source == null) | .manifest_path + | select(startswith($r) and (startswith($r + "komorebi-for-kde/") | not)) + | ltrimstr($r) | sub("/Cargo.toml$"; "")' | sort) +else + # merged workspace: the closure of the KDE packages on a Linux target + have=$(cd "$root" && for p in komorebi-linux komorebic-linux komorebi-client-linux komorebi-hotkeys; do + nice -n 19 cargo tree --offline --locked -p "$p" --target x86_64-unknown-linux-gnu --prefix none -e normal,build,dev 2>/dev/null + done | grep -o "($root/[^)]*)" | tr -d '()' | sed "s#^$root/##" | grep -v '^komorebi-for-kde' | sort -u) +fi +if [ "$want" != "$have" ]; then + echo "KDE source filter and cargo closure differ" >&2 + diff <(echo "$want") <(echo "$have") | sed 's/^</ only in root-crates.json:/; s/^>/ only in cargo closure: /' >&2 + exit 1 +fi +echo "ok: $(echo "$want" | wc -l) root crates match the KDE cargo closure" From 482c42d64f1fb5a5888ccb1eda5489e0b6f452f5 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:41:11 -0700 Subject: [PATCH 23/37] refactor(windows): move the animation settings to settings Plan step 10, S5 for Windows. The six ANIMATION_* statics (global enabled, style, duration; per-kind enabled, style, duration) and ANIMATION_FPS are gone (ANIMATION_MANAGER and GHOST_MOVEMENT_ENABLED stay: runtime state and a Windows-only setting). The Animation, AnimationDuration, AnimationFps and AnimationStyle commands each write settings().shared.animation with one update; the animation block of a load is one update through SharedDelta::apply (a global value clears that setting's per-kind map, a map replaces it, a block without fps has the default, no block keeps all); shutdown (daemon.rs, window_manager.rs) is animation_off_for_good(), one update that clears the per-kind map and turns the global flag off. Readers keep Windows' own rules, which are NOT the KDE and macOS ones: a kind is animated when the global flag is on OR its per-kind value is true (a per-kind false does not turn off a global true), and the workspace transition helpers keep their per-kind-wins rule; the accessors in settings.rs (animation_enabled_for, animation_for) encode the first and the existing transitions_enabled_by / duration_for / style_for are fed from one snapshot. Window::move/transparent/opaque and the maximize wait read enabled, duration and style from one snapshot, and no longer hold the per-kind map's lock for the rest of the function. BEHAVIOUR: no thread can see half an animation reload; one publish per load or command. Gate: Windows e2e (animation, config_reload, lifecycle for the shutdown path, commands). Verified: Windows clippy -D warnings --locked --all-targets on komorebi-windows (cross): clean. e2e not run. --- komorebi/src/animation/engine.rs | 7 +-- komorebi/src/animation/mod.rs | 35 ++++++------- komorebi/src/daemon.rs | 5 +- komorebi/src/live_resize.rs | 3 +- komorebi/src/process_command.rs | 85 +++++++++++++++++--------------- komorebi/src/scrolling.rs | 9 +--- komorebi/src/settings.rs | 67 +++++++++++++++++++++++++ komorebi/src/static_config.rs | 59 ++++++---------------- komorebi/src/window.rs | 68 +++---------------------- komorebi/src/window_manager.rs | 5 +- 10 files changed, 153 insertions(+), 190 deletions(-) diff --git a/komorebi/src/animation/engine.rs b/komorebi/src/animation/engine.rs index 98093c74..ce4c3182 100644 --- a/komorebi/src/animation/engine.rs +++ b/komorebi/src/animation/engine.rs @@ -3,12 +3,9 @@ use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; use std::cell::RefCell; -use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; -use super::ANIMATION_DURATION_GLOBAL; -use super::ANIMATION_FPS; use super::ANIMATION_MANAGER; use super::RenderDispatcher; @@ -32,7 +29,7 @@ impl AnimationEngine { } std::thread::sleep(Duration::from_millis( - ANIMATION_DURATION_GLOBAL.load(Ordering::SeqCst), + crate::settings::animation_duration_global(), )); } } @@ -135,7 +132,7 @@ impl AnimationEngine { } let target_frame_time = - Duration::from_millis(1000 / ANIMATION_FPS.load(Ordering::Relaxed)); + Duration::from_millis(1000 / crate::settings::animation_fps()); let animation_start = Instant::now(); let mut stats = FrameStats::default(); diff --git a/komorebi/src/animation/mod.rs b/komorebi/src/animation/mod.rs index abd27466..047c802d 100644 --- a/komorebi/src/animation/mod.rs +++ b/komorebi/src/animation/mod.rs @@ -6,7 +6,6 @@ use prefix::AnimationPrefix; use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use std::time::Duration; @@ -35,18 +34,6 @@ pub const DEFAULT_GHOST_MOVEMENT: bool = false; lazy_static! { pub static ref ANIMATION_MANAGER: Arc<Mutex<AnimationManager>> = Arc::new(Mutex::new(AnimationManager::new())); - pub static ref ANIMATION_STYLE_GLOBAL: Arc<Mutex<AnimationStyle>> = - Arc::new(Mutex::new(DEFAULT_ANIMATION_STYLE)); - pub static ref ANIMATION_ENABLED_GLOBAL: Arc<AtomicBool> = - Arc::new(AtomicBool::new(DEFAULT_ANIMATION_ENABLED)); - pub static ref ANIMATION_DURATION_GLOBAL: Arc<AtomicU64> = - Arc::new(AtomicU64::new(DEFAULT_ANIMATION_DURATION)); - pub static ref ANIMATION_STYLE_PER_ANIMATION: Arc<Mutex<HashMap<AnimationPrefix, AnimationStyle>>> = - Arc::new(Mutex::new(HashMap::new())); - pub static ref ANIMATION_ENABLED_PER_ANIMATION: Arc<Mutex<HashMap<AnimationPrefix, bool>>> = - Arc::new(Mutex::new(HashMap::new())); - pub static ref ANIMATION_DURATION_PER_ANIMATION: Arc<Mutex<HashMap<AnimationPrefix, u64>>> = - Arc::new(Mutex::new(HashMap::new())); } /// Whether the windows of a workspace slide out of a monitor and those of the @@ -87,32 +74,40 @@ fn style_for( /// Whether workspaces slide in and out of the monitor when they are switched pub fn workspace_transitions_enabled() -> bool { + let snapshot = crate::settings::settings().snapshot(); + let animation = &snapshot.shared.animation; + transitions_enabled_by( GHOST_MOVEMENT_ENABLED.load(Ordering::Relaxed), - ANIMATION_ENABLED_GLOBAL.load(Ordering::SeqCst), - &ANIMATION_ENABLED_PER_ANIMATION.lock(), + animation.enabled, + &animation.enabled_per_animation, ) } /// How long a workspace takes to slide in and out of a monitor pub fn workspace_transition_duration() -> Duration { + let snapshot = crate::settings::settings().snapshot(); + let animation = &snapshot.shared.animation; + duration_for( AnimationPrefix::Workspace, - &ANIMATION_DURATION_PER_ANIMATION.lock(), - ANIMATION_DURATION_GLOBAL.load(Ordering::SeqCst), + &animation.duration_per_animation, + animation.duration, ) } /// How a workspace eases as it slides in and out of a monitor pub fn workspace_transition_style() -> AnimationStyle { + let snapshot = crate::settings::settings().snapshot(); + let animation = &snapshot.shared.animation; + style_for( AnimationPrefix::Workspace, - &ANIMATION_STYLE_PER_ANIMATION.lock(), - *ANIMATION_STYLE_GLOBAL.lock(), + &animation.style_per_animation, + animation.style, ) } -pub static ANIMATION_FPS: AtomicU64 = AtomicU64::new(DEFAULT_ANIMATION_FPS); pub static GHOST_MOVEMENT_ENABLED: AtomicBool = AtomicBool::new(DEFAULT_GHOST_MOVEMENT); #[cfg(test)] diff --git a/komorebi/src/daemon.rs b/komorebi/src/daemon.rs index 4690106f..81ad851c 100644 --- a/komorebi/src/daemon.rs +++ b/komorebi/src/daemon.rs @@ -20,8 +20,6 @@ use clap::ValueEnum; use color_eyre::eyre; use color_eyre::eyre::bail; use crossbeam_utils::Backoff; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; use crate::animation::AnimationEngine; use crate::replace_env_in_path; use parking_lot::Mutex; @@ -364,8 +362,7 @@ pub fn run() -> eyre::Result<()> { let state = State::from(&*wm.lock()); std::fs::write(dumped_state, serde_json::to_string_pretty(&state)?)?; - ANIMATION_ENABLED_PER_ANIMATION.lock().clear(); - ANIMATION_ENABLED_GLOBAL.store(false, Ordering::SeqCst); + crate::settings::animation_off_for_good(); wm.lock().restore_all_windows(false)?; AnimationEngine::wait_for_all_animations(); diff --git a/komorebi/src/live_resize.rs b/komorebi/src/live_resize.rs index 7b3377e6..66e54bf8 100644 --- a/komorebi/src/live_resize.rs +++ b/komorebi/src/live_resize.rs @@ -14,7 +14,6 @@ //! it began puts the neighbours back. use crate::WindowsApi; -use crate::animation::ANIMATION_DURATION_GLOBAL; use crate::animation::GHOST_MOVEMENT_ENABLED; use crate::animation::ghost::GhostWindow; use crate::animation::ghost::is_swap_chain_window; @@ -368,7 +367,7 @@ fn glide_frame(from: &Rect, to: &Rect, progress: f64) -> Rect { /// long as an animation takes, and nothing else is done until they are there. For the windows /// of a strip that is let go of, which then does not jump to where it comes to rest. pub fn glide() { - let duration = Duration::from_millis(ANIMATION_DURATION_GLOBAL.load(Ordering::SeqCst)); + let duration = Duration::from_millis(crate::settings::animation_duration_global()); let mut covers = COVERS.lock(); let Some(covers) = covers.as_mut() else { diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 3848d75f..ffa6db6d 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -47,13 +47,6 @@ use crate::TCP_CONNECTIONS; use crate::TRAY_AND_MULTI_WINDOW_IDENTIFIERS; use crate::WINDOWS_11; use crate::WORKSPACE_MATCHING_RULES; -use crate::animation::ANIMATION_DURATION_GLOBAL; -use crate::animation::ANIMATION_DURATION_PER_ANIMATION; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; -use crate::animation::ANIMATION_FPS; -use crate::animation::ANIMATION_STYLE_GLOBAL; -use crate::animation::ANIMATION_STYLE_PER_ANIMATION; use crate::border_manager; use crate::border_manager::IMPLEMENTATION; use crate::border_manager::STYLE; @@ -1399,41 +1392,51 @@ impl WindowManager { border_manager::BORDER_OFFSET.store(offset, Ordering::SeqCst); force_update_borders = true; } - SocketMessage::Animation(enable, prefix) => match prefix { - Some(prefix) => { - ANIMATION_ENABLED_PER_ANIMATION - .lock() - .insert(prefix, enable); - } - None => { - ANIMATION_ENABLED_GLOBAL.store(enable, Ordering::SeqCst); - ANIMATION_ENABLED_PER_ANIMATION.lock().clear(); - } - }, - SocketMessage::AnimationDuration(duration, prefix) => match prefix { - Some(prefix) => { - ANIMATION_DURATION_PER_ANIMATION - .lock() - .insert(prefix, duration); - } - None => { - ANIMATION_DURATION_GLOBAL.store(duration, Ordering::SeqCst); - ANIMATION_DURATION_PER_ANIMATION.lock().clear(); - } - }, - SocketMessage::AnimationFps(fps) => { - ANIMATION_FPS.store(fps, Ordering::SeqCst); + SocketMessage::Animation(enable, prefix) => { + crate::settings::settings().update(|settings| { + let animation = &mut settings.shared.animation; + match prefix { + Some(prefix) => { + animation.enabled_per_animation.insert(prefix, enable); + } + None => { + animation.enabled = enable; + animation.enabled_per_animation.clear(); + } + } + }); + } + SocketMessage::AnimationDuration(duration, prefix) => { + crate::settings::settings().update(|settings| { + let animation = &mut settings.shared.animation; + match prefix { + Some(prefix) => { + animation.duration_per_animation.insert(prefix, duration); + } + None => { + animation.duration = duration; + animation.duration_per_animation.clear(); + } + } + }); + } + SocketMessage::AnimationFps(fps) => { + crate::settings::settings().update(|settings| settings.shared.animation.fps = fps); + } + SocketMessage::AnimationStyle(style, prefix) => { + crate::settings::settings().update(|settings| { + let animation = &mut settings.shared.animation; + match prefix { + Some(prefix) => { + animation.style_per_animation.insert(prefix, style); + } + None => { + animation.style = style; + animation.style_per_animation.clear(); + } + } + }); } - SocketMessage::AnimationStyle(style, prefix) => match prefix { - Some(prefix) => { - ANIMATION_STYLE_PER_ANIMATION.lock().insert(prefix, style); - } - None => { - let mut animation_style = ANIMATION_STYLE_GLOBAL.lock(); - *animation_style = style; - ANIMATION_STYLE_PER_ANIMATION.lock().clear(); - } - }, SocketMessage::ToggleTransparency => { crate::settings::settings().update(|settings| { settings.shared.transparency.enabled = !settings.shared.transparency.enabled; diff --git a/komorebi/src/scrolling.rs b/komorebi/src/scrolling.rs index 8f8bdd89..cf0d39e5 100644 --- a/komorebi/src/scrolling.rs +++ b/komorebi/src/scrolling.rs @@ -5,8 +5,6 @@ //! [`Workspace`]: a container is a tile in the strip, and is known to it by its id. use crate::WINDOW_HANDLING_BEHAVIOUR; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; use crate::animation::ANIMATION_MANAGER; use crate::animation::prefix::AnimationPrefix; use crate::container::Container; @@ -26,7 +24,6 @@ use komorebi_scrolling::ColumnWidth; use komorebi_scrolling::Options; use komorebi_scrolling::ScrollingSpace; use komorebi_scrolling::Visibility; -use std::sync::atomic::Ordering; /// What the layout options of a workspace come to for the model. pub(crate) fn scrolling_options(layout_options: Option<LayoutOptions>) -> Options { @@ -159,11 +156,7 @@ pub(crate) fn should_restore_when_placed( /// Whether windows that are moved are animated to where they go. pub(crate) fn animations_enabled() -> bool { - ANIMATION_ENABLED_GLOBAL.load(Ordering::SeqCst) - || ANIMATION_ENABLED_PER_ANIMATION - .lock() - .get(&AnimationPrefix::Movement) - .is_some_and(|enabled| *enabled) + crate::settings::animation_enabled_for(AnimationPrefix::Movement) } pub(crate) trait WorkspaceScrolling { diff --git a/komorebi/src/settings.rs b/komorebi/src/settings.rs index 9664abb8..1fd67857 100644 --- a/komorebi/src/settings.rs +++ b/komorebi/src/settings.rs @@ -7,6 +7,10 @@ use std::collections::HashMap; use std::sync::LazyLock; +use std::time::Duration; + +use crate::animation::prefix::AnimationPrefix; +use crate::core::animation::AnimationStyle; use komorebi_config::aspect_ratio::AspectRatio; use komorebi_layouts::DefaultLayout; @@ -77,6 +81,69 @@ pub fn transparency_alpha() -> u8 { settings().snapshot().shared.transparency.alpha } +// The animation settings. Windows decides whether a kind of animation is on as: the global flag, or +// a per-kind value of true (a per-kind false does NOT turn off a global true, unlike KDE and macOS). + +/// Whether `prefix` is animated: the global flag, or a per-kind true. +pub fn animation_enabled_for(prefix: AnimationPrefix) -> bool { + let snapshot = settings().snapshot(); + let animation = &snapshot.shared.animation; + + animation.enabled + || animation + .enabled_per_animation + .get(&prefix) + .is_some_and(|enabled| *enabled) +} + +/// How `prefix` is animated, from one snapshot, or `None` if it is not (see [`animation_enabled_for`]). +pub fn animation_for(prefix: AnimationPrefix) -> Option<(Duration, AnimationStyle)> { + let snapshot = settings().snapshot(); + let animation = &snapshot.shared.animation; + + let enabled = animation.enabled + || animation + .enabled_per_animation + .get(&prefix) + .is_some_and(|enabled| *enabled); + + enabled.then(|| { + ( + Duration::from_millis( + animation + .duration_per_animation + .get(&prefix) + .copied() + .unwrap_or(animation.duration), + ), + animation + .style_per_animation + .get(&prefix) + .copied() + .unwrap_or(animation.style), + ) + }) +} + +/// `animation.fps`. +pub fn animation_fps() -> u64 { + settings().snapshot().shared.animation.fps +} + +/// The global `animation.duration`, in milliseconds. +pub fn animation_duration_global() -> u64 { + settings().snapshot().shared.animation.duration +} + +/// Turns every animation off for good (the global flag and the per-kind values): what shutdown does +/// before it puts the windows back. +pub fn animation_off_for_good() { + settings().update(|settings| { + settings.shared.animation.enabled_per_animation.clear(); + settings.shared.animation.enabled = false; + }); +} + #[cfg(test)] mod tests { use std::sync::atomic::Ordering; diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index dfbb2888..89fd6dc2 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -21,17 +21,8 @@ use crate::TRAY_AND_MULTI_WINDOW_IDENTIFIERS; use crate::WINDOW_HANDLING_BEHAVIOUR; use crate::WINDOWS_11; use crate::WORKSPACE_MATCHING_RULES; -use crate::animation::ANIMATION_DURATION_GLOBAL; -use crate::animation::ANIMATION_DURATION_PER_ANIMATION; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; -use crate::animation::ANIMATION_FPS; -use crate::animation::ANIMATION_STYLE_GLOBAL; -use crate::animation::ANIMATION_STYLE_PER_ANIMATION; -use crate::animation::DEFAULT_ANIMATION_FPS; use crate::animation::DEFAULT_GHOST_MOVEMENT; use crate::animation::GHOST_MOVEMENT_ENABLED; -use crate::animation::PerAnimationPrefixConfig; use crate::asc::ApplicationSpecificConfiguration; use crate::asc::AscApplicationRulesOrSchema; use crate::border_manager; @@ -78,6 +69,7 @@ use color_eyre::eyre; use crossbeam_channel::Receiver; use hotwatch::EventKind; use hotwatch::Hotwatch; +use komorebi_settings::shared::AnimationDelta; use komorebi_settings::shared::SharedDelta; use komorebi_themes::colour::Colour; use parking_lot::Mutex; @@ -425,43 +417,20 @@ impl ApplyGlobals for StaticConfig { } if let Some(animations) = &self.animation { - match &animations.enabled { - PerAnimationPrefixConfig::Prefix(enabled) => { - ANIMATION_ENABLED_PER_ANIMATION.lock().clone_from(enabled); + // enabled, style, duration and fps as one update: a global value clears its per-animation + // map, a map replaces the map, a block without `fps` has the default (`SharedDelta::apply`) + crate::settings::settings().update(|settings| { + SharedDelta { + animation: Some(AnimationDelta { + enabled: animations.enabled.clone(), + style: animations.style.clone(), + duration: animations.duration.clone(), + fps: animations.fps, + }), + ..SharedDelta::default() } - PerAnimationPrefixConfig::Global(enabled) => { - ANIMATION_ENABLED_GLOBAL.store(*enabled, Ordering::SeqCst); - ANIMATION_ENABLED_PER_ANIMATION.lock().clear(); - } - } - - match &animations.style { - Some(PerAnimationPrefixConfig::Prefix(style)) => { - ANIMATION_STYLE_PER_ANIMATION.lock().clone_from(style); - } - Some(PerAnimationPrefixConfig::Global(style)) => { - let mut animation_style = ANIMATION_STYLE_GLOBAL.lock(); - *animation_style = *style; - ANIMATION_STYLE_PER_ANIMATION.lock().clear(); - } - None => {} - } - - match &animations.duration { - Some(PerAnimationPrefixConfig::Prefix(duration)) => { - ANIMATION_DURATION_PER_ANIMATION.lock().clone_from(duration); - } - Some(PerAnimationPrefixConfig::Global(duration)) => { - ANIMATION_DURATION_GLOBAL.store(*duration, Ordering::SeqCst); - ANIMATION_DURATION_PER_ANIMATION.lock().clear(); - } - None => {} - } - - ANIMATION_FPS.store( - animations.fps.unwrap_or(DEFAULT_ANIMATION_FPS), - Ordering::SeqCst, - ); + .apply(&mut settings.shared); + }); let ghost_movement_enabled = animations.ghost_movement.unwrap_or(DEFAULT_GHOST_MOVEMENT); diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index aabebb0e..3c1a7a13 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -11,13 +11,7 @@ use crate::REGEX_IDENTIFIERS; use crate::SLOW_APPLICATION_COMPENSATION_TIME; use crate::SLOW_APPLICATION_IDENTIFIERS; use crate::WSL2_UI_PROCESSES; -use crate::animation::ANIMATION_DURATION_GLOBAL; -use crate::animation::ANIMATION_DURATION_PER_ANIMATION; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; use crate::animation::ANIMATION_MANAGER; -use crate::animation::ANIMATION_STYLE_GLOBAL; -use crate::animation::ANIMATION_STYLE_PER_ANIMATION; use crate::animation::AnimationEngine; use crate::animation::RenderDispatcher; use crate::animation::ghost_dispatcher::GhostDispatcher; @@ -273,13 +267,7 @@ impl Window { let is_maximized = &new_rect == target_area; if is_maximized { windows_api::WindowsApi::unmaximize_window(self.hwnd); - let animation_enabled = ANIMATION_ENABLED_PER_ANIMATION.lock(); - let move_enabled = animation_enabled - .get(&GhostDispatcher::PREFIX) - .is_some_and(|v| *v); - drop(animation_enabled); - - if move_enabled || ANIMATION_ENABLED_GLOBAL.load(Ordering::SeqCst) { + if crate::settings::animation_enabled_for(GhostDispatcher::PREFIX) { let anim_count = ANIMATION_MANAGER .lock() .count_in_progress(GhostDispatcher::PREFIX); @@ -414,22 +402,8 @@ impl Window { return WindowsApi::position_window(self.hwnd, layout, top, true); } - let animation_enabled = ANIMATION_ENABLED_PER_ANIMATION.lock(); - let move_enabled = animation_enabled.get(&GhostDispatcher::PREFIX); - - if move_enabled.is_some_and(|enabled| *enabled) - || ANIMATION_ENABLED_GLOBAL.load(Ordering::SeqCst) - { - let duration = Duration::from_millis( - *ANIMATION_DURATION_PER_ANIMATION - .lock() - .get(&GhostDispatcher::PREFIX) - .unwrap_or(&ANIMATION_DURATION_GLOBAL.load(Ordering::SeqCst)), - ); - let style = *ANIMATION_STYLE_PER_ANIMATION - .lock() - .get(&GhostDispatcher::PREFIX) - .unwrap_or(&ANIMATION_STYLE_GLOBAL.lock()); + // enabled, duration and style from one snapshot + if let Some((duration, style)) = crate::settings::animation_for(GhostDispatcher::PREFIX) { let render_dispatcher = GhostDispatcher::new(self.hwnd, window_rect, *layout, top, style); @@ -610,22 +584,8 @@ impl Window { } pub fn transparent(self) -> eyre::Result<()> { - let animation_enabled = ANIMATION_ENABLED_PER_ANIMATION.lock(); - let transparent_enabled = animation_enabled.get(&TransparencyRenderDispatcher::PREFIX); - - if transparent_enabled.is_some_and(|enabled| *enabled) - || ANIMATION_ENABLED_GLOBAL.load(Ordering::SeqCst) - { - let duration = Duration::from_millis( - *ANIMATION_DURATION_PER_ANIMATION - .lock() - .get(&TransparencyRenderDispatcher::PREFIX) - .unwrap_or(&ANIMATION_DURATION_GLOBAL.load(Ordering::SeqCst)), - ); - let style = *ANIMATION_STYLE_PER_ANIMATION - .lock() - .get(&TransparencyRenderDispatcher::PREFIX) - .unwrap_or(&ANIMATION_STYLE_GLOBAL.lock()); + // enabled, duration and style from one snapshot + if let Some((duration, style)) = crate::settings::animation_for(TransparencyRenderDispatcher::PREFIX) { let render_dispatcher = TransparencyRenderDispatcher::new( self.hwnd, @@ -648,22 +608,8 @@ impl Window { } pub fn opaque(self) -> eyre::Result<()> { - let animation_enabled = ANIMATION_ENABLED_PER_ANIMATION.lock(); - let transparent_enabled = animation_enabled.get(&TransparencyRenderDispatcher::PREFIX); - - if transparent_enabled.is_some_and(|enabled| *enabled) - || ANIMATION_ENABLED_GLOBAL.load(Ordering::SeqCst) - { - let duration = Duration::from_millis( - *ANIMATION_DURATION_PER_ANIMATION - .lock() - .get(&TransparencyRenderDispatcher::PREFIX) - .unwrap_or(&ANIMATION_DURATION_GLOBAL.load(Ordering::SeqCst)), - ); - let style = *ANIMATION_STYLE_PER_ANIMATION - .lock() - .get(&TransparencyRenderDispatcher::PREFIX) - .unwrap_or(&ANIMATION_STYLE_GLOBAL.lock()); + // enabled, duration and style from one snapshot + if let Some((duration, style)) = crate::settings::animation_for(TransparencyRenderDispatcher::PREFIX) { let render_dispatcher = TransparencyRenderDispatcher::new( self.hwnd, diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 874d0af1..572d06ee 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -26,8 +26,6 @@ use uds_windows::UnixStream; use crate::HIDING_BEHAVIOUR; use crate::HidingBehaviour; -use crate::animation::ANIMATION_ENABLED_GLOBAL; -use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; use crate::animation::AnimationEngine; use crate::animation::engine::AnimationBatch; use crate::animation::transition; @@ -1452,8 +1450,7 @@ impl WindowManager { serde_json::to_string_pretty(&state)?, )?; - ANIMATION_ENABLED_PER_ANIMATION.lock().clear(); - ANIMATION_ENABLED_GLOBAL.store(false, Ordering::SeqCst); + crate::settings::animation_off_for_good(); self.restore_all_windows(ignore_restore)?; AnimationEngine::wait_for_all_animations(); From 4836a39b1c03a69f9b267a7a4e03b6f42cb48764 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:43:59 -0700 Subject: [PATCH 24/37] refactor(mac): ToggleWorkspaceWindowContainerBehaviour calls the named method KDE has The arm was the same code inline as toggle_workspace_window_container_behaviour on KDE (the two differ only in how rustfmt wrapped the match arms). The macOS arm calls a method with that name and body. No behaviour change. Verified: fake-CC cargo clippy -p komorebi-macos ... --all-targets -D warnings: PASS (type-check only). Not run: the macOS tests (the Mac Mini). --- .../komorebi/src/process_command.rs | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index 8415a1f3..3d225663 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -113,6 +113,24 @@ impl CommandTarget for WindowManager { } impl WindowManager { + /// Switches the focused workspace between creating a container for a new window and adding it to the focused one + pub fn toggle_workspace_window_container_behaviour(&mut self) -> eyre::Result<()> { + let current_global_behaviour = self.window_management_behaviour.current_behaviour; + if let Some(behaviour) = &mut self.focused_workspace_mut()?.window_container_behaviour { + match behaviour { + WindowContainerBehaviour::Create => *behaviour = WindowContainerBehaviour::Append, + WindowContainerBehaviour::Append => *behaviour = WindowContainerBehaviour::Create, + } + } else { + self.focused_workspace_mut()?.window_container_behaviour = + Some(match current_global_behaviour { + WindowContainerBehaviour::Create => WindowContainerBehaviour::Append, + WindowContainerBehaviour::Append => WindowContainerBehaviour::Create, + }); + }; + Ok(()) + } + /// Sets the column and row ratios of the focused workspace's layout pub fn set_layout_ratios( &mut self, @@ -1008,25 +1026,7 @@ impl WindowManager { SocketMessage::Retile => self.retile_all(false)?, SocketMessage::RetileWithResizeDimensions => self.retile_all(true)?, SocketMessage::ToggleWorkspaceWindowContainerBehaviour => { - let current_global_behaviour = self.window_management_behaviour.current_behaviour; - if let Some(behaviour) = - &mut self.focused_workspace_mut()?.window_container_behaviour - { - match behaviour { - WindowContainerBehaviour::Create => { - *behaviour = WindowContainerBehaviour::Append - } - WindowContainerBehaviour::Append => { - *behaviour = WindowContainerBehaviour::Create - } - } - } else { - self.focused_workspace_mut()?.window_container_behaviour = - Some(match current_global_behaviour { - WindowContainerBehaviour::Create => WindowContainerBehaviour::Append, - WindowContainerBehaviour::Append => WindowContainerBehaviour::Create, - }); - }; + self.toggle_workspace_window_container_behaviour()? } SocketMessage::ToggleWorkspaceFloatOverride => { let current_global_override = self.window_management_behaviour.float_override; From d7673d436fad7dd7334402a69e257defb3792c80 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:39:52 -0700 Subject: [PATCH 25/37] fix(bar): the update widget asks the platform for its release URLs The update widget's refresh thread polled the Windows repository's GitHub API on every platform (a hard-coded second URL, while the first fetch went through BarPlatform::latest_release_api_url), and the page the click opens was built for the Windows repository, so on macOS the widget compared the mac version against Windows releases after the first refresh and linked to the wrong project. The refresh now uses latest_release_api_url, and a new BarPlatform::release_page_url(version) builds the click target: Windows keeps https://github.com/LGUG2Z/komorebi/releases/v{version} exactly, macOS gets https://github.com/LGUG2Z/komorebi-for-mac/releases/tag/v{version}. BEHAVIOUR (macOS): the update widget compares against and links to the komorebi-for-mac releases. Windows output is unchanged (same URLs). Gate: macOS hand-check (see docs/dev/macos-handcheck.md); Windows needs no e2e. Verified: see the following revisions' fast-check results; not run on a Mac. --- crates/komorebi-bar-core/src/platform.rs | 3 +++ crates/komorebi-bar-core/src/widgets/update.rs | 9 ++++----- komorebi-bar/src/macos/os.rs | 4 ++++ komorebi-bar/src/windows/os.rs | 4 ++++ 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/komorebi-bar-core/src/platform.rs b/crates/komorebi-bar-core/src/platform.rs index c7c2316e..7117872d 100644 --- a/crates/komorebi-bar-core/src/platform.rs +++ b/crates/komorebi-bar-core/src/platform.rs @@ -31,6 +31,9 @@ pub trait BarPlatform: Send + Sync { /// The GitHub API URL that says which release of this platform's komorebi is the latest. fn latest_release_api_url(&self) -> &'static str; + /// The page of this platform's release `version` that the update widget opens when clicked. + fn release_page_url(&self, version: &str) -> String; + /// The icon of the program a command string would start (Windows: the executable's icon; /// macOS: none). fn command_icon(&self, command: &str) -> Option<ImageIcon>; diff --git a/crates/komorebi-bar-core/src/widgets/update.rs b/crates/komorebi-bar-core/src/widgets/update.rs index 04c068ea..c7bd51be 100644 --- a/crates/komorebi-bar-core/src/widgets/update.rs +++ b/crates/komorebi-bar-core/src/widgets/update.rs @@ -83,7 +83,7 @@ impl Update { { let client = reqwest::blocking::Client::new(); if let Ok(response) = client - .get("https://api.github.com/repos/LGUG2Z/komorebi/releases/latest") + .get(platform().latest_release_api_url()) .header("User-Agent", "komorebi-bar-version-checker") .send() { @@ -143,10 +143,9 @@ impl BarWidget for Update { if SelectableFrame::new(false) .show(ui, |ui| ui.add(Label::new(layout_job).selectable(false))) .clicked() - && let Err(error) = platform().open_system_tool(SystemTool::Url(format!( - "https://github.com/LGUG2Z/komorebi/releases/v{}", - self.latest_version - ))) + && let Err(error) = platform().open_system_tool(SystemTool::Url( + platform().release_page_url(&self.latest_version), + )) { eprintln!("{error}") } diff --git a/komorebi-bar/src/macos/os.rs b/komorebi-bar/src/macos/os.rs index 3275456e..dbab39cd 100644 --- a/komorebi-bar/src/macos/os.rs +++ b/komorebi-bar/src/macos/os.rs @@ -37,6 +37,10 @@ impl BarPlatform for MacBar { "https://api.github.com/repos/LGUG2Z/komorebi-for-mac/releases/latest" } + fn release_page_url(&self, version: &str) -> String { + format!("https://github.com/LGUG2Z/komorebi-for-mac/releases/tag/v{version}") + } + fn calendar_icon(&self) -> &'static str { CALENDAR } diff --git a/komorebi-bar/src/windows/os.rs b/komorebi-bar/src/windows/os.rs index 5ba8990c..ed41c03f 100644 --- a/komorebi-bar/src/windows/os.rs +++ b/komorebi-bar/src/windows/os.rs @@ -35,6 +35,10 @@ impl BarPlatform for WindowsBar { "https://api.github.com/repos/LGUG2Z/komorebi/releases/latest" } + fn release_page_url(&self, version: &str) -> String { + format!("https://github.com/LGUG2Z/komorebi/releases/v{version}") + } + fn calendar_icon(&self) -> &'static str { CALENDAR_DOTS } From 231e50b3fccd1a519f51e77442b2225699c66eab Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 17:15:39 -0700 Subject: [PATCH 26/37] test(core): tiling arithmetic of update_shared as native checks of the e2e layouts The Windows e2e scenarios layouts (111 checks), flipping, layout_flip, padding, closing, minimizing, floating, stacks, tiling and tiling_off assert where the tiles of a workspace are. Since the consolidation every daemon gets those tiles from komorebi-core's Workspace::update_shared, so they can be checked on the stub platform on Linux (and on the Mac Mini for macOS) instead of in a guest. crates/komorebi-core/tests/e2e_layouts.rs (6 tests) runs update_shared on a StubPlatform workspace for the 8 layouts of the scenario, 1 to 8 containers and three padding settings: one tile per container, inside the work area, not on each other; workspace padding moves tiles 40 px in, container padding shrinks every tile, and back as it was; each of the three flips equals the plain tiles mirrored (as a set); removing a container (what a closed, minimized or floated window does) leaves the others at least as much room; two containers, one a stack of two, are two tiles; with tiling off nothing is placed in any layout. Each test names the e2e checks it mirrors. They protect Windows, KDE and macOS alike. Platform dependent: the stub adds no border and no frame adjustment, so the Windows border of 7 px (windows_padding) and each daemon's own adjust_layout stay e2e only, as does the OS frame matching the tile. Verified: cargo test -p komorebi-core --test e2e_layouts, 6 passed (native Linux; macOS crates run later on the Mini). No source change, no bug found. --- crates/komorebi-core/tests/e2e_layouts.rs | 244 ++++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100644 crates/komorebi-core/tests/e2e_layouts.rs diff --git a/crates/komorebi-core/tests/e2e_layouts.rs b/crates/komorebi-core/tests/e2e_layouts.rs new file mode 100644 index 00000000..fb0bc47f --- /dev/null +++ b/crates/komorebi-core/tests/e2e_layouts.rs @@ -0,0 +1,244 @@ +//! What the Windows `layouts`, `flipping`, `layout_flip`, `padding`, `closing`, `tiling` and +//! `stacks` scenarios (shared with KDE, and the only place macOS-or-Windows tiling used to be +//! checked) assert about where `Workspace::update_shared` puts the windows, run on the stub +//! platform: the tiles the shared code hands to the platform (`latest_layout`, which the scenarios +//! compare the OS frames with) for every layout, count, padding and flip. +//! +//! These protect all three daemons (Windows, KDE, macOS: each calls `update_shared`). Platform +//! choice: the stub platform adds no border and adjusts nothing, so a daemon's own `adjust_layout` +//! (the Windows border of 7 px, macOS or KDE frame corrections) is NOT covered and stays e2e +//! (`windows_padding`). +//! +//! The Windows fixture `kfw-tiled.json` of the e2e library is the same state shape these +//! workspaces serialize to (see `state_roundtrip.rs`). + +mod common; + +use common::*; +use komorebi_core::Workspace; +use komorebi_layouts::Axis; +use komorebi_layouts::DefaultLayout; +use komorebi_layouts::Layout; +use komorebi_layouts::Rect; + +const LAYOUTS: [DefaultLayout; 8] = [ + DefaultLayout::BSP, + DefaultLayout::Columns, + DefaultLayout::Rows, + DefaultLayout::VerticalStack, + DefaultLayout::HorizontalStack, + DefaultLayout::UltrawideVerticalStack, + DefaultLayout::Grid, + DefaultLayout::RightMainVerticalStack, +]; + +const AREA: Rect = Rect { + left: 0, + top: 0, + right: 1920, + bottom: 1080, +}; + +fn workspace( + layout: DefaultLayout, + ids: &[u32], + container_padding: Option<i32>, + workspace_padding: Option<i32>, + flip: Option<Axis>, +) -> Workspace<StubPlatform> { + let mut workspace = workspace_of(ids); + workspace.layout = Layout::Default(layout); + workspace.layout_flip = flip; + workspace.globals.work_area = AREA; + workspace.globals.container_padding = container_padding; + workspace.globals.workspace_padding = workspace_padding; + workspace +} + +fn tiles( + layout: DefaultLayout, + count: u32, + container_padding: Option<i32>, + workspace_padding: Option<i32>, + flip: Option<Axis>, +) -> Vec<Rect> { + fresh(); + let ids: Vec<u32> = (1..=count).collect(); + let mut workspace = workspace(layout, &ids, container_padding, workspace_padding, flip); + workspace.update_shared().unwrap(); + workspace.latest_layout.clone() +} + +fn inside(r: &Rect, a: &Rect) -> bool { + r.left >= a.left + && r.top >= a.top + && r.left + r.right <= a.left + a.right + && r.top + r.bottom <= a.top + a.bottom +} + +fn overlap(a: &Rect, b: &Rect) -> bool { + a.left < b.left + b.right + && b.left < a.left + a.right + && a.top < b.top + b.bottom + && b.top < a.top + a.bottom +} + +fn area(r: &Rect) -> i64 { + i64::from(r.right) * i64::from(r.bottom) +} + +// mirrors: layouts / <layout>, <n> windows: every window is where the layout says +// mirrors: layouts / ... inside the work area +// mirrors: layouts / ... and not on each other +// mirrors: tiling / every window is where the layout says; <a> and <b> do not overlap +#[test] +fn every_layout_tiles_every_container_inside_the_work_area_and_off_the_others() { + for layout in LAYOUTS { + for count in 1..=8 { + for (cp, wp) in [(None, None), (Some(10), Some(20)), (Some(0), Some(0))] { + let t = tiles(layout, count, cp, wp, None); + assert_eq!(t.len(), count as usize, "{layout} {count}"); + for (i, r) in t.iter().enumerate() { + assert!( + inside(r, &AREA), + "{layout} {count} {cp:?}/{wp:?}: {i} {r:?}" + ); + assert!( + r.right > 0 && r.bottom > 0, + "{layout} {count}: {i} is empty" + ); + for (j, o) in t.iter().enumerate().skip(i + 1) { + assert!(!overlap(r, o), "{layout} {count}: {i} {r:?} over {j} {o:?}"); + } + } + } + } + } +} + +// mirrors: padding / a workspace padding 40 px more moves the windows 40 px in from the edge +// mirrors: padding / a container padding 30 px more leaves the windows less room +// mirrors: padding / with the padding as it was, the windows are as far from the edge as they were +#[test] +fn the_workspace_padding_moves_the_tiles_in_and_the_container_padding_shrinks_them() { + for layout in LAYOUTS { + let base = tiles(layout, 3, None, None, None); + let more = tiles(layout, 3, None, Some(40), None); + let edge = |t: &[Rect]| t.iter().map(|r| r.left).min().unwrap(); + assert_eq!( + edge(&more), + edge(&base) + 40, + "{layout}: workspace padding 40" + ); + assert!(inside(more.first().unwrap(), &AREA)); + + let padded = tiles(layout, 3, Some(30), None, None); + for (a, b) in base.iter().zip(&padded) { + assert!( + area(b) < area(a), + "{layout}: container padding 30 did not shrink {a:?}" + ); + } + + assert_eq!( + base, + tiles(layout, 3, None, None, None), + "{layout}: back as it was" + ); + } +} + +// mirrors: flipping / after 'flip-layout horizontal' every window is where the mirror of its place is +// mirrors: flipping / flipped again, every window is where it was +// mirrors: layout_flip / <label>: the daemon starts with the layout mirrored +// mirrors: layout_flip / 'flip-layout vertical' adds to it: flipped along both axes +#[test] +fn a_flip_mirrors_the_tiles_of_the_workspace_as_a_set() { + let mirror = |r: &Rect, axis: Axis| { + let mut m = *r; + if matches!(axis, Axis::Horizontal | Axis::HorizontalAndVertical) { + m.left = AREA.left + AREA.right - (r.left + r.right); + } + if matches!(axis, Axis::Vertical | Axis::HorizontalAndVertical) { + m.top = AREA.top + AREA.bottom - (r.top + r.bottom); + } + m + }; + let key = |r: &Rect| (r.left, r.top, r.right, r.bottom); + for layout in LAYOUTS { + for count in 1..=6 { + let plain = tiles(layout, count, Some(10), Some(20), None); + for axis in [ + Axis::Horizontal, + Axis::Vertical, + Axis::HorizontalAndVertical, + ] { + let mut flipped = tiles(layout, count, Some(10), Some(20), Some(axis)); + let mut want: Vec<Rect> = plain.iter().map(|r| mirror(r, axis)).collect(); + // the workspace padding is symmetric, so the mirror of the padded tiles is the + // padded mirror + flipped.sort_by_key(key); + want.sort_by_key(key); + assert_eq!(flipped, want, "{layout} {count} {axis}"); + } + } + } +} + +// mirrors: closing / the windows that are left take more room between them +// mirrors: minimizing / with <target> minimized the others take more room between them +// mirrors: floating / ... the others take more room between them +#[test] +fn removing_a_container_gives_the_others_more_room() { + for layout in LAYOUTS.into_iter().filter(|l| *l != DefaultLayout::Grid) { + fresh(); + let mut w = workspace(layout, &[1, 2, 3, 4], Some(10), Some(20), None); + w.update_shared().unwrap(); + let before: i64 = w.latest_layout.iter().map(area).max().unwrap(); + // the focused (last) container leaves, as a closed, minimized or floated window does + w.remove_focused_container(); + w.update_shared().unwrap(); + assert_eq!(w.latest_layout.len(), 3, "{layout}"); + let after: i64 = w.latest_layout.iter().map(area).max().unwrap(); + assert!(after >= before, "{layout}: {before} -> {after}"); + for (i, r) in w.latest_layout.iter().enumerate() { + assert!(inside(r, &AREA), "{layout}: {i} {r:?}"); + } + } +} + +// mirrors: stacks / two containers, one of them a stack of two (three windows, two tiles) +// mirrors: stacks / and they tile, not on each other +#[test] +fn a_stack_is_one_tile() { + for layout in LAYOUTS { + fresh(); + let mut w = workspace(layout, &[1, 2, 3], Some(10), Some(20), None); + // stack window 3 onto container 1 as `stack left` does + w.focus_container(2); + let _ = w.move_window_to_container(0); + w.update_shared().unwrap(); + assert_eq!(w.containers().len(), 2, "{layout}"); + assert_eq!(w.latest_layout.len(), 2, "{layout}"); + assert!( + !overlap(&w.latest_layout[0], &w.latest_layout[1]), + "{layout}" + ); + } +} + +// mirrors: tiling_off / after 'toggle-tiling' ... no window moved +// mirrors: tiling_off / ... a layout change does not move them either +#[test] +fn a_workspace_with_tiling_off_places_nothing_whatever_the_layout() { + for layout in LAYOUTS { + fresh(); + let mut w = workspace(layout, &[1, 2, 3], Some(10), Some(20), None); + w.tile = false; + w.update_shared().unwrap(); + assert!( + !log().iter().any(|l| l.starts_with("place_container")), + "{layout}: a window was placed" + ); + } +} From af5ac697497f30d3b6af5fd9ecafb1384afd2e97 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 16:33:53 -0700 Subject: [PATCH 27/37] fix(deny): clarify the license of the workspace crates the macOS deny check sees The kfm deny check failed with `licenses FAILED`: the unified workspace's crates have no license field and the macOS deny.toml only clarified the old crate names. Twelve clarify entries (LicenseRef-Komorebi-2.0, as for the existing ones) now cover komorebi-backend, -bar, -bar-core, -client, -collections, -config, -core, -protocol, -settings, -transport, komorebic and komorebic-core. Verified: cargo deny --offline --workspace with the flake's 11 --exclude arguments and `check --config komorebi-for-mac/deny.toml bans licenses sources` (nix shell nixpkgs#cargo-deny, on the Linux host over the same Cargo.lock): bans ok, licenses ok, sources ok; taplo --check passes on the file. The check on the Mini is not re-run. --- komorebi-for-mac/deny.toml | 60 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/komorebi-for-mac/deny.toml b/komorebi-for-mac/deny.toml index ff68c08a..8fb6302c 100644 --- a/komorebi-for-mac/deny.toml +++ b/komorebi-for-mac/deny.toml @@ -88,6 +88,66 @@ crate = "version-macos" expression = "LicenseRef-Komorebi-2.0" license-files = [] +[[licenses.clarify]] +crate = "komorebi-backend" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebi-bar" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebi-bar-core" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebi-client" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebi-collections" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebi-config" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebi-core" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebi-protocol" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebi-settings" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebi-transport" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebic" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "komorebic-core" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "base16-egui-themes" expression = "MIT" From 1879b86a5cb502a63c4f010fad79d474e77df21b Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:34:29 -0700 Subject: [PATCH 28/37] build(tools): add trim-target, gate-lock and lite-env Optional helpers for a shared host: trim-target deletes stale test executables from the persistent cargo target dirs, gate-lock is a FIFO flock for heavy and timing-sensitive gates, lite-env sources debug-info-off cargo settings. Copies of the host-side scripts with these differences: - trim-target: the default scratch dir is `${XDG_CACHE_HOME:-$HOME/.cache}/komorebi-fast-check` (was a /tmp/claude-1000/... scratchpad path), the same as fast-check; - gate-lock: GATE_LOCK_DIR defaults to `${XDG_STATE_HOME:-$HOME/.local/state}/komorebi-gate` (was /home/jado/komomono-work/.gate), in the header and in the code; - gate-lock: "/proc/$pid/cmdline" is quoted and a shellcheck directive disables SC2012 and SC2016 (ls of plain queue ticket names, and a bash -c script expanding its own $1); - lite-env: a `# shellcheck shell=bash` first line. Not committed: mini (host and credential specific), host-sample and jitter-probe (host measurement), the .bak files. Verified: bash -n and shellcheck clean. Not run: gate-lock was tested by its author with a scratch GATE_LOCK_DIR before this change; the default path change is untested. --- tools/gate-lock | 222 ++++++++++++++++++++++++++++++++++++++++++++++ tools/lite-env | 10 +++ tools/trim-target | 16 ++++ 3 files changed, 248 insertions(+) create mode 100755 tools/gate-lock create mode 100644 tools/lite-env create mode 100755 tools/trim-target diff --git a/tools/gate-lock b/tools/gate-lock new file mode 100755 index 00000000..7f99d762 --- /dev/null +++ b/tools/gate-lock @@ -0,0 +1,222 @@ +#!/usr/bin/env bash +# gate-lock: a host-wide queue for heavy gates (nix build checks, KDE VM suites, +# Windows e2e, long clippy), with a declared load class. Light checks never block. +# See tools/README.md. Never commits, never pushes, touches nothing but $GATE_LOCK_DIR. +# +# gate-lock run [opts] -- CMD... take the lock (FIFO), run CMD, release +# gate-lock adopt [opts] PID hold the lock until an already running PID exits +# gate-lock status [--short] who holds it, who waits, host load +# gate-lock wait [--max SEC] return when nobody holds it (takes nothing) +# gate-lock history [N] last N finished gates (default 20) +# +# Classes (--class): +# light never waits, never +# holds. If a timing gate is active the command runs as `nice -n 19` with +# CARGO_BUILD_JOBS=${GATE_LIGHT_JOBS:-3} (and `taskset -c $GATE_LIGHT_CPUS` +# if set), so that compile checks stay out of the way of a timing-sensitive run. +# heavy exclusive among heavy/timing gates: nix build of checks, KDE VM suite, +# cold or long clippy, anything that can push 1-min load above ~10. +# timing like heavy, and declares "this run is timing-sensitive": light work is +# throttled while it holds (Windows e2e, `commands`, core-e2e VM suites). +# +# Options for run/adopt: --class C --label TEXT --est MIN --front (jump the queue) +# --wait-max SEC (give up with exit 75) --idle-load N (after getting the lock, wait +# for the 1-min load to fall below N, at most --idle-max SEC, default 600) +# Env: GATE_LOCK_DIR (default ${XDG_STATE_HOME:-$HOME/.local/state}/komorebi-gate), GATE_OWNER (default: the +# workspace directory name, e.g. ws-u-kfw), GATE_LIGHT_JOBS, GATE_LIGHT_CPUS. +# shellcheck disable=SC2012,SC2016 # ls of queue tickets (plain names) and a bash -c script that expands $1 itself +set -uo pipefail + +DIR="${GATE_LOCK_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/komorebi-gate}" +LOCK="$DIR/heavy.lock" +HOLDER="$DIR/holder" +HIST="$DIR/history.log" +QUEUE="$DIR/queue" +mkdir -p "$QUEUE" + +owner() { + if [ -n "${GATE_OWNER:-}" ]; then echo "$GATE_OWNER"; return; fi + local d="$PWD" + while [ "$d" != "/" ]; do + case "$(basename "$d")" in ws-*) basename "$d"; return ;; esac + d="$(dirname "$d")" + done + echo "${USER:-unknown}" +} + +now() { date +%s; } +stamp() { date '+%F %T'; } +load1() { cut -d' ' -f1 /proc/loadavg; } +ago() { # seconds -> 12m / 1h05m + local s=$1 + if [ "$s" -lt 120 ]; then echo "${s}s" + elif [ "$s" -lt 7200 ]; then echo "$((s / 60))m" + else printf '%dh%02dm' $((s / 3600)) $(((s % 3600) / 60)); fi +} + +# Is the lock held right now? A shared-mode probe conflicts only with the exclusive +# holder, so probes never block each other (an acquirer may miss once and retries). +held() { ! ( exec 8>>"$LOCK"; flock -n -s 8 ) 2>/dev/null; } + +field() { sed -n "s/^$1=//p" "$HOLDER" 2>/dev/null | head -1; } + +timing_active() { held && [ "$(field class)" = timing ]; } + +prune_queue() { + local t pid + for t in "$QUEUE"/*; do + [ -e "$t" ] || continue + pid="$(sed -n 's/^pid=//p' "$t")" + if [ -z "$pid" ] || [ ! -d "/proc/$pid" ]; then rm -f "$t"; fi + done +} + +cmd_status() { + local short=0 + [ "${1:-}" = --short ] && short=1 + if held; then + local since age + since="$(field since)"; age=$(( $(now) - ${since:-$(now)} )) + if [ $short = 1 ]; then + echo "$(field class):$(field owner):$(field label):$(ago "$age")" + return 0 + fi + echo "HELD class=$(field class) owner=$(field owner) pid=$(field pid) for $(ago "$age") est=$(field est)min" + echo " label: $(field label)" + echo " cmd: $(field cmd)" + else + [ $short = 1 ] && { echo FREE; return 0; } + echo "FREE (nobody holds the heavy-gate lock)" + fi + prune_queue + local n=0 t + for t in $(ls "$QUEUE" 2>/dev/null | sort); do + n=$((n + 1)) + echo "QUEUE $n. class=$(sed -n 's/^class=//p' "$QUEUE/$t") owner=$(sed -n 's/^owner=//p' "$QUEUE/$t") waiting $(ago $(( $(now) - $(sed -n 's/^queued=//p' "$QUEUE/$t") ))) label: $(sed -n 's/^label=//p' "$QUEUE/$t")" + done + [ $n = 0 ] && echo "QUEUE empty" + echo "HOST load1=$(load1) cpus=$(nproc) $(awk '/MemAvailable/{printf "mem_avail=%.0fG", $2/1048576}' /proc/meminfo)" + if timing_active; then + echo "LIGHT throttled: nice 19, CARGO_BUILD_JOBS=${GATE_LIGHT_JOBS:-3}${GATE_LIGHT_CPUS:+, cpus $GATE_LIGHT_CPUS} (run light work through: gate-lock run --class light -- CMD)" + else + echo "LIGHT free (no timing gate active)" + fi +} + +cmd_history() { tail -n "${1:-20}" "$HIST" 2>/dev/null || echo "(no history)"; } + +cmd_wait() { + local max=0 start + [ "${1:-}" = --max ] && max="$2" + start=$(now) + while held; do + [ "$max" -gt 0 ] && [ $(( $(now) - start )) -ge "$max" ] && { echo "gate-lock: still held after ${max}s" >&2; return 75; } + sleep 2 + done +} + +run_light() { + local label="$1"; shift + if timing_active; then + echo "gate-lock: timing gate active ($(field owner): $(field label)); running light work throttled" >&2 + export CARGO_BUILD_JOBS="${GATE_LIGHT_JOBS:-3}" + local pre=(nice -n 19) + [ -n "${GATE_LIGHT_CPUS:-}" ] && pre=(taskset -c "$GATE_LIGHT_CPUS" nice -n 19) + "${pre[@]}" "$@" + else + "$@" + fi + return $? +} + +# acquire_and_run CLASS LABEL EST FRONT WAITMAX IDLELOAD IDLEMAX -- CMD... +acquire_and_run() { + local class="$1" label="$2" est="$3" front="$4" waitmax="$5" idleload="$6" idlemax="$7" + shift 8 + local me ticket queued rc child + me="$(owner)" + queued=$(now) + ticket="$QUEUE/$([ "$front" = 1 ] && echo 0 || echo 1)-$(date +%s%N)-$$" + printf 'pid=%s\nowner=%s\nclass=%s\nlabel=%s\nqueued=%s\n' "$$" "$me" "$class" "$label" "$queued" > "$ticket" + exec 9>>"$LOCK" + trap 'rm -f "$ticket"; exit 130' INT TERM HUP + local told=0 + while :; do + prune_queue + if [ "$(ls "$QUEUE" | sort | head -1)" = "$(basename "$ticket")" ]; then + flock -w 2 9 && break + else + sleep 1 + fi + if [ $told = 0 ]; then + echo "gate-lock: waiting for $class gate '$label' ($me); holder: $(cmd_status --short)" >&2; told=1 + fi + if [ "$waitmax" -gt 0 ] && [ $(( $(now) - queued )) -ge "$waitmax" ]; then + rm -f "$ticket"; echo "gate-lock: gave up after ${waitmax}s" >&2; return 75 + fi + done + rm -f "$ticket" + trap - INT TERM HUP + local waited=$(( $(now) - queued )) started + started=$(now) + printf 'pid=%s\nowner=%s\nclass=%s\nlabel=%s\nest=%s\nsince=%s\ncmd=%s\n' \ + "$$" "$me" "$class" "$label" "$est" "$started" "$*" > "$HOLDER.$$" && mv -f "$HOLDER.$$" "$HOLDER" + echo "gate-lock: acquired $class gate '$label' after $(ago "$waited")" >&2 + if [ -n "$idleload" ]; then + local t0; t0=$(now) + while awk -v l="$(load1)" -v m="$idleload" 'BEGIN{exit !(l>=m)}'; do + [ $(( $(now) - t0 )) -ge "$idlemax" ] && { echo "gate-lock: load still $(load1) >= $idleload after ${idlemax}s; going ahead (recorded)" >&2; break; } + sleep 5 + done + started=$(now) + fi + local load_start; load_start="$(load1)" + "$@" & + child=$! + trap 'kill -TERM "$child" 2>/dev/null' INT TERM HUP + wait "$child"; rc=$? + while kill -0 "$child" 2>/dev/null; do wait "$child"; rc=$?; done + trap - INT TERM HUP + printf '%s owner=%s class=%s label="%s" waited=%ss ran=%ss rc=%s load1_start=%s load1_end=%s\n' \ + "$(stamp)" "$me" "$class" "$label" "$waited" "$(( $(now) - started ))" "$rc" "$load_start" "$(load1)" >> "$HIST" + [ "$(field pid)" = "$$" ] && rm -f "$HOLDER" + return $rc +} + +sub="${1:-}"; [ $# -gt 0 ] && shift +case "$sub" in + status) cmd_status "$@" ;; + history) cmd_history "$@" ;; + wait) cmd_wait "$@" ;; + run|adopt) + class=""; label=""; est="?"; front=0; waitmax=0; idleload=""; idlemax=600 + while [ $# -gt 0 ]; do + case "$1" in + --class) class="$2"; shift 2 ;; + --label) label="$2"; shift 2 ;; + --est) est="$2"; shift 2 ;; + --front) front=1; shift ;; + --wait-max) waitmax="$2"; shift 2 ;; + --idle-load) idleload="$2"; shift 2 ;; + --idle-max) idlemax="$2"; shift 2 ;; + --) shift; break ;; + *) break ;; + esac + done + if [ "$sub" = adopt ]; then + pid="${1:?usage: gate-lock adopt [opts] PID}" + [ -d "/proc/$pid" ] || { echo "gate-lock: no process $pid" >&2; exit 2; } + class="${class:-timing}"; label="${label:-adopted pid $pid ($(tr '\0' ' ' < "/proc/$pid/cmdline" | cut -c1-60))}" + set -- bash -c 'while kill -0 "$1" 2>/dev/null; do sleep 5; done' _ "$pid" + fi + [ $# -gt 0 ] || { echo "gate-lock: no command (use: run --class C -- CMD...)" >&2; exit 2; } + [ -n "$class" ] || { echo "gate-lock: --class light|heavy|timing is required" >&2; exit 2; } + label="${label:-$*}" + case "$class" in + light) run_light "$label" "$@"; exit $? ;; + heavy|timing) acquire_and_run "$class" "$label" "$est" "$front" "$waitmax" "$idleload" "$idlemax" -- "$@"; exit $? ;; + *) echo "gate-lock: unknown class '$class'" >&2; exit 2 ;; + esac ;; + -h|--help|help|"") sed -n '2,31p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; [ -n "$sub" ] || exit 2 ;; + *) echo "gate-lock: unknown subcommand '$sub' (see --help)" >&2; exit 2 ;; +esac diff --git a/tools/lite-env b/tools/lite-env new file mode 100644 index 00000000..6c974a97 --- /dev/null +++ b/tools/lite-env @@ -0,0 +1,10 @@ +# shellcheck shell=bash +# lite-env: source this (". tools/lite-env") before gate builds that write a lot of disk. +# Debug info off for the dev/test profiles: same code, same tests, same pass/fail; much smaller +# test binaries (less disk write, shorter link). Panic backtraces lose line numbers. +# Use with its OWN target dir (the fingerprint changes, so the first build is cold): +# CARGO_TARGET_DIR=$FAST_CHECK_SCRATCH/target-lite-<name> . tools/lite-env +export CARGO_PROFILE_DEV_DEBUG=0 +export CARGO_PROFILE_TEST_DEBUG=0 +export CARGO_INCREMENTAL=${CARGO_INCREMENTAL:-0} +export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-3} diff --git a/tools/trim-target b/tools/trim-target new file mode 100755 index 00000000..98cb2f2e --- /dev/null +++ b/tools/trim-target @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Delete stale test executables from the shared cargo target dirs. A debug test binary is about +# 290MB and every workspace path that builds the KDE tests adds up to 79 of them; the KDE target +# dir grew from 30G to 109G in one evening this way. The binaries are rebuilt on demand. +# tools/trim-target [MINUTES] (default 45: binaries untouched for that long are removed) +set -euo pipefail +minutes=${1:-45} +S=${FAST_CHECK_SCRATCH:-${XDG_CACHE_HOME:-$HOME/.cache}/komorebi-fast-check} +for d in "$S"/kde-target "$S"/target-fast-win "$S"/target-fast-mac "$S"/target-fast-native "$S"/target-spikes; do + [ -d "$d/debug/deps" ] || continue + before=$(du -sm "$d" | cut -f1) + find "$d/debug/deps" -maxdepth 1 -type f -perm -u+x ! -name '*.*' -mmin +"$minutes" -delete + after=$(du -sm "$d" | cut -f1) + echo "$d: ${before}M -> ${after}M" +done +df -h / /mnt/e | tail -2 From b12be4b1a7e955c4281628265e426cedfaf18c7c Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:43:17 -0700 Subject: [PATCH 29/37] refactor(windows): move window_handling_behaviour to the platform settings, scoped guard in the border test Plan step 10, part of S7 and the scoped guard asked for in S5. WINDOW_HANDLING_BEHAVIOUR is no longer a static: it is settings().platform.window_handling_behaviour (WindowsSettings, default Sync). The load writes it with one update when the key is present (a missing key keeps it, as before); windows_api (the position calls) and scrolling read it through settings::window_handling_behaviour(), once per call. The border paint test (border_manager/border.rs is_painted) saved the static, stored a value and stored the old one back, which overwrote any change made in between. It now holds Handle::scoped on the field, which puts the previous value back on drop only if the field still holds the value it set. BEHAVIOUR: the position calls read a snapshot instead of an atomic cell (one RwLock read and Arc clone per call), and the load publishes the key through the handle. Gate: Windows e2e (commands, config_reload, lifecycle; anything that moves windows with window_handling_behaviour async if configured). Verified: Windows clippy -D warnings --locked --all-targets on komorebi-windows (cross): clean. e2e not run; the border paint test needs a desktop and was not run. --- komorebi/src/border_manager/border.rs | 7 ++++--- komorebi/src/lib.rs | 4 ---- komorebi/src/scrolling.rs | 3 +-- komorebi/src/settings.rs | 24 +++++++++++++++++++++--- komorebi/src/static_config.rs | 7 ++++--- komorebi/src/windows_api.rs | 11 +++++------ 6 files changed, 35 insertions(+), 21 deletions(-) diff --git a/komorebi/src/border_manager/border.rs b/komorebi/src/border_manager/border.rs index 3723681f..cdb9b5fd 100644 --- a/komorebi/src/border_manager/border.rs +++ b/komorebi/src/border_manager/border.rs @@ -834,8 +834,9 @@ mod tests { .expect("a window to put a border around"); let tracked_hwnd = tracked.0 as isize; - let previous = crate::WINDOW_HANDLING_BEHAVIOUR.load(); - crate::WINDOW_HANDLING_BEHAVIOUR.store(handling); + // put back when the guard is dropped, unless something else changed it meanwhile + let handling_override = crate::settings::settings() + .scoped(|settings| &mut settings.platform.window_handling_behaviour, handling); let mut border = Border::create("komorebi-border-test", tracked_hwnd, 0).expect("a border to paint"); @@ -854,7 +855,7 @@ mod tests { let painted = unsafe { std::ptr::read_volatile(&raw const border.rounded_rect.rect.right) } > 0.0; - crate::WINDOW_HANDLING_BEHAVIOUR.store(previous); + drop(handling_override); let border = Box::into_raw(border); unsafe { diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 28cc2814..c6e2b36d 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -75,7 +75,6 @@ use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; use crate::core::config_generation::WorkspaceMatchingRule; use color_eyre::eyre; -use crossbeam_utils::atomic::AtomicCell; use os_info::Version; use parking_lot::Mutex; use parking_lot::RwLock; @@ -277,9 +276,6 @@ pub static REMOVE_TITLEBARS: AtomicBool = AtomicBool::new(false); pub static SLOW_APPLICATION_COMPENSATION_TIME: AtomicU64 = AtomicU64::new(20); -pub static WINDOW_HANDLING_BEHAVIOUR: AtomicCell<WindowHandlingBehaviour> = - AtomicCell::new(WindowHandlingBehaviour::Sync); - shadow_rs::shadow!(build); pub const PUBLIC_KEY: [u8; 32] = [ diff --git a/komorebi/src/scrolling.rs b/komorebi/src/scrolling.rs index cf0d39e5..2352ddf7 100644 --- a/komorebi/src/scrolling.rs +++ b/komorebi/src/scrolling.rs @@ -4,7 +4,6 @@ //! `komorebi-scrolling` crate, so that every komorebi shares it. What is here is what needs a //! [`Workspace`]: a container is a tile in the strip, and is known to it by its id. -use crate::WINDOW_HANDLING_BEHAVIOUR; use crate::animation::ANIMATION_MANAGER; use crate::animation::prefix::AnimationPrefix; use crate::container::Container; @@ -37,7 +36,7 @@ const WIDTH_TOLERANCE: i32 = 16; /// moves are done by the time they are asked, and none is being animated. fn window_sizes_are_settled() -> bool { matches!( - WINDOW_HANDLING_BEHAVIOUR.load(), + crate::settings::window_handling_behaviour(), WindowHandlingBehaviour::Sync ) && ANIMATION_MANAGER.lock().count() == 0 } diff --git a/komorebi/src/settings.rs b/komorebi/src/settings.rs index 1fd67857..32a0a25a 100644 --- a/komorebi/src/settings.rs +++ b/komorebi/src/settings.rs @@ -13,6 +13,7 @@ use crate::animation::prefix::AnimationPrefix; use crate::core::animation::AnimationStyle; use komorebi_config::aspect_ratio::AspectRatio; +use komorebi_config::behaviour::WindowHandlingBehaviour; use komorebi_layouts::DefaultLayout; use komorebi_layouts::LayoutDefaultEntry; @@ -20,9 +21,21 @@ use komorebi_settings::Handle; use komorebi_settings::Shared; use komorebi_settings::shared::PlatformDefaults; -/// The part of the settings that only Windows has. Empty for now; the stackbar, hiding and handling behaviour and border style join it later. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct WindowsSettings {} +/// The part of the settings that only Windows has. The stackbar, hiding behaviour and border style +/// join it later. +#[derive(Clone, Debug, PartialEq)] +pub struct WindowsSettings { + /// `window_handling_behaviour`: whether windows are moved synchronously or asynchronously. + pub window_handling_behaviour: WindowHandlingBehaviour, +} + +impl Default for WindowsSettings { + fn default() -> Self { + Self { + window_handling_behaviour: WindowHandlingBehaviour::Sync, + } + } +} pub type Settings = komorebi_settings::Settings<WindowsSettings>; @@ -144,6 +157,11 @@ pub fn animation_off_for_good() { }); } +/// `window_handling_behaviour`, read once per window move. +pub fn window_handling_behaviour() -> WindowHandlingBehaviour { + settings().snapshot().platform.window_handling_behaviour +} + #[cfg(test)] mod tests { use std::sync::atomic::Ordering; diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index 89fd6dc2..1bd86d53 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -18,7 +18,6 @@ use crate::SLOW_APPLICATION_COMPENSATION_TIME; use crate::SLOW_APPLICATION_IDENTIFIERS; use crate::TRANSPARENCY_BLACKLIST; use crate::TRAY_AND_MULTI_WINDOW_IDENTIFIERS; -use crate::WINDOW_HANDLING_BEHAVIOUR; use crate::WINDOWS_11; use crate::WORKSPACE_MATCHING_RULES; use crate::animation::DEFAULT_GHOST_MOVEMENT; @@ -367,7 +366,7 @@ impl From<&WindowManager> for StaticConfig { floating_window_aspect_ratio: Option::from( crate::settings::floating_window_aspect_ratio(), ), - window_handling_behaviour: Option::from(WINDOW_HANDLING_BEHAVIOUR.load()), + window_handling_behaviour: Option::from(crate::settings::window_handling_behaviour()), ..Default::default() } } @@ -664,7 +663,9 @@ impl ApplyGlobals for StaticConfig { } if let Some(behaviour) = self.window_handling_behaviour { - WINDOW_HANDLING_BEHAVIOUR.store(behaviour); + crate::settings::settings().update(|settings| { + settings.platform.window_handling_behaviour = behaviour; + }); } Ok(()) diff --git a/komorebi/src/windows_api.rs b/komorebi/src/windows_api.rs index 98d3bed4..7f679ce8 100644 --- a/komorebi/src/windows_api.rs +++ b/komorebi/src/windows_api.rs @@ -163,7 +163,6 @@ use crate::core::Rect; use crate::DUPLICATE_MONITOR_SERIAL_IDS; use crate::MONITOR_INDEX_PREFERENCES; -use crate::WINDOW_HANDLING_BEHAVIOUR; use crate::Window; use crate::WindowHandlingBehaviour; use crate::WindowManager; @@ -529,7 +528,7 @@ impl WindowsApi { // blocking our thread in case the target window is not responding. if with_async_window_pos && matches!( - WINDOW_HANDLING_BEHAVIOUR.load(), + crate::settings::window_handling_behaviour(), WindowHandlingBehaviour::Async ) { @@ -576,7 +575,7 @@ impl WindowsApi { | SetWindowPosition::SHOW_WINDOW; if matches!( - WINDOW_HANDLING_BEHAVIOUR.load(), + crate::settings::window_handling_behaviour(), WindowHandlingBehaviour::Async ) { flags |= SetWindowPosition::ASYNC_WINDOW_POS; @@ -600,7 +599,7 @@ impl WindowsApi { | SetWindowPosition::SHOW_WINDOW; if matches!( - WINDOW_HANDLING_BEHAVIOUR.load(), + crate::settings::window_handling_behaviour(), WindowHandlingBehaviour::Async ) { flags |= SetWindowPosition::ASYNC_WINDOW_POS; @@ -630,7 +629,7 @@ impl WindowsApi { } if matches!( - WINDOW_HANDLING_BEHAVIOUR.load(), + crate::settings::window_handling_behaviour(), WindowHandlingBehaviour::Async ) { flags |= SetWindowPosition::ASYNC_WINDOW_POS; @@ -679,7 +678,7 @@ impl WindowsApi { // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow // TODO: error handling if matches!( - WINDOW_HANDLING_BEHAVIOUR.load(), + crate::settings::window_handling_behaviour(), WindowHandlingBehaviour::Async ) { unsafe { From 595e9c46a1afae1384dc5a4b8837505d3a95a9ff Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:44:21 -0700 Subject: [PATCH 30/37] refactor(kde,mac): monitor_idx_from_current_pos asks window::monitor_id_at_cursor() Both daemons' window.rs have monitor_id_at_cursor() (KDE: the backend's pointer position resolved to the monitor under it; macOS: MacosApi's monitor_from_point of its cursor position), and monitor_idx_from_current_pos in both window_manager.rs files is now the same text up to its macOS-only comment block. No behaviour change. Verified: KDE cargo test -p komorebi-linux (lite env): 664 passed, 0 failed; fake-CC cargo clippy -p komorebi-macos ... --all-targets -D warnings: PASS; Windows cargo clippy -p komorebi-windows --locked --all-targets -D warnings: PASS (the whole-workspace Windows clippy fails in komorebi-bar, E0046 missing release_page_url, which is not in this change and fails at the base). Not run: the macOS tests (the Mac Mini). --- komorebi-for-kde/komorebi/src/window.rs | 6 ++++++ komorebi-for-kde/komorebi/src/window_manager.rs | 4 ++-- komorebi-for-mac/komorebi/src/window.rs | 5 +++++ komorebi-for-mac/komorebi/src/window_manager.rs | 3 ++- 4 files changed, 15 insertions(+), 3 deletions(-) diff --git a/komorebi-for-kde/komorebi/src/window.rs b/komorebi-for-kde/komorebi/src/window.rs index 6d400e4d..578aaf7f 100644 --- a/komorebi-for-kde/komorebi/src/window.rs +++ b/komorebi-for-kde/komorebi/src/window.rs @@ -92,6 +92,12 @@ pub fn foreground_window_id() -> Option<PlatformWindowId> { backend().foreground_window().and_then(WindowId::to_u32) } +/// The id of the monitor the pointer is on, if the compositor says where it is +pub fn monitor_id_at_cursor() -> Option<u32> { + let (x, y) = backend().cursor_pos()?; + backend().monitor_from_point(x, y)?.to_u32() +} + /// Where the pointer is, if the compositor says pub fn cursor_position() -> Option<(i32, i32)> { backend().cursor_pos() diff --git a/komorebi-for-kde/komorebi/src/window_manager.rs b/komorebi-for-kde/komorebi/src/window_manager.rs index 2d952b57..8ac80635 100644 --- a/komorebi-for-kde/komorebi/src/window_manager.rs +++ b/komorebi-for-kde/komorebi/src/window_manager.rs @@ -84,6 +84,7 @@ use crate::static_config::StaticConfig; use crate::static_config::StaticConfigExt; use crate::window::Window; use crate::window::foreground_window_id; +use crate::window::monitor_id_at_cursor; use crate::window::should_act_individual; use crate::window_manager_event::WindowManagerEvent; use crate::window_manager_event_listener; @@ -2355,8 +2356,7 @@ impl WindowManager { } pub fn monitor_idx_from_current_pos(&mut self) -> Option<usize> { - let (x, y) = backend().cursor_pos()?; - let monitor_id = backend().monitor_from_point(x, y)?.to_u32()?; + let monitor_id = monitor_id_at_cursor()?; for (i, monitor) in self.monitors().iter().enumerate() { if monitor.id == monitor_id { diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 0684803c..895b6673 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -556,6 +556,11 @@ pub fn foreground_window_id() -> Option<u32> { MacosApi::foreground_window_id() } +/// The id of the monitor the pointer is on +pub fn monitor_id_at_cursor() -> Option<u32> { + MacosApi::monitor_from_point(MacosApi::cursor_pos()) +} + impl Window { pub fn new( element: CFRetained<AXUIElement>, diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index a1aba496..40f91cef 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -55,6 +55,7 @@ use crate::window::dragged_window; use crate::window::foreground_window_id; use crate::window::live_resize_begins; use crate::window::live_resize_ends; +use crate::window::monitor_id_at_cursor; use crate::window::should_act_individual; use crate::window_manager_event::ManualNotification; use crate::window_manager_event::SystemNotification; @@ -2467,7 +2468,7 @@ impl WindowManager { } pub fn monitor_idx_from_current_pos(&mut self) -> Option<usize> { - let monitor_id = MacosApi::monitor_from_point(MacosApi::cursor_pos())?; + let monitor_id = monitor_id_at_cursor()?; for (i, monitor) in self.monitors().iter().enumerate() { if monitor.id == monitor_id { From 89f28726098c131249cdd9cd36d9b8405a00271a Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:40:40 -0700 Subject: [PATCH 31/37] fix(bar): open the macOS settings, Activity Monitor and links with open The macOS bar's battery click spawned cmd.exe /C start ms-settings:batterysaver and the update click spawned explorer.exe, neither of which exists on macOS (the move kept them on purpose, handcheck D.B). Both now go through `open`, as the CPU, memory and network clicks already did. The decision which program and arguments a click runs is a pure function, system_tool_command(&SystemTool) -> (program, args), so the argv is unit tested: task manager is `open -a 'Activity Monitor'`, the battery is `open x-apple.systempreferences:com.apple.Battery-Settings.extension` (the pane id of System Settings in macOS 13 and later, the scheme the network pane already used; unconfirmed on a real Mac, hand-check row added), a URL is opened as is, a storage label opens its path. The module is macOS only (cfg(target_os = "macos") at the crate root), so none of this is built elsewhere. BEHAVIOUR (macOS): clicks on the battery and update widgets now open something. Gate: macOS hand-check rows M1-M3 in docs/dev/macos-handcheck.md and the unit tests on the Mac (cargo test -p komorebi-bar). Verified: type-check only on Linux (see the fast-check result in the progress log); tests not run here. --- komorebi-bar/src/macos/os.rs | 104 ++++++++++++++++++++++++++++------- 1 file changed, 83 insertions(+), 21 deletions(-) diff --git a/komorebi-bar/src/macos/os.rs b/komorebi-bar/src/macos/os.rs index dbab39cd..17f472a6 100644 --- a/komorebi-bar/src/macos/os.rs +++ b/komorebi-bar/src/macos/os.rs @@ -10,27 +10,8 @@ pub struct MacBar; impl BarPlatform for MacBar { fn open_system_tool(&self, tool: SystemTool) -> io::Result<()> { - match tool { - SystemTool::TaskManager => Command::new("open") - .args(["-a", "Activity Monitor"]) - .spawn(), - // cmd.exe does not exist on macOS: this is what the battery widget does today - SystemTool::PowerSettings => Command::new("cmd.exe") - .args(["/C", "start", "ms-settings:batterysaver"]) - .spawn(), - SystemTool::NetworkSettings => Command::new("open") - .args(["x-apple.systempreferences:com.apple.Network-Settings.extension"]) - .spawn(), - // explorer.exe does not exist on macOS: this is what the update widget does today - SystemTool::Url(url) => Command::new("explorer.exe").args([url]).spawn(), - SystemTool::StorageLocation(label) => { - let parts: Vec<&str> = label.split(' ').collect(); - let path = parts[..parts.len() - 1].join(" "); - - Command::new("open").args([path]).spawn() - } - } - .map(|_| ()) + let (program, args) = system_tool_command(&tool); + Command::new(program).args(args).spawn().map(|_| ()) } fn latest_release_api_url(&self) -> &'static str { @@ -62,3 +43,84 @@ impl BarPlatform for MacBar { None } } + +/// The program and arguments that open `tool` on macOS: everything goes through `open`. +fn system_tool_command(tool: &SystemTool) -> (&'static str, Vec<String>) { + let args: Vec<String> = match tool { + SystemTool::TaskManager => vec!["-a".into(), "Activity Monitor".into()], + // System Settings of macOS 13 and later (the same scheme as the network pane) + SystemTool::PowerSettings => { + vec!["x-apple.systempreferences:com.apple.Battery-Settings.extension".into()] + } + SystemTool::NetworkSettings => { + vec!["x-apple.systempreferences:com.apple.Network-Settings.extension".into()] + } + SystemTool::Url(url) => vec![url.clone()], + SystemTool::StorageLocation(label) => { + // the label is "<path> <usage>": the path is everything but the last word + let parts: Vec<&str> = label.split(' ').collect(); + vec![parts[..parts.len() - 1].join(" ")] + } + }; + + ("open", args) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn argv(tool: SystemTool) -> Vec<String> { + let (program, args) = system_tool_command(&tool); + assert_eq!( + program, "open", + "nothing on macOS is started by another program" + ); + args + } + + #[test] + fn the_task_manager_is_activity_monitor() { + assert_eq!(argv(SystemTool::TaskManager), ["-a", "Activity Monitor"]); + } + + #[test] + fn the_battery_opens_the_battery_pane_of_system_settings() { + assert_eq!( + argv(SystemTool::PowerSettings), + ["x-apple.systempreferences:com.apple.Battery-Settings.extension"] + ); + } + + #[test] + fn the_network_opens_the_network_pane_of_system_settings() { + assert_eq!( + argv(SystemTool::NetworkSettings), + ["x-apple.systempreferences:com.apple.Network-Settings.extension"] + ); + } + + #[test] + fn a_url_is_opened_in_the_default_browser() { + assert_eq!( + argv(SystemTool::Url("https://example.com/a b".into())), + ["https://example.com/a b"] + ); + } + + #[test] + fn a_storage_label_opens_its_path_without_the_free_space() { + assert_eq!( + argv(SystemTool::StorageLocation("/Volumes/My Disk 43%".into())), + ["/Volumes/My Disk"] + ); + } + + #[test] + fn the_release_page_is_the_one_of_the_mac_repository() { + assert_eq!( + MacBar.release_page_url("0.1.2"), + "https://github.com/LGUG2Z/komorebi-for-mac/releases/tag/v0.1.2" + ); + } +} From f085064af9bf4f68db0cf0be2190526d38114549 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 17:20:09 -0700 Subject: [PATCH 32/37] docs(dev): e2e-to-unit, which e2e checks the shared crates made testable natively Inventory of every Windows/shared e2e scenario and the KDE VM suites against the native tests that exist after the consolidation: class A (covered, cited), B (coverable with the shared crates, proposed test) and C (needs a real OS), with effort and value, ordered with the Windows-only e2e behaviours first. Gives the estimate of gate minutes saved today and if the B items existed, the seams the shared crates lack (daemon command handler, rule matching shared in komorebi-config, monitor reconciliation, stack cycling), and the tests added with the e2e check each mirrors. Verified: not applicable (documentation); the cited tests were read, and the added ones were run (see their revisions). --- docs/dev/e2e-to-unit.md | 142 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 docs/dev/e2e-to-unit.md diff --git a/docs/dev/e2e-to-unit.md b/docs/dev/e2e-to-unit.md new file mode 100644 index 00000000..12d5fa93 --- /dev/null +++ b/docs/dev/e2e-to-unit.md @@ -0,0 +1,142 @@ +# From e2e to unit: what the shared crates made testable natively + +Base: `wip-cand5` plus the revisions that add the tests named here. Written 2026-10-31. + +Before the shared crates, the Windows daemon could only be tested through a Windows guest (its crate +does not compile on Linux) and the macOS daemon through nothing. Now Windows, KDE and macOS call the +same `komorebi-core` (`Container`, `Workspace`, `Monitor`, `update_shared` and the platform hooks), +`komorebi-layouts`, `komorebi-scrolling`, `komorebi-settings`, `komorebi-protocol`, +`komorebi-config`, `komorebi-transport` and `komorebic-core`, so a native test of that code, on the +stub platform (`crates/komorebi-core/tests/common`) or `FakeBackend`, protects all three. This +document lists every e2e scenario, says whether that is now done, and ranks what is left. + +## What stays out of reach + +The daemons' own `process_command` / `process_event` are per platform (Windows: Win32 types; macOS: +Mac types), only the KDE one runs on `FakeBackend`. So a native test of "send this command, then the +state is that" exists for KDE only; for Windows and macOS it holds as far as the command's work is +done by shared `Workspace`/`Monitor` methods. Rule matching (`should_act_individual`) exists three +times (Windows `komorebi/src/window.rs:1178`, KDE `window.rs:661`, macOS `window.rs:1864`), not in +`komorebi-config`. Every row below says which of these a test reaches. + +## Classes + +- A: already covered natively. B: coverable natively with the shared API, not yet. C: needs a real OS + (compositor, Win32, timing, pointer, rendering, several processes). +- "Now" marks what this work added (revisions on `wip-u-e2e2unit`). +- Value: share of the gate it could stand in for. Effort S/M/L. +- Check counts: dynamic numbers where the gate printed them (layouts 111, commands 265), else the + number of check call sites in the scenario file (static, lower than the runs). + +## Windows-origin scenarios (first: only e2e-testable on Windows, now native) + +| Scenario (checks) | Behaviour | Class | Native test (cited, or proposed) | Eff. | Value | +|---|---|---|---|---|---| +| layouts (111) | 8 layouts x counts: each window where the layout says, inside the work area, not over another | A now (arithmetic); C (OS frame equals tile) | `crates/komorebi-core/tests/e2e_layouts.rs` `every_layout_tiles_every_container_inside_the_work_area_and_off_the_others` (shared `update_shared`), `komorebi-layouts/tests/layouts_everywhere.rs` (calculate, 3 areas, 1-12 windows) | S | high: 3 min, can shrink to 1 layout smoke | +| flipping (3) | flip-layout mirrors every place, flip back restores | A now | `e2e_layouts.rs` `a_flip_mirrors_the_tiles_of_the_workspace_as_a_set`; `layouts_everywhere.rs` flips | S | med | +| layout_flip (10) | `layout_flip` config mirrors from the start; flip-layout toggles; per workspace | A now for the maths; B for config key to `Workspace.layout_flip` | same tests; proposed: `komorebi-settings` or core test that loads a workspace config with `layout_flip` and checks the field | S | med | +| padding (7) | workspace/container padding moves and shrinks tiles, setting back restores | A now | `e2e_layouts.rs` `the_workspace_padding_moves_the_tiles_in...`; existing `update_shared.rs` `the_padding_of_the_workspace_wins_over_the_monitors_even_when_it_is_zero` | S | med | +| tiling (6), closing (5), minimizing (4), floating (7) | windows share the area; a leaving container (closed/minimized/floated) gives the others room | A now (room) + A (floating/removal): `workspace_layers.rs` floating_* , `workspace_containers.rs` removing_*; C: the OS event | `e2e_layouts.rs` `removing_a_container_gives_the_others_more_room` | S | med | +| stacks (23) | stack/cycle-stack/unstack: one tile per stack, window in view has focus, others away | A: core `workspace_containers.rs` `stacking_*`, `unstacking_*`, `container_behaviour.rs` hide/restore; now `e2e_layouts.rs` `a_stack_is_one_tile`. B: `cycle-stack` has no shared method (daemon-side) | S | med (23 checks, 3 min) | +| tiling_off (6) | toggle-tiling leaves windows, tiling again tiles | A now | `e2e_layouts.rs` `a_workspace_with_tiling_off_places_nothing...`; `update_shared.rs` `a_workspace_that_is_not_tiling_prunes_and_places_nothing` | S | low | +| monocle (12) | monocle fills area, others away, toggle back; focus behaviours | A: `workspace_layers.rs` `toggling_monocle_*`, `reintegrating_*`, `cycling_monocle_*`; `update_shared.rs` `a_monocle_container_gets_the_work_area_less_every_padding`. Focus behaviour is daemon-side (B, needs seam) | - | - | med | +| maximizing (29) | toggle-maximize, unmaximize on float, monocle wins | A: `workspace_layers.rs` `floating_the_maximized_window_*`, `update_shared.rs` `the_monocle_container_wins_over_a_maximized_window`; user-maximize event C | - | - | med | +| promoting (4), moving (4), focus (7) | promote first tile, swap/cycle-move, focus order | A: `workspace_containers.rs` `promoting_*`, `swapping_containers_*`, `cycling_wraps_*`, `directions_follow_the_layout_and_the_flip`; focus OS agreement C | - | - | low | +| workspaces (8), workspace_moves (8) | send/move/focus workspace, last-workspace | A: `monitor_workspaces.rs` (focus, last focused, ensure, remove); the OS hide/show is C | - | - | med | +| commands (265, 7.6 min) | every komorebic command leaves the daemon alive, answers state, manages every window | A now for command line (`crates/komorebic-core/tests/e2e_sweep.rs`: every SWEEP/PRINTED line is a Windows command; macOS lacks exactly 8) and for the KDE model (`komorebi-for-kde/komorebi/tests/command_sweep.rs`, about 185 messages, 0.2 s); B: same sweep for the Windows and macOS daemons (needs seam, below); C: stall-family (daemon busy 8 s), socket answering | S done / L for Win+mac | highest: biggest, flakiest scenario | +| unknown_monitor (12) | a window sent to a monitor that does not exist stays managed | B: shared `Monitor`/`Workspace::add_container` errors are covered (`monitor_workspaces.rs` `adding_a_container_to_a_workspace_that_is_not_there_is_an_error`); the daemon handler is per platform: needs seam | M | med (known flaky marker) | +| rules (12), rules_class (5), rules_exe (5), manage_rules (4), title_rule (5), startup_rules (5) | which window a rule catches (kind, strategy, composite, last wins, manage over ignore); the workspace it goes to | A now for matching, KDE copy only: `komorebi-for-kde/komorebi/tests/rule_matching.rs` (13 tests). Windows and macOS copies of `should_act_individual` untested natively (windows crate does not build on Linux; macOS needs the Mini). Workspace of a rule: A in core: `workspace_containers.rs` `initial_placement_rules_choose_where_a_new_window_goes`. When-evaluated (open vs rename), hide/show: C | M to move the function into `komorebi-config` and test once for three daemons (recommended seam) | high | +| state_fidelity (5) | state names title/exe/class/path as opened | A: `state_roundtrip.rs` (kfw/kfde fixtures, `the_fixtures_are_the_ones_the_e2e_library_has`, `a_windows_tiled_state_is_written_as_it_was_read`); what the OS reports C | - | - | low | +| queries (3) | `komorebic query X` answers from the state, resize save/load round trip | B: state answers per query are `StateQuery` handling in the daemon; resize round trip needs `process_command` (KDE: `resize.rs` `sizes_saved_to_a_file_are_loaded_back_from_it` A) | M | low | +| config_reload (8) | file change reloads names, layout, rules | A for the merge/reset semantics: `crates/komorebi-settings/tests/reload.rs` (`a_reload_merges_what_the_file_gives_and_resets_what_it_resets`), `src/handle.rs`; C: the file watch and the reload message dropped while the lock is held (the NEW failing check in gate5 is that mechanism) | - | - | med | +| placement (1 x 5 cases) | initial_window_placement_rules first/last/Nth | A: `workspace_containers.rs` `a_one_based_placement_index_is_zero_based_and_out_of_range_falls_back_after_the_focused`, `initial_placement_rules_choose_where_a_new_window_goes`. The known Windows failure (number 2) is a daemon event-path matter | - | - | low | +| scrolling (46) | strip, edges, columns, two monitors | A: `komorebi-scrolling/tests` (rules 80, tiles 40, heights 20, pan 16) and `update_shared.rs` `a_scrolling_workspace_*`; the resting window at an edge on the OS is C | - | - | med | +| resize_commands (7), resize (26) | resize-axis widens and gives back; edge drag | A: `resize_constraints.rs`, `update_shared.rs` `the_resize_constraints_are_enforced_before_the_layout_is_calculated`; B (S): `DefaultLayout::resize` increase then decrease is the identity (no test in `komorebi-layouts`); the pointer drag and client rounding C | S | med | +| pausing (4) | paused daemon ignores new windows | A: `komorebi-transport/src/pause.rs` (the message filter); the event filter is per daemon (B needs seam) | - | - | low | +| hotplug (11), monitors (13) | unplug/plug a display, windows move, send-to-monitor | A for the model in `monitor_workspaces.rs`; the reconcile is per platform (Windows `monitor_reconciliator`, macOS own): B needs seam; the display itself C | L | med | +| lifecycle (7), lifecycle_hidden (13), locking (7), handover (6), fullscreen (6), display_change (4), focus_follows_mouse (7) | stop/start restores windows, screen lock, minimize/unmanage/manage, fullscreen, mode change, pointer focus | A for hide/restore: `container_behaviour.rs` `restoring_*`, `workspace_layers.rs` `hiding_a_workspace_*`; the process, session, OS events and pointer are C | - | - | - | +| Windows extras: bar (21), windows_padding, cloaking, config_file, tracking, second_display, display_change | bar process and window, 7 px border, cloaking, file watch, system focus setting, QXL display | bar schema: A (`crates/komorebi-bar-core/tests/schema_oracle.rs`); rest C | - | - | - | + +## macOS-origin behaviour (never e2e-tested): what the shared tests now give + +macOS has no e2e. The shared-crate tests that exist protect its code path as far as the hooks do: +`state_roundtrip.rs` `a_macos_shaped_state_is_written_as_it_was_read_with_the_corner_last`, +`a_macos_state_cannot_be_read_without_its_corner`, the `StubWindow` that is `Clone` but not `Copy`, +and now `e2e_layouts.rs` (the tiles every macOS tiling goes through). Proposed B tests, platform +dependent and meant for the Mini: the hide-spot corner per monitor (`hide_spot` hook is +`StubState { spot }`) with `hide`/`restore` on a stack, and `komorebic-core` macOS command set +(`e2e_sweep.rs` pins which sweep commands macOS lacks). + +## KDE VM suites (33 suites with a test.py) + +All of them need a headless or Plasma KWin: C. The model parts of them are already native through +the KDE tests (`komorebi-for-kde/komorebi/tests`, about 880): `core-e2e` and `hotplug`, `placement`, +`workspace-rules`, `scrolling`, `stacks`, `user-maximize`, `commands`, `core-lock`, +`focus-follows-mouse`, `wallpaper` have a native model twin; `kwin*`, `check`, `module`, `keys-*`, +`look`, `features`, `rdp`, `render-smoke`, `latency`, `client-geometry`, `drag-resize`, +`live-resize`, `lock-sleep`, `run-kde`, `restart-survival`, `kwin-restart` are the compositor, the +session, keys, pixels or timing (C). The `commands` suite's sweep now has a native twin +(`command_sweep.rs`), so the suite can run a shorter sweep. + +## Counts + +Scenario rows: Windows/shared 43 scenarios + 7 Windows extras = 50. Classified by what is left to do +after this work: A (fully native for the shared logic, e2e only needed as a smoke) 22; A now (added by +this work) 9 of those (layouts, flipping, layout_flip, padding, tiling, closing, minimizing, floating, +tiling_off, stacks in part); B open 7 (commands for Windows/macOS daemons, unknown_monitor, queries, +hotplug reconcile, pausing event path, rules for Windows/macOS copies, resize identity); C only 21 +(lifecycle*, locking, display*, bar, extras, pointer, fullscreen, wallpaper rendering and the KDE +suites). KDE VM: 0 A fully, 33 C (about 10 with a native model twin). + +## Time saved + +The Windows gate is about 2.3 min per scenario for 35 scenarios (about 80 min), the KDE suites 15 +x 1-13 min. Honest estimate: + +- Today (what this work added): the arithmetic of layouts, flipping, layout_flip, padding, tiling + and the room checks is native. A guest still has to show the daemon hands the tiles to the OS, so + these scenarios shrink to one smoke each, or are merged into `tiling`: layouts (111 checks, about + 3 min) to one layout and 3 windows saves about 2 min; flipping, layout_flip, padding, + tiling_off, minimizing, closing, floating merged in `tiling` save about 7 x 2 = 14 min. About 16 + min of 80 (20%) on Windows, plus commands: the 7.6 min scenario keeps 20 commands as a smoke and + loses about 5 min once the Windows daemon is reachable by the sweep. +- If the B items existed (daemon model reachable natively for Windows and macOS, rule matching in + one shared function, config key tests): another 12 scenarios (rules, rules_class, rules_exe, + manage_rules, title_rule, startup_rules, state_fidelity, queries, config_reload, placement, + workspaces, workspace_moves) become one smoke each: about 25 min. Total about 45 min of the 80 min + gate (55%), and almost all the flaky checks (stall-family markers sit in commands, config_reload, + resize, maximizing, floating, which are the ones with timing). +- KDE VM: the model twins let `commands`, `placement`, `workspace-rules`, `hotplug`, `scrolling` + run with fewer cases; this is about 20-30 VM minutes of the 15 suites, not measured. + +Not saved: boot and golden image (3 s from a state), the C scenarios. + +## Seams that are missing (report only, nothing added) + +1. The daemon's `process_command` and `process_event` are per platform. A model-level + `CommandHandler<P>` in `komorebi-core` (taking `SocketMessage`, mutating `Monitor`/`Workspace`, + calling hooks) would let one sweep (`command_sweep.rs`) protect Windows and macOS: `commands`, + `unknown_monitor`, `queries`, `pausing`, `handover`, `moving`, `focus`, `monocle` focus behaviour. +2. `should_act` / `should_act_individual` three times: move into `komorebi-config` (it already has + `MatchingRule`, `MatchingStrategy`): one test file would replace the rule matching logic of rules, + rules_class, rules_exe, manage_rules, title_rule, startup_rules for all daemons. +3. Monitor reconciliation (Windows `monitor_reconciliator`, macOS own, KDE `reconcile.rs`) is not in + `komorebi-core`: a pure `reconcile(old: &[MonitorSnapshot], new: &[MonitorSnapshot]) -> Plan` + would make `hotplug` and `unknown_monitor` native. +4. `cycle-stack`, `cycle-stack-index`, `focus-stack-window` are daemon methods, not `Container` + methods; moving them into `komorebi-core::Container` would make the stacks scenario native + beyond the existing stack/unstack tests. +5. Event filtering while paused (`allowed_while_paused` is shared, the event path is not). + +## Tests added, with the e2e check each mirrors + +| Test file | Tests | Mirrors | +|---|---|---| +| `komorebi-layouts/tests/layouts_everywhere.rs` | 8 | layouts, flipping, layout_flip, padding, tiling, closing | +| `crates/komorebi-core/tests/e2e_layouts.rs` | 6 | layouts, flipping, layout_flip, padding, closing, minimizing, floating, stacks, tiling, tiling_off | +| `komorebi-for-kde/komorebi/tests/rule_matching.rs` | 13 | rules, rules_class, rules_exe, manage_rules, title_rule | +| `komorebi-for-kde/komorebi/tests/command_sweep.rs` | 1 (185 messages) | commands | +| `crates/komorebic-core/tests/e2e_sweep.rs` | 3 | commands | + +Each test says what stays e2e: the OS frame equals the tile, borders, event timing, the daemon's own +hooks. From 7bfaf6479d0978be1675bd62899c05f15488bcef Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 16:34:18 -0700 Subject: [PATCH 33/37] perf(nix): stamp the commit only into the final macOS package As for Windows and KDE: COMMIT_HASH was in the kfm commonArgs, so buildDepsOnly (about 1000 dependencies) and every kfm check got a new derivation for every commit and rebuilt in full on the Mac. commonArgs now has the constant "nix-check"; only fullBuild, and so packages.default and the extracted binaries, gets the real commit. Verified: the darwin clippy, nextest and deps attributes cannot be evaluated on this Linux host (a derivation of the stub source has to be built), so the drvPath table of the other attributes is the evidence; see the report. Needs a Mac build: after one cold build of the clippy check, a docs-only commit must be a cache hit. --- komorebi-for-mac/flake.nix | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/komorebi-for-mac/flake.nix b/komorebi-for-mac/flake.nix index 82634cc6..4ca2e262 100644 --- a/komorebi-for-mac/flake.nix +++ b/komorebi-for-mac/flake.nix @@ -143,7 +143,9 @@ cargoExtraArgs = "--locked ${packages}"; inherit src version; strictDeps = true; - COMMIT_HASH = self.rev or (pkgs.lib.removeSuffix "-dirty" (self.dirtyRev or "unknown")); + # 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"; nativeBuildInputs = [ pkgs.darwin.cctools ]; @@ -171,6 +173,7 @@ individualCrateArgs // { pname = "komorebi-workspace"; + COMMIT_HASH = self.rev or (pkgs.lib.removeSuffix "-dirty" (self.dirtyRev or "unknown")); } ); From f9b18a6f346a4e78c96161a55d6b22bcb62be89f Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:34:29 -0700 Subject: [PATCH 34/37] docs(tools): add tools/README.md and point build-and-test.md at the committed tools tools/README.md describes each tool, the tiered loops of fast-check (tier 1 cargo check and unit tests of the edited tree, tier 2 other-platform type-check or clippy, nix builds as the pre-landing gate), the prerequisites (jj, nix develop, jq, flock) and how the fake C compiler works for the macOS type-check. The measured warm times come from the host README and are dated 2026-10-31 (revision c89651fa). Personal progress-log and scratchpad references are removed. docs/dev/build-and-test.md gets a "Developer tools" section and links to tools/ where it named fast-check, kde-closure-check and the fake-CC command (the macOS block now says `tools/mac-check.sh`). Verified: links and commands read against the committed scripts; nothing else run. --- docs/dev/build-and-test.md | 24 ++++++-- tools/README.md | 112 +++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 4 deletions(-) create mode 100644 tools/README.md diff --git a/docs/dev/build-and-test.md b/docs/dev/build-and-test.md index c88fc533..cd145a19 100644 --- a/docs/dev/build-and-test.md +++ b/docs/dev/build-and-test.md @@ -29,6 +29,21 @@ shims `komorebic-linux`, `komorebic-macos`, `komorebi-client-linux`, `komorebi-c - Heavy builds and e2e should not run at the same time as a timing-sensitive e2e: the Windows `commands` scenario is the most sensitive (section 6). +## Developer tools + +`tools/` (README: [tools/README.md](../../tools/README.md)) holds the helper scripts, runnable from any jj +workspace of the repository; none of them writes to the source tree. + +| Command | Use | +|---|---| +| `tools/fast-check [--list] [--range \| --since REV]` | only the checks the touched paths need; warm in seconds (Windows clippy 8-9 s, KDE 1-3 s, macOS 2-3 s) | +| `tools/e2e-needed [--since REV]` | does this diff change the Windows e2e binaries (`NO` carries a previous passing e2e over) | +| `tools/kde-closure-check` | the KDE source filter list matches the KDE cargo closure | +| `tools/mac-check.sh` | macOS type-check on Linux (fake C compiler `tools/cc-fake.sh`) | +| `tools/trim-target`, `tools/gate-lock`, `tools/lite-env` | disk trimming, a heavy-gate lock, debug-info-off builds | + +The persistent target directories are under `$FAST_CHECK_SCRATCH` (default `~/.cache/komorebi-fast-check`). + ## 1. Windows (cross build from Linux via nix) Binaries (the flake cross-compiles to `x86_64-pc-windows-msvc` with an xwin SDK): @@ -48,7 +63,7 @@ nix build -L --no-link .#checks.x86_64-linux.komorebi-workspace-fmt .#checks.x86 nix build -L --no-link .#checks.x86_64-linux.e2e-tests # the Python of the e2e (pytest), no guest needed ``` -Quick loop without nix (what `fast-check` runs; clippy of the Windows tree from the nix dev shell): +Quick loop without nix builds (what `tools/fast-check` runs; clippy of the Windows tree from the nix dev shell): ```sh nix develop --command cargo clippy --workspace --locked --all-targets -- -D warnings @@ -77,7 +92,7 @@ A single test file: `cargo test -p komorebi-linux --test NAME` (the files are in The `-p komorebi --lib` that older notes use is the thin binary package now: the unit tests are in `komorebi-linux`. -Run `tools/kde-closure-check` after any dependency change in the KDE tree or the crates it uses: the KDE +Run `tools/kde-closure-check` (see [tools/README.md](../../tools/README.md)) after any dependency change in the KDE tree or the crates it uses: the KDE flake takes only the crates listed in `komorebi-for-kde/nix/root-crates.json`. KDE nix checks (no VM): from the root flake they are prefixed `kfde-`, and the VM checks are left out: @@ -147,10 +162,11 @@ and `komorebi-bar-macos` still build alone). Before any change that touches macO the Mac first: nothing else can run them. After that walk [macos-handcheck.md](macos-handcheck.md). On Linux, macOS can only be type-checked, through a fake C compiler and the target -`aarch64-apple-darwin` (`tools/fast-check` does it; it cannot link or run): +`aarch64-apple-darwin`: `tools/mac-check.sh` does it unconditionally, `tools/fast-check` when macOS files changed +(fake compiler: `tools/cc-fake.sh`); it cannot link or run: ```sh -COMMIT_HASH=dev cargo check --target aarch64-apple-darwin --workspace --all-targets # with CC_aarch64_apple_darwin set to a fake cc +tools/mac-check.sh # = COMMIT_HASH=dev cargo check --target aarch64-apple-darwin ... --all-targets, CC set to tools/cc-fake.sh ``` Nix, on a Mac: the checks of `komorebi-for-mac/flake.nix` (`komorebi-workspace-{clippy,fmt,toml-fmt,deny,nextest}`, diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 00000000..4939e7dd --- /dev/null +++ b/tools/README.md @@ -0,0 +1,112 @@ +# tools/ + +Developer tools for the three-platform workspace (Windows, KDE, macOS). They are bash scripts that only read +the repository (and `jj`), write persistent cargo target directories outside it, and never commit or push. +Run them from anywhere inside a jj workspace of the repository. + +Prerequisites: `jj`, `nix` with flakes (`nix develop`, `nix shell nixpkgs#gcc`), `jq`, `bash`, `flock` (only +for gate-lock). The Windows check runs through the dev shell of the root flake (`nix develop`, which provides +the xwin cross toolchain), so it needs no Windows host. `shellcheck` and `bash -n` are clean on every script. + +| tool | what it does | +|---|---| +| `fast-check` | runs only the checks the touched paths need (tiers below) | +| `mac-check.sh` | the macOS type-check on Linux, unconditionally (the macOS step of `fast-check`) | +| `cc-fake.sh` | the fake C compiler `mac-check.sh` and `fast-check` use for `aarch64-apple-darwin` | +| `kde-closure-check` | fails when `komorebi-for-kde/nix/root-crates.json` and the KDE cargo closure differ | +| `e2e-needed` | says whether a diff touches anything the Windows e2e binaries are built from | +| `trim-target` | deletes stale test executables from the persistent target directories | +| `gate-lock` | a host-wide FIFO lock for heavy gates (optional) | +| `lite-env` | source it to build with debug info off (optional) | + +## fast-check + +`tools/fast-check [--list] [--range | --since REV]`. It reads `jj diff --name-only` of `@` (`--range`: +`trunk()..@`; `--since REV`: `REV..@`), runs only the checks the touched paths need, prints the time of each +check, and exits non-zero on failure. `--list` is a dry run. An empty `@` runs nothing: use `--since`. + +The loops are tiered: tier 1 is the seconds-long cargo check and unit tests of the tree you edit, tier 2 the +type-check or clippy of the other platforms, and the nix builds (below) are the pre-landing gate, not part of +this tool. + +| touched | check (tier) | +|---|---| +| `komorebi-for-kde/**` | `cargo check`, `cargo test --lib` and `--test schemas -- --test-threads=1` of the KDE daemon package (1) | +| `komorebi-for-mac/**` | `cargo check --target aarch64-apple-darwin --all-targets` with the fake CC; type-check only, cannot link or test (2) | +| root Windows tree (`komorebi*/`, `e2e/`, `Cargo.*`) | `nix develop --command cargo clippy --locked --all-targets -- -D warnings` (2) | +| `komorebi-layouts/`, `komorebi-scrolling/` | native `cargo test` of both plus the Windows check | +| `crates/**` | native tests, plus the KDE, macOS and Windows checks | +| `*.nix`, `flake.lock` | evaluation only: `nix flake show` and `nix eval ...drvPath` of the named checks (no `nix flake check`) | +| `*.md`, `docs/`, `tools/`, images, `.github` | nothing | + +Persistent target directories live under `$FAST_CHECK_SCRATCH` (default `${XDG_CACHE_HOME:-~/.cache}/komorebi-fast-check`): +`target-fast-win` (2.8 GB), `kde-target` (shared, 30 GB, grows with test binaries: `tools/trim-target`), +`target-fast-mac` (2.2 GB), `target-fast-native` (0.5 GB). Delete them to reclaim disk; the next run is cold. + +Measured warm times (2026-10-31, jj revision c89651fa, WSL2 host): Windows clippy 8-9 s, KDE check 1-3 s and +`--lib` 1.4 s, macOS 3 s (`-p komorebi`) / 2 s (workspace), native 2-3 s. On a busy host run it under +`nice -n 19` with `CARGO_BUILD_JOBS=2`. + +Caveats + +- Windows clippy here is NOT the pre-landing gate: still run `nix build .#checks.x86_64-linux.komorebi-workspace-clippy` + (about 3.5 min) before landing; it uses crane's filtered source and catches filter bugs. +- macOS needs `COMMIT_HASH` (the tools set `dev`) when there is no `.git`. +- In a jj workspace without `.git`, `nix flake check --no-build` fails with `attribute 'dirtyRev' missing`, and it + evaluates every check (15-16 GB). `fast-check` therefore evaluates attributes with `nix flake show` and `nix eval`. +- KDE `tests/schemas.rs` shares a pid-only socket path; keep `--test-threads=1`. +- Single KDE test file: `CARGO_TARGET_DIR=$FAST_CHECK_SCRATCH/kde-target nix shell nixpkgs#gcc -c cargo test -p komorebi-linux --test <name>`. + +## macOS type-check (mac-check.sh, cc-fake.sh) + +macOS cannot be built, linked or tested on Linux. `tools/mac-check.sh [cargo args]` runs +`cargo check --target aarch64-apple-darwin --all-targets` inside `nix shell nixpkgs#gcc nixpkgs#pkg-config nixpkgs#openssl.dev` +with `CC_aarch64_apple_darwin=tools/cc-fake.sh`. The `-sys` crates' build scripts call the C compiler for the +Darwin target, which does not exist here; `cc-fake.sh` turns every compile into an empty object (preprocessing +`-E` goes to the real `gcc`) so the build scripts "succeed" and rustc type-checks the macOS code. It proves the +code type-checks, nothing about behaviour. `fast-check` uses the same script when macOS files change. + +## kde-closure-check + +`tools/kde-closure-check [repo]` (2 s) compares `komorebi-for-kde/nix/root-crates.json` (the root crates the KDE +flake's source filter takes) with `cargo metadata` / `cargo tree` of the KDE packages. Run it after any +`Cargo.toml` dependency change in the KDE tree or in the crates it uses; it exits 1 and prints the differences +when the list is stale (a stale list breaks the KDE nix build or rebuilds the VM suites needlessly). + +## e2e-needed + +`tools/e2e-needed [--range | --since REV] [--to REV] [--closure]` answers whether a diff can change +`komorebi.exe`, `komorebic.exe` or `komorebi-testwin.exe` (the Windows e2e inputs): the source directories of the +workspace crates they depend on (`cargo tree --offline --target x86_64-pc-windows-msvc`, 1-2 s, no build), files +pulled in by `include_str!`/`include!`, fixed inputs (`Cargo.lock`, root `Cargo.toml`, `rust-toolchain.toml`, +`flake.nix`, `flake.lock`, build scripts) and the harness (`e2e/`). `NO` means a passing e2e of the previous +binaries carries over; `YES` lists the files that decided it; files it does not understand count as YES. It +does not cover nextest, clippy, the bar screenshot, the KDE VM or the schema oracles. + +## trim-target + +`tools/trim-target [MINUTES]` (default 45) removes test executables not touched for that long from the +persistent target directories (a debug test binary is about 290 MB; the KDE target grew from 30 GB to 109 GB in +one evening without this). They are rebuilt on demand. + +## gate-lock (optional) + +A host-wide FIFO lock for heavy gates so two of them never run at once and a timing-sensitive run (Windows +e2e, KDE `commands`/`core-e2e`) is not disturbed. Bash plus `flock`; state in `${XDG_STATE_HOME:-~/.local/state}/komorebi-gate` +(`GATE_LOCK_DIR` overrides). + +``` +tools/gate-lock run --class heavy --label "clippy" --est 5 -- nix build -L --no-link .#checks.x86_64-linux.komorebi-workspace-clippy +tools/gate-lock run --class timing --label "win e2e" --est 60 --idle-load 3 -- nix run .#e2e-windows -- ... +tools/gate-lock run --class light -- cargo check -p komorebi # never waits; throttled while a timing gate is held +tools/gate-lock status [--short] | wait [--max SEC] | history [N] | adopt PID +``` + +`light` never waits (it runs `nice -n 19` with `CARGO_BUILD_JOBS=${GATE_LIGHT_JOBS:-3}` while a timing gate is +held), `heavy` and `timing` queue FIFO. It cannot stop work that does not use it and does not pin CPUs. + +## lite-env (optional) + +`. tools/lite-env` sets `CARGO_PROFILE_DEV_DEBUG=0`, `CARGO_PROFILE_TEST_DEBUG=0`, `CARGO_INCREMENTAL=0` (unless +already set) and `CARGO_BUILD_JOBS=3`: same code and tests, far smaller test binaries and less disk write. +Panic backtraces lose line numbers. Use a separate `CARGO_TARGET_DIR` (the first build is cold). Not for nix builds. From 278ef8f3fc2c908364f3b2e8f83d7e256ed1dd5d Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:44:08 -0700 Subject: [PATCH 35/37] docs(settings): S4 and S5 as landed, macOS hand-check section F docs/dev/settings.md section 10: what S4 and S5 moved, the differences between the daemons that were kept on purpose (KDE resets transparency keys on load and Windows keeps them; Windows animates a kind when the global flag is on or the per-kind value is true, KDE and macOS let the per-kind value win; the scoped guard on KDE, the suspend counter on macOS, the Windows shutdown write). docs/dev/macos-handcheck.md section F (appended, nothing else changed): the Mac checks for S3 and S5. Verified: not applicable (documentation). --- docs/dev/macos-handcheck.md | 8 ++++++++ docs/dev/settings.md | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/docs/dev/macos-handcheck.md b/docs/dev/macos-handcheck.md index 8513a57d..758335ac 100644 --- a/docs/dev/macos-handcheck.md +++ b/docs/dev/macos-handcheck.md @@ -148,3 +148,11 @@ F. In `window.rs` `AdhocWindow::hide` / `Window::hide` duplicate the restore-pos ## 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. + +## F. Settings: S3 and S5 (wip-u-settings3 and earlier), appended by the settings agent + +Type-check and clippy only; nothing here ran on a Mac. The settings now live in `settings()` (one snapshot per use); the process-wide statics for these groups are gone. + +1. **S3 groups (paddings, floating aspect ratio, `layout_defaults`, `display_index_preferences`).** Config with `default_workspace_padding` 20 and `default_container_padding` 15: tiles 20 px from the work area, 15 apart. Reload with the key dropped: padding stays (merge); set it to 5 and reload: 5. `layout_defaults`: set, reload, workspaces use it; remove and reload: they fall back (the key resets). Aspect ratio: `toggle-float` with centring uses the configured ratio; remove the key and reload: 4:3 (Standard). `display_index_preference 0 <serial>`: monitor order follows it. Reload during a drag or workspace switch: no one-frame flash of half-new padding. +2. **S5 animation (BEHAVIOUR: one snapshot for enabled, duration, style and fps).** Animation on (`komorebic animation true`), switch workspace: transition plays. While a transition runs, `komorebic animation-duration 1000`, then `animation-style`, then `animation false`: the running transition is not torn (no mix of old duration with new style), the next one follows the new values. Per-kind: `animation true --movement`, `animation false` (global): per-kind values are cleared by a global value, so movement is off again. Reload a file with `"animation": {"enabled": {"movement": true}}`: only movement animates and the global flag is untouched; reload a file with `"animation": {"enabled": true}` (no fps): fps back to 60; reload a file with no animation block: all animation settings keep their values. `komorebic animation-fps 30` then watch frame cadence. Stack a window (`stack`): no animation during the stack (the `suspend()` counter, unchanged), and animation is back after it, including after a stack command that fails. +3. The border and transparency groups (S6, S4) are not moved on macOS: transparency does not exist there. diff --git a/docs/dev/settings.md b/docs/dev/settings.md index da70d486..e7442380 100644 --- a/docs/dev/settings.md +++ b/docs/dev/settings.md @@ -332,3 +332,28 @@ all three daemons: statics removed, `apply_globals` applies them with one `Handl `display_index_preferences()`), each a clone from one snapshot. The only BEHAVIOUR is the single publish. Note the KDE integration test harness (`tests/config.rs`) now resets the paddings through `settings()`; it is the oracle that loads configurations over a fake desktop. + +## 10. S4 and S5 as landed on `wip-u-settings3`, and what writing them showed + +S4 (transparency enabled and alpha; KDE and Windows, macOS has none) and S5 (animation) moved the groups +with their writers and readers, KDE first, then macOS (S5 only), then Windows. Per-revision gates are in +the commit bodies. Differences between the daemons that the migration keeps, and that a later unification +must decide on purpose: + +* **Transparency on load:** KDE resets both keys when absent (`unwrap_or(false)`, `unwrap_or(200)`); + Windows keeps the value. Both go through `SharedDelta::apply`; KDE builds its delta with `Some(unwrap_or(..))`. + (The earlier table in section 2.1 said "kept" for both: corrected here.) +* **When is a kind of animation on?** KDE and macOS: the per-kind value wins over the global one + (`Animation::motion_for`). Windows: the global flag OR a per-kind true (a per-kind false does not turn off a + global true), for window moves and the transparency animation; its workspace-transition helpers keep the + per-kind-wins rule. The Windows accessors (`animation_enabled_for`, `animation_for`) encode its rule. +* **Save-and-restore of the global animation flag:** KDE's stacking commands now hold + `settings::animation_off()` (`Handle::scoped` on the global flag only, as the old swap did: per-kind values + are not suspended), which also restores on an early error return. macOS keeps its `suspend()` counter + (suspends every kind). Windows has no such write in the daemon; its shutdown path is the permanent + `animation_off_for_good()`. Windows `WINDOW_HANDLING_BEHAVIOUR` moved to `WindowsSettings` and its one + save-and-restore (the border paint test) uses `scoped`. +* The old Windows window-move code held the per-kind enabled map's lock for the rest of the function while + animating; it now takes one snapshot and holds nothing. + +S6 (borders) is next and is not started. From 7b070fffdaee91bf664d0e3e7b8a1489e52ed3c1 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:47:00 -0700 Subject: [PATCH 36/37] docs: KDE and macOS window_manager.rs and router after the converge, and the blockers docs/dev/core-model.md section 20: what the converge batch did (two platform accessors, eleven macOS arms onto KDE's named methods), where the two daemons stand (137 of 155 router arms byte-identical, 45% of KDE's window_manager function lines identical with macOS), why it is below the 60% bar (macOS's ContainerExt against the shared Container with a hiding spot, the ? against let _ policy, the platform entry points, the one-sided functions) and the four blockers with the recommended next step. Verified: not applicable (documentation); counts from the arm and function comparison at this tip. --- docs/dev/core-model.md | 54 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/docs/dev/core-model.md b/docs/dev/core-model.md index af0c3480..3cff818d 100644 --- a/docs/dev/core-model.md +++ b/docs/dev/core-model.md @@ -1317,3 +1317,57 @@ would move less than half of the file. wrongly called this an improvement). `WorkspacePlatform::begin_pass` is called once per pass after the layout is computed and its answer reaches the hooks as `Placement::pass`; Windows takes the snapshot there and `place_container` reads it, as the original did. + +## 20. KDE and macOS: the converge of `window_manager.rs` and the router, and why `WindowManager<P>` still waits + +Measured at the tip of `wip-u-wm` (cand5 plus the revisions below; no Windows file changed). + +**Done (refactors, no behaviour change):** both daemons ask `window::foreground_window_id()` and +`window::monitor_id_at_cursor()` instead of calling the backend or `MacosApi` inline (the macOS +`window.rs` gets the two one-line wrappers); twelve macOS `process_command` arms (eleven methods) that were the +same code inline as KDE's named methods now call methods with those names and bodies +(`cycle_focus_workspace`, `cycle_focus_empty_workspace`, `close_workspace`, +`move_container_to_last_workspace` for both the move and the send arm, `eager_focus`, +`set_border_colour`, `set_layout_ratios`, `answer_query`, `add_named_workspace_rule`, +`add_initial_named_workspace_rule`, `toggle_workspace_window_container_behaviour`). + +**Where it stands:** + +| | KDE against macOS | +|---|---| +| router arms present in both | 155 | +| of them byte-identical | 137 | +| of them different | 18: `Close`, `Minimize` (macOS window API), `DebugWindow`, `ManageRule`, `IgnoreRule`, `SessionFloatRule` (macOS identifies an application by role where KDE uses the class), `ReplaceConfiguration` (the run loop; no warning on macOS), `AddSubscriberPipe`, `ToggleWorkspaceLayer` (88 lines inline on macOS), `ResizeWindowAxis` (59 inline), the stack and unstack arms and `CycleStack*`, `FocusStackWindow` (KDE switches animations off around them), `ResizeWindowEdge` (1 line) | +| `window_manager.rs` function lines identical with macOS | 1156 of KDE's 2595 (45%); 105 functions on macOS, 97 on KDE | + +The 45% is below the 60% bar, and what separates the rest is not text: +- **the hiding spot and the container API.** macOS calls `container.hide_on(spot, omit, screen)`, + `load_focused_window_at(spot)?` and `restore_focused_window()?`, its own `ContainerExt`, where KDE and + the shared crate have `Container::hide(omit, spot)`, `load_focused_window(spot)` and `restore()`; nine + window manager functions (`add_window_to_container`, `cycle_container_window_*`, `focus_container_window`, + `stack_all`, `monocle_on/off`, `cycle_monocle`, `transfer_window`) differ in exactly these calls; +- **the error policy:** KDE writes `let _ = container.load_focused_window(())` (its window operations + cannot fail), macOS writes `...?` (AX calls can); the shared form is `?`, which is equivalent on KDE + because its operations always answer `Ok`; +- **platform entry points:** `init`, `stop`, `new`, `focus_workspace`, `manage_focused_window`, + `unmanage_focused_window`, `restore_all_windows`, `enforce_workspace_rules`, `resize_window` (52 + lines), `move_container_to_monitor`, `focus_floating_window_in_direction` (29); +- **one-sided functions:** macOS 16 (the live-resize family, `entering_borders`, `workspace_transition`, + `drag_origin`), KDE 4 (`adopt_maximize_change`, `adopt_workspace_change`, `sync_workspace_desktops`, + `reap_invalid_windows`). + +**Blockers for a `WindowManager<P>` over KDE and macOS (Windows keeps its own):** +1. macOS's `ContainerExt` (`hide_on`, `load_focused_window_at`, `restore_focused_window`) against the + shared `Container` with a `HideSpot`: kfm converges the container first (its semantics: AX errors, + `cfg!(test)` guards) so that the nine functions become identical; +2. the `?` against `let _` policy, then a mechanical KDE edit; +3. the eleven platform entry points above as `WindowManagerPlatform` hooks (`init`, `stop`, `new`, + `focus_workspace`, `restore_all_windows`, ...), which is as many hooks as functions moved, so the + shared text would be about half of the file with a dozen hooks: not worth it yet; +4. the 18 differing router arms, of which the stack family (animation guard) and the application + identity (role against class) are hooks and the rest are macOS's own bodies. + +Recommended next step: kfm unifies the container API (blocker 1) and the `?` policy (2) on both +daemons; after that the nine functions are identical and the shared share passes 60% without new +hooks, and `WindowManager<P>` can be created over KDE and macOS with the entry points of blocker 3 left +in each daemon's extension trait. From b212b554cdeead92f75ad73615f36f10335d2f68 Mon Sep 17 00:00:00 2001 From: LGUG2Z <LGUG2Z@fastmail.com> Date: Sat, 31 Oct 2026 15:40:40 -0700 Subject: [PATCH 37/37] docs(dev): macOS hand-check rows for the bar clicks and a list of findings needing a decision macos-handcheck.md gets section F (rows M1-M3) for the battery, CPU/network and update clicks fixed in the two preceding revisions (appended, the file is kfm's). known-issues.md is new: four findings that are not fixed because whether they are bugs, or the fix, is the owner's call, each with evidence (file and line), why it may or may not be a bug, the platforms and a proposed fix: KDE FocusWorkspaceNumber/Numbers/LastWorkspace without the pointer monitor preamble, Monitor::focus_workspace overwriting a workspace name, remove_container focusing focused-1, and the macOS subscriber push without a write timeout. Docs only. The line references were read in this tree (pointer-monitor preamble compared between the Windows and KDE process_command.rs); nothing was run. --- docs/dev/known-issues.md | 31 +++++++++++++++++++++++++++++++ docs/dev/macos-handcheck.md | 8 ++++++++ 2 files changed, 39 insertions(+) create mode 100644 docs/dev/known-issues.md diff --git a/docs/dev/known-issues.md b/docs/dev/known-issues.md new file mode 100644 index 00000000..f0ba8ea6 --- /dev/null +++ b/docs/dev/known-issues.md @@ -0,0 +1,31 @@ +# Known issues that need a decision + +Findings of the consolidation reviews and tests that are NOT fixed because whether they are bugs, or how to fix them, is a decision for the owner. Each has the evidence, why it may or may not be a bug, the platforms, and a proposed fix. Paths are relative to the repository root at the time of writing and may have moved. + +## 1. KDE FocusWorkspaceNumber, FocusWorkspaceNumbers and FocusLastWorkspace skip the pointer-monitor preamble + +- **Evidence**: komorebi-for-kde/komorebi/src/process_command.rs lines 1245-1277: the arms for the three messages call `focus_workspace` on the focused monitor directly. The Windows daemon (komorebi/src/process_command.rs:972-987 for `FocusWorkspaceNumber`, and lines about 2185 and 2215 for the helpers behind `FocusLastWorkspace` and `FocusWorkspaceNumbers`) first checks `monitor_idx_from_current_pos()`: when the pointer is on another monitor whose focused workspace is empty, that monitor becomes the focused one. KDE has the same preamble only in `cycle_focus_workspace` (line 897-909). +- **Why it may be a bug**: on a secondary monitor with an empty workspace and the pointer on it, `focus-workspace 2` switches the workspace of the monitor that was focused before, not the one the user is pointing at, unlike on Windows and unlike KDE's own `cycle-focus-workspace`. **Why not**: KWin may not report an empty monitor as pointed at the same way; the KDE tests do not cover it, so it may have been left out on purpose. +- **Platforms**: KDE only (the Windows and macOS daemons are not known to be affected; not checked on macOS). +- **Proposed fix**: add the preamble to the three arms, with a KDE unit test that the monitor under the pointer becomes the focused one; needs the owner to say which behaviour is intended. + +## 2. Monitor::focus_workspace overwrites an existing workspace name + +- **Evidence**: crates/komorebi-core/src/monitor.rs:159-165, `Monitor::focus_workspace`: on every focus it sets the workspace name to the platform's known name for that index, replacing a name the user or a rule gave the workspace. Pinned as-is by crates/komorebi-core/tests/monitor_workspaces.rs. +- **Why it may be a bug**: a workspace renamed at runtime (`workspace-name`) loses its name the next time it is focused. **Why not**: the original Windows and KDE code did exactly this (the name table is the source of truth there); it only matters where names can differ from the table. +- **Platforms**: all three (shared code, inherited unchanged from the Windows tree). +- **Proposed fix**: only fill the name when the workspace has none; a behaviour change on all three daemons, so it needs the Windows e2e (`workspace`/`commands` scenarios) before landing. + +## 3. Workspace::remove_container focuses the container before the focused one, not before the removed one + +- **Evidence**: crates/komorebi-core/src/workspace.rs:1011-1016, `remove_container`, calls `focus_previous_container` (lines 796-799), which focuses `focused_container_idx() - 1` (saturating) after the removal, whatever index was removed. Pinned by crates/komorebi-core/tests/workspace_containers.rs (around line 240). +- **Why it may be a bug**: closing a container that is not the focused one (a background window closes) moves the focus to a container next to the focused one rather than keeping the focused container focused. **Why not**: with the usual flow the removed container is the focused one, where both rules agree, and the original Windows code behaves identically. +- **Platforms**: all three (shared code). +- **Proposed fix**: when the removed index is below the focused one, decrement the focus by one; when it is above, leave it; when it is the focused one, focus the previous container. A behaviour change on all three, needing the Windows e2e (close scenarios) first. + +## 4. Subscriber pushes have no write timeout on macOS + +- **Evidence**: the macOS daemon's subscriber push (no write timeout in the subscriber send; see the macOS review notes in docs/dev/macos-handcheck.md): a stopped bar that does not read its socket wedges the daemon once the socket buffer is full. +- **Why it may be a bug**: a daemon must not hang on a client. **Why not fixed**: the Windows review showed that a write timeout can truncate a notification mid-message, so the naive fix is worse. +- **Platforms**: macOS (and the same shape on KDE, not verified). +- **Proposed fix**: write the notification from a per-subscriber thread or channel with a drop-the-subscriber policy; needs a design decision. diff --git a/docs/dev/macos-handcheck.md b/docs/dev/macos-handcheck.md index 8513a57d..7f098a8f 100644 --- a/docs/dev/macos-handcheck.md +++ b/docs/dev/macos-handcheck.md @@ -148,3 +148,11 @@ F. In `window.rs` `AdhocWindow::hide` / `Window::hide` duplicate the restore-pos ## 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. + +## F. Bar clicks (system tools) + +Run on the Mac with the unified bar; the unit tests for the argv are `cargo test -p komorebi-bar system_tool` and `release_page`. + +- **M1. Battery widget click**: opens System Settings on the Battery pane (`open x-apple.systempreferences:com.apple.Battery-Settings.extension`, macOS 13 or later). If it opens System Settings elsewhere, or nothing, the pane id is wrong for that macOS version: write down the version and what opened. Before the fix the click did nothing visible (it tried `cmd.exe`). +- **M2. CPU and memory widget click**: opens Activity Monitor (unchanged); the network widget click opens the Network pane; a storage widget click opens the folder in Finder. +- **M3. Update widget**: with an installed version older than the latest komorebi-for-mac release the widget shows the new version; click opens `https://github.com/LGUG2Z/komorebi-for-mac/releases/tag/v<version>` in the default browser (not the Windows repository). After 12 hours (or with `data_refresh_interval` set to a small value) the widget still compares against komorebi-for-mac releases, never Windows ones (the refresh used to poll the Windows repository).