Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

feat: create `IpcClient`; add cli support for wm queries and commands

Lars Bergerc312dbf69013
diff --git a/packages/wm/src/app_command.rs b/packages/wm/src/app_command.rs
index cb8d9a5c..6a554bf2 100644
--- a/packages/wm/src/app_command.rs
+++ b/packages/wm/src/app_command.rs
@@ -111,6 +111,8 @@ impl Verbosity {
pub enum QueryCommand {
/// Prints all windows.
Windows,
+ /// Prints all active workspaces.
+ Workspaces,
/// Prints all monitors.
Monitors,
/// Prints the active binding modes.
diff --git a/packages/wm/src/common/direction.rs b/packages/wm/src/common/direction.rs
index 45db67df..b53448f9 100644
--- a/packages/wm/src/common/direction.rs
+++ b/packages/wm/src/common/direction.rs
@@ -4,7 +4,7 @@ use anyhow::bail;
use serde::Serialize;
#[derive(Clone, Debug, PartialEq, Serialize)]
-#[serde(untagged, rename_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
pub enum Direction {
Left,
Right,
diff --git a/packages/wm/src/common/display_state.rs b/packages/wm/src/common/display_state.rs
index b886739c..bac31d88 100644
--- a/packages/wm/src/common/display_state.rs
+++ b/packages/wm/src/common/display_state.rs
@@ -3,7 +3,7 @@ use serde::Serialize;
/// Represents whether something is shown, hidden, or in an intermediary
/// state.
#[derive(Clone, Debug, PartialEq, Serialize)]
-#[serde(untagged, rename_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
pub enum DisplayState {
Shown,
Showing,
diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rs
index 2cfa3754..59c7c15f 100644
--- a/packages/wm/src/common/platform/event_listener.rs
+++ b/packages/wm/src/common/platform/event_listener.rs
@@ -1,10 +1,5 @@
-use std::sync::Arc;
-
use anyhow::Result;
-use tokio::sync::{
- mpsc::{self, UnboundedReceiver},
- Mutex,
-};
+use tokio::sync::mpsc::{self, UnboundedReceiver};
use crate::{
common::Point,
diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rs
index 84e44558..2eedd51e 100644
--- a/packages/wm/src/common/platform/platform.rs
+++ b/packages/wm/src/common/platform/platform.rs
@@ -1,9 +1,8 @@
use std::path::Path;
-use std::sync::Arc;
use crate::common::Point;
use anyhow::{bail, Context};
-use tokio::sync::{oneshot, Mutex};
+use tokio::sync::oneshot;
use tracing::warn;
use windows::core::{w, PCWSTR};
use windows::Win32::Foundation::{HWND, POINT};
@@ -21,10 +20,10 @@ use windows::Win32::UI::{
},
WindowsAndMessaging::{
CreateWindowExW, DestroyWindow, DispatchMessageW, GetAncestor,
- GetDesktopWindow, GetForegroundWindow, GetMessageW, GetParent,
- RegisterClassW, SetCursorPos, TranslateMessage, WindowFromPoint,
- CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, MSG, SW_NORMAL, WNDCLASSW,
- WNDPROC, WS_OVERLAPPEDWINDOW,
+ GetDesktopWindow, GetForegroundWindow, GetMessageW, RegisterClassW,
+ SetCursorPos, TranslateMessage, WindowFromPoint, CS_HREDRAW,
+ CS_VREDRAW, CW_USEDEFAULT, MSG, SW_NORMAL, WNDCLASSW, WNDPROC,
+ WS_OVERLAPPEDWINDOW,
},
};
diff --git a/packages/wm/src/common/tiling_direction.rs b/packages/wm/src/common/tiling_direction.rs
index 5e098c7e..d88f0767 100644
--- a/packages/wm/src/common/tiling_direction.rs
+++ b/packages/wm/src/common/tiling_direction.rs
@@ -6,7 +6,7 @@ use serde::Serialize;
use super::Direction;
#[derive(Clone, Debug, PartialEq, Serialize)]
-#[serde(untagged, rename_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
pub enum TilingDirection {
Vertical,
Horizontal,
diff --git a/packages/wm/src/common/units.rs b/packages/wm/src/common/units.rs
index 5b29061d..2acc810c 100644
--- a/packages/wm/src/common/units.rs
+++ b/packages/wm/src/common/units.rs
@@ -11,6 +11,7 @@ pub struct LengthValue {
}
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "snake_case")]
pub enum LengthUnit {
Pixel,
Percentage,
diff --git a/packages/wm/src/containers/container_type.rs b/packages/wm/src/containers/container_type.rs
index 3b6daaf2..4da6bfc6 100644
--- a/packages/wm/src/containers/container_type.rs
+++ b/packages/wm/src/containers/container_type.rs
@@ -1,9 +1,7 @@
use serde::{Deserialize, Serialize};
-/// TODO: Not sure whether this type is needed at all. Instead just use
-/// Serde enum tag.
#[derive(Debug, Deserialize, Clone, Serialize)]
-#[serde(tag = "type", rename_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
pub enum ContainerType {
Root,
Monitor,
diff --git a/packages/wm/src/containers/root_container.rs b/packages/wm/src/containers/root_container.rs
index a303d26e..52341e91 100644
--- a/packages/wm/src/containers/root_container.rs
+++ b/packages/wm/src/containers/root_container.rs
@@ -34,6 +34,7 @@ struct RootContainerInner {
///
/// Used for IPC and debug logging.
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct RootContainerDto {
id: Uuid,
parent: Option<Uuid>,
diff --git a/packages/wm/src/containers/split_container.rs b/packages/wm/src/containers/split_container.rs
index 374f3db3..e8a44961 100644
--- a/packages/wm/src/containers/split_container.rs
+++ b/packages/wm/src/containers/split_container.rs
@@ -42,6 +42,7 @@ struct SplitContainerInner {
///
/// Used for IPC and debug logging.
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct SplitContainerDto {
id: Uuid,
parent: Option<Uuid>,
@@ -56,6 +57,7 @@ pub struct SplitContainerDto {
}
#[derive(Debug, Serialize)]
+#[serde(untagged)]
pub enum SplitContainerChildDto {
NonTilingWindow(NonTilingWindowDto),
TilingWindow(TilingWindowDto),
diff --git a/packages/wm/src/ipc_client.rs b/packages/wm/src/ipc_client.rs
new file mode 100644
index 00000000..5f576ddc
--- /dev/null
+++ b/packages/wm/src/ipc_client.rs
@@ -0,0 +1,54 @@
+use anyhow::Context;
+use futures_util::{SinkExt, StreamExt};
+use tokio::net::TcpStream;
+use tokio_tungstenite::{
+ connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream,
+};
+
+use crate::ipc_server::DEFAULT_IPC_PORT;
+
+pub struct IpcClient {
+ stream: WebSocketStream<MaybeTlsStream<TcpStream>>,
+}
+
+impl IpcClient {
+ pub async fn connect() -> anyhow::Result<Self> {
+ let server_addr = format!("ws://127.0.0.1:{}", DEFAULT_IPC_PORT);
+
+ let (stream, _) = connect_async(server_addr)
+ .await
+ .context("Failed to connect to IPC server.")?;
+
+ Ok(Self { stream })
+ }
+
+ /// Sends an IPC message and waits for a reply.
+ pub async fn send_and_wait_reply(
+ &mut self,
+ message: String,
+ ) -> anyhow::Result<String> {
+ self
+ .stream
+ .send(Message::Text(message))
+ .await
+ .context("Failed to send command.")?;
+
+ let response = self
+ .stream
+ .next()
+ .await
+ .context("Failed to receive response.")?
+ .context("Invalid response message.")?;
+
+ let response_str = response.to_text()?;
+ Ok(response_str.to_owned())
+ // let response: ServerMessage = serde_json::from_str(response_str)?;
+
+ // match response {
+ // ServerMessage::ClientResponse(client_response) => {
+ // Ok(client_response)
+ // }
+ // _ => Err(anyhow::anyhow!("Unexpected response type")),
+ // }
+ }
+}
diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rs
index b23a4850..9fe5cec4 100644
--- a/packages/wm/src/ipc_server.rs
+++ b/packages/wm/src/ipc_server.rs
@@ -1,4 +1,4 @@
-use std::{collections::HashMap, net::SocketAddr, sync::Arc};
+use std::{collections::HashMap, iter, net::SocketAddr, sync::Arc};
use anyhow::Context;
use clap::Parser;
@@ -17,23 +17,25 @@ use uuid::Uuid;
use crate::{
app_command::{AppCommand, InvokeCommand, QueryCommand},
- containers::Container,
+ containers::{Container, WindowContainer},
+ monitors::Monitor,
wm_event::WmEvent,
wm_state::WmState,
+ workspaces::Workspace,
};
-const DEFAULT_IPC_PORT: u32 = 6123;
+pub const DEFAULT_IPC_PORT: u32 = 6123;
#[derive(Debug, Serialize)]
#[serde(tag = "message_type", rename_all = "snake_case")]
-enum ServerMessage {
+pub enum ServerMessage {
ClientResponse(ClientResponseMessage),
EventSubscription(EventSubscriptionMessage),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
-struct ClientResponseMessage {
+pub struct ClientResponseMessage {
client_message: String,
data: Option<ClientResponseData>,
error: Option<String>,
@@ -42,16 +44,17 @@ struct ClientResponseMessage {
#[derive(Debug, Serialize)]
#[serde(untagged)]
-enum ClientResponseData {
- Windows(Vec<Container>),
- Monitors(Vec<Container>),
+pub enum ClientResponseData {
+ Windows(Vec<WindowContainer>),
+ Monitors(Vec<Monitor>),
+ Workspaces(Vec<Workspace>),
BindingModes(Vec<String>),
Focused(Option<Container>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
-struct EventSubscriptionMessage {
+pub struct EventSubscriptionMessage {
data: Option<WmEvent>,
error: Option<String>,
subscription_id: String,
@@ -69,6 +72,7 @@ pub struct IpcServer {
mpsc::UnboundedReceiver<(AppCommand, mpsc::UnboundedSender<Message>)>,
pub wm_command_rx:
mpsc::UnboundedReceiver<(InvokeCommand, Option<Uuid>)>,
+ pub wm_command_tx: mpsc::UnboundedSender<(InvokeCommand, Option<Uuid>)>,
abort_handle: task::AbortHandle,
// /// Hashmap of event names and connections subscribed to that event.
// event_subs: Arc<Mutex<HashMap<Uuid, EventSubscription>>>,
@@ -87,18 +91,28 @@ impl IpcServer {
let task = task::spawn(async move {
while let Ok((stream, addr)) = server.accept().await {
- task::spawn(Self::handle_connection(
- stream,
- addr,
- event_subs.clone(),
- message_tx.clone(),
- ));
+ let event_subs = event_subs.clone();
+ let message_tx = message_tx.clone();
+
+ task::spawn(async move {
+ if let Err(err) = Self::handle_connection(
+ stream,
+ addr,
+ event_subs.clone(),
+ message_tx.clone(),
+ )
+ .await
+ {
+ error!("Error handling connection: {}", err);
+ }
+ });
}
});
Ok(Self {
message_rx,
wm_command_rx,
+ wm_command_tx,
abort_handle: task.abort_handle(),
// event_subs: event_subs.clone(),
})
@@ -130,13 +144,14 @@ impl IpcServer {
break;
}
}
- Some(msg) = incoming.next() => {
- let msg = msg.context("Error reading next websocket message.")?;
+ msg = incoming.next() => {
+ let msg = msg.unwrap().context("Error reading next websocket message.")?;
if msg.is_text() || msg.is_binary() {
- let app_command =
- AppCommand::try_parse_from(msg.to_text()?.split(" "))?;
+ let split_msg =
+ iter::once("").chain(msg.to_text()?.split_whitespace());
+ let app_command = AppCommand::try_parse_from(split_msg)?;
message_tx.send((app_command, response_tx.clone()))?;
}
}
@@ -144,6 +159,7 @@ impl IpcServer {
}
// TODO: Clean-up event subscriptions on errors.
+ info!("IPC disconnection from: {}.", addr);
let mut subscriptions = event_subs.lock().await;
// Remove event subscription on websocket disconnect.
@@ -155,8 +171,6 @@ impl IpcServer {
// });
}
- info!("IPC disconnection from: {}.", addr);
-
Ok(())
}
@@ -166,31 +180,37 @@ impl IpcServer {
response_tx: mpsc::UnboundedSender<Message>,
state: &mut WmState,
) -> anyhow::Result<()> {
- // TODO: Spawn a task so that it doesn't block main thread execution.
-
+ // TODO: Handle subscribe messages.
let response = match app_command {
- AppCommand::Start {
- config_path,
- verbosity,
- } => Err(anyhow::anyhow!("Start command not implemented.")),
AppCommand::Query { command } => match command {
- QueryCommand::Windows => Ok(ClientResponseData::BindingModes(
- state.binding_modes.clone(),
- )),
- QueryCommand::Monitors => Ok(ClientResponseData::BindingModes(
- state.binding_modes.clone(),
- )),
+ QueryCommand::Windows => {
+ Ok(ClientResponseData::Windows(state.windows()))
+ }
+ QueryCommand::Workspaces => {
+ Ok(ClientResponseData::Workspaces(state.workspaces()))
+ }
+ QueryCommand::Monitors => {
+ Ok(ClientResponseData::Monitors(state.monitors()))
+ }
QueryCommand::BindingModes => Ok(
ClientResponseData::BindingModes(state.binding_modes.clone()),
),
- QueryCommand::Focused => Ok(ClientResponseData::BindingModes(
- state.binding_modes.clone(),
- )),
+ QueryCommand::Focused => {
+ Ok(ClientResponseData::Focused(state.focused_container()))
+ }
},
AppCommand::Cmd {
context_container_id,
command,
- } => Err(anyhow::anyhow!("Cmd command not implemented.")),
+ } => self
+ .wm_command_tx
+ .send((command, context_container_id))
+ .map_err(|_| anyhow::anyhow!("Failed to send WM command."))
+ .and_then(|_| {
+ // TODO: Add a proper response type for command execution.
+ Ok(ClientResponseData::Focused(state.focused_container()))
+ }),
+ _ => Err(anyhow::anyhow!("Unsupported IPC command.")),
};
let error = response.as_ref().err().map(|err| err.to_string());
diff --git a/packages/wm/src/lib.rs b/packages/wm/src/lib.rs
index 704f9a38..3bdba7e1 100644
--- a/packages/wm/src/lib.rs
+++ b/packages/wm/src/lib.rs
@@ -4,6 +4,7 @@
pub mod app_command;
pub mod common;
pub mod containers;
+pub mod ipc_client;
pub mod ipc_server;
pub mod monitors;
pub mod user_config;
diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rs
index c5957a6d..332189cf 100644
--- a/packages/wm/src/main.rs
+++ b/packages/wm/src/main.rs
@@ -4,6 +4,7 @@
use std::{env, path::PathBuf};
use anyhow::{Context, Result};
+use ipc_client::IpcClient;
use tokio::process::Command;
use tracing::{debug, error, info};
@@ -17,6 +18,7 @@ use crate::{app_command::AppCommand, wm_event::WmEvent};
mod app_command;
mod common;
mod containers;
+mod ipc_client;
mod ipc_server;
mod monitors;
mod user_config;
@@ -47,7 +49,11 @@ async fn main() {
error!("Failed to start GlazeWM: {}", err);
}
}
- _ => todo!(),
+ _ => {
+ if let Err(err) = start_cli().await {
+ error!("{}", err);
+ }
+ }
}
}
@@ -112,6 +118,21 @@ async fn start_wm(config_path: Option<PathBuf>) -> Result<()> {
}
}
+async fn start_cli() -> Result<()> {
+ let mut client = IpcClient::connect().await?;
+
+ let command_str = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
+
+ let response = client
+ .send_and_wait_reply(command_str)
+ .await
+ .context("Failed to send command")?;
+
+ println!("{}", response);
+
+ Ok(())
+}
+
/// Launches watcher binary. This is a separate process that is responsible
/// for restoring hidden windows in case the main WM process crashes.
///
diff --git a/packages/wm/src/monitors/monitor.rs b/packages/wm/src/monitors/monitor.rs
index 1571a3b9..42aee204 100644
--- a/packages/wm/src/monitors/monitor.rs
+++ b/packages/wm/src/monitors/monitor.rs
@@ -1,7 +1,6 @@
use std::{
cell::{Ref, RefCell, RefMut},
collections::VecDeque,
- fmt,
rc::Rc,
};
@@ -35,6 +34,7 @@ struct MonitorInner {
///
/// Used for IPC and debug logging.
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct MonitorDto {
id: Uuid,
parent: Option<Uuid>,
diff --git a/packages/wm/src/windows/non_tiling_window.rs b/packages/wm/src/windows/non_tiling_window.rs
index 20c641e4..ce737d3c 100644
--- a/packages/wm/src/windows/non_tiling_window.rs
+++ b/packages/wm/src/windows/non_tiling_window.rs
@@ -44,6 +44,7 @@ struct NonTilingWindowInner {
///
/// Used for IPC and debug logging.
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct NonTilingWindowDto {
id: Uuid,
parent: Option<Uuid>,
diff --git a/packages/wm/src/windows/tiling_window.rs b/packages/wm/src/windows/tiling_window.rs
index 6523cc87..ad8ccf5a 100644
--- a/packages/wm/src/windows/tiling_window.rs
+++ b/packages/wm/src/windows/tiling_window.rs
@@ -51,6 +51,7 @@ struct TilingWindowInner {
///
/// Used for IPC and debug logging.
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct TilingWindowDto {
id: Uuid,
parent: Option<Uuid>,
diff --git a/packages/wm/src/windows/window_state.rs b/packages/wm/src/windows/window_state.rs
index 977764a3..4b8c3f9a 100644
--- a/packages/wm/src/windows/window_state.rs
+++ b/packages/wm/src/windows/window_state.rs
@@ -3,10 +3,56 @@ use serde::Serialize;
use crate::user_config::{FloatingStateConfig, FullscreenStateConfig};
/// Represents the various states a window can be in.
-#[derive(Clone, Debug, PartialEq, Serialize)]
+#[derive(Clone, Debug, PartialEq)]
pub enum WindowState {
Floating(FloatingStateConfig),
Fullscreen(FullscreenStateConfig),
Minimized,
Tiling,
}
+
+/// Intermediate struct for serializing `WindowState`.
+#[derive(Debug, Serialize)]
+struct WindowStateDto {
+ name: String,
+ options: Option<WindowStateOptions>,
+}
+
+/// Intermediate enum for serializing `WindowState`.
+#[derive(Debug, Serialize)]
+#[serde(untagged)]
+enum WindowStateOptions {
+ Floating(FloatingStateConfig),
+ Fullscreen(FullscreenStateConfig),
+}
+
+impl Serialize for WindowState {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ let type_str = match self {
+ WindowState::Floating(_) => "floating",
+ WindowState::Fullscreen(_) => "fullscreen",
+ WindowState::Minimized => "minimized",
+ WindowState::Tiling => "tiling",
+ };
+
+ let options = match self {
+ WindowState::Floating(floating) => {
+ Some(WindowStateOptions::Floating(floating.clone()))
+ }
+ WindowState::Fullscreen(fullscreen) => {
+ Some(WindowStateOptions::Fullscreen(fullscreen.clone()))
+ }
+ _ => None,
+ };
+
+ let dto = WindowStateDto {
+ name: type_str.to_string(),
+ options,
+ };
+
+ dto.serialize(serializer)
+ }
+}
diff --git a/packages/wm/src/workspaces/workspace.rs b/packages/wm/src/workspaces/workspace.rs
index 6a84761f..097b898a 100644
--- a/packages/wm/src/workspaces/workspace.rs
+++ b/packages/wm/src/workspaces/workspace.rs
@@ -39,6 +39,7 @@ struct WorkspaceInner {
///
/// Used for IPC and debug logging.
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct WorkspaceDto {
id: Uuid,
parent: Option<Uuid>,
@@ -52,6 +53,7 @@ pub struct WorkspaceDto {
}
#[derive(Debug, Serialize)]
+#[serde(untagged)]
pub enum WorkspaceChildDto {
NonTilingWindow(NonTilingWindowDto),
TilingWindow(TilingWindowDto),