GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: use `Memo` type for class and process name
Lars Berger840a5c876545
diff --git a/packages/wm/src/common/memo.rs b/packages/wm/src/common/memo.rsnew file mode 100644index 00000000..baf9af67--- /dev/null+++ b/packages/wm/src/common/memo.rs@@ -0,0 +1,59 @@+use std::sync::{Arc, Mutex};++/// A thread-safe type that provides lazy initialization and caching of a+/// value.+pub struct Memo<T>+where+ T: Clone,+{+ value: Arc<Mutex<Option<T>>>,+}++impl<T> Memo<T>+where+ T: Clone,+{+ /// Creates a new `Memo` instance with `None` as the initial value.+ pub fn new() -> Self {+ Memo {+ value: Arc::new(Mutex::new(None)),+ }+ }++ /// Retrieves the cached value if it exists, otherwise initializes it+ /// using the provided closure.+ pub fn get_or_init<F, R>(+ &self,+ retriever_fn: F,+ arg: &R,+ ) -> anyhow::Result<T>+ where+ F: FnOnce(&R) -> anyhow::Result<T>,+ T: Clone,+ {+ let mut value_ref = self.value.lock().unwrap();++ value_ref+ .as_ref()+ .map(|value| Ok(value.clone()))+ .unwrap_or_else(|| {+ let value = retriever_fn(&arg)?;+ *value_ref = Some(value.clone());+ Ok(value)+ })+ }++ /// Refreshes the cached value by generating a new value using the+ /// provided closure.+ pub fn update<F, R>(&self, retriever_fn: F, arg: &R) -> anyhow::Result<T>+ where+ F: FnOnce(&R) -> anyhow::Result<T>,+ T: Clone,+ {+ let mut value_ref = self.value.lock().unwrap();++ let value = retriever_fn(&arg)?;+ *value_ref = Some(value.clone());+ Ok(value)+ }+}diff --git a/packages/wm/src/common/mod.rs b/packages/wm/src/common/mod.rsindex 57f7a990..a3fbffcd 100644--- a/packages/wm/src/common/mod.rs+++ b/packages/wm/src/common/mod.rs@@ -4,6 +4,7 @@ mod direction;mod display_state;pub mod events;mod length_value;+mod memo;pub mod platform;mod point;mod rect;@@ -16,6 +17,7 @@ pub use color::*;pub use direction::*;pub use display_state::*;pub use length_value::*;+pub use memo::*;pub use point::*;pub use rect::*;pub use rect_delta::*;diff --git a/packages/wm/src/common/platform/native_window.rs b/packages/wm/src/common/platform/native_window.rsindex 4a5488b8..156f611e 100644--- a/packages/wm/src/common/platform/native_window.rs+++ b/packages/wm/src/common/platform/native_window.rs@@ -1,5 +1,3 @@-use std::sync::{Arc, Mutex, MutexGuard, RwLock};-use tracing::warn;use windows::{core::PWSTR,@@ -35,62 +33,25 @@ use windows::{};use crate::{- common::{Color, DisplayState, LengthValue, Rect, RectDelta},+ common::{Color, DisplayState, LengthValue, Memo, Rect, RectDelta},windows::WindowState,};-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: Memo<String>,- process_name: Arc<RwLock<Option<String>>>,- class_name: Arc<RwLock<Option<String>>>,+ process_name: Memo<String>,+ class_name: Memo<String>,}impl NativeWindow {+ /// Creates a new `NativeWindow` instance with the given window handle.pub fn new(handle: isize) -> Self {Self {handle,- title: Memo::new(Self::updated_title),- process_name: Arc::new(RwLock::new(None)),- class_name: Arc::new(RwLock::new(None)),+ title: Memo::new(),+ process_name: Memo::new(),+ class_name: Memo::new(),}}@@ -98,84 +59,85 @@ impl NativeWindow {/// string.////// This value is lazily retrieved and cached after first retrieval.- pub fn title(&self) -> String {- self.title.get(self).as_ref().unwrap().to_string()+ pub fn title(&self) -> anyhow::Result<String> {+ self.title.get_or_init(Self::updated_title, self)+ }++ /// Updates the cached window title.+ pub fn refresh_title(&self) -> anyhow::Result<String> {+ self.title.update(Self::updated_title, self)}- fn updated_title(&self) -> String {+ /// Gets the window's title. If the window is invalid, returns an empty+ /// string.+ fn updated_title(&self) -> anyhow::Result<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()+ Ok(String::from_utf16_lossy(&text[..length as usize]).into())}/// Gets the process name associated with the window.////// 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 {- Some(ref process_name) => Ok(process_name.clone()),- None => {- let mut process_id = 0u32;- unsafe {- GetWindowThreadProcessId(- HWND(self.handle),- Some(&mut process_id),- );- }-- let process_handle = unsafe {- OpenProcess(PROCESS_QUERY_INFORMATION, false, process_id)- }?;+ self+ .process_name+ .get_or_init(Self::updated_process_name, self)+ }- let mut buffer = [0u16; 256];- let mut length = buffer.len() as u32;- unsafe {- QueryFullProcessImageNameW(- process_handle,- PROCESS_NAME_WIN32,- PWSTR(buffer.as_mut_ptr()),- &mut length,- )?;-- CloseHandle(process_handle)?;- };-- let process_name = String::from_utf16(&buffer[..length as usize])?;- *self.process_name.write().unwrap() = Some(process_name.clone());- Ok(process_name)- }+ /// Gets the process name associated with the window.+ fn updated_process_name(&self) -> anyhow::Result<String> {+ let mut process_id = 0u32;+ unsafe {+ GetWindowThreadProcessId(HWND(self.handle), Some(&mut process_id));}++ let process_handle = unsafe {+ OpenProcess(PROCESS_QUERY_INFORMATION, false, process_id)+ }?;++ let mut buffer = [0u16; 256];+ let mut length = buffer.len() as u32;+ unsafe {+ QueryFullProcessImageNameW(+ process_handle,+ PROCESS_NAME_WIN32,+ PWSTR(buffer.as_mut_ptr()),+ &mut length,+ )?;++ CloseHandle(process_handle)?;+ };++ let process_name = String::from_utf16(&buffer[..length as usize])?;+ Ok(process_name)}/// Gets the class name of the window.////// 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 {- Some(ref class_name) => Ok(class_name.clone()),- None => {- let mut buffer = [0u16; 256];- let result =- unsafe { GetClassNameW(HWND(self.handle), &mut buffer) };-- if result == 0 {- return Err(windows::core::Error::from_win32().into());- }+ self.class_name.get_or_init(Self::updated_class_name, self)+ }- let class_name =- String::from_utf16_lossy(&buffer[..result as usize]);- *self.class_name.write().unwrap() = Some(class_name.clone());- Ok(class_name)- }+ /// Gets the class name of the window.+ fn updated_class_name(&self) -> anyhow::Result<String> {+ let mut buffer = [0u16; 256];+ let result = unsafe { GetClassNameW(HWND(self.handle), &mut buffer) };++ if result == 0 {+ return Err(windows::core::Error::from_win32().into());}++ let class_name = String::from_utf16_lossy(&buffer[..result as usize]);+ Ok(class_name)}/// Whether the window is actually visible.pub fn is_visible(&self) -> bool {let is_visible =unsafe { IsWindowVisible(HWND(self.handle)) }.as_bool();+is_visible && !self.is_cloaked()}diff --git a/packages/wm/src/windows/non_tiling_window.rs b/packages/wm/src/windows/non_tiling_window.rsindex d2e7b7cc..6abbcdf8 100644--- a/packages/wm/src/windows/non_tiling_window.rs+++ b/packages/wm/src/windows/non_tiling_window.rs@@ -76,9 +76,11 @@ impl NonTilingWindow {}pub fn to_tiling(&self, inner_gap: LengthValue) -> TilingWindow {+ let native = std::mem::take(&mut self.0.borrow_mut().native);+TilingWindow::new(Some(self.id()),- std::mem::take(&mut self.0.borrow_mut().native),+ 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 1e367c00..016cfe9c 100644--- a/packages/wm/src/windows/tiling_window.rs+++ b/packages/wm/src/windows/tiling_window.rs@@ -81,9 +81,11 @@ impl TilingWindow {state: WindowState,insertion_target: Option<(Container, usize)>,) -> NonTilingWindow {+ let native = std::mem::take(&mut self.0.borrow_mut().native);+NonTilingWindow::new(Some(self.id()),- std::mem::take(&mut self.0.borrow_mut().native),+ native,state,Some(WindowState::Tiling),self.border_delta(),