GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: partial ipc server implementation for parsing incoming commands
Lars Bergere51173052e7c
diff --git a/Cargo.lock b/Cargo.lockindex f0937869..2469451a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -717,6 +717,17 @@ dependencies = ["syn",]+[[package]]+name = "serde_json"+version = "1.0.117"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3"+dependencies = [+ "itoa",+ "ryu",+ "serde",+]+[[package]]name = "serde_yaml"version = "0.9.32"@@ -1270,6 +1281,7 @@ dependencies = ["ipc-client","regex","serde",+ "serde_json","serde_yaml","tokio","tokio-tungstenite",diff --git a/packages/wm/Cargo.toml b/packages/wm/Cargo.tomlindex c9fcc728..9958fea5 100644--- a/packages/wm/Cargo.toml+++ b/packages/wm/Cargo.toml@@ -18,6 +18,7 @@ futures-util = "0.3"home = "0.5"uuid = { version = "1", features = ["v4"] }serde = { version = "1", features = ["derive"] }+serde_json = "1"serde_yaml = "0.9"regex = { workspace = true }tokio = { workspace = true }diff --git a/packages/wm/src/app_command.rs b/packages/wm/src/app_command.rsindex ede4fb12..8681f8ae 100644--- a/packages/wm/src/app_command.rs+++ b/packages/wm/src/app_command.rs@@ -4,6 +4,7 @@ use anyhow::bail;use clap::{error::KindFormatter, Args, Parser};use serde::{Deserialize, Deserializer};use tracing::Level;+use uuid::Uuid;use crate::{common::{@@ -54,6 +55,9 @@ pub enum AppCommand {////// Requires an already running instance of the window manager.Cmd {+ #[clap(short = 'c')]+ context_container_id: Option<Uuid>,+#[clap(subcommand)]command: InvokeCommand,},diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rsindex 69c01854..3b402a53 100644--- a/packages/wm/src/ipc_server.rs+++ b/packages/wm/src/ipc_server.rs@@ -1,17 +1,18 @@-use std::sync::Arc;+use std::{collections::HashMap, sync::Arc};use anyhow::Result;+use clap::Parser;use futures_util::{SinkExt, StreamExt};use ipc_client::DEFAULT_IPC_ADDR;+use serde::Serialize;use tokio::{- net::TcpListener,- sync::{- mpsc::{self},- Mutex,- },+ net::{TcpListener, TcpStream},+ sync::{mpsc, Mutex},task,};-use tokio_tungstenite::accept_async;+use tokio_tungstenite::{+ accept_async, tungstenite::Message, WebSocketStream,+};use tracing::info;use uuid::Uuid;@@ -21,11 +22,32 @@ use crate::{wm_state::WmState,};+#[derive(Debug, Serialize)]+struct ServerMessage<T> {+ success: bool,+ message_type: ServerMessageType,+ data: Option<T>,+ error: Option<String>,+}++#[derive(Debug, Serialize)]+enum ServerMessageType {+ ClientResponse,+ EventSubscription,+}++#[derive(Debug)]+struct EventSubscription {+ subscription_id: String,+ stream: WebSocketStream<TcpStream>,+}+pub struct IpcServer {pub message_rx: mpsc::UnboundedReceiver<AppCommand>,pub wm_command_rx:mpsc::UnboundedReceiver<(InvokeCommand, Option<Uuid>)>,abort_handle: task::AbortHandle,+ // event_subscriptions: Arc<Mutex<HashMap<Uuid, EventSubscription>>>,}impl IpcServer {@@ -34,18 +56,17 @@ impl IpcServer {let (wm_command_tx, wm_command_rx) = mpsc::unbounded_channel();let server = TcpListener::bind(DEFAULT_IPC_ADDR).await?;+ info!("IPC server started on port {}.", DEFAULT_IPC_ADDR);++ // Hashmap of event names and connections subscribed to that event.+ let event_subscriptions = Arc::new(Mutex::new(HashMap::new()));let task = task::spawn(async move {while let Ok((stream, _)) = server.accept().await {- let mut ws_stream = accept_async(stream).await.unwrap();- info!("Received new IPC connection.");-- while let Some(msg) = ws_stream.next().await {- let msg = msg.unwrap();- if msg.is_text() || msg.is_binary() {- ws_stream.send(msg).await.unwrap();- }- }+ task::spawn(Self::handle_connection(+ stream,+ event_subscriptions.clone(),+ ));}});@@ -56,8 +77,50 @@ impl IpcServer {})}- pub async fn stop(&self) {- todo!()+ async fn handle_connection(+ stream: TcpStream,+ event_subscriptions: Arc<Mutex<HashMap<Uuid, EventSubscription>>>,+ ) -> anyhow::Result<()> {+ // let client_id = Uuid::new_v4().to_string();+ // info!("Received new IPC connection with client id: {}", client_id);+ info!("Received new IPC connection.");++ let mut subscriptions = event_subscriptions.lock().await;+ let mut ws_stream = accept_async(stream).await?;++ while let Some(Ok(msg)) = ws_stream.next().await {+ if msg.is_text() || msg.is_binary() {+ let app_command =+ AppCommand::try_parse_from(msg.to_text()?.split(" "))?;++ let res = match app_command {+ AppCommand::Start {+ config_path,+ verbosity,+ } => todo!(),+ AppCommand::Query { command } => todo!(),+ AppCommand::Cmd {+ context_container_id,+ command,+ } => todo!(),+ };++ // Respond to the client with the result of the command.+ let response_msg = Message::Text(serde_json::to_string(&res)?);+ ws_stream.send(response_msg).await?;+ }+ }++ // Remove event subscription on websocket disconnect.+ for (_, event_subscriptions) in subscriptions.iter_mut() {+ // event_subscriptions.retain(|subscription| {+ // // Remove the subscription associated with the disconnected websocket+ // // You'll need to modify this based on how you track the websocket connection+ // true+ // });+ }++ Ok(())}pub async fn process_message(@@ -69,12 +132,35 @@ impl IpcServer {}pub async fn process_event(&mut self, event: WmEvent) {- // TODO: Spawn a task so that it doesn't block main thread execution.+ // // TODO: Spawn a task so that it doesn't block main thread execution.+ // let subscriptions = self.event_subscriptions.lock().await;++ // if let Some(event_subscriptions) = subscriptions.get(event_name) {+ // for subscription in event_subscriptions {+ // let socket = subscription.socket.clone();+ // let event_message = ServerMessage {+ // success: true,+ // message_type: "EventSubscription".to_string(),+ // data: Some(event_data.clone()),+ // error: None,+ // };+ // let message =+ // Message::Text(serde_json::to_string(&event_message).unwrap());+ // tokio::spawn(async move {+ // let mut socket = socket.lock().await;+ // socket.send(message).await.expect("Failed to send event");+ // });+ // }+ // }+ }++ pub fn stop(&self) {+ self.abort_handle.abort();}}impl Drop for IpcServer {fn drop(&mut self) {- self.abort_handle.abort();+ self.stop();}}