GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: bring windows of the same state to the top of z-order (#923)
Lars Berger4c3192dab625
diff --git a/packages/wm-common/src/utils/iterator_ext.rs b/packages/wm-common/src/utils/iterator_ext.rsnew file mode 100644index 00000000..75c4eaf6--- /dev/null+++ b/packages/wm-common/src/utils/iterator_ext.rs@@ -0,0 +1,57 @@+use std::{collections::HashSet, hash::Hash};++/// Extension trait for iterators.+pub trait UniqueExt: Iterator {+ /// Returns an iterator that yields unique elements based on the key+ /// function.+ ///+ /// The key function must return a value that implements `Hash` and `Eq`.+ fn unique_by<K, F>(self, key_fn: F) -> UniqueBy<Self, K, F>+ where+ Self: Sized,+ K: Hash + Eq,+ F: FnMut(&Self::Item) -> K;+}++pub struct UniqueBy<I: Iterator, K, F> {+ iter: I,+ key_fn: F,+ seen: HashSet<K>,+}++// Implement the `Iterator` trait for the `UniqueBy` struct.+impl<I, K, F> Iterator for UniqueBy<I, K, F>+where+ I: Iterator,+ K: Hash + Eq,+ F: FnMut(&I::Item) -> K,+{+ type Item = I::Item;++ fn next(&mut self) -> Option<Self::Item> {+ for item in self.iter.by_ref() {+ let key = (self.key_fn)(&item);+ if self.seen.insert(key) {+ return Some(item);+ }+ }++ None+ }+}++// Implement the extension trait for all iterators.+impl<I: Iterator> UniqueExt for I {+ fn unique_by<K, F>(self, key_fn: F) -> UniqueBy<Self, K, F>+ where+ Self: Sized,+ K: Hash + Eq,+ F: FnMut(&Self::Item) -> K,+ {+ UniqueBy {+ iter: self,+ key_fn,+ seen: HashSet::new(),+ }+ }+}diff --git a/packages/wm-common/src/utils/mod.rs b/packages/wm-common/src/utils/mod.rsindex 0a9e41cb..c886d13b 100644--- a/packages/wm-common/src/utils/mod.rs+++ b/packages/wm-common/src/utils/mod.rs@@ -1,6 +1,8 @@+mod iterator_ext;mod memo;mod try_warn;mod vec_deque_ext;+pub use iterator_ext::*;pub use memo::*;pub use vec_deque_ext::*;diff --git a/packages/wm-common/src/window_state.rs b/packages/wm-common/src/window_state.rsindex 5ebb2536..37cde651 100644--- a/packages/wm-common/src/window_state.rs+++ b/packages/wm-common/src/window_state.rs@@ -27,4 +27,9 @@ impl WindowState {),}}++ #[must_use]+ pub fn is_same_state(&self, other: &Self) -> bool {+ std::mem::discriminant(self) == std::mem::discriminant(other)+ }}diff --git a/packages/wm-platform/src/native_window.rs b/packages/wm-platform/src/native_window.rsindex c8fd37b9..23ac5888 100644--- a/packages/wm-platform/src/native_window.rs+++ b/packages/wm-platform/src/native_window.rs@@ -29,11 +29,12 @@ use windows::{SendNotifyMessageW, SetForegroundWindow,SetLayeredWindowAttributes, SetWindowLongPtrW, SetWindowPlacement,SetWindowPos, ShowWindowAsync, GWL_EXSTYLE, GWL_STYLE, GW_OWNER,- HWND_NOTOPMOST, HWND_TOPMOST, LAYERED_WINDOW_ATTRIBUTES_FLAGS,- LWA_ALPHA, LWA_COLORKEY, SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED,- SWP_NOACTIVATE, SWP_NOCOPYBITS, SWP_NOMOVE, SWP_NOOWNERZORDER,- SWP_NOSENDCHANGING, SWP_NOSIZE, SWP_NOZORDER, SW_HIDE,- SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOWNA, WINDOWPLACEMENT,+ HWND_NOTOPMOST, HWND_TOP, HWND_TOPMOST,+ LAYERED_WINDOW_ATTRIBUTES_FLAGS, LWA_ALPHA, LWA_COLORKEY,+ SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED, SWP_NOACTIVATE,+ SWP_NOCOPYBITS, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSENDCHANGING,+ SWP_NOSIZE, SWP_NOZORDER, SWP_SHOWWINDOW, SW_HIDE, SW_MAXIMIZE,+ SW_MINIMIZE, SW_RESTORE, SW_SHOWNA, WINDOWPLACEMENT,WINDOW_EX_STYLE, WINDOW_STYLE, WM_CLOSE, WPF_ASYNCWINDOWPLACEMENT,WS_CAPTION, WS_CHILD, WS_DLGFRAME, WS_EX_LAYERED,WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_MAXIMIZEBOX, WS_THICKFRAME,@@ -52,7 +53,15 @@ use super::{iapplication_view_collection, iservice_provider, COM_INIT};/// process.pub const FOREGROUND_INPUT_IDENTIFIER: u32 = 6379;-#[derive(Debug, Clone)]+#[derive(Clone, Debug, PartialEq)]+pub enum ZOrder {+ Normal,+ AfterWindow(isize),+ Top,+ TopMost,+}++#[derive(Clone, Debug)]pub struct NativeWindow {pub handle: isize,title: Memo<String>,@@ -700,6 +709,7 @@ impl NativeWindow {&self,state: &WindowState,rect: &Rect,+ z_order: &ZOrder,is_visible: bool,hide_method: &HideMethod,has_pending_dpi_adjustment: bool,@@ -731,13 +741,11 @@ impl NativeWindow {| SWP_NOSENDCHANGING| SWP_ASYNCWINDOWPOS;- // Whether the window should be shown above all other windows.- let z_order = match state {- WindowState::Floating(config) if config.shown_on_top => HWND_TOPMOST,- WindowState::Fullscreen(config) if config.shown_on_top => {- HWND_TOPMOST- }- _ => HWND_NOTOPMOST,+ let z_order = match z_order {+ ZOrder::TopMost => HWND_TOPMOST,+ ZOrder::Top => HWND_TOP,+ ZOrder::Normal => HWND_NOTOPMOST,+ ZOrder::AfterWindow(hwnd) => HWND(*hwnd),};match state {@@ -801,7 +809,37 @@ impl NativeWindow {};// Whether to hide or show the window.- self.set_visible(is_visible, hide_method)+ self.set_visible(is_visible, hide_method)?;++ Ok(())+ }++ pub fn set_z_order(&self, z_order: &ZOrder) -> anyhow::Result<()> {+ let z_order = match z_order {+ ZOrder::TopMost => HWND_TOPMOST,+ ZOrder::Top => HWND_TOP,+ ZOrder::Normal => HWND_NOTOPMOST,+ ZOrder::AfterWindow(hwnd) => HWND(*hwnd),+ };++ unsafe {+ SetWindowPos(+ HWND(self.handle),+ z_order,+ 0,+ 0,+ 0,+ 0,+ SWP_NOACTIVATE+ | SWP_NOCOPYBITS+ | SWP_ASYNCWINDOWPOS+ | SWP_SHOWWINDOW+ | SWP_NOMOVE+ | SWP_NOSIZE,+ )+ }?;++ Ok(())}pub fn cleanup(&self) {diff --git a/packages/wm/src/commands/general/cycle_focus.rs b/packages/wm/src/commands/general/cycle_focus.rsindex 6f85e5f4..dd295038 100644--- a/packages/wm/src/commands/general/cycle_focus.rs+++ b/packages/wm/src/commands/general/cycle_focus.rs@@ -30,8 +30,7 @@ pub fn cycle_focus(loop {// Break if we have cycled back to the current state.- if std::mem::discriminant(¤t) == std::mem::discriminant(&next)- {+ if current.is_same_state(&next) {break;}diff --git a/packages/wm/src/commands/general/platform_sync.rs b/packages/wm/src/commands/general/platform_sync.rsindex a06e6175..f33bf2ee 100644--- a/packages/wm/src/commands/general/platform_sync.rs+++ b/packages/wm/src/commands/general/platform_sync.rs@@ -5,9 +5,9 @@ use tokio::task;use tracing::warn;use wm_common::{CornerStyle, CursorJumpTrigger, DisplayState, HideMethod, OpacityValue,- WindowEffectConfig, WmEvent,+ UniqueExt, WindowEffectConfig, WindowState, WmEvent,};-use wm_platform::Platform;+use wm_platform::{Platform, ZOrder};use crate::{models::{Container, WindowContainer},@@ -27,25 +27,35 @@ pub fn platform_sync(return Ok(());}- if !state.pending_sync.containers_to_redraw.is_empty() {- redraw_containers(state, config)?;- state.pending_sync.containers_to_redraw.clear();- }-- let recent_focused_container = state.recent_focused_container.clone();let focused_container =state.focused_container().context("No focused container.")?;- if state.pending_sync.cursor_jump {- if config.value.general.cursor_jump.enabled {- jump_cursor(focused_container.clone(), state, config)?;- }+ // Keep reference to the original focused container.+ let recent_focused_window = state.recent_focused_window.clone();- state.pending_sync.cursor_jump = false;+ if state.pending_sync.focus_change {+ sync_focus(&focused_container, state)?;+ }++ if !state.pending_sync.containers_to_redraw.is_empty()+ || state.pending_sync.focus_change+ {+ redraw_containers(+ &focused_container,+ recent_focused_window.as_ref(),+ state,+ config,+ )?;+ }++ if state.pending_sync.cursor_jump+ && config.value.general.cursor_jump.enabled+ {+ jump_cursor(focused_container.clone(), state, config)?;}- if state.pending_sync.focus_change- || state.pending_sync.reset_window_effects+ if state.pending_sync.update_focused_window_effect+ || state.pending_sync.update_all_window_effects{if let Ok(window) = focused_container.as_window_container() {apply_window_effects(&window, true, config);@@ -55,34 +65,30 @@ pub fn platform_sync(// For the sake of performance, we only update the border of the// previously focused window. If the `reset_window_effects` flag is// passed, the unfocused border is applied to all unfocused windows.- let unfocused_windows = if state.pending_sync.reset_window_effects {- state.windows()- } else {- recent_focused_container- .and_then(|container| container.as_window_container().ok())- .into_iter()- .collect()- }- .into_iter()- .filter(|window| window.id() != focused_container.id());+ let unfocused_windows =+ if state.pending_sync.update_all_window_effects {+ state.windows()+ } else {+ recent_focused_window+ .map(|(window, _)| window)+ .into_iter()+ .collect()+ }+ .into_iter()+ .filter(|window| window.id() != focused_container.id());for window in unfocused_windows {apply_window_effects(&window, false, config);}-- state.pending_sync.reset_window_effects = false;}- if state.pending_sync.focus_change {- sync_focus(focused_container.clone(), state)?;- state.pending_sync.focus_change = false;- }+ state.pending_sync.clear();Ok(())}fn sync_focus(- focused_container: Container,+ focused_container: &Container,state: &mut WmState,) -> anyhow::Result<()> {let native_window = match focused_container.as_window_container() {@@ -98,24 +104,142 @@ fn sync_focus(}}- // TODO: 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.-state.emit_event(WmEvent::FocusChanged {focused_container: focused_container.to_dto()?,});- state.recent_focused_container = Some(focused_container);+ if let Ok(window) = focused_container.as_window_container() {+ state.recent_focused_window = Some((window.clone(), window.state()));+ } else {+ state.recent_focused_window = None;+ }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.+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.focus_change+ || state.pending_sync.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())+ });++ // 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]+ };++ 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<()> {- for window in &state.windows_to_redraw() {+ 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 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+ .iter()+ .position(|order| order.id() == window.id())+ });++ for window in &windows_to_update {+ let should_bring_to_front = windows_to_bring_to_front.contains(window);++ // Whether the window should be shown above all other windows.+ let z_order = match window.state() {+ WindowState::Floating(config) if config.shown_on_top => {+ ZOrder::TopMost+ }+ WindowState::Fullscreen(config) if config.shown_on_top => {+ ZOrder::TopMost+ }+ _ if should_bring_to_front => {+ let focused_window = focused_container.as_window_container().ok();++ if let Some(focused) = focused_window {+ if window.id() == focused_container.id() {+ ZOrder::Normal+ } else {+ ZOrder::AfterWindow(focused.native().handle)+ }+ } else {+ ZOrder::Normal+ }+ }+ _ => ZOrder::Normal,+ };++ // Set the z-order of the window and skip updating it's position if the+ // window only requires a z-order change.+ if should_bring_to_front && !windows_to_redraw.contains(window) {+ if let Err(err) = window.native().set_z_order(&z_order) {+ warn!("Failed to set window z-order: {}", err);+ }++ continue;+ }+let workspace =window.workspace().context("Window has no workspace.")?;@@ -145,6 +269,7 @@ fn redraw_containers(if let Err(err) = window.native().set_position(&window.state(),&rect,+ &z_order,is_visible,&config.value.general.hide_method,window.has_pending_dpi_adjustment(),@@ -158,6 +283,10 @@ fn redraw_containers(// `false`.if config.value.general.hide_method == HideMethod::Cloak&& !config.value.general.show_all_in_taskbar+ && matches!(+ window.display_state(),+ DisplayState::Showing | DisplayState::Hiding+ ){if let Err(err) = window.native().set_taskbar_visibility(is_visible){diff --git a/packages/wm/src/commands/general/reload_config.rs b/packages/wm/src/commands/general/reload_config.rsindex 4e19b99b..9430dc76 100644--- a/packages/wm/src/commands/general/reload_config.rs+++ b/packages/wm/src/commands/general/reload_config.rs@@ -184,7 +184,7 @@ fn update_window_effects(}}- state.pending_sync.reset_window_effects = true;+ state.pending_sync.update_all_window_effects = true;Ok(())}diff --git a/packages/wm/src/commands/window/update_window_state.rs b/packages/wm/src/commands/window/update_window_state.rsindex 05b82c15..b60b6cc3 100644--- a/packages/wm/src/commands/window/update_window_state.rs+++ b/packages/wm/src/commands/window/update_window_state.rs@@ -138,9 +138,7 @@ fn set_non_tiling(let current_state = window.state();// Update the window's previous state if the discriminant changes.- if std::mem::discriminant(¤t_state)- != std::mem::discriminant(&target_state)- {+ if !current_state.is_same_state(&target_state) {window.set_prev_state(current_state);}diff --git a/packages/wm/src/events/handle_window_focused.rs b/packages/wm/src/events/handle_window_focused.rsindex 77a4ba79..94ee597b 100644--- a/packages/wm/src/events/handle_window_focused.rs+++ b/packages/wm/src/events/handle_window_focused.rs@@ -75,7 +75,7 @@ pub fn handle_window_focused(config,)?;- state.pending_sync.focus_change = true;+ state.pending_sync.update_focused_window_effect = true;}Ok(())diff --git a/packages/wm/src/events/handle_window_moved_or_resized_end.rs b/packages/wm/src/events/handle_window_moved_or_resized_end.rsindex e477b8fa..3b78c4b5 100644--- a/packages/wm/src/events/handle_window_moved_or_resized_end.rs+++ b/packages/wm/src/events/handle_window_moved_or_resized_end.rs@@ -82,8 +82,6 @@ pub fn handle_window_moved_or_resized_end(Some(LengthValue::from_px(height_delta)),state,)?;-- state.pending_sync.containers_to_redraw.push(parent);}}diff --git a/packages/wm/src/traits/window_getters.rs b/packages/wm/src/traits/window_getters.rsindex ba426f2d..59c2a165 100644--- a/packages/wm/src/traits/window_getters.rs+++ b/packages/wm/src/traits/window_getters.rs@@ -43,10 +43,7 @@ pub trait WindowGetters {possible_states.into_iter().find_map(|state| {- state.filter(|state| {- std::mem::discriminant(state)- != std::mem::discriminant(&self.state())- })+ state.filter(|state| !self.state().is_same_state(state))})// Default to tiling from a non-tiling state, and floating from a// tiling state.diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rsindex e3c740b8..3a58797a 100644--- a/packages/wm/src/wm.rs+++ b/packages/wm/src/wm.rs@@ -113,7 +113,11 @@ impl WindowManager {}}?;- platform_sync(state, config)+ if state.pending_sync.has_changes() {+ platform_sync(state, config)?;+ }++ Ok(())}pub fn process_commands(@@ -141,7 +145,9 @@ impl WindowManager {config,)?;- platform_sync(state, config)?;+ if state.pending_sync.has_changes() {+ platform_sync(state, config)?;+ }Ok(new_subject_container_id)}diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rsindex 79dc2cc4..63c637bb 100644--- a/packages/wm/src/wm_state.rs+++ b/packages/wm/src/wm_state.rs@@ -1,4 +1,4 @@-use std::{collections::HashSet, time::Instant};+use std::time::Instant;use anyhow::Context;use tokio::sync::mpsc::{self};@@ -35,10 +35,13 @@ pub struct WmState {/// workspace focus.pub recent_workspace_name: Option<String>,- /// Container that most recently had focus synced.+ /// Window that most recently had focus synced and a snapshot of its+ /// window state.///- /// Used for updating window effects on focus change.- pub recent_focused_container: Option<Container>,+ /// Used for updating window effects on focus change. Note that this+ /// container may be detached if it's a window that's recently been+ /// killed.+ pub recent_focused_window: Option<(WindowContainer, WindowState)>,/// Time since a previously focused window was unmanaged or minimized.///@@ -65,6 +68,7 @@ pub struct WmState {exit_tx: mpsc::UnboundedSender<()>,}+#[allow(clippy::struct_excessive_bools)]pub struct PendingSync {/// Containers (and their descendants) that have a pending redraw.pub containers_to_redraw: Vec<Container>,@@ -73,14 +77,35 @@ pub struct PendingSync {/// container.pub focus_change: bool,- /// Whether window effects should be reset.- pub reset_window_effects: bool,+ /// Whether window effect for the focused window should be updated.+ pub update_focused_window_effect: bool,++ /// Whether window effects for all windows should be updated.+ pub update_all_window_effects: bool,/// Whether to jump the cursor to the focused container (if enabled in/// user config).pub cursor_jump: bool,}+impl PendingSync {+ pub fn has_changes(&self) -> bool {+ self.focus_change+ || self.update_focused_window_effect+ || self.update_all_window_effects+ || self.cursor_jump+ || !self.containers_to_redraw.is_empty()+ }++ pub fn clear(&mut self) {+ self.containers_to_redraw.clear();+ self.focus_change = false;+ self.update_focused_window_effect = false;+ self.update_all_window_effects = false;+ self.cursor_jump = false;+ }+}+impl WmState {pub fn new(event_tx: mpsc::UnboundedSender<WmEvent>,@@ -91,10 +116,11 @@ impl WmState {pending_sync: PendingSync {containers_to_redraw: Vec::new(),focus_change: false,- reset_window_effects: false,+ update_focused_window_effect: false,+ update_all_window_effects: false,cursor_jump: false,},- recent_focused_container: None,+ recent_focused_window: None,recent_workspace_name: None,unmanaged_or_minimized_timestamp: None,binding_modes: Vec::new(),@@ -146,7 +172,7 @@ impl WmState {set_focused_descendant(&container_to_focus, None);self.pending_sync.focus_change = true;- self.pending_sync.reset_window_effects = true;+ self.pending_sync.update_all_window_effects = true;platform_sync(self, config)?;self.has_initialized = true;@@ -409,8 +435,6 @@ impl WmState {/// tiling -> floating), the original detached window might still be/// queued for a redraw and should be filtered out.pub fn windows_to_redraw(&self) -> Vec<WindowContainer> {- let mut unique_ids = HashSet::new();-self.pending_sync.containers_to_redraw@@ -418,7 +442,6 @@ impl WmState {.flat_map(CommonGetters::self_and_descendants).filter(|container| !container.is_detached()).filter_map(|container| container.try_into().ok())- .filter(|window: &WindowContainer| unique_ids.insert(window.id())).collect()}