Skip to content

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

refactor: remove wrapping arc + mutex around `WmState`

Lars Bergera806212af104
diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rs
index 526100c8..2cfa3754 100644
--- a/packages/wm/src/common/platform/event_listener.rs
+++ b/packages/wm/src/common/platform/event_listener.rs
@@ -49,7 +49,7 @@ impl EventListener {
/// Initializes listener for platform events.
///
/// Returns an instance of `EventListener`.
- pub async fn start(config: &UserConfig) -> Result<Self> {
+ pub fn start(config: &UserConfig) -> Result<Self> {
let (event_tx, event_rx) = mpsc::unbounded_channel();
let event_window = EventWindow::new(
diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rs
index bc23c48a..07f3713d 100644
--- a/packages/wm/src/common/platform/platform.rs
+++ b/packages/wm/src/common/platform/platform.rs
@@ -105,10 +105,10 @@ impl Platform {
}
/// Creates a new `EventListener` for the specified user config.
- pub async fn start_event_listener(
+ pub fn start_event_listener(
config: &UserConfig,
) -> anyhow::Result<EventListener> {
- EventListener::start(config).await
+ EventListener::start(config)
}
/// Creates a new `SingleInstance`.
diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rs
index 16eeb396..ca162835 100644
--- a/packages/wm/src/ipc_server.rs
+++ b/packages/wm/src/ipc_server.rs
@@ -2,7 +2,7 @@ use std::{collections::HashMap, net::SocketAddr, sync::Arc};
use anyhow::Context;
use clap::Parser;
-use futures_util::{future, pin_mut, SinkExt, StreamExt, TryStreamExt};
+use futures_util::{SinkExt, StreamExt};
use serde::Serialize;
use tokio::{
net::{TcpListener, TcpStream},
@@ -16,7 +16,7 @@ use tracing::{error, info};
use uuid::Uuid;
use crate::{
- app_command::{AppCommand, InvokeCommand},
+ app_command::{AppCommand, InvokeCommand, QueryCommand},
wm_event::WmEvent,
wm_state::WmState,
};
@@ -45,7 +45,7 @@ struct EventSubscription {
pub struct IpcServer {
pub message_rx:
- mpsc::UnboundedReceiver<(AppCommand, mpsc::UnboundedSender<String>)>,
+ mpsc::UnboundedReceiver<(AppCommand, mpsc::UnboundedSender<Message>)>,
pub wm_command_rx:
mpsc::UnboundedReceiver<(InvokeCommand, Option<Uuid>)>,
abort_handle: task::AbortHandle,
@@ -89,7 +89,7 @@ impl IpcServer {
event_subs: Arc<Mutex<HashMap<Uuid, EventSubscription>>>,
message_tx: mpsc::UnboundedSender<(
AppCommand,
- mpsc::UnboundedSender<String>,
+ mpsc::UnboundedSender<Message>,
)>,
) -> anyhow::Result<()> {
info!("Incoming IPC connection from: {}.", addr);
@@ -103,50 +103,25 @@ impl IpcServer {
loop {
tokio::select! {
- Some(response) = response_rx.recv() => {
- if let Err(e) = outgoing.send(Message::Text(response)).await {
- error!("Error sending response: {}", e);
- break;
- }
+ Some(response) = response_rx.recv() => {
+ if let Err(err) = outgoing.send(response).await {
+ error!("Error sending response: {}", err);
+ break;
}
- Some(msg) = incoming.next() => {
- let msg = msg.context("Error reading next websocket message.")?;
+ }
+ Some(msg) = incoming.next() => {
+ let msg = msg.context("Error reading next websocket message.")?;
- if msg.is_text() || msg.is_binary() {
- let app_command =
- AppCommand::try_parse_from(msg.to_text()?.split(" "))?;
+ if msg.is_text() || msg.is_binary() {
+ let app_command =
+ AppCommand::try_parse_from(msg.to_text()?.split(" "))?;
- message_tx.send((app_command, response_tx.clone()))?;
- }
+ message_tx.send((app_command, response_tx.clone()))?;
}
+ }
}
}
- // let receive_from_others = response_rx.map(Ok).forward(outgoing);
-
- // let get_incoming = incoming
- // .try_filter(|msg| future::ready(msg.is_text()))
- // .try_for_each(|msg| {
- // let tx = response_tx.clone();
-
- // // tx.
- // async move { self.handle_message(tx, msg).await }
- // });
-
- // pin_mut!(get_incoming, receive_from_others);
-
- // while let Some(msg) = ws_stream.next().await {
- // let msg = msg.context("Error reading next websocket message.")?;
-
- // if msg.is_text() || msg.is_binary() {
- // let app_command =
- // AppCommand::try_parse_from(msg.to_text()?.split(" "))?;
-
- // // message_tx.send((app_command, ws_stream))?;
- // message_tx.send((app_command))?;
- // }
- // }
-
// TODO: Clean-up event subscriptions on errors.
let mut subscriptions = event_subs.lock().await;
@@ -167,9 +142,8 @@ impl IpcServer {
pub async fn process_message(
&self,
app_command: AppCommand,
- response_tx: mpsc::UnboundedSender<String>,
- // ws_stream: WebSocketStream<TcpStream>,
- state: Arc<Mutex<WmState>>,
+ response_tx: mpsc::UnboundedSender<Message>,
+ state: &mut WmState,
) -> anyhow::Result<()> {
// TODO: Spawn a task so that it doesn't block main thread execution.
@@ -178,7 +152,12 @@ impl IpcServer {
config_path,
verbosity,
} => todo!(),
- AppCommand::Query { command } => todo!(),
+ AppCommand::Query { command } => match command {
+ QueryCommand::Windows => todo!(),
+ QueryCommand::Monitors => todo!(),
+ QueryCommand::BindingMode => todo!(),
+ QueryCommand::Focused => todo!(),
+ },
AppCommand::Cmd {
context_container_id,
command,
@@ -187,15 +166,13 @@ impl IpcServer {
// Respond to the client with the result of the command.
let response_msg = Message::Text(serde_json::to_string(&response)?);
- // response_tx.send(response_msg)?;
- response_tx.send("aaaa".to_string())?;
- // ws_stream.send(response_msg).await?;
+ response_tx.send(response_msg)?;
}
pub async fn process_event(
&mut self,
event: WmEvent,
- state: Arc<Mutex<WmState>>,
+ state: &mut WmState,
) -> anyhow::Result<()> {
// // TODO: Spawn a task so that it doesn't block main thread execution.
// let subscriptions = self.event_subscriptions.lock().await;
diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rs
index de637166..c5957a6d 100644
--- a/packages/wm/src/main.rs
+++ b/packages/wm/src/main.rs
@@ -64,19 +64,19 @@ async fn start_wm(config_path: Option<PathBuf>) -> Result<()> {
// Start watcher process for restoring hidden windows on crash.
start_watcher_process()?;
- let mut wm = WindowManager::new(&config).await?;
+ let mut wm = WindowManager::new(&config)?;
// Start IPC server after populating initial WM state.
let mut ipc_server = IpcServer::start().await?;
// Start listening for platform events.
- let mut event_listener = Platform::start_event_listener(&config).await?;
+ let mut event_listener = Platform::start_event_listener(&config)?;
loop {
tokio::select! {
Some(event) = event_listener.event_rx.recv() => {
debug!("Received platform event: {:?}", event);
- let res = wm.process_event(event, &mut config).await;
+ let res = wm.process_event(event, &mut config);
if let Err(err) = res {
error!("Failed to process event: {:?}", err);
@@ -84,14 +84,12 @@ async fn start_wm(config_path: Option<PathBuf>) -> Result<()> {
},
Some((app_command, response_tx)) = ipc_server.message_rx.recv() => {
info!("Received IPC message: {:?}", app_command);
- ipc_server.process_message(app_command, response_tx, wm.state.clone()).await;
+ ipc_server.process_message(app_command, response_tx, &mut wm.state).await;
},
- Some(wm_command) = ipc_server.wm_command_rx.recv() => {
- info!("Received WM command via IPC: {:?}", wm_command);
- let (command, subject_container_id) = wm_command;
+ Some((command, subject_container_id)) = ipc_server.wm_command_rx.recv() => {
+ info!("Received WM command via IPC: {:?}", command);
let res = wm
- .process_commands(vec![command], subject_container_id, &mut config)
- .await;
+ .process_commands(vec![command], subject_container_id, &mut config);
if let Err(err) = res {
error!("Failed to process command: {:?}", err);
@@ -108,7 +106,7 @@ async fn start_wm(config_path: Option<PathBuf>) -> Result<()> {
event_listener.update(&config, active_binding_modes);
}
- ipc_server.process_event(wm_event, wm.state.clone()).await;
+ ipc_server.process_event(wm_event, &mut wm.state).await;
},
}
}
diff --git a/packages/wm/src/user_config.rs b/packages/wm/src/user_config.rs
index 1f2190d9..4623833d 100644
--- a/packages/wm/src/user_config.rs
+++ b/packages/wm/src/user_config.rs
@@ -1,11 +1,8 @@
-use std::{path::PathBuf, sync::Arc};
+use std::path::PathBuf;
use anyhow::{Context, Result};
use serde::Deserialize;
-use tokio::{
- fs,
- sync::{mpsc, Mutex},
-};
+use tokio::{fs, sync::mpsc};
use crate::{
app_command::InvokeCommand,
diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rs
index c6ce831c..b7546df8 100644
--- a/packages/wm/src/wm.rs
+++ b/packages/wm/src/wm.rs
@@ -1,10 +1,5 @@
-use std::sync::Arc;
-
use anyhow::Context;
-use tokio::sync::{
- mpsc::{self},
- Mutex,
-};
+use tokio::sync::mpsc::{self};
use uuid::Uuid;
use crate::common::events::handle_mouse_move;
@@ -29,90 +24,80 @@ use crate::{
pub struct WindowManager {
pub event_rx: mpsc::UnboundedReceiver<WmEvent>,
- pub state: Arc<Mutex<WmState>>,
+ pub state: WmState,
}
impl WindowManager {
- pub async fn new(config: &UserConfig) -> anyhow::Result<Self> {
+ pub fn new(config: &UserConfig) -> anyhow::Result<Self> {
let (event_tx, event_rx) = mpsc::unbounded_channel();
let mut state = WmState::new(event_tx);
state.populate(&config)?;
- Ok(Self {
- event_rx,
- state: Arc::new(Mutex::new(state)),
- })
+ Ok(Self { event_rx, state })
}
- pub async fn process_event(
+ pub fn process_event(
&mut self,
event: PlatformEvent,
config: &mut UserConfig,
) -> anyhow::Result<()> {
- // Handle keybinding events separately since they would cause a double
- // borrow of the `state` mutex.
- if let PlatformEvent::KeybindingTriggered(kb_config) = event {
- self
- .process_commands(kb_config.commands, None, config)
- .await?;
-
- return Ok(());
- }
-
- let mut state = self.state.lock().await;
+ let state = &mut self.state;
match event {
PlatformEvent::PowerModeChanged => Ok(()),
PlatformEvent::DisplaySettingsChanged => {
- handle_display_settings_changed(&mut state, config)
+ handle_display_settings_changed(state, config)
+ }
+ PlatformEvent::KeybindingTriggered(kb_config) => {
+ // Return early since we don't want to redraw twice.
+ return self.process_commands(kb_config.commands, None, config);
}
PlatformEvent::MouseMove(event) => {
- handle_mouse_move(event, &mut state, config)
+ handle_mouse_move(event, state, config)
}
PlatformEvent::WindowDestroyed(window) => {
- handle_window_destroyed(window, &mut state)
+ handle_window_destroyed(window, state)
}
PlatformEvent::WindowFocused(window) => {
- handle_window_focused(window, &mut state, config)
+ handle_window_focused(window, state, config)
}
PlatformEvent::WindowHidden(window) => {
- handle_window_hidden(window, &mut state)
+ handle_window_hidden(window, state)
}
PlatformEvent::WindowLocationChanged(window) => {
- handle_window_location_changed(window, &mut state, config)
+ handle_window_location_changed(window, state, config)
}
PlatformEvent::WindowMinimized(window) => {
- handle_window_minimized(window, &mut state, config)
+ handle_window_minimized(window, state, config)
}
PlatformEvent::WindowMinimizeEnded(window) => {
- handle_window_minimize_ended(window, &mut state, config)
+ handle_window_minimize_ended(window, state, config)
}
PlatformEvent::WindowMovedOrResized(window) => {
- handle_window_moved_or_resized(window, &mut state)
+ handle_window_moved_or_resized(window, state)
}
PlatformEvent::WindowShown(window) => {
- handle_window_shown(window, &mut state, config)
+ handle_window_shown(window, state, config)
}
PlatformEvent::WindowTitleChanged(_) => Ok(()),
- _ => Ok(()),
}?;
- redraw(&mut state)?;
- sync_native_focus(&mut state)?;
+ redraw(state)?;
+ sync_native_focus(state)?;
Ok(())
}
- pub async fn process_commands(
+ pub fn process_commands(
&mut self,
commands: Vec<InvokeCommand>,
subject_container_id: Option<Uuid>,
config: &mut UserConfig,
) -> anyhow::Result<()> {
- let mut state = self.state.lock().await;
+ let state = &mut self.state;
- // Get container to run WM commands with.
+ // Get the container to run WM commands with.
let mut subject_container = match subject_container_id {
Some(id) => state.container_by_id(id).with_context(|| {
format!("No container found with the given ID '{}'.", id)
@@ -123,19 +108,21 @@ impl WindowManager {
};
for command in commands {
- command.run(subject_container.clone(), &mut state, config)?;
+ command.run(subject_container.clone(), state, config)?;
// Update the subject container in case the container type changes.
// For example, when going from a tiling to a floating window.
- subject_container =
- match state.container_by_id(subject_container.id()) {
+ subject_container = match subject_container.is_detached() {
+ false => subject_container,
+ true => match state.container_by_id(subject_container.id()) {
Some(container) => container,
None => break,
- }
+ },
+ }
}
- redraw(&mut state)?;
- sync_native_focus(&mut state)?;
+ redraw(state)?;
+ sync_native_focus(state)?;
Ok(())
}
diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rs
index 47005169..c623a43e 100644
--- a/packages/wm/src/wm_state.rs
+++ b/packages/wm/src/wm_state.rs
@@ -9,11 +9,11 @@ use crate::{
common::{
commands::sync_native_focus,
platform::{NativeMonitor, NativeWindow, Platform},
- Direction, Rect,
+ Direction,
},
containers::{
commands::{redraw, set_focused_descendant},
- traits::{CommonGetters, PositionGetters},
+ traits::CommonGetters,
Container, RootContainer, WindowContainer,
},
monitors::{commands::add_monitor, Monitor},