GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: change window title to be memoized with new `Memo` struct
Lars Bergerf72930ca183a
diff --git a/packages/wm/src/common/commands/platform_sync.rs b/packages/wm/src/common/commands/platform_sync.rsindex 9139e6ee..85c4734e 100644--- a/packages/wm/src/common/commands/platform_sync.rs+++ b/packages/wm/src/common/commands/platform_sync.rs@@ -61,16 +61,22 @@ pub fn sync_focus(focused_container: Container,state: &mut WmState,) -> anyhow::Result<()> {- let native_window = match focused_container.as_window_container() {- Ok(window) => window.native(),- _ => Platform::desktop_window(),- };-// Set focus to the given window handle. If the container is a normal// window, then this will trigger a `PlatformEvent::WindowFocused` event.- if Platform::foreground_window() != native_window {- let _ = native_window.set_foreground();- }+ match focused_container.as_window_container() {+ Ok(window) => {+ if Platform::foreground_window() != *window.native() {+ let _ = window.native().set_foreground();+ }+ }+ _ => {+ let desktop_window = Platform::desktop_window();++ if Platform::foreground_window() != desktop_window {+ let _ = desktop_window.set_foreground();+ }+ }+ };// TODO: Change z-index of workspace windows that match the focused// container's state. Make sure not to decrease z-index for floatingdiff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rsindex 02888392..4515a8d9 100644--- a/packages/wm/src/common/platform/event_listener.rs+++ b/packages/wm/src/common/platform/event_listener.rs@@ -7,7 +7,6 @@ use crate::{use super::{EventWindow, NativeWindow};-#[derive(Debug)]pub enum PlatformEvent {DisplaySettingsChanged,KeybindingTriggered(KeybindingConfig),diff --git a/packages/wm/src/common/platform/native_window.rs b/packages/wm/src/common/platform/native_window.rsindex 9a33af31..4a5488b8 100644--- a/packages/wm/src/common/platform/native_window.rs+++ b/packages/wm/src/common/platform/native_window.rs@@ -1,4 +1,4 @@-use std::sync::{Arc, RwLock};+use std::sync::{Arc, Mutex, MutexGuard, RwLock};use tracing::warn;use windows::{@@ -20,16 +20,15 @@ use windows::{},WindowsAndMessaging::{EnumWindows, GetClassNameW, GetWindow, GetWindowLongPtrW,- GetWindowPlacement, GetWindowRect, GetWindowTextW,- GetWindowThreadProcessId, IsIconic, IsWindowVisible, IsZoomed,- SendNotifyMessageW, SetForegroundWindow, SetWindowPos,- ShowWindowAsync, GWL_EXSTYLE, GWL_STYLE, GW_OWNER, HWND_NOTOPMOST,- HWND_TOPMOST, SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED,- SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_NOCOPYBITS,- SWP_NOSENDCHANGING, SWP_SHOWWINDOW, SW_MAXIMIZE, SW_MINIMIZE,- SW_RESTORE, WINDOWPLACEMENT, WINDOW_EX_STYLE, WINDOW_STYLE,- WM_CLOSE, WS_CAPTION, WS_CHILD, WS_EX_NOACTIVATE,- WS_EX_TOOLWINDOW, WS_THICKFRAME,+ GetWindowRect, GetWindowTextW, GetWindowThreadProcessId, IsIconic,+ IsWindowVisible, IsZoomed, SendNotifyMessageW,+ SetForegroundWindow, SetWindowPos, ShowWindowAsync, GWL_EXSTYLE,+ GWL_STYLE, GW_OWNER, HWND_NOTOPMOST, HWND_TOPMOST,+ SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED, SWP_HIDEWINDOW,+ SWP_NOACTIVATE, SWP_NOCOPYBITS, SWP_NOSENDCHANGING,+ SWP_SHOWWINDOW, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE,+ WINDOW_EX_STYLE, WINDOW_STYLE, WM_CLOSE, WS_CAPTION, WS_CHILD,+ WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_THICKFRAME,},},},@@ -40,10 +39,47 @@ use crate::{windows::WindowState,};-#[derive(Clone, Debug)]+struct Memo<T>+where+ T: Clone,+{+ value: Arc<Mutex<Option<T>>>,+ retriever: Arc<dyn Fn(&NativeWindow) -> T + Send + Sync>,+}++impl<T> Memo<T>+where+ T: Clone,+{+ fn new<F>(retriever: F) -> Self+ where+ F: Fn(&NativeWindow) -> T + Send + Sync + 'static,+ {+ Memo {+ value: Arc::new(Mutex::new(None)),+ retriever: Arc::new(retriever),+ }+ }++ fn get(&self, native: &NativeWindow) -> MutexGuard<Option<T>> {+ let mut value_ref = self.value.lock().unwrap();+ if value_ref.is_none() {+ let new_value = (self.retriever)(native);+ *value_ref = Some(new_value);+ }+ value_ref+ }++ fn refresh(&self, native: &NativeWindow) {+ let mut value_ref = self.value.lock().unwrap();+ let new_value = (self.retriever)(native);+ *value_ref = Some(new_value);+ }+}+pub struct NativeWindow {pub handle: isize,- title: Arc<RwLock<Option<String>>>,+ title: Memo<String>,process_name: Arc<RwLock<Option<String>>>,class_name: Arc<RwLock<Option<String>>>,}@@ -52,7 +88,7 @@ impl NativeWindow {pub fn new(handle: isize) -> Self {Self {handle,- title: Arc::new(RwLock::new(None)),+ title: Memo::new(Self::updated_title),process_name: Arc::new(RwLock::new(None)),class_name: Arc::new(RwLock::new(None)),}@@ -61,26 +97,20 @@ impl NativeWindow {/// Gets the window's title. If the window is invalid, returns an empty/// string.///- /// This value is lazily retrieved and is cached after first retrieval.+ /// This value is lazily retrieved and cached after first retrieval.pub fn title(&self) -> String {- let title_guard = self.title.read().unwrap();- match *title_guard {- Some(ref title) => title.clone(),- None => {- let mut text: [u16; 512] = [0; 512];- let length =- unsafe { GetWindowTextW(HWND(self.handle), &mut text) };+ self.title.get(self).as_ref().unwrap().to_string()+ }- let title = String::from_utf16_lossy(&text[..length as usize]);- *self.title.write().unwrap() = Some(title.clone());- title- }- }+ fn updated_title(&self) -> String {+ let mut text: [u16; 512] = [0; 512];+ let length = unsafe { GetWindowTextW(HWND(self.handle), &mut text) };+ String::from_utf16_lossy(&text[..length as usize]).into()}/// Gets the process name associated with the window.///- /// This value is lazily retrieved and is cached after first retrieval.+ /// This value is lazily retrieved and cached after first retrieval.pub fn process_name(&self) -> anyhow::Result<String> {let process_name_guard = self.process_name.read().unwrap();match *process_name_guard {@@ -120,7 +150,7 @@ impl NativeWindow {/// Gets the class name of the window.///- /// This value is lazily retrieved and is cached after first retrieval.+ /// This value is lazily retrieved and cached after first retrieval.pub fn class_name(&self) -> anyhow::Result<String> {let class_name_guard = self.class_name.read().unwrap();match *class_name_guard {@@ -464,6 +494,12 @@ impl PartialEq for NativeWindow {impl Eq for NativeWindow {}+impl Default for NativeWindow {+ fn default() -> Self {+ Self::new(0)+ }+}+pub fn available_windows() -> anyhow::Result<Vec<NativeWindow>> {available_window_handles()?.into_iter()diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rsindex 272e7fc8..5460326a 100644--- a/packages/wm/src/main.rs+++ b/packages/wm/src/main.rs@@ -5,8 +5,7 @@#![feature(iterator_try_collect)]#![feature(once_cell_try)]-use std::{process::Child, env, io, path::PathBuf};-+use std::{env, io, path::PathBuf, process::Child};use anyhow::{Context, Error, Result};use tokio::{process, process::Command, signal};@@ -99,7 +98,7 @@ async fn start_wm(loop {tokio::select! {Some(event) = event_listener.event_rx.recv() => {- debug!("Received platform event: {:?}", event);+ // debug!("Received platform event: {:?}", event);if let Err(err) = wm.process_event(event, &mut config) {error!("Failed to process event: {:?}", err);@@ -210,11 +209,14 @@ async fn start_cli(args: Vec<String>) -> Result<()> {////// This assumes the watcher binary exists in the same directory as the WM/// binary.--fn start_watcher_process() -> anyhow::Result<tokio::process::Child, Error> {+fn start_watcher_process() -> anyhow::Result<tokio::process::Child, Error>+{let watcher_path = env::current_exe()?- .parent()- .context("Failed to resolve path to the watcher process.")?- .join("watcher");- Command::new(&watcher_path).spawn().context("Failed to start watcher process")+ .parent()+ .context("Failed to resolve path to the watcher process.")?+ .join("watcher");++ Command::new(&watcher_path)+ .spawn()+ .context("Failed to start watcher process.")}diff --git a/packages/wm/src/windows/non_tiling_window.rs b/packages/wm/src/windows/non_tiling_window.rsindex ed408515..d2e7b7cc 100644--- a/packages/wm/src/windows/non_tiling_window.rs+++ b/packages/wm/src/windows/non_tiling_window.rs@@ -78,7 +78,7 @@ impl NonTilingWindow {pub fn to_tiling(&self, inner_gap: LengthValue) -> TilingWindow {TilingWindow::new(Some(self.id()),- self.native(),+ std::mem::take(&mut self.0.borrow_mut().native),Some(self.state()),self.border_delta(),self.floating_placement(),diff --git a/packages/wm/src/windows/tiling_window.rs b/packages/wm/src/windows/tiling_window.rsindex effdb420..1e367c00 100644--- a/packages/wm/src/windows/tiling_window.rs+++ b/packages/wm/src/windows/tiling_window.rs@@ -83,7 +83,7 @@ impl TilingWindow {) -> NonTilingWindow {NonTilingWindow::new(Some(self.id()),- self.native(),+ std::mem::take(&mut self.0.borrow_mut().native),state,Some(WindowState::Tiling),self.border_delta(),diff --git a/packages/wm/src/windows/traits/window_getters.rs b/packages/wm/src/windows/traits/window_getters.rsindex 28235ab5..5ecc799f 100644--- a/packages/wm/src/windows/traits/window_getters.rs+++ b/packages/wm/src/windows/traits/window_getters.rs@@ -1,3 +1,5 @@+use std::cell::Ref;+use enum_dispatch::enum_dispatch;use crate::{@@ -12,7 +14,7 @@ pub trait WindowGetters {fn prev_state(&self) -> Option<WindowState>;- fn native(&self) -> NativeWindow;+ fn native(&self) -> Ref<NativeWindow>;fn border_delta(&self) -> RectDelta;@@ -48,8 +50,8 @@ macro_rules! impl_window_getters {self.0.borrow().prev_state.clone()}- fn native(&self) -> NativeWindow {- self.0.borrow().native.clone()+ fn native(&self) -> Ref<NativeWindow> {+ Ref::map(self.0.borrow(), |inner| &inner.native)}fn border_delta(&self) -> RectDelta {diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rsindex 329d4282..7c0ec3cf 100644--- a/packages/wm/src/wm_state.rs+++ b/packages/wm/src/wm_state.rs@@ -234,7 +234,7 @@ impl WmState {self.windows().into_iter()- .find(|w| w.native() == *native_window)+ .find(|window| &*window.native() == native_window)}pub fn workspace_by_name(@@ -244,7 +244,7 @@ impl WmState {self.workspaces().into_iter()- .find(|w| w.config().name == workspace_name)+ .find(|workspace| workspace.config().name == workspace_name)}/// Gets windows that should be redrawn.