GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: add fn for moving container within tree; fix to `set_focused_descendant`
Lars Berger938106b5e549
diff --git a/packages/wm/src/common/events/handle_window_focused.rs b/packages/wm/src/common/events/handle_window_focused.rsindex ce429368..45690c52 100644--- a/packages/wm/src/common/events/handle_window_focused.rs+++ b/packages/wm/src/common/events/handle_window_focused.rs@@ -29,7 +29,6 @@ pub fn handle_window_focused(// Focus is already set to the WM's focused container.if state.focused_container() == Some(window.clone().into()) {- info!("already focused {:?}", state.root_container.clone());return Ok(());}@@ -54,13 +53,13 @@ pub fn handle_window_focused(// workspace, switch focus to Discord's workspace.if window.clone().display_state() == DisplayState::Hidden {// TODO: Log window details.- info!("Focusing off-screen window");+ info!("Focusing off-screen window.");// TODO: Focus the workspace of the hidden window.return Ok(());}// Update the WM's focus state.- set_focused_descendant(window.clone().into(), None, state);+ set_focused_descendant(window.clone().into(), None);state.emit_event(WmEvent::FocusChanged {focused_container: Into::<Container>::into(window).clone(),diff --git a/packages/wm/src/common/mod.rs b/packages/wm/src/common/mod.rsindex 6564a23c..a859780a 100644--- a/packages/wm/src/common/mod.rs+++ b/packages/wm/src/common/mod.rs@@ -9,6 +9,7 @@ mod rect;mod rect_delta;mod tiling_direction;mod units;+mod vec_deque_ext;pub use direction::*;pub use display_state::*;@@ -18,3 +19,4 @@ pub use rect::*;pub use rect_delta::*;pub use tiling_direction::*;pub use units::*;+pub use vec_deque_ext::*;diff --git a/packages/wm/src/common/vec_deque_ext.rs b/packages/wm/src/common/vec_deque_ext.rsnew file mode 100644index 00000000..57d32b4b--- /dev/null+++ b/packages/wm/src/common/vec_deque_ext.rs@@ -0,0 +1,23 @@+use std::collections::VecDeque;++pub trait VecDequeExt<T>+where+ T: PartialEq,+{+ /// Shifts a value to a specified index in a `VecDeque`.+ ///+ /// Inserts at index if value doesn't already exist in the `VecDeque`.+ fn shift_to_index(&mut self, target_index: usize, item: T);+}++impl<T> VecDequeExt<T> for VecDeque<T>+where+ T: PartialEq,+{+ fn shift_to_index(&mut self, target_index: usize, item: T) {+ if let Some(index) = self.iter().position(|x| x == &item) {+ self.remove(index);+ self.insert(target_index, item);+ }+ }+}diff --git a/packages/wm/src/containers/commands/mod.rs b/packages/wm/src/containers/commands/mod.rsindex 6ae306ca..7e1500a1 100644--- a/packages/wm/src/containers/commands/mod.rs+++ b/packages/wm/src/containers/commands/mod.rs@@ -1,18 +1,20 @@mod attach_container;mod center_cursor_on_container;-mod exec_process;mod detach_container;+mod exec_process;mod flatten_split_container;+mod move_container_within_tree;mod redraw;mod resize_tiling_container;mod set_active_window_border;mod set_focused_descendant;pub use attach_container::*;-pub use detach_container::*;pub use center_cursor_on_container::*;+pub use detach_container::*;pub use exec_process::*;pub use flatten_split_container::*;+pub use move_container_within_tree::*;pub use redraw::*;pub use resize_tiling_container::*;pub use set_active_window_border::*;diff --git a/packages/wm/src/containers/commands/move_container_within_tree.rs b/packages/wm/src/containers/commands/move_container_within_tree.rsnew file mode 100644index 00000000..5fbf511b--- /dev/null+++ b/packages/wm/src/containers/commands/move_container_within_tree.rs@@ -0,0 +1,167 @@+use anyhow::Context;++use crate::{+ common::VecDequeExt,+ containers::{traits::CommonGetters, Container},+};++use super::{attach_container, detach_container, set_focused_descendant};++pub fn move_container_within_tree(+ container_to_move: Container,+ target_parent: Container,+ target_index: usize,+) -> anyhow::Result<()> {+ // Get lowest common ancestor (LCA) between `container_to_move` and+ // `target_parent`. This could be the `target_parent` itself.+ let lowest_common_ancestor =+ lowest_common_ancestor(&container_to_move, &target_parent)+ .context("No common ancestor between containers.")?;++ // Handle case where target parent is the LCA. For example, when swapping+ // sibling containers or moving a container to a direct ancestor.+ if target_parent == lowest_common_ancestor {+ return move_to_lowest_common_ancestor(+ container_to_move,+ lowest_common_ancestor,+ target_index,+ );+ }++ // Get ancestor of `container_to_move` that is a direct child of the LCA.+ // This could be the `container_to_move` itself.+ let container_to_move_ancestor = container_to_move+ .self_and_ancestors()+ .find(|ancestor| {+ ancestor.parent() == Some(lowest_common_ancestor.clone())+ })+ .context("TODO.")?;++ // Likewise, get ancestor of `target_parent` that is a direct child of+ // the LCA.+ let target_parent_ancestor = target_parent+ .self_and_ancestors()+ .find(|ancestor| {+ ancestor.parent() == Some(lowest_common_ancestor.clone())+ })+ .context("TODO.")?;++ // Get whether the container is the focused descendant in its original+ // subtree.+ let is_focused_descendant = container_to_move+ == container_to_move_ancestor+ || container_to_move_ancestor+ .last_focused_descendant()+ .context("TODO.")?+ .self_and_ancestors()+ .any(|ancestor| ancestor == container_to_move);++ // Get whether the ancestor of `container_to_move` appears before+ // `target_parent`'s ancestor in the child focus order of the LCA.+ let original_focus_index = container_to_move_ancestor.focus_index();+ let is_subtree_focused =+ original_focus_index < target_parent_ancestor.focus_index();++ detach_container(container_to_move.clone())?;+ attach_container(+ &container_to_move.clone(),+ &target_parent.clone(),+ Some(target_index),+ )?;++ // Set `container_to_move` as focused descendant within target subtree if+ // its original subtree had focus more recently (even if the container is+ // not the last focused within that subtree).+ if is_subtree_focused {+ set_focused_descendant(+ container_to_move,+ Some(target_parent_ancestor.clone()),+ );+ }++ // If the focused descendant is moved to the targets subtree, then the+ // target's ancestor should be placed before the original ancestor in+ // LCA's child focus order.+ if is_focused_descendant && is_subtree_focused {+ lowest_common_ancestor+ .borrow_child_focus_order_mut()+ .shift_to_index(original_focus_index, target_parent_ancestor.id());+ }++ Ok(())+}++fn move_to_lowest_common_ancestor(+ container_to_move: Container,+ lowest_common_ancestor: Container,+ target_index: usize,+) -> anyhow::Result<()> {+ // Keep reference to focus index of container's ancestor in LCA's child+ // focus order.+ let original_focus_index = container_to_move+ .self_and_ancestors()+ .find(|ancestor| {+ ancestor.parent() == Some(lowest_common_ancestor.clone())+ })+ .context("TODO.")?+ .focus_index();++ // Keep reference to container index and number of children that LCA has.+ let original_index = container_to_move.index();+ let original_lca_child_count = lowest_common_ancestor.children().len();++ detach_container(container_to_move.clone())?;++ let new_lca_child_count = lowest_common_ancestor.children().len();+ let should_adjust_target_index = original_lca_child_count+ > new_lca_child_count+ && original_index < target_index;++ // Adjust for when target index changes on detach of container. For+ // example, when shifting a top-level container to the right in a+ // workspace.+ let adjusted_target_index = if should_adjust_target_index {+ target_index - 1+ } else {+ target_index+ };++ attach_container(+ &container_to_move.clone(),+ &lowest_common_ancestor.clone(),+ Some(adjusted_target_index),+ )?;++ lowest_common_ancestor+ .borrow_child_focus_order_mut()+ .shift_to_index(original_focus_index, container_to_move.id());++ Ok(())+}++/// Gets the lowest container in the tree that has both `container_a` and+/// `container_b` as descendants.+pub fn lowest_common_ancestor(+ container_a: &Container,+ container_b: &Container,+) -> Option<Container> {+ let mut ancestor_a = Some(container_a.clone());++ // Traverse upwards from container A.+ while let Some(current_ancestor_a) = ancestor_a {+ let mut ancestor_b = Some(container_b.clone());++ // Traverse upwards from container B.+ while let Some(current_ancestor_b) = ancestor_b {+ if current_ancestor_a == current_ancestor_b {+ return Some(current_ancestor_a);+ }++ ancestor_b = current_ancestor_b.parent();+ }++ ancestor_a = current_ancestor_a.parent();+ }++ None+}diff --git a/packages/wm/src/containers/commands/set_focused_descendant.rs b/packages/wm/src/containers/commands/set_focused_descendant.rsindex 7b26f69d..630fd2c8 100644--- a/packages/wm/src/containers/commands/set_focused_descendant.rs+++ b/packages/wm/src/containers/commands/set_focused_descendant.rs@@ -1,34 +1,29 @@use crate::{+ common::VecDequeExt,containers::{traits::CommonGetters, Container},- wm_state::WmState,};+/// Set a given container as the focused container up to and including the+/// end ancestor.pub fn set_focused_descendant(focused_descendant: Container,end_ancestor: Option<Container>,- state: &WmState,) {- let end_ancestor =- end_ancestor.unwrap_or_else(|| state.root_container.clone().into());-- // Traverse upwards, setting the container as the last focused up to and- // including the end ancestor.let mut target = focused_descendant;+ // Traverse upwards, shifting the container's ancestors to the front in+ // their focus order.while let Some(parent) = target.parent() {- {- let mut child_focus_order = parent.borrow_child_focus_order_mut();-- if let Some(index) =- child_focus_order.iter().position(|id| id == &target.id())- {- child_focus_order.remove(index);- child_focus_order.push_front(target.id());- }- }+ parent+ .borrow_child_focus_order_mut()+ .shift_to_index(0, target.id());// Exit if we've reached the end ancestor.- if target.id() == end_ancestor.id() {+ if end_ancestor+ .as_ref()+ .map(|end_ancestor| target.id() == end_ancestor.id())+ .unwrap_or(false)+ {break;}diff --git a/packages/wm/src/windows/commands/manage_window.rs b/packages/wm/src/windows/commands/manage_window.rsindex dfae3dae..cfc526fa 100644--- a/packages/wm/src/windows/commands/manage_window.rs+++ b/packages/wm/src/windows/commands/manage_window.rs@@ -31,7 +31,7 @@ pub fn manage_window(// Set the newly added window as focus descendant. This means the window// rules will be run as if the window is focused.- set_focused_descendant(window.clone().into(), None, &state);+ set_focused_descendant(window.clone().into(), None);// run_with_subject_container(window_rule_commands, window.clone());// // Update window in case the reference changes.@@ -128,6 +128,7 @@ fn create_window(native_window,window_state,prev_window_state,+ None,floating_placement,).into(),diff --git a/packages/wm/src/windows/non_tiling_window.rs b/packages/wm/src/windows/non_tiling_window.rsindex 216f517f..7636ee1f 100644--- a/packages/wm/src/windows/non_tiling_window.rs+++ b/packages/wm/src/windows/non_tiling_window.rs@@ -19,7 +19,7 @@ use crate::{impl_common_getters, impl_window_getters,};-use super::{traits::WindowGetters, WindowState};+use super::{traits::WindowGetters, TilingWindow, WindowState};#[derive(Clone)]pub struct NonTilingWindow(Rc<RefCell<NonTilingWindowInner>>);@@ -32,6 +32,7 @@ struct NonTilingWindowInner {native: NativeWindow,state: WindowState,prev_state: Option<WindowState>,+ insertion_reference: Option<(Container, usize)>,display_state: DisplayState,border_delta: RectDelta,has_pending_dpi_adjustment: bool,@@ -40,9 +41,10 @@ struct NonTilingWindowInner {impl NonTilingWindow {pub fn new(- native_window: NativeWindow,+ native: NativeWindow,state: WindowState,prev_state: Option<WindowState>,+ insertion_reference: Option<(Container, usize)>,floating_placement: Rect,) -> Self {let window = NonTilingWindowInner {@@ -50,9 +52,10 @@ impl NonTilingWindow {parent: None,children: VecDeque::new(),child_focus_order: VecDeque::new(),- native: native_window,+ native,state,prev_state,+ insertion_reference,display_state: DisplayState::Shown,border_delta: RectDelta::new(LengthValue::new_px(0.),@@ -67,6 +70,10 @@ impl NonTilingWindow {Self(Rc::new(RefCell::new(window)))}+ pub fn to_tiling(&self, inner_gap: LengthValue) -> TilingWindow {+ TilingWindow::new(self.native(), self.floating_placement(), inner_gap)+ }+pub fn to_dto(&self) -> anyhow::Result<NonTilingWindowDto> {Ok(NonTilingWindowDto {id: self.id(),diff --git a/packages/wm/src/windows/tiling_window.rs b/packages/wm/src/windows/tiling_window.rsindex cefadfca..500413d7 100644--- a/packages/wm/src/windows/tiling_window.rs+++ b/packages/wm/src/windows/tiling_window.rs@@ -25,7 +25,7 @@ use crate::{impl_tiling_size_getters, impl_window_getters,};-use super::{traits::WindowGetters, WindowState};+use super::{traits::WindowGetters, NonTilingWindow, WindowState};#[derive(Clone)]pub struct TilingWindow(Rc<RefCell<TilingWindowInner>>);@@ -47,7 +47,7 @@ struct TilingWindowInner {impl TilingWindow {pub fn new(- native_window: NativeWindow,+ native: NativeWindow,floating_placement: Rect,inner_gap: LengthValue,) -> Self {@@ -57,7 +57,7 @@ impl TilingWindow {children: VecDeque::new(),child_focus_order: VecDeque::new(),tiling_size: 1.0,- native: native_window,+ native,state: WindowState::Tiling,display_state: DisplayState::Shown,border_delta: RectDelta::new(@@ -78,6 +78,16 @@ impl TilingWindow {self.0.borrow().inner_gap.clone()}+ pub fn to_non_tiling(&self, state: WindowState) -> NonTilingWindow {+ NonTilingWindow::new(+ self.native(),+ state,+ Some(WindowState::Tiling),+ None,+ self.floating_placement(),+ )+ }+pub fn to_dto(&self) -> anyhow::Result<TilingWindowDto> {Ok(TilingWindowDto {id: self.id(),diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rsindex d1400a7c..4077cade 100644--- a/packages/wm/src/wm.rs+++ b/packages/wm/src/wm.rs@@ -154,7 +154,11 @@ impl WindowManager {InvokeCommand::WmDisableBindingMode { name } => todo!(),InvokeCommand::WmExit => todo!(),InvokeCommand::WmEnableBindingMode { name } => todo!(),- InvokeCommand::WmRedraw => redraw(state.deref_mut(), &config),+ InvokeCommand::WmRedraw => {+ let state = state.deref_mut();+ state.add_container_to_redraw(state.root_container.clone().into());+ redraw(state, &config)+ }InvokeCommand::WmReloadConfig => todo!(),InvokeCommand::WmToggleFocusMode => todo!(),}diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rsindex 85e5cb2d..c175aa6c 100644--- a/packages/wm/src/wm_state.rs+++ b/packages/wm/src/wm_state.rs@@ -106,7 +106,7 @@ impl WmState {.or(self.workspaces().pop().map(|c| c.into())).context("Failed to get container to focus.")?;- set_focused_descendant(container_to_focus, None, self);+ set_focused_descendant(container_to_focus, None);self.has_pending_focus_sync = true;redraw(self, config)?;