From 8a17e0ad006ecb7a839392cbe6f333fc0e4341fb Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 24 Sep 2025 16:29:36 -0700 Subject: [PATCH] feat(wm): add socket subscriptions This commit adds in the ability for users to subscribe to notifications via a Unix domain socket. Code was mostly just migrated from komorebi. Tested with "nc -vklU $(komorebic datadir)/test.sock" to create the socket and listen and then "komorebic subscribe-socket test.sock" to subscribe for notifications. --- justfile | 5 +- .../accessibility/notification_constants.rs | 1 + .../src/app_kit_notification_constants.rs | 1 + komorebi/src/container.rs | 2 +- komorebi/src/core/layout.rs | 1 + komorebi/src/core/mod.rs | 13 ++- komorebi/src/lib.rs | 93 +++++++++++++++++++ komorebi/src/main.rs | 12 +++ komorebi/src/monitor.rs | 1 + komorebi/src/monitor_reconciliator.rs | 20 +++- komorebi/src/process_command.rs | 88 +++++++++--------- komorebi/src/process_event.rs | 17 +++- komorebi/src/ring.rs | 1 + komorebi/src/state.rs | 49 ++++++++++ komorebi/src/window.rs | 27 +++++- komorebi/src/window_manager.rs | 39 ++++++++ komorebi/src/window_manager_event.rs | 3 + komorebi/src/workspace.rs | 2 + komorebic/src/main.rs | 37 ++++++-- 19 files changed, 347 insertions(+), 65 deletions(-) diff --git a/justfile b/justfile index 610d38aa..31882336 100644 --- a/justfile +++ b/justfile @@ -15,9 +15,12 @@ fix: clean: cargo clean -install target: +install-with-jsonschema target: cargo +stable install --path {{ target }} --locked --target-dir ~/.cargo/bin +install target: + cargo +stable install --path {{ target }} --locked --target-dir ~/.cargo/bin --no-default-features + build target: cargo +stable build --package {{ target }} --locked --release diff --git a/komorebi/src/accessibility/notification_constants.rs b/komorebi/src/accessibility/notification_constants.rs index 8bd11d37..f0e79b7a 100644 --- a/komorebi/src/accessibility/notification_constants.rs +++ b/komorebi/src/accessibility/notification_constants.rs @@ -48,6 +48,7 @@ pub const kAXAnnouncementKey: &str = "AXAnnouncementKey"; pub const kAXUIElementTitleKey: &str = "AXUIElementTitleKey"; #[derive(Debug, Copy, Clone, PartialEq, Eq, EnumString, Display, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum AccessibilityNotification { AXMainWindowChanged, AXFocusedWindowChanged, diff --git a/komorebi/src/app_kit_notification_constants.rs b/komorebi/src/app_kit_notification_constants.rs index d77c328e..67283bc3 100644 --- a/komorebi/src/app_kit_notification_constants.rs +++ b/komorebi/src/app_kit_notification_constants.rs @@ -10,6 +10,7 @@ use strum::Display; use strum::EnumString; #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, EnumString)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum AppKitWorkspaceNotification { // A notification that the workspace posts when any of the accessibility display options change. NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification, diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs index d25f6696..1bbcf093 100644 --- a/komorebi/src/container.rs +++ b/komorebi/src/container.rs @@ -10,7 +10,7 @@ use serde::Serialize; impl_ring_elements!(Container, Window); #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] - +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Container { pub id: String, pub locked: bool, diff --git a/komorebi/src/core/layout.rs b/komorebi/src/core/layout.rs index dd4131b6..a3ec0713 100644 --- a/komorebi/src/core/layout.rs +++ b/komorebi/src/core/layout.rs @@ -5,6 +5,7 @@ use serde::Deserialize; use serde::Serialize; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum Layout { Default(DefaultLayout), } diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index ef3dc96f..55b170d3 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -202,6 +202,13 @@ pub enum StateQuery { Version, } +#[derive(Default, Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct SubscribeOptions { + /// Only emit notifications when the window manager state has changed + pub filter_state_changes: bool, +} + // serde_as must be before derive #[serde_with::serde_as] #[derive(Clone, Debug, Serialize, Deserialize, Display)] @@ -390,9 +397,9 @@ pub enum SocketMessage { ToggleMouseFollowsFocus, // RemoveTitleBar(ApplicationIdentifier, String), // ToggleTitleBars, - // AddSubscriberSocket(String), - // AddSubscriberSocketWithOptions(String, SubscribeOptions), - // RemoveSubscriberSocket(String), + AddSubscriberSocket(String), + AddSubscriberSocketWithOptions(String, SubscribeOptions), + RemoveSubscriberSocket(String), // AddSubscriberPipe(String), // RemoveSubscriberPipe(String), ApplicationSpecificConfigurationSchema, diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 5fda1262..2269fab3 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -3,13 +3,18 @@ use crate::accessibility::AccessibilityApi; use crate::accessibility::error::AccessibilityError; use crate::core::ApplicationIdentifier; +use crate::core::SocketMessage; +use crate::core::SubscribeOptions; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; use crate::core::config_generation::WorkspaceMatchingRule; use crate::core_graphics::error::CoreGraphicsError; +use crate::monitor_reconciliator::MonitorNotification; +use crate::state::State; use crate::window::AspectRatio; use crate::window::PredefinedAspectRatio; +use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; use core::pathext::PathExt; use lazy_static::lazy_static; @@ -25,8 +30,12 @@ use objc2_core_foundation::CGRect; use objc2_core_foundation::CGSize; use parking_lot::Mutex; use regex::Regex; +use serde::Deserialize; +use serde::Serialize; use std::collections::HashMap; +use std::io::Write; use std::ops::Deref; +use std::os::unix::net::UnixStream; use std::path::PathBuf; use std::ptr::NonNull; use std::sync::Arc; @@ -78,6 +87,10 @@ lazy_static! { pub static ref DATA_DIR: PathBuf = dirs::data_local_dir() .expect("there is no local data directory") .join("komorebi"); + pub static ref SUBSCRIPTION_SOCKETS: Arc>> = + Arc::new(Mutex::new(HashMap::new())); + pub static ref SUBSCRIPTION_SOCKET_OPTIONS: Arc>> = + Arc::new(Mutex::new(HashMap::new())); static ref FLOATING_WINDOW_TOGGLE_ASPECT_RATIO: Arc> = Arc::new(Mutex::new( AspectRatio::Predefined(PredefinedAspectRatio::Widescreen) )); @@ -118,6 +131,86 @@ shadow_rs::shadow!(build); pub static DEFAULT_WORKSPACE_PADDING: AtomicI32 = AtomicI32::new(5); pub static DEFAULT_CONTAINER_PADDING: AtomicI32 = AtomicI32::new(5); +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum NotificationEvent { + WindowManager(WindowManagerEvent), + Socket(SocketMessage), + Monitor(MonitorNotification), + // TODO: See if we want reaper notifications as well + // // TODO: See if we're actually gonna use this + // VirtualDesktop(VirtualDesktopNotification), +} + +// #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq)] +// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +// pub enum VirtualDesktopNotification { +// EnteredAssociatedVirtualDesktop, +// LeftAssociatedVirtualDesktop, +// } + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct Notification { + pub event: NotificationEvent, + pub state: State, +} + +pub fn notify_subscribers( + notification: Notification, + state_has_been_modified: bool, +) -> eyre::Result<()> { + let is_override_event = matches!( + notification.event, + NotificationEvent::Socket(SocketMessage::AddSubscriberSocket(_)) + | NotificationEvent::Socket(SocketMessage::AddSubscriberSocketWithOptions(_, _)) + // | NotificationEvent::Socket(SocketMessage::Theme(_)) + | NotificationEvent::Socket(SocketMessage::ReloadStaticConfiguration(_)) // | NotificationEvent::WindowManager(WindowManagerEvent::TitleUpdate(_, _)) + // | NotificationEvent::WindowManager(WindowManagerEvent::Show(_, _)) + // | NotificationEvent::WindowManager(WindowManagerEvent::Uncloak(_, _)) + ); + + let notification = &serde_json::to_string(¬ification)?; + let mut stale_sockets = vec![]; + let mut sockets = SUBSCRIPTION_SOCKETS.lock(); + let options = SUBSCRIPTION_SOCKET_OPTIONS.lock(); + + for (socket, path) in &mut *sockets { + let apply_state_filter = (*options) + .get(socket) + .copied() + .unwrap_or_default() + .filter_state_changes; + + if !apply_state_filter || state_has_been_modified || is_override_event { + match UnixStream::connect(path) { + Ok(mut stream) => { + tracing::debug!("pushed notification to subscriber: {socket}"); + stream.write_all(notification.as_bytes())?; + } + Err(_) => { + stale_sockets.push(socket.clone()); + } + } + } + } + + for socket in stale_sockets { + tracing::warn!("removing stale subscription: {socket}"); + sockets.remove(&socket); + let socket_path = DATA_DIR.join(socket); + if let Err(error) = std::fs::remove_file(&socket_path) { + tracing::error!( + "could not remove stale subscriber socket file at {}: {error}", + socket_path.display() + ) + } + } + + Ok(()) +} + #[derive(Debug)] pub struct CoreFoundationRunLoop(pub CFRetained); unsafe impl Sync for CoreFoundationRunLoop {} diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index f260cc94..64111ca4 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -29,6 +29,8 @@ use objc2_core_graphics::CGPreflightScreenCaptureAccess; use objc2_core_graphics::CGRequestScreenCaptureAccess; use parking_lot::Mutex; use serde::Deserialize; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -281,5 +283,15 @@ fn main() -> eyre::Result<()> { wm.lock().restore_all_windows(false)?; + let sockets = komorebi::SUBSCRIPTION_SOCKETS.lock(); + for path in (*sockets).values() { + if let Ok(stream) = UnixStream::connect(path) { + stream.shutdown(Shutdown::Both)?; + } + } + + let socket = DATA_DIR.join("komorebi.sock"); + let _ = std::fs::remove_file(socket); + Ok(()) } diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 61265227..bd632388 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -52,6 +52,7 @@ impl From<&Monitor> for MonitorInformation { impl_ring_elements!(Monitor, Workspace); #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Monitor { pub id: u32, pub device: String, diff --git a/komorebi/src/monitor_reconciliator.rs b/komorebi/src/monitor_reconciliator.rs index d88b8114..dc7ce7d8 100644 --- a/komorebi/src/monitor_reconciliator.rs +++ b/komorebi/src/monitor_reconciliator.rs @@ -1,4 +1,8 @@ +use crate::Notification; +use crate::NotificationEvent; use crate::UPDATE_MONITOR_WORK_AREAS; +use crate::notify_subscribers; +use crate::state::State; use crate::window_manager::WindowManager; use crossbeam_channel::Receiver; use crossbeam_channel::Sender; @@ -12,7 +16,7 @@ use std::sync::atomic::Ordering; use strum::Display; #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] - +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum MonitorNotification { Resize(CGDirectDisplayID), } @@ -58,18 +62,30 @@ pub fn listen_for_notifications(wm: Arc>) -> color_eyre::Re Ok(()) } -pub fn handle_notifications(_wm: Arc>) -> color_eyre::Result<()> { +pub fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> { tracing::info!("listening"); let receiver = event_rx(); for notification in receiver { + let wm = wm.lock(); + + let initial_state = State::from(wm.as_ref()); + match notification { MonitorNotification::Resize(_display_id) => { tracing::debug!("handling resize notification"); UPDATE_MONITOR_WORK_AREAS.store(true, Ordering::Relaxed); } } + + notify_subscribers( + Notification { + event: NotificationEvent::Monitor(notification), + state: wm.as_ref().into(), + }, + initial_state.has_been_modified(&wm), + )?; } Ok(()) diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 643ffd5b..af17531b 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -1,7 +1,12 @@ +use crate::DATA_DIR; use crate::FLOATING_APPLICATIONS; use crate::IGNORE_IDENTIFIERS; use crate::MANAGE_IDENTIFIERS; +use crate::Notification; +use crate::NotificationEvent; use crate::SESSION_FLOATING_APPLICATIONS; +use crate::SUBSCRIPTION_SOCKET_OPTIONS; +use crate::SUBSCRIPTION_SOCKETS; use crate::WORKSPACE_MATCHING_RULES; use crate::build; use crate::core::ApplicationIdentifier; @@ -10,7 +15,6 @@ use crate::core::SocketMessage; use crate::core::StateQuery; use crate::core::WindowContainerBehaviour; use crate::core::arrangement::Axis; -use crate::core::asc::ApplicationSpecificConfiguration; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; @@ -21,14 +25,12 @@ use crate::core::layout::Layout; use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; use crate::macos_api::MacosApi; -use crate::monitor::Monitor; use crate::monitor::MonitorInformation; +use crate::notify_subscribers; use crate::state::GlobalState; use crate::state::State; -use crate::static_config::StaticConfig; use crate::window::AdhocWindow; use crate::window_manager::WindowManager; -use crate::workspace::Workspace; use crate::workspace::WorkspaceLayer; use crate::workspace::WorkspaceWindowLocation; use color_eyre::eyre; @@ -92,6 +94,11 @@ impl WindowManager { mut reply: impl std::io::Write, ) -> eyre::Result<()> { tracing::info!("processing command: {message}"); + + #[allow(clippy::useless_asref)] + // We don't have From implemented for &mut WindowManager + let initial_state = State::from(self.as_ref()); + self.handle_unmanaged_window_behaviour()?; match message { @@ -1407,7 +1414,9 @@ impl WindowManager { SocketMessage::ApplicationSpecificConfigurationSchema => { #[cfg(feature = "schemars")] { - let asc = schemars::schema_for!(Vec); + let asc = schemars::schema_for!( + Vec + ); let schema = serde_json::to_string_pretty(&asc)?; reply.write_all(schema.as_bytes())?; @@ -1432,57 +1441,46 @@ impl WindowManager { }); let generator = settings.into_generator(); - let socket_message = generator.into_root_schema_for::(); + let socket_message = + generator.into_root_schema_for::(); let schema = serde_json::to_string_pretty(&socket_message)?; reply.write_all(schema.as_bytes())?; } } + SocketMessage::AddSubscriberSocket(ref socket) => { + let mut sockets = SUBSCRIPTION_SOCKETS.lock(); + let socket_path = DATA_DIR.join(socket); + sockets.insert(socket.clone(), socket_path); + } + SocketMessage::AddSubscriberSocketWithOptions(ref socket, options) => { + let mut sockets = SUBSCRIPTION_SOCKETS.lock(); + let socket_path = DATA_DIR.join(socket); + sockets.insert(socket.clone(), socket_path); + + let mut socket_options = SUBSCRIPTION_SOCKET_OPTIONS.lock(); + socket_options.insert(socket.clone(), options); + } + SocketMessage::RemoveSubscriberSocket(ref socket) => { + let mut sockets = SUBSCRIPTION_SOCKETS.lock(); + sockets.remove(socket); + } } + notify_subscribers( + Notification { + event: NotificationEvent::Socket(message.clone()), + state: self.as_ref().into(), + }, + initial_state.has_been_modified(self.as_ref()), + )?; + self.update_known_window_ids(); + tracing::info!("processed"); + Ok(()) } - - #[tracing::instrument(skip(self))] - pub fn move_workspace_to_monitor(&mut self, idx: usize) -> eyre::Result<()> { - tracing::info!("moving workspace"); - let mouse_follows_focus = self.mouse_follows_focus; - let offset = self.work_area_offset; - let workspace = self - .remove_focused_workspace() - .ok_or_eyre("there is no workspace")?; - - { - let target_monitor: &mut Monitor = self - .monitors_mut() - .get_mut(idx) - .ok_or_eyre("there is no monitor")?; - - target_monitor.workspaces_mut().push_back(workspace); - target_monitor.update_workspaces_globals(offset); - target_monitor.focus_workspace(target_monitor.workspaces().len().saturating_sub(1))?; - target_monitor.load_focused_workspace(mouse_follows_focus)?; - } - - self.focus_monitor(idx)?; - self.update_focused_workspace(mouse_follows_focus, true) - } - - pub fn remove_focused_workspace(&mut self) -> Option { - let focused_monitor: &mut Monitor = self.focused_monitor_mut()?; - let focused_workspace_idx = focused_monitor.focused_workspace_idx(); - let workspace = focused_monitor.remove_workspace_by_idx(focused_workspace_idx); - if let Err(error) = focused_monitor.focus_workspace(focused_workspace_idx.saturating_sub(1)) - { - tracing::error!( - "Error focusing previous workspace while removing the focused workspace: {}", - error - ); - } - workspace - } } pub fn read_commands_uds( diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 217470d7..3620055d 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -1,4 +1,6 @@ use crate::FLOATING_APPLICATIONS; +use crate::Notification; +use crate::NotificationEvent; use crate::REGEX_IDENTIFIERS; use crate::TABBED_APPLICATIONS; use crate::WORKSPACE_MATCHING_RULES; @@ -11,6 +13,8 @@ use crate::core::config_generation::MatchingRule; use crate::core::default_layout::DefaultLayout; use crate::core::layout::Layout; use crate::macos_api::MacosApi; +use crate::notify_subscribers; +use crate::state::State; use crate::window::AdhocWindow; use crate::window::Window; use crate::window::should_act; @@ -92,6 +96,10 @@ impl WindowManager { ); } + #[allow(clippy::useless_asref)] + // We don't have From implemented for &mut WindowManager + let initial_state = State::from(self.as_ref()); + self.enforce_workspace_rules()?; match event { @@ -518,9 +526,16 @@ impl WindowManager { } } - self.enforce_workspace_rules()?; self.update_known_window_ids(); + notify_subscribers( + Notification { + event: NotificationEvent::WindowManager(event), + state: self.as_ref().into(), + }, + initial_state.has_been_modified(self.as_ref()), + )?; + Ok(()) } } diff --git a/komorebi/src/ring.rs b/komorebi/src/ring.rs index a473209c..147f8da7 100644 --- a/komorebi/src/ring.rs +++ b/komorebi/src/ring.rs @@ -4,6 +4,7 @@ use serde::Deserialize; use serde::Serialize; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Ring { elements: VecDeque, focused: usize, diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 856897ff..9aa3f083 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -66,6 +66,7 @@ impl Default for GlobalState { } #[allow(clippy::struct_excessive_bools)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct State { pub monitors: Ring, @@ -168,3 +169,51 @@ impl From<&WindowManager> for State { } } } + +impl State { + pub fn has_been_modified(&self, wm: &WindowManager) -> bool { + let new = Self::from(wm); + + if self.monitors != new.monitors { + return true; + } + + if self.is_paused != new.is_paused { + return true; + } + + if self.new_window_behaviour != new.new_window_behaviour { + return true; + } + + if self.float_override != new.float_override { + return true; + } + + if self.cross_monitor_move_behaviour != new.cross_monitor_move_behaviour { + return true; + } + + if self.unmanaged_window_operation_behaviour != new.unmanaged_window_operation_behaviour { + return true; + } + + if self.work_area_offset != new.work_area_offset { + return true; + } + + // if self.focus_follows_mouse != new.focus_follows_mouse { + // return true; + // } + + if self.mouse_follows_focus != new.mouse_follows_focus { + return true; + } + + // if self.has_pending_raise_op != new.has_pending_raise_op { + // return true; + // } + + false + } +} diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 260c6b98..28bc8e40 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -257,8 +257,8 @@ impl Serialize for Window { where S: Serializer, { - let mut state = serializer.serialize_struct("Window", 5)?; - state.serialize_field("window_id", &self.id)?; + let mut state = serializer.serialize_struct("Window", 6)?; + state.serialize_field("id", &self.id)?; state.serialize_field( "title", &self @@ -291,6 +291,29 @@ impl Serialize for Window { } } +#[cfg(feature = "schemars")] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +struct SerializedWindow { + id: u32, + title: String, + exe: String, + role: String, + subrole: String, + rect: Rect, +} + +#[cfg(feature = "schemars")] +impl schemars::JsonSchema for Window { + fn schema_name() -> String { + "Window".to_string() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::schema::Schema { + ::json_schema(generator) + } +} + impl Window { pub fn new( element: CFRetained, diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 8634d91e..d22e7455 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -2564,4 +2564,43 @@ impl WindowManager { Ok(()) } + + #[tracing::instrument(skip(self))] + pub fn move_workspace_to_monitor(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("moving workspace"); + let mouse_follows_focus = self.mouse_follows_focus; + let offset = self.work_area_offset; + let workspace = self + .remove_focused_workspace() + .ok_or_eyre("there is no workspace")?; + + { + let target_monitor: &mut Monitor = self + .monitors_mut() + .get_mut(idx) + .ok_or_eyre("there is no monitor")?; + + target_monitor.workspaces_mut().push_back(workspace); + target_monitor.update_workspaces_globals(offset); + target_monitor.focus_workspace(target_monitor.workspaces().len().saturating_sub(1))?; + target_monitor.load_focused_workspace(mouse_follows_focus)?; + } + + self.focus_monitor(idx)?; + self.update_focused_workspace(mouse_follows_focus, true) + } + + pub fn remove_focused_workspace(&mut self) -> Option { + let focused_monitor: &mut Monitor = self.focused_monitor_mut()?; + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspace = focused_monitor.remove_workspace_by_idx(focused_workspace_idx); + if let Err(error) = focused_monitor.focus_workspace(focused_workspace_idx.saturating_sub(1)) + { + tracing::error!( + "Error focusing previous workspace while removing the focused workspace: {}", + error + ); + } + workspace + } } diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index 386a8af3..0e018465 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -7,6 +7,7 @@ use serde::Serialize; use strum::Display; #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(tag = "type", content = "content")] pub enum SystemNotification { Accessibility(AccessibilityNotification), @@ -15,6 +16,7 @@ pub enum SystemNotification { } #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum ManualNotification { ShowOnInputEvent, ShowOnFocusChangeFirstTabDestroyed, @@ -22,6 +24,7 @@ pub enum ManualNotification { } #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(tag = "type", content = "content")] pub enum WindowManagerEvent { FocusChange(SystemNotification, i32, Option), diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 898bb430..c3401f10 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -24,6 +24,7 @@ use std::fmt::Formatter; use std::num::NonZeroUsize; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Workspace { pub name: Option, pub containers: Ring, @@ -57,6 +58,7 @@ pub struct Workspace { } #[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum WorkspaceLayer { #[default] Tiling, diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 143b6031..e8f09229 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -6,7 +6,6 @@ use clap::ValueEnum; use color_eyre::eyre; use fs_tail::TailedFile; use komorebi_client::ApplicationIdentifier; -use komorebi_client::ApplicationSpecificConfiguration; use komorebi_client::Axis; use komorebi_client::CycleDirection; use komorebi_client::DefaultLayout; @@ -18,7 +17,6 @@ use komorebi_client::Rect; use komorebi_client::Sizing; use komorebi_client::SocketMessage; use komorebi_client::StateQuery; -use komorebi_client::StaticConfig; use komorebi_client::replace_env_in_path; use komorebi_client::send_message; use komorebi_client::send_query; @@ -423,6 +421,18 @@ struct ResizeDelta { pixels: i32, } +#[derive(Parser)] +struct SubscribeSocket { + /// Name of the socket to send event notifications to + socket: String, +} + +#[derive(Parser)] +struct UnsubscribeSocket { + /// Name of the socket to stop sending event notifications to + socket: String, +} + #[derive(Parser)] struct GlobalWorkAreaOffset { /// Size of the left work area offset (set right to left * 2 to maintain right padding) @@ -608,12 +618,12 @@ enum SubCommand { /// Query the current window manager state #[clap(arg_required_else_help = true)] Query(Query), - // /// Subscribe to komorebi events using a Unix Domain Socket - // #[clap(arg_required_else_help = true)] - // SubscribeSocket(SubscribeSocket), - // /// Unsubscribe from komorebi events - // #[clap(arg_required_else_help = true)] - // UnsubscribeSocket(UnsubscribeSocket), + /// Subscribe to komorebi events using a Unix Domain Socket + #[clap(arg_required_else_help = true)] + SubscribeSocket(SubscribeSocket), + /// Unsubscribe from komorebi events + #[clap(arg_required_else_help = true)] + UnsubscribeSocket(UnsubscribeSocket), // /// Subscribe to komorebi events using a Named Pipe // #[clap(arg_required_else_help = true)] // #[clap(alias = "subscribe")] @@ -1695,7 +1705,7 @@ fn main() -> eyre::Result<()> { SubCommand::ApplicationSpecificConfigurationSchema => { #[cfg(feature = "schemars")] { - let asc = schemars::schema_for!(ApplicationSpecificConfiguration); + let asc = schemars::schema_for!(komorebi_client::ApplicationSpecificConfiguration); let schema = serde_json::to_string_pretty(&asc)?; println!("{schema}"); } @@ -1718,11 +1728,18 @@ fn main() -> eyre::Result<()> { }); let generator = settings.into_generator(); - let socket_message = generator.into_root_schema_for::(); + let socket_message = + generator.into_root_schema_for::(); let schema = serde_json::to_string_pretty(&socket_message)?; println!("{schema}"); } } + SubCommand::SubscribeSocket(arg) => { + send_message(&SocketMessage::AddSubscriberSocket(arg.socket))?; + } + SubCommand::UnsubscribeSocket(arg) => { + send_message(&SocketMessage::RemoveSubscriberSocket(arg.socket))?; + } } Ok(())