diff --git a/Cargo.lock b/Cargo.lock index b3b7ce90..c051a910 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3565,6 +3565,7 @@ dependencies = [ "komorebi-layouts", "komorebi-protocol", "komorebi-themes", + "regex", "schemars 1.2.3", "serde", "serde_json_lenient", diff --git a/crates/komorebi-bar-core/tests/config.rs b/crates/komorebi-bar-core/tests/config.rs new file mode 100644 index 00000000..aceacf5d --- /dev/null +++ b/crates/komorebi-bar-core/tests/config.rs @@ -0,0 +1,130 @@ +//! The configuration of the bar without a window: what is accepted, what is skipped on a +//! platform that cannot run a widget (D-coord-1: accepted and skipped with a warning), and the +//! `mouse` messages. + +use komorebi_bar_core::config::KomobarConfig; +use komorebi_bar_core::config::MouseMessage; +use komorebi_bar_core::widgets::komorebi_config::KomorebiLayout; +use komorebi_bar_core::widgets::network_config::NetworkConfig; +use komorebi_bar_core::widgets::widget::WidgetConfig; + +const WINDOWS: bool = cfg!(target_os = "windows"); + +fn parse(json: &str) -> KomobarConfig { + serde_json::from_str(json).expect("the configuration parses") +} + +const MIXED: &str = r#"{ + "left_widgets": [ + {"Komorebi": {"workspaces": {"enable": true, "hide_empty_workspaces": false}, "layout": {"enable": true}}}, + {"Keyboard": {"enable": true}} + ], + "center_widgets": [{"Media": {"enable": true}}], + "right_widgets": [ + {"Storage": {"enable": true}}, + {"Time": {"enable": true, "format": "TwentyFourHour"}}, + {"Systray": {"enable": true}}, + {"Cpu": {"enable": false}} + ], + "mouse": {"on_middle_click": "echo hi", "on_extra2_click": {"message": {"type": "Retile"}}} +}"#; + +fn all(config: &KomobarConfig) -> Vec<&WidgetConfig> { + config + .left_widgets + .iter() + .chain(config.center_widgets.iter().flatten()) + .chain(config.right_widgets.iter()) + .collect() +} + +#[test] +fn windows_only_widgets_are_accepted_on_every_platform() { + let config = parse(MIXED); + assert_eq!(all(&config).len(), 7); + assert!(config.mouse.is_some()); +} + +#[test] +fn a_widget_the_platform_cannot_run_is_named_and_not_enabled() { + let config = parse(MIXED); + let unsupported: Vec<_> = all(&config) + .into_iter() + .filter_map(|w| w.unsupported()) + .collect(); + if WINDOWS { + assert!(unsupported.is_empty()); + } else { + assert_eq!(unsupported, ["Keyboard", "Media", "Systray"]); + } + + let enabled: Vec = all(&config).iter().map(|w| w.enabled()).collect(); + // Komorebi, Keyboard, Media, Storage, Time, Systray, Cpu (disabled) + let expect = [true, WINDOWS, WINDOWS, true, true, WINDOWS, false]; + assert_eq!(enabled, expect); +} + +#[test] +fn a_command_mouse_message_is_a_plain_string() { + let config = parse(MIXED); + let mouse = config.mouse.expect("mouse"); + assert!(matches!(mouse.on_middle_click, Some(MouseMessage::Command(ref c)) if c == "echo hi")); + assert!(matches!( + mouse.on_extra2_click, + Some(MouseMessage::Komorebi(_)) + )); + assert!(mouse.has_command()); +} + +/// The scenario of the Windows e2e once wrote `{"Command": ...}`; it is not a message. +#[test] +fn a_tagged_command_is_rejected() { + let bad = r#"{"left_widgets": [], "right_widgets": [], + "mouse": {"on_middle_click": {"Command": "echo hi"}}}"#; + assert!(serde_json::from_str::(bad).is_err()); +} + +#[test] +fn the_network_widget_accepts_the_windows_only_interface_options() { + let json = r#"{"enable": true, "show_total_activity": false, "show_activity": true, + "default_interface_options": {"display_type": "Ipv4"}}"#; + let config: NetworkConfig = serde_json::from_str(json).expect("parses"); + assert!(config.default_interface_options.is_some()); + // the old spellings of the two required keys + let old = + r#"{"enable": true, "show_total_data_transmitted": true, "show_network_activity": false}"#; + assert!(serde_json::from_str::(old).is_ok()); +} + +#[test] +fn a_layout_is_read_from_its_name() { + let layout: KomorebiLayout = serde_json::from_str("\"BSP\"").expect("a default layout"); + assert!(matches!(layout, KomorebiLayout::Default(_))); + assert_eq!(layout.to_string(), "BSP"); + for (name, want) in [ + ("Monocle", "Monocle"), + ("Floating", "Floating"), + ("Paused", "Paused"), + ] { + let read: KomorebiLayout = serde_json::from_str(&format!("\"{name}\"")).unwrap(); + assert_eq!(read.to_string(), want); + } + assert!(serde_json::from_str::("\"Nonsense\"").is_err()); +} + +#[test] +fn read_fills_in_the_frame_and_keeps_what_was_set() { + let dir = std::env::temp_dir().join(format!("bar-core-config-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("bar.json"); + std::fs::write(&path, MIXED).unwrap(); + let config = KomobarConfig::read(&path).expect("reads"); + assert!(config.frame.is_some(), "a missing frame gets the default"); + assert_eq!(config.left_widgets.len(), 2); + assert!(config.mouse.is_some()); + // anything but json is refused + std::fs::write(dir.join("bar.toml"), MIXED).unwrap(); + let toml = dir.join("bar.toml"); + assert!(std::panic::catch_unwind(|| KomobarConfig::read(&toml)).is_err()); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/komorebi-config/Cargo.toml b/crates/komorebi-config/Cargo.toml index 432a1c74..0d672ee6 100644 --- a/crates/komorebi-config/Cargo.toml +++ b/crates/komorebi-config/Cargo.toml @@ -11,6 +11,7 @@ komorebi-themes = { path = "../../komorebi-themes" } clap = { workspace = true } color-eyre = { workspace = true } +regex = "1" serde = { workspace = true } serde_with = { version = "3.12", features = ["schemars_1"] } serde_json = { workspace = true, features = ["preserve_order"] } diff --git a/crates/komorebi-config/src/lib.rs b/crates/komorebi-config/src/lib.rs index a40e456b..6b0f7568 100644 --- a/crates/komorebi-config/src/lib.rs +++ b/crates/komorebi-config/src/lib.rs @@ -21,4 +21,5 @@ pub mod matching; pub mod placement; #[cfg(feature = "schemars")] pub mod platforms; +pub mod rules; pub mod static_config; diff --git a/crates/komorebi-config/src/rules.rs b/crates/komorebi-config/src/rules.rs new file mode 100644 index 00000000..e02bb656 --- /dev/null +++ b/crates/komorebi-config/src/rules.rs @@ -0,0 +1,374 @@ +//! Which of a list of rules a window matches. +//! +//! The evaluation every daemon shares: [`should_act`] returns the last rule of a list that matches +//! a window ([`RuleSubject`]: its title, executable, classes and path), a composite rule matching +//! when all of its conditions do, and [`should_act_individual`] decides one condition by its +//! matching strategy. A `Regex` id is looked up in a cache the daemon compiled when it loaded its +//! rules (an id with no compiled regex matches nothing); the cache is passed in so the lock that +//! guards it stays the daemon's. The one difference between the platforms is [`RuleQuirks`]. + +use std::collections::HashMap; + +use regex::Regex; + +use komorebi_protocol::types::ApplicationIdentifier; + +use crate::matching::IdWithIdentifier; +use crate::matching::MatchingRule; +use crate::matching::MatchingStrategy; + +/// What a window says about itself, as the rules see it +#[derive(Clone, Copy, Debug)] +pub struct RuleSubject<'a> { + pub title: &'a str, + /// The executable name; on Windows it carries the `.exe`, elsewhere it does not + pub exe_name: &'a str, + /// The window's classes; a `Class` condition holds when it holds for any of them. Windows has + /// exactly one + pub classes: &'a [&'a str], + pub path: &'a str, +} + +/// The differences between the platforms in how an id is read +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct RuleQuirks { + /// Remove every `.exe` from a rule id before comparing (also from a regex id, and so from the + /// key looked up in the regex cache): a rule written the Windows way names the same program + /// where executables have no suffix + pub strip_exe_from_ids: bool, +} + +impl RuleQuirks { + /// Windows: the id is compared as written + pub const WINDOWS: Self = Self { + strip_exe_from_ids: false, + }; + /// KDE and macOS: a `.exe` in the id is ignored + pub const UNIX: Self = Self { + strip_exe_from_ids: true, + }; +} + +#[allow(clippy::cognitive_complexity, clippy::too_many_lines)] +/// Returns the last of `identifiers` that matches the window, if one does: a simple rule matches +/// when its one condition does ([`should_act_individual`]), and a composite rule when all of its +/// conditions do +pub fn should_act( + subject: &RuleSubject, + quirks: RuleQuirks, + identifiers: &[MatchingRule], + regex_identifiers: &HashMap, +) -> Option { + let mut matching_rule = None; + for rule in identifiers { + match rule { + MatchingRule::Simple(identifier) => { + if should_act_individual(subject, quirks, identifier, regex_identifiers) { + matching_rule = Some(rule.clone()); + }; + } + MatchingRule::Composite(identifiers) => { + let mut composite_results = vec![]; + for identifier in identifiers { + composite_results.push(should_act_individual( + subject, + quirks, + identifier, + regex_identifiers, + )); + } + + if composite_results.iter().all(|&x| x) { + matching_rule = Some(rule.clone()); + } + } + } + } + + matching_rule +} + +#[allow(clippy::cognitive_complexity, clippy::too_many_lines)] +/// Returns true if and only if the condition `identifier` holds for the window +/// +/// The condition compares the title, the executable, any of the classes or the path with its id, +/// by its matching strategy. Without one, or with `Legacy`, a title or a class matches when it +/// starts or ends with the id, and an executable or a path when it is the id. A `Regex` id is +/// looked up in `regex_identifiers`, and an id with no compiled regex there matches nothing. +pub fn should_act_individual( + subject: &RuleSubject, + quirks: RuleQuirks, + identifier: &IdWithIdentifier, + regex_identifiers: &HashMap, +) -> bool { + let RuleSubject { + title, + exe_name, + classes, + path, + } = *subject; + let mut should_act = false; + + let stripped; + let identifier = if quirks.strip_exe_from_ids { + let mut copy = identifier.clone(); + copy.id = copy.id.replace(".exe", ""); + stripped = copy; + &stripped + } else { + identifier + }; + + match identifier.matching_strategy { + None | Some(MatchingStrategy::Legacy) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.starts_with(&identifier.id) || title.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.starts_with(&identifier.id) || class.ends_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.eq(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::Equals) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.eq(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.eq(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotEqual) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.eq(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.eq(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::StartsWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.starts_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.starts_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotStartWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.starts_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.starts_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::EndsWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.ends_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.ends_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotEndWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.ends_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.ends_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::Contains) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.contains(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.contains(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotContain) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.contains(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.contains(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::Regex) => match identifier.kind { + ApplicationIdentifier::Title => { + if let Some(re) = regex_identifiers.get(&identifier.id) + && re.is_match(title) + { + should_act = true; + } + } + ApplicationIdentifier::Class => { + if let Some(re) = regex_identifiers.get(&identifier.id) { + for class in classes { + if re.is_match(class) { + should_act = true; + } + } + } + } + ApplicationIdentifier::Exe => { + if let Some(re) = regex_identifiers.get(&identifier.id) + && re.is_match(exe_name) + { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if let Some(re) = regex_identifiers.get(&identifier.id) + && re.is_match(path) + { + should_act = true; + } + } + }, + } + + should_act +} diff --git a/crates/komorebi-config/tests/rule_matching.rs b/crates/komorebi-config/tests/rule_matching.rs new file mode 100644 index 00000000..21bb1f70 --- /dev/null +++ b/crates/komorebi-config/tests/rule_matching.rs @@ -0,0 +1,653 @@ +//! How a rule matches a window: the kinds (title, class, exe, path), every matching strategy, +//! composite rules and the last rule that matches winning. This is the one implementation all +//! three daemons call (`komorebi_config::rules`), so what the `rules`, `rules_class`, `rules_exe`, +//! `title_rule` and `startup_rules` end-to-end scenarios assert about WHICH window a rule catches +//! is asserted here once, with no window manager. These tests are the ones the KDE daemon had +//! (`komorebi-for-kde/komorebi/tests/rule_matching.rs`), moved with the function; they run the +//! KDE/macOS input shape (`RuleQuirks::UNIX`, a window with a list of classes). +//! +//! 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, what the OS reports as a window's title, class and +//! executable, and that an ignore rule is overridden by a manage rule (the daemon's +//! `should_manage`; KDE has `rule_matching.rs` for that). + +use komorebi_config::matching::IdWithIdentifier; +use komorebi_config::matching::MatchingRule; +use komorebi_config::matching::MatchingStrategy; +use komorebi_config::rules::RuleQuirks; +use komorebi_config::rules::RuleSubject; +use komorebi_protocol::types::ApplicationIdentifier; +use regex::Regex; +use std::collections::HashMap; + +fn should_act_individual( + title: &str, + exe_name: &str, + classes: &[&str], + path: &str, + rule: &IdWithIdentifier, + regex: &HashMap, +) -> bool { + komorebi_config::rules::should_act_individual( + &RuleSubject { + title, + exe_name, + classes, + path, + }, + RuleQuirks::UNIX, + rule, + regex, + ) +} + +fn should_act( + title: &str, + exe_name: &str, + classes: &[&str], + path: &str, + rules: &[MatchingRule], + regex: &HashMap, +) -> Option { + komorebi_config::rules::should_act( + &RuleSubject { + title, + exe_name, + classes, + path, + }, + RuleQuirks::UNIX, + rules, + regex, + ) +} + +fn should_act_window( + title: &str, + exe_name: &str, + class: &str, + path: &str, + rules: &[MatchingRule], + regex: &HashMap, +) -> Option { + should_act(title, exe_name, &[class], path, rules, regex) +} +fn id( + kind: ApplicationIdentifier, + id: &str, + strategy: Option, +) -> 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 { + 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, + std::slice::from_ref(&first), + &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, + std::slice::from_ref(&rule), + &no_regex(), + ) + }; + assert!(ask("a secret window").is_some()); + assert!(ask("a renamed window").is_none()); +} + +// The Windows input shape: one class, and an executable that carries its `.exe` +// (`RuleQuirks::WINDOWS`: a rule id is compared as written). + +const WIN_EXE: &str = "e2e-exe-sent.exe"; + +fn windows_matches(rule: &IdWithIdentifier, regex: &HashMap) -> bool { + komorebi_config::rules::should_act_individual( + &RuleSubject { + title: TITLE, + exe_name: WIN_EXE, + classes: &[CLASS], + path: PATH, + }, + RuleQuirks::WINDOWS, + rule, + regex, + ) +} + +// mirrors: rules_exe / a window an exe rule matches goes to the workspace the rule names +// mirrors: rules_exe / a window of another program stays on the first workspace +// (on Windows the rule id is `platform.exe_id(program)`, which is `e2e-exe-sent.exe`) +#[test] +fn on_windows_an_exe_rule_names_the_program_with_its_extension() { + for strategy in [None, Some(MatchingStrategy::Equals)] { + assert!(windows_matches( + &id(ApplicationIdentifier::Exe, WIN_EXE, strategy.clone()), + &no_regex() + )); + // not stripped: the id without the extension is another program + assert!(!windows_matches( + &id(ApplicationIdentifier::Exe, "e2e-exe-sent", strategy.clone()), + &no_regex() + )); + assert!(!windows_matches( + &id(ApplicationIdentifier::Exe, "e2e-exe-other.exe", strategy), + &no_regex() + )); + } + // the same ids on the KDE/macOS shape: the suffix of the id is ignored, so both name the + // program `e2e-exe-sent` + for written in ["e2e-exe-sent", "e2e-exe-sent.exe"] { + assert!(should_act_individual( + TITLE, + "e2e-exe-sent", + &[CLASS], + PATH, + &id( + ApplicationIdentifier::Exe, + written, + Some(MatchingStrategy::Equals) + ), + &no_regex() + )); + } +} + +#[test] +fn a_regex_id_is_looked_up_as_written_on_windows_and_without_exe_elsewhere() { + let written = "^e2e-exe-.*\\.exe$"; + let rule = id( + ApplicationIdentifier::Exe, + written, + Some(MatchingStrategy::Regex), + ); + let mut compiled = HashMap::new(); + compiled.insert(written.to_string(), Regex::new(written).unwrap()); + assert!(windows_matches(&rule, &compiled)); + // KDE/macOS look the cache up with `.exe` removed from the id (`^e2e-exe-.*\$`), which is + // not a key there: no match, whatever the executable is + assert!(!should_act_individual( + TITLE, + WIN_EXE, + &[CLASS], + PATH, + &rule, + &compiled + )); +} + +// mirrors: rules_class / a window a class rule matches goes to the workspace the rule names +// mirrors: rules_class / a window of another class stays on the first workspace +#[test] +fn a_window_with_one_class_is_decided_the_same_way_on_every_platform() { + // With ids that hold no `.exe` the two input shapes are the same function: the whole grid of + // kinds and strategies agrees, for ids that match and ids that do not. + let no_regex = no_regex(); + for kind in kinds() { + let text = text_of(kind); + let probes = [ + text.to_string(), + text[..4].to_string(), + text[text.len() - 4..].to_string(), + "zzzz-not-there".to_string(), + ]; + for strategy in [ + None, + Some(MatchingStrategy::Legacy), + Some(MatchingStrategy::Equals), + Some(MatchingStrategy::DoesNotEqual), + Some(MatchingStrategy::StartsWith), + Some(MatchingStrategy::DoesNotStartWith), + Some(MatchingStrategy::EndsWith), + Some(MatchingStrategy::DoesNotEndWith), + Some(MatchingStrategy::Contains), + Some(MatchingStrategy::DoesNotContain), + ] { + for probe in &probes { + let rule = id(kind, probe, strategy.clone()); + let subject = RuleSubject { + title: TITLE, + exe_name: EXE, + classes: &[CLASS], + path: PATH, + }; + assert_eq!( + komorebi_config::rules::should_act_individual( + &subject, + RuleQuirks::WINDOWS, + &rule, + &no_regex + ), + komorebi_config::rules::should_act_individual( + &subject, + RuleQuirks::UNIX, + &rule, + &no_regex + ), + "{kind:?} {strategy:?} {probe:?}" + ); + } + } + } +} + +// mirrors: rules_class / a window of another class stays on the first workspace +#[test] +fn a_negated_class_rule_holds_for_a_window_of_another_class_and_for_none_without_a_class() { + let rule = id( + ApplicationIdentifier::Class, + CLASS, + Some(MatchingStrategy::DoesNotEqual), + ); + // one class that is not the id: holds + assert!(should_act_individual( + TITLE, + EXE, + &["another"], + PATH, + &rule, + &no_regex() + )); + // the class the id names: does not + assert!(!should_act_individual( + TITLE, + EXE, + &[CLASS], + PATH, + &rule, + &no_regex() + )); + // a window with no class has none to hold for (KDE/macOS only; Windows always has one) + assert!(!should_act_individual( + TITLE, + EXE, + &[], + PATH, + &rule, + &no_regex() + )); +} diff --git a/crates/komorebi-core/src/command.rs b/crates/komorebi-core/src/command.rs new file mode 100644 index 00000000..712ee73e --- /dev/null +++ b/crates/komorebi-core/src/command.rs @@ -0,0 +1,369 @@ +//! The commands that only move the focus and the containers around the shared model. +//! +//! A daemon's `process_command` is a router over its `WindowManager`, which is per platform. What a +//! command does to the monitors, workspaces and containers does not depend on the platform, so the +//! commands whose work is only that are functions here, generic over a [`CommandHost`]: the few +//! operations of the window manager they build on (focus a monitor, show a workspace, move a +//! container). Each daemon implements the host with its own window manager, and the arm of its router +//! calls the function; a test implements it with a recording stub and checks the calls, which is how a +//! command's logic is tested without a Windows or macOS machine. + +use crate::Monitor; +use crate::MonitorPlatform; +use color_eyre::eyre; +use color_eyre::eyre::OptionExt; +use komorebi_layouts::CycleDirection; +use komorebi_layouts::OperationDirection; +use std::collections::VecDeque; +use std::num::NonZeroUsize; + +/// The window manager as the shared commands see it. +pub trait CommandHost { + /// The platform whose monitors the host has. + type P: MonitorPlatform; + + /// Whether the commands that act on the focused monitor first focus the monitor the pointer is + /// on when the workspace shown there is empty, for `cycle_focus_empty_workspace`, + /// `close_workspace` and `focus_last_workspace` (the other commands always do). Windows does it + /// for all of them; KDE and macOS do not. + const POINTER_PICKS_THE_MONITOR_FOR_ALL: bool = false; + + /// The monitors. + fn monitors(&self) -> &VecDeque>; + + /// The monitor that has the focus, if there is one. + fn focused_monitor(&self) -> Option<&Monitor>; + + /// The monitor that has the focus, mutably. + fn focused_monitor_mut(&mut self) -> Option<&mut Monitor>; + + /// The index of the monitor that has the focus. + fn focused_monitor_idx(&self) -> usize; + + /// The index of the monitor the pointer is on, if the platform says where it is. + fn monitor_idx_from_current_pos(&mut self) -> Option; + + /// Gives the focus to the monitor at `idx`. + fn focus_monitor(&mut self, idx: usize) -> eyre::Result<()>; + + /// Shows workspace `idx` on the focused monitor and focuses it. + fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()>; + + /// Moves the focused container to workspace `idx` of the focused monitor. + fn move_container_to_workspace( + &mut self, + idx: usize, + follow: bool, + direction: Option, + ) -> 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 +fn focus_the_monitor_under_the_pointer(host: &mut H) -> eyre::Result<()> { + if let Some(monitor_idx) = host.monitor_idx_from_current_pos() + && monitor_idx != host.focused_monitor_idx() + && let Some(monitor) = host.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + host.focus_monitor(monitor_idx)?; + } + + Ok(()) +} + +/// 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( + host: &mut H, + direction: CycleDirection, +) -> eyre::Result<()> { + focus_the_monitor_under_the_pointer(host)?; + + let focused_monitor = host.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")?, + ); + + host.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( + host: &mut H, + direction: CycleDirection, +) -> eyre::Result<()> { + if H::POINTER_PICKS_THE_MONITOR_FOR_ALL { + focus_the_monitor_under_the_pointer(host)?; + } + + let focused_monitor = host.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")?, + ); + } + + host.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(host: &mut H) -> eyre::Result<()> { + if H::POINTER_PICKS_THE_MONITOR_FOR_ALL { + focus_the_monitor_under_the_pointer(host)?; + } + + let mut can_close = false; + + if let Some(monitor) = host.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() + { + host.focus_workspace(next_focused_workspace_idx)?; + } + } + Ok(()) +} + +/// Focuses the workspace that was focused before this one +pub fn focus_last_workspace(host: &mut H) -> eyre::Result<()> { + if H::POINTER_PICKS_THE_MONITOR_FOR_ALL { + focus_the_monitor_under_the_pointer(host)?; + } + + let idx = host + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = host.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + host.focus_workspace(last_focused_workspace)?; + } + + host.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(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( + host: &mut H, + follow: bool, +) -> eyre::Result<()> { + focus_the_monitor_under_the_pointer(host)?; + + let idx = host + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = host.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + host.move_container_to_workspace(last_focused_workspace, follow, None)?; + } + + host.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + Ok(()) +} + +/// What the commands that move across monitors need besides [`CommandHost`]. +pub trait MonitorCommandHost: CommandHost { + /// Whether the pointer follows the focus. + fn mouse_follows_focus(&self) -> bool; + + /// Lays the focused workspace out again and, with `trigger_focus`, focuses its window. + fn update_focused_workspace( + &mut self, + follow_focus: bool, + trigger_focus: bool, + ) -> eyre::Result<()>; + + /// The direction in which one goes from the focused monitor to the one at `idx`, if they are + /// next to each other. + fn direction_from_monitor_idx(&self, idx: usize) -> Option; + + /// Moves the focused container to the monitor at `idx` (to workspace `workspace_idx` of it, or + /// the one it shows), and follows it when `follow` is set. + fn move_container_to_monitor( + &mut self, + idx: usize, + workspace_idx: Option, + follow: bool, + direction: Option, + ) -> eyre::Result<()>; + + /// The index of the workspace shown on the focused monitor. + fn focused_workspace_idx(&self) -> eyre::Result; +} + +/// Moves the focused container to the next or previous workspace of the focused monitor, and follows +/// it when `follow` is set +pub fn cycle_move_container_to_workspace( + host: &mut H, + direction: CycleDirection, + follow: bool, +) -> eyre::Result<()> { + let focused_monitor = host.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")?, + ); + + host.move_container_to_workspace(workspace_idx, follow, None)?; + Ok(()) +} + +/// Focuses the next or previous monitor +pub fn cycle_focus_monitor( + host: &mut H, + direction: CycleDirection, +) -> eyre::Result<()> { + let monitor_idx = direction.next_idx( + host.focused_monitor_idx(), + NonZeroUsize::new(host.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + host.focus_monitor(monitor_idx)?; + let mouse_follows_focus = host.mouse_follows_focus(); + host.update_focused_workspace(mouse_follows_focus, true)?; + Ok(()) +} + +/// Moves the focused container to the next or previous monitor, and follows it when `follow` is set +pub fn cycle_move_container_to_monitor( + host: &mut H, + direction: CycleDirection, + follow: bool, +) -> eyre::Result<()> { + let monitor_idx = direction.next_idx( + host.focused_monitor_idx(), + NonZeroUsize::new(host.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + let direction = host.direction_from_monitor_idx(monitor_idx); + host.move_container_to_monitor(monitor_idx, None, follow, direction)?; + Ok(()) +} + +/// Shows workspace `workspace_idx` of monitor `monitor_idx`, unless that is what is in front +pub fn focus_monitor_workspace_number( + host: &mut H, + monitor_idx: usize, + workspace_idx: usize, +) -> eyre::Result<()> { + let focused_monitor_idx = host.focused_monitor_idx(); + let focused_workspace_idx = host.focused_workspace_idx().unwrap_or_default(); + let focused_pair = (focused_monitor_idx, focused_workspace_idx); + + if focused_pair != (monitor_idx, workspace_idx) { + host.focus_monitor(monitor_idx)?; + host.focus_workspace(workspace_idx)?; + } + Ok(()) +} + +/// Moves the focused container to workspace `workspace_idx` of monitor `monitor_idx`, and follows it +/// when `follow` is set +pub fn move_container_to_monitor_workspace_number( + host: &mut H, + monitor_idx: usize, + workspace_idx: usize, + follow: bool, +) -> eyre::Result<()> { + let direction = host.direction_from_monitor_idx(monitor_idx); + host.move_container_to_monitor(monitor_idx, Option::from(workspace_idx), follow, direction)?; + Ok(()) +} + +/// What the commands that reach into a monitor's workspaces by index need besides [`CommandHost`]. +pub trait ContainerCommandHost: CommandHost { + /// The monitors, mutably. + fn monitors_mut(&mut self) -> &mut VecDeque>; +} + +/// Locks or unlocks container `container_idx` of workspace `workspace_idx` of monitor +/// `monitor_idx`, so that it keeps its index (or not) while others are inserted, removed or swapped. +/// A container index that is not there is ignored; a monitor or workspace that is not there is an +/// error. +pub fn set_container_locked( + host: &mut H, + monitor_idx: usize, + workspace_idx: usize, + container_idx: usize, + locked: bool, +) -> eyre::Result<()> { + let monitor = host + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("no monitor at the given index")?; + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("no workspace at the given index")?; + + if let Some(container) = workspace.containers_mut().get_mut(container_idx) { + container.locked = locked; + } + + Ok(()) +} diff --git a/crates/komorebi-core/src/lib.rs b/crates/komorebi-core/src/lib.rs index 4d39431d..3aceffad 100644 --- a/crates/komorebi-core/src/lib.rs +++ b/crates/komorebi-core/src/lib.rs @@ -7,6 +7,7 @@ #![deny(missing_docs)] +mod command; mod container; mod globals; #[allow(missing_docs)] @@ -14,6 +15,7 @@ mod monitor; #[allow(missing_docs)] mod workspace; +pub use command::*; pub use container::Container; pub use container::ContainerWindow; pub use container::WorkspaceWindow; diff --git a/crates/komorebi-core/tests/commands.rs b/crates/komorebi-core/tests/commands.rs new file mode 100644 index 00000000..d57e4123 --- /dev/null +++ b/crates/komorebi-core/tests/commands.rs @@ -0,0 +1,444 @@ +//! The shared commands of `komorebi_core::command`, on a recording host. +//! +//! Each test names the e2e check of `commands.py` (SWEEP) it mirrors: the e2e sends the command to a +//! running daemon and checks that it is answered and the daemon survives; here the effect on the +//! model is checked, for all three daemons at once. + +mod common; + +use color_eyre::eyre; +use common::*; +use komorebi_core::CommandHost; +use komorebi_core::Monitor; +use komorebi_layouts::CycleDirection; +use komorebi_layouts::OperationDirection; +use std::collections::VecDeque; + +struct Host { + monitors: VecDeque>, + focused: usize, + pointer_on: Option, + calls: Vec, + pointer_for_all: bool, +} + +fn monitor(workspaces: usize) -> Monitor { + let mut monitor: Monitor = serde_json::from_value(serde_json::json!({ + "id": 7, + "device": "Virtual-0", + "size": { "left": 0, "top": 0, "right": 1920, "bottom": 1080 }, + "work_area_size": { "left": 0, "top": 0, "right": 1920, "bottom": 1040 }, + "work_area_offset": null, + "window_based_work_area_offset": null, + "window_based_work_area_offset_limit": 1, + "workspaces": { "elements": [], "focused": 0 }, + "container_padding": null, + "workspace_padding": null, + "wallpaper": null, + "floating_layer_behaviour": null + })) + .unwrap(); + monitor.ensure_workspace_count(workspaces); + monitor +} + +impl Host { + fn new(workspaces: usize) -> Self { + fresh(); + Self { + monitors: VecDeque::from([monitor(workspaces)]), + focused: 0, + pointer_on: None, + calls: vec![], + pointer_for_all: false, + } + } + + fn shown(&self) -> usize { + self.monitors[self.focused].focused_workspace_idx() + } + + /// puts a window on workspace `idx` of the focused monitor + fn occupy(&mut self, idx: usize, window: u32) { + self.monitors[self.focused].workspaces_mut()[idx] + .new_container_for_window(StubWindow { id: window }); + } +} + +impl CommandHost for Host { + type P = StubPlatform; + + fn monitors(&self) -> &VecDeque> { + &self.monitors + } + + fn focused_monitor(&self) -> Option<&Monitor> { + self.monitors.get(self.focused) + } + + fn focused_monitor_mut(&mut self) -> Option<&mut Monitor> { + self.monitors.get_mut(self.focused) + } + + fn focused_monitor_idx(&self) -> usize { + self.focused + } + + fn monitor_idx_from_current_pos(&mut self) -> Option { + self.pointer_on + } + + fn focus_monitor(&mut self, idx: usize) -> eyre::Result<()> { + self.calls.push(format!("focus_monitor {idx}")); + self.focused = idx; + Ok(()) + } + + fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> { + self.calls.push(format!("focus_workspace {idx}")); + self.monitors[self.focused].focus_workspace(idx) + } + + fn move_container_to_workspace( + &mut self, + idx: usize, + follow: bool, + _: Option, + ) -> eyre::Result<()> { + self.calls.push(format!("move_container {idx} {follow}")); + Ok(()) + } +} + +#[test] +fn cycle_workspace_next_and_previous_wrap_around() { + // commands.py: "cycle-workspace next" / "cycle-workspace previous" + let mut host = Host::new(3); + + komorebi_core::cycle_focus_workspace(&mut host, CycleDirection::Next).unwrap(); + assert_eq!(host.shown(), 1); + komorebi_core::cycle_focus_workspace(&mut host, CycleDirection::Next).unwrap(); + komorebi_core::cycle_focus_workspace(&mut host, CycleDirection::Next).unwrap(); + assert_eq!( + host.shown(), + 0, + "next wraps from the last workspace to the first" + ); + + komorebi_core::cycle_focus_workspace(&mut host, CycleDirection::Previous).unwrap(); + assert_eq!(host.shown(), 2, "previous wraps from the first to the last"); +} + +#[test] +fn cycling_focuses_the_monitor_under_the_pointer_when_its_workspace_is_empty() { + // the preamble of cycle-workspace on a second monitor + let mut host = Host::new(2); + host.monitors.push_back(monitor(2)); + host.pointer_on = Some(1); + + komorebi_core::cycle_focus_workspace(&mut host, CycleDirection::Next).unwrap(); + + assert_eq!(host.calls[0], "focus_monitor 1"); + assert_eq!(host.focused, 1); +} + +#[test] +fn cycle_empty_workspace_skips_the_ones_with_windows() { + // commands.py: "cycle-empty-workspace next" + let mut host = Host::new(4); + host.occupy(0, 1); + host.occupy(1, 2); + + komorebi_core::cycle_focus_empty_workspace(&mut host, CycleDirection::Next).unwrap(); + + assert_eq!(host.shown(), 2); +} + +#[test] +fn cycle_empty_workspace_does_nothing_when_none_is_empty() { + let mut host = Host::new(2); + host.occupy(0, 1); + host.occupy(1, 2); + + komorebi_core::cycle_focus_empty_workspace(&mut host, CycleDirection::Next).unwrap(); + + assert!(host.calls.is_empty()); +} + +#[test] +fn close_workspace_removes_an_empty_unnamed_one_and_focuses_the_one_before() { + // commands.py: "close-workspace" + let mut host = Host::new(3); + host.monitors[0].focus_workspace(2).unwrap(); + + komorebi_core::close_workspace(&mut host).unwrap(); + + assert_eq!(host.monitors[0].workspaces().len(), 2); + assert_eq!(host.calls, ["focus_workspace 1"]); +} + +#[test] +fn close_workspace_keeps_a_workspace_with_a_window_a_name_or_the_only_one() { + let mut host = Host::new(2); + host.monitors[0].focus_workspace(1).unwrap(); + host.occupy(1, 1); + komorebi_core::close_workspace(&mut host).unwrap(); + assert_eq!(host.monitors[0].workspaces().len(), 2, "a window keeps it"); + + let mut host = Host::new(2); + host.monitors[0].focus_workspace(1).unwrap(); + host.monitors[0].workspaces_mut()[1].name = Some("web".to_string()); + komorebi_core::close_workspace(&mut host).unwrap(); + assert_eq!(host.monitors[0].workspaces().len(), 2, "a name keeps it"); + + let mut host = Host::new(1); + komorebi_core::close_workspace(&mut host).unwrap(); + assert_eq!(host.monitors[0].workspaces().len(), 1, "the only one stays"); +} + +#[test] +fn focus_last_workspace_goes_back_and_forth() { + // commands.py: "focus-last-workspace" twice + let mut host = Host::new(3); + host.monitors[0].focus_workspace(2).unwrap(); + + komorebi_core::focus_last_workspace(&mut host).unwrap(); + assert_eq!(host.shown(), 0, "the workspace shown before this one"); + + komorebi_core::focus_last_workspace(&mut host).unwrap(); + assert_eq!(host.shown(), 2, "and back again"); +} + +#[test] +fn move_to_last_workspace_moves_the_container_and_remembers_where_it_came_from() { + // commands.py: "move-to-last-workspace" and "send-to-last-workspace" + let mut host = Host::new(3); + host.monitors[0].focus_workspace(2).unwrap(); + + komorebi_core::move_container_to_last_workspace(&mut host, true).unwrap(); + assert_eq!(host.calls, ["move_container 0 true"]); + assert_eq!(host.monitors[0].last_focused_workspace, Some(2)); + + host.calls.clear(); + komorebi_core::move_container_to_last_workspace(&mut host, false).unwrap(); + assert_eq!( + host.calls, + ["move_container 2 false"], + "send does not follow" + ); +} + +#[test] +fn only_windows_lets_the_pointer_pick_the_monitor_for_the_empty_and_close_commands() { + // the platform switch of CommandHost::POINTER_PICKS_THE_MONITOR_FOR_ALL (default false: KDE and + // macOS); a host that says true gets the preamble for close and cycle-empty too + struct WindowsLike(Host); + + impl CommandHost for WindowsLike { + type P = StubPlatform; + const POINTER_PICKS_THE_MONITOR_FOR_ALL: bool = true; + + fn monitors(&self) -> &VecDeque> { + self.0.monitors() + } + fn focused_monitor(&self) -> Option<&Monitor> { + self.0.focused_monitor() + } + fn focused_monitor_mut(&mut self) -> Option<&mut Monitor> { + self.0.focused_monitor_mut() + } + fn focused_monitor_idx(&self) -> usize { + self.0.focused_monitor_idx() + } + fn monitor_idx_from_current_pos(&mut self) -> Option { + self.0.monitor_idx_from_current_pos() + } + fn focus_monitor(&mut self, idx: usize) -> eyre::Result<()> { + self.0.focus_monitor(idx) + } + fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> { + self.0.focus_workspace(idx) + } + fn move_container_to_workspace( + &mut self, + idx: usize, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + self.0.move_container_to_workspace(idx, follow, direction) + } + } + + let mut other = Host::new(2); + other.monitors.push_back(monitor(2)); + other.pointer_on = Some(1); + komorebi_core::close_workspace(&mut other).unwrap(); + assert!( + !other + .calls + .iter() + .any(|call| call.starts_with("focus_monitor")), + "KDE and macOS do not look at the pointer here" + ); + + let mut host = WindowsLike({ + let mut host = Host::new(2); + host.monitors.push_back(monitor(2)); + host.pointer_on = Some(1); + host + }); + komorebi_core::close_workspace(&mut host).unwrap(); + assert_eq!(host.0.calls[0], "focus_monitor 1"); +} + +impl komorebi_core::MonitorCommandHost for Host { + fn mouse_follows_focus(&self) -> bool { + true + } + + fn update_focused_workspace( + &mut self, + follow_focus: bool, + trigger_focus: bool, + ) -> eyre::Result<()> { + self.calls.push(format!( + "update_focused_workspace {follow_focus} {trigger_focus}" + )); + Ok(()) + } + + fn direction_from_monitor_idx(&self, idx: usize) -> Option { + (idx != self.focused).then_some(OperationDirection::Right) + } + + fn move_container_to_monitor( + &mut self, + idx: usize, + workspace_idx: Option, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + self.calls.push(format!( + "move_to_monitor {idx} {workspace_idx:?} {follow} {}", + direction.is_some() + )); + Ok(()) + } + + fn focused_workspace_idx(&self) -> eyre::Result { + Ok(self.shown()) + } +} + +fn two_monitors() -> Host { + let mut host = Host::new(3); + host.monitors.push_back(monitor(3)); + host +} + +#[test] +fn cycle_move_to_workspace_moves_and_send_to_workspace_does_not_follow() { + // commands.py: "cycle-move-to-workspace previous" and "cycle-send-to-workspace next" + let mut host = Host::new(3); + + komorebi_core::cycle_move_container_to_workspace(&mut host, CycleDirection::Previous, true) + .unwrap(); + komorebi_core::cycle_move_container_to_workspace(&mut host, CycleDirection::Next, false) + .unwrap(); + + assert_eq!( + host.calls, + ["move_container 2 true", "move_container 1 false"] + ); +} + +#[test] +fn cycle_monitor_focuses_the_next_monitor_and_lays_it_out() { + // commands.py: "cycle-monitor next" + let mut host = two_monitors(); + + komorebi_core::cycle_focus_monitor(&mut host, CycleDirection::Next).unwrap(); + + assert_eq!(host.focused, 1); + assert_eq!( + host.calls, + ["focus_monitor 1", "update_focused_workspace true true"] + ); + + komorebi_core::cycle_focus_monitor(&mut host, CycleDirection::Next).unwrap(); + assert_eq!(host.focused, 0, "it wraps"); +} + +#[test] +fn cycle_move_and_send_to_monitor_go_in_the_direction_of_the_target() { + // commands.py: "cycle-move-to-monitor next" and "cycle-send-to-monitor next" + let mut host = two_monitors(); + + komorebi_core::cycle_move_container_to_monitor(&mut host, CycleDirection::Next, true).unwrap(); + komorebi_core::cycle_move_container_to_monitor(&mut host, CycleDirection::Next, false).unwrap(); + + assert_eq!( + host.calls, + [ + "move_to_monitor 1 None true true", + "move_to_monitor 1 None false true" + ] + ); +} + +#[test] +fn focus_monitor_workspace_does_nothing_when_that_is_already_in_front() { + // commands.py: "focus-monitor-workspace 0 1" + let mut host = two_monitors(); + + komorebi_core::focus_monitor_workspace_number(&mut host, 0, 0).unwrap(); + assert!(host.calls.is_empty()); + + komorebi_core::focus_monitor_workspace_number(&mut host, 1, 2).unwrap(); + assert_eq!(host.calls, ["focus_monitor 1", "focus_workspace 2"]); +} + +#[test] +fn move_and_send_to_monitor_workspace_name_the_workspace() { + // commands.py: "move-to-monitor-workspace 0 1" and "send-to-monitor-workspace 0 1" + let mut host = two_monitors(); + + komorebi_core::move_container_to_monitor_workspace_number(&mut host, 1, 2, true).unwrap(); + komorebi_core::move_container_to_monitor_workspace_number(&mut host, 1, 2, false).unwrap(); + + assert_eq!( + host.calls, + [ + "move_to_monitor 1 Some(2) true true", + "move_to_monitor 1 Some(2) false true" + ] + ); +} + +impl komorebi_core::ContainerCommandHost for Host { + fn monitors_mut(&mut self) -> &mut VecDeque> { + &mut self.monitors + } +} + +#[test] +fn lock_and_unlock_a_container_by_index() { + // commands.py has toggle-lock; the by-index forms (lock/unlock-monitor-workspace-container) are in the KDE command_sweep + let mut host = Host::new(2); + host.occupy(0, 1); + + komorebi_core::set_container_locked(&mut host, 0, 0, 0, true).unwrap(); + assert!(host.monitors[0].workspaces()[0].containers()[0].locked); + + komorebi_core::set_container_locked(&mut host, 0, 0, 0, false).unwrap(); + assert!(!host.monitors[0].workspaces()[0].containers()[0].locked); +} + +#[test] +fn locking_a_container_that_is_not_there_is_ignored_but_a_missing_monitor_or_workspace_is_not() { + let mut host = Host::new(1); + + assert!(komorebi_core::set_container_locked(&mut host, 0, 0, 5, true).is_ok()); + assert!(komorebi_core::set_container_locked(&mut host, 3, 0, 0, true).is_err()); + assert!(komorebi_core::set_container_locked(&mut host, 0, 9, 0, true).is_err()); +} diff --git a/docs/dev/bar-e2e.md b/docs/dev/bar-e2e.md index 3b41647e..4f38448c 100644 --- a/docs/dev/bar-e2e.md +++ b/docs/dev/bar-e2e.md @@ -24,3 +24,52 @@ macOS (see `docs/dev/macos-handcheck.md`). Not run when it was written (the guest was reserved): lint only (`py_compile`, `ruff`, the runner's 157 unit tests pass). + +## The golden guest has no OpenGL 2.0 + +The Windows gate (candidate 5) found that the bar cannot open a window in the golden guest: +eframe's default renderer is `egui_glow`, the guest has the basic display adapter and QXL and no +OpenGL driver, so Windows offers only the generic software OpenGL 1.1 of `opengl32.dll`, and the bar +exits at start with `Error: egui_glow: OpenGL: egui_glow requires opengl 2.0+` +(`komorebi-bar/src/windows/mod.rs`, the `run_native` error). The scenario therefore reports the +window, stays-alive and daemon-restart checks as `skipped: guest has no OpenGL 2.0` when, and only +when, the bar's own output says that (`extras/bar.py`, `classify`); any other early exit is a +failure. The schema equality, the configuration read, `komorebic state` and `stop --bar` stay real +checks. A skip is not a pass: the bar's runtime behaviour is unverified until the guest can draw. + +### Getting rendering into the guest (analysis, nothing added) + +How the context is chosen: `komorebi-bar` uses `eframe` 0.33 with its default features, so only +the glow renderer is compiled (glutin + `egui_glow`); `NativeOptions` is left at its defaults on +Windows (the macOS bar sets its own), so the bar asks for a hardware OpenGL 2.0+ config through +glutin, falls back to the Windows generic GDI implementation (1.1) and `egui_glow` refuses it. + +1. Mesa llvmpipe `opengl32.dll` next to `komorebi-bar.exe` (the classic recipe: Mesa's + `opengl32.dll` takes over from the system one for that process). Not possible from this flake: + nixpkgs marks `pkgsCross.mingwW64.mesa` as an unsupported platform (`nix build --dry-run` refuses + it), and `nixpkgs` has no Windows `opengl32sw.dll` (that file ships with Qt) or ANGLE. Building + Mesa for mingw means porting its nix expression (swrast + llvm cross for mingw, a cross LLVM + build) and carrying a binary of unknown license status in the image: days of work, hours of + build, and the result is a third-party DLL in the test that real users do not run. +2. A wgpu renderer with the Windows software adapter. Windows 11 ships WARP, the software + Direct3D 12 rasteriser, in the Basic Render Driver, which the guest has; wgpu's DX12 backend + finds it as an adapter, no download. In `eframe` this is the `wgpu` feature plus + `NativeOptions { renderer: Renderer::Wgpu, .. }` (and `wgpu_options` with a fallback adapter if + it does not pick WARP by itself). The sources of the wgpu stack (wgpu 27, naga, wgpu-hal, + gpu-allocator, ash) are already in the local cargo registry because they are in `Cargo.lock` + as optional dependencies of eframe, so it should build offline. Proposal, smallest first: + in `komorebi-bar`'s `[target.'cfg(windows)'.dependencies]` ask for `eframe` with the `wgpu` + feature, and at start: try glow as now; if `run_native` fails with the OpenGL message, run again + with `Renderer::Wgpu` (the e2e then passes the window checks, and a user without OpenGL gets a + bar instead of an error). Cost: about 60 more crates in `Cargo.lock` that are compiled for + Windows only (cold build +3 to 5 minutes in CI, +8 to 12 MB in `komorebi-bar.exe`); a retry path + that needs `NativeOptions` to be built twice; a new, untested code path for real users (low + risk: it only runs where glow already failed). Without the fallback, a `KOMOREBI_BAR_RENDERER=wgpu` + switch the scenario sets would keep users on glow and cost the same dependencies. +3. ANGLE (EGL on Direct3D 11, itself on WARP) through `glutin`'s EGL support: needs + `libEGL.dll`/`libGLESv2.dll`, which are not in nix either. Rejected. + +Recommendation: 2, with the glow-then-wgpu fallback, as its own revision with the e2e `bar` +scenario as its gate (the window checks stop being skipped). Whether the guest's WARP accepts +wgpu's DX12 device (feature level, no HLSL compiler problem for egui's shaders) can only be +learned by running it; the first run should keep `RUST_LOG=wgpu_hal=debug` output in `bar.out`. diff --git a/docs/dev/core-model.md b/docs/dev/core-model.md index 3cff818d..a26aa3d9 100644 --- a/docs/dev/core-model.md +++ b/docs/dev/core-model.md @@ -1371,3 +1371,41 @@ Recommended next step: kfm unifies the container API (blocker 1) and the `?` pol daemons; after that the nine functions are identical and the shared share passes 60% without new hooks, and `WindowManager

` can be created over KDE and macOS with the entry points of blocker 3 left in each daemon's extension trait. + +## 21. The shared commands (`komorebi_core::command`, wip-u-cmd) + +**Mechanism.** The daemons' `WindowManager` is per platform, so the commands cannot be methods of a +shared type yet; they are free functions generic over a *host*, a small trait the daemon implements by +forwarding to its own methods: `CommandHost` (monitors, focused monitor, the monitor under the pointer, +`focus_monitor`, `focus_workspace`, `move_container_to_workspace`), `MonitorCommandHost` (mouse follows +focus, `update_focused_workspace`, `direction_from_monitor_idx`, `move_container_to_monitor`, the focused +workspace index) and `ContainerCommandHost` (`monitors_mut`). A recording stub host in +`crates/komorebi-core/tests/commands.rs` tests each function natively, naming the e2e check of +`commands.py` it mirrors; this is the model-level command harness that only KDE had. + +**Moved (sixteen router arms, the same text on all three daemons):** the workspace navigation +(`CycleFocusWorkspace`, `CycleFocusEmptyWorkspace`, `CloseWorkspace`, `FocusLastWorkspace`, +`MoveContainerToLastWorkspace`, `SendContainerToLastWorkspace`), the moves across workspaces and +monitors (`CycleMoveContainerToWorkspace`, `CycleSendContainerToWorkspace`, `CycleFocusMonitor`, +`CycleMoveContainerToMonitor`, `CycleSendContainerToMonitor`, `FocusMonitorWorkspaceNumber`, +`MoveContainerToMonitorWorkspaceNumber`, `SendContainerToMonitorWorkspaceNumber`) and the lock and +unlock of a container by index. The one platform difference found, that Windows lets the pointer pick the +monitor first for the empty, close and last-workspace commands (a probable omission on KDE and macOS, +section 18), is the const `CommandHost::POINTER_PICKS_THE_MONITOR_FOR_ALL`, true only for Windows. + +**What stays, and why** (identical across the three unless noted; each needs a `WindowManager` method +or field, so moving them means moving `WindowManager`, the blockers of section 18): +- the moves and focus by direction (`MoveWindow`, `FocusWindow`, `CycleFocusWindow`, `CycleMoveWindow`, + `PreselectDirection`, `Promote*`, `StackWindow`, `UnstackWindow`, `StackAll`, `CycleStack*`): they call + `move_container_in_direction`, `focus_container_in_direction` and the floating variants, which are the + big window manager functions with the platform window operations; +- the named-workspace commands (`MoveContainerToNamedWorkspace`, `SendContainerToNamedWorkspace`, + `FocusNamedWorkspace`, the layout and tiling by name): need `monitor_workspace_index_by_name`, a + `WindowManager` method over the monitors (a candidate for the next host method once the names are + in `Monitor`); +- the behaviour toggles (`ToggleCrossMonitorMoveBehaviour`, `ToggleWindowContainerBehaviour`): fields + of `WindowManager`; +- the layout and rule commands (`WorkspaceLayout*`, `WorkspaceRule`, `ContainerPadding`, + `WorkAreaOffset`, ...): thin calls of `WindowManager` methods that edit a workspace and re-layout, the + same coupling; +- queries, configuration, borders, animations, transparency, schema: statics and the platform. diff --git a/docs/dev/e2e-to-unit.md b/docs/dev/e2e-to-unit.md index 12d5fa93..62e63124 100644 --- a/docs/dev/e2e-to-unit.md +++ b/docs/dev/e2e-to-unit.md @@ -45,7 +45,7 @@ times (Windows `komorebi/src/window.rs:1178`, KDE `window.rs:661`, macOS `window | 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 | +| 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, once for all three daemons: `crates/komorebi-config/tests/rule_matching.rs` (16 tests, KDE/macOS and Windows input shapes; the matching moved to `komorebi_config::rules`, see `docs/dev/rule-matching.md`); KDE keeps the manage-rule rescue test. 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 | diff --git a/docs/dev/rule-matching.md b/docs/dev/rule-matching.md new file mode 100644 index 00000000..fbed6e89 --- /dev/null +++ b/docs/dev/rule-matching.md @@ -0,0 +1,35 @@ +# Window-rule matching: the three copies and the shared one + +`should_act` (the last rule of a list that matches a window, a composite rule needing all its +conditions) and `should_act_individual` (one condition, by its matching strategy) existed three +times: `komorebi/src/window.rs` (Windows), `komorebi-for-kde/komorebi/src/window.rs` and +`komorebi-for-mac/komorebi/src/window.rs`. They are now `komorebi_config::rules`, one +implementation that all three daemons call; each keeps its own function signatures as a thin +wrapper so no call site changed. + +## Classification (diff of the three copies, before the move) + +| aspect | Windows | KDE | macOS | +|---|---|---|---| +| inputs | title, exe_name, `class: &str`, path | title, exe_name, `classes: &[&str]`, path | same as KDE | +| classes | exactly one | any of the slice (`for` loop, true if any element satisfies the test) | same as KDE | +| `.exe` in the rule id | kept: `exe_name` carries `.exe` on Windows, ids are compared as written | `identifier.id.replace(".exe", "")` before anything else (every occurrence, also in a regex id and so in the regex-cache key looked up) | same as KDE | +| strategies (Legacy/None, Equals, DoesNotEqual, StartsWith, DoesNotStartWith, EndsWith, DoesNotEndWith, Contains, DoesNotContain, Regex) | same set, same semantics per kind | same | same | +| Legacy/None | title and class: starts or ends with the id; exe and path: equal | same | same | +| Regex | `regex_identifiers.get(&id)` keyed by the id, no entry means no match; applied to title, class, exe, path | same, class: any of the classes | same | +| case folding | none (all comparisons are case sensitive) | none | none | +| path handling | compared as given, no normalisation | same | same | +| `should_act` | last matching rule wins, composite = all conditions | identical to Windows except the `classes` type | identical to KDE | +| wrappers | `should_act_window(_individual)` pass the one class | same, pass `&[class]` | trait methods in `workspace.rs` call `should_act` | +| regex cache | `REGEX_IDENTIFIERS` static in `komorebi/src/lib.rs`, filled by static config | same name, KDE lib.rs | same name, macOS lib.rs | + +KDE and macOS are byte-identical in both functions. The Windows copy differs in exactly two +ways, and both are preserved by a flag or a one-element slice: + +1. one class instead of a list: `[class]` is equivalent to the single compare for every strategy + (checked arm by arm: any-of over one element is the one test; the negated strategies too); +2. no `.exe` stripping: `RuleQuirks::strip_exe_from_ids` (false on Windows, true on KDE and macOS). + +No other difference exists, so no per-call-site flag is needed beyond the one platform constant. +The regex cache stays in each daemon (`REGEX_IDENTIFIERS`, lock order unchanged); the shared +function receives it as `&HashMap` exactly as the copies did. diff --git a/e2e/platforms/qemu_windows/extras/bar.py b/e2e/platforms/qemu_windows/extras/bar.py index d4b78d70..fb97bc35 100644 --- a/e2e/platforms/qemu_windows/extras/bar.py +++ b/e2e/platforms/qemu_windows/extras/bar.py @@ -17,6 +17,7 @@ an artefact (`bar.png`, `bar-after-restart.png`). import hashlib import json import os +import re import time from pathlib import Path @@ -29,6 +30,7 @@ BAR_BINARY = f"{GUEST_BIN}\\komorebi-bar.exe" BAR_CONFIG = "C:\\e2e\\bar.json" BAR_OUTPUT = "C:\\e2e\\bar.out" # the title eframe gives the window (`run_native("komorebi-bar", ...)`) +ANSI = re.compile(r"\x1b\[[0-9;]*m") BAR_TITLE = "komorebi-bar" # how long the bar must keep running, in seconds ALIVE_SECONDS = 15 @@ -55,7 +57,8 @@ CONFIG = { # bar's PowerShell session "mouse": { "on_extra2_click": {"message": {"type": "Retile"}}, - "on_middle_click": {"Command": "echo komorebi-bar-e2e"}, + # `MouseMessage::Command(String)` is untagged: a plain string, not {"Command": ...} + "on_middle_click": "echo komorebi-bar-e2e", }, } @@ -101,6 +104,51 @@ def _alive_for(platform: WindowsPlatform, seconds: float) -> bool: return bool(_bar_pids(platform)) +# what the bar prints when eframe cannot make a window for lack of OpenGL (komorebi-bar's +# `run_native` error), as the gate printed it: "egui_glow requires opengl 2.0+" +NO_OPENGL_TEXT = "requires opengl" +NO_OPENGL = "guest has no OpenGL 2.0" + + +def classify(output: str) -> str | None: + """What the bar's own output says about its start: "no_opengl" (it could not make a + window for lack of OpenGL), "failed" (it ended with any other error: a configuration it + could not read, a crash) or None (no error, it runs).""" + if "Error:" not in output and "panicked" not in output: + return None + if NO_OPENGL_TEXT in output.lower(): + return "no_opengl" + return "failed" + + +def _bar_output(platform: WindowsPlatform) -> str: + try: + text = platform.agent_get_file(BAR_OUTPUT).decode(errors="replace") + except Exception: + return "" + return ANSI.sub("", text) + + +def _started(platform: WindowsPlatform) -> bool: + """The bar runs, or it has already ended with something to say.""" + return bool(_bar_pids(platform)) or classify(_bar_output(platform)) is not None + + +def _outcome(platform: WindowsPlatform) -> str: + """Waits for the bar's window or its end: "running" (the window is there), "no_opengl", + "failed", or "timeout" (neither within a minute).""" + deadline = time.monotonic() + 60 * platform._scale + while time.monotonic() < deadline: + if _bar_window(platform) is not None: + return "running" + if not _bar_pids(platform): + why = classify(_bar_output(platform)) + if why is not None: + return why + time.sleep(1) + return classify(_bar_output(platform)) or "timeout" + + def run(platform: WindowsPlatform, checks: Checks, clients: list[Client]) -> None: """Starts the bar on the tiled windows of `tiling` and walks through its life. The daemon runs at the end and the bar does not.""" @@ -128,12 +176,47 @@ def run(platform: WindowsPlatform, checks: Checks, clients: list[Client]) -> Non "cmd", "/c", f"{BAR_BINARY} --config {BAR_CONFIG} > {BAR_OUTPUT} 2>&1" ) + checks.check("the bar process starts", platform.wait_for(lambda: _started(platform), timeout=30)) + outcome = _outcome(platform) + text = _bar_output(platform) + (platform._out / "bar.out").write_text(text) + # the configuration is parsed before the window is made, so a bar that got as far as + # opening a window (or failing to) has read all of it, the Keyboard and Systray + # widgets and the mouse block included checks.check( - "the bar process starts", platform.wait_for(lambda: bool(_bar_pids(platform)), timeout=30) + "the bar reads its configuration (every widget, the mouse block)", + outcome != "failed" and "found configuration file" in text, ) - appeared = platform.wait_for(lambda: _bar_window(platform) is not None, timeout=60) - checks.check(f"the bar's window titled {BAR_TITLE!r} appears", appeared) + + if outcome == "no_opengl": + # the golden guest has no OpenGL 2.0 (basic display and QXL, no software opengl32), so + # eframe cannot make the window: not what a change of the bar did, and not a pass + for what in ( + f"the bar's window titled {BAR_TITLE!r} appears", + f"the bar keeps running for {ALIVE_SECONDS} s", + "the bar is still running after the daemon stopped", + "the bar runs on after the daemon is back", + ): + checks.skip(what, NO_OPENGL) + checks.check( + "`komorebic state` answers after the bar has started", + platform.wait_for(lambda: platform.komorebic_status("state")[0] == 0), + ) + platform.komorebic("stop", "--bar") + checks.check( + "`komorebic stop --bar` stops the daemon", + platform.wait_for(lambda: platform.komorebic_status("state")[0] != 0, timeout=20), + ) + platform.start_komorebi() + return + if outcome != "running": + checks.bad(f"the bar did not open its window ({outcome}); it printed: {text[:600]!r}") + platform.komorebic("stop", "--bar") + platform.start_komorebi() + return + window = _bar_window(platform) + checks.check(f"the bar's window titled {BAR_TITLE!r} appears", window is not None) if window is not None: frame = window["frame"] checks.check( @@ -197,10 +280,5 @@ def run(platform: WindowsPlatform, checks: Checks, clients: list[Client]) -> Non "`komorebic stop --bar` ends the bar process", platform.wait_for(lambda: not _bar_pids(platform), timeout=20), ) - try: - text = platform.agent_get_file(BAR_OUTPUT).decode(errors="replace") - (platform._out / "bar.out").write_text(text) - except Exception as e: - print(f" no bar output: {e}") # left as the other scenarios leave it: the daemon runs platform.start_komorebi() diff --git a/e2e/platforms/qemu_windows/run.py b/e2e/platforms/qemu_windows/run.py index 965a48d0..c3315d66 100644 --- a/e2e/platforms/qemu_windows/run.py +++ b/e2e/platforms/qemu_windows/run.py @@ -544,6 +544,8 @@ def main(argv: list[str]) -> int: failed += 1 continue print(f"{name}: passed {checks.passed} failed {checks.failed}") + if checks.skipped: + print(f"{name}: skipped {len(checks.skipped)}") if checks.known: print(f"{name}: known failures {len(checks.known)}") failed += checks.failed diff --git a/e2e/platforms/qemu_windows/tests/test_bar_scenario.py b/e2e/platforms/qemu_windows/tests/test_bar_scenario.py new file mode 100644 index 00000000..e4a266cd --- /dev/null +++ b/e2e/platforms/qemu_windows/tests/test_bar_scenario.py @@ -0,0 +1,31 @@ +"""What the `bar` scenario decides from the bar's own output, without a guest.""" + +from platforms.qemu_windows.extras import bar + +GL = ( + "2026-10-31T07:25:02Z INFO komorebi_bar::windows: found configuration file: C:\\e2e\\bar.json\n" + "Error: \n 0: egui_glow: OpenGL: egui_glow requires opengl 2.0+. \n" +) +PARSE = ( + "found configuration file: C:\\e2e\\bar.json\nError: \n" + " 0: data did not match any variant of untagged enum MouseMessage at line 59 column 3\n" +) + + +def test_no_opengl_is_told_from_other_errors(): + assert bar.classify(GL) == "no_opengl" + + +def test_any_other_error_is_a_failure(): + assert bar.classify(PARSE) == "failed" + assert bar.classify("thread 'main' panicked at x") == "failed" + + +def test_a_bar_that_prints_no_error_runs(): + assert bar.classify("") is None + assert bar.classify("found configuration file: x\nwatching configuration file\n") is None + + +def test_the_test_configuration_is_plain_json_values(): + # the untagged MouseMessage::Command is a string + assert isinstance(bar.CONFIG["mouse"]["on_middle_click"], str) diff --git a/komorebi-for-kde/komorebi/src/process_command.rs b/komorebi-for-kde/komorebi/src/process_command.rs index 8a9d0c66..7208edb5 100644 --- a/komorebi-for-kde/komorebi/src/process_command.rs +++ b/komorebi-for-kde/komorebi/src/process_command.rs @@ -219,7 +219,6 @@ //! 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; @@ -254,6 +253,7 @@ use crate::monitor::MonitorExt; use crate::monitor::MonitorInformation; use crate::notify_subscribers; use crate::scrolling::WorkspaceScrolling; +use crate::settings::animation_off; use crate::state::GlobalState; use crate::state::State; use crate::static_config::StaticConfig; @@ -890,126 +890,27 @@ impl WindowManager { /// 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(()) + komorebi_core::cycle_focus_workspace(self, direction) } /// 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<()> { - 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(()) + komorebi_core::cycle_focus_empty_workspace(self, direction) } /// 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<()> { - 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(()) + komorebi_core::close_workspace(self) } /// 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)?; - } + komorebi_core::move_container_to_last_workspace(self, follow) + } - 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(()) + /// Focuses the workspace that was focused before this one + pub fn focus_last_workspace(&mut self) -> eyre::Result<()> { + komorebi_core::focus_last_workspace(self) } /// Handles one message, writes the answer to a question to `reply`, and sends the subscribers @@ -1205,14 +1106,7 @@ impl WindowManager { self.focus_container_window(idx)?; } SocketMessage::CycleFocusMonitor(direction) => { - let monitor_idx = direction.next_idx( - self.focused_monitor_idx(), - NonZeroUsize::new(self.monitors().len()) - .ok_or_eyre("there must be at least one monitor")?, - ); - - self.focus_monitor(monitor_idx)?; - self.update_focused_workspace(self.mouse_follows_focus, true)?; + komorebi_core::cycle_focus_monitor(self, direction)? } SocketMessage::CycleFocusWorkspace(direction) => { self.cycle_focus_workspace(direction)? @@ -1229,22 +1123,7 @@ impl WindowManager { self.focus_monitor(monitor_idx)?; } } - SocketMessage::FocusLastWorkspace => { - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.focus_workspace(last_focused_workspace)?; - } - - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); - } + SocketMessage::FocusLastWorkspace => self.focus_last_workspace()?, SocketMessage::FocusWorkspaceNumber(workspace_idx) => { if self.focused_workspace_idx().unwrap_or_default() != workspace_idx { self.focus_workspace(workspace_idx)?; @@ -1263,15 +1142,7 @@ impl WindowManager { self.focus_workspace(workspace_idx)?; } SocketMessage::FocusMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { - let focused_monitor_idx = self.focused_monitor_idx(); - let focused_workspace_idx = self.focused_workspace_idx().unwrap_or_default(); - - let focused_pair = (focused_monitor_idx, focused_workspace_idx); - - if focused_pair != (monitor_idx, workspace_idx) { - self.focus_monitor(monitor_idx)?; - self.focus_workspace(workspace_idx)?; - } + komorebi_core::focus_monitor_workspace_number(self, monitor_idx, workspace_idx)? } SocketMessage::FocusNamedWorkspace(ref name) => { if let Some((monitor_idx, workspace_idx)) = @@ -1296,18 +1167,7 @@ impl WindowManager { self.move_container_to_last_workspace(false)?; } SocketMessage::CycleMoveContainerToWorkspace(direction) => { - 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.move_container_to_workspace(workspace_idx, true, None)?; + komorebi_core::cycle_move_container_to_workspace(self, direction, true)? } SocketMessage::MoveContainerToMonitorNumber(monitor_idx) => { let direction = self.direction_from_monitor_idx(monitor_idx); @@ -1317,60 +1177,33 @@ impl WindowManager { self.swap_focused_monitor(monitor_idx)?; } SocketMessage::CycleMoveContainerToMonitor(direction) => { - let monitor_idx = direction.next_idx( - self.focused_monitor_idx(), - NonZeroUsize::new(self.monitors().len()) - .ok_or_eyre("there must be at least one monitor")?, - ); - - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor(monitor_idx, None, true, direction)?; + komorebi_core::cycle_move_container_to_monitor(self, direction, true)? } SocketMessage::CycleSendContainerToWorkspace(direction) => { - 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.move_container_to_workspace(workspace_idx, false, None)?; + komorebi_core::cycle_move_container_to_workspace(self, direction, false)? } SocketMessage::SendContainerToMonitorNumber(monitor_idx) => { let direction = self.direction_from_monitor_idx(monitor_idx); self.move_container_to_monitor(monitor_idx, None, false, direction)?; } SocketMessage::CycleSendContainerToMonitor(direction) => { - let monitor_idx = direction.next_idx( - self.focused_monitor_idx(), - NonZeroUsize::new(self.monitors().len()) - .ok_or_eyre("there must be at least one monitor")?, - ); - - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor(monitor_idx, None, false, direction)?; + komorebi_core::cycle_move_container_to_monitor(self, direction, false)? } SocketMessage::SendContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor( + komorebi_core::move_container_to_monitor_workspace_number( + self, monitor_idx, - Option::from(workspace_idx), + workspace_idx, false, - direction, - )?; + )? } SocketMessage::MoveContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor( + komorebi_core::move_container_to_monitor_workspace_number( + self, monitor_idx, - Option::from(workspace_idx), + workspace_idx, true, - direction, - )?; + )? } SocketMessage::SendContainerToNamedWorkspace(ref workspace) => { if let Some((monitor_idx, workspace_idx)) = @@ -1529,40 +1362,24 @@ impl WindowManager { monitor_idx, workspace_idx, container_idx, - ) => { - let monitor = self - .monitors_mut() - .get_mut(monitor_idx) - .ok_or_eyre("no monitor at the given index")?; - - let workspace = monitor - .workspaces_mut() - .get_mut(workspace_idx) - .ok_or_eyre("no workspace at the given index")?; - - if let Some(container) = workspace.containers_mut().get_mut(container_idx) { - container.locked = true; - } - } + ) => komorebi_core::set_container_locked( + self, + monitor_idx, + workspace_idx, + container_idx, + true, + )?, SocketMessage::UnlockMonitorWorkspaceContainer( monitor_idx, workspace_idx, container_idx, - ) => { - let monitor = self - .monitors_mut() - .get_mut(monitor_idx) - .ok_or_eyre("no monitor at the given index")?; - - let workspace = monitor - .workspaces_mut() - .get_mut(workspace_idx) - .ok_or_eyre("no workspace at the given index")?; - - if let Some(container) = workspace.containers_mut().get_mut(container_idx) { - container.locked = false; - } - } + ) => komorebi_core::set_container_locked( + self, + monitor_idx, + workspace_idx, + container_idx, + false, + )?, SocketMessage::FlipLayout(layout_flip) => self.flip_layout(layout_flip)?, SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, SocketMessage::CycleLayout(direction) => self.cycle_layout(direction)?, @@ -2035,7 +1852,8 @@ impl WindowManager { theme_manager::send_notification(*theme.clone()); } SocketMessage::Transparency(enable) => { - crate::settings::settings().update(|settings| settings.shared.transparency.enabled = enable); + crate::settings::settings() + .update(|settings| settings.shared.transparency.enabled = enable); } SocketMessage::ToggleTransparency => { crate::settings::settings().update(|settings| { @@ -2043,7 +1861,8 @@ impl WindowManager { }); } SocketMessage::TransparencyAlpha(alpha) => { - crate::settings::settings().update(|settings| settings.shared.transparency.alpha = alpha); + 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) => { @@ -2201,6 +2020,86 @@ fn push_simple_rule(rules: &mut Vec, kind: ApplicationIdentifier, } } +/// The window manager as the shared commands of `komorebi_core::command` see it +impl komorebi_core::CommandHost for WindowManager { + type P = crate::workspace::KdePlatform; + + fn monitors(&self) -> &std::collections::VecDeque { + WindowManager::monitors(self) + } + + fn focused_monitor(&self) -> Option<&crate::monitor::Monitor> { + WindowManager::focused_monitor(self) + } + + fn focused_monitor_mut(&mut self) -> Option<&mut crate::monitor::Monitor> { + WindowManager::focused_monitor_mut(self) + } + + fn focused_monitor_idx(&self) -> usize { + WindowManager::focused_monitor_idx(self) + } + + fn monitor_idx_from_current_pos(&mut self) -> Option { + WindowManager::monitor_idx_from_current_pos(self) + } + + fn focus_monitor(&mut self, idx: usize) -> eyre::Result<()> { + WindowManager::focus_monitor(self, idx) + } + + fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> { + WindowManager::focus_workspace(self, idx) + } + + fn move_container_to_workspace( + &mut self, + idx: usize, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + WindowManager::move_container_to_workspace(self, idx, follow, direction) + } +} + +impl komorebi_core::MonitorCommandHost for WindowManager { + fn mouse_follows_focus(&self) -> bool { + self.mouse_follows_focus + } + + fn update_focused_workspace( + &mut self, + follow_focus: bool, + trigger_focus: bool, + ) -> eyre::Result<()> { + WindowManager::update_focused_workspace(self, follow_focus, trigger_focus) + } + + fn direction_from_monitor_idx(&self, idx: usize) -> Option { + WindowManager::direction_from_monitor_idx(self, idx) + } + + fn move_container_to_monitor( + &mut self, + idx: usize, + workspace_idx: Option, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + WindowManager::move_container_to_monitor(self, idx, workspace_idx, follow, direction) + } + + fn focused_workspace_idx(&self) -> eyre::Result { + WindowManager::focused_workspace_idx(self) + } +} + +impl komorebi_core::ContainerCommandHost for WindowManager { + fn monitors_mut(&mut self) -> &mut std::collections::VecDeque { + WindowManager::monitors_mut(self) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/komorebi-for-kde/komorebi/src/window.rs b/komorebi-for-kde/komorebi/src/window.rs index 578aaf7f..41faef78 100644 --- a/komorebi-for-kde/komorebi/src/window.rs +++ b/komorebi-for-kde/komorebi/src/window.rs @@ -24,17 +24,18 @@ use crate::MANAGE_IDENTIFIERS; use crate::PERMAIGNORE_CLASSES; use crate::REGEX_IDENTIFIERS; use crate::backend::backend; -use crate::core::ApplicationIdentifier; use crate::core::Rect; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; -use crate::core::config_generation::MatchingStrategy; use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; use color_eyre::eyre::OptionExt; use komorebi_backend::WindowId; pub use komorebi_config::aspect_ratio::AspectRatio; pub use komorebi_config::aspect_ratio::PredefinedAspectRatio; +use komorebi_config::rules; +use komorebi_config::rules::RuleQuirks; +use komorebi_config::rules::RuleSubject; use regex::Regex; use serde::Deserialize; use serde::Serialize; @@ -568,10 +569,6 @@ fn window_is_eligible( true } -/// Returns the last of `identifiers` that matches a window with this title, executable, classes -/// and path, if one does: a simple rule matches when its one condition does -/// ([`should_act_individual`]), and a composite rule when all of its conditions do -#[allow(clippy::cognitive_complexity, clippy::too_many_lines)] /// [`should_act`] for a window that has one class pub fn should_act_window( title: &str, @@ -610,6 +607,9 @@ pub fn should_act_window_individual( ) } +/// Returns the last of `identifiers` that matches a window with this title, executable, classes +/// and path, if one does (the shared evaluation, [`komorebi_config::rules::should_act`], with a +/// `.exe` in a rule id ignored) pub fn should_act( title: &str, exe_name: &str, @@ -618,52 +618,22 @@ pub fn should_act( identifiers: &[MatchingRule], regex_identifiers: &HashMap, ) -> Option { - let mut matching_rule = None; - for rule in identifiers { - match rule { - MatchingRule::Simple(identifier) => { - if should_act_individual( - title, - exe_name, - classes, - path, - identifier, - regex_identifiers, - ) { - matching_rule = Some(rule.clone()); - }; - } - MatchingRule::Composite(identifiers) => { - let mut composite_results = vec![]; - for identifier in identifiers { - composite_results.push(should_act_individual( - title, - exe_name, - classes, - path, - identifier, - regex_identifiers, - )); - } - - if composite_results.iter().all(|&x| x) { - matching_rule = Some(rule.clone()); - } - } - } - } - - matching_rule + rules::should_act( + &RuleSubject { + title, + exe_name, + classes, + path, + }, + RuleQuirks::UNIX, + identifiers, + regex_identifiers, + ) } /// Returns true if and only if the condition `identifier` holds for a window with this title, -/// executable, classes and path -/// -/// The condition compares the title, the executable, any of the classes or the path with its id, -/// by its matching strategy. Without one, or with `Legacy`, a title or a class matches when it -/// starts or ends with the id, and an executable or a path when it is the id. A `Regex` id is -/// looked up in `regex_identifiers`, and an id with no compiled regex there matches nothing. A -/// `.exe` in the id is ignored. +/// executable, classes and path (the shared evaluation, +/// [`komorebi_config::rules::should_act_individual`], with a `.exe` in the id ignored) pub fn should_act_individual( title: &str, exe_name: &str, @@ -672,263 +642,17 @@ pub fn should_act_individual( identifier: &IdWithIdentifier, regex_identifiers: &HashMap, ) -> bool { - let mut should_act = false; - - let mut identifier = identifier.clone(); - identifier.id = identifier.id.replace(".exe", ""); - - match identifier.matching_strategy { - None | Some(MatchingStrategy::Legacy) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.starts_with(&identifier.id) || title.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.starts_with(&identifier.id) || class.ends_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.eq(&identifier.id) { - should_act = true; - } - } + rules::should_act_individual( + &RuleSubject { + title, + exe_name, + classes, + path, }, - Some(MatchingStrategy::Equals) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.eq(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.eq(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotEqual) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if !class.eq(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if !exe_name.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.eq(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::StartsWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.starts_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.starts_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotStartWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if !class.starts_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if !exe_name.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.starts_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::EndsWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.ends_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.ends_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotEndWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if !class.ends_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if !exe_name.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.ends_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::Contains) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.contains(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.contains(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotContain) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if !class.contains(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if !exe_name.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.contains(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::Regex) => match identifier.kind { - ApplicationIdentifier::Title => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(title) - { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if let Some(re) = regex_identifiers.get(&identifier.id) { - for class in classes { - if re.is_match(class) { - should_act = true; - } - } - } - } - ApplicationIdentifier::Exe => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(exe_name) - { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(path) - { - should_act = true; - } - } - }, - } - - should_act + RuleQuirks::UNIX, + identifier, + regex_identifiers, + ) } #[cfg(test)] @@ -937,6 +661,8 @@ mod tests { use crate::backend::fake::Command; use crate::backend::fake::FakeBackend; use crate::backend::with_backend; + use crate::core::ApplicationIdentifier; + use crate::core::config_generation::MatchingStrategy; use std::sync::Arc; fn fake_with(id: u32) -> Arc { diff --git a/komorebi-for-kde/komorebi/tests/rule_matching.rs b/komorebi-for-kde/komorebi/tests/rule_matching.rs index 82de0259..de9d0853 100644 --- a/komorebi-for-kde/komorebi/tests/rule_matching.rs +++ b/komorebi-for-kde/komorebi/tests/rule_matching.rs @@ -1,426 +1,19 @@ -//! 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. +//! A manage rule rescuing a window an ignore rule covers, through the KDE daemon. Which window a +//! rule matches (kinds, strategies, composite, last wins) is tested once for all daemons in +//! `crates/komorebi-config/tests/rule_matching.rs`; what stays here is the daemon's `should_manage` +//! on the fake backend. 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, -) -> 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 { - 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), diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index 6884c5c6..da3e5181 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -292,158 +292,27 @@ impl WindowManager { /// 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(()) + komorebi_core::cycle_focus_workspace(self, direction) } /// 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(()) + komorebi_core::cycle_focus_empty_workspace(self, direction) } /// 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(()) + komorebi_core::close_workspace(self) } /// 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)?; - } + komorebi_core::move_container_to_last_workspace(self, follow) + } - 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(()) + /// Focuses the workspace that was focused before this one + pub fn focus_last_workspace(&mut self) -> eyre::Result<()> { + komorebi_core::focus_last_workspace(self) } /// Looks for a window of the executable `exe` on every monitor and workspace, and focuses it @@ -673,40 +542,24 @@ impl WindowManager { monitor_idx, workspace_idx, container_idx, - ) => { - let monitor = self - .monitors_mut() - .get_mut(monitor_idx) - .ok_or_eyre("no monitor at the given index")?; - - let workspace = monitor - .workspaces_mut() - .get_mut(workspace_idx) - .ok_or_eyre("no workspace at the given index")?; - - if let Some(container) = workspace.containers_mut().get_mut(container_idx) { - container.locked = true; - } - } + ) => komorebi_core::set_container_locked( + self, + monitor_idx, + workspace_idx, + container_idx, + true, + )?, SocketMessage::UnlockMonitorWorkspaceContainer( monitor_idx, workspace_idx, container_idx, - ) => { - let monitor = self - .monitors_mut() - .get_mut(monitor_idx) - .ok_or_eyre("no monitor at the given index")?; - - let workspace = monitor - .workspaces_mut() - .get_mut(workspace_idx) - .ok_or_eyre("no workspace at the given index")?; - - if let Some(container) = workspace.containers_mut().get_mut(container_idx) { - container.locked = false; - } - } + ) => komorebi_core::set_container_locked( + self, + monitor_idx, + workspace_idx, + container_idx, + false, + )?, SocketMessage::FlipLayout(layout_flip) => self.flip_layout(layout_flip)?, SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, SocketMessage::CycleLayout(direction) => self.cycle_layout(direction)?, @@ -720,14 +573,7 @@ impl WindowManager { self.is_paused = !self.is_paused; } SocketMessage::CycleFocusMonitor(direction) => { - let monitor_idx = direction.next_idx( - self.focused_monitor_idx(), - NonZeroUsize::new(self.monitors().len()) - .ok_or_eyre("there must be at least one monitor")?, - ); - - self.focus_monitor(monitor_idx)?; - self.update_focused_workspace(self.mouse_follows_focus, true)?; + komorebi_core::cycle_focus_monitor(self, direction)? } SocketMessage::CycleFocusWorkspace(direction) => { self.cycle_focus_workspace(direction)? @@ -744,38 +590,7 @@ impl WindowManager { self.focus_monitor(monitor_idx)?; } } - SocketMessage::FocusLastWorkspace => { - // 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 idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.focus_workspace(last_focused_workspace)?; - } - - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); - } + SocketMessage::FocusLastWorkspace => self.focus_last_workspace()?, SocketMessage::FocusWorkspaceNumber(workspace_idx) => { if self.focused_workspace_idx().unwrap_or_default() != workspace_idx { self.focus_workspace(workspace_idx)?; @@ -810,15 +625,7 @@ impl WindowManager { self.focus_workspace(workspace_idx)?; } SocketMessage::FocusMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { - let focused_monitor_idx = self.focused_monitor_idx(); - let focused_workspace_idx = self.focused_workspace_idx().unwrap_or_default(); - - let focused_pair = (focused_monitor_idx, focused_workspace_idx); - - if focused_pair != (monitor_idx, workspace_idx) { - self.focus_monitor(monitor_idx)?; - self.focus_workspace(workspace_idx)?; - } + komorebi_core::focus_monitor_workspace_number(self, monitor_idx, workspace_idx)? } SocketMessage::FocusNamedWorkspace(ref name) => { if let Some((monitor_idx, workspace_idx)) = @@ -1074,18 +881,7 @@ impl WindowManager { self.move_container_to_last_workspace(false)?; } SocketMessage::CycleMoveContainerToWorkspace(direction) => { - 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.move_container_to_workspace(workspace_idx, true, None)?; + komorebi_core::cycle_move_container_to_workspace(self, direction, true)? } SocketMessage::MoveContainerToMonitorNumber(monitor_idx) => { let direction = self.direction_from_monitor_idx(monitor_idx); @@ -1095,60 +891,33 @@ impl WindowManager { self.swap_focused_monitor(monitor_idx)?; } SocketMessage::CycleMoveContainerToMonitor(direction) => { - let monitor_idx = direction.next_idx( - self.focused_monitor_idx(), - NonZeroUsize::new(self.monitors().len()) - .ok_or_eyre("there must be at least one monitor")?, - ); - - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor(monitor_idx, None, true, direction)?; + komorebi_core::cycle_move_container_to_monitor(self, direction, true)? } SocketMessage::CycleSendContainerToWorkspace(direction) => { - 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.move_container_to_workspace(workspace_idx, false, None)?; + komorebi_core::cycle_move_container_to_workspace(self, direction, false)? } SocketMessage::SendContainerToMonitorNumber(monitor_idx) => { let direction = self.direction_from_monitor_idx(monitor_idx); self.move_container_to_monitor(monitor_idx, None, false, direction)?; } SocketMessage::CycleSendContainerToMonitor(direction) => { - let monitor_idx = direction.next_idx( - self.focused_monitor_idx(), - NonZeroUsize::new(self.monitors().len()) - .ok_or_eyre("there must be at least one monitor")?, - ); - - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor(monitor_idx, None, false, direction)?; + komorebi_core::cycle_move_container_to_monitor(self, direction, false)? } SocketMessage::SendContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor( + komorebi_core::move_container_to_monitor_workspace_number( + self, monitor_idx, - Option::from(workspace_idx), + workspace_idx, false, - direction, - )?; + )? } SocketMessage::MoveContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor( + komorebi_core::move_container_to_monitor_workspace_number( + self, monitor_idx, - Option::from(workspace_idx), + workspace_idx, true, - direction, - )?; + )? } SocketMessage::SendContainerToNamedWorkspace(ref workspace) => { if let Some((monitor_idx, workspace_idx)) = @@ -1958,6 +1727,86 @@ pub fn read_commands_uds(wm: &Arc>, stream: UnixStream) -> komorebi_transport::read_commands::(wm, stream, &NoPolicy) } +/// The window manager as the shared commands of `komorebi_core::command` see it +impl komorebi_core::CommandHost for WindowManager { + type P = crate::workspace::MacosPlatform; + + fn monitors(&self) -> &std::collections::VecDeque { + WindowManager::monitors(self) + } + + fn focused_monitor(&self) -> Option<&crate::monitor::Monitor> { + WindowManager::focused_monitor(self) + } + + fn focused_monitor_mut(&mut self) -> Option<&mut crate::monitor::Monitor> { + WindowManager::focused_monitor_mut(self) + } + + fn focused_monitor_idx(&self) -> usize { + WindowManager::focused_monitor_idx(self) + } + + fn monitor_idx_from_current_pos(&mut self) -> Option { + WindowManager::monitor_idx_from_current_pos(self) + } + + fn focus_monitor(&mut self, idx: usize) -> eyre::Result<()> { + WindowManager::focus_monitor(self, idx) + } + + fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> { + WindowManager::focus_workspace(self, idx) + } + + fn move_container_to_workspace( + &mut self, + idx: usize, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + WindowManager::move_container_to_workspace(self, idx, follow, direction) + } +} + +impl komorebi_core::MonitorCommandHost for WindowManager { + fn mouse_follows_focus(&self) -> bool { + self.mouse_follows_focus + } + + fn update_focused_workspace( + &mut self, + follow_focus: bool, + trigger_focus: bool, + ) -> eyre::Result<()> { + WindowManager::update_focused_workspace(self, follow_focus, trigger_focus) + } + + fn direction_from_monitor_idx(&self, idx: usize) -> Option { + WindowManager::direction_from_monitor_idx(self, idx) + } + + fn move_container_to_monitor( + &mut self, + idx: usize, + workspace_idx: Option, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + WindowManager::move_container_to_monitor(self, idx, workspace_idx, follow, direction) + } + + fn focused_workspace_idx(&self) -> eyre::Result { + WindowManager::focused_workspace_idx(self) + } +} + +impl komorebi_core::ContainerCommandHost for WindowManager { + fn monitors_mut(&mut self) -> &mut std::collections::VecDeque { + WindowManager::monitors_mut(self) + } +} + #[cfg(test)] mod tests { use crate::SocketMessage; diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 895b6673..92a29da4 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -39,12 +39,10 @@ use crate::animation::tracks::Verdict; use crate::application::Application; use crate::arrival; use crate::cf_dictionary_value; -use crate::core::ApplicationIdentifier; use crate::core::Rect; use crate::core::WindowHidingPosition; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; -use crate::core::config_generation::MatchingStrategy; use crate::core_graphics::CoreGraphicsApi; use crate::hidden_frame; use crate::is_visible_on_another_display; @@ -59,6 +57,9 @@ use crate::window_manager_event_listener; use color_eyre::eyre; pub use komorebi_config::aspect_ratio::AspectRatio; pub use komorebi_config::aspect_ratio::PredefinedAspectRatio; +use komorebi_config::rules; +use komorebi_config::rules::RuleQuirks; +use komorebi_config::rules::RuleSubject; use objc2::__framework_prelude::Retained; use objc2_app_kit::NSApplicationActivationOptions; use objc2_app_kit::NSRunningApplication; @@ -1824,7 +1825,9 @@ fn window_is_eligible( true } -#[allow(clippy::cognitive_complexity, clippy::too_many_lines)] +/// Returns the last of `identifiers` that matches a window with this title, executable, classes +/// and path, if one does (the shared evaluation, [`komorebi_config::rules::should_act`], with a +/// `.exe` in a rule id ignored) pub fn should_act( title: &str, exe_name: &str, @@ -1833,44 +1836,22 @@ pub fn should_act( identifiers: &[MatchingRule], regex_identifiers: &HashMap, ) -> Option { - let mut matching_rule = None; - for rule in identifiers { - match rule { - MatchingRule::Simple(identifier) => { - if should_act_individual( - title, - exe_name, - classes, - path, - identifier, - regex_identifiers, - ) { - matching_rule = Some(rule.clone()); - }; - } - MatchingRule::Composite(identifiers) => { - let mut composite_results = vec![]; - for identifier in identifiers { - composite_results.push(should_act_individual( - title, - exe_name, - classes, - path, - identifier, - regex_identifiers, - )); - } - - if composite_results.iter().all(|&x| x) { - matching_rule = Some(rule.clone()); - } - } - } - } - - matching_rule + rules::should_act( + &RuleSubject { + title, + exe_name, + classes, + path, + }, + RuleQuirks::UNIX, + identifiers, + regex_identifiers, + ) } +/// Returns true if and only if the condition `identifier` holds for a window with this title, +/// executable, classes and path (the shared evaluation, +/// [`komorebi_config::rules::should_act_individual`], with a `.exe` in the id ignored) pub fn should_act_individual( title: &str, exe_name: &str, @@ -1879,263 +1860,17 @@ pub fn should_act_individual( identifier: &IdWithIdentifier, regex_identifiers: &HashMap, ) -> bool { - let mut should_act = false; - - let mut identifier = identifier.clone(); - identifier.id = identifier.id.replace(".exe", ""); - - match identifier.matching_strategy { - None | Some(MatchingStrategy::Legacy) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.starts_with(&identifier.id) || title.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.starts_with(&identifier.id) || class.ends_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.eq(&identifier.id) { - should_act = true; - } - } + rules::should_act_individual( + &RuleSubject { + title, + exe_name, + classes, + path, }, - Some(MatchingStrategy::Equals) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.eq(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.eq(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotEqual) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if !class.eq(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if !exe_name.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.eq(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::StartsWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.starts_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.starts_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotStartWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if !class.starts_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if !exe_name.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.starts_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::EndsWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.ends_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.ends_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotEndWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if !class.ends_with(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if !exe_name.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.ends_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::Contains) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if class.contains(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if exe_name.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.contains(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotContain) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - for class in classes { - if !class.contains(&identifier.id) { - should_act = true; - } - } - } - ApplicationIdentifier::Exe => { - if !exe_name.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.contains(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::Regex) => match identifier.kind { - ApplicationIdentifier::Title => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(title) - { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if let Some(re) = regex_identifiers.get(&identifier.id) { - for class in classes { - if re.is_match(class) { - should_act = true; - } - } - } - } - ApplicationIdentifier::Exe => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(exe_name) - { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(path) - { - should_act = true; - } - } - }, - } - - should_act + RuleQuirks::UNIX, + identifier, + regex_identifiers, + ) } #[cfg(test)] diff --git a/komorebi/src/animation/engine.rs b/komorebi/src/animation/engine.rs index ce4c3182..64782215 100644 --- a/komorebi/src/animation/engine.rs +++ b/komorebi/src/animation/engine.rs @@ -131,8 +131,7 @@ impl AnimationEngine { ANIMATION_MANAGER.lock().start(key.as_str()); } - let target_frame_time = - Duration::from_millis(1000 / crate::settings::animation_fps()); + let target_frame_time = Duration::from_millis(1000 / crate::settings::animation_fps()); let animation_start = Instant::now(); let mut stats = FrameStats::default(); diff --git a/komorebi/src/border_manager/border.rs b/komorebi/src/border_manager/border.rs index cdb9b5fd..6050f9b4 100644 --- a/komorebi/src/border_manager/border.rs +++ b/komorebi/src/border_manager/border.rs @@ -835,8 +835,10 @@ mod tests { let tracked_hwnd = tracked.0 as isize; // 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 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"); diff --git a/komorebi/src/border_manager/mod.rs b/komorebi/src/border_manager/mod.rs index e06a3a6b..f4036938 100644 --- a/komorebi/src/border_manager/mod.rs +++ b/komorebi/src/border_manager/mod.rs @@ -421,8 +421,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result // however this pass ends, `continue` included, the thread is waiting for the next let _waiting = Waiting; // Check the wm state every time we receive a notification - let state = wm.lock(); - let _held = crate::lock_holder::held("border manager"); + let state = crate::lock_holder::lock(&wm, "border manager"); let is_paused = state.is_paused; let focused_monitor_idx = state.focused_monitor_idx(); let focused_workspace_idx = diff --git a/komorebi/src/daemon.rs b/komorebi/src/daemon.rs index 81ad851c..5b723e88 100644 --- a/komorebi/src/daemon.rs +++ b/komorebi/src/daemon.rs @@ -15,13 +15,13 @@ use std::sync::atomic::Ordering; #[cfg(feature = "deadlock_detection")] use std::time::Duration; +use crate::animation::AnimationEngine; +use crate::replace_env_in_path; use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; use color_eyre::eyre::bail; use crossbeam_utils::Backoff; -use crate::animation::AnimationEngine; -use crate::replace_env_in_path; use parking_lot::Mutex; #[cfg(feature = "deadlock_detection")] use parking_lot::deadlock; @@ -333,6 +333,7 @@ pub fn run() -> eyre::Result<()> { focus_manager::listen_for_notifications(wm.clone()); theme_manager::listen_for_notifications(); + crate::heartbeat::start(); listen_for_commands(wm.clone()); if let Some(port) = opts.tcp_port { diff --git a/komorebi/src/heartbeat.rs b/komorebi/src/heartbeat.rs new file mode 100644 index 00000000..d8039354 --- /dev/null +++ b/komorebi/src/heartbeat.rs @@ -0,0 +1,39 @@ +//! Evidence of a stall of the whole daemon. +//! +//! A thread that sleeps 100 ms in a loop and says so when it wakes up much later than that. If +//! it is late in the same moments in which every other thread of the daemon is silent, the +//! process (or the guest it runs in) was not scheduled; if only some threads are silent, one of +//! them holds something (see [`crate::lock_holder`]). + +use std::time::Duration; +use std::time::Instant; + +/// How long the heartbeat thread sleeps between two beats +const BEAT: Duration = Duration::from_millis(100); + +/// A beat later than this after the one before is logged +const LATE: Duration = Duration::from_millis(500); + +/// Starts the heartbeat thread +pub fn start() { + let _ = std::thread::Builder::new() + .name("heartbeat".to_string()) + .spawn(|| { + let mut last = Instant::now(); + + loop { + std::thread::sleep(BEAT); + + let now = Instant::now(); + let late = now.duration_since(last).saturating_sub(BEAT); + last = now; + + if late >= LATE { + tracing::warn!( + "heartbeat was {} ms late: the daemon was not scheduled for that long", + late.as_millis() + ); + } + } + }); +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index c6e2b36d..ef98074a 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -3,11 +3,11 @@ #[macro_use] extern crate komorebi_collections; -pub mod daemon; pub mod animation; pub mod border_manager; pub mod cloaked; pub mod com; +pub mod daemon; pub use komorebi_collections::ring; pub mod container; pub mod core; @@ -15,13 +15,14 @@ pub mod focus_manager; pub mod live_resize; pub use komorebi_collections::Lockable; pub use komorebi_collections::lockable_sequence; +pub mod heartbeat; +pub mod lock_holder; pub mod monitor; pub mod monitor_reconciliator; pub mod pan; pub mod process_command; pub mod process_event; pub mod process_movement; -pub mod lock_holder; pub mod reaper; pub mod scrolling; pub mod set_window_position; @@ -268,6 +269,10 @@ pub static DEFAULT_RESIZE_DELTA: i32 = komorebi_settings::shared::DEFAULT_RESIZE pub static DEFAULT_MOUSE_FOLLOWS_FOCUS: bool = komorebi_settings::shared::DEFAULT_MOUSE_FOLLOWS_FOCUS; +/// Counts the commands the window manager has processed. An answer computed from the rule lists +/// outside the lock (see `process_event::ManageCheck`) is only used if no command, which is what +/// changes those lists, has run since. +pub static COMMAND_GENERATION: AtomicU64 = AtomicU64::new(0); pub static INITIAL_CONFIGURATION_LOADED: AtomicBool = AtomicBool::new(false); pub static CUSTOM_FFM: AtomicBool = AtomicBool::new(false); pub static SESSION_ID: AtomicU32 = AtomicU32::new(0); diff --git a/komorebi/src/lock_holder.rs b/komorebi/src/lock_holder.rs index c43b66ee..d1ba2e16 100644 --- a/komorebi/src/lock_holder.rs +++ b/komorebi/src/lock_holder.rs @@ -91,6 +91,38 @@ pub fn describe() -> Option { }) } +/// A lock guard together with the record of who holds it, released together: the record first, then +/// the lock, so the diagnostics never say that a thread holds the lock after it has let go. Drop it +/// (`drop(guard)`) at the point where the lock is released. +pub struct HeldGuard<'a, T> { + // field order is drop order: the record goes before the guard + _held: Held, + guard: parking_lot::MutexGuard<'a, T>, +} + +/// Locks `mutex` and records `what` as the holder until the returned guard is dropped +pub fn lock(mutex: &Mutex, what: impl Into>) -> HeldGuard<'_, T> { + let guard = mutex.lock(); + HeldGuard { + _held: held(what), + guard, + } +} + +impl std::ops::Deref for HeldGuard<'_, T> { + type Target = T; + + fn deref(&self) -> &T { + &self.guard + } +} + +impl std::ops::DerefMut for HeldGuard<'_, T> { + fn deref_mut(&mut self) -> &mut T { + &mut self.guard + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/komorebi/src/monitor_reconciliator/mod.rs b/komorebi/src/monitor_reconciliator/mod.rs index 83c0d418..990a264f 100644 --- a/komorebi/src/monitor_reconciliator/mod.rs +++ b/komorebi/src/monitor_reconciliator/mod.rs @@ -276,8 +276,7 @@ where // Keep reference to Arc for potential re-locking let wm_arc = Arc::clone(&wm); - let mut wm = wm.lock(); - let _held = crate::lock_holder::held("monitor reconciliator"); + let mut wm = crate::lock_holder::lock(&wm, "monitor reconciliator"); let initial_state = State::from(wm.as_ref()); @@ -452,7 +451,7 @@ where ); // Re-acquire locks for state restoration - wm = wm_arc.lock(); + wm = crate::lock_holder::lock(&wm_arc, "monitor reconciliator"); // Update Win32 data for all monitors for monitor in wm.monitors_mut() { @@ -535,7 +534,7 @@ where ); // Re-acquire locks for removal processing - wm = wm_arc.lock(); + wm = crate::lock_holder::lock(&wm_arc, "monitor reconciliator"); monitor_cache = MONITOR_CACHE .get_or_init(|| Mutex::new(HashMap::new())) .lock(); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index ffa6db6d..6cc8c186 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -114,6 +114,22 @@ struct WindowsConnectionPolicy; impl ConnectionPolicy for WindowsConnectionPolicy { fn on_accept(&self, stream: &UnixStream) { + // when connections come in: a request that waits in the backlog while the process is + // stalled is seen here late, next to the heartbeat + { + static LAST_ACCEPT: parking_lot::Mutex> = + parking_lot::Mutex::new(None); + let now = std::time::Instant::now(); + let since = LAST_ACCEPT + .lock() + .replace(now) + .map(|last| now.duration_since(last)); + tracing::debug!( + "accepted a command connection ({} ms since the previous one)", + since.map_or(-1, |d| d.as_millis() as i64) + ); + } + match stream.set_read_timeout(Some(Duration::from_secs(1))) { Ok(()) => {} Err(error) => tracing::error!("{}", error), @@ -313,6 +329,15 @@ impl WindowManager { ) -> eyre::Result<()> { let _held = crate::lock_holder::held(format!("command {message}")); let command_started = std::time::Instant::now(); + // when this command is over, an event answer computed before it is not used (see + // `COMMAND_GENERATION`); the bump comes after the command has changed what it changes + struct BumpGeneration; + impl Drop for BumpGeneration { + fn drop(&mut self) { + crate::COMMAND_GENERATION.fetch_add(1, Ordering::SeqCst); + } + } + let _bump_generation = BumpGeneration; if let Some(virtual_desktop_id) = &self.virtual_desktop_id && let Some(id) = current_virtual_desktop() && id != *virtual_desktop_id @@ -435,40 +460,24 @@ impl WindowManager { monitor_idx, workspace_idx, container_idx, - ) => { - let monitor = self - .monitors_mut() - .get_mut(monitor_idx) - .ok_or_eyre("no monitor at the given index")?; - - let workspace = monitor - .workspaces_mut() - .get_mut(workspace_idx) - .ok_or_eyre("no workspace at the given index")?; - - if let Some(container) = workspace.containers_mut().get_mut(container_idx) { - container.locked = true; - } - } + ) => komorebi_core::set_container_locked( + self, + monitor_idx, + workspace_idx, + container_idx, + true, + )?, SocketMessage::UnlockMonitorWorkspaceContainer( monitor_idx, workspace_idx, container_idx, - ) => { - let monitor = self - .monitors_mut() - .get_mut(monitor_idx) - .ok_or_eyre("no monitor at the given index")?; - - let workspace = monitor - .workspaces_mut() - .get_mut(workspace_idx) - .ok_or_eyre("no workspace at the given index")?; - - if let Some(container) = workspace.containers_mut().get_mut(container_idx) { - container.locked = false; - } - } + ) => komorebi_core::set_container_locked( + self, + monitor_idx, + workspace_idx, + container_idx, + false, + )?, SocketMessage::ToggleLock => self.toggle_lock()?, SocketMessage::ToggleFloat => self.toggle_float(false)?, SocketMessage::ToggleMonocle => self.toggle_monocle()?, @@ -655,18 +664,7 @@ impl WindowManager { self.move_container_to_workspace(workspace_idx, true, None)?; } SocketMessage::CycleMoveContainerToWorkspace(direction) => { - 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.move_container_to_workspace(workspace_idx, true, None)?; + komorebi_core::cycle_move_container_to_workspace(self, direction, true)? } SocketMessage::MoveContainerToMonitorNumber(monitor_idx) => { let direction = self.direction_from_monitor_idx(monitor_idx); @@ -676,63 +674,36 @@ impl WindowManager { self.swap_focused_monitor(monitor_idx)?; } SocketMessage::CycleMoveContainerToMonitor(direction) => { - let monitor_idx = direction.next_idx( - self.focused_monitor_idx(), - NonZeroUsize::new(self.monitors().len()) - .ok_or_eyre("there must be at least one monitor")?, - ); - - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor(monitor_idx, None, true, direction)?; + komorebi_core::cycle_move_container_to_monitor(self, direction, true)? } SocketMessage::SendContainerToWorkspaceNumber(workspace_idx) => { self.move_container_to_workspace(workspace_idx, false, None)?; } SocketMessage::CycleSendContainerToWorkspace(direction) => { - 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.move_container_to_workspace(workspace_idx, false, None)?; + komorebi_core::cycle_move_container_to_workspace(self, direction, false)? } SocketMessage::SendContainerToMonitorNumber(monitor_idx) => { let direction = self.direction_from_monitor_idx(monitor_idx); self.move_container_to_monitor(monitor_idx, None, false, direction)?; } SocketMessage::CycleSendContainerToMonitor(direction) => { - let monitor_idx = direction.next_idx( - self.focused_monitor_idx(), - NonZeroUsize::new(self.monitors().len()) - .ok_or_eyre("there must be at least one monitor")?, - ); - - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor(monitor_idx, None, false, direction)?; + komorebi_core::cycle_move_container_to_monitor(self, direction, false)? } SocketMessage::SendContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor( + komorebi_core::move_container_to_monitor_workspace_number( + self, monitor_idx, - Option::from(workspace_idx), + workspace_idx, false, - direction, - )?; + )? } SocketMessage::MoveContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { - let direction = self.direction_from_monitor_idx(monitor_idx); - self.move_container_to_monitor( + komorebi_core::move_container_to_monitor_workspace_number( + self, monitor_idx, - Option::from(workspace_idx), + workspace_idx, true, - direction, - )?; + )? } SocketMessage::SendContainerToNamedWorkspace(ref workspace) => { if let Some((monitor_idx, workspace_idx)) = @@ -787,14 +758,7 @@ impl WindowManager { self.toggle_tiling()?; } SocketMessage::CycleFocusMonitor(direction) => { - let monitor_idx = direction.next_idx( - self.focused_monitor_idx(), - NonZeroUsize::new(self.monitors().len()) - .ok_or_eyre("there must be at least one monitor")?, - ); - - self.focus_monitor(monitor_idx)?; - self.update_focused_workspace(self.mouse_follows_focus, true)?; + komorebi_core::cycle_focus_monitor(self, direction)? } SocketMessage::FocusMonitorNumber(monitor_idx) => { self.focus_monitor(monitor_idx)?; @@ -983,15 +947,7 @@ impl WindowManager { self.focus_workspace_numbers(workspace_idx)?; } SocketMessage::FocusMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { - let focused_monitor_idx = self.focused_monitor_idx(); - let focused_workspace_idx = self.focused_workspace_idx().unwrap_or_default(); - - let focused_pair = (focused_monitor_idx, focused_workspace_idx); - - if focused_pair != (monitor_idx, workspace_idx) { - self.focus_monitor(monitor_idx)?; - self.focus_workspace(workspace_idx)?; - } + komorebi_core::focus_monitor_workspace_number(self, monitor_idx, workspace_idx)? } SocketMessage::FocusNamedWorkspace(ref name) => { if let Some((monitor_idx, workspace_idx)) = @@ -1443,10 +1399,12 @@ impl WindowManager { }); } SocketMessage::Transparency(enable) => { - crate::settings::settings().update(|settings| settings.shared.transparency.enabled = enable); + crate::settings::settings() + .update(|settings| settings.shared.transparency.enabled = enable); } SocketMessage::TransparencyAlpha(alpha) => { - crate::settings::settings().update(|settings| settings.shared.transparency.alpha = alpha); + crate::settings::settings() + .update(|settings| settings.shared.transparency.alpha = alpha); } SocketMessage::StackbarMode(mode) => { STACKBAR_MODE.store(mode); @@ -2183,33 +2141,7 @@ impl WindowManager { Ok(()) } pub fn move_container_to_last_workspace(&mut self, follow: bool) -> eyre::Result<()> { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.move_container_to_workspace(last_focused_workspace, follow, None)?; - } - - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); - Ok(()) + komorebi_core::move_container_to_last_workspace(self, follow) } pub fn focus_workspace_numbers(&mut self, workspace_idx: usize) -> eyre::Result<()> { @@ -2239,147 +2171,19 @@ impl WindowManager { } pub fn focus_last_workspace(&mut self) -> eyre::Result<()> { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let idx = self - .focused_monitor() - .ok_or_eyre("there is no monitor")? - .focused_workspace_idx(); - - if let Some(monitor) = self.focused_monitor_mut() - && let Some(last_focused_workspace) = monitor.last_focused_workspace - { - self.focus_workspace(last_focused_workspace)?; - } - - self.focused_monitor_mut() - .ok_or_eyre("there is no monitor")? - .last_focused_workspace = Option::from(idx); - Ok(()) + komorebi_core::focus_last_workspace(self) } pub fn close_workspace(&mut self) -> eyre::Result<()> { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let mut can_close = false; - - if let Some(monitor) = self.focused_monitor_mut() { - let focused_workspace_idx = monitor.focused_workspace_idx(); - let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); - - if let Some(workspace) = monitor.focused_workspace() - && monitor.workspaces().len() > 1 - && workspace.containers().is_empty() - && workspace.floating_windows().is_empty() - && workspace.monocle_container.is_none() - && workspace.maximized_window.is_none() - && workspace.name.is_none() - { - can_close = true; - } - - if can_close - && monitor - .workspaces_mut() - .remove(focused_workspace_idx) - .is_some() - { - self.focus_workspace(next_focused_workspace_idx)?; - } - } - Ok(()) + komorebi_core::close_workspace(self) } pub fn cycle_focus_empty_workspace(&mut self, direction: CycleDirection) -> eyre::Result<()> { - // This is to ensure that even on an empty workspace on a secondary monitor, the - // secondary monitor where the cursor is focused will be used as the target for - // the workspace switch op - if let Some(monitor_idx) = self.monitor_idx_from_current_pos() - && monitor_idx != self.focused_monitor_idx() - && let Some(monitor) = self.monitors().get(monitor_idx) - && let Some(workspace) = monitor.focused_workspace() - && workspace.is_empty() - { - self.focus_monitor(monitor_idx)?; - } - - let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; - - let focused_workspace_idx = focused_monitor.focused_workspace_idx(); - let workspaces = focused_monitor.workspaces().len(); - - let mut empty_workspaces = vec![]; - - for (idx, w) in focused_monitor.workspaces().iter().enumerate() { - if w.is_empty() { - empty_workspaces.push(idx); - } - } - - if !empty_workspaces.is_empty() { - let mut workspace_idx = direction.next_idx( - focused_workspace_idx, - NonZeroUsize::new(workspaces).ok_or_eyre("there must be at least one workspace")?, - ); - - while !empty_workspaces.contains(&workspace_idx) { - workspace_idx = direction.next_idx( - workspace_idx, - NonZeroUsize::new(workspaces) - .ok_or_eyre("there must be at least one workspace")?, - ); - } - - self.focus_workspace(workspace_idx)?; - } - Ok(()) + komorebi_core::cycle_focus_empty_workspace(self, direction) } 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(()) + komorebi_core::cycle_focus_workspace(self, direction) } pub fn toggle_workspace_layer(&mut self) -> eyre::Result<()> { @@ -2485,6 +2289,89 @@ impl WindowManager { } } +/// The window manager as the shared commands of `komorebi_core::command` see it +impl komorebi_core::CommandHost for WindowManager { + type P = crate::workspace::WindowsPlatform; + + // Windows lets the pointer pick the monitor first for these commands too + const POINTER_PICKS_THE_MONITOR_FOR_ALL: bool = true; + + fn monitors(&self) -> &std::collections::VecDeque { + WindowManager::monitors(self) + } + + fn focused_monitor(&self) -> Option<&crate::monitor::Monitor> { + WindowManager::focused_monitor(self) + } + + fn focused_monitor_mut(&mut self) -> Option<&mut crate::monitor::Monitor> { + WindowManager::focused_monitor_mut(self) + } + + fn focused_monitor_idx(&self) -> usize { + WindowManager::focused_monitor_idx(self) + } + + fn monitor_idx_from_current_pos(&mut self) -> Option { + WindowManager::monitor_idx_from_current_pos(self) + } + + fn focus_monitor(&mut self, idx: usize) -> eyre::Result<()> { + WindowManager::focus_monitor(self, idx) + } + + fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> { + WindowManager::focus_workspace(self, idx) + } + + fn move_container_to_workspace( + &mut self, + idx: usize, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + WindowManager::move_container_to_workspace(self, idx, follow, direction) + } +} + +impl komorebi_core::MonitorCommandHost for WindowManager { + fn mouse_follows_focus(&self) -> bool { + self.mouse_follows_focus + } + + fn update_focused_workspace( + &mut self, + follow_focus: bool, + trigger_focus: bool, + ) -> eyre::Result<()> { + WindowManager::update_focused_workspace(self, follow_focus, trigger_focus) + } + + fn direction_from_monitor_idx(&self, idx: usize) -> Option { + WindowManager::direction_from_monitor_idx(self, idx) + } + + fn move_container_to_monitor( + &mut self, + idx: usize, + workspace_idx: Option, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + WindowManager::move_container_to_monitor(self, idx, workspace_idx, follow, direction) + } + + fn focused_workspace_idx(&self) -> eyre::Result { + WindowManager::focused_workspace_idx(self) + } +} + +impl komorebi_core::ContainerCommandHost for WindowManager { + fn monitors_mut(&mut self) -> &mut std::collections::VecDeque { + WindowManager::monitors_mut(self) + } +} + #[cfg(test)] mod tests { use super::push_simple_rule; diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 3fcac487..36b11b67 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -122,9 +122,31 @@ pub fn listen_for_events(wm: Arc>) { tracing::info!("listening"); loop { if let Ok(event) = receiver.recv() { - let mut guard = wm.lock(); - let _held = crate::lock_holder::held("process_event"); - match guard.process_event(event) { + // Win32 calls on the event's window and rule matching need no window manager state, so + // they are not done with the lock held (they took seconds for a window that had + // just been created) + let check = ManageCheck::compute(event); + let waiting = std::time::Instant::now(); + let mut guard = crate::lock_holder::lock(&wm, "process_event"); + let handling = std::time::Instant::now(); + let result = guard.process_event_checked(event, check); + let (waited, handled) = (handling.duration_since(waiting), handling.elapsed()); + if waited.max(handled) >= crate::lock_holder::SLOW { + tracing::info!( + "process_event {}: waited for the lock {} ms, handled in {} ms", + event.title(), + waited.as_millis(), + handled.as_millis() + ); + } else { + tracing::debug!( + "process_event {}: waited for the lock {} ms, handled in {} ms", + event.title(), + waited.as_millis(), + handled.as_millis() + ); + } + match result { Ok(()) => {} Err(error) => { if cfg!(debug_assertions) { @@ -139,18 +161,74 @@ pub fn listen_for_events(wm: Arc>) { }); } +/// Whether an event's window is to be managed, found before the window manager is locked +pub struct ManageCheck { + should_manage: eyre::Result, + rule_debug: RuleDebug, + started: std::time::Instant, + generation: u64, +} + +impl ManageCheck { + /// Asks `Window::should_manage` for the window of the event. It reads the window, the rule + /// lists (in their documented lock order) and settings, never the window manager. + pub fn compute(event: WindowManagerEvent) -> Self { + let generation = crate::COMMAND_GENERATION.load(std::sync::atomic::Ordering::SeqCst); + let started = std::time::Instant::now(); + let mut rule_debug = RuleDebug::default(); + let should_manage = event.window().should_manage(Some(event), &mut rule_debug); + tracing::debug!( + "process_event: should_manage took {} ms", + started.elapsed().as_millis() + ); + + Self { + should_manage, + rule_debug, + started, + generation, + } + } + + /// Whether the answer can still be used: no command (which is what changes the rule lists) + /// has been processed since it was computed + fn is_current(&self) -> bool { + self.generation == crate::COMMAND_GENERATION.load(std::sync::atomic::Ordering::SeqCst) + } +} + impl WindowManager { - #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] - #[tracing::instrument(skip(self, event), fields(event = event.title(), winevent = event.winevent(), hwnd = event.hwnd()))] pub fn process_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> { + self.process_event_checked(event, ManageCheck::compute(event)) + } + + #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] + #[tracing::instrument(skip(self, event, check), fields(event = event.title(), winevent = event.winevent(), hwnd = event.hwnd()))] + pub fn process_event_checked( + &mut self, + event: WindowManagerEvent, + check: ManageCheck, + ) -> eyre::Result<()> { if self.is_paused { tracing::trace!("ignoring while paused"); return Ok(()); } - let mut rule_debug = RuleDebug::default(); - - let should_manage = event.window().should_manage(Some(event), &mut rule_debug)?; + // A command may have changed the rule lists while this event waited for the lock: the + // answer is then asked again, here, as it used to be. The window itself may have changed + // in the wait too; the handlers below already cope with a window that is gone or changed, + // as they did for an event that sat in the queue before the lock was taken. + let check = if check.is_current() { + tracing::debug!( + "process_event: should_manage answered {} ms before the lock was held", + check.started.elapsed().as_millis() + ); + check + } else { + ManageCheck::compute(event) + }; + let rule_debug = check.rule_debug; + let should_manage = check.should_manage?; // All event handlers below this point should only be processed if the event is // related to a window that should be managed by the WindowManager. diff --git a/komorebi/src/reaper.rs b/komorebi/src/reaper.rs index 37f8cd81..02904181 100644 --- a/komorebi/src/reaper.rs +++ b/komorebi/src/reaper.rs @@ -77,10 +77,12 @@ fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> for notification in receiver { let orphan_hwnds = notification.0; - let mut wm = wm.lock(); - let _held = crate::lock_holder::held("reaper"); + let mut wm = crate::lock_holder::lock(&wm, "reaper"); let mut update_borders = false; + // what the subscribers are told, and in what state, is decided here with the lock held and + // sent after it is released (a subscriber, or the disk, must not hold the lock) + let mut notifications = vec![]; for (hwnd, (m_idx, w_idx)) in orphan_hwnds.iter() { if let Some(monitor) = wm.monitors_mut().get_mut(*m_idx) { @@ -117,16 +119,23 @@ fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> wm.known_hwnds.remove(hwnd); let window = Window::from(*hwnd); - notify_subscribers( - crate::Notification { - event: NotificationEvent::WindowManager(WindowManagerEvent::Destroy( - WinEvent::ObjectDestroy, - window, - )), - state: wm.as_ref().into(), - }, - true, - )?; + notifications.push(crate::Notification { + event: NotificationEvent::WindowManager(WindowManagerEvent::Destroy( + WinEvent::ObjectDestroy, + window, + )), + state: wm.as_ref().into(), + }); + } + + let seq = HWND_LIST_SEQ.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + let known_hwnds = wm.known_hwnds.keys().copied().collect::>(); + + // the lock is released here, before the subscribers are pushed to and the file is written + drop(wm); + + for notification in notifications { + notify_subscribers(notification, true)?; } if update_borders { @@ -134,14 +143,7 @@ fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> } // Save to file - let hwnd_json = DATA_DIR.join("komorebi.hwnd.json"); - let file = OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(hwnd_json)?; - - serde_json::to_writer_pretty(&file, &wm.known_hwnds.keys().collect::>())?; + write_known_hwnds(seq, &known_hwnds)?; } Ok(()) @@ -213,3 +215,31 @@ fn find_orphans() -> color_eyre::Result<()> { } } } + +/// Numbers the lists of known handles, in the order the window manager decided them (taken with +/// the window manager locked), so that a list written late is not written over a newer one +pub static HWND_LIST_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The number of the list that is in `komorebi.hwnd.json`, and the lock that serialises the writes +static HWND_FILE: Mutex = Mutex::new(0); + +/// Writes `komorebi.hwnd.json`, synchronously, unless a newer list (`seq` from +/// [`HWND_LIST_SEQ`]) has been written already. The reaper calls it after it has released the +/// window manager lock, the commands with it held: the writes do not interleave and the file is +/// never overwritten by an older list. +pub fn write_known_hwnds(seq: u64, hwnds: &[isize]) -> std::io::Result<()> { + let mut written = HWND_FILE.lock(); + if seq < *written { + return Ok(()); + } + + let file = OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(DATA_DIR.join("komorebi.hwnd.json"))?; + serde_json::to_writer_pretty(&file, hwnds)?; + *written = seq; + + Ok(()) +} diff --git a/komorebi/src/stackbar_manager/mod.rs b/komorebi/src/stackbar_manager/mod.rs index 34318339..4d23a8e6 100644 --- a/komorebi/src/stackbar_manager/mod.rs +++ b/komorebi/src/stackbar_manager/mod.rs @@ -95,8 +95,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result let mut stackbars_monitors = STACKBARS_MONITORS.lock(); // Check the wm state every time we receive a notification - let mut state = wm.lock(); - let _held = crate::lock_holder::held("stackbar manager"); + let mut state = crate::lock_holder::lock(&wm, "stackbar manager"); // If stackbars are disabled if matches!(STACKBAR_MODE.load(), StackbarMode::Never) diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index 1bd86d53..dc7208f3 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -311,12 +311,8 @@ impl From<&WindowManager> for StaticConfig { border_offset: Option::from(border_manager::BORDER_OFFSET.load(Ordering::SeqCst)), border: Option::from(border_manager::BORDER_ENABLED.load(Ordering::SeqCst)), border_colours, - transparency: Option::from( - crate::settings::transparency_enabled(), - ), - transparency_alpha: Option::from( - crate::settings::transparency_alpha(), - ), + transparency: Option::from(crate::settings::transparency_enabled()), + transparency_alpha: Option::from(crate::settings::transparency_alpha()), transparency_ignore_rules: None, border_style: Option::from(STYLE.load()), #[allow(deprecated)] diff --git a/komorebi/src/transparency_manager.rs b/komorebi/src/transparency_manager.rs index dccb9d90..ec92409a 100644 --- a/komorebi/src/transparency_manager.rs +++ b/komorebi/src/transparency_manager.rs @@ -78,8 +78,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result known_hwnds.lock().clear(); // Check the wm state every time we receive a notification - let state = wm.lock(); - let _held = crate::lock_holder::held("transparency manager"); + let state = crate::lock_holder::lock(&wm, "transparency manager"); let focused_monitor_idx = state.focused_monitor_idx(); diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 3c1a7a13..1d825d0b 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -22,12 +22,10 @@ use crate::animation::transition; use crate::border_manager; use crate::cloaked; use crate::com::SetCloak; -use crate::core::ApplicationIdentifier; use crate::core::HidingBehaviour; use crate::core::Rect; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; -use crate::core::config_generation::MatchingStrategy; use crate::live_resize; use crate::styles::ExtendedWindowStyle; use crate::styles::WindowStyle; @@ -40,6 +38,9 @@ use color_eyre::eyre; use komorebi_backend::WindowId; pub use komorebi_config::aspect_ratio::AspectRatio; pub use komorebi_config::aspect_ratio::PredefinedAspectRatio; +use komorebi_config::rules; +use komorebi_config::rules::RuleQuirks; +use komorebi_config::rules::RuleSubject; use regex::Regex; use serde::Deserialize; use serde::Serialize; @@ -404,7 +405,6 @@ impl Window { // 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); @@ -585,8 +585,9 @@ impl Window { pub fn transparent(self) -> eyre::Result<()> { // enabled, duration and style from one snapshot - if let Some((duration, style)) = crate::settings::animation_for(TransparencyRenderDispatcher::PREFIX) { - + if let Some((duration, style)) = + crate::settings::animation_for(TransparencyRenderDispatcher::PREFIX) + { let render_dispatcher = TransparencyRenderDispatcher::new( self.hwnd, false, @@ -600,17 +601,15 @@ impl Window { let mut ex_style = self.ex_style()?; ex_style.insert(ExtendedWindowStyle::LAYERED); self.update_ex_style(&ex_style)?; - WindowsApi::set_transparent( - self.hwnd, - crate::settings::transparency_alpha(), - ) + WindowsApi::set_transparent(self.hwnd, crate::settings::transparency_alpha()) } } pub fn opaque(self) -> eyre::Result<()> { // enabled, duration and style from one snapshot - if let Some((duration, style)) = crate::settings::animation_for(TransparencyRenderDispatcher::PREFIX) { - + if let Some((duration, style)) = + crate::settings::animation_for(TransparencyRenderDispatcher::PREFIX) + { let render_dispatcher = TransparencyRenderDispatcher::new( self.hwnd, true, @@ -1074,6 +1073,9 @@ pub fn should_act_window_individual( should_act_individual(title, exe_name, class, path, identifier, regex_identifiers) } +/// Returns the last of `identifiers` that matches a window with this title, executable, class +/// and path, if one does (the shared evaluation, [`komorebi_config::rules::should_act`], with a +/// rule id compared as written) pub fn should_act( title: &str, exe_name: &str, @@ -1082,44 +1084,22 @@ pub fn should_act( identifiers: &[MatchingRule], regex_identifiers: &HashMap, ) -> Option { - let mut matching_rule = None; - for rule in identifiers { - match rule { - MatchingRule::Simple(identifier) => { - if should_act_individual( - title, - exe_name, - class, - path, - identifier, - regex_identifiers, - ) { - matching_rule = Some(rule.clone()); - }; - } - MatchingRule::Composite(identifiers) => { - let mut composite_results = vec![]; - for identifier in identifiers { - composite_results.push(should_act_individual( - title, - exe_name, - class, - path, - identifier, - regex_identifiers, - )); - } - - if composite_results.iter().all(|&x| x) { - matching_rule = Some(rule.clone()); - } - } - } - } - - matching_rule + rules::should_act( + &RuleSubject { + title, + exe_name, + classes: &[class], + path, + }, + RuleQuirks::WINDOWS, + identifiers, + regex_identifiers, + ) } +/// Returns true if and only if the condition `identifier` holds for a window with this title, +/// executable, class and path (the shared evaluation, +/// [`komorebi_config::rules::should_act_individual`], with the id compared as written) pub fn should_act_individual( title: &str, exe_name: &str, @@ -1128,238 +1108,15 @@ pub fn should_act_individual( identifier: &IdWithIdentifier, regex_identifiers: &HashMap, ) -> bool { - let mut should_act = false; - - match identifier.matching_strategy { - None | Some(MatchingStrategy::Legacy) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.starts_with(&identifier.id) || title.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if class.starts_with(&identifier.id) || class.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if exe_name.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.eq(&identifier.id) { - should_act = true; - } - } + rules::should_act_individual( + &RuleSubject { + title, + exe_name, + classes: &[class], + path, }, - Some(MatchingStrategy::Equals) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if class.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if exe_name.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.eq(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotEqual) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if !class.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if !exe_name.eq(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.eq(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::StartsWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if class.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if exe_name.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.starts_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotStartWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if !class.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if !exe_name.starts_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.starts_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::EndsWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if class.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if exe_name.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.ends_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotEndWith) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if !class.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if !exe_name.ends_with(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.ends_with(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::Contains) => match identifier.kind { - ApplicationIdentifier::Title => { - if title.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if class.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if exe_name.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if path.contains(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::DoesNotContain) => match identifier.kind { - ApplicationIdentifier::Title => { - if !title.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if !class.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if !exe_name.contains(&identifier.id) { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if !path.contains(&identifier.id) { - should_act = true; - } - } - }, - Some(MatchingStrategy::Regex) => match identifier.kind { - ApplicationIdentifier::Title => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(title) - { - should_act = true; - } - } - ApplicationIdentifier::Class => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(class) - { - should_act = true; - } - } - ApplicationIdentifier::Exe => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(exe_name) - { - should_act = true; - } - } - ApplicationIdentifier::Path => { - if let Some(re) = regex_identifiers.get(&identifier.id) - && re.is_match(path) - { - should_act = true; - } - } - }, - } - - should_act + RuleQuirks::WINDOWS, + identifier, + regex_identifiers, + ) } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 572d06ee..2abcb4f4 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -5,7 +5,6 @@ use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; use std::env::temp_dir; -use std::fs::OpenOptions; use std::io::ErrorKind; use std::net::Shutdown; use std::num::NonZeroUsize; @@ -4007,23 +4006,12 @@ impl WindowManager { } // Save to file - let hwnd_json = DATA_DIR.join("komorebi.hwnd.json"); - match OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(hwnd_json) - { - Ok(file) => { - if let Err(error) = - serde_json::to_writer_pretty(&file, &known_hwnds.keys().collect::>()) - { - tracing::error!("Failed to save list of known_hwnds on file: {}", error); - } - } - Err(error) => { - tracing::error!("Failed to save list of known_hwnds on file: {}", error); - } + let seq = crate::reaper::HWND_LIST_SEQ.fetch_add(1, Ordering::SeqCst) + 1; + if let Err(error) = crate::reaper::write_known_hwnds( + seq, + &known_hwnds.keys().copied().collect::>(), + ) { + tracing::error!("Failed to save list of known_hwnds on file: {}", error); } // Store new hwnds