GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: add commands for attaching container, resizing, activating a workspace, and adding a monitor
Lars Bergerd422e516f6a7
diff --git a/packages/wm/src/containers/commands/attach_container.rs b/packages/wm/src/containers/commands/attach_container.rsnew file mode 100644index 00000000..889b207e--- /dev/null+++ b/packages/wm/src/containers/commands/attach_container.rs@@ -0,0 +1,46 @@+use anyhow::bail;++use crate::containers::{+ traits::{CommonBehavior, TilingBehavior},+ Container, TilingContainer,+};++use super::resize_tiling_container;++/// Inserts a child container at the specified index. Only tiling+/// containers can have children.+///+/// The inserted child will be resized to fit the available space.+pub fn attach_container(+ child: Container,+ target_parent: &TilingContainer,+ target_index: usize,+) -> anyhow::Result<()> {+ if !child.is_detached() {+ bail!("Cannot attach an already attached container.");+ }++ target_parent+ .borrow_children_mut()+ .insert(target_index, child.clone());++ *child.borrow_parent_mut() = Some(target_parent.as_tiling_container());++ // Resize the child and its siblings if it is a tiling container.+ if let Ok(child) = TryInto::<TilingContainer>::try_into(child) {+ let resizable_siblings = child.tiling_siblings().collect::<Vec<_>>();++ if resizable_siblings.is_empty() {+ child.set_size_percent(1.0);+ return Ok(());+ }++ // Set initial size percentage to 0, and then size up the container+ // to the default percentage.+ let default_percentage = 1.0 / (resizable_siblings.len() + 1) as f32;+ child.set_size_percent(0.0);+ resize_tiling_container(&child, default_percentage);+ }++ Ok(())+}diff --git a/packages/wm/src/containers/commands/mod.rs b/packages/wm/src/containers/commands/mod.rsindex b7a42113..f89874d7 100644--- a/packages/wm/src/containers/commands/mod.rs+++ b/packages/wm/src/containers/commands/mod.rs@@ -1,3 +1,7 @@-mod redraw_command;+mod attach_container;+mod redraw;+mod resize_tiling_container;-pub use redraw_command::*;+pub use attach_container::*;+pub use redraw::*;+pub use resize_tiling_container::*;diff --git a/packages/wm/src/containers/commands/redraw_command.rs b/packages/wm/src/containers/commands/redraw.rssimilarity index 95%rename from packages/wm/src/containers/commands/redraw_command.rsrename to packages/wm/src/containers/commands/redraw.rsindex b24d1bce..42c605e8 100644--- a/packages/wm/src/containers/commands/redraw_command.rs+++ b/packages/wm/src/containers/commands/redraw.rs@@ -11,10 +11,10 @@ use crate::{wm_state::WmState,};-pub fn redraw_command(+pub fn redraw(state: &mut WmState,- user_config: UserConfig,-) -> anyhow::Result<&mut WmState> {+ config: &UserConfig,+) -> anyhow::Result<()> {let windows_to_redraw = state.windows_to_redraw();// Get windows that are minimized/maximized and shouldn't be.@@ -55,7 +55,7 @@ pub fn redraw_command(let position_args = get_position_args(&window,- user_config.value.general.show_floating_on_top,+ config.value.general.show_floating_on_top,);let _ = window.native().set_position(&position_args);@@ -71,7 +71,7 @@ pub fn redraw_command(}state.clear_containers_to_redraw();- Ok(state)+ Ok(())}fn get_position_args(diff --git a/packages/wm/src/containers/commands/resize_tiling_container.rs b/packages/wm/src/containers/commands/resize_tiling_container.rsnew file mode 100644index 00000000..183d3667--- /dev/null+++ b/packages/wm/src/containers/commands/resize_tiling_container.rs@@ -0,0 +1,85 @@+use crate::containers::{+ traits::{CommonBehavior, TilingBehavior},+ TilingContainer,+};++const MIN_SIZE_PERCENTAGE: f32 = 0.01;++pub fn resize_tiling_container(+ container_to_resize: &TilingContainer,+ resize_percentage: f32,+) {+ let resizable_siblings =+ container_to_resize.tiling_siblings().collect::<Vec<_>>();++ // Ignore cases where the container to resize is a workspace or the only+ // child.+ if resizable_siblings.is_empty()+ || container_to_resize.as_workspace().is_some()+ {+ return;+ }++ // Get available size percentage amongst siblings.+ let available_size_percentage =+ get_available_size_percentage(&resizable_siblings);++ let min_resize_delta =+ MIN_SIZE_PERCENTAGE - container_to_resize.size_percent();++ // Prevent the container from being smaller than the minimum and larger+ // than space available from sibling containers.+ let clamped_resize_percentage = resize_percentage+ .max(min_resize_delta)+ .min(available_size_percentage);++ // Resize the container.+ container_to_resize.set_size_percent(+ container_to_resize.size_percent() + clamped_resize_percentage,+ );++ // Distribute the size percentage amongst its siblings.+ let sibling_count = resizable_siblings.len();+ for sibling in resizable_siblings {+ let sibling_resize_percentage = get_sibling_resize_percentage(+ &sibling,+ sibling_count,+ clamped_resize_percentage,+ available_size_percentage,+ );++ sibling.set_size_percent(+ sibling.size_percent() - sibling_resize_percentage,+ );+ }+}++fn get_available_size_percentage(+ containers: &Vec<TilingContainer>,+) -> f32 {+ containers.iter().fold(0.0, |sum, container| {+ sum + container.size_percent() - MIN_SIZE_PERCENTAGE+ })+}++fn get_sibling_resize_percentage(+ sibling_to_resize: &TilingContainer,+ sibling_count: usize,+ size_percentage: f32,+ available_size_percentage: f32,+) -> f32 {+ let con_available_size_percentage =+ sibling_to_resize.size_percent() - MIN_SIZE_PERCENTAGE;++ // Get percentage of resize that affects this container. The available+ // size percentage here can be 0 when the main container to resize is+ // shrunk from max size percentage.+ let resize_factor =+ if available_size_percentage == 0.0 || size_percentage < 0.0 {+ 1.0 / sibling_count as f32+ } else {+ con_available_size_percentage / available_size_percentage+ };++ resize_factor * size_percentage+}diff --git a/packages/wm/src/containers/traits/tiling_behavior.rs b/packages/wm/src/containers/traits/tiling_behavior.rsindex 05966ae2..510ebd60 100644--- a/packages/wm/src/containers/traits/tiling_behavior.rs+++ b/packages/wm/src/containers/traits/tiling_behavior.rs@@ -1,11 +1,9 @@use enum_dispatch::enum_dispatch;-use crate::containers::{Container, DirectionContainer, TilingContainer};+use crate::containers::{DirectionContainer, TilingContainer};use super::CommonBehavior;-const MIN_SIZE_PERCENTAGE: f32 = 0.01;-#[enum_dispatch]pub trait TilingBehavior: CommonBehavior {fn as_tiling_container(&self) -> TilingContainer;@@ -13,118 +11,12 @@ pub trait TilingBehavior: CommonBehavior {fn size_percent(&self) -> f32;fn set_size_percent(&self, size_percent: f32) -> ();-- /// Inserts a child container at the specified index. Only tiling- /// containers can have children.- ///- /// The inserted child will be resized to fit the available space.- fn insert_child(&self, target_index: usize, child: Container) {- self- .borrow_children_mut()- .insert(target_index, child.clone());-- *child.borrow_parent_mut() = Some(self.as_tiling_container());-- if let Ok(child) = TryInto::<TilingContainer>::try_into(child) {- let resizable_siblings = child.tiling_siblings().collect::<Vec<_>>();-- if resizable_siblings.is_empty() {- child.set_size_percent(1.0);- return;- }-- // Set initial size percentage to 0, and then size up the container- // to the default percentage.- let default_percentage = 1.0 / (resizable_siblings.len() + 1) as f32;- child.set_size_percent(0.0);- resize_tiling_container(&child, default_percentage);- }- }-}--fn resize_tiling_container(- container_to_resize: &TilingContainer,- resize_percentage: f32,-) {- let resizable_siblings =- container_to_resize.tiling_siblings().collect::<Vec<_>>();-- // Ignore cases where the container to resize is a workspace or the only- // child.- if resizable_siblings.is_empty()- || container_to_resize.as_workspace().is_some()- {- return;- }-- // Get available size percentage amongst siblings.- let available_size_percentage =- get_available_size_percentage(&resizable_siblings);-- let min_resize_delta =- MIN_SIZE_PERCENTAGE - container_to_resize.size_percent();-- // Prevent the container from being smaller than the minimum and larger- // than space available from sibling containers.- let clamped_resize_percentage = resize_percentage- .max(min_resize_delta)- .min(available_size_percentage);-- // Resize the container.- container_to_resize.set_size_percent(- container_to_resize.size_percent() + clamped_resize_percentage,- );-- // Distribute the size percentage amongst its siblings.- let sibling_count = resizable_siblings.len();- for sibling in resizable_siblings {- let sibling_resize_percentage = get_sibling_resize_percentage(- &sibling,- sibling_count,- clamped_resize_percentage,- available_size_percentage,- );-- sibling.set_size_percent(- sibling.size_percent() - sibling_resize_percentage,- );- }-}--fn get_available_size_percentage(- containers: &Vec<TilingContainer>,-) -> f32 {- containers.iter().fold(0.0, |sum, container| {- sum + container.size_percent() - MIN_SIZE_PERCENTAGE- })-}--fn get_sibling_resize_percentage(- sibling_to_resize: &TilingContainer,- sibling_count: usize,- size_percentage: f32,- available_size_percentage: f32,-) -> f32 {- let con_available_size_percentage =- sibling_to_resize.size_percent() - MIN_SIZE_PERCENTAGE;-- // Get percentage of resize that affects this container. The available- // size percentage here can be 0 when the main container to resize is- // shrunk from max size percentage.- let resize_factor =- if available_size_percentage == 0.0 || size_percentage < 0.0 {- 1.0 / sibling_count as f32- } else {- con_available_size_percentage / available_size_percentage- };-- resize_factor * size_percentage}/// Implements the `TilingBehavior` trait for a given struct.////// Expects that the struct has a wrapping `RefCell` containing a struct-/// with a `children` field.+/// with a `size_percent` field.#[macro_export]macro_rules! impl_tiling_behavior {($struct_name:ident) => {diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rsindex bb1b6ed5..1229a35a 100644--- a/packages/wm/src/ipc_server.rs+++ b/packages/wm/src/ipc_server.rs@@ -67,11 +67,10 @@ impl IpcServer {_message: IpcMessage,wm_state: Arc<Mutex<WmState>>,) {- todo!()+ // TODO: Spawn a task so that it doesn't block main thread execution.}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 07f364d6..be5150a2 100644--- a/packages/wm/src/main.rs+++ b/packages/wm/src/main.rs@@ -71,7 +71,8 @@ async fn start_wm(config_path: Option<String>) -> Result<()> {wm.process_event(event).await},Some(wm_event) = wm.event_rx.recv() => {- info!("Received WM event: {:?}", wm_event);+ // TODO: Log event struct when debug of containers isn't recursive.+ info!("Received WM event");ipc_server.process_event(wm_event).await},Some(ipc_message) = ipc_server.message_rx.recv() => {diff --git a/packages/wm/src/monitors/commands/add_monitor.rs b/packages/wm/src/monitors/commands/add_monitor.rsnew file mode 100644index 00000000..86c8cf38--- /dev/null+++ b/packages/wm/src/monitors/commands/add_monitor.rs@@ -0,0 +1,38 @@+use anyhow::Context;++use crate::{+ common::platform::NativeMonitor,+ containers::commands::attach_container,+ monitors::Monitor,+ user_config::UserConfig,+ wm_event::{MonitorAddedEvent, WmEvent},+ wm_state::WmState,+ workspaces::commands::activate_workspace,+};++pub fn add_monitor(+ native_monitor: NativeMonitor,+ state: &mut WmState,+ config: &UserConfig,+) -> anyhow::Result<()> {+ // Create `Monitor` instance. This uses the working area of the monitor+ // instead of the bounds of the display. The working area excludes+ // taskbars and other reserved display space.+ let monitor = Monitor::new(native_monitor);++ attach_container(+ monitor.clone().into(),+ &state.root_container.clone().into(),+ 0,+ )?;++ state.emit_event(WmEvent::MonitorAdded(MonitorAddedEvent {+ added_monitor: monitor.clone(),+ }));++ // Activate a workspace on the newly added monitor.+ activate_workspace(None, &monitor, state, config)+ .context("At least 1 workspace is required per monitor.")?;++ Ok(())+}diff --git a/packages/wm/src/monitors/commands/mod.rs b/packages/wm/src/monitors/commands/mod.rsnew file mode 100644index 00000000..70f0ec97--- /dev/null+++ b/packages/wm/src/monitors/commands/mod.rs@@ -0,0 +1,3 @@+mod add_monitor;++pub use add_monitor::*;diff --git a/packages/wm/src/monitors/mod.rs b/packages/wm/src/monitors/mod.rsindex 407205d6..e75205b2 100644--- a/packages/wm/src/monitors/mod.rs+++ b/packages/wm/src/monitors/mod.rs@@ -1,3 +1,4 @@+pub mod commands;mod monitor;pub use monitor::*;diff --git a/packages/wm/src/wm_event.rs b/packages/wm/src/wm_event.rsindex 84967d5d..de1bdcd1 100644--- a/packages/wm/src/wm_event.rs+++ b/packages/wm/src/wm_event.rs@@ -3,6 +3,8 @@ use uuid::Uuid;use crate::{common::{platform::WindowHandle, TilingDirection},containers::Container,+ monitors::Monitor,+ workspaces::Workspace,};#[derive(Debug)]@@ -22,7 +24,7 @@ pub struct FocusedContainerMovedEvent {#[derive(Debug)]pub struct MonitorAddedEvent {- pub added_monitor: Container,+ pub added_monitor: Monitor,}#[derive(Debug)]@@ -54,7 +56,7 @@ pub struct WindowUnmanagedEvent {#[derive(Debug)]pub struct WorkspaceActivatedEvent {- pub activated_workspace: Container,+ pub activated_workspace: Workspace,}#[derive(Debug)]diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rsindex 6c9a8ce4..28c63ac2 100644--- a/packages/wm/src/wm_state.rs+++ b/packages/wm/src/wm_state.rs@@ -1,13 +1,19 @@use anyhow::anyhow;use tokio::sync::mpsc::UnboundedSender;+use tracing::warn;+use uuid::Uuid;use crate::{- common::platform::{NativeMonitor, NativeWindow, Platform},+ common::{+ platform::{NativeMonitor, NativeWindow, Platform},+ TilingDirection,+ },containers::{+ commands::attach_container,traits::{CommonBehavior, TilingBehavior},Container, RootContainer, WindowContainer,},- monitors::Monitor,+ monitors::{commands::add_monitor, Monitor},user_config::{BindingModeConfig, UserConfig},windows::TilingWindow,wm_event::WmEvent,@@ -17,17 +23,17 @@ use crate::{pub struct WmState {/// Root node of the container tree. Monitors are the children of the/// root node, followed by workspaces, then split containers/windows.- root_container: RootContainer,+ pub root_container: RootContainer,/// Containers (and their descendants) that have a pending redraw.containers_to_redraw: Vec<Container>,/// Whether native focus needs to be reassigned to the WM's focused/// container.- has_pending_focus_sync: bool,+ pub has_pending_focus_sync: bool,/// Currently enabled binding modes.- binding_modes: Vec<BindingModeConfig>,+ pub binding_modes: Vec<BindingModeConfig>,event_tx: UnboundedSender<WmEvent>,}@@ -48,22 +54,11 @@ impl WmState {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()?;-- for native_monitor in native_monitors {- let monitor = Monitor::new(native_monitor);-- let workspace_config = config- .workspace_config_for_monitor(&monitor, &self.workspaces())- .ok_or(anyhow!("No workspace config found for monitor."))?;-- 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());+ // Create a monitor, and consequently a workspace, for each detected+ // native monitor.+ for native_monitor in Platform::monitors()? {+ add_monitor(native_monitor, self, config)?;}for native_window in Platform::manageable_windows()? {@@ -74,12 +69,11 @@ impl WmState {if let Some(monitor) = nearest_monitor {// TODO: This should actually add to the monitor's displayed workspace.let window = TilingWindow::new(native_window);- monitor.insert_child(0, window.into());+ attach_container(window.into(), &monitor.into(), 0)?;}}self.has_pending_focus_sync = true;-Ok(())}@@ -158,11 +152,17 @@ impl WmState {// }// }- // pub fn container_by_id(&self, id: Uuid) -> Option<Arc<Container>> {- // self- // .root_container- // .self_and_descendants()- // .into_iter()- // .find(|container| container.id() == id)- // }+ pub fn emit_event(&self, event: WmEvent) {+ if let Err(err) = self.event_tx.send(event) {+ warn!("Failed to send event: {}", err);+ }+ }++ pub fn container_by_id(&self, id: Uuid) -> Option<Container> {+ self+ .root_container+ .self_and_descendants()+ .into_iter()+ .find(|container| container.id() == id)+ }}diff --git a/packages/wm/src/workspaces/commands/activate_workspace.rs b/packages/wm/src/workspaces/commands/activate_workspace.rsnew file mode 100644index 00000000..78a20186--- /dev/null+++ b/packages/wm/src/workspaces/commands/activate_workspace.rs@@ -0,0 +1,79 @@+use anyhow::Context;++use crate::{+ common::TilingDirection,+ containers::{commands::attach_container, traits::PositionBehavior},+ monitors::Monitor,+ user_config::{UserConfig, WorkspaceConfig},+ wm_event::{WmEvent, WorkspaceActivatedEvent},+ wm_state::WmState,+ workspaces::Workspace,+};++/// Activates a workspace on the target monitor.+///+/// If no workspace name is provided, the first suitable workspace defined+/// in the user's config will be used.+pub fn activate_workspace(+ workspace_name: Option<String>,+ target_monitor: &Monitor,+ state: &mut WmState,+ config: &UserConfig,+) -> anyhow::Result<()> {+ let workspace_config =+ get_workspace_config(workspace_name, target_monitor, state, config)?;++ let tiling_direction =+ match target_monitor.height() > target_monitor.width() {+ true => TilingDirection::Vertical,+ false => TilingDirection::Horizontal,+ };++ let workspace = Workspace::new(+ workspace_config,+ config.value.gaps.outer_gap.clone(),+ tiling_direction,+ );++ // Attach the created workspace to the specified monitor.+ attach_container(+ workspace.clone().into(),+ &target_monitor.clone().into(),+ 0,+ )?;++ state.emit_event(WmEvent::WorkspaceActivated(WorkspaceActivatedEvent {+ activated_workspace: workspace,+ }));++ Ok(())+}++fn get_workspace_config(+ workspace_name: Option<String>,+ target_monitor: &Monitor,+ state: &mut WmState,+ config: &UserConfig,+) -> anyhow::Result<WorkspaceConfig> {+ match workspace_name {+ Some(workspace_name) => {+ let found_config = state+ .workspaces()+ .iter()+ .find(|w| w.config().name == workspace_name)+ .with_context(|| {+ format!("Workspace with name {} doesn't exist.", workspace_name)+ })?+ .config();++ Ok(found_config)+ }+ None => {+ let inactive_config = config+ .workspace_config_for_monitor(&target_monitor, &state.workspaces())+ .context("No workspace config found for monitor.")?;++ Ok(inactive_config)+ }+ }+}diff --git a/packages/wm/src/workspaces/commands/mod.rs b/packages/wm/src/workspaces/commands/mod.rsnew file mode 100644index 00000000..2c0bec2b--- /dev/null+++ b/packages/wm/src/workspaces/commands/mod.rs@@ -0,0 +1,3 @@+mod activate_workspace;++pub use activate_workspace::*;diff --git a/packages/wm/src/workspaces/mod.rs b/packages/wm/src/workspaces/mod.rsindex c1f22fe9..8a95f077 100644--- a/packages/wm/src/workspaces/mod.rs+++ b/packages/wm/src/workspaces/mod.rs@@ -1,3 +1,4 @@+pub mod commands;mod workspace;pub use workspace::*;