diff --git a/crates/komorebi-protocol/src/message.rs b/crates/komorebi-protocol/src/message.rs index 4f24a923..4066493f 100644 --- a/crates/komorebi-protocol/src/message.rs +++ b/crates/komorebi-protocol/src/message.rs @@ -1,7 +1,39 @@ //! `SocketMessage`, the one message type of every komorebi socket. +use std::num::NonZeroUsize; +use std::path::PathBuf; +use std::str::FromStr; + +use color_eyre::eyre; +use komorebi_layouts::Axis; +use komorebi_layouts::CycleDirection; +use komorebi_layouts::DefaultLayout; +use komorebi_layouts::OperationDirection; +use komorebi_layouts::PanDirection; +use komorebi_layouts::PanGesture; +use komorebi_layouts::Rect; +use komorebi_layouts::Sizing; +use komorebi_themes::KomorebiTheme; use serde::Deserialize; use serde::Serialize; +use strum::Display; + +use crate::animation::AnimationStyle; +use crate::animation::prefix::AnimationPrefix; +use crate::pathext::ResolvedPathBuf; +use crate::types::ApplicationIdentifier; +use crate::types::BorderImplementation; +use crate::types::BorderStyle; +use crate::types::FocusFollowsMouseImplementation; +use crate::types::HidingBehaviour; +use crate::types::MonocleFocusBehaviour; +use crate::types::MoveBehaviour; +use crate::types::OperationBehaviour; +use crate::types::StackbarLabel; +use crate::types::StackbarMode; +use crate::types::StateQuery; +use crate::types::SubscribeOptions; +use crate::types::WindowKind; /// A state of the window manager as the JSON that `ApplyState` carries. /// @@ -25,6 +57,263 @@ impl schemars::JsonSchema for StateBlob { } } +/// A message to a daemon, as it is written on its socket: JSON, with the variant's name in +/// `type` and its arguments, if it has any, in `content`. +/// +/// One enum for every platform: `SocketMessage::platforms` says which daemons handle which +/// variant. A daemon answers a variant it does not handle with an error. +/// +/// # Example +/// +/// ```rust +/// use komorebi_protocol::message::SocketMessage; +/// use komorebi_protocol::types::StateQuery; +/// +/// let query = SocketMessage::Query(StateQuery::FocusedWorkspaceIndex); +/// assert_eq!( +/// String::from_utf8(query.as_bytes()?)?, +/// r#"{"type":"Query","content":"FocusedWorkspaceIndex"}"#, +/// ); +/// +/// let stop: SocketMessage = r#"{"type":"Stop"}"#.parse()?; +/// assert!(matches!(stop, SocketMessage::Stop)); +/// +/// # Ok::<(), Box>(()) +/// ``` +// serde_as must be before derive +#[serde_with::serde_as] +#[derive(Clone, Debug, Serialize, Deserialize, Display)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(tag = "type", content = "content")] +pub enum SocketMessage { + // Window / Container Commands + FocusWindow(OperationDirection), + MoveWindow(OperationDirection), + PreselectDirection(OperationDirection), + CancelPreselect, + CycleFocusWindow(CycleDirection), + CycleMoveWindow(CycleDirection), + StackWindow(OperationDirection), + UnstackWindow, + CycleStack(CycleDirection), + CycleStackIndex(CycleDirection), + FocusStackWindow(usize), + StackAll, + UnstackAll, + ResizeWindowEdge(OperationDirection, Sizing), + ResizeWindowAxis(Axis, Sizing), + MoveContainerToLastWorkspace, + SendContainerToLastWorkspace, + MoveContainerToMonitorNumber(usize), + CycleMoveContainerToMonitor(CycleDirection), + MoveContainerToWorkspaceNumber(usize), + MoveContainerToNamedWorkspace(String), + CycleMoveContainerToWorkspace(CycleDirection), + SendContainerToMonitorNumber(usize), + CycleSendContainerToMonitor(CycleDirection), + SendContainerToWorkspaceNumber(usize), + CycleSendContainerToWorkspace(CycleDirection), + SendContainerToMonitorWorkspaceNumber(usize, usize), + MoveContainerToMonitorWorkspaceNumber(usize, usize), + SendContainerToNamedWorkspace(String), + CycleMoveWorkspaceToMonitor(CycleDirection), + MoveWorkspaceToMonitorNumber(usize), + SwapWorkspacesToMonitorNumber(usize), + ForceFocus, + Close, + Minimize, + Promote, + PromoteSwap, + PromoteFocus, + PromoteWindow(OperationDirection), + EagerFocus(String), + LockMonitorWorkspaceContainer(usize, usize, usize), + UnlockMonitorWorkspaceContainer(usize, usize, usize), + ToggleLock, + ToggleFloat, + ToggleMonocle, + ToggleMaximize, + ToggleWindowContainerBehaviour, + ToggleFloatOverride, + WindowHidingBehaviour(HidingBehaviour), + ToggleCrossMonitorMoveBehaviour, + CrossMonitorMoveBehaviour(MoveBehaviour), + ToggleMonocleFocusBehaviour, + MonocleFocusBehaviour(MonocleFocusBehaviour), + UnmanagedWindowOperationBehaviour(OperationBehaviour), + // Current Workspace Commands + ManageFocusedWindow, + UnmanageFocusedWindow, + AdjustContainerPadding(Sizing, i32), + AdjustWorkspacePadding(Sizing, i32), + ChangeLayout(DefaultLayout), + CycleLayout(CycleDirection), + LayoutRatios(Option>, Option>), + ScrollingLayoutColumns(NonZeroUsize), + ScrollingLayoutFullWidth, + CenterFocus, + Expand, + Consume(OperationDirection), + Expel, + ToggleColumnStack, + Pan(PanDirection), + PanGesture(PanGesture), + ChangeLayoutCustom(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + FlipLayout(Axis), + ToggleWorkspaceWindowContainerBehaviour, + ToggleWorkspaceFloatOverride, + // Monitor and Workspace Commands + MonitorIndexPreference(usize, i32, i32, i32, i32), + DisplayIndexPreference(usize, String), + EnsureWorkspaces(usize, usize), + EnsureNamedWorkspaces(usize, Vec), + NewWorkspace, + ToggleTiling, + Stop, + StopIgnoreRestore, + TogglePause, + Retile, + RetileWithResizeDimensions, + QuickSave, + QuickLoad, + Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + CycleFocusMonitor(CycleDirection), + CycleFocusWorkspace(CycleDirection), + CycleFocusEmptyWorkspace(CycleDirection), + FocusMonitorNumber(usize), + FocusMonitorAtCursor, + FocusLastWorkspace, + CloseWorkspace, + FocusWorkspaceNumber(usize), + FocusWorkspaceNumbers(usize), + FocusMonitorWorkspaceNumber(usize, usize), + FocusNamedWorkspace(String), + ContainerPadding(usize, usize, i32), + NamedWorkspaceContainerPadding(String, i32), + FocusedWorkspaceContainerPadding(i32), + WorkspacePadding(usize, usize, i32), + NamedWorkspacePadding(String, i32), + FocusedWorkspacePadding(i32), + WorkspaceTiling(usize, usize, bool), + NamedWorkspaceTiling(String, bool), + WorkspaceName(usize, usize, String), + WorkspaceLayout(usize, usize, DefaultLayout), + NamedWorkspaceLayout(String, DefaultLayout), + WorkspaceLayoutCustom(usize, usize, #[serde_as(as = "ResolvedPathBuf")] PathBuf), + NamedWorkspaceLayoutCustom(String, #[serde_as(as = "ResolvedPathBuf")] PathBuf), + WorkspaceLayoutRule(usize, usize, usize, DefaultLayout), + NamedWorkspaceLayoutRule(String, usize, DefaultLayout), + WorkspaceLayoutCustomRule( + usize, + usize, + usize, + #[serde_as(as = "ResolvedPathBuf")] PathBuf, + ), + NamedWorkspaceLayoutCustomRule(String, usize, #[serde_as(as = "ResolvedPathBuf")] PathBuf), + ClearWorkspaceLayoutRules(usize, usize), + ClearNamedWorkspaceLayoutRules(String), + ToggleWorkspaceLayer, + // Configuration + ReloadConfiguration, + ReplaceConfiguration(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + ReloadStaticConfiguration(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + WatchConfiguration(bool), + CompleteConfiguration, + AltFocusHack(bool), + Theme(Box), + Animation(bool, Option), + AnimationDuration(u64, Option), + AnimationFps(u64), + AnimationStyle(AnimationStyle, Option), + #[serde(alias = "ActiveWindowBorder")] + Border(bool), + #[serde(alias = "ActiveWindowBorderColour")] + BorderColour(WindowKind, u32, u32, u32), + #[serde(alias = "ActiveWindowBorderStyle")] + BorderStyle(BorderStyle), + BorderWidth(i32), + BorderOffset(i32), + BorderImplementation(BorderImplementation), + Transparency(bool), + ToggleTransparency, + TransparencyAlpha(u8), + InvisibleBorders(Rect), + StackbarMode(StackbarMode), + StackbarLabel(StackbarLabel), + StackbarFocusedTextColour(u32, u32, u32), + StackbarUnfocusedTextColour(u32, u32, u32), + StackbarBackgroundColour(u32, u32, u32), + StackbarHeight(i32), + StackbarTabWidth(i32), + StackbarFontSize(i32), + StackbarFontFamily(Option), + WorkAreaOffset(Rect), + MonitorWorkAreaOffset(usize, Rect), + WorkspaceWorkAreaOffset(usize, usize, Rect), + ToggleWindowBasedWorkAreaOffset, + ResizeDelta(i32), + InitialWorkspaceRule(ApplicationIdentifier, String, usize, usize), + InitialNamedWorkspaceRule(ApplicationIdentifier, String, String), + WorkspaceRule(ApplicationIdentifier, String, usize, usize), + NamedWorkspaceRule(ApplicationIdentifier, String, String), + ClearWorkspaceRules(usize, usize), + ClearNamedWorkspaceRules(String), + ClearAllWorkspaceRules, + EnforceWorkspaceRules, + SessionFloatRule, + SessionFloatRules, + ClearSessionFloatRules, + #[serde(alias = "FloatRule")] + IgnoreRule(ApplicationIdentifier, String), + ManageRule(ApplicationIdentifier, String), + IdentifyObjectNameChangeApplication(ApplicationIdentifier, String), + IdentifyTrayApplication(ApplicationIdentifier, String), + IdentifyLayeredApplication(ApplicationIdentifier, String), + IdentifyBorderOverflowApplication(ApplicationIdentifier, String), + State, + GlobalState, + VisibleWindows, + MonitorInformation, + Query(StateQuery), + FocusFollowsMouse(FocusFollowsMouseImplementation, bool), + ToggleFocusFollowsMouse(FocusFollowsMouseImplementation), + MouseFollowsFocus(bool), + ToggleMouseFollowsFocus, + RemoveTitleBar(ApplicationIdentifier, String), + ToggleTitleBars, + AddSubscriberSocket(String), + AddSubscriberSocketWithOptions(String, SubscribeOptions), + RemoveSubscriberSocket(String), + AddSubscriberPipe(String), + RemoveSubscriberPipe(String), + ApplicationSpecificConfigurationSchema, + NotificationSchema, + SocketSchema, + StaticConfigSchema, + GenerateStaticConfig, + DebugWindow(i64), + // low level commands + ApplyState(StateBlob), + // handled by the KDE daemon only (see `platforms`) + ReloadHotkeys, + HotkeysState, +} + +impl SocketMessage { + /// Returns the message as JSON, the way a daemon reads it from its socket + pub fn as_bytes(&self) -> eyre::Result> { + Ok(serde_json::to_string(self)?.as_bytes().to_vec()) + } +} + +impl FromStr for SocketMessage { + type Err = serde_json::Error; + + fn from_str(s: &str) -> Result { + serde_json::from_str(s) + } +} #[cfg(test)] mod tests { use super::*; diff --git a/crates/komorebi-protocol/src/platforms.rs b/crates/komorebi-protocol/src/platforms.rs index b548f4f1..b935e7a3 100644 --- a/crates/komorebi-protocol/src/platforms.rs +++ b/crates/komorebi-protocol/src/platforms.rs @@ -1 +1,255 @@ -//! Placeholder: filled in by a later step 2 revision. +//! Which platform handles which `SocketMessage`. + +use crate::message::SocketMessage; + +/// A platform a komorebi daemon runs on +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Platform { + Windows, + MacOs, + Kde, +} + +impl Platform { + /// The platform this crate is compiled for. Linux is KDE: it is the only Linux daemon. + pub const CURRENT: Self = if cfg!(target_os = "windows") { + Self::Windows + } else if cfg!(target_os = "macos") { + Self::MacOs + } else { + Self::Kde + }; + + const fn bit(self) -> u8 { + match self { + Self::Windows => 1, + Self::MacOs => 2, + Self::Kde => 4, + } + } +} + +/// A set of platforms +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Platforms(u8); + +impl Platforms { + pub const ALL: Self = Self(7); + pub const WINDOWS: Self = Self(1); + pub const MACOS: Self = Self(2); + pub const KDE: Self = Self(4); + pub const WINDOWS_MACOS: Self = Self(1 | 2); + pub const WINDOWS_KDE: Self = Self(1 | 4); + + #[must_use] + pub const fn contains(self, platform: Platform) -> bool { + self.0 & platform.bit() != 0 + } +} + +impl SocketMessage { + /// The platforms whose daemon handles this message. + /// + /// One exhaustive `match`: a new variant does not compile until it is placed here. + #[must_use] + pub const fn platforms(&self) -> Platforms { + match self { + Self::AddSubscriberSocket(..) + | Self::AddSubscriberSocketWithOptions(..) + | Self::AdjustContainerPadding(..) + | Self::AdjustWorkspacePadding(..) + | Self::Animation(..) + | Self::AnimationDuration(..) + | Self::AnimationFps(..) + | Self::AnimationStyle(..) + | Self::ApplicationSpecificConfigurationSchema + | Self::Border(..) + | Self::BorderColour(..) + | Self::BorderOffset(..) + | Self::BorderWidth(..) + | Self::CancelPreselect + | Self::CenterFocus + | Self::ChangeLayout(..) + | Self::ClearAllWorkspaceRules + | Self::ClearNamedWorkspaceLayoutRules(..) + | Self::ClearNamedWorkspaceRules(..) + | Self::ClearSessionFloatRules + | Self::ClearWorkspaceLayoutRules(..) + | Self::ClearWorkspaceRules(..) + | Self::Close + | Self::CloseWorkspace + | Self::Consume(..) + | Self::ContainerPadding(..) + | Self::CrossMonitorMoveBehaviour(..) + | Self::CycleFocusEmptyWorkspace(..) + | Self::CycleFocusMonitor(..) + | Self::CycleFocusWindow(..) + | Self::CycleFocusWorkspace(..) + | Self::CycleLayout(..) + | Self::CycleMoveContainerToMonitor(..) + | Self::CycleMoveContainerToWorkspace(..) + | Self::CycleMoveWindow(..) + | Self::CycleMoveWorkspaceToMonitor(..) + | Self::CycleSendContainerToMonitor(..) + | Self::CycleSendContainerToWorkspace(..) + | Self::CycleStack(..) + | Self::CycleStackIndex(..) + | Self::DebugWindow(..) + | Self::DisplayIndexPreference(..) + | Self::EagerFocus(..) + | Self::EnforceWorkspaceRules + | Self::EnsureNamedWorkspaces(..) + | Self::EnsureWorkspaces(..) + | Self::Expand + | Self::Expel + | Self::FlipLayout(..) + | Self::FocusLastWorkspace + | Self::FocusMonitorAtCursor + | Self::FocusMonitorNumber(..) + | Self::FocusMonitorWorkspaceNumber(..) + | Self::FocusNamedWorkspace(..) + | Self::FocusStackWindow(..) + | Self::FocusWindow(..) + | Self::FocusWorkspaceNumber(..) + | Self::FocusWorkspaceNumbers(..) + | Self::FocusedWorkspaceContainerPadding(..) + | Self::FocusedWorkspacePadding(..) + | Self::GenerateStaticConfig + | Self::GlobalState + | Self::IgnoreRule(..) + | Self::InitialNamedWorkspaceRule(..) + | Self::InitialWorkspaceRule(..) + | Self::LayoutRatios(..) + | Self::Load(..) + | Self::LockMonitorWorkspaceContainer(..) + | Self::ManageFocusedWindow + | Self::ManageRule(..) + | Self::Minimize + | Self::MonitorInformation + | Self::MonitorWorkAreaOffset(..) + | Self::MonocleFocusBehaviour(..) + | Self::MouseFollowsFocus(..) + | Self::MoveContainerToLastWorkspace + | Self::MoveContainerToMonitorNumber(..) + | Self::MoveContainerToMonitorWorkspaceNumber(..) + | Self::MoveContainerToNamedWorkspace(..) + | Self::MoveContainerToWorkspaceNumber(..) + | Self::MoveWindow(..) + | Self::MoveWorkspaceToMonitorNumber(..) + | Self::NamedWorkspaceContainerPadding(..) + | Self::NamedWorkspaceLayout(..) + | Self::NamedWorkspaceLayoutRule(..) + | Self::NamedWorkspacePadding(..) + | Self::NamedWorkspaceRule(..) + | Self::NamedWorkspaceTiling(..) + | Self::NewWorkspace + | Self::NotificationSchema + | Self::Pan(..) + | Self::PreselectDirection(..) + | Self::Promote + | Self::PromoteFocus + | Self::PromoteSwap + | Self::PromoteWindow(..) + | Self::Query(..) + | Self::QuickLoad + | Self::QuickSave + | Self::ReloadStaticConfiguration(..) + | Self::RemoveSubscriberSocket(..) + | Self::ReplaceConfiguration(..) + | Self::ResizeDelta(..) + | Self::ResizeWindowAxis(..) + | Self::ResizeWindowEdge(..) + | Self::Retile + | Self::RetileWithResizeDimensions + | Self::Save(..) + | Self::ScrollingLayoutColumns(..) + | Self::ScrollingLayoutFullWidth + | Self::SendContainerToLastWorkspace + | Self::SendContainerToMonitorNumber(..) + | Self::SendContainerToMonitorWorkspaceNumber(..) + | Self::SendContainerToNamedWorkspace(..) + | Self::SendContainerToWorkspaceNumber(..) + | Self::SessionFloatRule + | Self::SessionFloatRules + | Self::SocketSchema + | Self::StackAll + | Self::StackWindow(..) + | Self::State + | Self::StaticConfigSchema + | Self::Stop + | Self::StopIgnoreRestore + | Self::SwapWorkspacesToMonitorNumber(..) + | Self::Theme(..) + | Self::ToggleColumnStack + | Self::ToggleCrossMonitorMoveBehaviour + | Self::ToggleFloat + | Self::ToggleFloatOverride + | Self::ToggleLock + | Self::ToggleMonocle + | Self::ToggleMonocleFocusBehaviour + | Self::ToggleMouseFollowsFocus + | Self::TogglePause + | Self::ToggleTiling + | Self::ToggleWindowBasedWorkAreaOffset + | Self::ToggleWindowContainerBehaviour + | Self::ToggleWorkspaceFloatOverride + | Self::ToggleWorkspaceLayer + | Self::ToggleWorkspaceWindowContainerBehaviour + | Self::UnlockMonitorWorkspaceContainer(..) + | Self::UnmanageFocusedWindow + | Self::UnmanagedWindowOperationBehaviour(..) + | Self::UnstackAll + | Self::UnstackWindow + | Self::VisibleWindows + | Self::WorkAreaOffset(..) + | Self::WorkspaceLayout(..) + | Self::WorkspaceLayoutRule(..) + | Self::WorkspaceName(..) + | Self::WorkspacePadding(..) + | Self::WorkspaceRule(..) + | Self::WorkspaceTiling(..) + | Self::WorkspaceWorkAreaOffset(..) => Platforms::ALL, + Self::AddSubscriberPipe(..) + | Self::AltFocusHack(..) + | Self::ApplyState(..) + | Self::BorderImplementation(..) + | Self::BorderStyle(..) + | Self::ChangeLayoutCustom(..) + | Self::CompleteConfiguration + | Self::ForceFocus + | Self::IdentifyBorderOverflowApplication(..) + | Self::IdentifyLayeredApplication(..) + | Self::IdentifyObjectNameChangeApplication(..) + | Self::IdentifyTrayApplication(..) + | Self::InvisibleBorders(..) + | Self::MonitorIndexPreference(..) + | Self::NamedWorkspaceLayoutCustom(..) + | Self::NamedWorkspaceLayoutCustomRule(..) + | Self::ReloadConfiguration + | Self::RemoveSubscriberPipe(..) + | Self::RemoveTitleBar(..) + | Self::StackbarBackgroundColour(..) + | Self::StackbarFocusedTextColour(..) + | Self::StackbarFontFamily(..) + | Self::StackbarFontSize(..) + | Self::StackbarHeight(..) + | Self::StackbarLabel(..) + | Self::StackbarMode(..) + | Self::StackbarTabWidth(..) + | Self::StackbarUnfocusedTextColour(..) + | Self::ToggleTitleBars + | Self::WatchConfiguration(..) + | Self::WindowHidingBehaviour(..) + | Self::WorkspaceLayoutCustom(..) + | Self::WorkspaceLayoutCustomRule(..) => Platforms::WINDOWS, + Self::FocusFollowsMouse(..) + | Self::ToggleFocusFollowsMouse(..) + | Self::ToggleMaximize + | Self::ToggleTransparency + | Self::Transparency(..) + | Self::TransparencyAlpha(..) => Platforms::WINDOWS_KDE, + Self::PanGesture(..) => Platforms::WINDOWS_MACOS, + Self::HotkeysState | Self::ReloadHotkeys => Platforms::KDE, + } + } +} diff --git a/crates/komorebi-protocol/tests/golden.rs b/crates/komorebi-protocol/tests/golden.rs index 0bedf20a..34f1cdb6 100644 --- a/crates/komorebi-protocol/tests/golden.rs +++ b/crates/komorebi-protocol/tests/golden.rs @@ -74,6 +74,115 @@ fn golden_variants_match_the_support_table() { } } + +use komorebi_protocol::message::SocketMessage; +use komorebi_protocol::platforms::Platform; + +/// Path-expansion instances depend on the compile target (HOME, %VAR%, ~): only with STRICT_PATHS=1 +fn is_path_extra(name: &str) -> bool { + ["@~", "@dollar", "@braces", "@percent", "@psenv"].iter().any(|s| name.ends_with(s)) +} + +fn pin_environment() { + // the goldens were generated with these values + unsafe { + std::env::set_var("HOME", "/golden-home"); + std::env::set_var("USERPROFILE", "C:\\golden-profile"); + std::env::set_var("GOLDEN_VAR", "golden-value"); + } +} + +/// Every instance that a platform's own enum accepted is accepted by the unified enum and is +/// written back as exactly the text the platform wrote. +#[test] +fn the_unified_enum_accepts_every_golden_instance_with_the_same_wire_text() { + pin_environment(); + let strict = std::env::var("STRICT_PATHS").as_deref() == Ok("1"); + let mut compared = 0; + for (platform, _) in PLATFORMS { + let g = golden(platform); + for (name, v) in g.as_object().unwrap() { + if !strict && is_path_extra(name) { + continue; + } + let instance = v["instance"].to_string(); + let message: SocketMessage = serde_json::from_str(&instance) + .unwrap_or_else(|e| panic!("{platform}: {name} is not accepted any more: {e}")); + let wire = serde_json::to_string(&message).unwrap(); + if v["payload_stubbed"] == Value::Bool(true) { + // the payload was a harness stand-in (ApplyState on Windows): the tag only + assert_eq!( + serde_json::from_str::(&wire).unwrap()["type"], + v["golden"]["type"], + "{platform}: {name}" + ); + } else { + assert_eq!(wire, v["wire"].as_str().unwrap(), "{platform}: {name}"); + } + compared += 1; + } + } + assert!(compared > 700, "compared only {compared} instances"); +} + +/// The variants of the unified schema, from the generator, one instance each +fn unified() -> (Value, Value) { + let dir = std::env::temp_dir().join(format!("komorebi-protocol-unified-{}", std::process::id())); + pin_environment(); + golden_gen::run::("unified", &dir, &[], &["ApplyState"]); + let schema = serde_json::from_str(&std::fs::read_to_string(dir.join("schema.json")).unwrap()).unwrap(); + let variants = serde_json::from_str(&std::fs::read_to_string(dir.join("variants.json")).unwrap()).unwrap(); + let _ = std::fs::remove_dir_all(dir); + (schema, variants) +} + +#[test] +fn the_unified_schema_has_every_variant_of_every_platform_and_all_of_them_round_trip() { + let (schema, variants) = unified(); + let in_schema: BTreeSet = schema["oneOf"] + .as_array() + .unwrap() + .iter() + .map(|b| b["properties"]["type"]["const"].as_str().unwrap().to_owned()) + .collect(); + assert_eq!(in_schema.len(), 197); + for (platform, _) in PLATFORMS { + let missing: Vec<_> = schema_variants(platform).difference(&in_schema).cloned().collect(); + assert!(missing.is_empty(), "{platform}: {missing:?} are not in the unified schema"); + } + for (name, v) in variants.as_object().unwrap() { + assert_eq!(v["deserialised"], Value::Bool(true), "{name}"); + } +} + +/// `platforms()` is exact, both ways, against the variant list of each platform's own enum. +#[test] +fn platforms_says_what_each_platform_handled_and_nothing_else() { + let (schema, variants) = unified(); + let all: Vec = schema["oneOf"] + .as_array() + .unwrap() + .iter() + .map(|b| b["properties"]["type"]["const"].as_str().unwrap().to_owned()) + .collect(); + for (platform, _) in PLATFORMS { + let handled = schema_variants(platform); + let which = match platform { + "windows" => Platform::Windows, + "kde" => Platform::Kde, + _ => Platform::MacOs, + }; + for name in &all { + let message: SocketMessage = serde_json::from_value(variants[name]["instance"].clone()).unwrap(); + assert_eq!( + message.platforms().contains(which), + handled.contains(name), + "{platform}: {name}" + ); + } + } +} + #[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)] #[serde(tag = "type", content = "content")] enum Stand {