GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: change `ConfigReader` -> `UserConfig` and wrap in arc + mutex
Lars Berger08679c12e17f
diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rsindex 68c17fa2..0de37bfe 100644--- a/packages/wm/src/common/platform/event_listener.rs+++ b/packages/wm/src/common/platform/event_listener.rs@@ -6,7 +6,7 @@ use tokio::sync::{Mutex,};-use crate::user_config::{KeybindingConfig, UserConfig};+use crate::user_config::{KeybindingConfig, ParsedConfig, UserConfig};use super::{EventWindow, NativeWindow};@@ -35,14 +35,14 @@ impl EventListener {/// Initializes listener for platform events.////// Creates an instance of `EventListener`.- pub async fn start(config: Arc<Mutex<UserConfig>>) -> Result<Self> {+ pub async fn start(config: &Arc<Mutex<UserConfig>>) -> Result<Self> {let (event_tx, event_rx) = mpsc::unbounded_channel();let config = config.lock().await;let event_window = EventWindow::new(event_tx,- config.keybindings.clone(),- config.general.focus_follows_cursor,+ config.value.keybindings.clone(),+ config.value.general.focus_follows_cursor,);Ok(Self {@@ -52,7 +52,7 @@ impl EventListener {}/// Updates the event listener with the latest user config.- pub fn update(&mut self, config: &UserConfig) {+ pub fn update(&mut self, config: &ParsedConfig) {self.event_window.update(config.keybindings.clone(),config.general.focus_follows_cursor,diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rsindex 056d59e0..d586035b 100644--- a/packages/wm/src/common/platform/platform.rs+++ b/packages/wm/src/common/platform/platform.rs@@ -3,7 +3,7 @@ use std::sync::Arc;use tokio::sync::Mutex;use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow;-use crate::user_config::UserConfig;+use crate::user_config::{ParsedConfig, UserConfig};use super::{native_monitor, native_window, EventListener, NativeMonitor,@@ -38,7 +38,7 @@ impl Platform {}pub async fn new_event_listener(- config: Arc<Mutex<UserConfig>>,+ config: &Arc<Mutex<UserConfig>>,) -> anyhow::Result<EventListener> {EventListener::start(config).await}diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rsindex eddd4640..bb1b6ed5 100644--- a/packages/wm/src/ipc_server.rs+++ b/packages/wm/src/ipc_server.rs@@ -71,6 +71,7 @@ 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!()}}diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rsindex 3d06b268..ceea0f7f 100644--- a/packages/wm/src/main.rs+++ b/packages/wm/src/main.rs@@ -12,7 +12,7 @@ use tokio::{};use tracing::{info, level_filters::LevelFilter};use tracing_subscriber::EnvFilter;-use user_config::ConfigReader;+use user_config::UserConfig;use wm::WindowManager;use crate::cli::{Cli, CliCommand};@@ -49,26 +49,21 @@ async fn main() {async fn start_wm(config_path: Option<String>) -> Result<()> {// Parse and validate user config.- let mut config_reader = ConfigReader::read(config_path).await?;+ let config = UserConfig::read(config_path).await?;let mut ipc_server = IpcServer::start().await?;// Start watcher process for restoring hidden windows on crash.start_watcher_process()?;- let mut wm = WindowManager::start(- config_reader.config(),- config_reader.changes_tx.clone(),- )?;+ let mut wm = WindowManager::start(&config).await?;// Start listening for platform events.- let mut event_listener =- Platform::new_event_listener(config_reader.config()).await?;+ let mut event_listener = Platform::new_event_listener(&config).await?;loop {let wm_state = wm.state.clone();- let config = config_reader.config();- let config = config.lock().await;+ let mut config = config.lock().await;tokio::select! {Some(event) = event_listener.event_rx.recv() => {@@ -87,7 +82,7 @@ async fn start_wm(config_path: Option<String>) -> Result<()> {info!("Received WM command via IPC: {:?}", wm_command);wm.process_command(wm_command).await},- Some(config) = config_reader.changes_rx.recv() => {+ Some(config) = config.changes_rx.recv() => {info!("Received user config update: {:?}", config);event_listener.update(&config);},diff --git a/packages/wm/src/user_config.rs b/packages/wm/src/user_config.rsindex af4e4787..1604f382 100644--- a/packages/wm/src/user_config.rs+++ b/packages/wm/src/user_config.rs@@ -112,7 +112,7 @@ pub struct WorkspaceConfig {}#[derive(Clone, Debug, Deserialize)]-pub struct UserConfig {+pub struct ParsedConfig {pub binding_modes: Vec<BindingModeConfig>,pub focus_borders: FocusBordersConfig,pub gaps: GapsConfig,@@ -122,47 +122,21 @@ pub struct UserConfig {pub workspaces: Vec<WorkspaceConfig>,}-impl UserConfig {- pub fn workspace_config_for_monitor(- &self,- monitor: &Monitor,- active_workspaces: &Vec<Workspace>,- ) -> Option<WorkspaceConfig> {- let mut inactive_configs = self.workspaces.iter().filter(|config| {- active_workspaces- .iter()- .find(|workspace| workspace.config().name == config.name)- .is_none()- });-- let bound_config = inactive_configs.find(|config| {- config- .bind_to_monitor- .as_ref()- .map(|m| m == &monitor.name())- .unwrap_or(false)- });-- // Get the first workspace config that isn't bound to a monitor.- bound_config- .or(inactive_configs.find(|config| config.bind_to_monitor.is_none()))- .cloned()- }-}-#[derive(Debug)]-pub struct ConfigReader {- pub config: Arc<Mutex<UserConfig>>,- pub changes_rx: mpsc::UnboundedReceiver<UserConfig>,- pub changes_tx: mpsc::UnboundedSender<UserConfig>,+pub struct UserConfig {+ pub value: ParsedConfig,+ pub changes_rx: mpsc::UnboundedReceiver<ParsedConfig>,+ pub changes_tx: mpsc::UnboundedSender<ParsedConfig>,}const SAMPLE_CONFIG: &str =include_str!("../../../resources/sample-config.yaml");-impl ConfigReader {+impl UserConfig {/// Read and validate the user config from the given path.- pub async fn read(config_path: Option<String>) -> Result<Self> {+ pub async fn read(+ config_path: Option<String>,+ ) -> Result<Arc<Mutex<Self>>> {let default_config_path = home::home_dir().context("Unable to get home directory.")?.join(".glzr/glazewm/config.yaml");@@ -183,13 +157,14 @@ impl ConfigReader {let parsed_config = serde_yaml::from_str(&config_str)?;- let (changes_tx, changes_rx) = mpsc::unbounded_channel::<UserConfig>();+ let (changes_tx, changes_rx) =+ mpsc::unbounded_channel::<ParsedConfig>();- Ok(Self {- config: Arc::new(Mutex::new(parsed_config)),+ Ok(Arc::new(Mutex::new(Self {+ value: parsed_config,changes_rx,changes_tx,- })+ })))}/// Initialize a new config file from the sample config resource.@@ -210,12 +185,45 @@ impl ConfigReader {Ok(())}- pub fn config(&self) -> Arc<Mutex<UserConfig>> {- self.config.clone()- }-// TODO: Maybe this should be on the impl of `UserConfig` instead.async fn refresh(&self) -> Result<()> {Ok(())}++ pub fn workspace_config_for_monitor(+ &self,+ monitor: &Monitor,+ active_workspaces: &Vec<Workspace>,+ ) -> Option<WorkspaceConfig> {+ let inactive_configs = self+ .value+ .workspaces+ .iter()+ .filter(|config| {+ active_workspaces+ .iter()+ .find(|workspace| workspace.config().name == config.name)+ .is_none()+ })+ .collect::<Vec<_>>();++ let bound_config = inactive_configs.iter().find(|&config| {+ config+ .bind_to_monitor+ .as_ref()+ .map(|monitor_name| monitor_name == &monitor.name())+ .unwrap_or(false)+ });++ // Get the first workspace config that isn't bound to a monitor.+ bound_config+ .or(+ inactive_configs+ .iter()+ .find(|config| config.bind_to_monitor.is_none()),+ )+ .or(inactive_configs.first())+ .cloned()+ .cloned()+ }}diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rsindex 3518fefe..3b594954 100644--- a/packages/wm/src/wm.rs+++ b/packages/wm/src/wm.rs@@ -7,8 +7,11 @@ use tokio::sync::{};use crate::{- common::platform::PlatformEvent, user_config::UserConfig,- wm_command::WmCommand, wm_event::WmEvent, wm_state::WmState,+ common::platform::PlatformEvent,+ user_config::{ParsedConfig, UserConfig},+ wm_command::WmCommand,+ wm_event::WmEvent,+ wm_state::WmState,};pub struct WindowManager {@@ -17,14 +20,12 @@ pub struct WindowManager {}impl WindowManager {- pub fn start(- config: Arc<Mutex<UserConfig>>,- config_changes_tx: UnboundedSender<UserConfig>,- ) -> Result<Self> {+ pub async fn start(config: &Arc<Mutex<UserConfig>>) -> Result<Self> {+ let config = config.lock().await;let (event_tx, event_rx) = mpsc::unbounded_channel();- let mut state = WmState::new(config, config_changes_tx, event_tx);- state.populate()?;+ let mut state = WmState::new(event_tx);+ state.populate(&config)?;Ok(Self {event_rx,@@ -33,7 +34,7 @@ impl WindowManager {}pub async fn process_event(&mut self, event: PlatformEvent) {- todo!()+ // TODO}pub async fn process_command(&mut self, command: WmCommand) {diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rsindex db6668cf..f0b90da5 100644--- a/packages/wm/src/wm_state.rs+++ b/packages/wm/src/wm_state.rs@@ -1,13 +1,11 @@-use std::{rc::Weak, sync::Arc};-use anyhow::anyhow;-use tokio::sync::{mpsc::UnboundedSender, Mutex};+use tokio::sync::mpsc::UnboundedSender;use crate::{common::platform::{NativeMonitor, NativeWindow, Platform},containers::{traits::TilingBehavior, Container, RootContainer},monitors::Monitor,- user_config::{BindingModeConfig, UserConfig},+ user_config::{BindingModeConfig, ParsedConfig, UserConfig},windows::TilingWindow,wm_event::WmEvent,workspaces::Workspace,@@ -28,38 +26,26 @@ pub struct WmState {/// Currently enabled binding modes.binding_modes: Vec<BindingModeConfig>,- /// Parsed user config.- config: Arc<Mutex<UserConfig>>,-- config_changes_tx: UnboundedSender<UserConfig>,-event_tx: UnboundedSender<WmEvent>,}impl WmState {- pub fn new(- config: Arc<Mutex<UserConfig>>,- config_changes_tx: UnboundedSender<UserConfig>,- event_tx: UnboundedSender<WmEvent>,- ) -> Self {+ pub fn new(event_tx: UnboundedSender<WmEvent>) -> Self {Self {root_container: RootContainer::new(),containers_to_redraw: Vec::new(),has_pending_focus_sync: false,binding_modes: Vec::new(),- config,- config_changes_tx,event_tx,}}/// Populates the initial WM state by creating containers for all/// existing windows and monitors.- pub fn populate(&mut self) -> anyhow::Result<()> {- // Get the originally focused window when the WM is started.+ pub fn populate(&mut self, config: &UserConfig) -> anyhow::Result<()> {+ // Get the originally focused window when the WM was started.let foreground_window = Platform::foreground_window();let native_monitors = Platform::monitors()?;- let config = self.config.try_lock()?;for native_monitor in native_monitors {let monitor = Monitor::new(native_monitor);@@ -68,8 +54,10 @@ impl WmState {.workspace_config_for_monitor(&monitor, &self.workspaces()).ok_or(anyhow!("No workspace config found for monitor."))?;- let workspace =- Workspace::new(workspace_config, config.gaps.outer_gap.clone());+ let workspace = Workspace::new(+ workspace_config,+ config.value.gaps.outer_gap.clone(),+ );monitor.insert_child(0, workspace.into());self.root_container.insert_child(0, monitor.into());