diff --git a/architecture.md b/architecture.md index 64b39d9..3f33e48 100644 --- a/architecture.md +++ b/architecture.md @@ -126,7 +126,7 @@ All outer crates depend inward on domain contracts; core depends on none of them - `SurfaceId`, `FaderId`, `ApplicationId`, `GroupId`, and `ProfileId` are stable persisted user IDs. Renaming a display label preserves its ID. - A physical binding is `(surface ID, MIDI channel, message kind, control number) -> fader ID + action`. A logical fader targets exactly one `Application`, `Group`, or the `default` output (later, an explicit `HardwareMixer`). Several faders/surfaces may target the same object. - An application object has selectors on explicit normalized fields: `application.name`, `application.id`, `application.process.binary`, or `media.name`. Preserve raw backend metadata for inspection. Never silently substitute one field for another. -- Matchers are `exact` (case-sensitive whole-string equality) or `regex` (Rust regex syntax, substring search unless anchored). Multiple selectors for an application are ORed. Missing properties do not match. Compile patterns once at config validation, with length/complexity limits; show actual matches in the editor. +- Matchers are `exact` (case-sensitive whole-string equality) or `regex` (Rust regex syntax, substring search unless anchored). Application `selector_mode` defaults to `any` (OR); `all` requires every selector (AND). Missing properties do not match. Empty lists and unknown modes are rejected. Compile patterns once at config validation, with length/complexity limits; show actual matches in the editor. - A matching application controls all its current playback streams. Stopped applications remain configured and display offline; new streams are discovered dynamically. Runtime handles include backend connection epoch plus object ID and an incarnation where needed to prevent ID-reuse bugs. PIDs, backend indices, and discovery order are never durable identity. - Groups reference application IDs only in v1; no nested groups or cycles. Overlapping selectors/groups are allowed: deduplicate resolved streams within each command and show overlap in the editor. Separate commands are serialized by server arrival order; the last accepted command touching a stream wins. Overlap is shared control, not multiple multiplicative gain layers. - Maintain requested state, observed per-stream/per-channel state, pending operation IDs, errors, and availability separately. A write acknowledgment means accepted by the adapter; success requires observation/readback. Derived objects can be `mixed`, `offline`, `pending`, or `partially failed`. @@ -134,8 +134,9 @@ All outer crates depend inward on domain contracts; core depends on none of them ### Planned matching and media-control extensions The agreed stretch-goal order is AND selectors and richer process metadata, -then targeted MPRIS media controls (M13 in `task.md`). These are future work, -not additions to the current profile schema. +then targeted MPRIS media controls (M13 in `task.md`). Selector composition is +implemented in the domain/configuration layer; process metadata and media +controls remain future work, not additions to the current profile schema. The existing `media.name` regex `(?i) - YouTube$` is sufficient for YouTube streams whose reported title has that suffix. Do not couple this use case to diff --git a/config/src/document.rs b/config/src/document.rs index be24977..a005ce0 100644 --- a/config/src/document.rs +++ b/config/src/document.rs @@ -300,6 +300,19 @@ pickup_tolerance = 0.02 }) } + /// Changes selector composition without replacing selectors or their comments. + pub fn set_application_selector_mode( + &mut self, + id: &str, + mode: crate::SelectorMode, + ) -> Result<(), ConfigError> { + self.transaction(|document| { + let table = find_table_mut(document, "applications", id)?; + table["selector_mode"] = value(mode.as_str()); + Ok(()) + }) + } + /// Replaces one capture selector while retaining every other selector. pub fn set_application_selector( &mut self, diff --git a/config/src/lib.rs b/config/src/lib.rs index 1996ec9..57e2752 100644 --- a/config/src/lib.rs +++ b/config/src/lib.rs @@ -29,8 +29,8 @@ pub use paths::{XdgEnvironment, XdgPaths}; pub use profile::{ Action, Adapter, Application, Audio, Binding, Fader, FaderDensity, Group, MessageKind, MixerLayoutEntry, MixerOrientation, NewStreamPolicy, Profile, Selector, SelectorField, - SeparatorDecoration, SeparatorSize, StartupPolicy, StatusDisplayMode, Surface, TargetKind, - UiTheme, + SelectorMode, SeparatorDecoration, SeparatorSize, StartupPolicy, StatusDisplayMode, Surface, + TargetKind, UiTheme, }; pub use state::{ CachedObservation, DesiredWrite, PersistedState, ProfileState, StartupState, UiView, diff --git a/config/src/profile.rs b/config/src/profile.rs index 39097b2..d104a34 100644 --- a/config/src/profile.rs +++ b/config/src/profile.rs @@ -127,6 +127,30 @@ pub struct Application { id: String, label: String, selectors: Vec, + #[serde(default)] + selector_mode: SelectorMode, +} + +/// Composition of an application's nonempty capture selector list. +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SelectorMode { + /// Legacy OR behavior. + #[default] + Any, + /// Require every selector to match. + All, +} + +impl SelectorMode { + /// Stable TOML representation. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Any => "any", + Self::All => "all", + } + } } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] @@ -552,6 +576,12 @@ impl Application { &self.selectors } + /// How this application's capture selectors are combined. + #[must_use] + pub const fn selector_mode(&self) -> SelectorMode { + self.selector_mode + } + /// Compiles this validated application's selectors for live stream matching. pub fn matcher(&self) -> Result { let id = parse_id::(&self.id, "application.id")?; @@ -560,7 +590,11 @@ impl Application { .iter() .map(Selector::compile) .collect::, _>>()?; - ApplicationMatcher::new(id, selectors) + let mode = match self.selector_mode { + SelectorMode::Any => fader_core::SelectorMode::Any, + SelectorMode::All => fader_core::SelectorMode::All, + }; + ApplicationMatcher::with_mode(id, selectors, mode) .map_err(|error| ConfigError::validation("application.selectors", error.to_string())) } } diff --git a/config/tests/editor.rs b/config/tests/editor.rs index 41a2660..2dddf7c 100644 --- a/config/tests/editor.rs +++ b/config/tests/editor.rs @@ -5,6 +5,30 @@ use fader_config::{ const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml"); +#[test] +fn selector_mode_edit_survives_serialization_without_replacing_selectors() { + let mut draft = ProfileDocument::parse(PROFILE).unwrap(); + let original = draft.preview().unwrap().applications()[0] + .selectors() + .to_vec(); + draft + .set_application_selector_mode("music", fader_config::SelectorMode::All) + .unwrap(); + let saved = draft.source(); + let restored = ProfileDocument::parse(&saved).unwrap().preview().unwrap(); + assert_eq!( + restored.applications()[0].selector_mode(), + fader_config::SelectorMode::All + ); + assert_eq!(restored.applications()[0].selectors(), original); + assert!( + draft + .set_application_selector_mode("missing", fader_config::SelectorMode::Any) + .is_err() + ); + assert_eq!(draft.source(), saved); +} + #[test] fn removing_a_surface_clears_its_bindings_and_default_controller_atomically() { let mut draft = ProfileDocument::parse(PROFILE).unwrap(); diff --git a/config/tests/schema.rs b/config/tests/schema.rs index 035ee41..12c23ce 100644 --- a/config/tests/schema.rs +++ b/config/tests/schema.rs @@ -6,6 +6,42 @@ const EXAMPLE: &str = include_str!("../../examples/profiles/desktop.toml"); const ARCH_PIPEWIRE: &str = include_str!("../../examples/profiles/arch-pipewire.toml"); const ARCHITECTURE: &str = include_str!("../../architecture.md"); +#[test] +fn selector_composition_defaults_to_any_and_all_requires_every_field() { + let source = EXAMPLE.replace( + "selectors = [{ field = \"application.name\", exact = \"Music Player\" }]", + "selectors = [{ field = \"application.name\", exact = \"Music Player\" }, { field = \"media.name\", regex = '(?i) - YouTube$' }]", + ); + let partial = StreamMetadata::new().with_application_name("Music Player"); + let complete = partial.clone().with_media_name("A song - YouTube"); + let legacy = Profile::parse(&source).unwrap(); + assert!( + legacy.applications()[0] + .matcher() + .unwrap() + .matches(&partial) + ); + let source = source.replacen( + "label = \"Music\"", + "label = \"Music\"\nselector_mode = \"all\"", + 1, + ); + let profile = Profile::parse(&source).unwrap(); + let matcher = profile.applications()[0].matcher().unwrap(); + assert!(!matcher.matches(&partial)); + assert!(matcher.matches(&complete)); + assert!(!matcher.matches(&complete.with_application_name("Other Player"))); + assert_eq!( + profile, + Profile::parse(&profile.to_toml().unwrap()).unwrap() + ); + assert!( + Profile::parse(&source.replace("selector_mode = \"all\"", "selector_mode = \"xor\"")) + .is_err() + ); + assert!(Profile::parse(&source.replace("regex = '(?i) - YouTube$'", "regex = '['")).is_err()); +} + #[test] fn architecture_profile_parses_and_round_trips_semantically() { let marker = "The following profile"; diff --git a/core/src/lib.rs b/core/src/lib.rs index f603b2f..1fd120f 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -31,7 +31,7 @@ pub use group::{RelativeGroupState, VolumeMode, VolumeView, plan_volume, volume_ pub use id::{ApplicationId, FaderId, GroupId, IdError, ProfileId, SurfaceId}; pub use matching::{ ApplicationMatcher, ApplicationRuntime, ApplicationSelector, MetadataField, SelectorError, - SelectorKind, StreamHandle, StreamMetadata, + SelectorKind, SelectorMode, StreamHandle, StreamMetadata, }; pub use mute::{MuteIntent, MutePlanner, mute_view}; pub use pickup::{Pickup, PickupError, PickupState}; diff --git a/core/src/matching.rs b/core/src/matching.rs index fe3be62..ed928f5 100644 --- a/core/src/matching.rs +++ b/core/src/matching.rs @@ -230,11 +230,22 @@ fn validate_pattern(pattern: &str) -> Result<(), SelectorError> { Ok(()) } -/// Immutable OR-combination of selectors for one virtual application. +/// How the nonempty selector list is combined. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum SelectorMode { + /// At least one selector must match (legacy behavior). + #[default] + Any, + /// Every selector must match; absent fields fail their selector. + All, +} + +/// Immutable combination of selectors for one virtual application. #[derive(Clone, Debug)] pub struct ApplicationMatcher { id: ApplicationId, selectors: Vec, + mode: SelectorMode, } impl ApplicationMatcher { @@ -246,11 +257,28 @@ impl ApplicationMatcher { pub fn new( id: ApplicationId, selectors: Vec, + ) -> Result { + Self::with_mode(id, selectors, SelectorMode::Any) + } + + /// Constructs an explicitly combined matcher. + /// + /// # Errors + /// Returns [`SelectorError::NoSelectors`] for an empty selector list, + /// including All mode (an empty conjunction must not match everything). + pub fn with_mode( + id: ApplicationId, + selectors: Vec, + mode: SelectorMode, ) -> Result { if selectors.is_empty() { return Err(SelectorError::NoSelectors { application: id }); } - Ok(Self { id, selectors }) + Ok(Self { + id, + selectors, + mode, + }) } /// Returns the stable application identifier. @@ -259,12 +287,19 @@ impl ApplicationMatcher { &self.id } - /// Returns whether any configured selector matches. + /// Returns whether the configured selector combination matches. #[must_use] pub fn matches(&self, metadata: &StreamMetadata) -> bool { - self.selectors - .iter() - .any(|selector| selector.matches(metadata)) + match self.mode { + SelectorMode::Any => self + .selectors + .iter() + .any(|selector| selector.matches(metadata)), + SelectorMode::All => self + .selectors + .iter() + .all(|selector| selector.matches(metadata)), + } } } @@ -413,6 +448,14 @@ mod tests { assert!(matcher.matches(&StreamMetadata::new().with_process_binary("librewolf"))); } + #[test] + fn empty_conjunction_is_rejected_instead_of_matching_everything() { + assert!(matches!( + ApplicationMatcher::with_mode(application_id(), vec![], SelectorMode::All), + Err(SelectorError::NoSelectors { .. }) + )); + } + #[test] fn malformed_and_unbounded_patterns_are_rejected() { assert!(matches!( diff --git a/docs/configuration.md b/docs/configuration.md index 69760f2..aeb2840 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -127,6 +127,25 @@ Supported fields are `application.name`, `application.id`, `application.process.binary`, and `media.name`. Exact matches are whole-string and case-sensitive. Regexes use Rust's bounded `regex` syntax. +Applications may set `selector_mode = "all"` to require every selector to +match (AND). The default `"any"` preserves OR matching for existing profiles. +Missing fields fail their selector; empty selector lists and unknown modes are +rejected. For example, requiring a particular application ID and media title: + +```toml +[[applications]] +id = "music-video" +label = "Music video" +selector_mode = "all" +selectors = [ + { field = "application.id", exact = "example.player" }, + { field = "media.name", regex = '(?i) - YouTube$' }, +] +``` + +For the original YouTube-only capture use case, the single `media.name` selector +below remains sufficient; no additional application condition is needed. + The capture editor's **Save and exit** row validates and saves the current field, match mode and pattern to the draft without reopening the pattern popup. Invalid patterns leave the editor open with an error. **Esc** cancels local diff --git a/task.md b/task.md index 07f580a..344bae2 100644 --- a/task.md +++ b/task.md @@ -586,6 +586,9 @@ YouTube capture use case; no browser-name condition is needed. express the composition clearly; exact/regex and missing-field behavior are deterministic; existing profiles retain their matches; invalid composition is rejected before activation; save/reload preserves the expression. + Domain/configuration slice: `selector_mode = "any"` (default OR) or `"all"` + (AND), preserving missing-field and bounded pattern validation. TUI integration + and full milestone verification remain pending. - [ ] **M13.2 Richer process metadata:** enrich stream metadata with available process paths and Steam launch identity, then expose validated matcher fields and useful diagnostics. Dependencies: M1.2, M4. Acceptance: bounded adapter