Skip to content

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

feat: add `child_focus_order` and focus-related getters; add `sync_native_focus` and `set_focused_descendant` commands

Lars Berger30c65f068096
diff --git a/packages/wm/src/app_command.rs b/packages/wm/src/app_command.rs
index d7a8c2fc..6c8f5071 100644
--- a/packages/wm/src/app_command.rs
+++ b/packages/wm/src/app_command.rs
@@ -101,15 +101,8 @@ pub enum QueryCommand {
#[derive(Clone, Debug, Parser)]
#[clap(rename_all = "snake_case")]
pub enum InvokeCommand {
+ AdjustBorders(InvokeAdjustBordersCommand),
Close,
- ChangeBorders(InvokeChangeBordersCommand),
- ChangeTilingDirection {
- #[clap(long = "tiling_dir")]
- tiling_direction: Option<TilingDirection>,
-
- #[clap(long)]
- toggle: bool,
- },
Focus(InvokeFocusCommand),
Ignore,
Move(InvokeMoveCommand),
@@ -120,28 +113,25 @@ pub enum InvokeCommand {
Resize(InvokeResizeCommand),
SetFloating {
#[clap(long)]
- toggle: bool,
- },
- SetFullscreen {
- #[clap(long)]
- toggle: bool,
- },
- SetMaximized {
- #[clap(long)]
- toggle: bool,
- },
- SetMinimized {
- #[clap(long)]
- toggle: bool,
- },
- SetTiling {
- #[clap(long)]
- toggle: bool,
+ centered: bool,
},
+ SetFullscreen,
+ SetMaximized,
+ SetMinimized,
+ SetTiling,
ShellExec {
#[clap(long, num_args = 1..)]
command: Vec<String>,
},
+ ToggleFloating {
+ #[clap(long)]
+ centered: bool,
+ },
+ ToggleFullscreen,
+ ToggleMaximized,
+ ToggleMinimized,
+ ToggleTiling,
+ ToggleTilingDirection,
WmDisableBindingMode {
#[clap(long)]
name: String,
@@ -153,10 +143,7 @@ pub enum InvokeCommand {
},
WmRedraw,
WmReloadConfig,
- WmChangeFocusMode {
- #[clap(long)]
- toggle: bool,
- },
+ WmToggleFocusMode,
}
impl<'de> Deserialize<'de> for InvokeCommand {
@@ -180,12 +167,18 @@ impl<'de> Deserialize<'de> for InvokeCommand {
#[derive(Args, Clone, Debug)]
#[group(required = true, multiple = true)]
-pub struct InvokeChangeBordersCommand {
- #[clap(long)]
- width: Option<LengthValue>,
+pub struct InvokeAdjustBordersCommand {
+ #[clap(long, allow_hyphen_values = true)]
+ top: Option<LengthValue>,
- #[clap(long)]
- height: Option<LengthValue>,
+ #[clap(long, allow_hyphen_values = true)]
+ right: Option<LengthValue>,
+
+ #[clap(long, allow_hyphen_values = true)]
+ bottom: Option<LengthValue>,
+
+ #[clap(long, allow_hyphen_values = true)]
+ left: Option<LengthValue>,
}
#[derive(Args, Clone, Debug)]
@@ -222,9 +215,9 @@ pub struct InvokeMoveCommand {
#[derive(Args, Clone, Debug)]
#[group(required = true, multiple = true)]
pub struct InvokeResizeCommand {
- #[clap(long)]
+ #[clap(long, allow_hyphen_values = true)]
width: Option<LengthValue>,
- #[clap(long)]
+ #[clap(long, allow_hyphen_values = true)]
height: Option<LengthValue>,
}
diff --git a/packages/wm/src/common/commands/mod.rs b/packages/wm/src/common/commands/mod.rs
new file mode 100644
index 00000000..93d10d62
--- /dev/null
+++ b/packages/wm/src/common/commands/mod.rs
@@ -0,0 +1,3 @@
+mod sync_native_focus;
+
+pub use sync_native_focus::*;
diff --git a/packages/wm/src/common/commands/sync_native_focus.rs b/packages/wm/src/common/commands/sync_native_focus.rs
new file mode 100644
index 00000000..d8f47499
--- /dev/null
+++ b/packages/wm/src/common/commands/sync_native_focus.rs
@@ -0,0 +1,39 @@
+use anyhow::Context;
+
+use crate::{
+ common::platform::Platform, containers::Container,
+ windows::traits::WindowBehavior, wm_event::WmEvent, wm_state::WmState,
+};
+
+pub fn sync_native_focus(state: &mut WmState) -> anyhow::Result<()> {
+ if !state.has_pending_focus_sync {
+ return Ok(());
+ }
+
+ // Container that the WM believes should have focus.
+ let focused_container =
+ state.focused_container().context("No focused container.")?;
+
+ let native_window = match focused_container.clone() {
+ Container::TilingWindow(window) => window.native(),
+ Container::NonTilingWindow(window) => window.native(),
+ _ => Platform::desktop_window(),
+ };
+
+ // Set focus to the given window handle. If the container is a normal
+ // window, then this will trigger `EVENT_SYSTEM_FOREGROUND` window event
+ // and its handler.
+ let _ = native_window.set_foreground();
+
+ state.emit_event(WmEvent::NativeFocusSynced {
+ focused_container: focused_container.clone(),
+ });
+
+ state.emit_event(WmEvent::FocusChanged {
+ focused_container: focused_container,
+ });
+
+ state.has_pending_focus_sync = false;
+
+ Ok(())
+}
diff --git a/packages/wm/src/common/mod.rs b/packages/wm/src/common/mod.rs
index 48bb7c6d..7469602e 100644
--- a/packages/wm/src/common/mod.rs
+++ b/packages/wm/src/common/mod.rs
@@ -1,3 +1,4 @@
+pub mod commands;
mod direction;
mod display_state;
mod focus_mode;
diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rs
index 0de37bfe..1529cf17 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, ParsedConfig, UserConfig};
+use crate::user_config::{KeybindingConfig, UserConfig};
use super::{EventWindow, NativeWindow};
@@ -52,10 +52,10 @@ impl EventListener {
}
/// Updates the event listener with the latest user config.
- pub fn update(&mut self, config: &ParsedConfig) {
+ pub fn update(&mut self, config: &UserConfig) {
self.event_window.update(
- config.keybindings.clone(),
- config.general.focus_follows_cursor,
+ config.value.keybindings.clone(),
+ config.value.general.focus_follows_cursor,
);
}
}
diff --git a/packages/wm/src/common/platform/native_monitor.rs b/packages/wm/src/common/platform/native_monitor.rs
index 8fdca2f4..69d969c7 100644
--- a/packages/wm/src/common/platform/native_monitor.rs
+++ b/packages/wm/src/common/platform/native_monitor.rs
@@ -3,6 +3,7 @@ use windows::Win32::{
Graphics::Gdi::{
EnumDisplayMonitors, GetMonitorInfoW, HDC, HMONITOR, MONITORINFOEXW,
},
+ UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},
};
pub type MonitorHandle = HMONITOR;
@@ -18,6 +19,7 @@ pub struct NativeMonitor {
pub height: i32,
pub x: i32,
pub y: i32,
+ pub dpi: f32,
}
impl NativeMonitor {
@@ -28,6 +30,7 @@ impl NativeMonitor {
height: i32,
x: i32,
y: i32,
+ dpi: f32,
) -> Self {
Self {
handle,
@@ -36,6 +39,7 @@ impl NativeMonitor {
height,
x,
y,
+ dpi,
}
}
}
@@ -95,12 +99,11 @@ fn handle_to_monitor(
monitor_info.monitorInfo.cbSize =
std::mem::size_of::<MONITORINFOEXW>() as u32;
- unsafe {
- GetMonitorInfoW(handle, &mut monitor_info as *mut _ as *mut _)
- }
- .ok()?;
+ unsafe { GetMonitorInfoW(handle, &mut monitor_info as *mut _ as _) }
+ .ok()?;
let device_name = String::from_utf16_lossy(&monitor_info.szDevice);
+ let dpi = monitor_dpi(handle)?;
Ok(NativeMonitor::new(
handle,
@@ -111,5 +114,17 @@ fn handle_to_monitor(
- monitor_info.monitorInfo.rcMonitor.top,
monitor_info.monitorInfo.rcMonitor.left,
monitor_info.monitorInfo.rcMonitor.top,
+ dpi,
))
}
+
+fn monitor_dpi(handle: MonitorHandle) -> anyhow::Result<f32> {
+ let mut dpi_x = u32::default();
+ let mut dpi_y = u32::default();
+
+ unsafe {
+ GetDpiForMonitor(handle, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y)
+ }?;
+
+ Ok(dpi_y as f32 / 96.0)
+}
diff --git a/packages/wm/src/common/platform/native_window.rs b/packages/wm/src/common/platform/native_window.rs
index 78e36ee2..43d2ecc6 100644
--- a/packages/wm/src/common/platform/native_window.rs
+++ b/packages/wm/src/common/platform/native_window.rs
@@ -23,7 +23,8 @@ use windows::{
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,
+ WS_CHILD, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_MAXIMIZE,
+ WS_MINIMIZE, WS_THICKFRAME,
},
},
},
@@ -183,15 +184,15 @@ impl NativeWindow {
}
pub fn is_minimized(&self) -> bool {
- todo!()
+ self.has_window_style(WS_MINIMIZE)
}
pub fn is_maximized(&self) -> bool {
- todo!()
+ self.has_window_style(WS_MAXIMIZE)
}
pub fn is_resizable(&self) -> bool {
- todo!()
+ self.has_window_style(WS_THICKFRAME)
}
pub fn is_app_bar(&self) -> bool {
@@ -223,11 +224,11 @@ impl NativeWindow {
Ok(())
}
- fn size(&self) -> (i32, i32) {
+ pub fn placement(&self) -> Rect {
let mut placement = WINDOWPLACEMENT::default();
let _ = unsafe { GetWindowPlacement(self.handle, &mut placement) };
let rect = placement.rcNormalPosition;
- ((rect.right - rect.left), (rect.bottom - rect.top))
+ Rect::from_ltrb(rect.left, rect.top, rect.right, rect.bottom)
}
fn has_window_style(&self, style: WINDOW_STYLE) -> bool {
diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rs
index ca2f2d81..b4dc8eda 100644
--- a/packages/wm/src/common/platform/platform.rs
+++ b/packages/wm/src/common/platform/platform.rs
@@ -1,7 +1,9 @@
use std::sync::Arc;
use tokio::sync::Mutex;
-use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow;
+use windows::Win32::UI::WindowsAndMessaging::{
+ GetDesktopWindow, GetForegroundWindow,
+};
use crate::user_config::UserConfig;
@@ -18,6 +20,11 @@ impl Platform {
NativeWindow::new(handle)
}
+ pub fn desktop_window() -> NativeWindow {
+ let handle = unsafe { GetDesktopWindow() };
+ NativeWindow::new(handle)
+ }
+
pub fn monitors() -> anyhow::Result<Vec<NativeMonitor>> {
native_monitor::available_monitors()
}
diff --git a/packages/wm/src/common/rect.rs b/packages/wm/src/common/rect.rs
index 36b8c277..d4b4b7eb 100644
--- a/packages/wm/src/common/rect.rs
+++ b/packages/wm/src/common/rect.rs
@@ -57,7 +57,7 @@ impl Rect {
Self::from_xy(x, y, self.width(), self.height())
}
- pub fn translate_to_center(&mut self, outer_rect: Rect) -> Self {
+ pub fn translate_to_center(&mut self, outer_rect: &Rect) -> Self {
Self::translate_to_coordinates(
self,
outer_rect.left + (outer_rect.width() / 2) - (self.width() / 2),
@@ -72,7 +72,7 @@ impl Rect {
)
}
- pub fn apply_delta(&self, delta: RectDelta) -> Self {
+ 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()),
diff --git a/packages/wm/src/containers/commands/mod.rs b/packages/wm/src/containers/commands/mod.rs
index f89874d7..001a17f0 100644
--- a/packages/wm/src/containers/commands/mod.rs
+++ b/packages/wm/src/containers/commands/mod.rs
@@ -1,7 +1,9 @@
mod attach_container;
mod redraw;
mod resize_tiling_container;
+mod set_focused_descendant;
pub use attach_container::*;
pub use redraw::*;
pub use resize_tiling_container::*;
+pub use set_focused_descendant::*;
diff --git a/packages/wm/src/containers/commands/redraw.rs b/packages/wm/src/containers/commands/redraw.rs
index 42c605e8..ae890678 100644
--- a/packages/wm/src/containers/commands/redraw.rs
+++ b/packages/wm/src/containers/commands/redraw.rs
@@ -82,7 +82,7 @@ fn get_position_args(
// 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().apply_delta(&window.border_delta())
}
_ => window.to_rect(),
};
diff --git a/packages/wm/src/containers/commands/resize_tiling_container.rs b/packages/wm/src/containers/commands/resize_tiling_container.rs
index 183d3667..a3f687c9 100644
--- a/packages/wm/src/containers/commands/resize_tiling_container.rs
+++ b/packages/wm/src/containers/commands/resize_tiling_container.rs
@@ -22,7 +22,7 @@ pub fn resize_tiling_container(
// Get available size percentage amongst siblings.
let available_size_percentage =
- get_available_size_percentage(&resizable_siblings);
+ available_size_percentage(&resizable_siblings);
let min_resize_delta =
MIN_SIZE_PERCENTAGE - container_to_resize.size_percent();
@@ -41,7 +41,7 @@ pub fn resize_tiling_container(
// 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(
+ let sibling_resize_percentage = sibling_resize_percentage(
&sibling,
sibling_count,
clamped_resize_percentage,
@@ -54,15 +54,13 @@ pub fn resize_tiling_container(
}
}
-fn get_available_size_percentage(
- containers: &Vec<TilingContainer>,
-) -> f32 {
+fn 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(
+fn sibling_resize_percentage(
sibling_to_resize: &TilingContainer,
sibling_count: usize,
size_percentage: f32,
diff --git a/packages/wm/src/containers/commands/set_focused_descendant.rs b/packages/wm/src/containers/commands/set_focused_descendant.rs
new file mode 100644
index 00000000..556a1279
--- /dev/null
+++ b/packages/wm/src/containers/commands/set_focused_descendant.rs
@@ -0,0 +1,36 @@
+use crate::{
+ containers::{traits::CommonBehavior, Container},
+ wm_state::WmState,
+};
+
+pub fn set_focused_descendant(
+ focused_descendant: Container,
+ end_ancestor: Option<&Container>,
+ state: &WmState,
+) {
+ let root = state.root_container.clone().into();
+ let end_ancestor = end_ancestor.unwrap_or(&root);
+
+ // Traverse upwards, setting the container as the last focused until the
+ // root container or `end_ancestor` is reached.
+ let mut target = focused_descendant;
+
+ while let Some(parent) = target.parent() {
+ if parent.id() == end_ancestor.id() {
+ break;
+ }
+
+ {
+ 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());
+ }
+ }
+
+ target = parent.into();
+ }
+}
diff --git a/packages/wm/src/containers/container.rs b/packages/wm/src/containers/container.rs
index d188f8cb..70f79443 100644
--- a/packages/wm/src/containers/container.rs
+++ b/packages/wm/src/containers/container.rs
@@ -33,6 +33,15 @@ impl From<TilingContainer> for Container {
}
}
+impl From<WindowContainer> for Container {
+ fn from(window_container: WindowContainer) -> Self {
+ match window_container {
+ WindowContainer::NonTilingWindow(c) => Container::NonTilingWindow(c),
+ WindowContainer::TilingWindow(c) => Container::TilingWindow(c),
+ }
+ }
+}
+
impl PartialEq for Container {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
diff --git a/packages/wm/src/containers/root_container.rs b/packages/wm/src/containers/root_container.rs
index 8eae0c11..8ead8833 100644
--- a/packages/wm/src/containers/root_container.rs
+++ b/packages/wm/src/containers/root_container.rs
@@ -22,6 +22,7 @@ struct RootContainerInner {
id: Uuid,
parent: Option<TilingContainer>,
children: VecDeque<Container>,
+ child_focus_order: VecDeque<Uuid>,
size_percent: f32,
}
@@ -31,6 +32,7 @@ impl RootContainer {
id: Uuid::new_v4(),
parent: None,
children: VecDeque::new(),
+ child_focus_order: VecDeque::new(),
size_percent: 1.0,
};
diff --git a/packages/wm/src/containers/split_container.rs b/packages/wm/src/containers/split_container.rs
index 012b4eae..8ecf08d7 100644
--- a/packages/wm/src/containers/split_container.rs
+++ b/packages/wm/src/containers/split_container.rs
@@ -26,6 +26,7 @@ struct SplitContainerInner {
id: Uuid,
parent: Option<TilingContainer>,
children: VecDeque<Container>,
+ child_focus_order: VecDeque<Uuid>,
size_percent: f32,
tiling_direction: TilingDirection,
}
@@ -36,6 +37,7 @@ impl SplitContainer {
id: Uuid::new_v4(),
parent: None,
children: VecDeque::new(),
+ child_focus_order: VecDeque::new(),
size_percent: 1.0,
tiling_direction,
};
diff --git a/packages/wm/src/containers/traits/common_behavior.rs b/packages/wm/src/containers/traits/common_behavior.rs
index cac8a4da..a4a42338 100644
--- a/packages/wm/src/containers/traits/common_behavior.rs
+++ b/packages/wm/src/containers/traits/common_behavior.rs
@@ -34,6 +34,10 @@ pub trait CommonBehavior {
fn borrow_children_mut(&self) -> RefMut<'_, VecDeque<Container>>;
+ fn borrow_child_focus_order(&self) -> Ref<'_, VecDeque<Uuid>>;
+
+ fn borrow_child_focus_order_mut(&self) -> RefMut<'_, VecDeque<Uuid>>;
+
/// Gets the parent container, unless this container is the root.
fn parent(&self) -> Option<TilingContainer> {
self.borrow_parent().clone()
@@ -51,13 +55,19 @@ pub trait CommonBehavior {
}
/// 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())
- })
+ ///
+ /// Returns 0 if the container has no parent.
+ fn index(&self) -> usize {
+ self
+ .borrow_parent()
+ .as_ref()
+ .and_then(|parent| {
+ parent
+ .borrow_children()
+ .iter()
+ .position(|child| child.id() == self.id())
+ })
+ .unwrap_or(0)
}
fn descendants(&self) -> Descendants {
@@ -106,21 +116,59 @@ pub trait CommonBehavior {
fn parent_workspace(&self) -> Option<Workspace> {
self
- .ancestors()
+ .self_and_ancestors()
.find_map(|container| container.as_workspace().cloned())
}
fn parent_monitor(&self) -> Option<Monitor> {
self
- .ancestors()
+ .self_and_ancestors()
.find_map(|container| container.as_monitor().cloned())
}
fn parent_direction_container(&self) -> Option<DirectionContainer> {
self
- .ancestors()
+ .self_and_ancestors()
.find_map(|container| container.try_into().ok())
}
+
+ /// Index of this container in parent's child focus order.
+ ///
+ /// Returns 0 if the container has no parent.
+ fn focus_index(&self) -> usize {
+ self
+ .parent()
+ .and_then(|parent| {
+ parent
+ .borrow_child_focus_order()
+ .iter()
+ .position(|id| id == &self.id())
+ })
+ .unwrap_or(0)
+ }
+
+ /// Child container that last had focus.
+ fn last_focused_child(&self) -> Option<Container> {
+ let child_focus_order = self.borrow_child_focus_order();
+ let child_id = child_focus_order.front()?;
+
+ self
+ .borrow_children()
+ .iter()
+ .find(|child| child.id() == *child_id)
+ .cloned()
+ }
+
+ /// Gets the last focused descendant by traversing downwards.
+ fn last_focused_descendant(&self) -> Option<Container> {
+ let mut descendant = self.last_focused_child()?;
+
+ while let Some(child) = descendant.last_focused_child() {
+ descendant = child;
+ }
+
+ Some(descendant)
+ }
}
/// An iterator over ancestors of a given container.
@@ -218,6 +266,16 @@ macro_rules! impl_common_behavior {
fn borrow_children_mut(&self) -> RefMut<'_, VecDeque<Container>> {
RefMut::map(self.0.borrow_mut(), |c| &mut c.children)
}
+
+ fn borrow_child_focus_order(&self) -> Ref<'_, VecDeque<Uuid>> {
+ Ref::map(self.0.borrow(), |c| &c.child_focus_order)
+ }
+
+ fn borrow_child_focus_order_mut(
+ &self,
+ ) -> RefMut<'_, VecDeque<Uuid>> {
+ RefMut::map(self.0.borrow_mut(), |c| &mut c.child_focus_order)
+ }
}
};
}
diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rs
index 6cecae2e..1dd1a629 100644
--- a/packages/wm/src/main.rs
+++ b/packages/wm/src/main.rs
@@ -1,4 +1,4 @@
-use std::{env, path::PathBuf};
+use std::{env, ops::DerefMut, path::PathBuf};
use anyhow::{Context, Result};
use tokio::process::Command;
@@ -85,9 +85,9 @@ async fn start_wm(config_path: Option<PathBuf>) -> Result<()> {
},
Some(wm_command) = ipc_server.wm_command_rx.recv() => {
info!("Received WM command via IPC: {:?}", wm_command);
- wm.process_command(wm_command).await
+ let _ = wm.process_command(wm_command, config.deref_mut()).await;
},
- Some(config) = config.changes_rx.recv() => {
+ Some(_) = config.changes_rx.recv() => {
info!("Received user config update: {:?}", config);
event_listener.update(&config);
},
diff --git a/packages/wm/src/monitors/monitor.rs b/packages/wm/src/monitors/monitor.rs
index c4750c56..81efdc8c 100644
--- a/packages/wm/src/monitors/monitor.rs
+++ b/packages/wm/src/monitors/monitor.rs
@@ -4,6 +4,7 @@ use std::{
rc::Rc,
};
+use anyhow::Context;
use uuid::Uuid;
use crate::{
@@ -24,6 +25,7 @@ struct MonitorInner {
id: Uuid,
parent: Option<TilingContainer>,
children: VecDeque<Container>,
+ child_focus_order: VecDeque<Uuid>,
size_percent: f32,
native: NativeMonitor,
}
@@ -34,6 +36,7 @@ impl Monitor {
id: Uuid::new_v4(),
parent: None,
children: VecDeque::new(),
+ child_focus_order: VecDeque::new(),
size_percent: 1.0,
native: native_monitor,
};
@@ -53,8 +56,24 @@ impl Monitor {
todo!()
}
- pub fn displayed_workspace(&self) -> Workspace {
- todo!()
+ pub fn displayed_workspace(&self) -> Option<Workspace> {
+ self
+ .borrow_children()
+ .front()
+ .and_then(|c| c.as_workspace())
+ .cloned()
+ }
+
+ /// Whether there is a difference in DPI between this monitor and the
+ /// parent monitor of another container.
+ pub fn has_dpi_difference(
+ &self,
+ other: &Container,
+ ) -> anyhow::Result<bool> {
+ let other_monitor =
+ other.parent_monitor().context("No parent monitor.")?;
+
+ Ok(self.native().dpi != other_monitor.native().dpi)
}
}
diff --git a/packages/wm/src/user_config.rs b/packages/wm/src/user_config.rs
index 082f3e59..bc0a789f 100644
--- a/packages/wm/src/user_config.rs
+++ b/packages/wm/src/user_config.rs
@@ -125,8 +125,8 @@ pub struct ParsedConfig {
#[derive(Debug)]
pub struct UserConfig {
pub value: ParsedConfig,
- pub changes_rx: mpsc::UnboundedReceiver<ParsedConfig>,
- pub changes_tx: mpsc::UnboundedSender<ParsedConfig>,
+ pub changes_rx: mpsc::UnboundedReceiver<()>,
+ pub changes_tx: mpsc::UnboundedSender<()>,
}
const SAMPLE_CONFIG: &str =
@@ -156,8 +156,7 @@ impl UserConfig {
// similar to https://github.com/AlexanderThaller/format_serde_error
let parsed_config = serde_yaml::from_str(&config_str)?;
- let (changes_tx, changes_rx) =
- mpsc::unbounded_channel::<ParsedConfig>();
+ let (changes_tx, changes_rx) = mpsc::unbounded_channel::<()>();
Ok(Arc::new(Mutex::new(Self {
value: parsed_config,
diff --git a/packages/wm/src/windows/commands/manage_window_command.rs b/packages/wm/src/windows/commands/manage_window_command.rs
index 64489d3a..abea7240 100644
--- a/packages/wm/src/windows/commands/manage_window_command.rs
+++ b/packages/wm/src/windows/commands/manage_window_command.rs
@@ -1,10 +1,172 @@
-use crate::wm_state::WmState;
+use anyhow::Context;
+use tracing::info;
-pub struct ManageWindowCommand;
+use crate::{
+ common::platform::NativeWindow,
+ containers::{
+ commands::attach_container,
+ traits::{CommonBehavior, PositionBehavior},
+ TilingContainer, WindowContainer,
+ },
+ user_config::UserConfig,
+ windows::{
+ traits::WindowBehavior, NonTilingWindow, TilingWindow, WindowState,
+ },
+ wm_event::WmEvent,
+ wm_state::WmState,
+};
-pub fn manage_window_command(
- command: ManageWindowCommand,
+pub fn manage_window(
+ native_window: NativeWindow,
+ target_parent: Option<TilingContainer>,
state: &mut WmState,
+ config: &UserConfig,
) -> anyhow::Result<()> {
- todo!()
+ // Attach the new window as the first child of the target parent (if
+ // provided), otherwise, add as a sibling of the focused container.
+ let (target_parent, target_index) = match target_parent {
+ Some(parent) => (parent, 0),
+ None => insertion_target(state)?,
+ };
+
+ // Create the window instance.
+ let window =
+ create_window(native_window, &target_parent, state, config)?;
+
+ attach_container(window.clone().into(), &target_parent, target_index)?;
+
+ // let window_rules = config.matching_window_rules(&window);
+ // let window_rule_commands =
+ // window_rules.iter().flat_map(|rule| &rule.commands);
+
+ // // 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());
+ // run_with_subject_container(window_rule_commands, window.clone());
+
+ // // Update window in case the reference changes.
+ // let window = window_service.get_window_by_handle(window.handle());
+
+ // // Window might be detached if 'ignore' command has been invoked.
+ // if window.is_none() || !window.unwrap().is_detached() {
+ // return Ok(());
+ // }
+
+ info!("New window managed");
+ state.emit_event(WmEvent::WindowManaged {
+ managed_window: window.clone(),
+ });
+
+ // OS focus should be set to the newly added window in case it's not
+ // already focused.
+ state.has_pending_focus_sync = true;
+
+ Ok(())
+}
+
+fn create_window(
+ native_window: NativeWindow,
+ target_parent: &TilingContainer,
+ state: &mut WmState,
+ config: &UserConfig,
+) -> anyhow::Result<WindowContainer> {
+ let target_workspace = target_parent
+ .parent_workspace()
+ .context("No target workspace.")?;
+
+ let nearest_monitor = state
+ .nearest_monitor(&native_window)
+ .context("No nearest monitor.")?;
+
+ let nearest_workspace = nearest_monitor
+ .displayed_workspace()
+ .context("No nearest workspace.")?;
+
+ // Calculate where window should be placed when floating is enabled. Use the original
+ // width/height of the window and optionally position it in the center of the workspace.
+ let floating_placement = if nearest_workspace.id()
+ == target_workspace.id()
+ && !config.value.general.center_new_floating_windows
+ {
+ native_window.placement()
+ } else {
+ native_window
+ .placement()
+ .translate_to_center(&target_workspace.to_rect())
+ };
+
+ let window_state = window_state_to_create(&native_window);
+
+ // TODO: Instead always use None and move this logic to handler for
+ // toggling minimized state.
+ let prev_window_state = match window_state {
+ WindowState::Minimized => {
+ if native_window.is_resizable() {
+ Some(WindowState::Tiling)
+ } else {
+ Some(WindowState::Floating)
+ }
+ }
+ _ => None,
+ };
+
+ let window_container: WindowContainer = match window_state {
+ WindowState::Tiling => {
+ TilingWindow::new(native_window, floating_placement).into()
+ }
+ _ => NonTilingWindow::new(
+ native_window,
+ window_state,
+ prev_window_state,
+ floating_placement,
+ )
+ .into(),
+ };
+
+ // The OS might spawn the window on a different monitor to the target
+ // parent, so adjustments might need to be made because of DPI.
+ if nearest_monitor
+ .has_dpi_difference(&window_container.clone().into())?
+ {
+ window_container.set_has_pending_dpi_adjustment(true);
+ }
+
+ Ok(window_container)
+}
+
+/// TODO: Handle detection of fullscreen windows.
+/// TODO: Consider initializing maximized windows as tiling.
+fn window_state_to_create(native_window: &NativeWindow) -> WindowState {
+ if native_window.is_minimized() {
+ return WindowState::Minimized;
+ }
+
+ if native_window.is_maximized() {
+ return WindowState::Maximized;
+ }
+
+ // Initialize windows that can't be resized as floating.
+ if !native_window.is_resizable() {
+ return WindowState::Floating;
+ }
+
+ WindowState::Tiling
+}
+
+fn insertion_target(
+ state: &WmState,
+) -> anyhow::Result<(TilingContainer, usize)> {
+ let focused_container =
+ state.focused_container().context("No focused container.")?;
+
+ if focused_container.is_workspace() {
+ Ok((focused_container.try_into().map_err(anyhow::Error::msg)?, 0))
+ } else {
+ let parent = focused_container
+ .parent()
+ .map(|p| p.into())
+ .context("No insertion target.")?;
+
+ Ok((parent, focused_container.index() + 1))
+ }
}
diff --git a/packages/wm/src/windows/mod.rs b/packages/wm/src/windows/mod.rs
index 92b60012..57f33996 100644
--- a/packages/wm/src/windows/mod.rs
+++ b/packages/wm/src/windows/mod.rs
@@ -1,4 +1,4 @@
-// pub mod commands;
+pub mod commands;
mod non_tiling_window;
mod tiling_window;
pub mod traits;
diff --git a/packages/wm/src/windows/non_tiling_window.rs b/packages/wm/src/windows/non_tiling_window.rs
index 3e35b5b8..f1defc49 100644
--- a/packages/wm/src/windows/non_tiling_window.rs
+++ b/packages/wm/src/windows/non_tiling_window.rs
@@ -27,23 +27,31 @@ struct NonTilingWindowInner {
id: Uuid,
parent: Option<TilingContainer>,
children: VecDeque<Container>,
+ child_focus_order: VecDeque<Uuid>,
native: NativeWindow,
- position: Rect,
state: WindowState,
+ prev_state: Option<WindowState>,
display_state: DisplayState,
border_delta: RectDelta,
has_pending_dpi_adjustment: bool,
+ floating_placement: Rect,
}
impl NonTilingWindow {
- pub fn new(native_window: NativeWindow, state: WindowState) -> Self {
+ pub fn new(
+ native_window: NativeWindow,
+ state: WindowState,
+ prev_state: Option<WindowState>,
+ floating_placement: Rect,
+ ) -> Self {
let window = NonTilingWindowInner {
id: Uuid::new_v4(),
parent: None,
children: VecDeque::new(),
+ child_focus_order: VecDeque::new(),
native: native_window,
- position: Rect::from_xy(0, 0, 0, 0),
state,
+ prev_state,
display_state: DisplayState::Shown,
border_delta: RectDelta::new(
LengthValue::new_px(0.),
@@ -52,6 +60,7 @@ impl NonTilingWindow {
LengthValue::new_px(0.),
),
has_pending_dpi_adjustment: false,
+ floating_placement,
};
Self(Rc::new(RefCell::new(window)))
@@ -63,18 +72,18 @@ impl_window_behavior!(NonTilingWindow);
impl PositionBehavior for NonTilingWindow {
fn width(&self) -> i32 {
- self.0.borrow().position.width()
+ self.0.borrow().floating_placement.width()
}
fn height(&self) -> i32 {
- self.0.borrow().position.height()
+ self.0.borrow().floating_placement.height()
}
fn x(&self) -> i32 {
- self.0.borrow().position.x()
+ self.0.borrow().floating_placement.x()
}
fn y(&self) -> i32 {
- self.0.borrow().position.y()
+ self.0.borrow().floating_placement.y()
}
}
diff --git a/packages/wm/src/windows/tiling_window.rs b/packages/wm/src/windows/tiling_window.rs
index 5e801371..9ba00d5c 100644
--- a/packages/wm/src/windows/tiling_window.rs
+++ b/packages/wm/src/windows/tiling_window.rs
@@ -7,7 +7,9 @@ use std::{
use uuid::Uuid;
use crate::{
- common::{platform::NativeWindow, DisplayState, LengthValue, RectDelta},
+ common::{
+ platform::NativeWindow, DisplayState, LengthValue, Rect, RectDelta,
+ },
containers::{
traits::{CommonBehavior, PositionBehavior, TilingBehavior},
Container, ContainerType, TilingContainer,
@@ -26,20 +28,26 @@ struct TilingWindowInner {
id: Uuid,
parent: Option<TilingContainer>,
children: VecDeque<Container>,
+ child_focus_order: VecDeque<Uuid>,
size_percent: f32,
native: NativeWindow,
state: WindowState,
display_state: DisplayState,
border_delta: RectDelta,
has_pending_dpi_adjustment: bool,
+ floating_placement: Rect,
}
impl TilingWindow {
- pub fn new(native_window: NativeWindow) -> Self {
+ pub fn new(
+ native_window: NativeWindow,
+ floating_placement: Rect,
+ ) -> Self {
let window = TilingWindowInner {
id: Uuid::new_v4(),
parent: None,
children: VecDeque::new(),
+ child_focus_order: VecDeque::new(),
size_percent: 1.0,
native: native_window,
state: WindowState::Tiling,
@@ -51,6 +59,7 @@ impl TilingWindow {
LengthValue::new_px(0.),
),
has_pending_dpi_adjustment: false,
+ floating_placement,
};
Self(Rc::new(RefCell::new(window)))
diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rs
index 08addedf..b1b62803 100644
--- a/packages/wm/src/wm.rs
+++ b/packages/wm/src/wm.rs
@@ -1,4 +1,7 @@
-use std::sync::Arc;
+use std::{
+ ops::{Deref, DerefMut},
+ sync::Arc,
+};
use anyhow::Result;
use tokio::sync::{
@@ -8,7 +11,8 @@ use tokio::sync::{
use crate::{
app_command::InvokeCommand, common::platform::PlatformEvent,
- user_config::UserConfig, wm_event::WmEvent, wm_state::WmState,
+ containers::commands::redraw, user_config::UserConfig,
+ wm_event::WmEvent, wm_state::WmState,
};
pub struct WindowManager {
@@ -34,7 +38,39 @@ impl WindowManager {
// TODO
}
- pub async fn process_command(&mut self, command: InvokeCommand) {
- // TODO
+ pub async fn process_command(
+ &mut self,
+ command: InvokeCommand,
+ config: &mut UserConfig,
+ ) -> anyhow::Result<()> {
+ let mut state = self.state.lock().await;
+
+ match command {
+ InvokeCommand::AdjustBorders(_) => todo!(),
+ InvokeCommand::Close => todo!(),
+ InvokeCommand::Focus(_) => todo!(),
+ InvokeCommand::Ignore => todo!(),
+ InvokeCommand::Move(_) => todo!(),
+ InvokeCommand::MoveWorkspace { direction } => todo!(),
+ InvokeCommand::Resize(_) => todo!(),
+ InvokeCommand::SetFloating { centered } => todo!(),
+ InvokeCommand::SetFullscreen => todo!(),
+ InvokeCommand::SetMaximized => todo!(),
+ InvokeCommand::SetMinimized => todo!(),
+ InvokeCommand::SetTiling => todo!(),
+ InvokeCommand::ShellExec { command } => todo!(),
+ InvokeCommand::ToggleFloating { centered } => todo!(),
+ InvokeCommand::ToggleFullscreen => todo!(),
+ InvokeCommand::ToggleMaximized => todo!(),
+ InvokeCommand::ToggleMinimized => todo!(),
+ InvokeCommand::ToggleTiling => todo!(),
+ InvokeCommand::ToggleTilingDirection => todo!(),
+ InvokeCommand::WmDisableBindingMode { name } => todo!(),
+ InvokeCommand::WmExit => todo!(),
+ InvokeCommand::WmEnableBindingMode { name } => todo!(),
+ InvokeCommand::WmRedraw => redraw(state.deref_mut(), &config),
+ InvokeCommand::WmReloadConfig => todo!(),
+ InvokeCommand::WmToggleFocusMode => todo!(),
+ }
}
}
diff --git a/packages/wm/src/wm_event.rs b/packages/wm/src/wm_event.rs
index abd1dfe0..ea2922cb 100644
--- a/packages/wm/src/wm_event.rs
+++ b/packages/wm/src/wm_event.rs
@@ -2,7 +2,7 @@ use uuid::Uuid;
use crate::{
common::{platform::WindowHandle, TilingDirection},
- containers::Container,
+ containers::{Container, WindowContainer},
monitors::Monitor,
workspaces::Workspace,
};
@@ -33,7 +33,7 @@ pub enum WmEvent {
},
UserConfigReloaded,
WindowManaged {
- managed_window: Container,
+ managed_window: WindowContainer,
},
WindowUnmanaged {
unmanaged_id: Uuid,
diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rs
index d4f2eb8b..6dda0f4f 100644
--- a/packages/wm/src/wm_state.rs
+++ b/packages/wm/src/wm_state.rs
@@ -1,16 +1,22 @@
-use tokio::sync::mpsc::UnboundedSender;
+use anyhow::Context;
+use tokio::sync::mpsc::{self};
use tracing::warn;
use uuid::Uuid;
use crate::{
- common::platform::{NativeMonitor, NativeWindow, Platform},
+ common::{
+ commands::sync_native_focus,
+ platform::{NativeMonitor, NativeWindow, Platform},
+ FocusMode,
+ },
containers::{
- commands::attach_container, traits::CommonBehavior, Container,
- RootContainer, WindowContainer,
+ commands::{redraw, set_focused_descendant},
+ traits::CommonBehavior,
+ Container, RootContainer, WindowContainer,
},
monitors::{commands::add_monitor, Monitor},
- user_config::{BindingModeConfig, UserConfig},
- windows::TilingWindow,
+ user_config::UserConfig,
+ windows::{commands::manage_window, traits::WindowBehavior},
wm_event::WmEvent,
workspaces::Workspace,
};
@@ -27,14 +33,15 @@ pub struct WmState {
/// container.
pub has_pending_focus_sync: bool,
- /// Currently enabled binding modes.
- pub binding_modes: Vec<BindingModeConfig>,
+ /// Names of any currently enabled binding modes.
+ pub binding_modes: Vec<String>,
- event_tx: UnboundedSender<WmEvent>,
+ /// Sender for emitting WM-related events.
+ event_tx: mpsc::UnboundedSender<WmEvent>,
}
impl WmState {
- pub fn new(event_tx: UnboundedSender<WmEvent>) -> Self {
+ pub fn new(event_tx: mpsc::UnboundedSender<WmEvent>) -> Self {
Self {
root_container: RootContainer::new(),
containers_to_redraw: Vec::new(),
@@ -57,18 +64,33 @@ impl WmState {
}
for native_window in Platform::manageable_windows()? {
- let nearest_monitor = Platform::nearest_monitor(&native_window)
- .and_then(|native| self.monitor_from_native(&native))
- .or(self.monitors().first().cloned());
-
- if let Some(monitor) = nearest_monitor {
- // TODO: This should actually add to the monitor's displayed workspace.
- let window = TilingWindow::new(native_window);
- attach_container(window.into(), &monitor.into(), 0)?;
+ let nearest_workspace = self
+ .nearest_monitor(&native_window)
+ .and_then(|m| m.displayed_workspace());
+
+ if let Some(workspace) = nearest_workspace {
+ manage_window(
+ native_window,
+ Some(workspace.into()),
+ self,
+ config,
+ )?;
}
}
+ let container_to_focus = self
+ .window_from_native(&foreground_window)
+ .map(|c| c.as_container())
+ .or(self.windows().pop().map(|c| c.into()))
+ .or(self.workspaces().pop().map(|c| c.into()))
+ .context("Failed to get container to focus.")?;
+
+ set_focused_descendant(container_to_focus, None, self);
self.has_pending_focus_sync = true;
+
+ redraw(self, config)?;
+ sync_native_focus(self)?;
+
Ok(())
}
@@ -77,6 +99,7 @@ impl WmState {
.root_container
.children()
.iter()
+ // Safety: Direct children of the root container are always monitors.
.map(|c| c.as_monitor().cloned().unwrap())
.collect()
}
@@ -86,10 +109,30 @@ impl WmState {
.monitors()
.iter()
.flat_map(|c| c.children())
+ // Safety: Direct children of monitors are always workspaces.
.map(|c| c.as_workspace().cloned().unwrap())
.collect()
}
+ pub fn windows(&self) -> Vec<WindowContainer> {
+ self
+ .root_container
+ .descendants()
+ .filter_map(|container| container.try_into().ok())
+ .collect()
+ }
+
+ /// Gets the monitor that encompasses the largest portion of a given
+ /// window.
+ pub fn nearest_monitor(
+ &self,
+ native_window: &NativeWindow,
+ ) -> Option<Monitor> {
+ Platform::nearest_monitor(&native_window)
+ .and_then(|native| self.monitor_from_native(&native))
+ .or(self.monitors().first().cloned())
+ }
+
pub fn monitor_from_native(
&self,
native_monitor: &NativeMonitor,
@@ -104,8 +147,12 @@ impl WmState {
pub fn window_from_native(
&self,
native_window: &NativeWindow,
- ) -> Option<&Container> {
- todo!()
+ ) -> Option<WindowContainer> {
+ self
+ .windows()
+ .iter()
+ .find(|w| w.native() == *native_window)
+ .cloned()
}
/// Gets windows that should be redrawn.
@@ -129,23 +176,19 @@ impl WmState {
self.containers_to_redraw.clear();
}
- // Get the currently focused container. This can either be a `Window` or
- // a `Workspace` without any descendant windows.
- // pub fn focused_container(&self) -> Arc<Container> {
- // self
- // .root_container
- // .last_focused_descendant()
- // .unwrap()
- // .clone()
- // }
-
- // /// Whether a tiling or floating container is currently focused.
- // pub fn focus_mode(&self) -> FocusMode {
- // match self.focused_container().r#type() {
- // ContainerType::FloatingWindow => FocusMode::Floating,
- // _ => FocusMode::Tiling,
- // }
- // }
+ /// Gets the currently focused container. This can either be a window or
+ /// a workspace without any descendant windows.
+ pub fn focused_container(&self) -> Option<Container> {
+ self.root_container.last_focused_descendant()
+ }
+
+ /// Whether a tiling or floating container is currently focused.
+ pub fn focus_mode(&self) -> Option<FocusMode> {
+ self.focused_container().map(|c| match c {
+ Container::NonTilingWindow(_) => FocusMode::Floating,
+ _ => FocusMode::Tiling,
+ })
+ }
pub fn emit_event(&self, event: WmEvent) {
if let Err(err) = self.event_tx.send(event) {
diff --git a/packages/wm/src/workspaces/workspace.rs b/packages/wm/src/workspaces/workspace.rs
index 4005969c..45dad4fd 100644
--- a/packages/wm/src/workspaces/workspace.rs
+++ b/packages/wm/src/workspaces/workspace.rs
@@ -26,6 +26,7 @@ struct WorkspaceInner {
id: Uuid,
parent: Option<TilingContainer>,
children: VecDeque<Container>,
+ child_focus_order: VecDeque<Uuid>,
size_percent: f32,
tiling_direction: TilingDirection,
config: WorkspaceConfig,
@@ -42,6 +43,7 @@ impl Workspace {
id: Uuid::new_v4(),
parent: None,
children: VecDeque::new(),
+ child_focus_order: VecDeque::new(),
size_percent: 1.0,
tiling_direction,
config,
diff --git a/resources/sample-config.yaml b/resources/sample-config.yaml
index 32f6e614..c28d50c8 100644
--- a/resources/sample-config.yaml
+++ b/resources/sample-config.yaml
@@ -69,7 +69,7 @@ window_rules:
match_class_name: 'Chrome_WidgetWin_1|MozillaDialogClass'
# Some applications (eg. Steam) have borders that extend past the normal border size.
- - commands: ['change_borders --right -7px --bottom -7px --left -7px']
+ - commands: ['adjust_borders --right -7px --bottom -7px --left -7px']
match_process_name: 'steam'
binding_modes:
@@ -125,23 +125,23 @@ keybindings:
bindings: ['Alt+R']
# Change tiling direction. This determines where new tiling windows will be inserted.
- - commands: ['change_tiling_direction --toggle']
+ - commands: ['toggle_tiling_direction']
bindings: ['Alt+V']
# Change focus between floating / tiling windows.
- - commands: ['wm_change_focus_mode --toggle']
+ - commands: ['wm_toggle_focus_mode']
bindings: ['Alt+Space']
# Change the focused window to be floating / tiling.
- - commands: ['set_floating --centered --toggle']
+ - commands: ['toggle_floating --centered']
bindings: ['Alt+Shift+Space']
# Change the focused window to be maximized / unmaximized.
- - commands: ['set_maximized --toggle']
+ - commands: ['toggle_maximized']
bindings: ['Alt+X']
# Minimize focused window.
- - commands: ['set_minimized --toggle']
+ - commands: ['toggle_minimized']
bindings: ['Alt+M']
# Close focused window.