Skip to content

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

feat: consistent window z-order on focus and startup (#932)

Lars Bergera7c2891bcf97
diff --git a/packages/wm-platform/src/platform.rs b/packages/wm-platform/src/platform.rs
index 675f9a09..c9732c20 100644
--- a/packages/wm-platform/src/platform.rs
+++ b/packages/wm-platform/src/platform.rs
@@ -109,7 +109,8 @@ impl Platform {
/// Gets a vector of "manageable" windows as `NativeWindow` instances.
///
/// Manageable windows are visible windows that the WM is most likely
- /// able to manage.
+ /// able to manage. Windows are returned in z-order (top to bottom),
+ /// although the order is not guaranteed by the underlying API.
pub fn manageable_windows() -> anyhow::Result<Vec<NativeWindow>> {
Ok(
native_window::available_windows()?
diff --git a/packages/wm/src/commands/general/platform_sync.rs b/packages/wm/src/commands/general/platform_sync.rs
index 20011224..2f45b3e3 100644
--- a/packages/wm/src/commands/general/platform_sync.rs
+++ b/packages/wm/src/commands/general/platform_sync.rs
@@ -31,14 +31,10 @@ pub fn platform_sync(
}
if !state.pending_sync.containers_to_redraw().is_empty()
+ || !state.pending_sync.workspaces_to_reorder().is_empty()
|| state.pending_sync.needs_focus_update()
{
- redraw_containers(
- &focused_container,
- recent_focused_window.as_ref(),
- state,
- config,
- )?;
+ redraw_containers(&focused_container, state, config)?;
}
if state.pending_sync.needs_cursor_jump()
@@ -116,95 +112,103 @@ fn sync_focus(
Ok(())
}
-/// Change z-index of workspace windows that match the focused
-/// container's state. Make sure not to decrease z-index for floating
-/// windows that are always on top.
+/// Finds windows that should be brought to the top of their workspace's
+/// z-order.
+///
+/// Windows are brought to front if they match the focused window's state
+/// (floating/tiling) and any of these conditions are met:
+/// * Focus has changed to a different window.
+/// * Focused window's state has changed (e.g. tiling -> floating).
+/// * Focused window has moved to a different workspace.
fn windows_to_bring_to_front(
focused_container: &Container,
- recent_focused_window: Option<&(WindowContainer, WindowState)>,
state: &WmState,
) -> anyhow::Result<Vec<WindowContainer>> {
- let Some(focused_window) = focused_container.as_window_container().ok()
- else {
- return Ok(vec![]);
- };
-
let focused_workspace =
focused_container.workspace().context("No workspace.")?;
- // Bring windows to front if either:
- // 1. Focus has changed.
- // 2. A cross monitor move has occurred (check for pending cursor jump).
- // 3. Focused window state has changed.
- // 4. Focused window has moved to a different workspace.
- let should_bring_to_front = state.pending_sync.needs_focus_update()
- || state.pending_sync.needs_cursor_jump()
- || recent_focused_window.is_some_and(|(prev_window, prev_state)| {
- let prev_workspace_id =
- prev_window.workspace().map(|workspace| workspace.id());
-
- *prev_state != focused_window.state()
- || prev_workspace_id != Some(focused_workspace.id())
- });
+ // Add focused workspace if there's been a focus change.
+ let workspaces_to_reorder = state
+ .pending_sync
+ .workspaces_to_reorder()
+ .iter()
+ .chain(
+ state
+ .pending_sync
+ .needs_focus_update()
+ .then_some(&focused_workspace),
+ )
+ .unique_by(|workspace| workspace.id());
// Bring forward windows that match the focused state. Only do this for
// tiling/floating windows.
- let windows_to_bring_to_front = if should_bring_to_front {
- focused_workspace
- .descendants()
- .filter_map(|descendant| descendant.as_window_container().ok())
- .filter(|window| {
- let is_floating_or_tiling = matches!(
- window.state(),
- WindowState::Floating(_) | WindowState::Tiling
- );
-
- is_floating_or_tiling
- && window.state().is_same_state(&focused_window.state())
- })
- .collect::<Vec<_>>()
- } else {
- vec![focused_window]
- };
+ let windows_to_bring_to_front = workspaces_to_reorder
+ .flat_map(|workspace| {
+ let focused_descendant = workspace
+ .descendant_focus_order()
+ .next()
+ .and_then(|container| container.as_window_container().ok());
+
+ match focused_descendant {
+ Some(focused_descendant) => workspace
+ .descendants()
+ .filter_map(|descendant| descendant.as_window_container().ok())
+ .filter(|window| {
+ let is_floating_or_tiling = matches!(
+ window.state(),
+ WindowState::Floating(_) | WindowState::Tiling
+ );
+
+ is_floating_or_tiling
+ && window.state().is_same_state(&focused_descendant.state())
+ })
+ .collect(),
+ None => vec![],
+ }
+ })
+ .collect::<Vec<_>>();
Ok(windows_to_bring_to_front)
}
fn redraw_containers(
focused_container: &Container,
- recent_focused_window: Option<&(WindowContainer, WindowState)>,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
let windows_to_redraw = state.windows_to_redraw();
- let windows_to_bring_to_front = windows_to_bring_to_front(
- focused_container,
- recent_focused_window,
- state,
- )?;
-
- let mut windows_to_update = windows_to_redraw
- .iter()
- .chain(&windows_to_bring_to_front)
- .unique_by(|window| window.id())
- .collect::<Vec<_>>();
+ let windows_to_bring_to_front =
+ windows_to_bring_to_front(focused_container, state)?;
- let descendant_focus_order = state
- .root_container
- .descendant_focus_order()
- .collect::<Vec<_>>();
-
- // Sort the windows to update by their focus order. The most recently
- // focused window will be updated first.
- windows_to_update.sort_by_key(|window| {
- descendant_focus_order
+ let windows_to_update = {
+ let mut windows = windows_to_redraw
.iter()
- .position(|order| order.id() == window.id())
- });
+ .chain(&windows_to_bring_to_front)
+ .unique_by(|window| window.id())
+ .collect::<Vec<_>>();
+
+ let descendant_focus_order = state
+ .root_container
+ .descendant_focus_order()
+ .collect::<Vec<_>>();
+
+ // Sort the windows to update by their focus order. The most recently
+ // focused window will be updated first.
+ windows.sort_by_key(|window| {
+ descendant_focus_order
+ .iter()
+ .position(|order| order.id() == window.id())
+ });
+
+ windows
+ };
for window in &windows_to_update {
let should_bring_to_front = windows_to_bring_to_front.contains(window);
+ let workspace =
+ window.workspace().context("Window has no workspace.")?;
+
// Whether the window should be shown above all other windows.
let z_order = match window.state() {
WindowState::Floating(config) if config.shown_on_top => {
@@ -214,13 +218,16 @@ fn redraw_containers(
ZOrder::TopMost
}
_ if should_bring_to_front => {
- let focused_window = focused_container.as_window_container().ok();
+ let focused_descendant = workspace
+ .descendant_focus_order()
+ .next()
+ .and_then(|container| container.as_window_container().ok());
- if let Some(focused) = focused_window {
- if window.id() == focused_container.id() {
+ if let Some(focused_descendant) = focused_descendant {
+ if window.id() == focused_descendant.id() {
ZOrder::Normal
} else {
- ZOrder::AfterWindow(focused.native().handle)
+ ZOrder::AfterWindow(focused_descendant.native().handle)
}
} else {
ZOrder::Normal
@@ -241,9 +248,6 @@ fn redraw_containers(
continue;
}
- let workspace =
- window.workspace().context("Window has no workspace.")?;
-
// Transition display state depending on whether window will be
// shown or hidden.
window.set_display_state(
diff --git a/packages/wm/src/commands/window/move_window_in_direction.rs b/packages/wm/src/commands/window/move_window_in_direction.rs
index 6dfc61dc..2839d2f8 100644
--- a/packages/wm/src/commands/window/move_window_in_direction.rs
+++ b/packages/wm/src/commands/window/move_window_in_direction.rs
@@ -267,7 +267,8 @@ fn move_to_workspace_in_direction(
.pending_sync
.queue_containers_to_redraw(target_workspace.tiling_children())
.queue_containers_to_redraw(parent.tiling_children())
- .queue_cursor_jump();
+ .queue_cursor_jump()
+ .queue_workspace_to_reorder(target_workspace);
};
Ok(())
diff --git a/packages/wm/src/commands/window/move_window_to_workspace.rs b/packages/wm/src/commands/window/move_window_to_workspace.rs
index fc94acdc..5097e09d 100644
--- a/packages/wm/src/commands/window/move_window_to_workspace.rs
+++ b/packages/wm/src/commands/window/move_window_to_workspace.rs
@@ -7,7 +7,7 @@ use crate::{
container::{move_container_within_tree, set_focused_descendant},
workspace::activate_workspace,
},
- models::{Container, WindowContainer, WorkspaceTarget},
+ models::{WindowContainer, WorkspaceTarget},
traits::{CommonGetters, PositionGetters, WindowGetters},
user_config::UserConfig,
wm_state::WmState,
@@ -115,8 +115,10 @@ pub fn move_window_to_workspace(
// monitor, we want to reset focus to the workspace that was displayed
// on that monitor.
if let Some(focus_reset_target) = focus_reset_target {
- set_focused_descendant(&focus_reset_target, None);
- state.pending_sync.queue_focus_change();
+ set_focused_descendant(
+ &focus_reset_target,
+ Some(&target_monitor.into()),
+ );
}
// Retain focus within the workspace from where the window was moved.
@@ -125,18 +127,21 @@ pub fn move_window_to_workspace(
state.pending_sync.queue_focus_change();
}
- let containers_to_redraw: Vec<Container> = match window {
- WindowContainer::NonTilingWindow(_) => vec![window.into()],
- WindowContainer::TilingWindow(_) => current_workspace
- .tiling_children()
- .chain(target_workspace.tiling_children())
- .map(Into::into)
- .collect(),
+ match window {
+ WindowContainer::NonTilingWindow(_) => {
+ state.pending_sync.queue_container_to_redraw(window);
+ }
+ WindowContainer::TilingWindow(_) => {
+ state
+ .pending_sync
+ .queue_containers_to_redraw(current_workspace.tiling_children())
+ .queue_containers_to_redraw(target_workspace.tiling_children());
+ }
};
state
.pending_sync
- .queue_containers_to_redraw(containers_to_redraw);
+ .queue_workspace_to_reorder(target_workspace);
}
Ok(())
diff --git a/packages/wm/src/commands/window/update_window_state.rs b/packages/wm/src/commands/window/update_window_state.rs
index bd8088ac..84cbc75b 100644
--- a/packages/wm/src/commands/window/update_window_state.rs
+++ b/packages/wm/src/commands/window/update_window_state.rs
@@ -110,7 +110,8 @@ fn set_tiling(
state
.pending_sync
- .queue_containers_to_redraw(target_parent.tiling_children());
+ .queue_containers_to_redraw(target_parent.tiling_children())
+ .queue_workspace_to_reorder(workspace);
Ok(tiling_window.into())
}
@@ -132,6 +133,8 @@ fn set_non_tiling(
return Ok(window);
}
+ let workspace = window.workspace().context("No workspace.")?;
+
match window {
WindowContainer::NonTilingWindow(window) => {
let current_state = window.state();
@@ -139,6 +142,7 @@ fn set_non_tiling(
// Update the window's previous state if the discriminant changes.
if !current_state.is_same_state(&target_state) {
window.set_prev_state(current_state);
+ state.pending_sync.queue_workspace_to_reorder(workspace);
}
window.set_state(target_state);
@@ -148,7 +152,6 @@ fn set_non_tiling(
}
WindowContainer::TilingWindow(window) => {
let parent = window.parent().context("No parent")?;
- let workspace = window.workspace().context("No workspace.")?;
let non_tiling_window = window.to_non_tiling(
target_state.clone(),
@@ -180,7 +183,8 @@ fn set_non_tiling(
state
.pending_sync
.queue_container_to_redraw(non_tiling_window.clone())
- .queue_containers_to_redraw(workspace.tiling_children());
+ .queue_containers_to_redraw(workspace.tiling_children())
+ .queue_workspace_to_reorder(workspace);
Ok(non_tiling_window.into())
}
diff --git a/packages/wm/src/events/handle_window_focused.rs b/packages/wm/src/events/handle_window_focused.rs
index da8438aa..f89241ce 100644
--- a/packages/wm/src/events/handle_window_focused.rs
+++ b/packages/wm/src/events/handle_window_focused.rs
@@ -48,13 +48,14 @@ pub fn handle_window_focused(
return Ok(());
}
+ let workspace = window.workspace().context("No workspace")?;
+
// Handle focus events from windows on hidden workspaces. For example,
// if Discord is forcefully shown by the OS when it's on a hidden
// workspace, switch focus to Discord's workspace.
- if window.clone().display_state() == DisplayState::Hidden {
+ if window.display_state() == DisplayState::Hidden {
info!("Focusing off-screen window: {window}");
- let workspace = window.workspace().context("No workspace")?;
focus_workspace(
WorkspaceTarget::Name(workspace.config().name),
state,
@@ -73,7 +74,10 @@ pub fn handle_window_focused(
config,
)?;
- state.pending_sync.queue_focused_effect_update();
+ state
+ .pending_sync
+ .queue_focused_effect_update()
+ .queue_workspace_to_reorder(workspace);
}
Ok(())
diff --git a/packages/wm/src/pending_sync.rs b/packages/wm/src/pending_sync.rs
index 04be71ca..8687e011 100644
--- a/packages/wm/src/pending_sync.rs
+++ b/packages/wm/src/pending_sync.rs
@@ -2,7 +2,10 @@ use std::collections::HashMap;
use uuid::Uuid;
-use crate::{models::Container, traits::CommonGetters};
+use crate::{
+ models::{Container, Workspace},
+ traits::CommonGetters,
+};
#[derive(Default)]
#[allow(clippy::struct_excessive_bools)]
@@ -10,6 +13,10 @@ pub struct PendingSync {
/// Containers (and their descendants) that have a pending redraw.
containers_to_redraw: HashMap<Uuid, Container>,
+ /// Workspaces where z-order should be updated. Windows that match the
+ /// focused window's state should be brought to the front.
+ workspaces_to_reorder: Vec<Workspace>,
+
/// Whether native focus should be reassigned to the WM's focused
/// container.
needs_focus_update: bool,
@@ -27,15 +34,17 @@ pub struct PendingSync {
impl PendingSync {
pub fn has_changes(&self) -> bool {
- self.needs_focus_update
+ !self.containers_to_redraw.is_empty()
+ || !self.workspaces_to_reorder.is_empty()
+ || self.needs_focus_update
|| self.needs_focused_effect_update
|| self.needs_all_effects_update
|| self.needs_cursor_jump
- || !self.containers_to_redraw.is_empty()
}
pub fn clear(&mut self) -> &mut Self {
self.containers_to_redraw.clear();
+ self.workspaces_to_reorder.clear();
self.needs_focus_update = false;
self.needs_focused_effect_update = false;
self.needs_all_effects_update = false;
@@ -79,6 +88,14 @@ impl PendingSync {
self
}
+ pub fn queue_workspace_to_reorder(
+ &mut self,
+ workspace: Workspace,
+ ) -> &mut Self {
+ self.workspaces_to_reorder.push(workspace);
+ self
+ }
+
pub fn queue_focus_change(&mut self) -> &mut Self {
self.needs_focus_update = true;
self
@@ -118,4 +135,8 @@ impl PendingSync {
pub fn containers_to_redraw(&self) -> &HashMap<Uuid, Container> {
&self.containers_to_redraw
}
+
+ pub fn workspaces_to_reorder(&self) -> &Vec<Workspace> {
+ &self.workspaces_to_reorder
+ }
}
diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rs
index a929f12a..8e1db1fb 100644
--- a/packages/wm/src/wm_state.rs
+++ b/packages/wm/src/wm_state.rs
@@ -104,7 +104,10 @@ impl WmState {
add_monitor(native_monitor, self, config)?;
}
- for native_window in Platform::manageable_windows()? {
+ // Manage windows in reverse z-order (bottom to top). This helps to
+ // preserve the original stacking order.
+ for native_window in Platform::manageable_windows()?.into_iter().rev()
+ {
let nearest_workspace = self
.nearest_monitor(&native_window)
.and_then(|m| m.displayed_workspace());
@@ -133,6 +136,10 @@ impl WmState {
.queue_focus_change()
.queue_all_effects_update();
+ for workspace in self.workspaces() {
+ self.pending_sync.queue_workspace_to_reorder(workspace);
+ }
+
platform_sync(self, config)?;
self.has_initialized = true;