GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: implement `Serialize` trait for all types sent across IPC
Lars Berger9bf5036601f4
diff --git a/Cargo.lock b/Cargo.lockindex b9492277..98da5988 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1025,6 +1025,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f00cc9702ca12d3c81455259621e676d0f7251cec66a21e98fe2e9a37db93b2a"dependencies = ["getrandom",+ "serde",][[package]]diff --git a/packages/wm/Cargo.toml b/packages/wm/Cargo.tomlindex b13791fd..194adeab 100644--- a/packages/wm/Cargo.toml+++ b/packages/wm/Cargo.toml@@ -21,7 +21,7 @@ enum_dispatch = "0.3"enum-as-inner = "0.6"futures-util = "0.3"home = "0.5"-uuid = { version = "1", features = ["v4"] }+uuid = { version = "1", features = ["v4", "serde"] }serde = { version = "1", features = ["derive"] }serde_json = "1"serde_yaml = "0.9"diff --git a/packages/wm/src/app_command.rs b/packages/wm/src/app_command.rsindex 8681f8ae..cb8d9a5c 100644--- a/packages/wm/src/app_command.rs+++ b/packages/wm/src/app_command.rs@@ -2,7 +2,7 @@ use std::{iter, path::PathBuf};use anyhow::bail;use clap::{error::KindFormatter, Args, Parser};-use serde::{Deserialize, Deserializer};+use serde::{Deserialize, Deserializer, Serialize};use tracing::Level;use uuid::Uuid;@@ -114,12 +114,12 @@ pub enum QueryCommand {/// Prints all monitors.Monitors,/// Prints the active binding modes.- BindingMode,+ BindingModes,/// Prints the focused container (either a window or an empty workspace).Focused,}-#[derive(Clone, Debug, Parser)]+#[derive(Clone, Debug, Parser, Serialize)]pub enum InvokeCommand {AdjustBorders(InvokeAdjustBordersCommand),Close,@@ -463,7 +463,7 @@ impl<'de> Deserialize<'de> for InvokeCommand {}}-#[derive(Args, Clone, Debug)]+#[derive(Args, Clone, Debug, Serialize)]#[group(required = true, multiple = true)]pub struct InvokeAdjustBordersCommand {#[clap(long, allow_hyphen_values = true)]@@ -479,7 +479,7 @@ pub struct InvokeAdjustBordersCommand {left: Option<LengthValue>,}-#[derive(Args, Clone, Debug)]+#[derive(Args, Clone, Debug, Serialize)]#[group(required = true, multiple = false)]pub struct InvokeFocusCommand {#[clap(long = "dir")]@@ -498,7 +498,7 @@ pub struct InvokeFocusCommand {recent_workspace: bool,}-#[derive(Args, Clone, Debug)]+#[derive(Args, Clone, Debug, Serialize)]#[group(required = true, multiple = false)]pub struct InvokeMoveCommand {/// Direction to move the window.@@ -510,7 +510,7 @@ pub struct InvokeMoveCommand {workspace: Option<String>,}-#[derive(Args, Clone, Debug)]+#[derive(Args, Clone, Debug, Serialize)]#[group(required = true, multiple = true)]pub struct InvokeResizeCommand {#[clap(long, allow_hyphen_values = true)]diff --git a/packages/wm/src/common/color.rs b/packages/wm/src/common/color.rsindex c6dab69e..550dbc10 100644--- a/packages/wm/src/common/color.rs+++ b/packages/wm/src/common/color.rs@@ -1,8 +1,9 @@-use anyhow::bail;-use serde::{Deserialize, Deserializer};use std::str::FromStr;-#[derive(Debug, Clone)]+use anyhow::bail;+use serde::{Deserialize, Deserializer, Serialize};++#[derive(Debug, Clone, Serialize)]pub struct ColorRGBA {pub r: u8,pub g: u8,@@ -30,7 +31,7 @@ impl FromStr for ColorRGBA {if chars.next() != Some('#') {bail!("Color must start with a `#`.");}-+println!("r: {}", &unparsed[1..3]);println!("g: {}", &unparsed[3..5]);println!("b: {}", &unparsed[5..7]);@@ -54,7 +55,7 @@ impl<'de> Deserialize<'de> for ColorRGBA {whereD: Deserializer<'de>,{- let s = String::deserialize(deserializer)?;- ColorRGBA::from_str(&s).map_err(serde::de::Error::custom)+ let str = String::deserialize(deserializer)?;+ Self::from_str(&str).map_err(serde::de::Error::custom)}}diff --git a/packages/wm/src/common/direction.rs b/packages/wm/src/common/direction.rsindex 44f38a85..45db67df 100644--- a/packages/wm/src/common/direction.rs+++ b/packages/wm/src/common/direction.rs@@ -1,8 +1,10 @@use std::str::FromStr;use anyhow::bail;+use serde::Serialize;-#[derive(Clone, Debug, PartialEq)]+#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(untagged, rename_all = "snake_case")]pub enum Direction {Left,Right,diff --git a/packages/wm/src/common/display_state.rs b/packages/wm/src/common/display_state.rsindex e9d18a1e..b886739c 100644--- a/packages/wm/src/common/display_state.rs+++ b/packages/wm/src/common/display_state.rs@@ -1,6 +1,9 @@+use serde::Serialize;+/// Represents whether something is shown, hidden, or in an intermediary/// state.-#[derive(Clone, Debug, PartialEq)]+#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(untagged, rename_all = "snake_case")]pub enum DisplayState {Shown,Showing,diff --git a/packages/wm/src/common/platform/native_monitor.rs b/packages/wm/src/common/platform/native_monitor.rsindex 4d98cf1b..65aa0e7e 100644--- a/packages/wm/src/common/platform/native_monitor.rs+++ b/packages/wm/src/common/platform/native_monitor.rs@@ -3,7 +3,7 @@ use std::cell::OnceCell;use windows::{core::PCWSTR,Win32::{- Foundation::{BOOL, LPARAM, RECT},+ Foundation::{BOOL, HWND, LPARAM, RECT},Graphics::Gdi::{EnumDisplayDevicesW, EnumDisplayMonitors, GetMonitorInfoW,MonitorFromWindow, DISPLAY_DEVICEW, DISPLAY_DEVICE_ACTIVE, HDC,@@ -18,8 +18,6 @@ use windows::{use crate::common::Rect;-use super::WindowHandle;-pub type MonitorHandle = HMONITOR;#[derive(Clone, Debug)]@@ -202,9 +200,10 @@ extern "system" fn available_monitor_handles_proc(true.into()}-pub fn nearest_monitor(window_handle: WindowHandle) -> NativeMonitor {- let handle =- unsafe { MonitorFromWindow(window_handle, MONITOR_DEFAULTTONEAREST) };+pub fn nearest_monitor(window_handle: isize) -> NativeMonitor {+ let handle = unsafe {+ MonitorFromWindow(HWND(window_handle), MONITOR_DEFAULTTONEAREST)+ };NativeMonitor::new(handle)}diff --git a/packages/wm/src/common/platform/native_window.rs b/packages/wm/src/common/platform/native_window.rsindex e51f9a26..c30806f6 100644--- a/packages/wm/src/common/platform/native_window.rs+++ b/packages/wm/src/common/platform/native_window.rs@@ -43,18 +43,16 @@ use crate::{windows::WindowState,};-pub type WindowHandle = HWND;-#[derive(Clone, Debug)]pub struct NativeWindow {- pub handle: WindowHandle,+ pub handle: isize,title: Arc<RwLock<Option<String>>>,process_name: Arc<RwLock<Option<String>>>,class_name: Arc<RwLock<Option<String>>>,}impl NativeWindow {- pub fn new(handle: WindowHandle) -> Self {+ pub fn new(handle: isize) -> Self {Self {handle,title: Arc::new(RwLock::new(None)),@@ -73,7 +71,8 @@ impl NativeWindow {Some(ref title) => title.clone(),None => {let mut text: [u16; 512] = [0; 512];- let length = unsafe { GetWindowTextW(self.handle, &mut text) };+ let length =+ unsafe { GetWindowTextW(HWND(self.handle), &mut text) };let title = String::from_utf16_lossy(&text[..length as usize]);*self.title.write().unwrap() = Some(title.clone());@@ -92,7 +91,10 @@ impl NativeWindow {None => {let mut process_id = 0u32;unsafe {- GetWindowThreadProcessId(self.handle, Some(&mut process_id));+ GetWindowThreadProcessId(+ HWND(self.handle),+ Some(&mut process_id),+ );}let process_handle = unsafe {@@ -128,7 +130,8 @@ impl NativeWindow {Some(ref class_name) => Ok(class_name.clone()),None => {let mut buffer = [0u16; 256];- let result = unsafe { GetClassNameW(self.handle, &mut buffer) };+ let result =+ unsafe { GetClassNameW(HWND(self.handle), &mut buffer) };if result == 0 {return Err(windows::core::Error::from_win32().into());@@ -144,7 +147,8 @@ impl NativeWindow {/// Whether the window is actually visible.pub fn is_visible(&self) -> bool {- let is_visible = unsafe { IsWindowVisible(self.handle) }.as_bool();+ let is_visible =+ unsafe { IsWindowVisible(HWND(self.handle)) }.as_bool();is_visible && !self.is_cloaked()}@@ -157,7 +161,7 @@ impl NativeWindow {let _ = unsafe {DwmGetWindowAttribute(- self.handle,+ HWND(self.handle),DWMWA_CLOAKED,&mut cloaked as *mut u32 as _,std::mem::size_of::<u32>() as u32,@@ -187,20 +191,22 @@ impl NativeWindow {// ignored. This includes the autocomplete popup in Notepad++ and title// bar menu in Keepass. Although not foolproof, these can typically be// identified by having an owner window and no title bar.- let is_menu_window = unsafe { GetWindow(self.handle, GW_OWNER) }.0- != 0- && !self.has_window_style(WS_CAPTION);+ let is_menu_window =+ unsafe { GetWindow(HWND(self.handle), GW_OWNER) }.0 != 0+ && !self.has_window_style(WS_CAPTION);!is_menu_window}pub fn is_minimized(&self) -> bool {- unsafe { IsIconic(self.handle) }.as_bool()+ unsafe { IsIconic(HWND(self.handle)) }.as_bool()}pub fn is_maximized(&self) -> bool {let mut placement = WINDOWPLACEMENT::default();- let _ = unsafe { GetWindowPlacement(self.handle, &mut placement) };+ let _ =+ unsafe { GetWindowPlacement(HWND(self.handle), &mut placement) };+placement.showCmd == SW_MAXIMIZE.0 as u32}@@ -233,7 +239,7 @@ impl NativeWindow {}// Set as the foreground window.- unsafe { SetForegroundWindow(self.handle) }.ok()?;+ unsafe { SetForegroundWindow(HWND(self.handle)) }.ok()?;Ok(())}@@ -241,7 +247,7 @@ impl NativeWindow {pub fn set_border_color(&self, color_rgba: u32) -> anyhow::Result<()> {unsafe {DwmSetWindowAttribute(- self.handle,+ HWND(self.handle),DWMWA_BORDER_COLOR,&color_rgba as *const _ as *const c_void,std::mem::size_of::<u32>() as u32,@@ -257,7 +263,7 @@ impl NativeWindow {let dwm_res = unsafe {DwmGetWindowAttribute(- self.handle,+ HWND(self.handle),DWMWA_EXTENDED_FRAME_BOUNDS,&mut rect as *mut _ as _,std::mem::size_of::<RECT>() as u32,@@ -283,7 +289,7 @@ impl NativeWindow {fn border_position(&self) -> anyhow::Result<Rect> {let mut rect = RECT::default();- unsafe { GetWindowRect(self.handle, &mut rect as *mut _ as _) }?;+ unsafe { GetWindowRect(HWND(self.handle), &mut rect as *mut _ as _) }?;Ok(Rect::from_ltrb(rect.left,@@ -308,36 +314,39 @@ impl NativeWindow {}fn has_window_style(&self, style: WINDOW_STYLE) -> bool {- unsafe {- let current_style = GetWindowLongPtrW(self.handle, GWL_STYLE);- (current_style & style.0 as isize) != 0- }+ let current_style =+ unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_STYLE) };++ (current_style & style.0 as isize) != 0}fn has_window_style_ex(&self, style: WINDOW_EX_STYLE) -> bool {- unsafe {- let current_style = GetWindowLongPtrW(self.handle, GWL_EXSTYLE);- (current_style & style.0 as isize) != 0- }+ let current_style =+ unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_EXSTYLE) };++ (current_style & style.0 as isize) != 0}pub fn restore(&self) -> anyhow::Result<()> {- unsafe { ShowWindowAsync(self.handle, SW_RESTORE).ok() }?;+ unsafe { ShowWindowAsync(HWND(self.handle), SW_RESTORE).ok() }?;Ok(())}pub fn maximize(&self) -> anyhow::Result<()> {- unsafe { ShowWindowAsync(self.handle, SW_MAXIMIZE).ok() }?;+ unsafe { ShowWindowAsync(HWND(self.handle), SW_MAXIMIZE).ok() }?;Ok(())}pub fn minimize(&self) -> anyhow::Result<()> {- unsafe { ShowWindowAsync(self.handle, SW_MINIMIZE).ok() }?;+ unsafe { ShowWindowAsync(HWND(self.handle), SW_MINIMIZE).ok() }?;Ok(())}pub fn close(&self) -> anyhow::Result<()> {- unsafe { SendNotifyMessageW(self.handle, WM_CLOSE, None, None) }?;+ unsafe {+ SendNotifyMessageW(HWND(self.handle), WM_CLOSE, None, None)+ }?;+Ok(())}@@ -375,7 +384,7 @@ impl NativeWindow {_ => {unsafe {SetWindowPos(- self.handle,+ HWND(self.handle),z_order,rect.x(),rect.y(),@@ -406,8 +415,8 @@ pub fn available_windows() -> anyhow::Result<Vec<NativeWindow>> {.collect()}-pub fn available_window_handles() -> anyhow::Result<Vec<WindowHandle>> {- let mut handles: Vec<WindowHandle> = Vec::new();+pub fn available_window_handles() -> anyhow::Result<Vec<isize>> {+ let mut handles: Vec<isize> = Vec::new();unsafe {EnumWindows(@@ -423,7 +432,7 @@ extern "system" fn available_window_handles_proc(handle: HWND,data: LPARAM,) -> BOOL {- let handles = data.0 as *mut Vec<HWND>;- unsafe { (*handles).push(handle) };+ let handles = data.0 as *mut Vec<isize>;+ unsafe { (*handles).push(handle.0) };true.into()}diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rsindex 07f3713d..84e44558 100644--- a/packages/wm/src/common/platform/platform.rs+++ b/packages/wm/src/common/platform/platform.rs@@ -32,7 +32,7 @@ use crate::user_config::UserConfig;use super::{native_monitor, native_window, EventListener, NativeMonitor,- NativeWindow, SingleInstance, WindowHandle,+ NativeWindow, SingleInstance,};pub type WindowProcedure = WNDPROC;@@ -43,13 +43,13 @@ impl Platform {/// Gets the `NativeWindow` instance of the currently focused window.pub fn foreground_window() -> NativeWindow {let handle = unsafe { GetForegroundWindow() };- NativeWindow::new(handle)+ NativeWindow::new(handle.0)}/// Gets the `NativeWindow` instance of the desktop window.pub fn desktop_window() -> NativeWindow {let handle = unsafe { GetDesktopWindow() };- NativeWindow::new(handle)+ NativeWindow::new(handle.0)}/// Gets a vector of available monitors as `NativeMonitor` instances@@ -120,19 +120,8 @@ impl Platform {pub fn get_root_ancestor(window: &NativeWindow,) -> anyhow::Result<NativeWindow> {- let handle = unsafe { GetAncestor(window.handle, GA_ROOT) };- Ok(NativeWindow::new(handle))- }-- // Gets the parent window of the specified window.- pub fn get_parent(window: &NativeWindow) -> Option<NativeWindow> {- let handle = unsafe { GetParent(window.handle) };- if handle == HWND(0) {- // if a zero pointer is returned, it means the window has no parent.- None- } else {- Some(NativeWindow::new(handle))- }+ let handle = unsafe { GetAncestor(HWND(window.handle), GA_ROOT) };+ Ok(NativeWindow::new(handle.0))}/// Sets the cursor position to the specified coordinates.@@ -162,8 +151,9 @@ impl Platform {x: point.x,y: point.y,};+let handle = unsafe { WindowFromPoint(point) };- Ok(NativeWindow::new(handle))+ Ok(NativeWindow::new(handle.0))}/// Spawns a hidden message window and starts a message loop.@@ -173,7 +163,7 @@ impl Platform {pub unsafe fn create_message_loop(mut abort_rx: oneshot::Receiver<()>,window_procedure: WindowProcedure,- ) -> anyhow::Result<WindowHandle> {+ ) -> anyhow::Result<isize> {let wnd_class = WNDCLASSW {lpszClassName: w!("MessageWindow"),style: CS_HREDRAW | CS_VREDRAW,@@ -221,7 +211,7 @@ impl Platform {}}- Ok(handle)+ Ok(handle.0)}/// Parses a command string into a program name/path and arguments. Thisdiff --git a/packages/wm/src/common/platform/win_event_hook.rs b/packages/wm/src/common/platform/win_event_hook.rsindex bc3b3a01..7157c3fc 100644--- a/packages/wm/src/common/platform/win_event_hook.rs+++ b/packages/wm/src/common/platform/win_event_hook.rs@@ -57,7 +57,7 @@ impl WinEventHook {Ok(window_event_hook)}- fn handle_event(&self, event_type: u32, handle: HWND) {+ fn handle_event(&self, event_type: u32, handle: isize) {let window = NativeWindow::new(handle);let platform_event = match event_type {@@ -176,7 +176,7 @@ extern "system" fn window_event_hook_proc(WINDOW_EVENT_HOOK.with(|hook| {if let Some(hook) = hook.get() {- hook.handle_event(event_type, handle);+ hook.handle_event(event_type, handle.0);}});}diff --git a/packages/wm/src/common/rect.rs b/packages/wm/src/common/rect.rsindex 2a485b79..5e9bd503 100644--- a/packages/wm/src/common/rect.rs+++ b/packages/wm/src/common/rect.rs@@ -1,6 +1,8 @@+use serde::Serialize;+use super::{Direction, RectDelta};-#[derive(Debug, Clone)]+#[derive(Debug, Clone, Serialize)]pub struct Rect {/// X-coordinate of the left edge of the rectangle.pub left: i32,diff --git a/packages/wm/src/common/rect_delta.rs b/packages/wm/src/common/rect_delta.rsindex 3955c780..461f001a 100644--- a/packages/wm/src/common/rect_delta.rs+++ b/packages/wm/src/common/rect_delta.rs@@ -1,11 +1,11 @@use std::str::FromStr;use anyhow::bail;-use serde::{Deserialize, Deserializer};+use serde::{Deserialize, Deserializer, Serialize};use super::LengthValue;-#[derive(Debug, Clone)]+#[derive(Debug, Clone, Serialize)]pub struct RectDelta {/// The delta in x-coordinates on the left of the rectangle.pub left: LengthValue,diff --git a/packages/wm/src/common/tiling_direction.rs b/packages/wm/src/common/tiling_direction.rsindex ced1f546..5e098c7e 100644--- a/packages/wm/src/common/tiling_direction.rs+++ b/packages/wm/src/common/tiling_direction.rs@@ -1,10 +1,12 @@use std::str::FromStr;use anyhow::bail;+use serde::Serialize;use super::Direction;-#[derive(Clone, Debug, PartialEq)]+#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(untagged, rename_all = "snake_case")]pub enum TilingDirection {Vertical,Horizontal,diff --git a/packages/wm/src/common/units.rs b/packages/wm/src/common/units.rsindex 95a608be..5b29061d 100644--- a/packages/wm/src/common/units.rs+++ b/packages/wm/src/common/units.rs@@ -2,15 +2,15 @@ use std::str::FromStr;use anyhow::{bail, Context};use regex::Regex;-use serde::{Deserialize, Deserializer};+use serde::{Deserialize, Deserializer, Serialize};-#[derive(Debug, Clone)]+#[derive(Debug, Clone, Serialize)]pub struct LengthValue {pub amount: f32,pub unit: LengthUnit,}-#[derive(Debug, Clone)]+#[derive(Debug, Clone, Serialize)]pub enum LengthUnit {Pixel,Percentage,diff --git a/packages/wm/src/containers/container.rs b/packages/wm/src/containers/container.rsindex 1dc27fad..e280d279 100644--- a/packages/wm/src/containers/container.rs+++ b/packages/wm/src/containers/container.rs@@ -1,5 +1,6 @@use enum_as_inner::EnumAsInner;use enum_dispatch::enum_dispatch;+use serde::Serialize;use crate::{monitors::Monitor,@@ -10,8 +11,9 @@ use crate::{use super::{traits::CommonGetters, RootContainer, SplitContainer};/// A container of any type.-#[derive(Clone, Debug, EnumAsInner)]+#[derive(Clone, Debug, EnumAsInner, Serialize)]#[enum_dispatch(CommonGetters, PositionGetters)]+#[serde(untagged)]pub enum Container {Root(RootContainer),Monitor(Monitor),@@ -60,8 +62,9 @@ impl Eq for Container {}/// * `CommonGetters`/// * `PositionGetters`/// * `TilingSizeGetters`-#[derive(Clone, Debug, EnumAsInner)]+#[derive(Clone, Debug, EnumAsInner, Serialize)]#[enum_dispatch(CommonGetters, PositionGetters, TilingSizeGetters)]+#[serde(untagged)]pub enum TilingContainer {Split(SplitContainer),TilingWindow(TilingWindow),@@ -91,8 +94,9 @@ impl Eq for TilingContainer {}/// * `CommonGetters`/// * `PositionGetters`/// * `WindowGetters`-#[derive(Clone, Debug, EnumAsInner)]+#[derive(Clone, Debug, EnumAsInner, Serialize)]#[enum_dispatch(CommonGetters, PositionGetters, WindowGetters)]+#[serde(untagged)]pub enum WindowContainer {TilingWindow(TilingWindow),NonTilingWindow(NonTilingWindow),@@ -137,8 +141,9 @@ impl Eq for WindowContainer {}/// * `CommonGetters`/// * `PositionGetters`/// * `TilingDirectionGetters`-#[derive(Clone, Debug, EnumAsInner)]+#[derive(Clone, Debug, EnumAsInner, Serialize)]#[enum_dispatch(CommonGetters, PositionGetters, TilingDirectionGetters)]+#[serde(untagged)]pub enum DirectionContainer {Workspace(Workspace),Split(SplitContainer),@@ -174,3 +179,38 @@ impl PartialEq for DirectionContainer {}impl Eq for DirectionContainer {}++/// Implements the `Debug` trait for a given container struct.+///+/// Expects that the struct has a `to_dto()` method.+#[macro_export]+macro_rules! impl_container_debug {+ ($type:ty) => {+ impl std::fmt::Debug for $type {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ std::fmt::Debug::fmt(+ &self.to_dto().map_err(|_| std::fmt::Error),+ f,+ )+ }+ }+ };+}++/// Implements the `Serialize` trait for a given container struct.+///+/// Expects that the struct has a `to_dto()` method.+#[macro_export]+macro_rules! impl_container_serialize {+ ($type:ty) => {+ impl serde::Serialize for $type {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ let dto = self.to_dto().map_err(serde::ser::Error::custom)?;+ dto.serialize(serializer)+ }+ }+ };+}diff --git a/packages/wm/src/containers/root_container.rs b/packages/wm/src/containers/root_container.rsindex cdaf6e19..a303d26e 100644--- a/packages/wm/src/containers/root_container.rs+++ b/packages/wm/src/containers/root_container.rs@@ -1,14 +1,17 @@use std::{cell::{Ref, RefCell, RefMut},collections::VecDeque,- fmt,rc::Rc,};use anyhow::Context;+use serde::Serialize;use uuid::Uuid;-use crate::{impl_common_getters, monitors::MonitorDto};+use crate::{+ impl_common_getters, impl_container_debug, impl_container_serialize,+ monitors::MonitorDto,+};use super::{traits::{CommonGetters, PositionGetters},@@ -27,6 +30,17 @@ struct RootContainerInner {child_focus_order: VecDeque<Uuid>,}+/// User-friendly representation of a root container.+///+/// Used for IPC and debug logging.+#[derive(Debug, Serialize)]+pub struct RootContainerDto {+ id: Uuid,+ parent: Option<Uuid>,+ children: Vec<MonitorDto>,+ child_focus_order: Vec<Uuid>,+}+impl RootContainer {pub fn new() -> Self {let root = RootContainerInner {@@ -43,10 +57,11 @@ impl RootContainer {let children = self.children().iter()- .map(|c| {- c.as_monitor()+ .map(|child| {+ child+ .as_monitor().context("Root container has an invalid child type.")- .and_then(|c| c.to_dto())+ .and_then(|monitor| monitor.to_dto())}).try_collect()?;@@ -59,6 +74,8 @@ impl RootContainer {}}+impl_container_debug!(RootContainer);+impl_container_serialize!(RootContainer);impl_common_getters!(RootContainer, ContainerType::Root);impl PositionGetters for RootContainer {@@ -78,20 +95,3 @@ impl PositionGetters for RootContainer {Ok(0)}}--impl fmt::Debug for RootContainer {- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {- fmt::Debug::fmt(&self.to_dto().map_err(|_| std::fmt::Error), f)- }-}--/// User-friendly representation of a root container.-///-/// Used for IPC and debug logging.-#[derive(Debug)]-pub struct RootContainerDto {- id: Uuid,- parent: Option<Uuid>,- children: Vec<MonitorDto>,- child_focus_order: Vec<Uuid>,-}diff --git a/packages/wm/src/containers/split_container.rs b/packages/wm/src/containers/split_container.rsindex 8c70845e..374f3db3 100644--- a/packages/wm/src/containers/split_container.rs+++ b/packages/wm/src/containers/split_container.rs@@ -1,17 +1,18 @@use std::{cell::{Ref, RefCell, RefMut},collections::VecDeque,- fmt,rc::Rc,};use anyhow::{bail, Context};+use serde::Serialize;use uuid::Uuid;use crate::{common::{LengthValue, TilingDirection},- impl_common_getters, impl_position_getters_as_resizable,- impl_tiling_direction_getters, impl_tiling_size_getters,+ impl_common_getters, impl_container_debug, impl_container_serialize,+ impl_position_getters_as_resizable, impl_tiling_direction_getters,+ impl_tiling_size_getters,windows::{NonTilingWindowDto, TilingWindowDto},};@@ -37,6 +38,30 @@ struct SplitContainerInner {inner_gap: LengthValue,}+/// User-friendly representation of a split container.+///+/// Used for IPC and debug logging.+#[derive(Debug, Serialize)]+pub struct SplitContainerDto {+ id: Uuid,+ parent: Option<Uuid>,+ children: Vec<SplitContainerChildDto>,+ child_focus_order: Vec<Uuid>,+ tiling_size: f32,+ width: i32,+ height: i32,+ x: i32,+ y: i32,+ tiling_direction: TilingDirection,+}++#[derive(Debug, Serialize)]+pub enum SplitContainerChildDto {+ NonTilingWindow(NonTilingWindowDto),+ TilingWindow(TilingWindowDto),+ Split(SplitContainerDto),+}+impl SplitContainer {pub fn new(tiling_direction: TilingDirection,@@ -92,37 +117,9 @@ impl SplitContainer {}}+impl_container_debug!(SplitContainer);+impl_container_serialize!(SplitContainer);impl_common_getters!(SplitContainer, ContainerType::Split);impl_tiling_size_getters!(SplitContainer);impl_tiling_direction_getters!(SplitContainer);impl_position_getters_as_resizable!(SplitContainer);--impl fmt::Debug for SplitContainer {- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {- fmt::Debug::fmt(&self.to_dto().map_err(|_| std::fmt::Error), f)- }-}--/// User-friendly representation of a split container.-///-/// Used for IPC and debug logging.-#[derive(Debug)]-pub struct SplitContainerDto {- id: Uuid,- parent: Option<Uuid>,- children: Vec<SplitContainerChildDto>,- child_focus_order: Vec<Uuid>,- tiling_size: f32,- width: i32,- height: i32,- x: i32,- y: i32,- tiling_direction: TilingDirection,-}--#[derive(Debug)]-pub enum SplitContainerChildDto {- NonTilingWindow(NonTilingWindowDto),- TilingWindow(TilingWindowDto),- Split(SplitContainerDto),-}diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rsindex ca162835..b23a4850 100644--- a/packages/wm/src/ipc_server.rs+++ b/packages/wm/src/ipc_server.rs@@ -17,6 +17,7 @@ use uuid::Uuid;use crate::{app_command::{AppCommand, InvokeCommand, QueryCommand},+ containers::Container,wm_event::WmEvent,wm_state::WmState,};@@ -24,17 +25,37 @@ use crate::{const DEFAULT_IPC_PORT: u32 = 6123;#[derive(Debug, Serialize)]-struct ServerMessage<T> {- success: bool,- message_type: ServerMessageType,- data: Option<T>,+#[serde(tag = "message_type", rename_all = "snake_case")]+enum ServerMessage {+ ClientResponse(ClientResponseMessage),+ EventSubscription(EventSubscriptionMessage),+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+struct ClientResponseMessage {+ client_message: String,+ data: Option<ClientResponseData>,error: Option<String>,+ success: bool,+}++#[derive(Debug, Serialize)]+#[serde(untagged)]+enum ClientResponseData {+ Windows(Vec<Container>),+ Monitors(Vec<Container>),+ BindingModes(Vec<String>),+ Focused(Option<Container>),}#[derive(Debug, Serialize)]-enum ServerMessageType {- ClientResponse,- EventSubscription,+#[serde(rename_all = "camelCase")]+struct EventSubscriptionMessage {+ data: Option<WmEvent>,+ error: Option<String>,+ subscription_id: String,+ success: bool,}#[derive(Debug)]@@ -151,22 +172,42 @@ impl IpcServer {AppCommand::Start {config_path,verbosity,- } => todo!(),+ } => Err(anyhow::anyhow!("Start command not implemented.")),AppCommand::Query { command } => match command {- QueryCommand::Windows => todo!(),- QueryCommand::Monitors => todo!(),- QueryCommand::BindingMode => todo!(),- QueryCommand::Focused => todo!(),+ QueryCommand::Windows => Ok(ClientResponseData::BindingModes(+ state.binding_modes.clone(),+ )),+ QueryCommand::Monitors => Ok(ClientResponseData::BindingModes(+ state.binding_modes.clone(),+ )),+ QueryCommand::BindingModes => Ok(+ ClientResponseData::BindingModes(state.binding_modes.clone()),+ ),+ QueryCommand::Focused => Ok(ClientResponseData::BindingModes(+ state.binding_modes.clone(),+ )),},AppCommand::Cmd {context_container_id,command,- } => todo!(),+ } => Err(anyhow::anyhow!("Cmd command not implemented.")),+ };++ let error = response.as_ref().err().map(|err| err.to_string());+ let success = response.as_ref().is_ok();++ let response = ClientResponseMessage {+ client_message: "TODO".to_string(),+ data: response.ok(),+ error,+ success,};// Respond to the client with the result of the command.let response_msg = Message::Text(serde_json::to_string(&response)?);response_tx.send(response_msg)?;++ Ok(())}pub async fn process_event(diff --git a/packages/wm/src/monitors/monitor.rs b/packages/wm/src/monitors/monitor.rsindex 1c856d9c..1571a3b9 100644--- a/packages/wm/src/monitors/monitor.rs+++ b/packages/wm/src/monitors/monitor.rs@@ -6,6 +6,7 @@ use std::{};use anyhow::Context;+use serde::Serialize;use uuid::Uuid;use crate::{@@ -15,7 +16,7 @@ use crate::{Container, ContainerType, DirectionContainer, TilingContainer,WindowContainer,},- impl_common_getters,+ impl_common_getters, impl_container_debug, impl_container_serialize,workspaces::{Workspace, WorkspaceDto},};@@ -30,6 +31,22 @@ struct MonitorInner {native: NativeMonitor,}+/// User-friendly representation of a monitor.+///+/// Used for IPC and debug logging.+#[derive(Debug, Serialize)]+pub struct MonitorDto {+ id: Uuid,+ parent: Option<Uuid>,+ children: Vec<WorkspaceDto>,+ child_focus_order: Vec<Uuid>,+ width: i32,+ height: i32,+ x: i32,+ y: i32,+ dpi: f32,+}+impl Monitor {pub fn new(native_monitor: NativeMonitor) -> Self {let monitor = MonitorInner {@@ -102,6 +119,8 @@ impl Monitor {}}+impl_container_debug!(Monitor);+impl_container_serialize!(Monitor);impl_common_getters!(Monitor, ContainerType::Monitor);impl PositionGetters for Monitor {@@ -121,25 +140,3 @@ impl PositionGetters for Monitor {Ok(self.0.borrow().native.working_rect()?.y())}}--impl fmt::Debug for Monitor {- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {- fmt::Debug::fmt(&self.to_dto().map_err(|_| std::fmt::Error), f)- }-}--/// User-friendly representation of a monitor.-///-/// Used for IPC and debug logging.-#[derive(Debug)]-pub struct MonitorDto {- id: Uuid,- parent: Option<Uuid>,- children: Vec<WorkspaceDto>,- child_focus_order: Vec<Uuid>,- width: i32,- height: i32,- x: i32,- y: i32,- dpi: f32,-}diff --git a/packages/wm/src/user_config.rs b/packages/wm/src/user_config.rsindex 4623833d..fe525da9 100644--- a/packages/wm/src/user_config.rs+++ b/packages/wm/src/user_config.rs@@ -1,7 +1,7 @@use std::path::PathBuf;use anyhow::{Context, Result};-use serde::Deserialize;+use serde::{Deserialize, Serialize};use tokio::{fs, sync::mpsc};use crate::{@@ -122,7 +122,7 @@ impl UserConfig {}}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct ParsedConfig {pub binding_modes: Vec<BindingModeConfig>,pub focus_borders: FocusBordersConfig,@@ -134,7 +134,7 @@ pub struct ParsedConfig {pub workspaces: Vec<WorkspaceConfig>,}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct BindingModeConfig {/// Name of the binding mode.pub name: String,@@ -146,7 +146,7 @@ pub struct BindingModeConfig {pub keybindings: Vec<KeybindingConfig>,}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct FocusBordersConfig {/// Border of the focused window.pub active: FocusBorder,@@ -155,7 +155,7 @@ pub struct FocusBordersConfig {pub inactive: FocusBorder,}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct FocusBorder {/// Whether to use a custom border color.pub enabled: bool,@@ -164,7 +164,7 @@ pub struct FocusBorder {pub color: ColorRGBA,}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct GapsConfig {/// Gap between adjacent windows.pub inner_gap: LengthValue,@@ -173,7 +173,7 @@ pub struct GapsConfig {pub outer_gap: RectDelta,}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct GeneralConfig {/// Center the cursor in the middle of a newly focused window.#[serde(default = "default_bool::<false>")]@@ -189,7 +189,7 @@ pub struct GeneralConfig {pub toggle_workspace_on_refocus: bool,}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct KeybindingConfig {/// Keyboard shortcut to trigger the keybinding.pub bindings: Vec<String>,@@ -198,7 +198,7 @@ pub struct KeybindingConfig {pub commands: Vec<InvokeCommand>,}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct WindowRuleConfig {pub match_process_name: Option<String>,pub match_class_name: Option<String>,@@ -206,13 +206,13 @@ pub struct WindowRuleConfig {pub commands: Vec<InvokeCommand>,}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct WindowStateDefaultsConfig {pub floating: FloatingStateConfig,pub fullscreen: FullscreenStateConfig,}-#[derive(Clone, Debug, Deserialize, PartialEq)]+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]pub struct FloatingStateConfig {/// Whether to center new floating windows.#[serde(default = "default_bool::<true>")]@@ -223,7 +223,7 @@ pub struct FloatingStateConfig {pub show_on_top: bool,}-#[derive(Clone, Debug, Deserialize, PartialEq)]+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]pub struct FullscreenStateConfig {/// Whether to prefer fullscreen windows to be maximized.#[serde(default = "default_bool::<true>")]@@ -238,7 +238,7 @@ pub struct FullscreenStateConfig {pub remove_title_bar: bool,}-#[derive(Clone, Debug, Deserialize)]+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct WorkspaceConfig {pub name: String,pub display_name: Option<String>,diff --git a/packages/wm/src/windows/non_tiling_window.rs b/packages/wm/src/windows/non_tiling_window.rsindex 7092514f..20c641e4 100644--- a/packages/wm/src/windows/non_tiling_window.rs+++ b/packages/wm/src/windows/non_tiling_window.rs@@ -1,10 +1,10 @@use std::{cell::{Ref, RefCell, RefMut},collections::VecDeque,- fmt,rc::Rc,};+use serde::Serialize;use uuid::Uuid;use crate::{@@ -16,7 +16,8 @@ use crate::{Container, ContainerType, DirectionContainer, TilingContainer,WindowContainer,},- impl_common_getters, impl_window_getters,+ impl_common_getters, impl_container_debug, impl_container_serialize,+ impl_window_getters,};use super::{traits::WindowGetters, TilingWindow, WindowState};@@ -39,6 +40,25 @@ struct NonTilingWindowInner {floating_placement: Rect,}+/// User-friendly representation of a non-tiling window.+///+/// Used for IPC and debug logging.+#[derive(Debug, Serialize)]+pub struct NonTilingWindowDto {+ id: Uuid,+ parent: Option<Uuid>,+ width: i32,+ height: i32,+ x: i32,+ y: i32,+ 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(id: Option<Uuid>,@@ -104,6 +124,8 @@ impl NonTilingWindow {}}+impl_container_debug!(NonTilingWindow);+impl_container_serialize!(NonTilingWindow);impl_common_getters!(NonTilingWindow, ContainerType::Window);impl_window_getters!(NonTilingWindow);@@ -124,28 +146,3 @@ impl PositionGetters for NonTilingWindow {Ok(self.0.borrow().floating_placement.y())}}--impl fmt::Debug for NonTilingWindow {- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {- fmt::Debug::fmt(&self.to_dto().map_err(|_| std::fmt::Error), f)- }-}--/// User-friendly representation of a non-tiling window.-///-/// Used for IPC and debug logging.-#[derive(Debug)]-pub struct NonTilingWindowDto {- id: Uuid,- parent: Option<Uuid>,- width: i32,- height: i32,- x: i32,- y: i32,- state: WindowState,- prev_state: Option<WindowState>,- display_state: DisplayState,- border_delta: RectDelta,- has_pending_dpi_adjustment: bool,- floating_placement: Rect,-}diff --git a/packages/wm/src/windows/tiling_window.rs b/packages/wm/src/windows/tiling_window.rsindex 2f471a96..6523cc87 100644--- a/packages/wm/src/windows/tiling_window.rs+++ b/packages/wm/src/windows/tiling_window.rs@@ -1,11 +1,11 @@use std::{cell::{Ref, RefCell, RefMut},collections::VecDeque,- fmt,rc::Rc,};use anyhow::Context;+use serde::Serialize;use uuid::Uuid;use crate::{@@ -21,8 +21,9 @@ use crate::{Container, ContainerType, DirectionContainer, TilingContainer,WindowContainer,},- impl_common_getters, impl_position_getters_as_resizable,- impl_tiling_size_getters, impl_window_getters,+ impl_common_getters, impl_container_debug, impl_container_serialize,+ impl_position_getters_as_resizable, impl_tiling_size_getters,+ impl_window_getters,};use super::{traits::WindowGetters, NonTilingWindow, WindowState};@@ -46,6 +47,26 @@ struct TilingWindowInner {inner_gap: LengthValue,}+/// User-friendly representation of a tiling window.+///+/// Used for IPC and debug logging.+#[derive(Debug, Serialize)]+pub struct TilingWindowDto {+ id: Uuid,+ parent: Option<Uuid>,+ tiling_size: f32,+ width: i32,+ height: i32,+ x: i32,+ y: i32,+ state: WindowState,+ prev_state: Option<WindowState>,+ display_state: DisplayState,+ border_delta: RectDelta,+ has_pending_dpi_adjustment: bool,+ floating_placement: Rect,+}+impl TilingWindow {pub fn new(id: Option<Uuid>,@@ -113,33 +134,9 @@ impl TilingWindow {}}+impl_container_debug!(TilingWindow);+impl_container_serialize!(TilingWindow);impl_common_getters!(TilingWindow, ContainerType::Window);impl_tiling_size_getters!(TilingWindow);impl_position_getters_as_resizable!(TilingWindow);impl_window_getters!(TilingWindow);--impl fmt::Debug for TilingWindow {- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {- fmt::Debug::fmt(&self.to_dto().map_err(|_| std::fmt::Error), f)- }-}--/// User-friendly representation of a tiling window.-///-/// Used for IPC and debug logging.-#[derive(Debug)]-pub struct TilingWindowDto {- id: Uuid,- parent: Option<Uuid>,- tiling_size: f32,- width: i32,- height: i32,- x: i32,- y: i32,- state: WindowState,- prev_state: Option<WindowState>,- display_state: DisplayState,- border_delta: RectDelta,- has_pending_dpi_adjustment: bool,- floating_placement: Rect,-}diff --git a/packages/wm/src/windows/window_state.rs b/packages/wm/src/windows/window_state.rsindex 1d641dcf..977764a3 100644--- a/packages/wm/src/windows/window_state.rs+++ b/packages/wm/src/windows/window_state.rs@@ -1,7 +1,9 @@+use serde::Serialize;+use crate::user_config::{FloatingStateConfig, FullscreenStateConfig};/// Represents the various states a window can be in.-#[derive(Clone, Debug, PartialEq)]+#[derive(Clone, Debug, PartialEq, Serialize)]pub enum WindowState {Floating(FloatingStateConfig),Fullscreen(FullscreenStateConfig),diff --git a/packages/wm/src/wm_event.rs b/packages/wm/src/wm_event.rsindex fc7274bc..75000e97 100644--- a/packages/wm/src/wm_event.rs+++ b/packages/wm/src/wm_event.rs@@ -1,14 +1,15 @@+use serde::Serialize;use uuid::Uuid;use crate::{- common::{platform::WindowHandle, TilingDirection},+ common::TilingDirection,containers::{Container, WindowContainer},monitors::Monitor,- user_config::BindingModeConfig,+ user_config::{BindingModeConfig, ParsedConfig},workspaces::Workspace,};-#[derive(Debug)]+#[derive(Debug, Serialize)]pub enum WmEvent {BindingModesChanged {active_binding_modes: Vec<BindingModeConfig>,@@ -33,13 +34,17 @@ pub enum WmEvent {modified_id: Uuid,new_tiling_direction: TilingDirection,},- UserConfigReloaded,+ UserConfigChanged {+ config_path: String,+ config_string: String,+ parsed_config: ParsedConfig,+ },WindowManaged {managed_window: WindowContainer,},WindowUnmanaged {unmanaged_id: Uuid,- unmanaged_handle: WindowHandle,+ unmanaged_handle: isize,},WorkspaceActivated {activated_workspace: Workspace,diff --git a/packages/wm/src/workspaces/workspace.rs b/packages/wm/src/workspaces/workspace.rsindex 86dff2e6..6a84761f 100644--- a/packages/wm/src/workspaces/workspace.rs+++ b/packages/wm/src/workspaces/workspace.rs@@ -5,6 +5,7 @@ use std::{};use anyhow::{bail, Context};+use serde::Serialize;use uuid::Uuid;use crate::{@@ -14,12 +15,13 @@ use crate::{Container, ContainerType, DirectionContainer, SplitContainerDto,TilingContainer, WindowContainer,},- impl_common_getters, impl_tiling_direction_getters,+ impl_common_getters, impl_container_debug, impl_container_serialize,+ impl_tiling_direction_getters,user_config::WorkspaceConfig,windows::{NonTilingWindowDto, TilingWindowDto},};-#[derive(Clone, Debug)]+#[derive(Clone)]pub struct Workspace(Rc<RefCell<WorkspaceInner>>);#[derive(Debug)]@@ -33,6 +35,29 @@ struct WorkspaceInner {outer_gaps: RectDelta,}+/// User-friendly representation of a workspace.+///+/// Used for IPC and debug logging.+#[derive(Debug, Serialize)]+pub struct WorkspaceDto {+ id: Uuid,+ parent: Option<Uuid>,+ children: Vec<WorkspaceChildDto>,+ child_focus_order: Vec<Uuid>,+ width: i32,+ height: i32,+ x: i32,+ y: i32,+ tiling_direction: TilingDirection,+}++#[derive(Debug, Serialize)]+pub enum WorkspaceChildDto {+ NonTilingWindow(NonTilingWindowDto),+ TilingWindow(TilingWindowDto),+ Split(SplitContainerDto),+}+impl Workspace {pub fn new(config: WorkspaceConfig,@@ -100,6 +125,8 @@ impl Workspace {}}+impl_container_debug!(Workspace);+impl_container_serialize!(Workspace);impl_common_getters!(Workspace, ContainerType::Workspace);impl_tiling_direction_getters!(Workspace);@@ -136,26 +163,3 @@ impl PositionGetters for Workspace {Ok(parent.y()? + self.outer_gaps().top.to_pixels(parent.height()?))}}--/// User-friendly representation of a workspace.-///-/// Used for IPC and debug logging.-#[derive(Debug)]-pub struct WorkspaceDto {- id: Uuid,- parent: Option<Uuid>,- children: Vec<WorkspaceChildDto>,- child_focus_order: Vec<Uuid>,- width: i32,- height: i32,- x: i32,- y: i32,- tiling_direction: TilingDirection,-}--#[derive(Debug)]-pub enum WorkspaceChildDto {- NonTilingWindow(NonTilingWindowDto),- TilingWindow(TilingWindowDto),- Split(SplitContainerDto),-}