From c84db9a894cfd6ab8e5299efa142f1404d600ea0 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sun, 21 Sep 2025 21:07:50 -0700 Subject: [PATCH] feat(wm): impl state, global-state and visible-windows This commit implements the State, GlobalState and VisibleWindows SocketMessage variants. These are the first of the SocketMessage variants send by komorebic which receive a reply which is printed out to the console. I think the next thing to do will probably be to get the extended display info so that the MonitorInformation variant can be handled too. --- Cargo.lock | 69 +++++++++++++ justfile | 2 +- komorebi/Cargo.toml | 3 +- komorebi/src/application.rs | 2 +- komorebi/src/container.rs | 19 +++- komorebi/src/core/mod.rs | 3 + komorebi/src/lib.rs | 18 +++- komorebi/src/monitor.rs | 5 +- komorebi/src/process_command.rs | 46 ++++++++- komorebi/src/state.rs | 168 ++++++++++++++++++++++++++++++++ komorebi/src/window.rs | 75 ++++++++++++-- komorebi/src/window_manager.rs | 6 ++ komorebi/src/workspace.rs | 42 +++++++- komorebic/src/main.rs | 23 +++++ 14 files changed, 462 insertions(+), 19 deletions(-) create mode 100644 komorebi/src/state.rs diff --git a/Cargo.lock b/Cargo.lock index 8a867a2c..1beed588 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -599,6 +599,7 @@ dependencies = [ "dirs", "hotwatch", "lazy_static", + "nanoid", "objc2", "objc2-app-kit", "objc2-application-services", @@ -738,6 +739,15 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "nanoid" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8" +dependencies = [ + "rand", +] + [[package]] name = "nix" version = "0.30.1" @@ -1059,6 +1069,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.101" @@ -1077,6 +1096,36 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + [[package]] name = "redox_syscall" version = "0.5.17" @@ -1890,3 +1939,23 @@ name = "windows_x86_64_msvc" version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + +[[package]] +name = "zerocopy" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/justfile b/justfile index 0beb52cf..b75c6688 100644 --- a/justfile +++ b/justfile @@ -3,7 +3,7 @@ export RUST_BACKTRACE := "full" fmt: test -z "$(rg 'eyre!' --type rust)" || (echo "eyre! macro not allowed"; false) test -z "$(rg 'dbg!' --type rust)" || (echo "dbg! macro not allowed"; false) - test -z "$(rg 'println!' --type rust)" || (echo "println! macro not allowed"; false) + test -z "$(rg 'println!' --type rust ./komorebi)" || (echo "println! macro not allowed"; false) cargo +nightly fmt cargo +stable clippy prettier --write README.md diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 324e797f..15552e31 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -26,4 +26,5 @@ serde_with = "3" strum = { version = "0.27", features = ["derive"] } thiserror = { workspace = true } tracing = "0.1" -tracing-subscriber = { version = "0.3", features = ["env-filter"] } \ No newline at end of file +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +nanoid = "0.4" \ No newline at end of file diff --git a/komorebi/src/application.rs b/komorebi/src/application.rs index 38fa4bfc..52db02ec 100644 --- a/komorebi/src/application.rs +++ b/komorebi/src/application.rs @@ -42,7 +42,7 @@ const NOTIFICATIONS: &[&str] = &[ kAXUIElementDestroyedNotification, ]; -#[derive(Debug, Clone)] +#[derive(Debug, Default, Clone, PartialEq)] pub struct Application { element: AccessibilityUiElement, pub process_id: i32, diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs index 07690891..773aa6ae 100644 --- a/komorebi/src/container.rs +++ b/komorebi/src/container.rs @@ -3,13 +3,28 @@ use crate::lockable_sequence::Lockable; use crate::ring::Ring; use crate::window::Window; use color_eyre::eyre; +use nanoid::nanoid; +use serde::Deserialize; +use serde::Serialize; impl_ring_elements!(Container, Window); -#[derive(Debug, Default, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] + pub struct Container { - pub windows: Ring, + pub id: String, pub locked: bool, + pub windows: Ring, +} + +impl Default for Container { + fn default() -> Self { + Self { + id: nanoid!(), + locked: false, + windows: Default::default(), + } + } } impl Lockable for Container { diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 1c81fef0..2db56ab5 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -232,6 +232,9 @@ pub enum SocketMessage { PromoteFocus, PromoteWindow(OperationDirection), ReloadStaticConfiguration(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + State, + GlobalState, + VisibleWindows, } impl SocketMessage { diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index f7893fc9..9e7142a5 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -1,5 +1,6 @@ #![warn(clippy::all)] +use crate::accessibility::AccessibilityApi; use crate::accessibility::error::AccessibilityError; use crate::core::ApplicationIdentifier; use crate::core::config_generation::IdWithIdentifier; @@ -51,6 +52,7 @@ pub mod notification_center_listener; pub mod process_command; pub mod process_event; pub mod reaper; +pub mod state; pub mod static_config; pub mod window; pub mod window_manager; @@ -129,7 +131,7 @@ impl Deref for CoreFoundationRunLoop { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq)] pub struct AccessibilityUiElement(pub CFRetained); unsafe impl Sync for AccessibilityUiElement {} unsafe impl Send for AccessibilityUiElement {} @@ -141,7 +143,13 @@ impl Deref for AccessibilityUiElement { } } -#[derive(Debug, Clone)] +impl Default for AccessibilityUiElement { + fn default() -> Self { + Self(unsafe { AXUIElement::new_system_wide() }) + } +} + +#[derive(Debug, Clone, PartialEq)] pub struct AccessibilityObserver(pub CFRetained); unsafe impl Sync for AccessibilityObserver {} unsafe impl Send for AccessibilityObserver {} @@ -153,6 +161,12 @@ impl Deref for AccessibilityObserver { } } +impl Default for AccessibilityObserver { + fn default() -> Self { + Self(AccessibilityApi::create_observer(1, None).unwrap()) + } +} + pub fn cf_array_as(array: &CFArray) -> impl Iterator> + use<'_, T> { let count = CFArray::count(array); (0..count).flat_map(move |idx| { diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 111c3c53..d90b7df2 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -13,12 +13,14 @@ use crate::workspace::WorkspaceGlobals; use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use serde::Deserialize; +use serde::Serialize; use std::collections::VecDeque; use std::sync::atomic::Ordering; impl_ring_elements!(Monitor, Workspace); -#[derive(Debug)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Monitor { pub id: u32, pub workspaces: Ring, @@ -29,6 +31,7 @@ pub struct Monitor { pub window_based_work_area_offset_limit: isize, pub container_padding: Option, pub workspace_padding: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub last_focused_workspace: Option, pub floating_layer_behaviour: Option, } diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 888fcde0..ff19ca9b 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -6,12 +6,15 @@ use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; use crate::macos_api::MacosApi; use crate::monitor::Monitor; +use crate::state::GlobalState; +use crate::state::State; use crate::window_manager::WindowManager; use crate::workspace::Workspace; use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use color_eyre::eyre::OptionExt; use parking_lot::Mutex; +use std::collections::HashMap; use std::io::BufRead; use std::io::BufReader; use std::num::NonZeroUsize; @@ -62,11 +65,11 @@ pub fn listen_for_commands(wm: Arc>) { } impl WindowManager { - #[tracing::instrument(skip(self, _reply))] + #[tracing::instrument(skip(self, reply))] pub fn process_command( &mut self, message: SocketMessage, - mut _reply: impl std::io::Write, + mut reply: impl std::io::Write, ) -> eyre::Result<()> { tracing::info!("processing command: {message}"); self.handle_unmanaged_window_behaviour()?; @@ -793,6 +796,45 @@ impl WindowManager { SocketMessage::ReloadStaticConfiguration(ref pathbuf) => { self.reload_static_configuration(pathbuf)?; } + SocketMessage::State => { + let state = match serde_json::to_string_pretty(&State::from(&*self)) { + Ok(state) => state, + Err(error) => error.to_string(), + }; + + tracing::info!("replying to state"); + + reply.write_all(state.as_bytes())?; + + tracing::info!("replying to state done"); + } + SocketMessage::GlobalState => { + let state = match serde_json::to_string_pretty(&GlobalState::default()) { + Ok(state) => state, + Err(error) => error.to_string(), + }; + + tracing::info!("replying to global state"); + + reply.write_all(state.as_bytes())?; + + tracing::info!("replying to global state done"); + } + SocketMessage::VisibleWindows => { + let mut monitor_visible_windows = HashMap::new(); + + for monitor in self.monitors() { + if let Some(ws) = monitor.focused_workspace() { + monitor_visible_windows + .insert(monitor.id, ws.visible_window_details().clone()); + } + } + + let visible_windows_state = serde_json::to_string_pretty(&monitor_visible_windows) + .unwrap_or_else(|error| error.to_string()); + + reply.write_all(visible_windows_state.as_bytes())?; + } } Ok(()) diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs new file mode 100644 index 00000000..72e17913 --- /dev/null +++ b/komorebi/src/state.rs @@ -0,0 +1,168 @@ +use crate::DATA_DIR; +use crate::HOME_DIR; +use crate::IGNORE_IDENTIFIERS; +use crate::MANAGE_IDENTIFIERS; +use crate::WORKSPACE_MATCHING_RULES; +use crate::core::MoveBehaviour; +use crate::core::OperationBehaviour; +use crate::core::WindowContainerBehaviour; +use crate::core::config_generation::MatchingRule; +use crate::core::config_generation::WorkspaceMatchingRule; +use crate::core::rect::Rect; +use crate::monitor::Monitor; +use crate::ring::Ring; +use crate::window_manager::WindowManager; +use crate::workspace::Workspace; +use serde::Deserialize; +use serde::Serialize; +use std::collections::VecDeque; +use std::path::PathBuf; + +#[allow(clippy::struct_excessive_bools)] +#[derive(Debug, Serialize, Deserialize)] +pub struct GlobalState { + // pub border_enabled: bool, + // pub border_colours: BorderColours, + // pub border_style: BorderStyle, + // pub border_offset: i32, + // pub border_width: i32, + // pub stackbar_mode: StackbarMode, + // pub stackbar_label: StackbarLabel, + // pub stackbar_focused_text_colour: Colour, + // pub stackbar_unfocused_text_colour: Colour, + // pub stackbar_tab_background_colour: Colour, + // pub stackbar_tab_width: i32, + // pub stackbar_height: i32, + // pub transparency_enabled: bool, + // pub transparency_alpha: u8, + // pub transparency_blacklist: Vec, + // pub remove_titlebars: bool, + // #[serde(alias = "float_identifiers")] + pub ignore_identifiers: Vec, + pub manage_identifiers: Vec, + // pub layered_whitelist: Vec, + // pub tray_and_multi_window_identifiers: Vec, + // pub name_change_on_launch_identifiers: Vec, + // pub monitor_index_preferences: HashMap, + // pub display_index_preferences: HashMap, + // pub ignored_duplicate_monitor_serial_ids: Vec, + pub workspace_rules: Vec, + // pub window_hiding_behaviour: HidingBehaviour, + pub configuration_dir: PathBuf, + pub data_dir: PathBuf, + // pub custom_ffm: bool, +} + +impl Default for GlobalState { + fn default() -> Self { + Self { + ignore_identifiers: IGNORE_IDENTIFIERS.lock().clone(), + manage_identifiers: MANAGE_IDENTIFIERS.lock().clone(), + workspace_rules: WORKSPACE_MATCHING_RULES.lock().clone(), + configuration_dir: HOME_DIR.clone(), + data_dir: DATA_DIR.clone(), + } + } +} + +#[allow(clippy::struct_excessive_bools)] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct State { + pub monitors: Ring, + // pub monitor_usr_idx_map: HashMap, + pub is_paused: bool, + pub resize_delta: i32, + pub new_window_behaviour: WindowContainerBehaviour, + pub float_override: bool, + pub cross_monitor_move_behaviour: MoveBehaviour, + pub unmanaged_window_operation_behaviour: OperationBehaviour, + pub work_area_offset: Option, + // pub focus_follows_mouse: Option, + pub mouse_follows_focus: bool, + // pub has_pending_raise_op: bool, +} + +impl From<&WindowManager> for State { + fn from(wm: &WindowManager) -> Self { + // This is used to remove any information that doesn't need to be passed on to subscribers + // or to be shown with the `komorebic state` command. Currently it is only removing the + // `workspace_config` field from every workspace, but more stripping can be added later if + // needed. + let mut stripped_monitors = Ring::default(); + *stripped_monitors.elements_mut() = wm + .monitors() + .iter() + .map(|monitor| Monitor { + id: monitor.id, + size: monitor.size, + work_area_size: monitor.work_area_size, + work_area_offset: monitor.work_area_offset, + window_based_work_area_offset: monitor.window_based_work_area_offset, + window_based_work_area_offset_limit: monitor.window_based_work_area_offset_limit, + workspaces: { + let mut ws = Ring::default(); + *ws.elements_mut() = monitor + .workspaces() + .iter() + .map(|workspace| Workspace { + name: workspace.name.clone(), + containers: workspace.containers.clone(), + monocle_container: workspace.monocle_container.clone(), + monocle_container_restore_idx: workspace.monocle_container_restore_idx, + maximized_window: workspace.maximized_window.clone(), + maximized_window_restore_idx: workspace.maximized_window_restore_idx, + floating_windows: workspace.floating_windows.clone(), + layout: workspace.layout.clone(), + layout_options: workspace.layout_options, + layout_rules: workspace.layout_rules.clone(), + layout_flip: workspace.layout_flip, + workspace_padding: workspace.workspace_padding, + container_padding: workspace.container_padding, + latest_layout: workspace.latest_layout.clone(), + resize_dimensions: workspace.resize_dimensions.clone(), + tile: workspace.tile, + work_area_offset: workspace.work_area_offset, + apply_window_based_work_area_offset: workspace + .apply_window_based_work_area_offset, + window_container_behaviour: workspace.window_container_behaviour, + window_container_behaviour_rules: workspace + .window_container_behaviour_rules + .clone(), + float_override: workspace.float_override, + layer: workspace.layer, + floating_layer_behaviour: workspace.floating_layer_behaviour, + globals: workspace.globals, + // wallpaper: workspace.wallpaper.clone(), + workspace_config: None, + }) + .collect::>(); + ws.focus(monitor.workspaces.focused_idx()); + ws + }, + last_focused_workspace: monitor.last_focused_workspace, + // workspace_names: monitor.workspace_names.clone(), + container_padding: monitor.container_padding, + workspace_padding: monitor.workspace_padding, + // wallpaper: monitor.wallpaper.clone(), + floating_layer_behaviour: monitor.floating_layer_behaviour, + }) + .collect::>(); + stripped_monitors.focus(wm.monitors.focused_idx()); + + Self { + monitors: stripped_monitors, + // monitor_usr_idx_map: wm.monitor_usr_idx_map.clone(), + is_paused: wm.is_paused, + work_area_offset: wm.work_area_offset, + resize_delta: wm.resize_delta, + new_window_behaviour: wm.window_management_behaviour.current_behaviour, + float_override: wm.window_management_behaviour.float_override, + cross_monitor_move_behaviour: wm.cross_monitor_move_behaviour, + // focus_follows_mouse: wm.focus_follows_mouse, + mouse_follows_focus: wm.mouse_follows_focus, + // has_pending_raise_op: wm.has_pending_raise_op, + unmanaged_window_operation_behaviour: wm.unmanaged_window_operation_behaviour, + // has_pending_raise_op: false, + } + } +} diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index aee7113c..dd1e407e 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -41,6 +41,7 @@ use crate::reaper::ReaperNotification; use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; +use color_eyre::eyre::OptionExt; use objc2::__framework_prelude::Retained; use objc2_app_kit::NSApplicationActivationOptions; use objc2_app_kit::NSRunningApplication; @@ -64,6 +65,8 @@ use objc2_core_graphics::kCGWindowOwnerPID; use regex::Regex; use serde::Deserialize; use serde::Serialize; +use serde::Serializer; +use serde::ser::SerializeStruct; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::ffi::c_void; @@ -172,14 +175,39 @@ impl WindowInfo { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Deserialize, PartialEq)] pub struct Window { pub id: u32, + #[serde(skip_deserializing)] pub element: AccessibilityUiElement, + #[serde(skip_deserializing)] pub application: Application, + #[serde(skip_deserializing)] observer: AccessibilityObserver, } +#[allow(clippy::module_name_repetitions)] +#[derive(Debug, Clone, Serialize)] +pub struct WindowDetails { + pub title: String, + pub exe: String, + pub role: String, + pub subrole: String, +} + +impl TryFrom<&Window> for WindowDetails { + type Error = eyre::ErrReport; + + fn try_from(value: &Window) -> std::result::Result { + Ok(Self { + title: value.title().ok_or_eyre("can't read title")?, + exe: value.exe().ok_or_eyre("can't read exee")?, + role: value.role().ok_or_eyre("can't read role")?, + subrole: value.subrole().ok_or_eyre("can't read subrole")?, + }) + } +} + impl Drop for Window { fn drop(&mut self) { // this gets called when a cloned Window is dropped, so we need to make sure it only @@ -197,12 +225,6 @@ impl Drop for Window { } } -impl PartialEq for Window { - fn eq(&self, other: &Self) -> bool { - self.id == other.id - } -} - impl Display for Window { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut display = format!( @@ -232,6 +254,45 @@ impl Display for Window { } } +impl Serialize for Window { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut state = serializer.serialize_struct("Window", 5)?; + state.serialize_field("window_id", &self.id)?; + state.serialize_field( + "title", + &self + .title() + .unwrap_or_else(|| String::from("could not get window title")), + )?; + state.serialize_field( + "exe", + &self + .exe() + .unwrap_or_else(|| String::from("could not get window exe")), + )?; + state.serialize_field( + "role", + &self + .role() + .unwrap_or_else(|| String::from("could not get window accessibility role")), + )?; + state.serialize_field( + "subrole", + &self + .subrole() + .unwrap_or_else(|| String::from("could not get window accessibility subrole")), + )?; + state.serialize_field( + "rect", + &Rect::from(MacosApi::window_rect(&self.element).unwrap_or_default()), + )?; + state.end() + } +} + impl Window { pub fn new( element: CFRetained, diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index b695d59c..d2f6664a 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -94,6 +94,12 @@ impl EnforceWorkspaceRuleOp { } } +impl AsRef for WindowManager { + fn as_ref(&self) -> &Self { + self + } +} + impl WindowManager { #[allow(clippy::field_reassign_with_default)] pub fn new( diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 027088e7..5964daac 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -13,6 +13,7 @@ use crate::macos_api::MacosApi; use crate::ring::Ring; use crate::static_config::WorkspaceConfig; use crate::window::Window; +use crate::window::WindowDetails; use color_eyre::eyre; use color_eyre::eyre::OptionExt; use serde::Deserialize; @@ -21,13 +22,15 @@ use std::fmt::Display; use std::fmt::Formatter; use std::num::NonZeroUsize; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Workspace { pub name: Option, pub containers: Ring, pub monocle_container: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub monocle_container_restore_idx: Option, pub maximized_window: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub maximized_window_restore_idx: Option, pub floating_windows: Ring, pub layout: Layout, @@ -44,9 +47,11 @@ pub struct Workspace { pub window_container_behaviour: Option, pub window_container_behaviour_rules: Option>, pub float_override: Option, + #[serde(skip)] pub globals: WorkspaceGlobals, pub layer: WorkspaceLayer, pub floating_layer_behaviour: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub workspace_config: Option, } @@ -101,7 +106,7 @@ impl Default for Workspace { } } -#[derive(Debug, Default, Copy, Clone, PartialEq)] +#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq)] /// Settings setup either by the parent monitor or by the `WindowManager` pub struct WorkspaceGlobals { pub container_padding: Option, @@ -819,6 +824,39 @@ impl Workspace { vec } + + pub fn visible_window_details(&self) -> Vec { + let mut vec: Vec = vec![]; + + if let Some(maximized) = &self.maximized_window + && let Ok(details) = (maximized).try_into() + { + vec.push(details); + } + + if let Some(monocle) = &self.monocle_container + && let Some(focused) = monocle.focused_window() + && let Ok(details) = focused.try_into() + { + vec.push(details); + } + + for container in self.containers() { + if let Some(focused) = container.focused_window() + && let Ok(details) = focused.try_into() + { + vec.push(details); + } + } + + for window in self.floating_windows() { + if let Ok(details) = window.try_into() { + vec.push(details); + } + } + + vec + } } impl Workspace { diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 22ea0408..d1a71899 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -10,6 +10,7 @@ use komorebi_client::PathExt; use komorebi_client::Sizing; use komorebi_client::SocketMessage; use komorebi_client::send_message; +use komorebi_client::send_query; use lazy_static::lazy_static; use std::path::PathBuf; use std::sync::atomic::AtomicBool; @@ -176,6 +177,12 @@ struct Opts { #[derive(Parser)] enum SubCommand { + /// Show a JSON representation of the current window manager state + State, + /// Show a JSON representation of the current global state + GlobalState, + /// Show a JSON representation of visible windows + VisibleWindows, /// Change focus to the window in the specified direction #[clap(arg_required_else_help = true)] Focus(Focus), @@ -340,6 +347,13 @@ enum SubCommand { ToggleCrossMonitorMoveBehaviour, } +fn print_query(message: &SocketMessage) { + match send_query(message) { + Ok(response) => println!("{response}"), + Err(error) => panic!("{}", error), + } +} + fn main() -> eyre::Result<()> { let opts: Opts = Opts::parse(); @@ -545,6 +559,15 @@ fn main() -> eyre::Result<()> { SubCommand::SwapWorkspacesWithMonitor(arg) => { send_message(&SocketMessage::SwapWorkspacesToMonitorNumber(arg.target))?; } + SubCommand::State => { + print_query(&SocketMessage::State); + } + SubCommand::GlobalState => { + print_query(&SocketMessage::GlobalState); + } + SubCommand::VisibleWindows => { + print_query(&SocketMessage::VisibleWindows); + } } Ok(())