Skip to content

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

feat: partial implementation of subscribe command

Lars Berger4785a72cad68
diff --git a/packages/wm/src/app_command.rs b/packages/wm/src/app_command.rs
index 6a554bf2..3170bd8a 100644
--- a/packages/wm/src/app_command.rs
+++ b/packages/wm/src/app_command.rs
@@ -1,7 +1,7 @@
use std::{iter, path::PathBuf};
use anyhow::bail;
-use clap::{error::KindFormatter, Args, Parser};
+use clap::{error::KindFormatter, Args, Parser, ValueEnum};
use serde::{Deserialize, Deserializer, Serialize};
use tracing::Level;
use uuid::Uuid;
@@ -61,16 +61,23 @@ pub enum AppCommand {
#[clap(subcommand)]
command: InvokeCommand,
},
+
+ /// Subscribe to a WM event (e.g. `window_close`) and print
+ ///
+ /// Requires an already running instance of the window manager.
+ Subscribe {
+ /// WM event(s) to subscribe to.
+ #[clap(short = 'e', long, value_enum, num_args = 1..)]
+ events: Vec<SubscribableEvent>,
+ },
}
impl AppCommand {
/// Parses `AppCommand` from command line arguments.
///
/// Defaults to `AppCommand::Start` if no arguments are provided.
- pub fn parse_with_default() -> Self {
- let args = std::env::args().skip(1);
-
- match args.len() == 0 {
+ pub fn parse_with_default(args: &Vec<String>) -> Self {
+ match args.len() == 1 {
true => AppCommand::Start {
config_path: None,
verbosity: Verbosity {
@@ -78,7 +85,7 @@ impl AppCommand {
quiet: false,
},
},
- false => AppCommand::parse(),
+ false => AppCommand::parse_from(args),
}
}
}
@@ -121,6 +128,24 @@ pub enum QueryCommand {
Focused,
}
+#[derive(Clone, Debug, ValueEnum)]
+#[clap(rename_all = "snake_case")]
+pub enum SubscribableEvent {
+ BindingModesChanged,
+ FocusChanged,
+ FocusedContainerMoved,
+ MonitorAdded,
+ MonitorUpdated,
+ MonitorRemoved,
+ TilingDirectionChanged,
+ UserConfigChanged,
+ WindowManaged,
+ WindowUnmanaged,
+ WorkspaceActivated,
+ WorkspaceDeactivated,
+ WorkspaceMoved,
+}
+
#[derive(Clone, Debug, Parser, Serialize)]
pub enum InvokeCommand {
AdjustBorders(InvokeAdjustBordersCommand),
diff --git a/packages/wm/src/ipc_client.rs b/packages/wm/src/ipc_client.rs
index 5f576ddc..420df964 100644
--- a/packages/wm/src/ipc_client.rs
+++ b/packages/wm/src/ipc_client.rs
@@ -22,17 +22,19 @@ impl IpcClient {
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> {
+ /// Sends a message to the IPC server.
+ pub async fn send(&mut self, message: String) -> anyhow::Result<()> {
self
.stream
.send(Message::Text(message))
.await
.context("Failed to send command.")?;
+ Ok(())
+ }
+
+ /// Waits and returns the next reply from the IPC server.
+ pub async fn next_reply(&mut self) -> anyhow::Result<String> {
let response = self
.stream
.next()
@@ -42,13 +44,5 @@ impl IpcClient {
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/main.rs b/packages/wm/src/main.rs
index 92b96901..002a5f82 100644
--- a/packages/wm/src/main.rs
+++ b/packages/wm/src/main.rs
@@ -8,6 +8,7 @@
use std::{env, path::PathBuf};
use anyhow::{Context, Result};
+use app_command::Verbosity;
use ipc_client::IpcClient;
use tokio::process::Command;
use tracing::{debug, error, info};
@@ -32,36 +33,42 @@ mod wm_event;
mod wm_state;
mod workspaces;
+/// Main entry point for the application.
+///
+/// Conditionally runs the WM or CLI based on the given subcommand.
#[tokio::main]
async fn main() {
- match AppCommand::parse_with_default() {
+ let args = std::env::args().collect::<Vec<_>>();
+ let app_command = AppCommand::parse_with_default(&args);
+
+ let res = match app_command {
AppCommand::Start {
config_path,
verbosity,
- } => {
- // Set log level based on verbosity flag.
- tracing_subscriber::fmt()
- .with_max_level(verbosity.level())
- .init();
-
- info!(
- "Starting WM with log level {:?}.",
- verbosity.level().to_string()
- );
-
- if let Err(err) = start_wm(config_path).await {
- error!("Failed to start GlazeWM: {}", err);
- }
- }
- _ => {
- if let Err(err) = start_cli().await {
- error!("{}", err);
- }
- }
+ } => start_wm(config_path, verbosity).await,
+ AppCommand::Subscribe { .. } => start_cli(args, true).await,
+ _ => start_cli(args, false).await,
+ };
+
+ if let Err(err) = res {
+ error!("{}", err);
}
}
-async fn start_wm(config_path: Option<PathBuf>) -> Result<()> {
+async fn start_wm(
+ config_path: Option<PathBuf>,
+ verbosity: Verbosity,
+) -> Result<()> {
+ // Set log level based on verbosity flag.
+ tracing_subscriber::fmt()
+ .with_max_level(verbosity.level())
+ .init();
+
+ info!(
+ "Starting WM with log level {:?}.",
+ verbosity.level().to_string()
+ );
+
// Ensure that only one instance of the WM is running.
let _ = Platform::new_single_instance()?;
@@ -122,15 +129,23 @@ async fn start_wm(config_path: Option<PathBuf>) -> Result<()> {
}
}
-async fn start_cli() -> Result<()> {
+async fn start_cli(
+ args: Vec<String>,
+ is_subscribe_message: bool,
+) -> Result<()> {
+ tracing_subscriber::fmt().init();
+
let mut client = IpcClient::connect().await?;
- let command_str = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
+ client
+ .send(args[1..].join(" "))
+ .await
+ .context("Failed to send command to IPC server.")?;
let response = client
- .send_and_wait_reply(command_str)
+ .next_reply()
.await
- .context("Failed to send command")?;
+ .context("Failed to receive response from IPC server.")?;
println!("{}", response);