Skip to content

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

feat: fully implement redraw command; fix container iterators

Lars Berger4dc0df73955d
diff --git a/packages/wm/src/common/platform/native_window.rs b/packages/wm/src/common/platform/native_window.rs
index 4577c4f1..78e36ee2 100644
--- a/packages/wm/src/common/platform/native_window.rs
+++ b/packages/wm/src/common/platform/native_window.rs
@@ -17,10 +17,13 @@ use windows::{
WindowsAndMessaging::{
EnumWindows, GetClassNameW, GetWindow, GetWindowLongPtrW,
GetWindowPlacement, GetWindowTextW, GetWindowThreadProcessId,
- IsWindowVisible, SetForegroundWindow, ShowWindowAsync,
- GWL_EXSTYLE, GWL_STYLE, GW_OWNER, SW_RESTORE, WINDOWPLACEMENT,
- WINDOW_EX_STYLE, WINDOW_STYLE, WS_CAPTION, WS_CHILD,
- WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,
+ IsWindowVisible, SetForegroundWindow, SetWindowPos,
+ ShowWindowAsync, GWL_EXSTYLE, GWL_STYLE, GW_OWNER, HWND_NOTOPMOST,
+ HWND_TOPMOST, SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED,
+ SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_NOCOPYBITS, SWP_NOMOVE,
+ SWP_NOSENDCHANGING, SWP_NOSIZE, SWP_SHOWWINDOW, SW_RESTORE,
+ WINDOWPLACEMENT, WINDOW_EX_STYLE, WINDOW_STYLE, WS_CAPTION,
+ WS_CHILD, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,
},
},
},
@@ -30,7 +33,7 @@ use crate::common::Rect;
pub type WindowHandle = HWND;
-#[derive(Debug)]
+#[derive(Clone, Debug)]
pub struct NativeWindow {
pub handle: WindowHandle,
title: Arc<RwLock<Option<String>>>,
@@ -246,7 +249,47 @@ impl NativeWindow {
Ok(())
}
- pub fn set_position(&self) -> anyhow::Result<()> {
+ pub fn set_position(
+ &self,
+ args: &SetPositionArgs,
+ ) -> anyhow::Result<()> {
+ let mut swp_flags = SWP_FRAMECHANGED
+ | SWP_NOACTIVATE
+ | SWP_NOCOPYBITS
+ | SWP_NOSENDCHANGING
+ | SWP_ASYNCWINDOWPOS;
+
+ // Whether to show or hide the window.
+ if args.visible {
+ swp_flags |= SWP_SHOWWINDOW;
+ } else {
+ swp_flags |= SWP_HIDEWINDOW;
+ };
+
+ // Whether to actually move and resize the window.
+ if !args.move_and_resize {
+ swp_flags |= SWP_NOSIZE;
+ swp_flags |= SWP_NOMOVE;
+ }
+
+ // Whether the window should be shown above all other windows.
+ let z_order = match args.show_on_top {
+ true => HWND_TOPMOST,
+ false => HWND_NOTOPMOST,
+ };
+
+ unsafe {
+ SetWindowPos(
+ args.window_handle,
+ z_order,
+ args.rect.x(),
+ args.rect.y(),
+ args.rect.width(),
+ args.rect.height(),
+ swp_flags,
+ )
+ }?;
+
Ok(())
}
}
@@ -259,6 +302,15 @@ impl PartialEq for NativeWindow {
impl Eq for NativeWindow {}
+/// Arguments to pass to `NativeWindow::set_position`.
+pub struct SetPositionArgs {
+ pub window_handle: WindowHandle,
+ pub visible: bool,
+ pub show_on_top: bool,
+ pub move_and_resize: bool,
+ pub rect: Rect,
+}
+
pub fn available_windows() -> anyhow::Result<Vec<NativeWindow>> {
available_window_handles()?
.into_iter()
@@ -279,12 +331,6 @@ pub fn available_window_handles() -> anyhow::Result<Vec<WindowHandle>> {
Ok(handles)
}
-pub struct SetPositionArgs {
- show: bool,
- show_on_top: bool,
- rect: Rect,
-}
-
extern "system" fn available_window_handles_proc(
handle: HWND,
data: LPARAM,
diff --git a/packages/wm/src/common/rect.rs b/packages/wm/src/common/rect.rs
index 49eae43a..36b8c277 100644
--- a/packages/wm/src/common/rect.rs
+++ b/packages/wm/src/common/rect.rs
@@ -1,3 +1,5 @@
+use super::RectDelta;
+
#[derive(Debug, Clone)]
pub struct Rect {
/// X-coordinate of the left edge of the rectangle.
@@ -69,4 +71,13 @@ impl Rect {
self.top + (self.height() / 2),
)
}
+
+ pub fn apply_delta(&self, delta: RectDelta) -> Self {
+ Self::from_ltrb(
+ self.left - delta.left.to_pixels(self.width()),
+ self.top - delta.top.to_pixels(self.height()),
+ self.right + delta.right.to_pixels(self.width()),
+ self.bottom + delta.bottom.to_pixels(self.height()),
+ )
+ }
}
diff --git a/packages/wm/src/common/units.rs b/packages/wm/src/common/units.rs
index 237161b8..98e5d58f 100644
--- a/packages/wm/src/common/units.rs
+++ b/packages/wm/src/common/units.rs
@@ -17,6 +17,13 @@ pub enum LengthUnit {
}
impl LengthValue {
+ pub fn new_px(amount: f32) -> Self {
+ Self {
+ amount,
+ unit: LengthUnit::Pixel,
+ }
+ }
+
/// Parses a string containing a number followed by a unit (`px`, `%`).
///
/// Example:
diff --git a/packages/wm/src/containers/commands/redraw_command.rs b/packages/wm/src/containers/commands/redraw_command.rs
index c5910876..9668fcc5 100644
--- a/packages/wm/src/containers/commands/redraw_command.rs
+++ b/packages/wm/src/containers/commands/redraw_command.rs
@@ -1,16 +1,17 @@
-use std::ptr::null_mut;
+use anyhow::Context;
use crate::{
- common::DisplayState,
+ common::{platform::SetPositionArgs, DisplayState},
+ containers::{
+ traits::{CommonBehavior, PositionBehavior},
+ WindowContainer,
+ },
user_config::UserConfig,
windows::{traits::WindowBehavior, WindowState},
wm_state::WmState,
};
-pub struct RedrawCommand;
-
pub fn redraw_handler(
- command: RedrawCommand,
state: &mut WmState,
user_config: UserConfig,
) -> anyhow::Result<&mut WmState> {
@@ -20,9 +21,10 @@ pub fn redraw_handler(
let windows_to_restore = windows_to_redraw
.iter()
.filter(|window| match window.state() {
- WindowState::Maximized => window.native().is_maximized(),
- WindowState::Minimized => window.native().is_minimized(),
- _ => false,
+ WindowState::Minimized | WindowState::Maximized => false,
+ _ => {
+ window.native().is_maximized() || window.native().is_minimized()
+ }
})
.collect::<Vec<_>>();
@@ -32,13 +34,10 @@ pub fn redraw_handler(
let _ = window.native().restore();
}
- // Get z-order to set for floating windows.
- let should_show_on_top = user_config.value.general.show_floating_on_top;
-
for window in &windows_to_redraw {
let workspace = window
.ancestors()
- .find_map(|ancestor| ancestor.as_workspace())
+ .find_map(|ancestor| ancestor.as_workspace().cloned())
.context("Window has no workspace.")?;
// Transition display state depending on whether window will be
@@ -55,14 +54,19 @@ pub fn redraw_handler(
},
);
- let position = get_redraw_position(&window);
- window.native().set_position(position);
+ let position_args = get_position_args(
+ &window,
+ user_config.value.general.show_floating_on_top,
+ );
+
+ let _ = window.native().set_position(&position_args);
- // When there's a mismatch between the DPI of the monitor and the window,
- // `SetWindowPos` might size the window incorrectly. By calling `SetWindowPos`
- // twice, inconsistencies after the first move are resolved.
+ // When there's a mismatch between the DPI of the monitor and the
+ // window, the window might be sized incorrectly after the first move.
+ // If we set the position twice, inconsistencies after the first move
+ // are resolved.
if window.has_pending_dpi_adjustment() {
- window.native().set_position(position);
+ let _ = window.native().set_position(&position_args);
window.set_has_pending_dpi_adjustment(false);
}
}
@@ -71,93 +75,33 @@ pub fn redraw_handler(
Ok(state)
}
-fn get_redraw_position(window: &Window) {
+fn get_position_args(
+ window: &WindowContainer,
+ show_floating_on_top: bool,
+) -> SetPositionArgs {
+ // Avoid adjusting the borders of non-tiling windows. Otherwise the
+ // window will increase in size from its original placement.
+ let rect = match window.state() {
+ WindowState::Tiling => {
+ window.to_rect().apply_delta(window.border_delta())
+ }
+ _ => window.to_rect(),
+ };
+
SetPositionArgs {
- show: match window.display_state() {
+ window_handle: window.native().handle,
+ visible: match window.display_state() {
DisplayState::Showing | DisplayState::Shown => true,
_ => false,
},
- }
-}
-
-fn set_window_position(&self, window: &Window) {
- let default_flags = SetWindowPosFlags::FRAME_CHANGED
- | SetWindowPosFlags::NO_ACTIVATE
- | SetWindowPosFlags::NO_COPY_BITS
- | SetWindowPosFlags::NO_SEND_CHANGING
- | SetWindowPosFlags::ASYNC_WINDOW_POS;
-
- let workspace = window
- .ancestors()
- .find_map(|ancestor| ancestor.as_workspace())
- .context("Window has no workspace.")?;
-
- let is_workspace_displayed = workspace.is_displayed();
-
- // Show or hide the window depending on whether the workspace is displayed.
- let default_flags = if is_workspace_displayed {
- default_flags | SetWindowPosFlags::SHOW_WINDOW
- } else {
- default_flags | SetWindowPosFlags::HIDE_WINDOW
- };
-
- let default_flags = if window.is::<MaximizedWindow>() {
- default_flags | SetWindowPosFlags::NO_SIZE | SetWindowPosFlags::NO_MOVE
- } else {
- default_flags
- };
-
- // Transition display state depending on whether window will be shown/hidden.
- window.set_display_state(
- match (window.display_state(), is_workspace_displayed) {
- (DisplayState::Hidden | DisplayState::Hiding, true) => {
- DisplayState::Showing
- }
- (DisplayState::Shown | DisplayState::Showing, false) => {
- DisplayState::Hiding
- }
- _ => window.display_state(),
+ show_on_top: match window.state() {
+ WindowState::Floating => show_floating_on_top,
+ _ => false,
},
- );
-
- if window.is::<TilingWindow>() {
- set_window_pos(
- window.handle(),
- null_mut(),
- window.x() - window.border_delta().left,
- window.y() - window.border_delta().top,
- window.width()
- + window.border_delta().left
- + window.border_delta().right,
- window.height()
- + window.border_delta().top
- + window.border_delta().bottom,
- default_flags,
- );
- return;
+ move_and_resize: match window.state() {
+ WindowState::Floating | WindowState::Tiling => true,
+ _ => false,
+ },
+ rect,
}
-
- // Get z-order to set for floating windows.
- let should_show_on_top = self
- .user_config_service
- .general_config()
- .show_floating_on_top;
-
- let floating_z_order = if should_show_on_top {
- ZOrderFlags::TopMost
- } else {
- ZOrderFlags::NoTopMost
- };
-
- // Avoid adjusting the borders of floating windows. Otherwise the window will
- // increase in size from its original placement.
- set_window_pos(
- window.handle(),
- floating_z_order as _,
- window.x(),
- window.y(),
- window.width(),
- window.height(),
- default_flags,
- );
}
diff --git a/packages/wm/src/containers/traits/common_behavior.rs b/packages/wm/src/containers/traits/common_behavior.rs
index 2ee92163..8f5f46ab 100644
--- a/packages/wm/src/containers/traits/common_behavior.rs
+++ b/packages/wm/src/containers/traits/common_behavior.rs
@@ -34,22 +34,30 @@ pub trait CommonBehavior {
fn borrow_children_mut(&self) -> RefMut<'_, VecDeque<Container>>;
- /// Returns a reference to the parent container, unless this container is
- /// the root.
- ///
- /// # Panics
- ///
- /// Panics if the container is currently mutably borrowed.
+ /// Gets the parent container, unless this container is the root.
fn parent(&self) -> Option<TilingContainer> {
self.borrow_parent().clone()
}
+ /// Direct children of this container.
fn children(&self) -> VecDeque<Container> {
self.borrow_children().clone()
}
+ /// Whether this container is detached from the tree (ie. it does not
+ /// have a parent).
fn is_detached(&self) -> bool {
- self.parent().is_none()
+ self.borrow_parent().as_ref().is_none()
+ }
+
+ /// Index of this container amongst its siblings.
+ fn index(&self) -> Option<usize> {
+ self.borrow_parent().as_ref().and_then(|parent| {
+ parent
+ .children()
+ .iter()
+ .position(|child| child.id() == self.id())
+ })
}
fn descendants(&self) -> Descendants {
@@ -64,11 +72,19 @@ pub trait CommonBehavior {
Descendants { stack }
}
- fn siblings(&self) -> Siblings {
- Siblings(Some(self.as_container()))
+ fn siblings(&self) -> Box<dyn Iterator<Item = Container> + '_> {
+ Box::new(
+ self
+ .parent()
+ .into_iter()
+ .flat_map(|parent| parent.children())
+ .filter(move |sibling| sibling.id() != self.id()),
+ )
}
- fn tiling_siblings(&self) -> Box<dyn Iterator<Item = TilingContainer>> {
+ fn tiling_siblings(
+ &self,
+ ) -> Box<dyn Iterator<Item = TilingContainer> + '_> {
Box::new(
self
.siblings()
@@ -77,77 +93,60 @@ pub trait CommonBehavior {
}
fn ancestors(&self) -> Ancestors {
- Ancestors(self.parent())
+ Ancestors {
+ start: self.parent().map(|c| c.into()),
+ }
}
- fn self_and_ancestors(&self) -> SelfAndAncestors {
- SelfAndAncestors(Some(self.as_container()))
+ fn self_and_ancestors(&self) -> Ancestors {
+ Ancestors {
+ start: Some(self.as_container()),
+ }
}
}
-/// Helper macro for implementing iterators that return `Option<Container>`.
-#[macro_export]
-macro_rules! impl_container_iterator {
- ($name: ident, $next: expr) => {
- impl Iterator for $name {
- type Item = Container;
-
- fn next(&mut self) -> Option<Container> {
- match self.0.take() {
- Some(container) => {
- self.0 = $next(&container);
- Some(container)
- }
- None => None,
- }
- }
- }
- };
+/// An iterator over ancestors of a given container.
+pub struct Ancestors {
+ start: Option<Container>,
}
-/// Helper macro for implementing iterators that return `Option<TilingContainer>`.
-#[macro_export]
-macro_rules! impl_tiling_container_iterator {
- ($name: ident, $next: expr) => {
- impl Iterator for $name {
- type Item = TilingContainer;
-
- fn next(&mut self) -> Option<TilingContainer> {
- match self.0.take() {
- Some(container) => {
- self.0 = $next(&container);
- Some(container)
- }
- None => None,
- }
- }
- }
- };
-}
+impl Iterator for Ancestors {
+ type Item = Container;
-/// An iterator over ancestors of a given container.
-pub struct Ancestors(Option<TilingContainer>);
-impl_tiling_container_iterator!(
- Ancestors,
- |container: &TilingContainer| { container.parent() }
-);
-
-/// An iterator over itself and ancestors of a given container.
-pub struct SelfAndAncestors(Option<Container>);
-impl_container_iterator!(SelfAndAncestors, |container: &Container| {
- container.parent().map(|parent| parent.into())
-});
+ fn next(&mut self) -> Option<Container> {
+ self.start.take().map(|container| {
+ self.start = container.parent().map(|c| c.into());
+ container
+ })
+ }
+}
/// An iterator over siblings of a given container.
-pub struct Siblings(Option<Container>);
-impl_container_iterator!(Siblings, |container: &Container| {
- container.parent().and_then(|parent| {
- parent
- .children()
- .into_iter()
- .find(|child| child != container)
- })
-});
+// pub struct Siblings {
+// ignore: Container,
+// current: Option<Container>,
+// }
+
+// impl Iterator for Siblings {
+// type Item = Container;
+
+// fn next(&mut self) -> Option<Container> {
+// self.current.take().map(|container| {
+// self.ignore = container.parent().map(|c| c.into());
+// container
+// })
+// }
+// }
+
+// impl_container_iterator!(Siblings, |container: &Container| {
+// println!("siblings: {:?}", container.id());
+// container.parent().and_then(|parent| {
+// parent
+// .children()
+// .into_iter()
+// .find(|child| child != container)
+// })
+// });
/// An iterator over descendants of a given container.
pub struct Descendants {
diff --git a/packages/wm/src/containers/traits/position_behavior.rs b/packages/wm/src/containers/traits/position_behavior.rs
index 45e22e4f..e87355ed 100644
--- a/packages/wm/src/containers/traits/position_behavior.rs
+++ b/packages/wm/src/containers/traits/position_behavior.rs
@@ -1,13 +1,23 @@
use enum_dispatch::enum_dispatch;
-use crate::containers::{Container, TilingContainer, WindowContainer};
+use crate::{
+ common::Rect,
+ containers::{Container, TilingContainer, WindowContainer},
+};
#[enum_dispatch]
pub trait PositionBehavior {
fn width(&self) -> i32;
+
fn height(&self) -> i32;
+
fn x(&self) -> i32;
+
fn y(&self) -> i32;
+
+ fn to_rect(&self) -> Rect {
+ Rect::from_xy(self.x(), self.y(), self.width(), self.height())
+ }
}
/// Implements the `PositionBehavior` trait for tiling containers that can
diff --git a/packages/wm/src/containers/traits/tiling_behavior.rs b/packages/wm/src/containers/traits/tiling_behavior.rs
index 2e2281e8..dc425a1b 100644
--- a/packages/wm/src/containers/traits/tiling_behavior.rs
+++ b/packages/wm/src/containers/traits/tiling_behavior.rs
@@ -1,6 +1,6 @@
use enum_dispatch::enum_dispatch;
-use crate::containers::{Container, TilingContainer, WindowContainer};
+use crate::containers::{Container, TilingContainer};
use super::CommonBehavior;
@@ -14,6 +14,10 @@ pub trait TilingBehavior: CommonBehavior {
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()
@@ -29,7 +33,8 @@ pub trait TilingBehavior: CommonBehavior {
return;
}
- // Set initial size percentage to 0, and then size up the container to `defaultPercent`.
+ // 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);
diff --git a/packages/wm/src/windows/non_tiling_window.rs b/packages/wm/src/windows/non_tiling_window.rs
index d0814e7a..3e35b5b8 100644
--- a/packages/wm/src/windows/non_tiling_window.rs
+++ b/packages/wm/src/windows/non_tiling_window.rs
@@ -7,7 +7,9 @@ use std::{
use uuid::Uuid;
use crate::{
- common::{platform::NativeWindow, DisplayState, Rect},
+ common::{
+ platform::NativeWindow, DisplayState, LengthValue, Rect, RectDelta,
+ },
containers::{
traits::{CommonBehavior, PositionBehavior},
Container, ContainerType, TilingContainer,
@@ -29,6 +31,7 @@ struct NonTilingWindowInner {
position: Rect,
state: WindowState,
display_state: DisplayState,
+ border_delta: RectDelta,
has_pending_dpi_adjustment: bool,
}
@@ -42,6 +45,12 @@ impl NonTilingWindow {
position: Rect::from_xy(0, 0, 0, 0),
state,
display_state: DisplayState::Shown,
+ border_delta: RectDelta::new(
+ LengthValue::new_px(0.),
+ LengthValue::new_px(0.),
+ LengthValue::new_px(0.),
+ LengthValue::new_px(0.),
+ ),
has_pending_dpi_adjustment: false,
};
diff --git a/packages/wm/src/windows/tiling_window.rs b/packages/wm/src/windows/tiling_window.rs
index 5dc48066..5e801371 100644
--- a/packages/wm/src/windows/tiling_window.rs
+++ b/packages/wm/src/windows/tiling_window.rs
@@ -7,7 +7,7 @@ use std::{
use uuid::Uuid;
use crate::{
- common::{platform::NativeWindow, DisplayState},
+ common::{platform::NativeWindow, DisplayState, LengthValue, RectDelta},
containers::{
traits::{CommonBehavior, PositionBehavior, TilingBehavior},
Container, ContainerType, TilingContainer,
@@ -30,6 +30,7 @@ struct TilingWindowInner {
native: NativeWindow,
state: WindowState,
display_state: DisplayState,
+ border_delta: RectDelta,
has_pending_dpi_adjustment: bool,
}
@@ -43,6 +44,12 @@ impl TilingWindow {
native: native_window,
state: WindowState::Tiling,
display_state: DisplayState::Shown,
+ border_delta: RectDelta::new(
+ LengthValue::new_px(0.),
+ LengthValue::new_px(0.),
+ LengthValue::new_px(0.),
+ LengthValue::new_px(0.),
+ ),
has_pending_dpi_adjustment: false,
};
diff --git a/packages/wm/src/windows/traits/window_behavior.rs b/packages/wm/src/windows/traits/window_behavior.rs
index 27f31272..557b9de5 100644
--- a/packages/wm/src/windows/traits/window_behavior.rs
+++ b/packages/wm/src/windows/traits/window_behavior.rs
@@ -1,7 +1,7 @@
use enum_dispatch::enum_dispatch;
use crate::{
- common::{platform::NativeWindow, DisplayState},
+ common::{platform::NativeWindow, DisplayState, RectDelta},
containers::WindowContainer,
windows::WindowState,
};
@@ -12,6 +12,8 @@ pub trait WindowBehavior {
fn native(&self) -> NativeWindow;
+ fn border_delta(&self) -> RectDelta;
+
fn display_state(&self) -> DisplayState;
fn set_display_state(&self, display_state: DisplayState) -> ();
@@ -33,19 +35,23 @@ macro_rules! impl_window_behavior {
($struct_name:ident) => {
impl WindowBehavior for $struct_name {
fn state(&self) -> WindowState {
- self.0.borrow().state
+ self.0.borrow().state.clone()
}
fn native(&self) -> NativeWindow {
- self.0.borrow().native
+ self.0.borrow().native.clone()
+ }
+
+ fn border_delta(&self) -> RectDelta {
+ self.0.borrow().border_delta.clone()
}
fn display_state(&self) -> DisplayState {
- self.0.borrow().display_state
+ self.0.borrow().display_state.clone()
}
fn set_display_state(&self, display_state: DisplayState) {
- self.0.borrow().display_state = display_state;
+ self.0.borrow_mut().display_state = display_state;
}
fn has_pending_dpi_adjustment(&self) -> bool {
@@ -56,7 +62,7 @@ macro_rules! impl_window_behavior {
&self,
has_pending_dpi_adjustment: bool,
) {
- self.0.borrow().has_pending_dpi_adjustment =
+ self.0.borrow_mut().has_pending_dpi_adjustment =
has_pending_dpi_adjustment;
}
}
diff --git a/packages/wm/src/workspaces/workspace.rs b/packages/wm/src/workspaces/workspace.rs
index bd72e023..2bac04a7 100644
--- a/packages/wm/src/workspaces/workspace.rs
+++ b/packages/wm/src/workspaces/workspace.rs
@@ -43,10 +43,16 @@ impl Workspace {
Self(Rc::new(RefCell::new(workspace)))
}
+ /// Underlying config for the workspace.
pub fn config(&self) -> WorkspaceConfig {
self.0.borrow().config.clone()
}
+ pub fn is_displayed(&self) -> bool {
+ // TODO
+ true
+ }
+
fn outer_gaps(&self) -> Ref<'_, RectDelta> {
Ref::map(self.0.borrow(), |c| &c.outer_gaps)
}