GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: remove `PartialServerMessage` struct; use separate deserializers for certain config fields
Lars Berger0379b5b34138
diff --git a/packages/wm/src/common/color.rs b/packages/wm/src/common/color.rsindex 550dbc10..1a9f2123 100644--- a/packages/wm/src/common/color.rs+++ b/packages/wm/src/common/color.rs@@ -1,9 +1,9 @@use std::str::FromStr;use anyhow::bail;-use serde::{Deserialize, Deserializer, Serialize};+use serde::{Deserialize, Serialize};-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Deserialize, Clone, Serialize)]pub struct ColorRGBA {pub r: u8,pub g: u8,@@ -49,13 +49,3 @@ impl FromStr for ColorRGBA {Ok(Self { r, g, b, a })}}--impl<'de> Deserialize<'de> for ColorRGBA {- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>- where- D: Deserializer<'de>,- {- let str = String::deserialize(deserializer)?;- Self::from_str(&str).map_err(serde::de::Error::custom)- }-}diff --git a/packages/wm/src/common/rect_delta.rs b/packages/wm/src/common/rect_delta.rsindex 461f001a..5f788f26 100644--- a/packages/wm/src/common/rect_delta.rs+++ b/packages/wm/src/common/rect_delta.rs@@ -1,11 +1,11 @@use std::str::FromStr;use anyhow::bail;-use serde::{Deserialize, Deserializer, Serialize};+use serde::{Deserialize, Serialize};use super::LengthValue;-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Deserialize, Clone, Serialize)]pub struct RectDelta {/// The delta in x-coordinates on the left of the rectangle.pub left: LengthValue,@@ -85,13 +85,3 @@ impl FromStr for RectDelta {}}}--impl<'de> Deserialize<'de> for RectDelta {- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>- where- D: Deserializer<'de>,- {- let str = String::deserialize(deserializer)?;- Self::from_str(&str).map_err(serde::de::Error::custom)- }-}diff --git a/packages/wm/src/common/units.rs b/packages/wm/src/common/units.rsindex 21a9c211..1a8fd4f4 100644--- a/packages/wm/src/common/units.rs+++ b/packages/wm/src/common/units.rs@@ -2,15 +2,15 @@ use std::str::FromStr;use anyhow::{bail, Context};use regex::Regex;-use serde::{Deserialize, Deserializer, Serialize};+use serde::{Deserialize, Serialize};-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Deserialize, Clone, Serialize)]pub struct LengthValue {pub amount: f32,pub unit: LengthUnit,}-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Deserialize, Clone, Serialize)]#[serde(rename_all = "snake_case")]pub enum LengthUnit {Pixel,@@ -77,13 +77,3 @@ impl FromStr for LengthValue {Ok(LengthValue { amount, unit })}}--impl<'de> Deserialize<'de> for LengthValue {- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>- where- D: Deserializer<'de>,- {- let str = String::deserialize(deserializer)?;- Self::from_str(&str).map_err(serde::de::Error::custom)- }-}diff --git a/packages/wm/src/ipc_client.rs b/packages/wm/src/ipc_client.rsindex ac5e5e75..ec8012d1 100644--- a/packages/wm/src/ipc_client.rs+++ b/packages/wm/src/ipc_client.rs@@ -1,26 +1,12 @@use anyhow::Context;use futures_util::{SinkExt, StreamExt};-use serde::{Deserialize, Serialize};-use serde_json::value::RawValue;use tokio::net::TcpStream;use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream,};use uuid::Uuid;-use crate::ipc_server::DEFAULT_IPC_PORT;--/// Utility struct for partially deserializing server messages.-#[derive(Clone, Debug, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct PartialServerMessage {- pub client_message: Option<String>,- pub data: Box<RawValue>,- pub error: Option<String>,- pub message_type: String,- pub subscription_id: Option<Uuid>,- pub success: bool,-}+use crate::ipc_server::{ServerMessage, DEFAULT_IPC_PORT};pub struct IpcClient {stream: WebSocketStream<MaybeTlsStream<TcpStream>>,@@ -49,9 +35,7 @@ impl IpcClient {}/// Waits and returns the next reply from the IPC server.- pub async fn next_response(- &mut self,- ) -> anyhow::Result<PartialServerMessage> {+ pub async fn next_message(&mut self) -> anyhow::Result<ServerMessage> {let response = self.stream.next()@@ -60,7 +44,7 @@ impl IpcClient {.context("Invalid response message.")?;let json_response =- serde_json::from_str::<PartialServerMessage>(response.to_text()?)?;+ serde_json::from_str::<ServerMessage>(response.to_text()?)?;Ok(json_response)}@@ -68,10 +52,12 @@ impl IpcClient {pub async fn client_response(&mut self,client_message: &str,- ) -> Option<PartialServerMessage> {- while let Ok(response) = self.next_response().await {- if response.client_message == Some(client_message.to_string()) {- return Some(response);+ ) -> Option<ServerMessage> {+ while let Ok(response) = self.next_message().await {+ if let ServerMessage::ClientResponse(client_response) = &response {+ if client_response.client_message == client_message {+ return Some(response);+ }}}@@ -81,10 +67,12 @@ impl IpcClient {pub async fn event_subscription(&mut self,subscription_id: &Uuid,- ) -> Option<PartialServerMessage> {- while let Ok(response) = self.next_response().await {- if response.subscription_id == Some(*subscription_id) {- return Some(response);+ ) -> Option<ServerMessage> {+ while let Ok(response) = self.next_message().await {+ if let ServerMessage::EventSubscription(event_sub) = &response {+ if &event_sub.subscription_id == subscription_id {+ return Some(response);+ }}}diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rsindex b8b93a0e..4f73a18c 100644--- a/packages/wm/src/ipc_server.rs+++ b/packages/wm/src/ipc_server.rs@@ -42,14 +42,20 @@ pub struct ClientResponseMessage {#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(untagged)]pub enum ClientResponseData {- BindingModes(Vec<BindingModeConfig>),+ BindingModes(BindingModesData),Command(CommandData),EventSubscribe(EventSubscribeData),EventUnsubscribe,- Focused(ContainerDto),- Monitors(Vec<ContainerDto>),- Windows(Vec<ContainerDto>),- Workspaces(Vec<ContainerDto>),+ Focused(FocusedData),+ Monitors(MonitorsData),+ Windows(WindowsData),+ Workspaces(WorkspacesData),+}++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct BindingModesData {+ pub binding_modes: Vec<BindingModeConfig>,}#[derive(Clone, Debug, Deserialize, Serialize)]@@ -64,6 +70,30 @@ pub struct EventSubscribeData {pub subscription_id: Uuid,}+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct FocusedData {+ pub focused: ContainerDto,+}++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MonitorsData {+ pub monitors: Vec<ContainerDto>,+}++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WindowsData {+ pub windows: Vec<ContainerDto>,+}++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WorkspacesData {+ pub workspaces: Vec<ContainerDto>,+}+#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(rename_all = "camelCase")]pub struct EventSubscriptionMessage {@@ -212,29 +242,40 @@ impl IpcServer {) -> anyhow::Result<ClientResponseData> {let response_data = match app_command {AppCommand::Query { command } => match command {- QueryCommand::Windows => ClientResponseData::Windows(- wm.state- .windows()- .into_iter()- .map(|window| window.to_dto())- .try_collect()?,- ),- QueryCommand::Workspaces => ClientResponseData::Workspaces(- wm.state- .workspaces()- .into_iter()- .map(|workspace| workspace.to_dto())- .try_collect()?,- ),- QueryCommand::Monitors => ClientResponseData::Monitors(- wm.state- .monitors()- .into_iter()- .map(|monitor| monitor.to_dto())- .try_collect()?,- ),+ QueryCommand::Windows => {+ ClientResponseData::Windows(WindowsData {+ windows: wm+ .state+ .windows()+ .into_iter()+ .map(|window| window.to_dto())+ .try_collect()?,+ })+ }+ QueryCommand::Workspaces => {+ ClientResponseData::Workspaces(WorkspacesData {+ workspaces: wm+ .state+ .workspaces()+ .into_iter()+ .map(|workspace| workspace.to_dto())+ .try_collect()?,+ })+ }+ QueryCommand::Monitors => {+ ClientResponseData::Monitors(MonitorsData {+ monitors: wm+ .state+ .monitors()+ .into_iter()+ .map(|monitor| monitor.to_dto())+ .try_collect()?,+ })+ }QueryCommand::BindingModes => {- ClientResponseData::BindingModes(wm.state.binding_modes.clone())+ ClientResponseData::BindingModes(BindingModesData {+ binding_modes: wm.state.binding_modes.clone(),+ })}QueryCommand::Focused => {let focused_container = wm@@ -242,7 +283,9 @@ impl IpcServer {.focused_container().context("No focused container.")?;- ClientResponseData::Focused(focused_container.to_dto()?)+ ClientResponseData::Focused(FocusedData {+ focused: focused_container.to_dto()?,+ })}},AppCommand::Command {diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rsindex 27b69f4e..a6b4acad 100644--- a/packages/wm/src/main.rs+++ b/packages/wm/src/main.rs@@ -8,16 +8,15 @@use std::{env, path::PathBuf};use anyhow::{Context, Result};-use app_command::InvokeCommand;-use sys_tray::SystemTray;use tokio::{process::Command, signal};use tracing::{debug, error, info};use crate::{- app_command::{AppCommand, Verbosity},+ app_command::{AppCommand, InvokeCommand, Verbosity},common::platform::Platform,ipc_client::IpcClient,- ipc_server::{EventSubscribeData, IpcServer},+ ipc_server::{ClientResponseData, IpcServer, ServerMessage},+ sys_tray::SystemTray,user_config::UserConfig,wm::WindowManager,wm_event::WmEvent,@@ -51,7 +50,7 @@ async fn main() {config_path,verbosity,} => start_wm(config_path, verbosity).await,- _ => start_cli(args, app_command).await,+ _ => start_cli(args).await,};if let Err(err) = res {@@ -160,10 +159,7 @@ async fn start_wm(}}-async fn start_cli(- args: Vec<String>,- app_command: AppCommand,-) -> Result<()> {+async fn start_cli(args: Vec<String>) -> Result<()> {tracing_subscriber::fmt().init();let mut client = IpcClient::connect().await?;@@ -179,29 +175,27 @@ async fn start_cli(.await.context("Failed to receive response from IPC server.")?;- let is_subscribe_message =- matches!(app_command, AppCommand::Subscribe { .. });-- // Exit on first response received when not subscribing to an event.- if !is_subscribe_message {- println!("{}", serde_json::to_string(&client_response)?);- std::process::exit(0);+ if let ServerMessage::ClientResponse(client_response) = client_response {+ match client_response.data {+ // For event subscriptions, omit the initial response message and+ // continuously output subsequent event messages.+ Some(ClientResponseData::EventSubscribe(data)) => loop {+ let event_subscription = client+ .event_subscription(&data.subscription_id)+ .await+ .context("Failed to receive response from IPC server.")?;++ println!("{}", serde_json::to_string(&event_subscription)?);+ },+ // For all other messages, output and exit when the first response+ // message is received.+ _ => {+ println!("{}", serde_json::to_string(&client_response)?);+ }+ }}- // Otherwise, expect a subscription ID in the client response.- let subscribe_data = serde_json::from_str::<EventSubscribeData>(- client_response.data.get(),- )?;-- // Continuously listen for server responses.- loop {- let event_subscription = client- .event_subscription(&subscribe_data.subscription_id)- .await- .context("Failed to receive response from IPC server.")?;-- println!("{}", serde_json::to_string(&event_subscription)?);- }+ Ok(())}/// Launches watcher binary. This is a separate process that is responsiblediff --git a/packages/wm/src/user_config.rs b/packages/wm/src/user_config.rsindex 8c22467c..9d076f8b 100644--- a/packages/wm/src/user_config.rs+++ b/packages/wm/src/user_config.rs@@ -1,7 +1,7 @@-use std::path::PathBuf;+use std::{path::PathBuf, str::FromStr};use anyhow::{Context, Result};-use serde::{Deserialize, Serialize};+use serde::{Deserialize, Deserializer, Serialize};use tokio::fs;use crate::{@@ -179,6 +179,7 @@ pub struct FocusBorder {pub enabled: bool,/// Border color of the window.+ #[serde(deserialize_with = "deserialize_color")]pub color: ColorRGBA,}@@ -186,9 +187,11 @@ pub struct FocusBorder {#[serde(rename_all(serialize = "camelCase"))]pub struct GapsConfig {/// Gap between adjacent windows.+ #[serde(deserialize_with = "deserialize_length_value")]pub inner_gap: LengthValue,/// Gap between windows and the screen edge.+ #[serde(deserialize_with = "deserialize_rect_delta")]pub outer_gap: RectDelta,}@@ -277,3 +280,36 @@ pub struct WorkspaceConfig {const fn default_bool<const V: bool>() -> bool {V}++/// Deserializes `Color` from a string.+fn deserialize_color<'de, D>(+ deserializer: D,+) -> Result<ColorRGBA, D::Error>+where+ D: Deserializer<'de>,+{+ let str = String::deserialize(deserializer)?;+ ColorRGBA::from_str(&str).map_err(serde::de::Error::custom)+}++/// Deserializes `RectDelta` from a string.+fn deserialize_rect_delta<'de, D>(+ deserializer: D,+) -> Result<RectDelta, D::Error>+where+ D: Deserializer<'de>,+{+ let str = String::deserialize(deserializer)?;+ RectDelta::from_str(&str).map_err(serde::de::Error::custom)+}++/// Deserializes `LengthValue` from a string.+fn deserialize_length_value<'de, D>(+ deserializer: D,+) -> Result<LengthValue, D::Error>+where+ D: Deserializer<'de>,+{+ let str = String::deserialize(deserializer)?;+ LengthValue::from_str(&str).map_err(serde::de::Error::custom)+}